-
Notifications
You must be signed in to change notification settings - Fork 15
/
goodel.gs
365 lines (271 loc) · 9.61 KB
/
goodel.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
function Goodel (sheetName) {
return Goodel.Modeler(sheetName);
}
/*
* Modeler takes the name of the sheet where the table is kept.
* It expects the first row to be a header with column names
* Ie. it won't search that row.
*/
Goodel.Modeler = function (sheetName) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(),
sheet = spreadsheet.getSheetByName(sheetName),
table = new Goodel.Table(sheet),
columns = table.getRow(1).getValues()[0];
if (sheet == null) {
var missingSheetMsg = 'Could not find sheet "<sheetName>" in active spreadsheet.'
.replace("<sheetName>", sheetName);
throw new Error (missingSheetMsg);
}
function Model (instanceAttrHash) {
this.model = Model;
for (var attr in instanceAttrHash) {
this[attr] = instanceAttrHash[attr];
}
}
Model.sheet = sheet;
Model.name = sheet.getName();
Model.table = table;
Model.columns = columns;
for (var classMethod in Goodel._modelClassMethods) {
Model[classMethod] = Goodel._modelClassMethods[classMethod];
}
Model.prototype = Object.create(Goodel._ModelInstance.prototype);
return Model;
}
Goodel._modelClassMethods = function () {}
Goodel._modelClassMethods.findWhere = function (searchHash) {
return this.table.findWhere(searchHash);
}
Goodel._modelClassMethods.findBy = function (searchHash) {
var attrs = this.table.findBy(searchHash);
return new this(attrs);
}
Goodel._modelClassMethods.create = function (recordHash) {
var newRecord = [], len = this.columns.length, i;
for (i = 0; i < len; i++) {
var column = this.columns[i],
attribute = recordHash[column] || "";
newRecord.push(attribute);
}
var emptyRowIdx = this.table.getEmptyRowIdx(),
row = this.table.getRow(emptyRowIdx);
row.setValues([newRecord]);
this.table.numRows++;
return newRecord;
}
Goodel._modelClassMethods.toString = function () {
return "{ sheet: <sheet>, columns: <columns> }"
.replace("<sheet>", this.sheet.getName())
.replace("<columns>", this.columns);
}
Goodel._ModelInstance = function () {}
Goodel._ModelInstance.prototype.save = function () {
this.model.create(this);
}
Goodel._ModelInstance.prototype.toString = function () {
var stringifiedObj = [];
for (var key in this) {
if (this.hasOwnProperty(key)) {
var kvPair = "<key> = <value>"
.replace("<key>", key)
.replace("<value>", this[key]);
stringifiedObj.push(kvPair);
}
}
stringifiedObj = "{ " + stringifiedObj.join(", ") + " }";
return stringifiedObj;
}
var ALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
Goodel.Table = function (sheet) {
this.sheet = sheet;
this.numColumns = this.getEmptyColumnIdx() - 1;
this.numRows = this.getEmptyRowIdx() - 1;
this.columns = this.getRow(1).getValues()[0];
this.columnMap = null;
this._buildColumnMap();
}
Goodel.Table.prototype.findBy = function (searchHash) {
/* If there are more than 50 cells to check,
* use native search with single query.
* Otherwise, make one query per row.
*/
if (this.numRows * this.numColumns > 50 ) {
return this.natFindBy(searchHash);
} else {
return this.manFindBy(searchHash);
}
}
Goodel.Table.prototype.findWhere = function (searchHash) {
// Same as above
if (this.numRows * this.numColumns > 50) {
return this.natFindWhere(searchHash);
} else {
return this.manFindWhere(searchHash);
}
}
Goodel.Table.prototype.manFindBy = function (searchHash) {
// Loop through rows
for (var rowIdx = 1; rowIdx <= this.numRows; rowIdx++) {
// Check match for every search key
var isAMatch = true;
for (var searchKey in searchHash) {
var columnIdx = this.columnMap[searchKey];
if (columnIdx == undefined) this._throwBadAttrMsg(searchKey);
var attribute = this.getCell(rowIdx, columnIdx).getValue();
if (searchHash[searchKey] != attribute) isAMatch = false;
}
// Return record when first match is found
if (isAMatch) {
var row = this.getRow(rowIdx).getValues()[0],
record = this._hashifyRow(row);
return record;
}
}
// Return null if no matches are found
return null
}
Goodel.Table.prototype.manFindWhere = function (searchHash) {
var searchResults = [];
// Loop through rows
for (var rowIdx = 1; rowIdx <= this.numRows; rowIdx++) {
var isAMatch = true;
// Check match for every search key
for (var searchKey in searchHash) {
var columnIdx = this.columnMap[searchKey];
if (columnIdx == undefined) this._throwBadAttrMsg(searchKey);
var attribute = this.getCell(rowIdx, columnIdx).getValue();
if (searchHash[searchKey] != attribute) isAMatch = false;
}
// Add record to results array if it's a match
if (isAMatch) {
var row = this.getRow(rowIdx).getValues()[0],
record = this._hashifyRow(row);
searchResults.push(record);
}
}
return searchResults;
}
Goodel.Table.prototype.natFindBy = function (searchHash) {
/*
* Create a temporary sheet with a random name
* where the search formula is inserted.
* Then retrieves the search results and delete the sheet.
*/
// Same as above
var tempSheetName = Math.random().toString(36),
spreadsheet = this.sheet.getParent(),
tempSheet = spreadsheet.insertSheet(tempSheetName),
firstCell = tempSheet.getRange(1,1);
var searchFormula = this._getSearchRange(),
searchConditions = this._buildSearchConditions(searchHash)
searchFormula += searchConditions + ')';
firstCell.setFormula(searchFormula);
var firstCellValue = firstCell.getValue();
if (firstCellValue == "#N/A") return null;
if (firstCellValue == "#ERROR!") throw new Error("Query error");
var matchingRow = tempSheet.getRange(1, 1, 1, this.numColumns).getValues()[0];
var matchingRecord = this._hashifyRow(matchingRow);
spreadsheet.deleteSheet(tempSheet);
return matchingRecord;
}
Goodel.Table.prototype.natFindWhere = function (searchHash) {
// Same as above
var tempSheetName = Math.random().toString(36),
spreadsheet = this.sheet.getParent();
var tempSheet = spreadsheet.insertSheet(tempSheetName),
firstCell = tempSheet.getRange(1,1),
searchResults = [];
var searchFormula = this._getSearchRange(),
searchConditions = this._buildSearchConditions(searchHash)
searchFormula += searchConditions + ')';
firstCell.setFormula(searchFormula);
var firstCellValue = firstCell.getValue();
if (firstCellValue == "#N/A") return null;
if (firstCellValue == "#ERROR!") throw new Error("Query error");
// If one or more records were found,
// loop through them and add them to the results array
var i = 1;
var thisRow = tempSheet.getRange(i, 1, 1, this.numColumns).getValues()[0];
while (thisRow[0] != "") {
var foundRecord = this._hashifyRow(thisRow);
searchResults.push(foundRecord);
thisRow = tempSheet.getRange(++i, 1, 1, this.numColumns).getValues()[0];
}
spreadsheet.deleteSheet(tempSheet);
return searchResults;
}
Goodel.Table.prototype._buildSearchConditions = function (searchHash) {
var searchConditions = "";
for (var key in searchHash) {
var searchColumn = ALPHABET[this.columnMap[key] - 1];
if (searchColumn === undefined) this._throwBadAttrMsg(key);
var condition = '<table>!<searchCol>2:<searchCol><lastRow> = "<searchVal>"'
.replace("<table>", this.sheet.getName())
.replace(/<searchCol>/g, searchColumn)
.replace("<lastRow>", this.getEmptyRowIdx() - 1)
.replace("<searchVal>", searchHash[key]);
searchConditions += condition + ',';
}
// Remove trailing ', '
searchConditions = searchConditions.slice(0, searchConditions.length - 1);
return searchConditions;
}
Goodel.Table.prototype._throwBadAttrMsg = function (key) {
var badAttributeMsg = '<sheetName> table does not have a "<key>" column.'
.replace("<sheetName>", this.sheet.getName())
.replace("<key>", key);
throw new Error(badAttributeMsg);
}
Goodel.Table.prototype._getSearchRange = function () {
return "=FILTER(<table>!A2:<lastRow>, "
.replace("<table>", this.sheet.getName())
.replace("<lastRow>", this.getEmptyRowIdx() - 1);
}
Goodel.Table.prototype._hashifyRow = function (row) {
var record = {}, len = this.numColumns, i;
for (i = 0; i < len; i++) {
var attr = this.columns[i];
if (row[i] == "") {
record[attr] = null;
} else {
record[attr] = row[i];
}
}
return record;
}
Goodel.Table.prototype.getRow = function (row) {
return this.sheet.getRange(row, 1, 1, this.numColumns);
}
Goodel.Table.prototype.getCell = function (row, col) {
return this.sheet.getRange(row, col);
}
Goodel.Table.prototype.getRange = function (row, col, nRows, nCols) {
return this.sheet.getRange(row, col, nRows, nCols);
}
Goodel.Table.prototype.getEmptyRowIdx = function () {
var rowIdx = 1;
while (this.getCell(rowIdx, 1).getValue() != "") {
rowIdx += 1;
}
return rowIdx;
}
Goodel.Table.prototype.getEmptyColumnIdx = function () {
var columnIdx = 1;
while (this.getCell(1, columnIdx).getValue() != "") {
columnIdx += 1;
}
return columnIdx;
}
Goodel.Table.prototype._buildColumnMap = function () {
var columnMap = {},
len = this.numColumns,
columns = this.getRow(1).getValues()[0],
i;
for (i = 0; i < len; i++) {
var column = columns[i];
columnMap[column] = i + 1;
}
this.columnMap = columnMap;
}