iobroker.sql 3.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +138 -424
  3. package/admin/i18n/de/translations.json +1 -1
  4. package/admin/i18n/en/translations.json +1 -1
  5. package/admin/i18n/es/translations.json +12 -12
  6. package/admin/i18n/fr/translations.json +1 -1
  7. package/admin/i18n/it/translations.json +1 -1
  8. package/admin/i18n/nl/translations.json +1 -1
  9. package/admin/i18n/pt/translations.json +1 -1
  10. package/admin/i18n/ru/translations.json +1 -1
  11. package/admin/jsonConfig.json +423 -321
  12. package/admin/words.js +12 -12
  13. package/build/lib/aggregate.js +1484 -0
  14. package/build/lib/aggregate.js.map +1 -0
  15. package/build/lib/connection-factory.js +7 -0
  16. package/build/lib/connection-factory.js.map +1 -0
  17. package/build/lib/mssql-client.js +67 -0
  18. package/build/lib/mssql-client.js.map +1 -0
  19. package/build/lib/mssql.js +267 -0
  20. package/build/lib/mssql.js.map +1 -0
  21. package/build/lib/mysql-client.js +55 -0
  22. package/build/lib/mysql-client.js.map +1 -0
  23. package/build/lib/mysql.js +245 -0
  24. package/build/lib/mysql.js.map +1 -0
  25. package/build/lib/postgresql-client.js +56 -0
  26. package/build/lib/postgresql-client.js.map +1 -0
  27. package/build/lib/postgresql.js +241 -0
  28. package/build/lib/postgresql.js.map +1 -0
  29. package/build/lib/sql-client-pool.js +369 -0
  30. package/build/lib/sql-client-pool.js.map +1 -0
  31. package/build/lib/sql-client.js +110 -0
  32. package/build/lib/sql-client.js.map +1 -0
  33. package/build/lib/sqlite.js +244 -0
  34. package/build/lib/sqlite.js.map +1 -0
  35. package/build/lib/sqlite3-client.js +68 -0
  36. package/build/lib/sqlite3-client.js.map +1 -0
  37. package/build/main.js +3591 -0
  38. package/build/main.js.map +1 -0
  39. package/docker-compose.yaml +57 -0
  40. package/io-package.json +41 -19
  41. package/package.json +28 -20
  42. package/admin/.gitignore +0 -0
  43. package/lib/aggregate.js +0 -1000
  44. package/lib/mssql-client.js +0 -61
  45. package/lib/mssql.js +0 -278
  46. package/lib/mysql-client.js +0 -62
  47. package/lib/mysql.js +0 -263
  48. package/lib/postgresql-client.js +0 -202
  49. package/lib/postgresql.js +0 -260
  50. package/lib/sqlite.js +0 -260
  51. package/lib/tools.js +0 -99
  52. package/main.js +0 -3469
package/build/main.js ADDED
@@ -0,0 +1,3591 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SqlAdapter = void 0;
37
+ const adapter_core_1 = require("@iobroker/adapter-core"); // Get common adapter utils
38
+ const aggregate_1 = require("./lib/aggregate");
39
+ const node_fs_1 = require("node:fs");
40
+ const node_path_1 = require("node:path");
41
+ const MSSQL = __importStar(require("./lib/mssql"));
42
+ const MySQL = __importStar(require("./lib/mysql"));
43
+ const PostgreSQL = __importStar(require("./lib/postgresql"));
44
+ const SQLite = __importStar(require("./lib/sqlite"));
45
+ const mssql_client_1 = require("./lib/mssql-client");
46
+ const mysql_client_1 = require("./lib/mysql-client");
47
+ const postgresql_client_1 = require("./lib/postgresql-client");
48
+ const sqlite3_client_1 = require("./lib/sqlite3-client");
49
+ const SQLFuncs = {
50
+ mssql: {
51
+ init: MSSQL.init,
52
+ destroy: MSSQL.destroy,
53
+ getFirstTs: MSSQL.getFirstTs,
54
+ insert: MSSQL.insert,
55
+ retention: MSSQL.retention,
56
+ getIdSelect: MSSQL.getIdSelect,
57
+ getIdInsert: MSSQL.getIdInsert,
58
+ getIdUpdate: MSSQL.getIdUpdate,
59
+ getFromSelect: MSSQL.getFromSelect,
60
+ getFromInsert: MSSQL.getFromInsert,
61
+ getCounterDiff: MSSQL.getCounterDiff,
62
+ getHistory: MSSQL.getHistory,
63
+ deleteFromTable: MSSQL.deleteFromTable,
64
+ update: MSSQL.update,
65
+ },
66
+ mysql: {
67
+ init: MySQL.init,
68
+ destroy: MySQL.destroy,
69
+ getFirstTs: MySQL.getFirstTs,
70
+ insert: MySQL.insert,
71
+ retention: MySQL.retention,
72
+ getIdSelect: MySQL.getIdSelect,
73
+ getIdInsert: MySQL.getIdInsert,
74
+ getIdUpdate: MySQL.getIdUpdate,
75
+ getFromSelect: MySQL.getFromSelect,
76
+ getFromInsert: MySQL.getFromInsert,
77
+ getCounterDiff: MySQL.getCounterDiff,
78
+ getHistory: MySQL.getHistory,
79
+ deleteFromTable: MySQL.deleteFromTable,
80
+ update: MySQL.update,
81
+ },
82
+ postgresql: {
83
+ init: PostgreSQL.init,
84
+ destroy: PostgreSQL.destroy,
85
+ getFirstTs: PostgreSQL.getFirstTs,
86
+ insert: PostgreSQL.insert,
87
+ retention: PostgreSQL.retention,
88
+ getIdSelect: PostgreSQL.getIdSelect,
89
+ getIdInsert: PostgreSQL.getIdInsert,
90
+ getIdUpdate: PostgreSQL.getIdUpdate,
91
+ getFromSelect: PostgreSQL.getFromSelect,
92
+ getFromInsert: PostgreSQL.getFromInsert,
93
+ getCounterDiff: PostgreSQL.getCounterDiff,
94
+ getHistory: PostgreSQL.getHistory,
95
+ deleteFromTable: PostgreSQL.deleteFromTable,
96
+ update: PostgreSQL.update,
97
+ },
98
+ sqlite: {
99
+ init: SQLite.init,
100
+ destroy: SQLite.destroy,
101
+ getFirstTs: SQLite.getFirstTs,
102
+ insert: SQLite.insert,
103
+ retention: SQLite.retention,
104
+ getIdSelect: SQLite.getIdSelect,
105
+ getIdInsert: SQLite.getIdInsert,
106
+ getIdUpdate: SQLite.getIdUpdate,
107
+ getFromSelect: SQLite.getFromSelect,
108
+ getFromInsert: SQLite.getFromInsert,
109
+ getCounterDiff: SQLite.getCounterDiff,
110
+ getHistory: SQLite.getHistory,
111
+ deleteFromTable: SQLite.deleteFromTable,
112
+ update: SQLite.update,
113
+ },
114
+ };
115
+ const clients = {
116
+ postgresql: { multiRequests: true },
117
+ mysql: { multiRequests: true },
118
+ sqlite: { multiRequests: false },
119
+ mssql: { multiRequests: true },
120
+ };
121
+ const types = {
122
+ number: 0,
123
+ string: 1,
124
+ boolean: 2,
125
+ object: 1,
126
+ };
127
+ const dbNames = ['ts_number', 'ts_string', 'ts_bool'];
128
+ const storageTypes = ['Number', 'String', 'Boolean'];
129
+ function isEqual(a, b) {
130
+ //console.log('Compare ' + JSON.stringify(a) + ' with ' + JSON.stringify(b));
131
+ // Create arrays of property names
132
+ if (a === null || a === undefined || b === null || b === undefined) {
133
+ return a === b;
134
+ }
135
+ const aProps = Object.getOwnPropertyNames(a);
136
+ const bProps = Object.getOwnPropertyNames(b);
137
+ // If the number of properties is different,
138
+ // objects are not equivalent
139
+ if (aProps.length !== bProps.length) {
140
+ //console.log('num props different: ' + JSON.stringify(aProps) + ' / ' + JSON.stringify(bProps));
141
+ return false;
142
+ }
143
+ for (let i = 0; i < aProps.length; i++) {
144
+ const propName = aProps[i];
145
+ if (typeof a[propName] !== typeof b[propName]) {
146
+ //console.log('type props ' + propName + ' different');
147
+ return false;
148
+ }
149
+ else if (typeof a[propName] === 'object') {
150
+ if (!isEqual(a[propName], b[propName])) {
151
+ return false;
152
+ }
153
+ }
154
+ else {
155
+ // If values of same property are not equal,
156
+ // objects are not equivalent
157
+ if (a[propName] !== b[propName]) {
158
+ //console.log('props ' + propName + ' different');
159
+ return false;
160
+ }
161
+ }
162
+ }
163
+ // If we made it this far, objects
164
+ // are considered equivalent
165
+ return true;
166
+ }
167
+ const MAX_TASKS = 100;
168
+ function sortByTs(a, b) {
169
+ const aTs = a.ts;
170
+ const bTs = b.ts;
171
+ return aTs < bTs ? -1 : aTs > bTs ? 1 : 0;
172
+ }
173
+ class SqlAdapter extends adapter_core_1.Adapter {
174
+ sqlDPs = {};
175
+ from = {};
176
+ tasks = [];
177
+ tasksReadType = [];
178
+ tasksStart = [];
179
+ isFromRunning = {};
180
+ aliasMap = {};
181
+ finished = false;
182
+ sqlConnected = null;
183
+ multiRequests = true;
184
+ subscribeAll = false;
185
+ clientPool = null;
186
+ reconnectTimeout = null;
187
+ testConnectTimeout = null;
188
+ dpOverviewTimeout = null;
189
+ bufferChecker = null;
190
+ activeConnections = 0;
191
+ poolBorrowGuard = []; // required until https://github.com/intellinote/sql-client/issues/7 is fixed
192
+ logConnectionUsage = true;
193
+ postgresDbCreated = false;
194
+ lockTasks = false;
195
+ sqlFuncs = null;
196
+ constructor(options = {}) {
197
+ super({
198
+ ...options,
199
+ name: 'sql',
200
+ ready: () => this.main(),
201
+ message: (obj) => this.processMessage(obj),
202
+ stateChange: (id, state) => {
203
+ id = this.aliasMap[id] || id;
204
+ this.pushHistory(id, state);
205
+ },
206
+ objectChange: (id, obj) => {
207
+ let tmpState;
208
+ const now = Date.now();
209
+ const formerAliasId = this.aliasMap[id] || id;
210
+ if (obj?.common?.custom?.[this.namespace] &&
211
+ typeof obj.common.custom[this.namespace] === 'object' &&
212
+ obj.common.custom[this.namespace].enabled) {
213
+ const realId = id;
214
+ let checkForRemove = true;
215
+ if (obj.common.custom?.[this.namespace]?.aliasId) {
216
+ if (obj.common.custom[this.namespace].aliasId !== id) {
217
+ this.aliasMap[id] = obj.common.custom[this.namespace].aliasId;
218
+ this.log.debug(`Registered Alias: ${id} --> ${this.aliasMap[id]}`);
219
+ id = this.aliasMap[id];
220
+ checkForRemove = false;
221
+ }
222
+ else {
223
+ this.log.warn(`Ignoring Alias-ID because identical to ID for ${id}`);
224
+ obj.common.custom[this.namespace].aliasId = '';
225
+ }
226
+ }
227
+ if (checkForRemove && this.aliasMap[id]) {
228
+ this.log.debug(`Removed Alias: ${id} !-> ${this.aliasMap[id]}`);
229
+ delete this.aliasMap[id];
230
+ }
231
+ if (!this.sqlDPs[formerAliasId]?.config && !this.subscribeAll) {
232
+ // un-subscribe
233
+ for (const _id in this.sqlDPs) {
234
+ if (Object.prototype.hasOwnProperty.call(this.sqlDPs, _id) &&
235
+ Object.prototype.hasOwnProperty.call(this.sqlDPs, this.sqlDPs[_id].realId)) {
236
+ this.unsubscribeForeignStates(this.sqlDPs[_id].realId);
237
+ }
238
+ }
239
+ this.subscribeAll = true;
240
+ this.subscribeForeignStates('*');
241
+ }
242
+ if (this.sqlDPs[id] && this.sqlDPs[id].index === undefined) {
243
+ this.getId(id, this.sqlDPs[id].dbType, () => this.reInit(id, realId, formerAliasId, obj));
244
+ }
245
+ else {
246
+ this.reInit(id, realId, formerAliasId, obj);
247
+ }
248
+ }
249
+ else {
250
+ if (this.aliasMap[id]) {
251
+ this.log.debug(`Removed Alias: ${id} !-> ${this.aliasMap[id]}`);
252
+ delete this.aliasMap[id];
253
+ }
254
+ const sqlDP = this.sqlDPs[id];
255
+ id = formerAliasId;
256
+ if (sqlDP?.config) {
257
+ this.log.info(`disabled logging of ${id}`);
258
+ if (sqlDP.relogTimeout) {
259
+ clearTimeout(sqlDP.relogTimeout);
260
+ sqlDP.relogTimeout = null;
261
+ }
262
+ if (sqlDP.timeout) {
263
+ clearTimeout(sqlDP.timeout);
264
+ sqlDP.timeout = null;
265
+ }
266
+ if (sqlDP.state) {
267
+ tmpState = { ...sqlDP.state };
268
+ }
269
+ const state = sqlDP.state ? tmpState || null : null;
270
+ if (sqlDP.config) {
271
+ sqlDP.config.enabled = false;
272
+ if (sqlDP.skipped && !sqlDP.config.disableSkippedValueLogging) {
273
+ this.pushValueIntoDB(id, sqlDP.skipped, false, true);
274
+ sqlDP.skipped = null;
275
+ }
276
+ if (this.config.writeNulls) {
277
+ const nullValue = {
278
+ val: null,
279
+ ts: now,
280
+ lc: now,
281
+ q: 0x40,
282
+ from: `system.adapter.${this.namespace}`,
283
+ ack: true,
284
+ };
285
+ if (sqlDP.config.changesOnly && state && state.val !== null) {
286
+ ((_id, _state, _nullValue) => {
287
+ _state.ts = now;
288
+ _state.from = `system.adapter.${this.namespace}`;
289
+ nullValue.ts += 4;
290
+ nullValue.lc += 4; // because of MS SQL
291
+ this.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
292
+ this.pushValueIntoDB(_id, _state, false, true, () => {
293
+ // terminate values with null to indicate adapter stop. timestamp + 1
294
+ this.log.debug(`Write 2/2 "null" _id: ${_id}`);
295
+ this.pushValueIntoDB(_id, _nullValue, false, false, () => delete this.sqlDPs[id]);
296
+ });
297
+ })(id, state, nullValue);
298
+ }
299
+ else {
300
+ // terminate values with null to indicate adapter stop. timestamp + 1
301
+ this.log.debug(`Write 0 NULL _id: ${id}`);
302
+ this.pushValueIntoDB(id, nullValue, false, false, () => delete this.sqlDPs[id]);
303
+ }
304
+ }
305
+ else {
306
+ this.storeCached(id, () => delete this.sqlDPs[id]);
307
+ }
308
+ }
309
+ else {
310
+ delete this.sqlDPs[id];
311
+ }
312
+ }
313
+ }
314
+ },
315
+ unload: (callback) => {
316
+ void this.finish(callback);
317
+ },
318
+ });
319
+ }
320
+ borrowClientFromPool(callback) {
321
+ if (!this.clientPool) {
322
+ this.setConnected(false);
323
+ return callback(new Error('No database connection'));
324
+ }
325
+ this.setConnected(true);
326
+ if (this.activeConnections >= this.config.maxConnections) {
327
+ if (this.logConnectionUsage) {
328
+ this.log.debug(`Borrow connection not possible: ${this.activeConnections} >= Max - Store for Later`);
329
+ }
330
+ this.poolBorrowGuard.push(callback);
331
+ return;
332
+ }
333
+ this.activeConnections++;
334
+ if (this.logConnectionUsage) {
335
+ this.log.debug(`Borrow connection from pool: ${this.activeConnections} now`);
336
+ }
337
+ this.clientPool.borrow((err, client) => {
338
+ if (!err && client) {
339
+ // make sure we always have at least one error listener to prevent crashes
340
+ if (client.on && client.listenerCount && !client.listenerCount('error')) {
341
+ client.on('error', (err) => this.log.warn(`SQL client error: ${err}`));
342
+ }
343
+ }
344
+ else if (!client) {
345
+ this.activeConnections--;
346
+ }
347
+ callback(err, client);
348
+ });
349
+ }
350
+ returnClientToPool(client) {
351
+ if (client) {
352
+ this.activeConnections--;
353
+ }
354
+ if (this.logConnectionUsage) {
355
+ this.log.debug(`Return connection to pool: ${this.activeConnections} now`);
356
+ }
357
+ if (this.clientPool && client) {
358
+ if (this.poolBorrowGuard.length) {
359
+ this.activeConnections++;
360
+ if (this.logConnectionUsage) {
361
+ this.log.debug(`Borrow returned connection directly: ${this.activeConnections} now`);
362
+ }
363
+ const callback = this.poolBorrowGuard.shift();
364
+ callback(null, client);
365
+ }
366
+ else {
367
+ try {
368
+ this.clientPool.return(client);
369
+ }
370
+ catch {
371
+ // Ignore
372
+ }
373
+ }
374
+ }
375
+ }
376
+ normalizeCustomConfig(customConfig) {
377
+ // maxLength
378
+ if (!customConfig.maxLength && customConfig.maxLength !== '0' && customConfig.maxLength !== 0) {
379
+ customConfig.maxLength = this.config.maxLength || 0;
380
+ }
381
+ else {
382
+ customConfig.maxLength = parseInt(customConfig.maxLength, 10);
383
+ }
384
+ // retention
385
+ if (customConfig.retention || customConfig.retention === 0) {
386
+ customConfig.retention = parseInt(customConfig.retention, 10) || 0;
387
+ }
388
+ else {
389
+ customConfig.retention = this.config.retention;
390
+ }
391
+ if (customConfig.retention === -1) {
392
+ // customRetentionDuration
393
+ if (customConfig.customRetentionDuration !== undefined &&
394
+ customConfig.customRetentionDuration !== null &&
395
+ customConfig.customRetentionDuration !== '') {
396
+ customConfig.customRetentionDuration =
397
+ parseInt(customConfig.customRetentionDuration, 10) || 0;
398
+ }
399
+ else {
400
+ customConfig.customRetentionDuration = this.config.customRetentionDuration;
401
+ }
402
+ customConfig.retention = customConfig.customRetentionDuration * 24 * 60 * 60;
403
+ }
404
+ // debounceTime and debounce compatibility handling
405
+ if (!customConfig.blockTime && customConfig.blockTime !== '0' && customConfig.blockTime !== 0) {
406
+ if (!customConfig.debounce && customConfig.debounce !== '0' && customConfig.debounce !== 0) {
407
+ customConfig.blockTime = this.config.blockTime || 0;
408
+ }
409
+ else {
410
+ customConfig.blockTime = parseInt(customConfig.debounce, 10) || 0;
411
+ }
412
+ }
413
+ else {
414
+ customConfig.blockTime = parseInt(customConfig.blockTime, 10) || 0;
415
+ }
416
+ if (!customConfig.debounceTime && customConfig.debounceTime !== '0' && customConfig.debounceTime !== 0) {
417
+ customConfig.debounceTime = this.config.debounceTime || 0;
418
+ }
419
+ else {
420
+ customConfig.debounceTime = parseInt(customConfig.debounceTime, 10) || 0;
421
+ }
422
+ // changesOnly
423
+ customConfig.changesOnly = customConfig.changesOnly === true || customConfig.changesOnly === 'true';
424
+ // ignoreZero
425
+ customConfig.ignoreZero = customConfig.ignoreZero === true || customConfig.ignoreZero === 'true';
426
+ // round
427
+ if (customConfig.round !== null && customConfig.round !== undefined && customConfig.round !== '') {
428
+ customConfig.round = parseInt(customConfig.round, 10);
429
+ if (!isFinite(customConfig.round) || customConfig.round < 0) {
430
+ customConfig.round = this.config.round;
431
+ }
432
+ else {
433
+ customConfig.round = Math.pow(10, parseInt(customConfig.round, 10));
434
+ }
435
+ }
436
+ else {
437
+ customConfig.round = this.config.round;
438
+ }
439
+ // ignoreAboveNumber
440
+ if (customConfig.ignoreAboveNumber !== undefined &&
441
+ customConfig.ignoreAboveNumber !== null &&
442
+ customConfig.ignoreAboveNumber !== '') {
443
+ customConfig.ignoreAboveNumber = parseFloat(customConfig.ignoreAboveNumber) || null;
444
+ }
445
+ // ignoreBelowNumber incl. ignoreBelowZero compatibility handling
446
+ if (customConfig.ignoreBelowNumber !== undefined &&
447
+ customConfig.ignoreBelowNumber !== null &&
448
+ customConfig.ignoreBelowNumber !== '') {
449
+ customConfig.ignoreBelowNumber = parseFloat(customConfig.ignoreBelowNumber) || null;
450
+ }
451
+ else if (customConfig.ignoreBelowZero === 'true' || customConfig.ignoreBelowZero === true) {
452
+ customConfig.ignoreBelowNumber = 0;
453
+ }
454
+ // disableSkippedValueLogging
455
+ if (customConfig.disableSkippedValueLogging !== undefined &&
456
+ customConfig.disableSkippedValueLogging !== null &&
457
+ customConfig.disableSkippedValueLogging !== '') {
458
+ customConfig.disableSkippedValueLogging =
459
+ customConfig.disableSkippedValueLogging === 'true' || customConfig.disableSkippedValueLogging === true;
460
+ }
461
+ else {
462
+ customConfig.disableSkippedValueLogging = this.config.disableSkippedValueLogging;
463
+ }
464
+ // enableDebugLogs
465
+ if (customConfig.enableDebugLogs !== undefined &&
466
+ customConfig.enableDebugLogs !== null &&
467
+ customConfig.enableDebugLogs !== '') {
468
+ customConfig.enableDebugLogs =
469
+ customConfig.enableDebugLogs === 'true' || customConfig.enableDebugLogs === true;
470
+ }
471
+ else {
472
+ customConfig.enableDebugLogs = this.config.enableDebugLogs;
473
+ }
474
+ // changesRelogInterval
475
+ if (customConfig.changesRelogInterval || customConfig.changesRelogInterval === 0) {
476
+ customConfig.changesRelogInterval = parseInt(customConfig.changesRelogInterval, 10) || 0;
477
+ }
478
+ else {
479
+ customConfig.changesRelogInterval = this.config.changesRelogInterval;
480
+ }
481
+ // changesMinDelta
482
+ if (customConfig.changesMinDelta || customConfig.changesMinDelta === 0) {
483
+ customConfig.changesMinDelta = parseFloat(customConfig.changesMinDelta.toString().replace(/,/g, '.')) || 0;
484
+ }
485
+ else {
486
+ customConfig.changesMinDelta = this.config.changesMinDelta;
487
+ }
488
+ // storageType
489
+ if (!customConfig.storageType) {
490
+ customConfig.storageType = false;
491
+ }
492
+ // add one day if retention is too small
493
+ if (customConfig.retention && customConfig.retention <= 604800) {
494
+ customConfig.retention += 86400;
495
+ }
496
+ return customConfig;
497
+ }
498
+ reInit(id, realId, formerAliasId, obj) {
499
+ const customConfig = this.normalizeCustomConfig(obj.common.custom?.[this.namespace]);
500
+ if (this.sqlDPs[formerAliasId]?.config && isEqual(customConfig, this.sqlDPs[formerAliasId].config)) {
501
+ if (obj.common.custom?.[this.namespace].enableDebugLogs) {
502
+ this.log.debug(`Object ${id} unchanged. Ignore`);
503
+ }
504
+ return;
505
+ }
506
+ // relogTimeout
507
+ if (this.sqlDPs[formerAliasId] && this.sqlDPs[formerAliasId].relogTimeout) {
508
+ clearTimeout(this.sqlDPs[formerAliasId].relogTimeout);
509
+ this.sqlDPs[formerAliasId].relogTimeout = null;
510
+ }
511
+ const writeNull = !this.sqlDPs[id]?.config;
512
+ this.sqlDPs[id] = {
513
+ config: customConfig,
514
+ state: this.sqlDPs[id]?.state || null,
515
+ list: this.sqlDPs[id]?.list || [],
516
+ inFlight: this.sqlDPs[id]?.inFlight || {},
517
+ timeout: this.sqlDPs[id]?.timeout || null,
518
+ ts: this.sqlDPs[id]?.ts || null,
519
+ lastLogTime: 0,
520
+ relogTimeout: null,
521
+ realId: realId,
522
+ lastCheck: this.sqlDPs[id]?.lastCheck || Date.now() - Math.floor(Math.random() * 21600000 /* 6 hours */), // randomize lastCheck to avoid all datapoints to be checked at same timepoint
523
+ };
524
+ // changesRelogInterval
525
+ if (this.sqlDPs[id].config.changesOnly && this.sqlDPs[id].config.changesRelogInterval > 0) {
526
+ this.sqlDPs[id].relogTimeout = setTimeout((_id) => this.reLogHelper(_id), this.sqlDPs[id].config.changesRelogInterval * 500 * (1 + Math.random()), id);
527
+ }
528
+ if (writeNull && this.config.writeNulls) {
529
+ this.writeNulls(id);
530
+ }
531
+ this.log.info(`enabled logging of ${id}, Alias=${id !== realId}, WriteNulls=${writeNull}`);
532
+ }
533
+ setConnected(isConnected) {
534
+ if (this.sqlConnected !== isConnected) {
535
+ this.sqlConnected = isConnected;
536
+ void this.setState('info.connection', this.sqlConnected, true);
537
+ }
538
+ }
539
+ connect(callback) {
540
+ if (this.reconnectTimeout) {
541
+ clearTimeout(this.reconnectTimeout);
542
+ this.reconnectTimeout = null;
543
+ }
544
+ if (!this.clientPool) {
545
+ this.setConnected(false);
546
+ let sqLiteOptions;
547
+ let msSQLOptions;
548
+ let mySQLOptions;
549
+ let postgreSQLOptions;
550
+ const poolOptions = {
551
+ max_idle: this.config.dbtype === 'sqlite' ? 1 : 2,
552
+ };
553
+ if (this.config.maxConnections) {
554
+ poolOptions.max_active = this.config.maxConnections + 1; // we use our own Pool limiter logic, so let library have one more to not block us too early
555
+ poolOptions.max_wait = 10000; // hard code for now
556
+ poolOptions.when_exhausted = 'block';
557
+ }
558
+ if (!this.config.dbtype) {
559
+ return this.log.error('DB Type is not defined!');
560
+ }
561
+ if (!clients[this.config.dbtype]) {
562
+ return this.log.error(`Unknown type "${this.config.dbtype}"`);
563
+ }
564
+ if (this.config.dbtype === 'postgresql') {
565
+ postgreSQLOptions = {
566
+ host: this.config.host,
567
+ user: this.config.user || '',
568
+ password: this.config.password || '',
569
+ port: this.config.port || undefined,
570
+ database: 'postgres',
571
+ ssl: this.config.encrypt
572
+ ? {
573
+ rejectUnauthorized: !!this.config.rejectUnauthorized,
574
+ }
575
+ : undefined,
576
+ };
577
+ }
578
+ else if (this.config.dbtype === 'mssql') {
579
+ msSQLOptions = {
580
+ server: this.config.host, // needed for MSSQL
581
+ user: this.config.user || '',
582
+ password: this.config.password || '',
583
+ port: this.config.port || undefined,
584
+ options: {
585
+ encrypt: !!this.config.encrypt,
586
+ trustServerCertificate: !this.config.rejectUnauthorized,
587
+ },
588
+ };
589
+ }
590
+ else if (this.config.dbtype === 'mysql') {
591
+ mySQLOptions = {
592
+ host: this.config.host, // needed for PostgreSQL , MySQL
593
+ user: this.config.user || '',
594
+ password: this.config.password || '',
595
+ port: this.config.port || undefined,
596
+ ssl: this.config.encrypt
597
+ ? {
598
+ rejectUnauthorized: !!this.config.rejectUnauthorized,
599
+ }
600
+ : undefined,
601
+ };
602
+ }
603
+ else if (this.config.dbtype === 'sqlite') {
604
+ sqLiteOptions = { fileName: this.getSqlLiteDir(this.config.fileName) };
605
+ }
606
+ if (this.config.dbtype === 'postgresql' && !this.postgresDbCreated && postgreSQLOptions) {
607
+ // special solution for postgres. Connect first to Db "postgres", create new DB "iobroker" and then connect to "iobroker" DB.
608
+ // connect first to DB postgres and create iobroker DB
609
+ this.log.info(`Postgres connection options: ${JSON.stringify(postgreSQLOptions).replace(postgreSQLOptions.password || '******', '****')}`);
610
+ const _client = new postgresql_client_1.PostgreSQLClient(postgreSQLOptions);
611
+ _client.on?.('error', (err) => this.log.warn(`SQL client error: ${err}`));
612
+ return _client.connect((err) => {
613
+ if (err) {
614
+ this.log.error(err.toString());
615
+ if (this.reconnectTimeout) {
616
+ clearTimeout(this.reconnectTimeout);
617
+ }
618
+ this.reconnectTimeout = setTimeout(() => {
619
+ this.reconnectTimeout = null;
620
+ this.connect(callback);
621
+ }, 30000);
622
+ return;
623
+ }
624
+ if (this.config.doNotCreateDatabase) {
625
+ _client.disconnect();
626
+ this.postgresDbCreated = true;
627
+ this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
628
+ this.reconnectTimeout = setTimeout(() => {
629
+ this.reconnectTimeout = null;
630
+ this.connect(callback);
631
+ }, 100);
632
+ }
633
+ else {
634
+ _client.execute(`CREATE DATABASE ${this.config.dbname};`, (err) => {
635
+ _client.disconnect();
636
+ const typedError = err;
637
+ if (typedError && typedError.code !== '42P04') {
638
+ // if error not about yet exists
639
+ this.postgresDbCreated = false;
640
+ this.log.error(JSON.stringify(typedError));
641
+ this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
642
+ this.reconnectTimeout = setTimeout(() => {
643
+ this.reconnectTimeout = null;
644
+ this.connect(callback);
645
+ }, 30000);
646
+ }
647
+ else {
648
+ // remember that DB is created
649
+ this.postgresDbCreated = true;
650
+ this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
651
+ this.reconnectTimeout = setTimeout(() => {
652
+ this.reconnectTimeout = null;
653
+ this.connect(callback);
654
+ }, 100);
655
+ }
656
+ });
657
+ }
658
+ });
659
+ }
660
+ if (this.config.dbtype === 'postgresql' && postgreSQLOptions) {
661
+ postgreSQLOptions.database = this.config.dbname;
662
+ }
663
+ try {
664
+ if (this.config.dbtype === 'mssql' && msSQLOptions) {
665
+ this.clientPool = new mssql_client_1.MSSQLClientPool(poolOptions, msSQLOptions);
666
+ }
667
+ else if (this.config.dbtype === 'mysql' && mySQLOptions) {
668
+ this.clientPool = new mysql_client_1.MySQL2ClientPool(poolOptions, mySQLOptions);
669
+ }
670
+ else if (this.config.dbtype === 'sqlite' && sqLiteOptions) {
671
+ this.clientPool = new sqlite3_client_1.SQLite3ClientPool(poolOptions, sqLiteOptions);
672
+ }
673
+ else if (this.config.dbtype === 'postgresql' && postgreSQLOptions) {
674
+ this.clientPool = new postgresql_client_1.PostgreSQLClientPool(poolOptions, postgreSQLOptions);
675
+ }
676
+ else {
677
+ throw new Error('DB connection options not defined');
678
+ }
679
+ return this.clientPool.open(poolOptions, (err) => {
680
+ this.activeConnections = 0;
681
+ if (err) {
682
+ this.clientPool = null;
683
+ this.setConnected(false);
684
+ // JSON.stringify(Error) is "{}" and would swallow the message
685
+ this.log.error(err.message || err.toString());
686
+ this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
687
+ this.reconnectTimeout = setTimeout(() => {
688
+ this.reconnectTimeout = null;
689
+ this.connect(callback);
690
+ }, 30000);
691
+ }
692
+ else {
693
+ if (this.reconnectTimeout) {
694
+ clearTimeout(this.reconnectTimeout);
695
+ }
696
+ setImmediate(() => this.connect(callback));
697
+ }
698
+ });
699
+ }
700
+ catch (ex) {
701
+ this.log.error(ex.toString());
702
+ this.log.error(ex.stack);
703
+ this.clientPool = null;
704
+ this.activeConnections = 0;
705
+ this.setConnected(false);
706
+ this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
707
+ this.reconnectTimeout = setTimeout(() => {
708
+ this.reconnectTimeout = null;
709
+ this.connect(callback);
710
+ }, 30000);
711
+ return;
712
+ }
713
+ }
714
+ this.allScripts(this.sqlFuncs.init(this.config.dbname, this.config.doNotCreateDatabase), 0, err => {
715
+ if (err) {
716
+ //this.log.error(err);
717
+ this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
718
+ this.reconnectTimeout = setTimeout(() => {
719
+ this.reconnectTimeout = null;
720
+ this.connect(callback);
721
+ }, 30000);
722
+ }
723
+ else {
724
+ this.log.info(`Connected to ${this.config.dbtype}`);
725
+ // read all DB IDs and all FROM ids
726
+ this.getAllIds(() => this.getAllFroms(callback));
727
+ }
728
+ });
729
+ }
730
+ // Find sqlite data directory
731
+ getSqlLiteDir(fileName) {
732
+ fileName ||= 'sqlite.db';
733
+ fileName = fileName.replace(/\\/g, '/');
734
+ if (fileName[0] === '/' || fileName.match(/^\w:\//)) {
735
+ return fileName;
736
+ }
737
+ // normally /opt/iobroker/node_modules/iobroker.js-controller
738
+ // but can be /example/ioBroker.js-controller
739
+ const config = (0, node_path_1.join)((0, adapter_core_1.getAbsoluteDefaultDataDir)(), 'sqlite');
740
+ // create sqlite directory
741
+ if (!(0, node_fs_1.existsSync)(config)) {
742
+ (0, node_fs_1.mkdirSync)(config);
743
+ }
744
+ return (0, node_path_1.normalize)((0, node_path_1.join)(config, fileName));
745
+ }
746
+ async testConnection(msg) {
747
+ if (!msg?.message?.config) {
748
+ if (msg.callback) {
749
+ this.sendTo(msg.from, msg.command, { error: 'invalid config' }, msg.callback);
750
+ }
751
+ return;
752
+ }
753
+ let sqLiteOptions;
754
+ let msSQLOptions;
755
+ let mySQLOptions;
756
+ let postgreSQLOptions;
757
+ const config = msg.message.config;
758
+ config.port = parseInt(config.port, 10) || 0;
759
+ if (config.dockerMysql?.enabled) {
760
+ // The container is started by the docker plugin; only align the connection settings
761
+ this.applyDockerMysqlConfig(config);
762
+ }
763
+ if (config.dbtype === 'postgresql') {
764
+ postgreSQLOptions = {
765
+ host: config.host,
766
+ user: config.user || '',
767
+ password: config.password || '',
768
+ port: config.port || undefined,
769
+ database: 'postgres',
770
+ ssl: config.encrypt
771
+ ? {
772
+ rejectUnauthorized: !!config.rejectUnauthorized,
773
+ }
774
+ : undefined,
775
+ };
776
+ }
777
+ else if (config.dbtype === 'mssql') {
778
+ msSQLOptions = {
779
+ server: config.host, // needed for MSSQL
780
+ user: config.user || '',
781
+ password: config.password || '',
782
+ port: config.port || undefined,
783
+ options: {
784
+ encrypt: !!config.encrypt,
785
+ trustServerCertificate: !config.rejectUnauthorized,
786
+ },
787
+ };
788
+ }
789
+ else if (config.dbtype === 'mysql') {
790
+ mySQLOptions = {
791
+ host: config.host, // needed for PostgreSQL , MySQL
792
+ user: config.user || '',
793
+ password: config.password || '',
794
+ port: config.port || undefined,
795
+ ssl: config.encrypt
796
+ ? {
797
+ rejectUnauthorized: !!config.rejectUnauthorized,
798
+ }
799
+ : undefined,
800
+ };
801
+ }
802
+ else if (config.dbtype === 'sqlite') {
803
+ sqLiteOptions = { fileName: this.getSqlLiteDir(config.fileName) };
804
+ }
805
+ try {
806
+ let client;
807
+ if (config.dbtype === 'postgresql' && postgreSQLOptions) {
808
+ client = new postgresql_client_1.PostgreSQLClient(postgreSQLOptions);
809
+ }
810
+ else if (config.dbtype === 'mssql' && msSQLOptions) {
811
+ client = new mssql_client_1.MSSQLClient(msSQLOptions);
812
+ }
813
+ else if (config.dbtype === 'mysql' && mySQLOptions) {
814
+ client = new mysql_client_1.MySQL2Client(mySQLOptions);
815
+ }
816
+ else if (config.dbtype === 'sqlite' && sqLiteOptions) {
817
+ client = new sqlite3_client_1.SQLite3Client(sqLiteOptions);
818
+ }
819
+ else {
820
+ this.sendTo(msg.from, msg.command, { error: 'Unknown DB type' }, msg.callback);
821
+ return;
822
+ }
823
+ client.on?.('error', (err) => this.log.warn(`SQL client error: ${err}`));
824
+ this.testConnectTimeout = setTimeout(() => {
825
+ this.testConnectTimeout = null;
826
+ this.sendTo(msg.from, msg.command, { error: 'connect timeout' }, msg.callback);
827
+ }, 5000);
828
+ const err = await new Promise(resolve => client.connect((err) => {
829
+ if (err) {
830
+ if (this.testConnectTimeout) {
831
+ clearTimeout(this.testConnectTimeout);
832
+ this.testConnectTimeout = null;
833
+ }
834
+ this.sendTo(msg.from, msg.command, { error: `${err.code} ${err.toString()}` }, msg.callback);
835
+ return;
836
+ }
837
+ client.execute('SELECT 2 + 3 AS x', (err /* , rows, fields */) => {
838
+ client.disconnect();
839
+ resolve(err);
840
+ });
841
+ }));
842
+ if (this.testConnectTimeout) {
843
+ clearTimeout(this.testConnectTimeout);
844
+ this.testConnectTimeout = null;
845
+ this.sendTo(msg.from, msg.command, { error: err?.toString() || null }, msg.callback);
846
+ return;
847
+ }
848
+ }
849
+ catch (ex) {
850
+ if (this.testConnectTimeout) {
851
+ clearTimeout(this.testConnectTimeout);
852
+ this.testConnectTimeout = null;
853
+ }
854
+ this.sendTo(msg.from, msg.command, { error: ex.toString() }, msg.callback);
855
+ }
856
+ }
857
+ destroyDB(msg) {
858
+ try {
859
+ this.allScripts(this.sqlFuncs.destroy(this.config.dbname), 0, err => {
860
+ if (err) {
861
+ this.log.error(err.toString());
862
+ this.sendTo(msg.from, msg.command, { error: err.toString() }, msg.callback);
863
+ }
864
+ else {
865
+ this.sendTo(msg.from, msg.command, { error: null, result: 'deleted' }, msg.callback);
866
+ // restart adapter
867
+ setTimeout(() => this.getForeignObject(`system.adapter.${this.namespace}`, (err, obj) => {
868
+ if (!err && obj) {
869
+ void this.setForeignObject(obj._id, obj);
870
+ }
871
+ else {
872
+ this.log.error(`Cannot read object "system.adapter.${this.namespace}": ${err || 'Config does not exist'}`);
873
+ this.stop ? void this.stop() : void this.terminate();
874
+ }
875
+ }), 2000);
876
+ }
877
+ });
878
+ }
879
+ catch (ex) {
880
+ return this.sendTo(msg.from, msg.command, { error: ex.toString() }, msg.callback);
881
+ }
882
+ }
883
+ _userQuery(msg, callback) {
884
+ try {
885
+ if (typeof msg.message !== 'string' || !msg.message.length) {
886
+ throw new Error('No query provided');
887
+ }
888
+ this.log.debug(msg.message);
889
+ this.borrowClientFromPool((err, client) => {
890
+ if (err || !client) {
891
+ this.sendTo(msg.from, msg.command, { error: err?.toString() || 'No client' }, msg.callback);
892
+ this.returnClientToPool(client);
893
+ callback?.();
894
+ }
895
+ else {
896
+ client.execute(msg.message, (err, rows /* , fields */) => {
897
+ this.returnClientToPool(client);
898
+ //convert ts for postgresql and ms sqlserver
899
+ if (!err && rows?.[0] && typeof rows[0].ts === 'string') {
900
+ for (let i = 0; i < rows.length; i++) {
901
+ rows[i].ts = parseInt(rows[i].ts, 10);
902
+ }
903
+ }
904
+ this.sendTo(msg.from, msg.command, { error: err ? err.toString() : null, result: rows }, msg.callback);
905
+ callback?.();
906
+ });
907
+ }
908
+ });
909
+ }
910
+ catch (err) {
911
+ this.sendTo(msg.from, msg.command, { error: err.toString() }, msg.callback);
912
+ callback?.();
913
+ }
914
+ }
915
+ // execute custom query
916
+ query(msg) {
917
+ if (!this.multiRequests) {
918
+ if (this.tasks.length > MAX_TASKS) {
919
+ const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
920
+ this.log.error(error);
921
+ this.sendTo(msg.from, msg.command, { error }, msg.callback);
922
+ }
923
+ else {
924
+ this.tasks.push({ operation: 'userQuery', msg });
925
+ if (this.tasks.length === 1) {
926
+ this.processTasks();
927
+ }
928
+ }
929
+ }
930
+ else {
931
+ this._userQuery(msg);
932
+ }
933
+ }
934
+ // one script
935
+ oneScript(script, cb) {
936
+ try {
937
+ this.borrowClientFromPool((err, client) => {
938
+ if (err || !client) {
939
+ this.clientPool?.close();
940
+ this.activeConnections = 0;
941
+ this.clientPool = null;
942
+ this.setConnected(false);
943
+ this.log.error(err?.toString() || 'No database connection');
944
+ return cb?.(err || new Error('No database connection'));
945
+ }
946
+ this.log.debug(script);
947
+ client.execute(script, (err) => {
948
+ this.log.debug(`Response: ${JSON.stringify(err)}`);
949
+ if (err) {
950
+ const typedError = err;
951
+ // Database 'iobroker' already exists. Choose a different database name.
952
+ if (typedError.number === 1801 ||
953
+ // There is already an object named 'sources' in the database.
954
+ typedError.number === 2714) {
955
+ // do nothing
956
+ err = null;
957
+ }
958
+ else if (typedError.message?.match(/^SQLITE_ERROR: table [\w_]+ already exists$/)) {
959
+ // do nothing
960
+ err = null;
961
+ }
962
+ else if (typedError.errno == 1007 || typedError.errno == 1050) {
963
+ // if a database exists or table exists,
964
+ // do nothing
965
+ err = null;
966
+ }
967
+ else if (typedError.code === '42P04') {
968
+ // if a database exists or table exists,
969
+ // do nothing
970
+ err = null;
971
+ }
972
+ else if (typedError.code === '42P07') {
973
+ const match = script.match(/CREATE\s+TABLE\s+(\w*)\s+\(/);
974
+ if (match) {
975
+ this.log.debug(`OK. Table "${match[1]}" yet exists`);
976
+ err = null;
977
+ }
978
+ else {
979
+ this.log.error(script);
980
+ this.log.error(err.toString());
981
+ }
982
+ }
983
+ else if (script.startsWith('CREATE INDEX')) {
984
+ this.log.info('Ignore Error on Create index. You might want to create the index yourself!');
985
+ this.log.info(script);
986
+ this.log.info(`${typedError.code}: ${err}`);
987
+ err = null;
988
+ }
989
+ else {
990
+ this.log.error(script);
991
+ this.log.error(err.toString());
992
+ }
993
+ }
994
+ this.returnClientToPool(client);
995
+ cb?.(err);
996
+ });
997
+ });
998
+ }
999
+ catch (ex) {
1000
+ this.log.error(ex);
1001
+ cb?.(ex);
1002
+ }
1003
+ }
1004
+ // all scripts
1005
+ allScripts(scripts, index, cb) {
1006
+ index ||= 0;
1007
+ if (scripts && index < scripts.length) {
1008
+ this.oneScript(scripts[index], err => {
1009
+ if (err) {
1010
+ cb?.(err);
1011
+ }
1012
+ else {
1013
+ this.allScripts(scripts, index + 1, cb);
1014
+ }
1015
+ });
1016
+ }
1017
+ else {
1018
+ cb?.();
1019
+ }
1020
+ }
1021
+ finish(callback) {
1022
+ let count = 0;
1023
+ const now = Date.now();
1024
+ const allFinished = () => {
1025
+ if (this.clientPool) {
1026
+ this.clientPool.close();
1027
+ this.activeConnections = 0;
1028
+ this.clientPool = null;
1029
+ this.setConnected(false);
1030
+ }
1031
+ if (typeof this.finished === 'object') {
1032
+ setTimeout((cb) => {
1033
+ for (let f = 0; f < cb.length; f++) {
1034
+ typeof cb[f] === 'function' && cb[f]();
1035
+ }
1036
+ }, 500, this.finished);
1037
+ this.finished = true;
1038
+ }
1039
+ };
1040
+ const finishId = (id) => {
1041
+ if (!this.sqlDPs[id]) {
1042
+ return;
1043
+ }
1044
+ if (this.sqlDPs[id].relogTimeout) {
1045
+ clearTimeout(this.sqlDPs[id].relogTimeout);
1046
+ this.sqlDPs[id].relogTimeout = null;
1047
+ }
1048
+ if (this.sqlDPs[id].timeout) {
1049
+ clearTimeout(this.sqlDPs[id].timeout);
1050
+ this.sqlDPs[id].timeout = null;
1051
+ }
1052
+ const state = this.sqlDPs[id].state ? { ...this.sqlDPs[id].state } : null;
1053
+ if (this.sqlDPs[id].skipped &&
1054
+ !(this.sqlDPs[id].config && this.sqlDPs[id].config.disableSkippedValueLogging)) {
1055
+ count++;
1056
+ this.pushValueIntoDB(id, this.sqlDPs[id].skipped, false, true, () => {
1057
+ if (!--count) {
1058
+ this.pushValuesIntoDB(id, this.sqlDPs[id].list, () => {
1059
+ allFinished();
1060
+ });
1061
+ }
1062
+ });
1063
+ this.sqlDPs[id].skipped = null;
1064
+ }
1065
+ const nullValue = {
1066
+ ack: true,
1067
+ val: null,
1068
+ ts: now,
1069
+ lc: now,
1070
+ q: 0x40,
1071
+ from: `system.adapter.${this.namespace}`,
1072
+ };
1073
+ if (this.sqlDPs[id].config && this.config.writeNulls) {
1074
+ if (this.sqlDPs[id].config.changesOnly && state && state.val !== null) {
1075
+ count++;
1076
+ ((_id, _state, _nullValue) => {
1077
+ _state.ts = now;
1078
+ _state.from = `system.adapter.${this.namespace}`;
1079
+ nullValue.ts += 4;
1080
+ nullValue.lc += 4; // because of MS SQL
1081
+ this.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
1082
+ this.pushValueIntoDB(_id, _state, false, true, () => {
1083
+ // terminate values with null to indicate adapter stop. timestamp + 1
1084
+ this.log.debug(`Write 2/2 "null" _id: ${_id}`);
1085
+ this.pushValueIntoDB(_id, _nullValue, false, true, () => {
1086
+ if (!--count) {
1087
+ this.pushValuesIntoDB(id, this.sqlDPs[id].list, () => {
1088
+ allFinished();
1089
+ });
1090
+ }
1091
+ });
1092
+ });
1093
+ })(id, state, nullValue);
1094
+ }
1095
+ else {
1096
+ // terminate values with null to indicate adapter stop. timestamp + 1
1097
+ count++;
1098
+ this.log.debug(`Write 0 NULL _id: ${id}`);
1099
+ this.pushValueIntoDB(id, nullValue, false, true, () => {
1100
+ if (!--count) {
1101
+ this.pushValuesIntoDB(id, this.sqlDPs[id].list, () => {
1102
+ allFinished();
1103
+ });
1104
+ }
1105
+ });
1106
+ }
1107
+ }
1108
+ };
1109
+ if (!this.subscribeAll) {
1110
+ for (const _id in this.sqlDPs) {
1111
+ if (Object.prototype.hasOwnProperty.call(this.sqlDPs, _id) &&
1112
+ Object.prototype.hasOwnProperty.call(this.sqlDPs, this.sqlDPs[_id].realId)) {
1113
+ this.unsubscribeForeignStates(this.sqlDPs[_id].realId);
1114
+ }
1115
+ }
1116
+ }
1117
+ else {
1118
+ this.subscribeAll = false;
1119
+ this.unsubscribeForeignStates('*');
1120
+ }
1121
+ if (this.reconnectTimeout) {
1122
+ clearTimeout(this.reconnectTimeout);
1123
+ this.reconnectTimeout = null;
1124
+ }
1125
+ if (this.testConnectTimeout) {
1126
+ clearTimeout(this.testConnectTimeout);
1127
+ this.testConnectTimeout = null;
1128
+ }
1129
+ if (this.dpOverviewTimeout) {
1130
+ clearTimeout(this.dpOverviewTimeout);
1131
+ this.dpOverviewTimeout = null;
1132
+ }
1133
+ if (this.bufferChecker) {
1134
+ clearInterval(this.bufferChecker);
1135
+ this.bufferChecker = null;
1136
+ }
1137
+ if (this.finished) {
1138
+ if (callback) {
1139
+ if (this.finished === true) {
1140
+ callback();
1141
+ }
1142
+ else {
1143
+ this.finished.push(callback);
1144
+ }
1145
+ }
1146
+ return;
1147
+ }
1148
+ this.finished = [callback];
1149
+ let dpcount = 0;
1150
+ let delay = 0;
1151
+ for (const id in this.sqlDPs) {
1152
+ if (!Object.prototype.hasOwnProperty.call(this.sqlDPs, id)) {
1153
+ continue;
1154
+ }
1155
+ dpcount++;
1156
+ delay += dpcount % 50 === 0 ? 1000 : 0;
1157
+ setTimeout(finishId, delay, id);
1158
+ }
1159
+ if (!dpcount && callback) {
1160
+ if (this.clientPool) {
1161
+ this.clientPool.close();
1162
+ this.activeConnections = 0;
1163
+ this.clientPool = null;
1164
+ this.setConnected(false);
1165
+ }
1166
+ callback();
1167
+ }
1168
+ }
1169
+ processMessage(msg) {
1170
+ if (msg.command === 'features') {
1171
+ this.sendTo(msg.from, msg.command, { supportedFeatures: ['update', 'delete', 'deleteRange', 'deleteAll', 'storeState'] }, msg.callback);
1172
+ }
1173
+ else if (msg.command === 'getHistory') {
1174
+ this.getHistorySql(msg);
1175
+ }
1176
+ else if (msg.command === 'getCounter') {
1177
+ this.getCounterDiff(msg);
1178
+ }
1179
+ else if (msg.command === 'test') {
1180
+ void this.testConnection(msg);
1181
+ }
1182
+ else if (msg.command === 'destroy') {
1183
+ this.destroyDB(msg);
1184
+ }
1185
+ else if (msg.command === 'query') {
1186
+ this.query(msg);
1187
+ }
1188
+ else if (msg.command === 'update') {
1189
+ this.updateState(msg);
1190
+ }
1191
+ else if (msg.command === 'delete') {
1192
+ this.deleteHistoryEntry(msg);
1193
+ }
1194
+ else if (msg.command === 'deleteAll') {
1195
+ this.deleteStateAll(msg);
1196
+ }
1197
+ else if (msg.command === 'deleteRange') {
1198
+ this.deleteHistoryEntry(msg);
1199
+ }
1200
+ else if (msg.command === 'storeState') {
1201
+ this.storeState(msg).catch(e => this.log.error(`Cannot store state: ${e}`));
1202
+ }
1203
+ else if (msg.command === 'getDpOverview') {
1204
+ this.getDpOverview(msg);
1205
+ }
1206
+ else if (msg.command === 'enableHistory') {
1207
+ this.enableHistory(msg);
1208
+ }
1209
+ else if (msg.command === 'disableHistory') {
1210
+ this.disableHistory(msg);
1211
+ }
1212
+ else if (msg.command === 'getEnabledDPs') {
1213
+ this.getEnabledDPs(msg);
1214
+ }
1215
+ else if (msg.command === 'stopInstance') {
1216
+ this.finish(() => {
1217
+ if (msg.callback) {
1218
+ this.sendTo(msg.from, msg.command, 'stopped', msg.callback);
1219
+ setTimeout(() => (this.stop ? this.stop() : this.terminate?.()), 200);
1220
+ }
1221
+ });
1222
+ }
1223
+ }
1224
+ processStartValues(callback) {
1225
+ if (this.tasksStart?.length) {
1226
+ const task = this.tasksStart.shift();
1227
+ const sqlDP = this.sqlDPs[task.id];
1228
+ if (sqlDP.config.changesOnly) {
1229
+ void this.getForeignState(sqlDP.realId, (err, state) => {
1230
+ const now = task.now || Date.now();
1231
+ this.pushHistory(task.id, {
1232
+ val: null,
1233
+ ts: state ? now - 4 : now, // 4 is because of MS SQL
1234
+ lc: state ? now - 4 : now, // 4 is because of MS SQL
1235
+ ack: true,
1236
+ q: 0x40,
1237
+ from: `system.adapter.${this.namespace}`,
1238
+ });
1239
+ if (state) {
1240
+ state.ts = now;
1241
+ state.lc = now;
1242
+ state.from = `system.adapter.${this.namespace}`;
1243
+ this.pushHistory(task.id, state);
1244
+ }
1245
+ setImmediate(() => this.processStartValues());
1246
+ });
1247
+ }
1248
+ else {
1249
+ const now = Date.now();
1250
+ this.pushHistory(task.id, {
1251
+ val: null,
1252
+ ts: task.now || now,
1253
+ lc: task.now || now,
1254
+ ack: true,
1255
+ q: 0x40,
1256
+ from: `system.adapter.${this.namespace}`,
1257
+ });
1258
+ setImmediate(() => this.processStartValues());
1259
+ }
1260
+ if (sqlDP.config?.changesOnly && sqlDP.config.changesRelogInterval > 0) {
1261
+ if (sqlDP.relogTimeout) {
1262
+ clearTimeout(sqlDP.relogTimeout);
1263
+ }
1264
+ sqlDP.relogTimeout = setTimeout((id) => this.reLogHelper(id), sqlDP.config.changesRelogInterval * 500 * Math.random() + sqlDP.config.changesRelogInterval * 500, task.id);
1265
+ }
1266
+ }
1267
+ else {
1268
+ callback && callback();
1269
+ }
1270
+ }
1271
+ writeNulls(id, now) {
1272
+ if (!id) {
1273
+ now = Date.now();
1274
+ Object.keys(this.sqlDPs)
1275
+ .filter(_id => this.sqlDPs[_id] && this.sqlDPs[_id].config)
1276
+ .forEach(_id => this.writeNulls(_id, now));
1277
+ }
1278
+ else {
1279
+ now ||= Date.now();
1280
+ this.tasksStart.push({ id, now });
1281
+ if (this.tasksStart.length === 1 && this.sqlConnected) {
1282
+ this.processStartValues();
1283
+ }
1284
+ }
1285
+ }
1286
+ pushHistory(id, state, timerRelog) {
1287
+ timerRelog ||= false;
1288
+ // Push into DB
1289
+ if (this.sqlDPs[id]) {
1290
+ const settings = this.sqlDPs[id].config;
1291
+ if (!settings || !state) {
1292
+ return;
1293
+ }
1294
+ if (state && state.val === undefined) {
1295
+ return this.log.warn(`state value undefined received for ${id} which is not allowed. Ignoring.`);
1296
+ }
1297
+ if (typeof state.val === 'string' && settings.storageType !== 'String') {
1298
+ if (isFinite(state.val)) {
1299
+ state.val = parseFloat(state.val);
1300
+ }
1301
+ }
1302
+ if (settings.enableDebugLogs) {
1303
+ this.log.debug(`new value received for ${id} (storageType ${settings.storageType}), new-value=${state.val}, ts=${state.ts}, relog=${timerRelog}`);
1304
+ }
1305
+ let ignoreDebounce = false;
1306
+ if (!timerRelog) {
1307
+ const valueUnstable = !!this.sqlDPs[id].timeout;
1308
+ // When a debounce timer runs and the value is the same as the last one, ignore it
1309
+ if (this.sqlDPs[id].timeout && state.ts !== state.lc) {
1310
+ settings.enableDebugLogs &&
1311
+ this.log.debug(`value not changed debounce ${id}, value=${state.val}, ts=${state.ts}, debounce timer keeps running`);
1312
+ return;
1313
+ }
1314
+ else if (this.sqlDPs[id].timeout) {
1315
+ // if value changed, clear timer
1316
+ settings.enableDebugLogs &&
1317
+ this.log.debug(`value changed during debounce time ${id}, value=${state.val}, ts=${state.ts}, debounce timer restarted`);
1318
+ clearTimeout(this.sqlDPs[id].timeout);
1319
+ this.sqlDPs[id].timeout = null;
1320
+ }
1321
+ if (!valueUnstable &&
1322
+ settings.blockTime &&
1323
+ this.sqlDPs[id].state &&
1324
+ this.sqlDPs[id].state.ts + settings.blockTime > state.ts) {
1325
+ settings.enableDebugLogs &&
1326
+ this.log.debug(`value ignored blockTime ${id}, value=${state.val}, ts=${state.ts}, lastState.ts=${this.sqlDPs[id].state.ts}, blockTime=${settings.blockTime}`);
1327
+ return;
1328
+ }
1329
+ if (settings.ignoreZero && (state.val === undefined || state.val === null || state.val === 0)) {
1330
+ if (settings.enableDebugLogs) {
1331
+ this.log.debug(`value ignore because zero or null ${id}, new-value=${state.val}, ts=${state.ts}`);
1332
+ }
1333
+ return;
1334
+ }
1335
+ if (typeof settings.ignoreBelowNumber === 'number' &&
1336
+ typeof state.val === 'number' &&
1337
+ state.val < settings.ignoreBelowNumber) {
1338
+ if (settings.enableDebugLogs) {
1339
+ this.log.debug(`value ignored because below ${settings.ignoreBelowNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
1340
+ }
1341
+ return;
1342
+ }
1343
+ if (typeof settings.ignoreAboveNumber === 'number' &&
1344
+ typeof state.val === 'number' &&
1345
+ state.val > settings.ignoreAboveNumber) {
1346
+ if (settings.enableDebugLogs) {
1347
+ this.log.debug(`value ignored because above ${settings.ignoreAboveNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
1348
+ }
1349
+ return;
1350
+ }
1351
+ if (this.sqlDPs[id].state && settings.changesOnly) {
1352
+ if (!settings.changesRelogInterval) {
1353
+ if ((this.sqlDPs[id].state.val !== null || state.val === null) && state.ts !== state.lc) {
1354
+ // remember new timestamp
1355
+ if (!valueUnstable && !settings.disableSkippedValueLogging) {
1356
+ this.sqlDPs[id].skipped = state;
1357
+ }
1358
+ settings.enableDebugLogs &&
1359
+ this.log.debug(`value not changed ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1360
+ return;
1361
+ }
1362
+ }
1363
+ else if (this.sqlDPs[id].lastLogTime) {
1364
+ if ((this.sqlDPs[id].state.val !== null || state.val === null) &&
1365
+ state.ts !== state.lc &&
1366
+ Math.abs(this.sqlDPs[id].lastLogTime - state.ts) < settings.changesRelogInterval * 1000) {
1367
+ // remember new timestamp
1368
+ if (!valueUnstable && !settings.disableSkippedValueLogging) {
1369
+ this.sqlDPs[id].skipped = state;
1370
+ }
1371
+ settings.enableDebugLogs &&
1372
+ this.log.debug(`value not changed ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1373
+ return;
1374
+ }
1375
+ if (state.ts !== state.lc) {
1376
+ settings.enableDebugLogs &&
1377
+ this.log.debug(`value-not-changed-relog ${id}, value=${state.val}, lastLogTime=${this.sqlDPs[id].lastLogTime}, ts=${state.ts}`);
1378
+ ignoreDebounce = true;
1379
+ }
1380
+ }
1381
+ if (typeof state.val === 'number') {
1382
+ if (this.sqlDPs[id].state.val !== null &&
1383
+ settings.changesMinDelta &&
1384
+ Math.abs(this.sqlDPs[id].state.val - state.val) < settings.changesMinDelta) {
1385
+ if (!valueUnstable && !settings.disableSkippedValueLogging) {
1386
+ this.sqlDPs[id].skipped = state;
1387
+ }
1388
+ if (settings.enableDebugLogs) {
1389
+ this.log.debug(`Min-Delta not reached ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1390
+ }
1391
+ return;
1392
+ }
1393
+ if (settings.changesMinDelta && settings.enableDebugLogs) {
1394
+ this.log.debug(`Min-Delta reached ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1395
+ }
1396
+ }
1397
+ else if (settings.enableDebugLogs) {
1398
+ this.log.debug(`Min-Delta ignored because no number ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1399
+ }
1400
+ }
1401
+ }
1402
+ if (settings.counter && this.sqlDPs[id].state) {
1403
+ if (this.sqlDPs[id].type !== types.number) {
1404
+ this.log.error('Counter must have type "number"!');
1405
+ }
1406
+ else if (state.val === null ||
1407
+ this.sqlDPs[id].state.val === null ||
1408
+ state.val < this.sqlDPs[id].state.val) {
1409
+ // if the actual value is less then last seen counter, store both values
1410
+ this.pushValueIntoDB(id, this.sqlDPs[id].state, true);
1411
+ this.pushValueIntoDB(id, state, true);
1412
+ }
1413
+ }
1414
+ if (this.sqlDPs[id].relogTimeout) {
1415
+ clearTimeout(this.sqlDPs[id].relogTimeout);
1416
+ this.sqlDPs[id].relogTimeout = null;
1417
+ }
1418
+ if (timerRelog) {
1419
+ state = { ...state };
1420
+ state.ts = Date.now();
1421
+ state.from = `system.adapter.${this.namespace}`;
1422
+ settings.enableDebugLogs &&
1423
+ this.log.debug(`timed-relog ${id}, value=${state.val}, lastLogTime=${this.sqlDPs[id].lastLogTime}, ts=${state.ts}`);
1424
+ ignoreDebounce = true;
1425
+ }
1426
+ else {
1427
+ if (settings.changesOnly && this.sqlDPs[id].skipped) {
1428
+ settings.enableDebugLogs &&
1429
+ this.log.debug(`Skipped value logged ${id}, value=${this.sqlDPs[id].skipped.val}, ts=${this.sqlDPs[id].skipped.ts}`);
1430
+ this.pushHelper(id, this.sqlDPs[id].skipped);
1431
+ this.sqlDPs[id].skipped = null;
1432
+ }
1433
+ if (this.sqlDPs[id].state &&
1434
+ ((this.sqlDPs[id].state.val === null && state.val !== null) ||
1435
+ (this.sqlDPs[id].state.val !== null && state.val === null))) {
1436
+ ignoreDebounce = true;
1437
+ }
1438
+ else if (!this.sqlDPs[id].state && state.val === null) {
1439
+ ignoreDebounce = true;
1440
+ }
1441
+ }
1442
+ if (settings.debounceTime && !ignoreDebounce && !timerRelog) {
1443
+ // Discard changes in the debounce time to store last stable value
1444
+ this.sqlDPs[id].timeout && clearTimeout(this.sqlDPs[id].timeout);
1445
+ this.sqlDPs[id].timeout = setTimeout((id, state) => {
1446
+ if (!this.sqlDPs[id]) {
1447
+ return;
1448
+ }
1449
+ this.sqlDPs[id].timeout = null;
1450
+ this.sqlDPs[id].state = state;
1451
+ this.sqlDPs[id].lastLogTime = state.ts;
1452
+ if (settings.enableDebugLogs) {
1453
+ this.log.debug(`Value logged ${id}, value=${this.sqlDPs[id].state.val}, ts=${this.sqlDPs[id].state.ts}`);
1454
+ }
1455
+ this.pushHelper(id);
1456
+ if (settings.changesOnly && settings.changesRelogInterval > 0) {
1457
+ this.sqlDPs[id].relogTimeout = setTimeout((_id) => this.reLogHelper(_id), settings.changesRelogInterval * 1000, id);
1458
+ }
1459
+ }, settings.debounceTime, id, state);
1460
+ }
1461
+ else {
1462
+ if (!timerRelog) {
1463
+ this.sqlDPs[id].state = state;
1464
+ }
1465
+ this.sqlDPs[id].lastLogTime = state.ts;
1466
+ if (settings.enableDebugLogs) {
1467
+ this.log.debug(`Value logged ${id}, value=${this.sqlDPs[id].state?.val}, ts=${this.sqlDPs[id].state?.ts}`);
1468
+ }
1469
+ this.pushHelper(id, state);
1470
+ if (settings.changesOnly && settings.changesRelogInterval > 0) {
1471
+ this.sqlDPs[id].relogTimeout = setTimeout((_id) => this.reLogHelper(_id), settings.changesRelogInterval * 1000, id);
1472
+ }
1473
+ }
1474
+ }
1475
+ }
1476
+ reLogHelper(_id) {
1477
+ if (!this.sqlDPs[_id]) {
1478
+ this.log.info(`non-existing id ${_id}`);
1479
+ }
1480
+ else {
1481
+ this.sqlDPs[_id].relogTimeout = null;
1482
+ if (this.sqlDPs[_id].skipped) {
1483
+ this.pushHistory(_id, this.sqlDPs[_id].skipped, true);
1484
+ }
1485
+ else if (this.sqlDPs[_id].state) {
1486
+ this.pushHistory(_id, this.sqlDPs[_id].state, true);
1487
+ }
1488
+ else {
1489
+ void this.getForeignState(this.sqlDPs[_id].realId, (err, state) => {
1490
+ if (err) {
1491
+ this.log.info(`init timed Relog: can not get State for ${_id} : ${err}`);
1492
+ }
1493
+ else if (!state) {
1494
+ this.log.info(`init timed Relog: disable relog because state not set so far for ${_id}: ${JSON.stringify(state)}`);
1495
+ }
1496
+ else {
1497
+ this.log.debug(`init timed Relog: getState ${_id}: Value=${state.val}, ack=${state.ack}, ts=${state.ts}, lc=${state.lc}`);
1498
+ this.sqlDPs[_id].state = state;
1499
+ this.pushHistory(_id, this.sqlDPs[_id].state, true);
1500
+ }
1501
+ });
1502
+ }
1503
+ }
1504
+ }
1505
+ pushHelper(_id, state, cb) {
1506
+ if (!this.sqlDPs[_id] || (!this.sqlDPs[_id].state && !state)) {
1507
+ return;
1508
+ }
1509
+ state ||= this.sqlDPs[_id].state;
1510
+ const _settings = this.sqlDPs[_id].config || {};
1511
+ let val = state.val;
1512
+ if (val !== null && (typeof val === 'object' || typeof val === 'undefined')) {
1513
+ val = JSON.stringify(val);
1514
+ }
1515
+ if (val !== null && val !== undefined) {
1516
+ if (_settings.enableDebugLogs) {
1517
+ this.log.debug(`Datatype ${_id}: Currently: ${typeof val}, StorageType: ${_settings.storageType}`);
1518
+ }
1519
+ if (typeof val === 'string' && _settings.storageType !== 'String') {
1520
+ _settings.enableDebugLogs && this.log.debug(`Do Automatic Datatype conversion for ${_id}`);
1521
+ if (isFinite(val)) {
1522
+ val = parseFloat(val);
1523
+ }
1524
+ else if (val === 'true') {
1525
+ val = true;
1526
+ }
1527
+ else if (val === 'false') {
1528
+ val = false;
1529
+ }
1530
+ }
1531
+ if (_settings.storageType === 'String' && typeof val !== 'string') {
1532
+ val = val.toString();
1533
+ }
1534
+ else if (_settings.storageType === 'Number' && typeof val !== 'number') {
1535
+ if (typeof val === 'boolean') {
1536
+ val = val ? 1 : 0;
1537
+ }
1538
+ else {
1539
+ return this.log.info(`Do not store value "${val}" for ${_id} because no number`);
1540
+ }
1541
+ }
1542
+ else if (_settings.storageType === 'Boolean' && typeof val !== 'boolean') {
1543
+ val = !!val;
1544
+ }
1545
+ }
1546
+ else {
1547
+ _settings.enableDebugLogs && this.log.debug(`Datatype ${_id}: Currently: null`);
1548
+ }
1549
+ state.val = val;
1550
+ this.pushValueIntoDB(_id, state, false, false, cb);
1551
+ }
1552
+ getAllIds(cb) {
1553
+ const query = this.sqlFuncs.getIdSelect(this.config.dbname);
1554
+ this.log.debug(query);
1555
+ this.borrowClientFromPool((err, client) => {
1556
+ if (err || !client) {
1557
+ this.returnClientToPool(client);
1558
+ return cb?.(err || new Error('No client'));
1559
+ }
1560
+ client.execute(query, (err, rows) => {
1561
+ this.returnClientToPool(client);
1562
+ if (err) {
1563
+ this.log.error(`Cannot select ${query}: ${err}`);
1564
+ return cb?.(err);
1565
+ }
1566
+ if (rows?.length) {
1567
+ let id;
1568
+ for (let r = 0; r < rows.length; r++) {
1569
+ id = rows[r].name;
1570
+ this.sqlDPs[id] ||= {};
1571
+ this.sqlDPs[id].index = rows[r].id;
1572
+ if (rows[r].type !== null) {
1573
+ this.sqlDPs[id].dbType = rows[r].type;
1574
+ }
1575
+ }
1576
+ }
1577
+ cb?.();
1578
+ });
1579
+ });
1580
+ }
1581
+ getAllFroms(cb) {
1582
+ const query = this.sqlFuncs.getFromSelect(this.config.dbname);
1583
+ this.log.debug(query);
1584
+ this.borrowClientFromPool((err, client) => {
1585
+ if (err || !client) {
1586
+ this.returnClientToPool(client);
1587
+ return cb?.(err || new Error('No client'));
1588
+ }
1589
+ client.execute(query, (err, rows /* , fields */) => {
1590
+ this.returnClientToPool(client);
1591
+ if (err) {
1592
+ this.log.error(`Cannot select ${query}: ${err}`);
1593
+ return cb?.(err);
1594
+ }
1595
+ if (rows?.length) {
1596
+ for (let r = 0; r < rows.length; r++) {
1597
+ this.from[rows[r].name] = rows[r].id;
1598
+ }
1599
+ }
1600
+ cb?.();
1601
+ });
1602
+ });
1603
+ }
1604
+ _checkRetention(query, cb) {
1605
+ this.log.debug(query);
1606
+ this.borrowClientFromPool((err, client) => {
1607
+ if (err || !client) {
1608
+ this.returnClientToPool(client);
1609
+ this.log.error(err?.toString() || 'No client');
1610
+ cb?.();
1611
+ }
1612
+ else {
1613
+ client.execute(query, (err) => {
1614
+ this.returnClientToPool(client);
1615
+ if (err) {
1616
+ this.log.warn(`Retention: Cannot delete ${query}: ${err}`);
1617
+ }
1618
+ cb?.();
1619
+ });
1620
+ }
1621
+ });
1622
+ }
1623
+ checkRetention(id) {
1624
+ if (this.sqlDPs[id]?.config?.retention) {
1625
+ const dt = Date.now();
1626
+ // check every 6 hours
1627
+ if (!this.sqlDPs[id].lastCheck || dt - this.sqlDPs[id].lastCheck >= 21600000 /* 6 hours */) {
1628
+ this.sqlDPs[id].lastCheck = dt;
1629
+ if (!dbNames[this.sqlDPs[id].type]) {
1630
+ this.log.error(`No type ${this.sqlDPs[id].type} found for ${id}. Retention is not possible.`);
1631
+ }
1632
+ else {
1633
+ const query = this.sqlFuncs.retention(this.config.dbname, this.sqlDPs[id].index, dbNames[this.sqlDPs[id].type], this.sqlDPs[id].config.retention);
1634
+ if (!this.multiRequests) {
1635
+ if (this.tasks.length > MAX_TASKS) {
1636
+ return this.log.error(`Cannot queue new requests, because more than ${MAX_TASKS}`);
1637
+ }
1638
+ const start = this.tasks.length === 1;
1639
+ this.tasks.push({ operation: 'delete', query });
1640
+ // delete counters too
1641
+ if (this.sqlDPs[id] && this.sqlDPs[id].type === 0) {
1642
+ // 0 === number
1643
+ const query = this.sqlFuncs.retention(this.config.dbname, this.sqlDPs[id].index, 'ts_counter', this.sqlDPs[id].config.retention);
1644
+ this.tasks.push({ operation: 'delete', query });
1645
+ }
1646
+ start && this.processTasks();
1647
+ }
1648
+ else {
1649
+ this._checkRetention(query, () => {
1650
+ // delete counters too
1651
+ if (this.sqlDPs[id] && this.sqlDPs[id].type === 0) {
1652
+ // 0 === number
1653
+ const query = this.sqlFuncs.retention(this.config.dbname, this.sqlDPs[id].index, 'ts_counter', this.sqlDPs[id].config.retention);
1654
+ this._checkRetention(query);
1655
+ }
1656
+ });
1657
+ }
1658
+ }
1659
+ }
1660
+ }
1661
+ }
1662
+ _insertValueIntoDB(query, id, cb) {
1663
+ this.log.debug(query);
1664
+ this.borrowClientFromPool((err, client) => {
1665
+ if (err || !client) {
1666
+ this.returnClientToPool(client);
1667
+ this.log.error(err?.toString() || 'No client');
1668
+ cb?.(); // BF asked (2021.12.14): may be return here err?
1669
+ }
1670
+ else {
1671
+ client.execute(query, (err /* , rows, fields */) => {
1672
+ this.returnClientToPool(client);
1673
+ if (err) {
1674
+ this.log.error(`Cannot insert ${query}: ${err} (id: ${id})`);
1675
+ }
1676
+ else {
1677
+ this.checkRetention(id);
1678
+ }
1679
+ cb?.(); // BF asked (2021.12.14): may be return here err?
1680
+ });
1681
+ }
1682
+ });
1683
+ }
1684
+ _executeQuery(query, id, cb) {
1685
+ this.log.debug(query);
1686
+ this.borrowClientFromPool((err, client) => {
1687
+ if (err || !client) {
1688
+ this.returnClientToPool(client);
1689
+ this.log.error(err?.toString() || 'No client');
1690
+ cb?.();
1691
+ }
1692
+ else {
1693
+ client.execute(query, (err) => {
1694
+ this.returnClientToPool(client);
1695
+ if (err) {
1696
+ this.log.error(`Cannot query ${query}: ${err} (id: ${id})`);
1697
+ }
1698
+ cb?.();
1699
+ });
1700
+ }
1701
+ });
1702
+ }
1703
+ processReadTypes() {
1704
+ if (this.tasksReadType?.length) {
1705
+ const task = this.tasksReadType[0];
1706
+ if (!this.sqlDPs[task.id]) {
1707
+ this.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
1708
+ task.cb?.(new Error(`Ignore type lookup for ${task.id} because not enabled anymore`));
1709
+ task.cb = null;
1710
+ setImmediate(() => {
1711
+ this.tasksReadType.shift();
1712
+ this.processReadTypes();
1713
+ });
1714
+ return;
1715
+ }
1716
+ const sqlDP = this.sqlDPs[task.id];
1717
+ this.log.debug(`Type set in Def for ${task.id}: ${this.sqlDPs[task.id].config && this.sqlDPs[task.id].config.storageType}`);
1718
+ if (sqlDP.config?.storageType) {
1719
+ sqlDP.type = types[sqlDP.config.storageType.toLowerCase()];
1720
+ this.log.debug(`Type (from Def) for ${task.id}: ${sqlDP.type}`);
1721
+ this.processVerifyTypes(task);
1722
+ }
1723
+ else if (sqlDP.dbType !== undefined) {
1724
+ sqlDP.type = sqlDP.dbType;
1725
+ if (sqlDP.config) {
1726
+ sqlDP.config.storageType = storageTypes[sqlDP.type];
1727
+ }
1728
+ this.log.debug(`Type (from DB-Type) for ${task.id}: ${sqlDP.type}`);
1729
+ this.processVerifyTypes(task);
1730
+ }
1731
+ else {
1732
+ void this.getForeignObject(sqlDP.realId, (err, obj) => {
1733
+ if (err) {
1734
+ this.log.warn(`Error while get Object for Def for ${sqlDP.realId}: ${err}`);
1735
+ }
1736
+ if (!sqlDP) {
1737
+ this.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
1738
+ task.cb?.(new Error(`Ignore type lookup for ${task.id} because not enabled anymore`));
1739
+ task.cb = null;
1740
+ return setImmediate(() => {
1741
+ this.tasksReadType.shift();
1742
+ this.processReadTypes();
1743
+ });
1744
+ }
1745
+ else if (obj?.common?.type && types[obj.common.type.toLowerCase()] !== undefined) {
1746
+ // read type from object
1747
+ this.log.debug(`${obj.common.type.toLowerCase()} / ${types[obj.common.type.toLowerCase()]} / ${JSON.stringify(obj.common)}`);
1748
+ sqlDP.type = types[obj.common.type.toLowerCase()];
1749
+ if (sqlDP.config) {
1750
+ sqlDP.config.storageType = storageTypes[sqlDP.type];
1751
+ }
1752
+ this.log.debug(`Type (from Obj) for ${task.id}: ${sqlDP.type}`);
1753
+ this.processVerifyTypes(task);
1754
+ }
1755
+ else if (sqlDP.type === undefined) {
1756
+ void this.getForeignState(sqlDP.realId, (err, state) => {
1757
+ if (!this.sqlDPs[task.id]) {
1758
+ this.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
1759
+ task.cb?.(new Error(`Ignore type lookup for ${task.id} because not enabled anymore`));
1760
+ task.cb = null;
1761
+ return setImmediate(() => {
1762
+ this.tasksReadType.shift();
1763
+ this.processReadTypes();
1764
+ });
1765
+ }
1766
+ if (err && task.state) {
1767
+ this.log.warn(`Fallback to type of current state value because no other valid type found`);
1768
+ state = task.state;
1769
+ }
1770
+ if (state &&
1771
+ state.val !== null &&
1772
+ state.val !== undefined &&
1773
+ types[typeof state.val] !== undefined) {
1774
+ this.sqlDPs[task.id].type = types[typeof state.val];
1775
+ if (this.sqlDPs[task.id].config) {
1776
+ this.sqlDPs[task.id].config.storageType = storageTypes[this.sqlDPs[task.id].type];
1777
+ }
1778
+ }
1779
+ else {
1780
+ this.log.warn(`Store data for ${task.id} as string because no other valid type found (${state ? typeof state.val : 'state not existing'})`);
1781
+ this.sqlDPs[task.id].type = 1; // string
1782
+ }
1783
+ this.log.debug(`Type (from State) for ${task.id}: ${this.sqlDPs[task.id].type}`);
1784
+ this.processVerifyTypes(task);
1785
+ });
1786
+ }
1787
+ else {
1788
+ // all OK
1789
+ task.cb?.();
1790
+ task.cb = null;
1791
+ this.tasksReadType.shift();
1792
+ this.processReadTypes();
1793
+ }
1794
+ });
1795
+ }
1796
+ }
1797
+ }
1798
+ processVerifyTypes(task) {
1799
+ if (this.sqlDPs[task.id].index !== undefined &&
1800
+ this.sqlDPs[task.id].type !== undefined &&
1801
+ this.sqlDPs[task.id].type !== this.sqlDPs[task.id].dbType) {
1802
+ this.sqlDPs[task.id].dbType = this.sqlDPs[task.id].type;
1803
+ const query = this.sqlFuncs.getIdUpdate(this.config.dbname, this.sqlDPs[task.id].index, this.sqlDPs[task.id].type);
1804
+ this.log.debug(query);
1805
+ return this.borrowClientFromPool((err, client) => {
1806
+ if (err || !client) {
1807
+ this.returnClientToPool(client);
1808
+ this.processVerifyTypes(task);
1809
+ return;
1810
+ }
1811
+ client.execute(query, err => {
1812
+ this.returnClientToPool(client);
1813
+ if (err) {
1814
+ this.log.error(`error updating history config for ${task.id} to pin datatype: ${query}: ${err}`);
1815
+ }
1816
+ else {
1817
+ this.log.info(`changed history configuration to pin detected datatype for ${task.id}`);
1818
+ }
1819
+ this.processVerifyTypes(task);
1820
+ });
1821
+ });
1822
+ }
1823
+ task.cb?.();
1824
+ task.cb = null;
1825
+ setTimeout(() => {
1826
+ this.tasksReadType.shift();
1827
+ this.processReadTypes();
1828
+ }, 50);
1829
+ }
1830
+ prepareTaskReadDbId(id, state, isCounter, cb) {
1831
+ if (!this.sqlDPs[id]) {
1832
+ cb?.(new Error(`${id} not active any more`));
1833
+ return;
1834
+ }
1835
+ const type = this.sqlDPs[id].type;
1836
+ if (type === undefined) {
1837
+ // Can not happen anymore
1838
+ let warn;
1839
+ if (state.val === null) {
1840
+ warn = `Ignore null value for ${id} because no type defined till now.`;
1841
+ }
1842
+ else {
1843
+ warn = `Cannot store values of type "${typeof state.val}" for ${id}`;
1844
+ }
1845
+ this.log.warn(warn);
1846
+ cb?.(new Error(warn));
1847
+ return;
1848
+ }
1849
+ let tmpState;
1850
+ // get SQL id of state
1851
+ if (this.sqlDPs[id].index === undefined) {
1852
+ this.sqlDPs[id].isRunning ||= [];
1853
+ tmpState = { ...state };
1854
+ this.sqlDPs[id].isRunning.push({ id, state: tmpState, cb, isCounter });
1855
+ if (this.sqlDPs[id].isRunning.length === 1) {
1856
+ // read or create in DB
1857
+ return this.getId(id, type, (err, _id) => {
1858
+ this.log.debug(`prepareTaskCheckTypeAndDbId getId Result - isRunning length = ${this.sqlDPs[id].isRunning ? this.sqlDPs[id].isRunning.length : 'none'}`);
1859
+ if (err) {
1860
+ this.log.warn(`Cannot get index of "${_id}": ${err}`);
1861
+ this.sqlDPs[_id].isRunning?.forEach(r => r.cb?.(new Error(`Cannot get index of "${r.id}": ${err}`)));
1862
+ }
1863
+ else {
1864
+ this.sqlDPs[_id].isRunning?.forEach(r => r.cb?.());
1865
+ }
1866
+ this.sqlDPs[_id].isRunning = undefined;
1867
+ });
1868
+ }
1869
+ return;
1870
+ }
1871
+ // get from
1872
+ if (!isCounter && state.from && !this.from[state.from]) {
1873
+ this.isFromRunning[state.from] ||= [];
1874
+ tmpState = { ...state };
1875
+ const isFromRunning = this.isFromRunning[state.from];
1876
+ isFromRunning.push({ id, state: tmpState, cb });
1877
+ if (isFromRunning.length === 1) {
1878
+ // read or create in DB
1879
+ return this.getFrom(state.from, (err, from) => {
1880
+ this.log.debug(`prepareTaskCheckTypeAndDbId getFrom ${from} Result - isRunning length = ${this.isFromRunning[from] ? this.isFromRunning[from].length : 'none'}`);
1881
+ if (err) {
1882
+ this.log.warn(`Cannot get "from" for "${from}": ${err}`);
1883
+ this.isFromRunning[from]?.forEach(f => f.cb?.(new Error(`Cannot get "from" for "${from}": ${err}`)));
1884
+ }
1885
+ else {
1886
+ this.isFromRunning[from]?.forEach(f => f.cb?.());
1887
+ }
1888
+ this.isFromRunning[from] = null;
1889
+ });
1890
+ }
1891
+ return;
1892
+ }
1893
+ if (state.ts) {
1894
+ state.ts = parseInt(state.ts, 10);
1895
+ }
1896
+ try {
1897
+ if (state.val !== null && typeof state.val === 'object') {
1898
+ state.val = JSON.stringify(state.val);
1899
+ }
1900
+ }
1901
+ catch {
1902
+ const error = `Cannot convert the object value "${id}"`;
1903
+ this.log.error(error);
1904
+ cb?.(new Error(error));
1905
+ return;
1906
+ }
1907
+ cb?.();
1908
+ }
1909
+ prepareTaskCheckTypeAndDbId(id, state, isCounter, cb) {
1910
+ // check if we know about this ID
1911
+ if (!this.sqlDPs[id]) {
1912
+ if (cb) {
1913
+ setImmediate(() => cb(new Error(`Unknown ID: ${id}`)));
1914
+ }
1915
+ return;
1916
+ }
1917
+ // Check SQL connection
1918
+ if (!this.clientPool) {
1919
+ this.log.warn('No Connection to database');
1920
+ if (cb) {
1921
+ setImmediate(() => cb(new Error('No Connection to database')));
1922
+ }
1923
+ return;
1924
+ }
1925
+ this.log.debug(`prepareTaskCheckTypeAndDbId CALLED for ${id}`);
1926
+ // read type of value
1927
+ if (this.sqlDPs[id].type !== undefined) {
1928
+ this.prepareTaskReadDbId(id, state, isCounter, cb);
1929
+ }
1930
+ else {
1931
+ // read type from DB
1932
+ this.tasksReadType.push({
1933
+ id,
1934
+ state,
1935
+ cb: err => {
1936
+ if (err) {
1937
+ cb?.(err);
1938
+ }
1939
+ else {
1940
+ this.prepareTaskReadDbId(id, state, isCounter, cb);
1941
+ }
1942
+ },
1943
+ });
1944
+ if (this.tasksReadType.length === 1) {
1945
+ this.processReadTypes();
1946
+ }
1947
+ }
1948
+ }
1949
+ pushValueIntoDB(id, state, isCounter, storeInCacheOnly, cb) {
1950
+ if (!this.sqlDPs[id] || !state) {
1951
+ return cb?.();
1952
+ }
1953
+ this.log.debug(`pushValueIntoDB called for ${id} (type: ${this.sqlDPs[id].type}, ID: ${this.sqlDPs[id].index}) and state: ${JSON.stringify(state)}`);
1954
+ this.prepareTaskCheckTypeAndDbId(id, state, isCounter, (err) => {
1955
+ if (!this.sqlDPs[id]) {
1956
+ return cb?.();
1957
+ }
1958
+ this.log.debug(`pushValueIntoDB-prepareTaskCheckTypeAndDbId RESULT for ${id} (type: ${this.sqlDPs[id].type}, ID: ${this.sqlDPs[id].index}) and state: ${JSON.stringify(state)}: ${err}`);
1959
+ if (err) {
1960
+ return cb?.(err);
1961
+ }
1962
+ const type = this.sqlDPs[id].type;
1963
+ // increase timestamp if last is the same
1964
+ if (!isCounter && this.sqlDPs[id].ts && state.ts === this.sqlDPs[id].ts) {
1965
+ state.ts++;
1966
+ }
1967
+ // remember last timestamp
1968
+ this.sqlDPs[id].ts = state.ts;
1969
+ // if it was not deleted in this time
1970
+ this.sqlDPs[id].list ||= [];
1971
+ this.sqlDPs[id].list.push({
1972
+ state,
1973
+ from: state.from ? this.from[state.from] : 0,
1974
+ table: isCounter ? 'ts_counter' : dbNames[type],
1975
+ });
1976
+ const _settings = this.sqlDPs[id].config || {};
1977
+ const maxLength = _settings.maxLength !== undefined ? _settings.maxLength : this.config.maxLength || 0;
1978
+ if ((cb || (_settings && this.sqlDPs[id].list.length > maxLength)) && !storeInCacheOnly) {
1979
+ this.storeCached(id, cb);
1980
+ }
1981
+ else if (cb && storeInCacheOnly) {
1982
+ setImmediate(cb);
1983
+ }
1984
+ });
1985
+ }
1986
+ storeCached(onlyId, cb) {
1987
+ let count = 0;
1988
+ for (const id in this.sqlDPs) {
1989
+ if (!Object.prototype.hasOwnProperty.call(this.sqlDPs, id) || (onlyId !== undefined && onlyId !== id)) {
1990
+ continue;
1991
+ }
1992
+ const _settings = this.sqlDPs[id].config || {};
1993
+ if (_settings && this.sqlDPs[id]?.list?.length) {
1994
+ if (_settings.enableDebugLogs) {
1995
+ this.log.debug(`inserting ${this.sqlDPs[id].list.length} entries from ${id} to DB`);
1996
+ }
1997
+ const inFlightId = `${id}_${Date.now()}_${Math.random()}`;
1998
+ this.sqlDPs[id].inFlight ||= {};
1999
+ this.sqlDPs[id].inFlight[inFlightId] = this.sqlDPs[id].list;
2000
+ this.sqlDPs[id].list = [];
2001
+ count++;
2002
+ this.pushValuesIntoDB(id, this.sqlDPs[id].inFlight[inFlightId], (err) => {
2003
+ if (this.sqlDPs[id]?.inFlight?.[inFlightId]) {
2004
+ delete this.sqlDPs[id].inFlight[inFlightId];
2005
+ }
2006
+ if (!--count && cb) {
2007
+ cb?.(err);
2008
+ cb = null;
2009
+ }
2010
+ });
2011
+ if (onlyId !== undefined) {
2012
+ break;
2013
+ }
2014
+ }
2015
+ }
2016
+ if (!count && cb) {
2017
+ cb();
2018
+ }
2019
+ }
2020
+ pushValuesIntoDB(id, list, cb) {
2021
+ if (!list.length) {
2022
+ if (cb) {
2023
+ setImmediate(() => cb());
2024
+ }
2025
+ return;
2026
+ }
2027
+ if (!this.multiRequests) {
2028
+ if (this.tasks.length > MAX_TASKS) {
2029
+ const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2030
+ this.log.error(error);
2031
+ cb?.(new Error(error));
2032
+ }
2033
+ else {
2034
+ this.tasks.push({ operation: 'insert', index: this.sqlDPs[id].index, list, id, callback: cb });
2035
+ this.tasks.length === 1 && this.processTasks();
2036
+ }
2037
+ }
2038
+ else {
2039
+ const query = this.sqlFuncs.insert(this.config.dbname, this.sqlDPs[id].index, list);
2040
+ this._insertValueIntoDB(query, id, cb);
2041
+ }
2042
+ }
2043
+ processTasks() {
2044
+ if (this.lockTasks) {
2045
+ return this.log.debug('Tries to execute task, but last one not finished!');
2046
+ }
2047
+ this.lockTasks = true;
2048
+ if (this.tasks.length) {
2049
+ if (this.tasks[0].operation === 'query') {
2050
+ const taskQuery = this.tasks[0];
2051
+ this._executeQuery(taskQuery.query, this.tasks[0].id, () => {
2052
+ taskQuery.callback?.();
2053
+ this.tasks.shift();
2054
+ this.lockTasks = false;
2055
+ if (this.tasks.length) {
2056
+ setTimeout(() => this.processTasks(), this.config.requestInterval);
2057
+ }
2058
+ });
2059
+ }
2060
+ else if (this.tasks[0].operation === 'insert') {
2061
+ const taskInsert = this.tasks[0];
2062
+ const callbacks = [];
2063
+ if (taskInsert.callback) {
2064
+ callbacks.push(taskInsert.callback);
2065
+ }
2066
+ for (let i = 1; i < this.tasks.length; i++) {
2067
+ if (this.tasks[i].operation === 'insert') {
2068
+ const _taskInsert = this.tasks[i];
2069
+ if (taskInsert.index === _taskInsert.index) {
2070
+ taskInsert.list = taskInsert.list.concat(_taskInsert.list);
2071
+ if (_taskInsert.callback) {
2072
+ callbacks.push(_taskInsert.callback);
2073
+ }
2074
+ this.tasks.splice(i, 1);
2075
+ i--;
2076
+ }
2077
+ }
2078
+ }
2079
+ const query = this.sqlFuncs.insert(this.config.dbname, this.tasks[0].index, this.tasks[0].list);
2080
+ this._insertValueIntoDB(query, this.tasks[0].id, () => {
2081
+ callbacks.forEach(cb => cb());
2082
+ this.tasks.shift();
2083
+ this.lockTasks = false;
2084
+ if (this.tasks.length) {
2085
+ setTimeout(() => this.processTasks(), this.config.requestInterval);
2086
+ }
2087
+ });
2088
+ }
2089
+ else if (this.tasks[0].operation === 'select') {
2090
+ const taskSelect = this.tasks[0];
2091
+ this.#getDataFromDB(taskSelect.query, taskSelect.options, (err, rows) => {
2092
+ taskSelect.callback?.(err, rows);
2093
+ this.tasks.shift();
2094
+ this.lockTasks = false;
2095
+ if (this.tasks.length) {
2096
+ setTimeout(() => this.processTasks(), this.config.requestInterval);
2097
+ }
2098
+ });
2099
+ }
2100
+ else if (this.tasks[0].operation === 'userQuery') {
2101
+ const taskUserQuery = this.tasks[0];
2102
+ this._userQuery(taskUserQuery.msg, () => {
2103
+ this.tasks.shift();
2104
+ this.lockTasks = false;
2105
+ if (this.tasks.length) {
2106
+ setTimeout(() => this.processTasks(), this.config.requestInterval);
2107
+ }
2108
+ });
2109
+ }
2110
+ else if (this.tasks[0].operation === 'delete') {
2111
+ const taskDelete = this.tasks[0];
2112
+ this._checkRetention(taskDelete.query, () => {
2113
+ this.tasks.shift();
2114
+ this.lockTasks = false;
2115
+ if (this.tasks.length) {
2116
+ setTimeout(() => this.processTasks(), this.config.requestInterval);
2117
+ }
2118
+ });
2119
+ }
2120
+ else {
2121
+ this.log.error(`unknown task: ${this.tasks[0].operation}`);
2122
+ this.tasks[0].callback?.('Unknown task');
2123
+ this.tasks.shift();
2124
+ this.lockTasks = false;
2125
+ if (this.tasks.length) {
2126
+ setTimeout(() => this.processTasks(), this.config.requestInterval);
2127
+ }
2128
+ }
2129
+ }
2130
+ }
2131
+ // may be it is required to cache all the data in memory
2132
+ getId(id, type, cb) {
2133
+ let query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
2134
+ this.log.debug(query);
2135
+ this.borrowClientFromPool((err, client) => {
2136
+ if (err || !client) {
2137
+ this.returnClientToPool(client);
2138
+ cb?.(err || new Error('No client'), id);
2139
+ return;
2140
+ }
2141
+ client.execute(query, (err, rows /* , fields */) => {
2142
+ if (!this.sqlDPs[id]) {
2143
+ this.returnClientToPool(client);
2144
+ cb?.(new Error(`ID ${id} no longer active`), id);
2145
+ return;
2146
+ }
2147
+ if (err) {
2148
+ this.returnClientToPool(client);
2149
+ this.log.error(`Cannot select ${query}: ${err}`);
2150
+ cb?.(err, id);
2151
+ return;
2152
+ }
2153
+ if (!rows?.length) {
2154
+ if (type !== null && type !== undefined) {
2155
+ // insert
2156
+ query = this.sqlFuncs.getIdInsert(this.config.dbname, id, type);
2157
+ this.log.debug(query);
2158
+ client.execute(query, (err /* , rows, fields */) => {
2159
+ if (err) {
2160
+ this.returnClientToPool(client);
2161
+ this.log.error(`Cannot insert ${query}: ${err}`);
2162
+ cb?.(err, id);
2163
+ }
2164
+ else {
2165
+ query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
2166
+ this.log.debug(query);
2167
+ client.execute(query, (err, rows /* , fields */) => {
2168
+ this.returnClientToPool(client);
2169
+ if (err) {
2170
+ this.log.error(`Cannot select ${query}: ${err}`);
2171
+ cb?.(err, id);
2172
+ }
2173
+ else if (rows?.[0]) {
2174
+ this.sqlDPs[id].index = rows[0].id;
2175
+ this.sqlDPs[id].type = rows[0].type;
2176
+ cb?.(null, id);
2177
+ }
2178
+ else {
2179
+ this.log.error(`No result for select ${query}: after insert`);
2180
+ cb?.(new Error(`No result for select ${query}: after insert`), id);
2181
+ }
2182
+ });
2183
+ }
2184
+ });
2185
+ }
2186
+ else {
2187
+ this.returnClientToPool(client);
2188
+ cb?.(new Error('id not found'), id);
2189
+ }
2190
+ }
2191
+ else {
2192
+ this.sqlDPs[id].index = rows[0].id;
2193
+ if (rows[0].type === null || typeof rows[0].type !== 'number') {
2194
+ this.sqlDPs[id].type = type === null ? 1 : type; // default string
2195
+ const query = this.sqlFuncs.getIdUpdate(this.config.dbname, this.sqlDPs[id].index, this.sqlDPs[id].type);
2196
+ this.log.debug(query);
2197
+ client.execute(query, err => {
2198
+ this.returnClientToPool(client);
2199
+ if (err) {
2200
+ this.log.error(`error updating history config for ${id} to pin datatype: ${query}: ${err}`);
2201
+ }
2202
+ else {
2203
+ this.log.info(`changed history configuration to pin detected datatype for ${id}`);
2204
+ }
2205
+ cb?.(null, id);
2206
+ });
2207
+ }
2208
+ else {
2209
+ this.returnClientToPool(client);
2210
+ this.sqlDPs[id].type = rows[0].type;
2211
+ cb?.(null, id);
2212
+ }
2213
+ }
2214
+ });
2215
+ });
2216
+ }
2217
+ // may be it is required to cache all the data in memory
2218
+ getFrom(_from, cb) {
2219
+ // const sources = (this.config.dbtype !== 'postgresql' ? (this.config.dbname + '.') : '') + 'sources';
2220
+ let query = this.sqlFuncs.getFromSelect(this.config.dbname, _from);
2221
+ this.log.debug(query);
2222
+ this.borrowClientFromPool((err, client) => {
2223
+ if (err || !client) {
2224
+ this.returnClientToPool(client);
2225
+ return cb?.(err || new Error('No client'), _from);
2226
+ }
2227
+ client.execute(query, (err, rows /* , fields */) => {
2228
+ if (err) {
2229
+ this.returnClientToPool(client);
2230
+ this.log.error(`Cannot select ${query}: ${err}`);
2231
+ return cb?.(err, _from);
2232
+ }
2233
+ if (!rows?.length) {
2234
+ // insert
2235
+ query = this.sqlFuncs.getFromInsert(this.config.dbname, _from);
2236
+ this.log.debug(query);
2237
+ client.execute(query, err => {
2238
+ if (err) {
2239
+ this.returnClientToPool(client);
2240
+ this.log.error(`Cannot insert ${query}: ${err}`);
2241
+ return cb?.(err, _from);
2242
+ }
2243
+ query = this.sqlFuncs.getFromSelect(this.config.dbname, _from);
2244
+ this.log.debug(query);
2245
+ client.execute(query, (err, rows /* , fields */) => {
2246
+ this.returnClientToPool(client);
2247
+ if (err || !rows?.length) {
2248
+ this.log.error(`Cannot select ${query}: ${err}`);
2249
+ return cb?.(err, _from);
2250
+ }
2251
+ this.from[_from] = rows[0].id;
2252
+ cb?.(null, _from);
2253
+ });
2254
+ });
2255
+ }
2256
+ else {
2257
+ this.returnClientToPool(client);
2258
+ this.from[_from] = rows[0].id;
2259
+ cb?.(null, _from);
2260
+ }
2261
+ });
2262
+ });
2263
+ }
2264
+ getOneCachedData(id, options, cache) {
2265
+ if (this.sqlDPs[id]) {
2266
+ let anyInflight = false;
2267
+ let res = [];
2268
+ for (const inFlightId in this.sqlDPs[id].inFlight) {
2269
+ this.log.debug(`getOneCachedData: add ${this.sqlDPs[id].inFlight[inFlightId].length} inFlight datapoints for ${options.id}`);
2270
+ res = res.concat(this.sqlDPs[id].inFlight[inFlightId]);
2271
+ anyInflight ||= !!this.sqlDPs[id].inFlight[inFlightId].length;
2272
+ }
2273
+ res = res.concat(this.sqlDPs[id].list);
2274
+ // todo can be optimized
2275
+ if (res) {
2276
+ let iProblemCount = 0;
2277
+ let vLast = null;
2278
+ for (let i = res.length - 1; i >= 0; i--) {
2279
+ if (!res[i] || !res[i].state) {
2280
+ iProblemCount++;
2281
+ continue;
2282
+ }
2283
+ if (options.start && res[i].state.ts < options.start) {
2284
+ // add one before start
2285
+ cache.unshift({ ...res[i].state });
2286
+ break;
2287
+ }
2288
+ else if (res[i].state.ts > options.end) {
2289
+ // add one after end
2290
+ vLast = res[i].state;
2291
+ continue;
2292
+ }
2293
+ if (vLast) {
2294
+ cache.unshift({ ...vLast });
2295
+ vLast = null;
2296
+ }
2297
+ cache.unshift({ ...res[i].state });
2298
+ if (options.returnNewestEntries &&
2299
+ options.count &&
2300
+ cache.length >= options.count &&
2301
+ (options.aggregate === 'onchange' || !options.aggregate || options.aggregate === 'none')) {
2302
+ break;
2303
+ }
2304
+ }
2305
+ if (iProblemCount) {
2306
+ this.log.warn(`getOneCachedData: got null states ${iProblemCount} times for ${options.id}`);
2307
+ }
2308
+ this.log.debug(`getOneCachedData: got ${res.length} datapoints for ${options.id}`);
2309
+ return anyInflight;
2310
+ }
2311
+ this.log.debug(`getOneCachedData: datapoints for ${options.id} do not yet exist`);
2312
+ }
2313
+ return false;
2314
+ }
2315
+ getCachedData(options, callback) {
2316
+ const cache = [];
2317
+ let anyInflight = false;
2318
+ if (options.id) {
2319
+ anyInflight = this.getOneCachedData(options.id, options, cache);
2320
+ }
2321
+ else {
2322
+ for (const id in this.sqlDPs) {
2323
+ if (Object.prototype.hasOwnProperty.call(this.sqlDPs, id)) {
2324
+ anyInflight ||= this.getOneCachedData(id, options, cache);
2325
+ }
2326
+ }
2327
+ }
2328
+ let earliestTs = null;
2329
+ for (let c = 0; c < cache.length; c++) {
2330
+ if (typeof cache[c].ts === 'string') {
2331
+ cache[c].ts = parseInt(cache[c].ts, 10);
2332
+ }
2333
+ if (this.common?.loglevel === 'debug') {
2334
+ cache[c].date = new Date(cache[c].ts);
2335
+ }
2336
+ if (options.ack) {
2337
+ cache[c].ack = !!cache[c].ack;
2338
+ }
2339
+ if (typeof cache[c].val === 'number' && isFinite(cache[c].val) && options.round) {
2340
+ cache[c].val = Math.round(cache[c].val * options.round) / options.round;
2341
+ }
2342
+ if (options.id && this.sqlDPs[options.id] && this.sqlDPs[options.id].type === 2) {
2343
+ // 2 === boolean
2344
+ cache[c].val = !!cache[c].val;
2345
+ }
2346
+ if (options.addId && !cache[c].id && options.id) {
2347
+ cache[c].id = options.id;
2348
+ }
2349
+ if (earliestTs === null || cache[c].ts < earliestTs) {
2350
+ earliestTs = cache[c].ts;
2351
+ }
2352
+ }
2353
+ // options.length = cache.length;
2354
+ callback(cache, !!options.returnNewestEntries && !!options.count && cache.length >= options.count, anyInflight, earliestTs);
2355
+ }
2356
+ #getDataFromDB(query, options, callback) {
2357
+ this.log.debug(query);
2358
+ this.borrowClientFromPool((err, client) => {
2359
+ if (err || !client) {
2360
+ this.returnClientToPool(client);
2361
+ callback?.(err || new Error('No client'));
2362
+ return;
2363
+ }
2364
+ client.execute(query, (err, rows /* , fields */) => {
2365
+ this.returnClientToPool(client);
2366
+ if (!err && rows) {
2367
+ for (let c = 0; c < rows.length; c++) {
2368
+ if (typeof rows[c].ts === 'string') {
2369
+ rows[c].ts = parseInt(rows[c].ts, 10);
2370
+ }
2371
+ if (this.common?.loglevel === 'debug') {
2372
+ rows[c].date = new Date(rows[c].ts);
2373
+ }
2374
+ if (options.ack) {
2375
+ rows[c].ack = !!rows[c].ack;
2376
+ }
2377
+ if (typeof rows[c].val === 'number' && isFinite(rows[c].val) && options.round) {
2378
+ rows[c].val = Math.round(rows[c].val * options.round) / options.round;
2379
+ }
2380
+ if (options.id && this.sqlDPs[options.id] && this.sqlDPs[options.id].type === 2) {
2381
+ // 2 === boolean
2382
+ rows[c].val = !!rows[c].val;
2383
+ }
2384
+ if (options.addId && !rows[c].id && options.id) {
2385
+ rows[c].id = options.id;
2386
+ }
2387
+ }
2388
+ }
2389
+ callback?.(err, rows);
2390
+ });
2391
+ });
2392
+ }
2393
+ getDataFromDB(table, options, callback) {
2394
+ const query = this.sqlFuncs.getHistory(this.config.dbname, table, options);
2395
+ this.log.debug(query);
2396
+ if (!this.multiRequests) {
2397
+ if (this.tasks.length > MAX_TASKS) {
2398
+ this.log.error(`Cannot queue new requests, because more than ${MAX_TASKS}`);
2399
+ callback?.(new Error(`Cannot queue new requests, because more than ${MAX_TASKS}`));
2400
+ }
2401
+ else {
2402
+ this.tasks.push({ operation: 'select', query, options, callback });
2403
+ if (this.tasks.length === 1) {
2404
+ this.processTasks();
2405
+ }
2406
+ }
2407
+ }
2408
+ else {
2409
+ this.#getDataFromDB(query, options, callback);
2410
+ }
2411
+ }
2412
+ getCounterDataFromDB(options, callback) {
2413
+ const query = this.sqlFuncs.getCounterDiff(this.config.dbname, options);
2414
+ this.log.debug(query);
2415
+ if (!this.multiRequests) {
2416
+ if (this.tasks.length > MAX_TASKS) {
2417
+ const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2418
+ this.log.error(error);
2419
+ callback?.(new Error(error));
2420
+ }
2421
+ else {
2422
+ this.tasks.push({ operation: 'select', query, options, callback });
2423
+ if (this.tasks.length === 1) {
2424
+ this.processTasks();
2425
+ }
2426
+ }
2427
+ }
2428
+ else {
2429
+ this.#getDataFromDB(query, options, callback);
2430
+ }
2431
+ }
2432
+ getCounterDiff(msg) {
2433
+ const id = msg.message.id;
2434
+ const start = msg.message.options.start || 0;
2435
+ const end = msg.message.options.end || Date.now() + 5000000;
2436
+ if (!this.sqlDPs[id]) {
2437
+ this.sendTo(msg.from, msg.command, { result: [], step: null, error: 'Not enabled' }, msg.callback);
2438
+ }
2439
+ else {
2440
+ if (!this.sqlFuncs.getCounterDiff) {
2441
+ this.sendTo(msg.from, msg.command, { result: [], step: null, error: 'Counter option is not enabled for this type of SQL' }, msg.callback);
2442
+ }
2443
+ else {
2444
+ const options = { id, start, end, index: this.sqlDPs[id].index };
2445
+ this.getCounterDataFromDB(options, (err, data) => (0, aggregate_1.sendResponseCounter)(this, msg, options, err?.toString() || data || []));
2446
+ }
2447
+ }
2448
+ }
2449
+ getHistorySql(msg) {
2450
+ const startTime = Date.now();
2451
+ if (!msg.message?.options) {
2452
+ return this.sendTo(msg.from, msg.command, {
2453
+ error: 'Invalid call. No options for getHistory provided',
2454
+ }, msg.callback);
2455
+ }
2456
+ // callers send this either as a real boolean/number or as a string
2457
+ let ignoreNull;
2458
+ if (msg.message.options.ignoreNull === true || msg.message.options.ignoreNull === 'true') {
2459
+ ignoreNull = true; // include nulls and replace them with the last value
2460
+ }
2461
+ else if (msg.message.options.ignoreNull === 0 || msg.message.options.ignoreNull === '0') {
2462
+ ignoreNull = 0; // include nulls and replace them with 0
2463
+ }
2464
+ else {
2465
+ ignoreNull = false; // include nulls
2466
+ }
2467
+ const logId = (msg.message.id ? msg.message.id : 'all') + Date.now() + Math.random();
2468
+ const options = {
2469
+ id: msg.message.id === '*' ? null : msg.message.id,
2470
+ start: msg.message.options.start,
2471
+ end: msg.message.options.end || Date.now() + 5000000,
2472
+ step: parseInt(msg.message.options.step, 10) || undefined,
2473
+ count: parseInt(msg.message.options.count, 10),
2474
+ ignoreNull,
2475
+ aggregate: msg.message.options.aggregate || 'average', // One of: max, min, average, total, none, on-change
2476
+ limit: parseInt(msg.message.options.limit, 10) || parseInt(msg.message.options.count, 10) || 2000,
2477
+ from: msg.message.options.from || false,
2478
+ q: msg.message.options.q || false,
2479
+ ack: msg.message.options.ack || false,
2480
+ addId: msg.message.options.addId || false,
2481
+ sessionId: msg.message.options.sessionId,
2482
+ returnNewestEntries: msg.message.options.returnNewestEntries || false,
2483
+ percentile: msg.message.options.aggregate === 'percentile'
2484
+ ? parseInt(msg.message.options.percentile, 10) || 50
2485
+ : undefined,
2486
+ quantile: msg.message.options.aggregate === 'quantile'
2487
+ ? parseFloat(msg.message.options.quantile) || 0.5
2488
+ : undefined,
2489
+ integralUnit: msg.message.options.aggregate === 'integral'
2490
+ ? parseInt(msg.message.options.integralUnit, 10) || 60
2491
+ : undefined,
2492
+ integralInterpolation: msg.message.options.aggregate === 'integral'
2493
+ ? msg.message.options.integralInterpolation || 'none'
2494
+ : null,
2495
+ removeBorderValues: msg.message.options.removeBorderValues || false,
2496
+ // ID in database
2497
+ index: msg.message.id === '*' ? null : this.sqlDPs[msg.message.id]?.index || null,
2498
+ };
2499
+ this.log.debug(`${logId} getHistory message: ${JSON.stringify(msg.message)}`);
2500
+ if (!options.count || isNaN(options.count)) {
2501
+ if (options.aggregate === 'none' || options.aggregate === 'onchange') {
2502
+ options.count = options.limit;
2503
+ }
2504
+ else {
2505
+ options.count = 500;
2506
+ }
2507
+ }
2508
+ try {
2509
+ if (options.start && typeof options.start !== 'number') {
2510
+ options.start = new Date(options.start).getTime();
2511
+ }
2512
+ }
2513
+ catch {
2514
+ return this.sendTo(msg.from, msg.command, {
2515
+ error: `Invalid call. Start date ${JSON.stringify(options.start)} is not a valid date`,
2516
+ }, msg.callback);
2517
+ }
2518
+ try {
2519
+ if (options.end && typeof options.end !== 'number') {
2520
+ options.end = new Date(options.end).getTime();
2521
+ }
2522
+ }
2523
+ catch {
2524
+ return this.sendTo(msg.from, msg.command, {
2525
+ error: `Invalid call. End date ${JSON.stringify(options.end)} is not a valid date`,
2526
+ }, msg.callback);
2527
+ }
2528
+ if (!options.start && options.count) {
2529
+ options.returnNewestEntries = true;
2530
+ }
2531
+ if (msg.message.options.round !== null &&
2532
+ msg.message.options.round !== undefined &&
2533
+ msg.message.options.round !== '') {
2534
+ msg.message.options.round = parseInt(msg.message.options.round, 10);
2535
+ if (!isFinite(msg.message.options.round) || msg.message.options.round < 0) {
2536
+ options.round = this.config.round === null ? undefined : this.config.round;
2537
+ }
2538
+ else {
2539
+ options.round = Math.pow(10, parseInt(msg.message.options.round, 10));
2540
+ }
2541
+ }
2542
+ else {
2543
+ options.round = this.config.round === null ? undefined : this.config.round;
2544
+ }
2545
+ if (options.id && this.aliasMap[options.id]) {
2546
+ options.id = this.aliasMap[options.id];
2547
+ }
2548
+ if ((options.aggregate === 'percentile' && options.percentile < 0) || options.percentile > 100) {
2549
+ this.log.error(`Invalid percentile value: ${options.percentile}, use 50 as default`);
2550
+ options.percentile = 50;
2551
+ }
2552
+ if ((options.aggregate === 'quantile' && options.quantile < 0) || options.quantile > 1) {
2553
+ this.log.error(`Invalid quantile value: ${options.quantile}, use 0.5 as default`);
2554
+ options.quantile = 0.5;
2555
+ }
2556
+ if (options.aggregate === 'integral' &&
2557
+ (typeof options.integralUnit !== 'number' || options.integralUnit <= 0)) {
2558
+ this.log.error(`Invalid integralUnit value: ${options.integralUnit}, use 60s as default`);
2559
+ options.integralUnit = 60;
2560
+ }
2561
+ if (options.id) {
2562
+ this.sqlDPs[options.id] ||= {};
2563
+ }
2564
+ const debugLog = !!((options.id && this.sqlDPs[options.id]?.config?.enableDebugLogs) ||
2565
+ this.config.enableDebugLogs);
2566
+ if (options.start > options.end) {
2567
+ const _end = options.end;
2568
+ options.end = options.start;
2569
+ options.start = _end;
2570
+ }
2571
+ if (!options.start && !options.count) {
2572
+ options.start = Date.now() - 86400000; // - 1 day
2573
+ }
2574
+ if (debugLog) {
2575
+ this.log.debug(`${logId} getHistory options final: ${JSON.stringify(options)}`);
2576
+ }
2577
+ if (options.id && this.sqlDPs[options.id].type === undefined && this.sqlDPs[options.id].dbType !== undefined) {
2578
+ const storageType = this.sqlDPs[options.id].config?.storageType;
2579
+ if (storageType) {
2580
+ if (storageTypes.indexOf(storageType) === this.sqlDPs[options.id].dbType) {
2581
+ if (debugLog) {
2582
+ this.log.debug(`${logId} For getHistory for id ${options.id}: Type empty, use storageType dbType ${this.sqlDPs[options.id].dbType}`);
2583
+ }
2584
+ this.sqlDPs[options.id].type = this.sqlDPs[options.id].dbType;
2585
+ }
2586
+ }
2587
+ else {
2588
+ if (debugLog) {
2589
+ this.log.debug(`${logId} For getHistory for id ${options.id}: Type empty, use dbType ${this.sqlDPs[options.id].dbType}`);
2590
+ }
2591
+ this.sqlDPs[options.id].type = this.sqlDPs[options.id].dbType;
2592
+ }
2593
+ }
2594
+ if (options.id && this.sqlDPs[options.id].index === undefined) {
2595
+ // read or create in DB
2596
+ return this.getId(options.id, null, err => {
2597
+ if (err) {
2598
+ this.log.warn(`Cannot get index of "${options.id}": ${err}`);
2599
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, [], startTime);
2600
+ }
2601
+ else {
2602
+ this.getHistorySql(msg);
2603
+ }
2604
+ });
2605
+ }
2606
+ if (options.id && this.sqlDPs[options.id].type === undefined) {
2607
+ this.log.warn(`For getHistory for id "${options.id}": Type empty. Need to write data first. Index = ${this.sqlDPs[options.id].index}`);
2608
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, 'Please wait till next data record is logged and reload.', startTime);
2609
+ return;
2610
+ }
2611
+ // if specific id requested
2612
+ if (options.id) {
2613
+ const type = this.sqlDPs[options.id].type;
2614
+ options.index = this.sqlDPs[options.id].index;
2615
+ this.getCachedData(options, (cacheData, isFull, includesInFlightData, earliestTs) => {
2616
+ if (debugLog) {
2617
+ this.log.debug(`${logId} after getCachedData: length = ${cacheData.length}, isFull=${isFull}`);
2618
+ }
2619
+ // if all data read
2620
+ if (isFull &&
2621
+ cacheData.length &&
2622
+ (options.aggregate === 'onchange' || !options.aggregate || options.aggregate === 'none')) {
2623
+ cacheData.sort(sortByTs);
2624
+ if (options.count && cacheData.length > options.count && options.aggregate === 'none') {
2625
+ cacheData.splice(0, cacheData.length - options.count);
2626
+ if (debugLog) {
2627
+ this.log.debug(`${logId} cut cacheData to ${options.count} values`);
2628
+ }
2629
+ }
2630
+ this.log.debug(`${logId} Send: ${cacheData.length} values in: ${Date.now() - startTime}ms`);
2631
+ this.sendTo(msg.from, msg.command, {
2632
+ result: cacheData,
2633
+ step: null,
2634
+ error: null,
2635
+ }, msg.callback);
2636
+ }
2637
+ else {
2638
+ const origEnd = options.end;
2639
+ if (includesInFlightData && earliestTs) {
2640
+ options.end = earliestTs;
2641
+ }
2642
+ // if not all data read
2643
+ this.getDataFromDB(dbNames[type], options, (err, data) => {
2644
+ if (!err && data) {
2645
+ options.end = origEnd;
2646
+ if (options.aggregate === 'none' && options.count && options.returnNewestEntries) {
2647
+ cacheData = cacheData.reverse();
2648
+ data = cacheData.concat(data);
2649
+ }
2650
+ else {
2651
+ data = data.concat(cacheData);
2652
+ }
2653
+ if (debugLog) {
2654
+ this.log.debug(`${logId} after getDataFromDB: length = ${data.length}`);
2655
+ }
2656
+ if (options.count &&
2657
+ data.length > options.count &&
2658
+ options.aggregate === 'none' &&
2659
+ !options.returnNewestEntries) {
2660
+ if (options.start) {
2661
+ for (let i = 0; i < data.length; i++) {
2662
+ if (data[i].ts < options.start) {
2663
+ data.splice(i, 1);
2664
+ i--;
2665
+ }
2666
+ else {
2667
+ break;
2668
+ }
2669
+ }
2670
+ }
2671
+ data.splice(options.count);
2672
+ if (debugLog) {
2673
+ this.log.debug(`${logId} pre-cut data to ${options.count} oldest values`);
2674
+ }
2675
+ }
2676
+ data.sort(sortByTs);
2677
+ }
2678
+ try {
2679
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, err?.toString() || data || [], startTime, debugLog ? logId : undefined);
2680
+ }
2681
+ catch (e) {
2682
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, e.toString(), startTime);
2683
+ }
2684
+ });
2685
+ }
2686
+ });
2687
+ }
2688
+ else {
2689
+ // if all IDs requested
2690
+ let rows = [];
2691
+ let count = 0;
2692
+ this.getCachedData(options, (cacheData, isFull, includesInFlightData, earliestTs) => {
2693
+ if (isFull && cacheData.length) {
2694
+ cacheData.sort(sortByTs);
2695
+ (0, aggregate_1.sendResponse)(this, msg, '', options, cacheData, startTime, debugLog ? logId : undefined);
2696
+ }
2697
+ else {
2698
+ if (includesInFlightData && earliestTs) {
2699
+ options.end = earliestTs;
2700
+ }
2701
+ for (let db = 0; db < dbNames.length; db++) {
2702
+ count++;
2703
+ this.getDataFromDB(dbNames[db], options, (err, data) => {
2704
+ if (data) {
2705
+ rows = rows.concat(data);
2706
+ }
2707
+ if (!--count) {
2708
+ rows.sort(sortByTs);
2709
+ try {
2710
+ (0, aggregate_1.sendResponse)(this, msg, '', options, rows, startTime);
2711
+ }
2712
+ catch (e) {
2713
+ (0, aggregate_1.sendResponse)(this, msg, '', options, e.toString(), startTime);
2714
+ }
2715
+ }
2716
+ });
2717
+ }
2718
+ }
2719
+ });
2720
+ }
2721
+ }
2722
+ update(id, state, cb) {
2723
+ // first try to find the value in not yet saved data
2724
+ let found = false;
2725
+ if (this.sqlDPs[id]) {
2726
+ const res = this.sqlDPs[id].list;
2727
+ if (res) {
2728
+ for (let i = res.length - 1; i >= 0; i--) {
2729
+ if (res[i].state.ts === state.ts) {
2730
+ if (state.val !== undefined) {
2731
+ res[i].state.val = state.val;
2732
+ }
2733
+ if (state.q !== undefined && res[i].state.q !== undefined) {
2734
+ res[i].state.q = state.q;
2735
+ }
2736
+ if (state.from !== undefined && res[i].from !== undefined) {
2737
+ res[i].state.from = state.from;
2738
+ }
2739
+ if (state.ack !== undefined) {
2740
+ res[i].state.ack = state.ack;
2741
+ }
2742
+ found = true;
2743
+ break;
2744
+ }
2745
+ }
2746
+ }
2747
+ }
2748
+ if (!found) {
2749
+ this.prepareTaskCheckTypeAndDbId(id, state, false, (err) => {
2750
+ if (err) {
2751
+ return cb?.(err);
2752
+ }
2753
+ const type = this.sqlDPs[id].type;
2754
+ const query = this.sqlFuncs.update(this.config.dbname, this.sqlDPs[id].index, state, this.from[state.from], dbNames[type]);
2755
+ if (!this.multiRequests) {
2756
+ if (this.tasks.length > MAX_TASKS) {
2757
+ const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2758
+ this.log.error(error);
2759
+ cb?.(new Error(error));
2760
+ }
2761
+ else {
2762
+ this.tasks.push({ operation: 'query', query, id, callback: cb });
2763
+ this.tasks.length === 1 && this.processTasks();
2764
+ }
2765
+ }
2766
+ else {
2767
+ this._executeQuery(query, id, cb);
2768
+ }
2769
+ });
2770
+ }
2771
+ else {
2772
+ cb?.();
2773
+ }
2774
+ }
2775
+ #delete(id, state, cb) {
2776
+ // first try to find the value in not yet saved data
2777
+ let found = false;
2778
+ if (this.sqlDPs[id]) {
2779
+ const res = this.sqlDPs[id].list;
2780
+ if (res) {
2781
+ if (!state.ts && !state.start && !state.end) {
2782
+ this.sqlDPs[id].list = [];
2783
+ }
2784
+ else {
2785
+ for (let i = res.length - 1; i >= 0; i--) {
2786
+ if (state.start && state.end) {
2787
+ if (res[i].state.ts >= state.start && res[i].state.ts <= state.end) {
2788
+ res.splice(i, 1);
2789
+ }
2790
+ }
2791
+ else if (state.start) {
2792
+ if (res[i].state.ts >= state.start) {
2793
+ res.splice(i, 1);
2794
+ }
2795
+ }
2796
+ else if (state.end) {
2797
+ if (res[i].state.ts <= state.end) {
2798
+ res.splice(i, 1);
2799
+ }
2800
+ }
2801
+ else if (res[i].state.ts === state.ts) {
2802
+ res.splice(i, 1);
2803
+ found = true;
2804
+ break;
2805
+ }
2806
+ }
2807
+ }
2808
+ }
2809
+ }
2810
+ if (!found) {
2811
+ this.prepareTaskCheckTypeAndDbId(id, state, false, err => {
2812
+ if (err) {
2813
+ return cb?.(err);
2814
+ }
2815
+ const type = this.sqlDPs[id].type;
2816
+ let query;
2817
+ if (state.start && state.end) {
2818
+ query = this.sqlFuncs.deleteFromTable(this.config.dbname, dbNames[type], this.sqlDPs[id].index, state.start, state.end);
2819
+ }
2820
+ else if (state.ts) {
2821
+ query = this.sqlFuncs.deleteFromTable(this.config.dbname, dbNames[type], this.sqlDPs[id].index, state.ts);
2822
+ }
2823
+ else {
2824
+ // delete all entries for ID
2825
+ query = this.sqlFuncs.deleteFromTable(this.config.dbname, dbNames[type], this.sqlDPs[id].index);
2826
+ }
2827
+ if (!this.multiRequests) {
2828
+ if (this.tasks.length > MAX_TASKS) {
2829
+ const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2830
+ this.log.error(error);
2831
+ cb?.(new Error(error));
2832
+ }
2833
+ else {
2834
+ this.tasks.push({ operation: 'query', query, id, callback: cb });
2835
+ this.tasks.length === 1 && this.processTasks();
2836
+ }
2837
+ }
2838
+ else {
2839
+ this._executeQuery(query, id, cb);
2840
+ }
2841
+ });
2842
+ }
2843
+ else {
2844
+ cb?.();
2845
+ }
2846
+ }
2847
+ updateState(msg) {
2848
+ if (!msg.message) {
2849
+ this.log.error('updateState called with invalid data');
2850
+ return this.sendTo(msg.from, msg.command, {
2851
+ error: `Invalid call: ${JSON.stringify(msg)}`,
2852
+ }, msg.callback);
2853
+ }
2854
+ let id;
2855
+ if (Array.isArray(msg.message)) {
2856
+ this.log.debug(`updateState ${msg.message.length} items`);
2857
+ for (let i = 0; i < msg.message.length; i++) {
2858
+ id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
2859
+ if (msg.message[i].state && typeof msg.message[i].state === 'object') {
2860
+ this.update(id, msg.message[i].state);
2861
+ }
2862
+ else {
2863
+ this.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
2864
+ }
2865
+ }
2866
+ }
2867
+ else if (msg.message.state && Array.isArray(msg.message.state)) {
2868
+ this.log.debug(`updateState ${msg.message.state.length} items`);
2869
+ id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
2870
+ for (let j = 0; j < msg.message.state.length; j++) {
2871
+ if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
2872
+ this.update(id, msg.message.state[j]);
2873
+ }
2874
+ else {
2875
+ this.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
2876
+ }
2877
+ }
2878
+ }
2879
+ else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
2880
+ this.log.debug('updateState 1 item');
2881
+ id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
2882
+ return this.update(id, msg.message.state, () => this.sendTo(msg.from, msg.command, {
2883
+ success: true,
2884
+ sqlConnected: !!this.clientPool,
2885
+ }, msg.callback));
2886
+ }
2887
+ else {
2888
+ this.log.error('updateState called with invalid data');
2889
+ return this.sendTo(msg.from, msg.command, {
2890
+ error: `Invalid call: ${JSON.stringify(msg)}`,
2891
+ }, msg.callback);
2892
+ }
2893
+ this.sendTo(msg.from, msg.command, {
2894
+ success: true,
2895
+ sqlConnected: !!this.clientPool,
2896
+ }, msg.callback);
2897
+ }
2898
+ deleteHistoryEntry(msg) {
2899
+ if (!msg.message) {
2900
+ this.log.error('deleteHistoryEntry called with invalid data');
2901
+ return this.sendTo(msg.from, msg.command, {
2902
+ error: `Invalid call: ${JSON.stringify(msg)}`,
2903
+ }, msg.callback);
2904
+ }
2905
+ let id;
2906
+ if (Array.isArray(msg.message)) {
2907
+ this.log.debug(`deleteHistoryEntry ${msg.message.length} items`);
2908
+ for (let i = 0; i < msg.message.length; i++) {
2909
+ id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
2910
+ // {id: 'blabla', ts: 892}
2911
+ if (msg.message[i].ts) {
2912
+ this.#delete(id, { ts: msg.message[i].ts });
2913
+ }
2914
+ else if (msg.message[i].start) {
2915
+ if (typeof msg.message[i].start === 'string') {
2916
+ msg.message[i].start = new Date(msg.message[i].start).getTime();
2917
+ }
2918
+ if (typeof msg.message[i].end === 'string') {
2919
+ msg.message[i].end = new Date(msg.message[i].end).getTime();
2920
+ }
2921
+ this.#delete(id, { start: msg.message[i].start, end: msg.message[i].end || Date.now() });
2922
+ }
2923
+ else if (typeof msg.message[i].state === 'object' &&
2924
+ msg.message[i].state &&
2925
+ msg.message[i].state.ts) {
2926
+ this.#delete(id, { ts: msg.message[i].state.ts });
2927
+ }
2928
+ else if (typeof msg.message[i].state === 'object' &&
2929
+ msg.message[i].state &&
2930
+ msg.message[i].state.start) {
2931
+ if (typeof msg.message[i].state.start === 'string') {
2932
+ msg.message[i].state.start = new Date(msg.message[i].state.start).getTime();
2933
+ }
2934
+ if (typeof msg.message[i].state.end === 'string') {
2935
+ msg.message[i].state.end = new Date(msg.message[i].state.end).getTime();
2936
+ }
2937
+ this.#delete(id, {
2938
+ start: msg.message[i].state.start,
2939
+ end: msg.message[i].state.end || Date.now(),
2940
+ });
2941
+ }
2942
+ else {
2943
+ this.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
2944
+ }
2945
+ }
2946
+ }
2947
+ else if (msg.message.state && Array.isArray(msg.message.state)) {
2948
+ this.log.debug(`deleteHistoryEntry ${msg.message.state.length} items`);
2949
+ id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
2950
+ for (let j = 0; j < msg.message.state.length; j++) {
2951
+ if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
2952
+ if (msg.message.state[j].ts) {
2953
+ this.#delete(id, { ts: msg.message.state[j].ts });
2954
+ }
2955
+ else if (msg.message.state[j].start) {
2956
+ if (typeof msg.message.state[j].start === 'string') {
2957
+ msg.message.state[j].start = new Date(msg.message.state[j].start).getTime();
2958
+ }
2959
+ if (typeof msg.message.state[j].end === 'string') {
2960
+ msg.message.state[j].end = new Date(msg.message.state[j].end).getTime();
2961
+ }
2962
+ this.#delete(id, {
2963
+ start: msg.message.state[j].start,
2964
+ end: msg.message.state[j].end || Date.now(),
2965
+ });
2966
+ }
2967
+ }
2968
+ else if (msg.message.state[j] && typeof msg.message.state[j] === 'number') {
2969
+ this.#delete(id, { ts: msg.message.state[j] });
2970
+ }
2971
+ else {
2972
+ this.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
2973
+ }
2974
+ }
2975
+ }
2976
+ else if (msg.message.ts && Array.isArray(msg.message.ts)) {
2977
+ this.log.debug(`deleteHistoryEntry ${msg.message.ts.length} items`);
2978
+ id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
2979
+ for (let j = 0; j < msg.message.ts.length; j++) {
2980
+ if (msg.message.ts[j] && typeof msg.message.ts[j] === 'number') {
2981
+ this.#delete(id, { ts: msg.message.ts[j] });
2982
+ }
2983
+ else {
2984
+ this.log.warn(`Invalid state for ${JSON.stringify(msg.message.ts[j])}`);
2985
+ }
2986
+ }
2987
+ }
2988
+ else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
2989
+ this.log.debug('deleteHistoryEntry 1 item');
2990
+ id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
2991
+ return this.#delete(id, { ts: msg.message.state.ts }, () => this.sendTo(msg.from, msg.command, {
2992
+ success: true,
2993
+ sqlConnected: !!this.clientPool,
2994
+ }, msg.callback));
2995
+ }
2996
+ else if (msg.message.id && msg.message.ts && typeof msg.message.ts === 'number') {
2997
+ this.log.debug('deleteHistoryEntry 1 item');
2998
+ id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
2999
+ return this.#delete(id, { ts: msg.message.ts }, () => this.sendTo(msg.from, msg.command, {
3000
+ success: true,
3001
+ sqlConnected: !!this.clientPool,
3002
+ }, msg.callback));
3003
+ }
3004
+ else {
3005
+ this.log.error('deleteHistoryEntry called with invalid data');
3006
+ return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
3007
+ }
3008
+ this.sendTo(msg.from, msg.command, {
3009
+ success: true,
3010
+ sqlConnected: !!this.clientPool,
3011
+ }, msg.callback);
3012
+ }
3013
+ deleteStateAll(msg) {
3014
+ if (!msg.message) {
3015
+ this.log.error('deleteStateAll called with invalid data');
3016
+ return this.sendTo(msg.from, msg.command, {
3017
+ error: `Invalid call: ${JSON.stringify(msg)}`,
3018
+ }, msg.callback);
3019
+ }
3020
+ let id;
3021
+ if (Array.isArray(msg.message)) {
3022
+ this.log.debug(`deleteStateAll ${msg.message.length} items`);
3023
+ for (let i = 0; i < msg.message.length; i++) {
3024
+ id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
3025
+ this.#delete(id, {});
3026
+ }
3027
+ }
3028
+ else if (msg.message.id) {
3029
+ this.log.debug('deleteStateAll 1 item');
3030
+ id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3031
+ return this.#delete(id, {}, () => this.sendTo(msg.from, msg.command, {
3032
+ success: true,
3033
+ sqlConnected: !!this.clientPool,
3034
+ }, msg.callback));
3035
+ }
3036
+ else {
3037
+ this.log.error('deleteStateAll called with invalid data');
3038
+ return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
3039
+ }
3040
+ this.sendTo(msg.from, msg.command, {
3041
+ success: true,
3042
+ sqlConnected: !!this.clientPool,
3043
+ }, msg.callback);
3044
+ }
3045
+ storeStatePushData(id, state, applyRules) {
3046
+ if (!state || typeof state !== 'object') {
3047
+ throw new Error(`State ${JSON.stringify(state)} for ${id} is not valid`);
3048
+ }
3049
+ if (!this.sqlDPs[id]?.config) {
3050
+ if (applyRules) {
3051
+ throw new Error(`sql not enabled for ${id}, so can not apply the rules as requested`);
3052
+ }
3053
+ this.sqlDPs[id] ||= {};
3054
+ this.sqlDPs[id].realId = id;
3055
+ }
3056
+ return new Promise((resolve, reject) => {
3057
+ if (applyRules) {
3058
+ this.pushHistory(id, state);
3059
+ resolve(true);
3060
+ }
3061
+ else {
3062
+ this.pushHelper(id, state, err => {
3063
+ if (err) {
3064
+ reject(new Error(`Error writing state for ${id}: ${err.message}, Data: ${JSON.stringify(state)}`));
3065
+ }
3066
+ else {
3067
+ resolve(true);
3068
+ }
3069
+ });
3070
+ }
3071
+ });
3072
+ }
3073
+ async storeState(msg) {
3074
+ if (!msg.message) {
3075
+ this.log.error('storeState called with invalid data');
3076
+ return this.sendTo(msg.from, msg.command, {
3077
+ error: `Invalid call: ${JSON.stringify(msg)}`,
3078
+ }, msg.callback);
3079
+ }
3080
+ const errors = [];
3081
+ let successCount = 0;
3082
+ if (Array.isArray(msg.message)) {
3083
+ this.log.debug(`storeState ${msg.message.length} items`);
3084
+ for (let i = 0; i < msg.message.length; i++) {
3085
+ const id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
3086
+ try {
3087
+ await this.storeStatePushData(id, msg.message[i].state, msg.message[i].rules);
3088
+ successCount++;
3089
+ }
3090
+ catch (err) {
3091
+ errors.push(err.message);
3092
+ }
3093
+ }
3094
+ }
3095
+ else if (msg.message.id && Array.isArray(msg.message.state)) {
3096
+ this.log.debug(`storeState ${msg.message.state.length} items`);
3097
+ const id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3098
+ for (let j = 0; j < msg.message.state.length; j++) {
3099
+ try {
3100
+ await this.storeStatePushData(id, msg.message.state[j], msg.message.rules);
3101
+ successCount++;
3102
+ }
3103
+ catch (err) {
3104
+ errors.push(err.message);
3105
+ }
3106
+ }
3107
+ }
3108
+ else if (msg.message.id && msg.message.state) {
3109
+ this.log.debug('storeState 1 item');
3110
+ const id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3111
+ try {
3112
+ await this.storeStatePushData(id, msg.message.state, msg.message.rules);
3113
+ successCount++;
3114
+ }
3115
+ catch (err) {
3116
+ errors.push(err.message);
3117
+ }
3118
+ }
3119
+ else {
3120
+ this.log.error('storeState called with invalid data');
3121
+ return this.sendTo(msg.from, msg.command, {
3122
+ error: `Invalid call: ${JSON.stringify(msg)}`,
3123
+ }, msg.callback);
3124
+ }
3125
+ if (errors.length) {
3126
+ this.log.warn(`storeState executed with ${errors.length} errors: ${errors.join(', ')}`);
3127
+ return this.sendTo(msg.from, msg.command, {
3128
+ error: `${errors.length} errors happened while storing data`,
3129
+ errors: errors,
3130
+ successCount,
3131
+ }, msg.callback);
3132
+ }
3133
+ this.log.debug(`storeState executed with ${successCount} states successfully`);
3134
+ this.sendTo(msg.from, msg.command, {
3135
+ success: true,
3136
+ successCount,
3137
+ sqlConnected: !!this.clientPool,
3138
+ }, msg.callback);
3139
+ }
3140
+ getDpOverview(msg) {
3141
+ const result = [];
3142
+ const query = this.sqlFuncs.getIdSelect(this.config.dbname);
3143
+ this.log.info(query);
3144
+ this.borrowClientFromPool((err, client) => {
3145
+ if (err || !client) {
3146
+ this.returnClientToPool(client);
3147
+ return this.sendTo(msg.from, msg.command, {
3148
+ error: `Cannot select ${query}: ${err || 'no client'}`,
3149
+ }, msg.callback);
3150
+ }
3151
+ client.execute(query, (err, rows /* , fields */) => {
3152
+ if (err) {
3153
+ this.returnClientToPool(client);
3154
+ this.log.error(`Cannot select ${query}: ${err}`);
3155
+ this.sendTo(msg.from, msg.command, {
3156
+ error: `Cannot select ${query}: ${err}`,
3157
+ }, msg.callback);
3158
+ return;
3159
+ }
3160
+ this.log.info(`Query result ${JSON.stringify(rows)}`);
3161
+ if (rows?.length) {
3162
+ for (let r = 0; r < rows.length; r++) {
3163
+ result[rows[r].type] ||= {};
3164
+ result[rows[r].type][rows[r].id] = { name: rows[r].name };
3165
+ switch (dbNames[rows[r].type]) {
3166
+ case 'ts_number':
3167
+ result[rows[r].type][rows[r].id].type = 'number';
3168
+ break;
3169
+ case 'ts_string':
3170
+ result[rows[r].type][rows[r].id].type = 'string';
3171
+ break;
3172
+ case 'ts_bool':
3173
+ result[rows[r].type][rows[r].id].type = 'boolean';
3174
+ break;
3175
+ }
3176
+ }
3177
+ this.log.info(`initialisation result: ${JSON.stringify(result)}`);
3178
+ this.getFirstTsForIds(client, 0, result, msg);
3179
+ }
3180
+ });
3181
+ });
3182
+ }
3183
+ getFirstTsForIds(client, typeId, resultData, msg) {
3184
+ if (typeId < dbNames.length) {
3185
+ if (!resultData[typeId]) {
3186
+ this.getFirstTsForIds(client, (typeId + 1), resultData, msg);
3187
+ }
3188
+ else {
3189
+ const query = this.sqlFuncs.getFirstTs(this.config.dbname, dbNames[typeId]);
3190
+ this.log.info(query);
3191
+ client.execute(query, (err, rows /* , fields */) => {
3192
+ if (err) {
3193
+ this.returnClientToPool(client);
3194
+ this.log.error(`Cannot select ${query}: ${err}`);
3195
+ this.sendTo(msg.from, msg.command, {
3196
+ error: `Cannot select ${query}: ${err}`,
3197
+ }, msg.callback);
3198
+ return;
3199
+ }
3200
+ this.log.info(`Query result ${JSON.stringify(rows)}`);
3201
+ if (rows?.length) {
3202
+ for (let r = 0; r < rows.length; r++) {
3203
+ if (resultData[typeId][rows[r].id]) {
3204
+ resultData[typeId][rows[r].id].ts = rows[r].ts;
3205
+ }
3206
+ }
3207
+ }
3208
+ this.log.info(`enhanced result (${typeId}): ${JSON.stringify(resultData)}`);
3209
+ this.dpOverviewTimeout = setTimeout((_client, typeId, resultData, msg) => {
3210
+ this.dpOverviewTimeout = null;
3211
+ this.getFirstTsForIds(_client, typeId, resultData, msg);
3212
+ }, 5000, client, typeId + 1, resultData, msg);
3213
+ });
3214
+ }
3215
+ }
3216
+ else {
3217
+ this.returnClientToPool(client);
3218
+ this.log.info('consolidate data ...');
3219
+ const result = {};
3220
+ for (let ti = 0; ti < dbNames.length; ti++) {
3221
+ if (resultData[ti]) {
3222
+ for (const index in resultData[ti]) {
3223
+ if (!Object.prototype.hasOwnProperty.call(resultData[ti], index)) {
3224
+ continue;
3225
+ }
3226
+ const id = resultData[ti][index].name;
3227
+ if (!result[id]) {
3228
+ result[id] = {
3229
+ type: resultData[ti][index].type || 'undefined',
3230
+ ts: resultData[ti][index].ts,
3231
+ };
3232
+ }
3233
+ else {
3234
+ result[id].type = 'undefined';
3235
+ if (result[id].ts !== undefined &&
3236
+ (resultData[ti][index].ts === undefined || resultData[ti][index].ts < result[id].ts)) {
3237
+ result[id].ts = resultData[ti][index].ts;
3238
+ }
3239
+ }
3240
+ }
3241
+ }
3242
+ }
3243
+ this.log.info(`Result: ${JSON.stringify(result)}`);
3244
+ this.sendTo(msg.from, msg.command, {
3245
+ success: true,
3246
+ result: result,
3247
+ }, msg.callback);
3248
+ }
3249
+ }
3250
+ enableHistory(msg) {
3251
+ if (!msg.message?.id) {
3252
+ this.log.error('enableHistory called with invalid data');
3253
+ this.sendTo(msg.from, msg.command, { error: 'Invalid call' }, msg.callback);
3254
+ return;
3255
+ }
3256
+ const obj = {};
3257
+ obj.common = {};
3258
+ obj.common.custom = {};
3259
+ obj.common.custom[this.namespace] = msg.message.options || {};
3260
+ obj.common.custom[this.namespace].enabled = true;
3261
+ this.extendForeignObject(msg.message.id, obj, err => {
3262
+ if (err) {
3263
+ this.log.error(`enableHistory: ${err}`);
3264
+ this.sendTo(msg.from, msg.command, {
3265
+ error: err,
3266
+ }, msg.callback);
3267
+ }
3268
+ else {
3269
+ this.log.info(JSON.stringify(obj));
3270
+ this.sendTo(msg.from, msg.command, { success: true }, msg.callback);
3271
+ }
3272
+ });
3273
+ }
3274
+ disableHistory(msg) {
3275
+ if (!msg.message?.id) {
3276
+ this.log.error('disableHistory called with invalid data');
3277
+ return this.sendTo(msg.from, msg.command, {
3278
+ error: 'Invalid call',
3279
+ }, msg.callback);
3280
+ }
3281
+ const obj = {};
3282
+ obj.common = {};
3283
+ obj.common.custom = {
3284
+ [this.namespace]: {
3285
+ enabled: false,
3286
+ },
3287
+ };
3288
+ this.extendForeignObject(msg.message.id, obj, err => {
3289
+ if (err) {
3290
+ this.log.error(`disableHistory: ${err}`);
3291
+ this.sendTo(msg.from, msg.command, {
3292
+ error: err,
3293
+ }, msg.callback);
3294
+ }
3295
+ else {
3296
+ this.log.info(JSON.stringify(obj));
3297
+ this.sendTo(msg.from, msg.command, { success: true }, msg.callback);
3298
+ }
3299
+ });
3300
+ }
3301
+ getEnabledDPs(msg) {
3302
+ const data = {};
3303
+ for (const id in this.sqlDPs) {
3304
+ if (Object.prototype.hasOwnProperty.call(this.sqlDPs, id) && this.sqlDPs[id]?.config?.enabled) {
3305
+ data[this.sqlDPs[id].realId] = this.sqlDPs[id].config;
3306
+ }
3307
+ }
3308
+ this.sendTo(msg.from, msg.command, data, msg.callback);
3309
+ }
3310
+ /**
3311
+ * Align the connection settings with the MySQL container declared in docker-compose.yaml.
3312
+ *
3313
+ * The container itself (image, ports, volumes, credentials) is defined there and created by the
3314
+ * docker plugin. This only mirrors the values the adapter needs to connect, because the admin UI
3315
+ * hides host/port/user/password/dbname/dbtype while the docker container is enabled and those
3316
+ * fields may still hold stale values from a previous manual setup.
3317
+ */
3318
+ applyDockerMysqlConfig(config) {
3319
+ config.dockerMysql ||= { enabled: false };
3320
+ config.dbtype = 'mysql';
3321
+ config.dbname = 'iobroker';
3322
+ config.user = 'iobroker';
3323
+ config.password = 'iobroker';
3324
+ config.dockerMysql.port = parseInt(config.dockerMysql.port || '3306', 10) || 3306;
3325
+ config.port = config.dockerMysql.port;
3326
+ config.host = config.dockerMysql.bind || '127.0.0.1';
3327
+ config.multiRequests = true;
3328
+ config.maxConnections = 100;
3329
+ if (config.dockerPhpMyAdmin) {
3330
+ config.dockerPhpMyAdmin.port = parseInt(config.dockerPhpMyAdmin.port || '8080', 10) || 8080;
3331
+ }
3332
+ }
3333
+ normalizeAdapterConfig(config) {
3334
+ config.dbname ||= 'iobroker';
3335
+ if (config.writeNulls === undefined) {
3336
+ config.writeNulls = true;
3337
+ }
3338
+ config.retention = parseInt(config.retention, 10) || 0;
3339
+ if (config.retention === -1) {
3340
+ // Custom timeframe
3341
+ config.retention = (parseInt(config.customRetentionDuration, 10) || 0) * 24 * 60 * 60;
3342
+ }
3343
+ config.debounce = parseInt(config.debounce, 10) || 0;
3344
+ config.requestInterval =
3345
+ config.requestInterval === undefined || config.requestInterval === null || config.requestInterval === ''
3346
+ ? 0
3347
+ : parseInt(config.requestInterval, 10) || 0;
3348
+ if (config.changesRelogInterval !== null && config.changesRelogInterval !== undefined) {
3349
+ config.changesRelogInterval = parseInt(config.changesRelogInterval, 10);
3350
+ }
3351
+ else {
3352
+ config.changesRelogInterval = 0;
3353
+ }
3354
+ if (!clients[config.dbtype]) {
3355
+ this.log.error(`Unknown DB type: ${config.dbtype}`);
3356
+ void this.stop?.();
3357
+ }
3358
+ if (config.multiRequests !== undefined && config.dbtype !== 'sqlite') {
3359
+ clients[config.dbtype].multiRequests = config.multiRequests;
3360
+ }
3361
+ if (config.maxConnections !== undefined && config.dbtype !== 'sqlite') {
3362
+ config.maxConnections = parseInt(config.maxConnections, 10);
3363
+ if (config.maxConnections !== 0 && !config.maxConnections) {
3364
+ config.maxConnections = 100;
3365
+ }
3366
+ }
3367
+ else {
3368
+ config.maxConnections = 1; // SQLite does not support multiple connections
3369
+ }
3370
+ if (config.changesMinDelta !== null && config.changesMinDelta !== undefined) {
3371
+ config.changesMinDelta = parseFloat(config.changesMinDelta.toString().replace(/,/g, '.'));
3372
+ }
3373
+ else {
3374
+ config.changesMinDelta = 0;
3375
+ }
3376
+ if (config.blockTime !== null && config.blockTime !== undefined) {
3377
+ config.blockTime = parseInt(config.blockTime, 10) || 0;
3378
+ }
3379
+ else {
3380
+ if (config.debounce !== null && config.debounce !== undefined) {
3381
+ config.debounce = parseInt(config.debounce, 10) || 0;
3382
+ }
3383
+ else {
3384
+ config.blockTime = 0;
3385
+ }
3386
+ }
3387
+ if (config.debounceTime !== null && config.debounceTime !== undefined) {
3388
+ config.debounceTime = parseInt(config.debounceTime, 10) || 0;
3389
+ }
3390
+ else {
3391
+ config.debounceTime = 0;
3392
+ }
3393
+ if (config.maxLength !== null && config.maxLength !== undefined) {
3394
+ config.maxLength = parseInt(config.maxLength, 10) || 0;
3395
+ }
3396
+ else {
3397
+ config.maxLength = 0;
3398
+ }
3399
+ this.multiRequests = clients[config.dbtype].multiRequests;
3400
+ if (!this.multiRequests) {
3401
+ config.writeNulls = false;
3402
+ }
3403
+ config.port = parseInt(config.port, 10) || 0;
3404
+ if (config.round !== null && config.round !== undefined && config.round !== '') {
3405
+ config.round = parseInt(config.round, 10);
3406
+ if (!isFinite(config.round) || config.round < 0) {
3407
+ config.round = null;
3408
+ this.log.info(`Invalid round value: ${config.round} - ignore, do not round values`);
3409
+ }
3410
+ else {
3411
+ config.round = Math.pow(10, config.round);
3412
+ }
3413
+ }
3414
+ else {
3415
+ config.round = null;
3416
+ }
3417
+ return config;
3418
+ }
3419
+ /**
3420
+ * Make sure the 'iobroker' user exists in the containerized MySQL.
3421
+ *
3422
+ * The mysql image already creates it from MYSQL_USER/MYSQL_PASSWORD on first start, so this is a
3423
+ * fallback for volumes that were created before those variables were declared. The container is
3424
+ * started by the docker plugin and may still be initialising, therefore the connection is retried.
3425
+ */
3426
+ async createUserInDocker(retries = 30) {
3427
+ const mySQLOptions = {
3428
+ host: this.config.host, // needed for PostgreSQL , MySQL
3429
+ user: 'root',
3430
+ password: this.config.dockerMysql.rootPassword || 'root_iobroker',
3431
+ port: this.config.port || undefined,
3432
+ ssl: this.config.encrypt
3433
+ ? {
3434
+ rejectUnauthorized: !!this.config.rejectUnauthorized,
3435
+ }
3436
+ : undefined,
3437
+ };
3438
+ for (let attempt = 1; attempt <= retries; attempt++) {
3439
+ const client = new mysql_client_1.MySQL2Client(mySQLOptions);
3440
+ try {
3441
+ await client.connectAsync();
3442
+ // Show all users
3443
+ const exists = await client.executeAsync(`SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'iobroker') as "ex";`);
3444
+ if (exists?.[0]?.ex !== 1) {
3445
+ // create user
3446
+ await client.executeAsync(`CREATE USER 'iobroker'@'%' IDENTIFIED BY 'iobroker';`);
3447
+ await client.executeAsync(`GRANT ALL PRIVILEGES ON * . * TO 'iobroker'@'%';`);
3448
+ await client.executeAsync(`FLUSH PRIVILEGES;`);
3449
+ }
3450
+ await client.disconnectAsync();
3451
+ return;
3452
+ }
3453
+ catch (e) {
3454
+ try {
3455
+ await client.disconnectAsync();
3456
+ }
3457
+ catch {
3458
+ // the connection was never established
3459
+ }
3460
+ if (attempt === retries) {
3461
+ // Do not abort the start-up: the user is normally created by the image itself
3462
+ this.log.warn(`Cannot verify the "iobroker" user in the MySQL container: ${e}`);
3463
+ return;
3464
+ }
3465
+ this.log.debug(`MySQL container not ready yet (${attempt}/${retries}), waiting...`);
3466
+ await new Promise(resolve => setTimeout(resolve, 2000));
3467
+ }
3468
+ }
3469
+ }
3470
+ async main() {
3471
+ this.setConnected(false);
3472
+ // set default history if not yet set
3473
+ try {
3474
+ const obj = await this.getForeignObjectAsync('system.config');
3475
+ if (obj?.common && !obj.common.defaultHistory) {
3476
+ obj.common.defaultHistory = this.namespace;
3477
+ await this.setForeignObjectAsync('system.config', obj);
3478
+ this.log.info(`Set default history instance to "${this.namespace}"`);
3479
+ }
3480
+ }
3481
+ catch (e) {
3482
+ this.log.error(`Cannot get system config: ${e}`);
3483
+ }
3484
+ // The MySQL and phpMyAdmin containers are declared in docker-compose.yaml and are started by
3485
+ // the docker plugin. Align the connection settings before normalising, because normalisation
3486
+ // derives multiRequests/maxConnections/writeNulls from dbtype.
3487
+ if (this.config.dockerMysql?.enabled) {
3488
+ this.applyDockerMysqlConfig(this.config);
3489
+ }
3490
+ // Normalize adapter config
3491
+ const config = this.normalizeAdapterConfig(this.config);
3492
+ this.sqlFuncs = SQLFuncs[config.dbtype];
3493
+ if (config.dockerMysql?.enabled) {
3494
+ // Check that the user 'iobroker' exists
3495
+ await this.createUserInDocker();
3496
+ }
3497
+ if (config.dbtype === 'sqlite' || this.config.host) {
3498
+ this.connect(() => {
3499
+ // read all custom settings
3500
+ this.getObjectView('system', 'custom', {}, (err, doc) => {
3501
+ let count = 0;
3502
+ if (doc?.rows) {
3503
+ for (let i = 0, l = doc.rows.length; i < l; i++) {
3504
+ if (doc.rows[i].value?.[this.namespace]) {
3505
+ let id = doc.rows[i].id;
3506
+ const realId = id;
3507
+ if (doc.rows[i].value[this.namespace] && doc.rows[i].value[this.namespace].aliasId) {
3508
+ this.aliasMap[id] = doc.rows[i].value[this.namespace].aliasId;
3509
+ this.log.debug(`Found Alias: ${id} --> ${this.aliasMap[id]}`);
3510
+ id = this.aliasMap[id];
3511
+ }
3512
+ let storedIndex = null;
3513
+ let storedType = null;
3514
+ if (this.sqlDPs[id] && this.sqlDPs[id].index !== undefined) {
3515
+ storedIndex = this.sqlDPs[id].index;
3516
+ }
3517
+ if (this.sqlDPs[id] && this.sqlDPs[id].dbType !== undefined) {
3518
+ storedType = this.sqlDPs[id].dbType;
3519
+ }
3520
+ // the view returns the whole custom container, the settings for this
3521
+ // instance are below the namespace key
3522
+ const config = this.normalizeCustomConfig(doc.rows[i].value[this.namespace]);
3523
+ this.sqlDPs[id] ||= {};
3524
+ const sqlDP = this.sqlDPs[id];
3525
+ sqlDP.config = config;
3526
+ if (storedIndex !== null) {
3527
+ sqlDP.index = storedIndex;
3528
+ }
3529
+ if (storedType !== null) {
3530
+ sqlDP.dbType = storedType;
3531
+ }
3532
+ if (!config || typeof config !== 'object' || config.enabled === false) {
3533
+ delete this.sqlDPs[id];
3534
+ }
3535
+ else {
3536
+ count++;
3537
+ this.log.info(`enabled logging of ${id}, Alias=${id !== realId}, ${count} points now activated`);
3538
+ // relogTimeout
3539
+ if (config.changesOnly && config.changesRelogInterval > 0) {
3540
+ if (sqlDP.relogTimeout) {
3541
+ clearTimeout(sqlDP.relogTimeout);
3542
+ }
3543
+ sqlDP.relogTimeout = setTimeout(_id => {
3544
+ this.sqlDPs[_id].relogTimeout = null;
3545
+ this.reLogHelper(_id);
3546
+ }, sqlDP.config.changesRelogInterval * 500 * (1 + Math.random()), id);
3547
+ }
3548
+ sqlDP.realId = realId;
3549
+ sqlDP.list ||= [];
3550
+ sqlDP.inFlight ||= {};
3551
+ // randomize lastCheck to avoid all datapoints to be checked at the same timepoint
3552
+ sqlDP.lastCheck = Date.now() - Math.floor(Math.random() * 21600000 /* 6 hours */);
3553
+ }
3554
+ }
3555
+ }
3556
+ }
3557
+ if (this.config.writeNulls) {
3558
+ this.writeNulls();
3559
+ }
3560
+ if (count < 200) {
3561
+ Object.keys(this.sqlDPs).forEach(id => this.sqlDPs[id]?.config &&
3562
+ !this.sqlDPs[id].realId &&
3563
+ this.log.warn(`No realID found for ${id}`));
3564
+ this.subscribeForeignStates(Object.keys(this.sqlDPs).filter(id => this.sqlDPs[id]?.config && this.sqlDPs[id].realId));
3565
+ }
3566
+ else {
3567
+ this.subscribeAll = true;
3568
+ this.subscribeForeignStates('*');
3569
+ }
3570
+ this.subscribeForeignObjects('*');
3571
+ this.log.debug('Initialization done');
3572
+ this.setConnected(true);
3573
+ this.processStartValues();
3574
+ // store all buffered data every 10 minutes to not lost the data
3575
+ this.bufferChecker = setInterval(() => this.storeCached(), 10 * 60000);
3576
+ });
3577
+ });
3578
+ }
3579
+ }
3580
+ }
3581
+ exports.SqlAdapter = SqlAdapter;
3582
+ // If started as allInOne mode => return function to create instance
3583
+ if (require.main !== module) {
3584
+ // Export the constructor in compact mode
3585
+ module.exports = (options) => new SqlAdapter(options);
3586
+ }
3587
+ else {
3588
+ // otherwise start the instance directly
3589
+ (() => new SqlAdapter())();
3590
+ }
3591
+ //# sourceMappingURL=main.js.map