-
Notifications
You must be signed in to change notification settings - Fork 0
/
SQLPerformanceTable.js
489 lines (402 loc) · 13.2 KB
/
SQLPerformanceTable.js
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
const sqlFormatter = require("sql-formatter");
const hljs = require("highlight.js");
class SQLPerformanceTable
{
/**
* If strLanguage is not set, it will default to navigator.language if a translation exists, otherwise "en" (English).
*
* @param {string|undefined} strLanguage = undefined
*/
constructor(strLanguage = undefined)
{
this._strLanguageCode = strLanguage || navigator.language;
this._objSQLQueriesToPerformanceCounters = {};
this._mapSQLQueryToTableRow = new Map();
this._strCurrentSortColumnName = "fetchedRows";
this._strCurrentSortDirection = "DESC";
this._promiseSortingSQLQueriesTable = null;
this._elTable = document.createElement("table");
// Bootstrap specific.
this._elTable.classList.add("table");
this._elTable.classList.add("table-hover");
// For destroy.
this._arrDisposeCalls = [];
// For destroy or clear.
this._arrDisposeCallsTableRows = [];
this._initTable();
}
/**
* Removes events listeners, removes the table from its parent node and sets various stuff to null.
*/
destroy()
{
if(!this._arrDisposeCalls)
{
return;
}
if(this._elTable)
{
if(this._elTable.parentNode)
{
this._elTable.parentNode.removeChild(this._elTable);
}
this._elTable = null;
}
this._promiseSortingSQLQueriesTable = null;
this._mapSQLQueryToTableRow.clear();
this._mapSQLQueryToTableRow = null;
this._arrDisposeCalls.map(fnDispose => { fnDispose(); });
this._arrDisposeCalls.splice(0);
this._arrDisposeCalls = null;
this._objSQLQueriesToPerformanceCounters = {};
}
/**
* @returns {HTMLElementTable}
*/
get table()
{
return this._elTable;
}
/**
* @returns {Object.<string, translation: string>}
*/
get texts()
{
if(SQLPerformanceTable.texts[this._strLanguageCode || navigator.language])
{
return SQLPerformanceTable.texts[this._strLanguageCode || navigator.language];
}
return SQLPerformanceTable.texts["en"];
}
/**
* Clears the table keeping the header.
*/
clear()
{
this._mapSQLQueryToTableRow.clear();
this._arrDisposeCallsTableRows.map(fnDispose => { fnDispose(); });
this._arrDisposeCallsTableRows.splice(0);
while(this._elTable.rows.length > 1)
{
this._elTable.deleteRow(this._elTable.rows.length - 1);
}
this._objSQLQueriesToPerformanceCounters = {};
}
/**
* objSQLToPerformanceCounters may contain only newly modified queries.
*
* @param {Object<string, metrics:{successCount: number, errorCount: number, successMillisecondsTotal: number, fetchedRows: number, affectedRows: number, changedRows: 0, errorMillisecondsTotal: number, successMillisecondsAverage: number, errorMillisecondsAverage: number}>} objSQLToPerformanceCounters
* @param {boolean} bClearExisting
*/
update(objSQLToPerformanceCounters, bClearExisting = false)
{
if(bClearExisting)
{
this.clear();
}
Object.assign(this._objSQLQueriesToPerformanceCounters, objSQLToPerformanceCounters);
for(const strSQL in this._objSQLQueriesToPerformanceCounters)
{
let elRow = this._mapSQLQueryToTableRow.get(strSQL);
if(!elRow)
{
elRow = this._elTable.insertRow(-1);
this._mapSQLQueryToTableRow.set(strSQL, elRow);
for(const strColumnName of SQLPerformanceTable.columnNames)
{
const elCell = elRow.insertCell(-1);
if(strColumnName === "query")
{
const elCodeSQL = document.createElement("code");
elCodeSQL.innerText = strSQL;
const elCodeSQLFormatted = document.createElement("code");
// When not using a build system, maybe sqlFormatter is not available on the global namespace (window).
if(sqlFormatter)
{
elCodeSQLFormatted.innerText = sqlFormatter.format(strSQL);
}
elCodeSQLFormatted.style.whiteSpace = "pre-wrap";
// When not using a build system, maybe hljs is not available on the global namespace (window).
if(hljs)
{
hljs.highlightBlock(elCodeSQL);
hljs.highlightBlock(elCodeSQLFormatted);
}
elCell.appendChild(elCodeSQL);
elCell.appendChild(elCodeSQLFormatted);
elCodeSQLFormatted.style.display = "none";
// When not using a build system, maybe sqlFormatter is not available on the global namespace (window).
if(sqlFormatter)
{
elCell.style.cursor = "pointer";
const fnOnClick = (() => {
if(elCodeSQLFormatted.style.display === "none")
{
elCodeSQLFormatted.style.display = "";
elCodeSQL.style.display = "none";
}
else
{
elCodeSQLFormatted.style.display = "none";
elCodeSQL.style.display = "";
}
}).bind(this);
elCodeSQL.addEventListener("click", fnOnClick);
this._arrDisposeCallsTableRows.push(() => { elCodeSQL.removeEventListener("click", fnOnClick); });
elCodeSQLFormatted.addEventListener("click", fnOnClick);
this._arrDisposeCallsTableRows.push(() => { elCodeSQLFormatted.removeEventListener("click", fnOnClick); });
}
}
else if(strColumnName === "copyToClipboard")
{
if(navigator && navigator.clipboard && navigator.clipboard.writeText)
{
const elAnchorCopyToClipboard = document.createElement("a");
elAnchorCopyToClipboard.innerHTML = /*html*/`📋`;
elAnchorCopyToClipboard.title = this.texts.copyToClipboard;
elAnchorCopyToClipboard.href = "javascript:void(0)";
const fnOnClick = (async() => {
let strSQLForClipboard = strSQL;
if(sqlFormatter)
{
try
{
strSQLForClipboard = sqlFormatter.format(strSQL)
}
catch(error)
{
console.error(error);
}
}
try
{
await navigator.clipboard.writeText(strSQLForClipboard);
}
catch(error)
{
alert(error.message);
}
}).bind(this);
elAnchorCopyToClipboard.addEventListener("click", fnOnClick);
this._arrDisposeCallsTableRows.push(() => { elAnchorCopyToClipboard.removeEventListener("click", fnOnClick); });
elCell.appendChild(elAnchorCopyToClipboard);
}
}
else
{
if(this._objSQLQueriesToPerformanceCounters[strSQL])
{
elCell.innerText = this._renderValue(strColumnName, this._objSQLQueriesToPerformanceCounters[strSQL]);
elCell.title = strColumnName;
elCell.style.textAlign = "right";
elCell.style.whiteSpace = "pre";
}
else
{
// console.error(`${strSQL} no longer set in this._objSQLQueriesToPerformanceCounters`);
}
}
}
}
else
{
for(const nColumnIndex in SQLPerformanceTable.columnNames)
{
if(nColumnIndex < (/*sql*/ 1 + /*copy to clipboard*/ 1))
{
continue;
}
const elCell = elRow.cells.item(nColumnIndex);
if(elCell)
{
if(objSQLToPerformanceCounters[strSQL])
{
elCell.innerText = this._renderValue(/*strColumnName*/ elCell.title, objSQLToPerformanceCounters[strSQL]);
}
else
{
// console.error(`${strSQL} no longer set in this._objSQLQueriesToPerformanceCounters`);
}
}
}
}
}
this.sort(this._strCurrentSortColumnName, this._strCurrentSortDirection);
}
/**
* Sorts the table in place by moving the rows using HTMLElement.insertBefore().
*
* @param {string} strColumnName = "fetchedRows"
* @param {string} strSortDirection = "DESC"
*/
sort(strColumnName = "fetchedRows", strSortDirection = "DESC")
{
this._strCurrentSortColumnName = strColumnName;
this._strCurrentSortDirection = strSortDirection;
const mapObjectToSQL = new Map();
for(const strSQL in this._objSQLQueriesToPerformanceCounters)
{
mapObjectToSQL.set(this._objSQLQueriesToPerformanceCounters[strSQL], strSQL);
}
const arrDataRows = Object.values(this._objSQLQueriesToPerformanceCounters);
arrDataRows.sort((objPerformanceCountersA, objPerformanceCountersB) => {
return (strSortDirection === "ASC" ? 1 : -1) * (objPerformanceCountersB[strColumnName] - objPerformanceCountersA[strColumnName]);
});
// console.log(`Sorting ${strColumnName} ${strSortDirection}`, arrDataRows);
let elPreviousRow = null;
for(let i = 0; i < arrDataRows.length; i++)
{
const objPerformanceCounters = arrDataRows[i];
const strSQL = mapObjectToSQL.get(objPerformanceCounters);
if(strSQL)
{
const elRow = this._mapSQLQueryToTableRow.get(strSQL);
if(elRow)
{
if(elPreviousRow)
{
elRow.parentNode.insertBefore(elRow, elPreviousRow);
}
elPreviousRow = elRow;
}
else
{
// console.error(`Could not find table row for ${strSQL} when sorting.`);
}
}
else
{
// console.error(`Could not find SQL for performance counters object ${JSON.stringify(objPerformanceCounters)}`);
}
}
}
_renderValue(strColumnName, objSQLToPerformanceCounter)
{
let strText;
if(["successMillisecondsTotal", "errorMillisecondsTotal"].includes(strColumnName))
{
const nSeconds = parseInt(objSQLToPerformanceCounter[strColumnName] / 1000);
strText = `${nSeconds} ${nSeconds === 1 ? this.texts.secondShort : this.texts.secondsShort}`;
}
else if(["successMillisecondsAverage", "errorMillisecondsAverage"].includes(strColumnName))
{
const nMilliseconds = objSQLToPerformanceCounter[strColumnName];
strText = `${nMilliseconds} ${nMilliseconds === 1 ? this.texts.millisecondShort : this.texts.millisecondsShort}`;
}
else
{
strText = objSQLToPerformanceCounter[strColumnName];
}
return strText;
}
/**
* Adds a header row into this._elTable and click event listeners for sortable columns.
*/
_initTable()
{
if(this._elTable.rows.length)
{
return;
}
const elRowHeader = this._elTable.insertRow(-1);
for(const strColumnName of SQLPerformanceTable.columnNames)
{
const elCell = elRowHeader.insertCell(-1);
elCell.textContent = this.texts[strColumnName];
elCell.title = strColumnName;
elCell.style.fontWeight = "bold";
if(strColumnName === "query")
{
// It doesn't make sense to sort based on the query.
}
else if(strColumnName === "copyToClipboard")
{
// It doesn't make sense to sort based on the clipboard button.
elCell.textContent = "";
}
else
{
elCell.style.textAlign = "right";
elCell.style.cursor = "pointer";
const fnOnClick = (async() => {
let strSortDirection;
if(this._strCurrentSortColumnName === strColumnName)
{
strSortDirection = this._strCurrentSortDirection === "DESC" ? "ASC" : "DESC";
}
else
{
strSortDirection = "DESC";
}
this.sort(strColumnName, strSortDirection);
}).bind(this);
elCell.addEventListener("click", fnOnClick);
this._arrDisposeCalls.push(() => { elCell.removeEventListener("click", fnOnClick); });
}
}
}
};
// Except for "query", all other column names are sortable, see SQLPerformanceTable.sort().
SQLPerformanceTable.columnNames = [
"query",
"copyToClipboard",
"fetchedRows",
"affectedRows",
"changedRows",
"successCount",
"successMillisecondsAverage",
"successMillisecondsTotal",
"errorCount",
"errorMillisecondsAverage",
"errorMillisecondsTotal"
];
// Feel free to add translations after importing the class into your scope.
SQLPerformanceTable.texts = {
en: {
query: "SQL query",
fetchedRows: "Fetched rows",
affectedRows: "Affected rows",
changedRows: "Changed rows",
successCount: "Success count",
successMillisecondsAverage: "Success average duration",
successMillisecondsTotal: "Total duration",
errorCount: "No. of errors",
errorMillisecondsAverage: "Error average duration",
errorMillisecondsTotal: "Total error duration",
second: "second",
seconds: "seconds",
millisecond: "millisecond",
milliseconds: "milliseconds",
secondShort: "sec",
secondsShort: "sec",
millisecondShort: "ms",
millisecondsShort: "ms",
copyToClipboard: "Copy to clipboard"
},
ro: {
query: "Interogare",
fetchedRows: "Rânduri întoarse",
affectedRows: "Rânduri afectate",
changedRows: "Rânduri schimbate",
successCount: "Nr. rulări cu succes",
successMillisecondsAverage: "Medie rulare cu succes",
successMillisecondsTotal: "Total rulări cu succes",
errorCount: "Nr. erori",
errorMillisecondsAverage: "Medie rulare erori",
errorMillisecondsTotal: "Total rulare erori",
second: "secundă",
seconds: "secunde",
millisecond: "milisecundă",
milliseconds: "milisecunde",
secondShort: "sec",
secondsShort: "sec",
millisecondShort: "ms",
millisecondsShort: "ms",
copyToClipboard: "Copiază în clipboard"
}
};
SQLPerformanceTable.texts["ro-RO"] = SQLPerformanceTable.texts.ro;
SQLPerformanceTable.texts["ro-MD"] = SQLPerformanceTable.texts.ro;
SQLPerformanceTable.texts["en-US"] = SQLPerformanceTable.texts.en;
SQLPerformanceTable.texts["en-UK"] = SQLPerformanceTable.texts.en;
module.exports = SQLPerformanceTable;