Repository navigation
Expand file tree
/
Copy pathModel.js
More file actions
507 lines (454 loc) · 15.8 KB
/
Copy pathModel.js
File metadata and controls
507 lines (454 loc) · 15.8 KB
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
function Model(parent) {
this.parent = parent;
this.tables = [];
this.relationships = [];
this.bufferTables = [];
let performanceTimer = 0;
this.addTable = function (tableID, tableInstance) {
this.tables.push({ tableID: tableID, object: tableInstance });
return this.tables[this.tables.length - 1];
};
this.getTable = function (tableID) {
let foundTable = this.tables.filter((x) => x.tableID == tableID);
return foundTable.length ? foundTable[0] : null;
};
this.getBufferTable = function (tableID) {
let foundTable = this.bufferTables.filter((x) => x.tableID == tableID)[0];
return foundTable || null;
};
this.addRelationship = function (from, primarykey, to, foreignkey) {
this.relationships.push({ from, primarykey, to, foreignkey });
};
this.loadBuffer = function () {
this.bufferTables = this.tables.map((x) => {
return { tableID: x.tableID, object: x.object.copy() };
});
};
this.applyFilters = function (tableID, valueArr, field) {
//Return if there is no table in the buffer
if (!this.bufferTables.length) return;
//Apply the filter to the target table
this.bufferTables = this.bufferTables.map((x) =>
x.tableID == tableID
? { tableID: x.tableID, object: x.object.filterTable(valueArr, field) }
: x
);
//Propogate with depth first search algorithm
let visited = [];
let stack = [];
visited.push(tableID);
stack.push(tableID);
while (stack.length > 0) {
let lastTableInStack = stack[stack.length - 1];
let availableRelations = this.relationships.filter(
(rel) => rel.from == lastTableInStack && !visited.includes(rel.to)
);
if (availableRelations.length) {
let source = lastTableInStack;
let target = availableRelations[0].to;
let primaryKey = availableRelations[0].primarykey;
let foreignKey = availableRelations[0].foreignkey;
//Retrieve primary key values, these will match with the foreignKey values in target table
let primaryKeyValues = [
...new Set(
this.getBufferTable(source)
.object.selectColumn(primaryKey)
.data[0].slice(1)
),
];
//Apply filter by array to target table
this.bufferTables = this.bufferTables.map((x) =>
x.tableID == target
? {
tableID: x.tableID,
object: x.object.filterTable(primaryKeyValues, foreignKey),
}
: x
);
//We are done
visited.push(target);
stack.push(target);
} else {
//No more relationships available, propagation step ended
stack.pop();
}
}
};
this.aggregate = function (desiredColumn, aggrMethod) {
let result = 0;
let columnData = desiredColumn.filter((x) => x != ""); //Eliminate blanks by default
if (aggrMethod == "SUM") {
for (k = 0; k < columnData.length; k++) {
result += Number(columnData[k]);
}
} else if (aggrMethod == "AVERAGE") {
if (!columnData.length) {
result = 0;
} else {
for (k = 0; k < columnData.length; k++) {
result += Number(columnData[k]);
}
result = (result / columnData.length).toFixed(2);
}
} else if (aggrMethod == "COUNT") {
result = columnData.length;
} else if (aggrMethod == "FIRST") {
result = columnData[0];
} else if (aggrMethod == "LAST") {
result = columnData[columnData.length - 1];
} else if (aggrMethod == "MAX") {
result = Math.max(...columnData.map((x) => Number(x)));
} else if (aggrMethod == "MIN") {
result = Math.min(...columnData.map((x) => Number(x)));
} else if (aggrMethod == "COUNTDISTINCT") {
result = [...new Set(columnData)].length;
}
return result;
};
this.sortResponse = function (arr, header, order) {
let rawArr = JSON.parse(JSON.stringify(arr)); //deep copy
//Find the column to sort by header name
let colIndex;
for (let i = 0; i < rawArr.length; i++) {
if (rawArr[i][0] == header) {
colIndex = i;
}
}
//Transpose data from rows to columns
let transposedArray = [];
for (let i = 0; i < rawArr[0].length; i++) {
let rowArr = [];
for (let j = 0; j < rawArr.length; j++) {
rowArr.push(rawArr[j][i]);
}
transposedArray.push(rowArr);
}
//Split body and headers
let headerArr = transposedArray[0];
let bodyArr = transposedArray.slice(1);
let firstNonBlank = null;
for (let i = 1; i < rawArr[colIndex].length; i++) {
if (rawArr[colIndex][i] != null) {
firstNonBlank = rawArr[colIndex][i];
break;
}
}
//If data type is Date
if (isDate(firstNonBlank)) {
//Sort dates
bodyArr.sort((a, b) =>
order == "descending"
? Date.parse(b[colIndex]) - Date.parse(a[colIndex])
: Date.parse(a[colIndex]) - Date.parse(b[colIndex])
);
}
//If data type is Number
else if (isNumber(firstNonBlank)) {
//Sort numbers
bodyArr.sort((a, b) =>
order == "descending"
? b[colIndex] - a[colIndex]
: a[colIndex] - b[colIndex]
);
}
//If data type is String
else {
bodyArr.sort(); //sorts a to z by default
if (order == "descending") bodyArr.reverse();
}
//Merge headers and body
let mergedArr = [headerArr, ...bodyArr];
let finalFormat = [];
//Transpose into row format again
for (let col = 0; col < mergedArr[0].length; col++) {
let bufferCol = [];
for (let row = 0; row < mergedArr.length; row++) {
bufferCol.push(mergedArr[row][col]);
}
finalFormat.push(bufferCol);
}
//Return sorted array
return finalFormat;
};
this.sortValues = function (arr, order) {
let rawArr = JSON.parse(JSON.stringify(arr)); //deep copy
//If data type is Date
if (isDate(rawArr[1]) || isNumber(rawArr[1])) {
rawArr.sort((a, b) =>
order == "descending"
? Date.parse(b) - Date.parse(a)
: Date.parse(a) - Date.parse(b)
);
} else {
//Sort strings
rawArr.sort(); //sorts a to z by default
if (order == "descending") rawArr.reverse();
}
return rawArr;
};
this.evaluateMeasure = function (field) {
let calculatedExpression = field.expression;
let functionsToEvaluate = [
"SUM",
"AVERAGE",
"COUNTDISTINCT",
"COUNT",
"MIN",
"MAX",
"FIRST",
"LAST",
];
let calculationSteps = 0;
for (let i = 0; i < functionsToEvaluate.length; i++) {
while (
this.evalFormula(
String(calculatedExpression),
functionsToEvaluate[i]
) != calculatedExpression
) {
calculationSteps++;
let oldExp = calculatedExpression;
calculatedExpression = this.evalFormula(
String(calculatedExpression),
functionsToEvaluate[i]
);
/* Uncomment to see expression evaluation steps
console.log(
`[${calculationSteps}] ${oldExp} ===> ${calculatedExpression}`
); */
}
}
let nonMathCharacters = calculatedExpression.match(
/[^1-9+0+\(+\)+\*+\/+\++\-+\s]/
);
if (nonMathCharacters) {
//Cannot evaluate, non matchmatical characters exist
return calculatedExpression;
} else {
//This might be evaluated
let evaluatedValue;
let errorFound = 0;
try {
evaluatedValue = eval(calculatedExpression);
} catch (e) {
console.error(
"ERROR : There is a problem with your field expression. Please check sytnax, table and field names."
);
errorFound = 1;
}
return !errorFound ? evaluatedValue : null;
}
};
this.evalFormula = function (expression, aggrFunction) {
//aggFunction = SUM, AVERAGE, MIN, MAX, FIRST, LAST, COUNT, DISTINCTCOUNT
let functionStartStr = aggrFunction + "(";
let functionEndStr = ")";
//Try to find the start of function
let startFound = expression.indexOf(functionStartStr);
if (startFound < 0) return expression; //function doesn't exist, return expression unchanged
//Try to find the end of function AFTER the start keywords
let endFoundAfterStart = expression
.slice(startFound + functionStartStr.length)
.indexOf(functionEndStr);
if (endFoundAfterStart < 0) return expression; //function doesn't exist, return expression unchanged
if (endFoundAfterStart < 1) return expression; //if function parameter is empty, return expression unchanged
//Find the absolute position of the end string
let endFound = startFound + functionStartStr.length + endFoundAfterStart;
//Extract the string between which are function parameters
let stringBetween = expression.slice(
startFound + functionStartStr.length,
endFound
);
//Extract table name and field name from function parameter
let fieldStart = "[";
let fieldEnd = "]";
//Try to find the start of field
let fieldStartFound = stringBetween.indexOf(fieldStart);
if (fieldStartFound < 0) return expression; //If field start is not found, return expression unchanged
if (fieldStartFound < 1) return expression; //If table name is missing, return unchanged (writing extra line so its easy to understand)
//Try to find the end of field AFTER the start character
let fieldEndFoundAfterStart = stringBetween
.slice(fieldStartFound + fieldStart.length)
.indexOf(fieldEnd);
if (fieldEndFoundAfterStart < 0) return expression; //If field end is not found, return expression unchanged
if (fieldEndFoundAfterStart < 1) return expression; //If field name is empty, return expression unchanged
//Find the absolute position of end character
let fieldEndFound =
fieldStartFound + fieldStart.length + fieldEndFoundAfterStart;
//Extract the table name and the field names
let tableName = stringBetween.slice(0, fieldStartFound);
let fieldName = stringBetween.slice(
fieldStartFound + fieldStart.length,
fieldEndFound
);
//Now we can aggregate
let targetTable = this.getBufferTable(tableName);
if (targetTable == null) return expression; //No such table, return expression unchanged
let targetColumn = targetTable.object.selectColumn(fieldName);
if (targetColumn == null) return expression; //No such column, return expression unchanged
//Calculate a single value
let dataBody = targetColumn.data[0].slice(1);
let aggregatedValue = this.aggregate(dataBody, aggrFunction);
//Replace the original expression with new value and return
return (
expression.slice(0, startFound) +
String(aggregatedValue) +
expression.slice(endFound + 1)
);
};
this.query = function (
uniqueID,
rowField,
columnField,
valueFields,
filterContext,
sortAlias,
sortOrder
) {
performanceTimer = 0;
let distinctRows = [];
let distinctColumns = [];
let valueColumns = [];
this.loadBuffer();
for (let k = 0; k < filterContext.length; k++) {
this.applyFilters(
filterContext[k].tableID,
filterContext[k].values,
filterContext[k].fieldName
);
}
//Process queries that consist of row and value(s)
if (!columnField && rowField && valueFields) {
//Get distinct row values
distinctRows = [
...new Set(
this.getBufferTable(rowField.tableID)
.object.selectColumn(rowField.fieldName)
.data[0].slice(1)
),
];
//Each value represents a column in the final format, therefore loop through values
for (let i = 0; i < valueFields.length; i++) {
//Prepare empty columns for each value
valueColumns.push([]);
//For each distinct value in the rows
for (let j = 0; j < distinctRows.length; j++) {
//Load the buffer from original tables and apply filters from the page
this.loadBuffer();
//Apply filter context (filters from the page)
for (let k = 0; k < filterContext.length; k++) {
this.applyFilters(
filterContext[k].tableID,
filterContext[k].values,
filterContext[k].fieldName
);
}
//Apply row context
this.applyFilters(
rowField.tableID,
[distinctRows[j]],
rowField.fieldName
);
//Evaluate expression and push to valueColumns
valueColumns[i].push(this.evaluateMeasure(valueFields[i]));
}
}
//Prepare response before sorting
let response = [];
response.push([rowField.alias, ...distinctRows]);
for (let i = 0; i < valueFields.length; i++) {
response.push([valueFields[i].alias, ...valueColumns[i]]);
}
//Sort response before sending to visual
let containsAlias = 0;
for (let i = 0; i < response.length; i++) {
if (response[i][0] == sortAlias) {
containsAlias = 1;
}
}
if (containsAlias) {
response = this.sortResponse(response, sortAlias, sortOrder);
}
//Send response to the visual
return response;
}
//Process queries with row, column and single value
else if (columnField && rowField && valueFields) {
//Get distinct row values
distinctRows = [
...new Set(
this.getBufferTable(rowField.tableID)
.object.selectColumn(rowField.fieldName)
.data[0].slice(1)
),
];
//Get distinct column values
distinctColumns = [
...new Set(
this.getBufferTable(columnField.tableID)
.object.selectColumn(columnField.fieldName)
.data[0].slice(1)
),
];
//Sort columns if requested here, before calculating the value for each column and row
if (sortAlias == columnField.alias) {
distinctColumns = this.sortValues(distinctColumns, sortOrder);
}
//For each distinct row value
for (let i = 0; i < distinctColumns.length; i++) {
//Add empty columns for values
valueColumns.push([]);
//For each column
for (let j = 0; j < distinctRows.length; j++) {
//Refresh the buffer from original tables and filters from the page
this.loadBuffer();
for (let m = 0; m < filterContext.length; m++) {
this.applyFilters(
filterContext[m].tableID,
filterContext[m].values,
filterContext[m].fieldName
);
}
//Apply column context
this.applyFilters(
columnField.tableID,
[distinctColumns[i]],
columnField.fieldName
);
//Apply row context
this.applyFilters(
rowField.tableID,
[distinctRows[j]],
rowField.fieldName
);
//Evaluate expression and push to valueColumns
valueColumns[i].push(this.evaluateMeasure(valueFields[0]));
}
}
//Prepare response before sorting
let response = [];
response.push([rowField.alias, ...distinctRows]);
for (let i = 0; i < distinctColumns.length; i++) {
response.push([distinctColumns[i], ...valueColumns[i]]);
}
//Sort by rows if requested
if (sortAlias == rowField.alias) {
response = this.sortResponse(response, sortAlias, sortOrder);
}
return response;
}
//Process only value requests
else if (!rowField && !columnField && valueFields) {
this.loadBuffer();
//Apply filter context (filters from the page)
for (let k = 0; k < filterContext.length; k++) {
this.applyFilters(
filterContext[k].tableID,
filterContext[k].values,
filterContext[k].fieldName
);
}
return this.evaluateMeasure(valueFields[0]);
}
};
}