iobroker.sql 4.2.1 → 4.4.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 (81) hide show
  1. package/README.md +66 -12
  2. package/admin/custom/assets/Components-Biqn0PcX.js +1 -0
  3. package/admin/custom/assets/DataBrowser-DTTVoTBj.js +7 -0
  4. package/admin/custom/assets/{_virtual_mf-localSharedImportMap___mfe_internal__SqlComponentsSet__mf_owner__1-BkAtL7lu.js → _virtual_mf-localSharedImportMap___mfe_internal__SqlComponentsSet__mf_owner__1-DAGgRMdx.js} +1 -1
  5. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-DiZBpJW2.js +1439 -0
  6. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__loadShare__shared-DmziGsfK.js +2 -0
  7. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-CY-VVm-e.js +122 -0
  8. package/admin/custom/assets/{_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__153366462090512__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__-B_v57Qfr.js → _virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__--SURtz9t.js} +1 -1
  9. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__prebuild__react_mf_2_dom_mf_1_client__prebuild__-SIym-UC8.js +9 -0
  10. package/admin/custom/assets/{dist-CSJEdwl2.js → dist-ChhOvPa4.js} +1 -1
  11. package/admin/custom/assets/helpers-CwABI1ut.js +1 -0
  12. package/admin/custom/assets/hostInit-Bp3K06oA.js +1 -0
  13. package/admin/custom/assets/index-BACEccc0.js +1 -0
  14. package/admin/custom/assets/{lib-CJNvVWNJ.js → lib-BlyWjmi5.js} +2 -2
  15. package/admin/custom/assets/{mf-entry-bootstrap-0-93bb3b2a.js → mf-entry-bootstrap-0-03451604.js} +3 -3
  16. package/admin/custom/assets/pendingShares-BhtJBPS2.js +2 -0
  17. package/admin/custom/assets/prod-m5pRY8Jx.js +15 -0
  18. package/admin/custom/assets/rolldown-runtime-COiEfhsA.js +1 -0
  19. package/admin/custom/assets/utils-Cqsn1la4.js +4 -0
  20. package/admin/custom/customComponents.js +2 -2
  21. package/admin/custom/i18n/de.json +15 -0
  22. package/admin/custom/i18n/en.json +15 -0
  23. package/admin/custom/i18n/es.json +15 -0
  24. package/admin/custom/i18n/fr.json +15 -0
  25. package/admin/custom/i18n/it.json +15 -0
  26. package/admin/custom/i18n/nl.json +15 -0
  27. package/admin/custom/i18n/pl.json +15 -0
  28. package/admin/custom/i18n/pt.json +15 -0
  29. package/admin/custom/i18n/ru.json +15 -0
  30. package/admin/custom/i18n/uk.json +15 -0
  31. package/admin/custom/i18n/zh-cn.json +15 -0
  32. package/admin/custom/mf-manifest.json +1 -1
  33. package/admin/jsonConfig.json +177 -52
  34. package/admin/jsonCustom.json +106 -27
  35. package/build/lib/connection-factory.js +5 -0
  36. package/build/lib/connection-factory.js.map +1 -1
  37. package/build/lib/errors.js +58 -0
  38. package/build/lib/errors.js.map +1 -1
  39. package/build/lib/messages.js +250 -0
  40. package/build/lib/messages.js.map +1 -1
  41. package/build/lib/mssql.js +41 -21
  42. package/build/lib/mssql.js.map +1 -1
  43. package/build/lib/mysql-client.js +87 -13
  44. package/build/lib/mysql-client.js.map +1 -1
  45. package/build/lib/mysql.js +198 -132
  46. package/build/lib/mysql.js.map +1 -1
  47. package/build/lib/names.js +47 -0
  48. package/build/lib/names.js.map +1 -0
  49. package/build/lib/optional-drivers.js.map +1 -1
  50. package/build/lib/postgresql.js +31 -16
  51. package/build/lib/postgresql.js.map +1 -1
  52. package/build/lib/sql-client-pool.js +7 -1
  53. package/build/lib/sql-client-pool.js.map +1 -1
  54. package/build/lib/sql-client.js +48 -5
  55. package/build/lib/sql-client.js.map +1 -1
  56. package/build/lib/sql-string.js +57 -0
  57. package/build/lib/sql-string.js.map +1 -0
  58. package/build/lib/sqlite.js +29 -17
  59. package/build/lib/sqlite.js.map +1 -1
  60. package/build/lib/statement.js +27 -0
  61. package/build/lib/statement.js.map +1 -0
  62. package/build/lib/values.js +42 -0
  63. package/build/lib/values.js.map +1 -1
  64. package/build/lib/write-buffer.js +80 -0
  65. package/build/lib/write-buffer.js.map +1 -0
  66. package/build/main.js +611 -367
  67. package/build/main.js.map +1 -1
  68. package/io-package.json +34 -28
  69. package/package.json +6 -6
  70. package/admin/custom/assets/Components-DSsR9Vkk.js +0 -1
  71. package/admin/custom/assets/DataBrowser-7kgmmIwY.js +0 -1
  72. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__153366462090512__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BJJWYgdj.js +0 -1217
  73. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__153366462090512__loadShare__shared-Cngqjbz9.js +0 -2
  74. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__153366462090512__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-RXcK0i6Q.js +0 -122
  75. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__153366462090512__prebuild__react_mf_2_dom_mf_1_client__prebuild__-TBtXQFpm.js +0 -9
  76. package/admin/custom/assets/helpers-DT5-3o-l.js +0 -1
  77. package/admin/custom/assets/hostInit-ff9zqDdL.js +0 -1
  78. package/admin/custom/assets/index-BiVFssgl.js +0 -1
  79. package/admin/custom/assets/pendingShares-CpzmKQTZ.js +0 -2
  80. package/admin/custom/assets/rolldown-runtime-Dd_uD5pT.js +0 -1
  81. package/admin/custom/assets/utils-BFhwh2EC.js +0 -4
package/build/main.js CHANGED
@@ -47,10 +47,13 @@ const mysql_client_1 = require("./lib/mysql-client");
47
47
  const connection_options_1 = require("./lib/connection-options");
48
48
  const messages_1 = require("./lib/messages");
49
49
  const values_1 = require("./lib/values");
50
+ const names_1 = require("./lib/names");
51
+ const statement_1 = require("./lib/statement");
50
52
  const statistics_1 = require("./lib/statistics");
51
53
  const postgresql_client_1 = require("./lib/postgresql-client");
52
54
  const sqlite3_client_1 = require("./lib/sqlite3-client");
53
55
  const errors_1 = require("./lib/errors");
56
+ const write_buffer_1 = require("./lib/write-buffer");
54
57
  const SQLFuncs = {
55
58
  mssql: {
56
59
  init: MSSQL.init,
@@ -192,8 +195,15 @@ function isEqual(a, b) {
192
195
  /** Every time series table the statistics and the cleanup have to look at */
193
196
  const STAT_TABLES = ['ts_number', 'ts_string', 'ts_bool', 'ts_counter'];
194
197
  const MAX_TASKS = 100;
195
- /** Maximal number of rows one `getRawEntries` call may return */
196
- const MAX_RAW_ENTRIES = 2000;
198
+ /** Milliseconds a pooled connection may be idle before it is replaced (`max_age` of the pool) */
199
+ const POOL_MAX_IDLE_AGE = 60_000;
200
+ /** Milliseconds between two warnings about values kept while the database is not reachable */
201
+ const KEPT_LOG_INTERVAL = 60_000;
202
+ /**
203
+ * Maximal number of rows one `getRawEntries` call may return. An export of the data browser reads with
204
+ * this page size, and 5000 rows of numbers are still well below 1 MB as a message
205
+ */
206
+ const MAX_RAW_ENTRIES = 5000;
197
207
  /** How often an unchanged connection error is repeated as error in the log */
198
208
  const REPEATED_ERROR_INTERVAL = 3_600_000;
199
209
  function sortByTs(a, b) {
@@ -288,8 +298,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
288
298
  this.log.debug(`Removed Alias: ${id} !-> ${this.aliasMap[id]}`);
289
299
  delete this.aliasMap[id];
290
300
  }
291
- const sqlDP = this.sqlDPs[id];
301
+ // the entry is stored under the alias ID, not under the real ID of the object
292
302
  id = formerAliasId;
303
+ const sqlDP = this.sqlDPs[id];
293
304
  if (sqlDP?.config) {
294
305
  this.log.info(`disabled logging of ${id}`);
295
306
  if (sqlDP.relogTimeout) {
@@ -354,6 +365,19 @@ class SqlAdapter extends adapter_core_1.Adapter {
354
365
  },
355
366
  });
356
367
  }
368
+ /**
369
+ * Log a statement on debug level.
370
+ *
371
+ * Only built when debug is on: a batch carries up to 3000 bound values, and turning them into text
372
+ * for every write would cost CPU even when nothing is logged.
373
+ *
374
+ * @param statement plain SQL or SQL with values
375
+ */
376
+ #debugStatement(statement) {
377
+ if (this.log.level === 'debug' || this.log.level === 'silly') {
378
+ this.log.debug((0, statement_1.statementToString)(statement));
379
+ }
380
+ }
357
381
  borrowClientFromPool(callback) {
358
382
  if (!this.clientPool) {
359
383
  this.setConnected(false);
@@ -378,7 +402,16 @@ class SqlAdapter extends adapter_core_1.Adapter {
378
402
  // drops the flagged client on the next borrow. This just makes the reconnect
379
403
  // visible in the log.
380
404
  if (client.on && client.listenerCount && !client.listenerCount('error')) {
381
- client.on('error', (err) => this.log.warn(`SQL connection lost, will reconnect: ${(0, errors_1.formatError)(err)}`));
405
+ client.on('error', (err) => {
406
+ // An idle connection in the pool that the server closed (e.g. after `wait_timeout`)
407
+ // is simply replaced on the next borrow - nothing was lost, so no warning.
408
+ if (client.borrowed_at) {
409
+ this.log.warn(`SQL connection lost, will reconnect: ${(0, errors_1.formatError)(err)}`);
410
+ }
411
+ else {
412
+ this.log.debug(`Idle SQL connection closed by the server: ${(0, errors_1.formatError)(err)}`);
413
+ }
414
+ });
382
415
  }
383
416
  // A real, working connection was handed out - this, not the mere existence of a pool
384
417
  // object, is what info.connection reports (#374).
@@ -404,7 +437,19 @@ class SqlAdapter extends adapter_core_1.Adapter {
404
437
  this.log.debug(`Return connection to pool: ${this.activeConnections} now`);
405
438
  }
406
439
  if (this.clientPool && client) {
407
- if (this.poolBorrowGuard.length) {
440
+ if (this.poolBorrowGuard.length && client.isBroken()) {
441
+ // A broken client must not go to the waiter directly: it would fail its statements
442
+ // too, and every further waiter after it. Give it back to the pool, which drops it on
443
+ // the next borrow, and borrow a fresh connection for the waiter instead.
444
+ try {
445
+ this.clientPool.return(client);
446
+ }
447
+ catch {
448
+ // Ignore
449
+ }
450
+ this.borrowClientFromPool(this.poolBorrowGuard.shift());
451
+ }
452
+ else if (this.poolBorrowGuard.length) {
408
453
  this.activeConnections++;
409
454
  if (this.logConnectionUsage) {
410
455
  this.log.debug(`Borrow returned connection directly: ${this.activeConnections} now`);
@@ -489,13 +534,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
489
534
  if (customConfig.ignoreAboveNumber !== undefined &&
490
535
  customConfig.ignoreAboveNumber !== null &&
491
536
  customConfig.ignoreAboveNumber !== '') {
492
- customConfig.ignoreAboveNumber = parseFloat(customConfig.ignoreAboveNumber) || null;
537
+ customConfig.ignoreAboveNumber = (0, values_1.parseLimit)(customConfig.ignoreAboveNumber);
493
538
  }
494
539
  // ignoreBelowNumber incl. ignoreBelowZero compatibility handling
495
540
  if (customConfig.ignoreBelowNumber !== undefined &&
496
541
  customConfig.ignoreBelowNumber !== null &&
497
542
  customConfig.ignoreBelowNumber !== '') {
498
- customConfig.ignoreBelowNumber = parseFloat(customConfig.ignoreBelowNumber) || null;
543
+ customConfig.ignoreBelowNumber = (0, values_1.parseLimit)(customConfig.ignoreBelowNumber);
499
544
  }
500
545
  else if (customConfig.ignoreBelowZero === 'true' || customConfig.ignoreBelowZero === true) {
501
546
  customConfig.ignoreBelowNumber = 0;
@@ -639,6 +684,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
639
684
  const poolOptions = {
640
685
  max_idle: this.config.dbtype === 'sqlite' ? 1 : 2,
641
686
  };
687
+ if (this.config.dbtype !== 'sqlite') {
688
+ // A connection that was idle for a while is opened anew instead of being reused: servers
689
+ // close idle connections themselves (MySQL `wait_timeout`, often 60-300 s on hosted
690
+ // databases), and a write on such a connection fails (#587). 60 s is below the usual values.
691
+ poolOptions.max_age = POOL_MAX_IDLE_AGE;
692
+ // close expired idle connections between borrows too, before the server resets them
693
+ poolOptions.evictionRunInterval = POOL_MAX_IDLE_AGE / 2;
694
+ }
642
695
  if (this.config.maxConnections) {
643
696
  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
644
697
  poolOptions.max_wait = 10000; // hard code for now
@@ -691,7 +744,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
691
744
  // With "do not create database" this whole phase is skipped and the adapter connects
692
745
  // straight to the configured database: a restricted role or a managed PostgreSQL often
693
746
  // has no access to the maintenance DB "postgres" at all (#404, #285).
694
- this.log.info(`Postgres connection options: ${JSON.stringify(postgreSQLOptions).replace(postgreSQLOptions.password || '******', '****')}`);
747
+ this.log.info(`Postgres connection options: ${JSON.stringify({ ...postgreSQLOptions, password: '****' })}`);
695
748
  const _client = new postgresql_client_1.PostgreSQLClient(postgreSQLOptions);
696
749
  _client.on?.('error', (err) => this.log.warn(`SQL client error: ${(0, errors_1.formatError)(err)}`));
697
750
  return _client.connect((err) => {
@@ -739,7 +792,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
739
792
  this.clientPool = new mssql_client_1.MSSQLClientPool(poolOptions, msSQLOptions);
740
793
  }
741
794
  else if (this.config.dbtype === 'mysql' && mySQLOptions) {
742
- this.clientPool = new mysql_client_1.MySQL2ClientPool(poolOptions, mySQLOptions);
795
+ this.clientPool = new mysql_client_1.MySQL2ClientPool(poolOptions, mySQLOptions, serverMode => {
796
+ if (!this.#sqlModeLogged) {
797
+ this.#sqlModeLogged = true;
798
+ this.log.info(`The MySQL server runs with sql_mode "${serverMode}". NO_BACKSLASH_ESCAPES is removed for the connections of this adapter, because the values are escaped with backslashes.`);
799
+ }
800
+ });
743
801
  }
744
802
  else if (this.config.dbtype === 'sqlite' && sqLiteOptions) {
745
803
  this.clientPool = new sqlite3_client_1.SQLite3ClientPool(poolOptions, sqLiteOptions);
@@ -931,7 +989,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
931
989
  }
932
990
  destroyDB(msg) {
933
991
  try {
934
- this.allScripts(this.sqlFuncs.destroy(this.config.dbname), 0, err => {
992
+ this.allScripts(this.sqlFuncs.destroy(this.config.dbname, this.config.doNotCreateDatabase), 0, err => {
935
993
  if (err) {
936
994
  this.log.error(err.toString());
937
995
  this.sendTo(msg.from, msg.command, { error: err.toString() }, msg.callback);
@@ -990,7 +1048,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
990
1048
  // execute custom query
991
1049
  query(msg) {
992
1050
  if (!this.multiRequests) {
993
- if (this.tasks.length > MAX_TASKS) {
1051
+ if (this.#queueFull()) {
994
1052
  const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
995
1053
  this.log.error(error);
996
1054
  this.sendTo(msg.from, msg.command, { error }, msg.callback);
@@ -1101,6 +1159,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
1101
1159
  let datapointsPending = 0;
1102
1160
  let allDispatched = false;
1103
1161
  const allFinished = () => {
1162
+ // A flush of the buffers (every 10 min, or because a buffer was full) can still be running
1163
+ // or queued: its rows are no longer in `list` but in `inFlight`. Closing the pool now
1164
+ // would fail them. Wait until they are done; the controller's stopTimeout is the limit.
1165
+ if (this.#writesInFlight > 0) {
1166
+ this.#onWritesDone = allFinished;
1167
+ return;
1168
+ }
1104
1169
  if (this.clientPool) {
1105
1170
  this.clientPool.close();
1106
1171
  this.activeConnections = 0;
@@ -1152,10 +1217,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
1152
1217
  // Values this datapoint has to write before its buffer goes out, so that the boundary
1153
1218
  // markers keep their order relative to the buffered values.
1154
1219
  let pendingWrites = 0;
1220
+ let flushed = false;
1155
1221
  const flushBuffer = () => {
1156
- if (pendingWrites) {
1222
+ if (pendingWrites || flushed) {
1157
1223
  return;
1158
1224
  }
1225
+ flushed = true;
1159
1226
  const buffered = this.sqlDPs[id]?.list;
1160
1227
  // Not every entry in sqlDPs is a configured datapoint: storeState, getHistory and
1161
1228
  // the object view create stubs with `sqlDPs[id] ||= {}` just to carry an index, and
@@ -1248,31 +1315,50 @@ class SqlAdapter extends adapter_core_1.Adapter {
1248
1315
  return;
1249
1316
  }
1250
1317
  this.finished = [callback];
1251
- let dpcount = 0;
1252
- let delay = 0;
1253
- for (const id in this.sqlDPs) {
1254
- if (!Object.prototype.hasOwnProperty.call(this.sqlDPs, id)) {
1255
- continue;
1256
- }
1257
- dpcount++;
1258
- datapointsPending++;
1259
- delay += dpcount % 50 === 0 ? 1000 : 0;
1260
- setTimeout(finishId, delay, id);
1261
- }
1262
- // Only now may a datapoint reporting in finish the whole run: the dispatch above is spread
1263
- // over seconds, so an early finisher must not close the pool under the ones still queued.
1318
+ // All datapoints at once. The dispatch used to be staggered by 1 s per 50 datapoints, so
1319
+ // beyond about 450 datapoints the last ones were only started after the 10 s `stopTimeout`
1320
+ // and their values were lost (#587). The load is limited elsewhere: by the connection limit
1321
+ // (`maxConnections`, writes wait in poolBorrowGuard) and, for SQLite, by the task queue,
1322
+ // which takes any number of inserts.
1323
+ const ids = Object.keys(this.sqlDPs);
1324
+ datapointsPending = ids.length;
1325
+ const dpcount = ids.length;
1326
+ for (const id of ids) {
1327
+ finishId(id);
1328
+ }
1329
+ // Only now may a datapoint reporting in finish the whole run: an early finisher must not
1330
+ // close the pool under the ones still being dispatched.
1264
1331
  allDispatched = true;
1265
- if (!dpcount && callback) {
1332
+ if (dpcount && datapointsPending <= 0) {
1333
+ allFinished();
1334
+ }
1335
+ if (!dpcount) {
1266
1336
  if (this.clientPool) {
1267
1337
  this.clientPool.close();
1268
1338
  this.activeConnections = 0;
1269
1339
  this.clientPool = null;
1270
1340
  this.setConnected(false);
1271
1341
  }
1272
- callback();
1342
+ // so that a second finish() (stopInstance message, then unload) does not wait forever
1343
+ this.finished = true;
1344
+ callback?.();
1273
1345
  }
1274
1346
  }
1275
1347
  processMessage(msg) {
1348
+ // A message with an unexpected shape (`getCounter` without `options`, `null` in an array, ...)
1349
+ // used to throw in the handler and take the adapter down with UNCAUGHT_EXCEPTION. The sender
1350
+ // gets the error instead.
1351
+ try {
1352
+ this.#dispatchMessage(msg);
1353
+ }
1354
+ catch (err) {
1355
+ this.log.error(`Cannot process "${msg.command}" ${JSON.stringify(msg.message)}: ${(0, errors_1.formatError)(err)}`);
1356
+ if (msg.callback) {
1357
+ this.sendTo(msg.from, msg.command, { error: `Invalid call: ${(0, errors_1.formatError)(err)}` }, msg.callback);
1358
+ }
1359
+ }
1360
+ }
1361
+ #dispatchMessage(msg) {
1276
1362
  // Answer with an error instead of dereferencing a `sqlFuncs` that is still null. Guarding
1277
1363
  // here covers every database-backed command at once; the alternative would be a check at
1278
1364
  // each of the ~30 `this.sqlFuncs!` uses, every one of which is only reachable from here
@@ -1658,6 +1744,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1658
1744
  }
1659
1745
  pushHelper(_id, state, cb) {
1660
1746
  if (!this.sqlDPs[_id] || (!this.sqlDPs[_id].state && !state)) {
1747
+ cb?.();
1661
1748
  return;
1662
1749
  }
1663
1750
  state ||= this.sqlDPs[_id].state;
@@ -1690,7 +1777,10 @@ class SqlAdapter extends adapter_core_1.Adapter {
1690
1777
  val = val ? 1 : 0;
1691
1778
  }
1692
1779
  else {
1693
- return this.log.info(`Do not store value "${val}" for ${_id} because no number`);
1780
+ this.log.info(`Do not store value "${val}" for ${_id} because no number`);
1781
+ // `storeState` waits for this callback; without it the message was never answered
1782
+ cb?.();
1783
+ return;
1694
1784
  }
1695
1785
  }
1696
1786
  else if (_settings.storageType === 'Boolean' && typeof val !== 'boolean') {
@@ -1700,12 +1790,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
1700
1790
  else {
1701
1791
  _settings.enableDebugLogs && this.log.debug(`Datatype ${_id}: Currently: null`);
1702
1792
  }
1703
- state.val = val;
1704
- this.pushValueIntoDB(_id, state, false, false, cb);
1793
+ // A copy: `state` is the reference value of "Record changes only" (sqlDPs[id].state), and
1794
+ // the converted value must not replace it.
1795
+ this.pushValueIntoDB(_id, { ...state, val }, false, false, cb);
1705
1796
  }
1706
1797
  getAllIds(cb) {
1707
1798
  const query = this.sqlFuncs.getIdSelect(this.config.dbname);
1708
- this.log.debug(query);
1799
+ this.#debugStatement(query);
1709
1800
  this.borrowClientFromPool((err, client) => {
1710
1801
  if (err || !client) {
1711
1802
  this.returnClientToPool(client);
@@ -1714,7 +1805,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1714
1805
  client.execute(query, (err, rows) => {
1715
1806
  this.returnClientToPool(client);
1716
1807
  if (err) {
1717
- this.log.error(`Cannot select ${query}: ${err}`);
1808
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
1718
1809
  return cb?.(err);
1719
1810
  }
1720
1811
  if (rows?.length) {
@@ -1734,7 +1825,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1734
1825
  }
1735
1826
  getAllFroms(cb) {
1736
1827
  const query = this.sqlFuncs.getFromSelect(this.config.dbname);
1737
- this.log.debug(query);
1828
+ this.#debugStatement(query);
1738
1829
  this.borrowClientFromPool((err, client) => {
1739
1830
  if (err || !client) {
1740
1831
  this.returnClientToPool(client);
@@ -1743,7 +1834,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1743
1834
  client.execute(query, (err, rows /* , fields */) => {
1744
1835
  this.returnClientToPool(client);
1745
1836
  if (err) {
1746
- this.log.error(`Cannot select ${query}: ${err}`);
1837
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
1747
1838
  return cb?.(err);
1748
1839
  }
1749
1840
  if (rows?.length) {
@@ -1756,7 +1847,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1756
1847
  });
1757
1848
  }
1758
1849
  _checkRetention(query, cb) {
1759
- this.log.debug(query);
1850
+ this.#debugStatement(query);
1760
1851
  this.borrowClientFromPool((err, client) => {
1761
1852
  if (err || !client) {
1762
1853
  this.returnClientToPool(client);
@@ -1767,7 +1858,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1767
1858
  client.execute(query, (err) => {
1768
1859
  this.returnClientToPool(client);
1769
1860
  if (err) {
1770
- this.log.warn(`Retention: Cannot delete ${query}: ${err}`);
1861
+ this.log.warn(`Retention: Cannot delete ${(0, statement_1.statementToString)(query)}: ${err}`);
1771
1862
  }
1772
1863
  cb?.();
1773
1864
  });
@@ -1786,7 +1877,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1786
1877
  else {
1787
1878
  const query = this.sqlFuncs.retention(this.config.dbname, this.sqlDPs[id].index, dbNames[this.sqlDPs[id].type], this.sqlDPs[id].config.retention);
1788
1879
  if (!this.multiRequests) {
1789
- if (this.tasks.length > MAX_TASKS) {
1880
+ if (this.#queueFull()) {
1790
1881
  return this.log.error(`Cannot queue new requests, because more than ${MAX_TASKS}`);
1791
1882
  }
1792
1883
  const start = this.tasks.length === 1;
@@ -1816,44 +1907,64 @@ class SqlAdapter extends adapter_core_1.Adapter {
1816
1907
  /**
1817
1908
  * Write one batch of values.
1818
1909
  *
1819
- * `sqlFuncs.insert()` chunks at 500 rows per statement and emits one statement per table, so a batch
1820
- * can be more than one query. They must be sent one by one: no driver here is configured for
1821
- * multi-statement batches (mysql2 needs `multipleStatements`, node-sqlite3's run() takes a single
1822
- * statement), and enabling that would only widen the injection surface of the `query` message.
1823
- * All statements share one borrowed connection, and the first failure aborts the rest - same as the
1824
- * single concatenated query did before.
1910
+ * The batch is split into groups of one table with at most 500 rows, and each group is one INSERT.
1911
+ * They must be sent one by one: no driver here is configured for multi-statement batches (mysql2
1912
+ * needs `multipleStatements`, node-sqlite3's run() takes a single statement), and enabling that
1913
+ * would only widen the injection surface of the `query` message. All statements share one borrowed
1914
+ * connection, and the first failure aborts the rest.
1915
+ *
1916
+ * The error is passed on (#587). Before, it was only logged and the whole batch was gone, while
1917
+ * `storeState` answered with success. If the database was not reachable - no connection from the
1918
+ * pool, or the connection broke - the rows that were not written are passed on as well, the group
1919
+ * that failed and all after it, so the caller can keep them for a retry. On an SQL error they are
1920
+ * not: the same rows would fail again.
1921
+ *
1922
+ * @param list the rows of one datapoint
1923
+ * @param index the database ID of the datapoint
1924
+ * @param id the ioBroker ID, for the log and the retention check
1925
+ * @param cb the error, and the unwritten rows if a retry makes sense
1825
1926
  */
1826
- _insertValuesIntoDB(queries, id, cb) {
1927
+ _insertValuesIntoDB(list, index, id, cb) {
1928
+ const groups = (0, write_buffer_1.splitBatch)(list);
1827
1929
  this.borrowClientFromPool((err, client) => {
1828
1930
  if (err || !client) {
1829
1931
  this.returnClientToPool(client);
1830
- this.log.error(err ? (0, errors_1.formatError)(err) : 'No client');
1831
- cb?.(); // BF asked (2021.12.14): may be return here err?
1932
+ const error = err || new Error('No client');
1933
+ this.log.error((0, errors_1.formatError)(error));
1934
+ cb?.(error, list);
1832
1935
  return;
1833
1936
  }
1834
1937
  const next = (i) => {
1835
- if (i >= queries.length) {
1938
+ if (i >= groups.length) {
1836
1939
  this.returnClientToPool(client);
1837
1940
  this.checkRetention(id);
1838
- cb?.(); // BF asked (2021.12.14): may be return here err?
1941
+ cb?.();
1839
1942
  return;
1840
1943
  }
1841
- this.log.debug(queries[i]);
1842
- client.execute(queries[i], (err /* , rows, fields */) => {
1843
- if (err) {
1844
- this.returnClientToPool(client);
1845
- this.log.error(`Cannot insert ${queries[i]}: ${err} (id: ${id})`);
1846
- cb?.(); // BF asked (2021.12.14): may be return here err?
1944
+ const queries = this.sqlFuncs.insert(this.config.dbname, index, groups[i]);
1945
+ const run = (q) => {
1946
+ if (q >= queries.length) {
1947
+ next(i + 1);
1847
1948
  return;
1848
1949
  }
1849
- next(i + 1);
1850
- });
1950
+ this.#debugStatement(queries[q]);
1951
+ client.execute(queries[q], (err /* , rows, fields */) => {
1952
+ if (err) {
1953
+ this.returnClientToPool(client);
1954
+ this.log.error(`Cannot insert ${(0, statement_1.statementToString)(queries[q])}: ${err} (id: ${id})`);
1955
+ cb?.(err, (0, errors_1.isConnectionError)(err) ? groups.slice(i).flat() : undefined);
1956
+ return;
1957
+ }
1958
+ run(q + 1);
1959
+ });
1960
+ };
1961
+ run(0);
1851
1962
  };
1852
1963
  next(0);
1853
1964
  });
1854
1965
  }
1855
1966
  _executeQuery(query, id, cb) {
1856
- this.log.debug(query);
1967
+ this.#debugStatement(query);
1857
1968
  this.borrowClientFromPool((err, client) => {
1858
1969
  if (err || !client) {
1859
1970
  this.returnClientToPool(client);
@@ -1864,7 +1975,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1864
1975
  client.execute(query, (err) => {
1865
1976
  this.returnClientToPool(client);
1866
1977
  if (err) {
1867
- this.log.error(`Cannot query ${query}: ${err} (id: ${id})`);
1978
+ this.log.error(`Cannot query ${(0, statement_1.statementToString)(query)}: ${err} (id: ${id})`);
1868
1979
  }
1869
1980
  cb?.(err);
1870
1981
  });
@@ -1972,7 +2083,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1972
2083
  this.sqlDPs[task.id].type !== this.sqlDPs[task.id].dbType) {
1973
2084
  this.sqlDPs[task.id].dbType = this.sqlDPs[task.id].type;
1974
2085
  const query = this.sqlFuncs.getIdUpdate(this.config.dbname, this.sqlDPs[task.id].index, this.sqlDPs[task.id].type);
1975
- this.log.debug(query);
2086
+ this.#debugStatement(query);
1976
2087
  return this.borrowClientFromPool((err, client) => {
1977
2088
  if (err || !client) {
1978
2089
  this.returnClientToPool(client);
@@ -1982,7 +2093,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1982
2093
  client.execute(query, err => {
1983
2094
  this.returnClientToPool(client);
1984
2095
  if (err) {
1985
- this.log.error(`error updating history config for ${task.id} to pin datatype: ${query}: ${err}`);
2096
+ this.log.error(`error updating history config for ${task.id} to pin datatype: ${(0, statement_1.statementToString)(query)}: ${err}`);
1986
2097
  }
1987
2098
  else {
1988
2099
  this.log.info(`changed history configuration to pin detected datatype for ${task.id}`);
@@ -2022,19 +2133,26 @@ class SqlAdapter extends adapter_core_1.Adapter {
2022
2133
  if (this.sqlDPs[id].index === undefined) {
2023
2134
  this.sqlDPs[id].isRunning ||= [];
2024
2135
  tmpState = { ...state };
2025
- this.sqlDPs[id].isRunning.push({ id, state: tmpState, cb, isCounter });
2026
- if (this.sqlDPs[id].isRunning.length === 1) {
2136
+ const waiting = this.sqlDPs[id].isRunning;
2137
+ waiting.push({ id, state: tmpState, cb, isCounter });
2138
+ if (waiting.length === 1) {
2027
2139
  // read or create in DB
2028
- return this.getId(id, type, (err, _id) => {
2029
- this.log.debug(`prepareTaskCheckTypeAndDbId getId Result - isRunning length = ${this.sqlDPs[id].isRunning ? this.sqlDPs[id].isRunning.length : 'none'}`);
2140
+ return this.getId(id, type, err => {
2141
+ // The datapoint can be disabled or deleted while the lookup runs. Then
2142
+ // this.sqlDPs[id] is gone; reading it threw inside the driver callback (uncaught).
2143
+ // The waiting list is kept in a local, so its callbacks are still answered.
2144
+ const sqlDP = this.sqlDPs[id];
2145
+ this.log.debug(`prepareTaskCheckTypeAndDbId getId Result - isRunning length = ${waiting.length}`);
2146
+ if (sqlDP?.isRunning === waiting) {
2147
+ sqlDP.isRunning = undefined;
2148
+ }
2030
2149
  if (err) {
2031
- this.log.warn(`Cannot get index of "${_id}": ${err}`);
2032
- this.sqlDPs[_id].isRunning?.forEach(r => r.cb?.(new Error(`Cannot get index of "${r.id}": ${err}`)));
2150
+ this.log.warn(`Cannot get index of "${id}": ${err}`);
2151
+ waiting.forEach(r => r.cb?.(new Error(`Cannot get index of "${r.id}": ${err}`)));
2033
2152
  }
2034
2153
  else {
2035
- this.sqlDPs[_id].isRunning?.forEach(r => r.cb?.());
2154
+ waiting.forEach(r => r.cb?.());
2036
2155
  }
2037
- this.sqlDPs[_id].isRunning = undefined;
2038
2156
  });
2039
2157
  }
2040
2158
  return;
@@ -2154,6 +2272,116 @@ class SqlAdapter extends adapter_core_1.Adapter {
2154
2272
  }
2155
2273
  });
2156
2274
  }
2275
+ /**
2276
+ * Keep rows that could not be written, because the database was not reachable, for the next write
2277
+ * of the datapoint.
2278
+ *
2279
+ * The rows go in front of the values logged in the meantime; beyond the cap the oldest are dropped.
2280
+ * The order in the database does not depend on it, the rows are keyed by timestamp.
2281
+ * If the connection broke after the server had committed the statement, its rows are sent again:
2282
+ * the tables with a primary key ignore the duplicate, `ts_counter` (MySQL/PostgreSQL) and the MSSQL
2283
+ * tables get it twice.
2284
+ *
2285
+ * Not when the adapter stops or the datapoint is being disabled: nothing would write the buffer
2286
+ * any more.
2287
+ *
2288
+ * Besides the limit per datapoint, all datapoints together keep at most {@link MAX_KEPT_ROWS} rows,
2289
+ * so the memory stays bounded however many datapoints are logged. The warning is one line for all
2290
+ * datapoints, at most once per {@link KEPT_LOG_INTERVAL}: during an outage every write fails.
2291
+ *
2292
+ * @param id the datapoint
2293
+ * @param unwritten the rows that were not written
2294
+ * @returns how many of the rows are kept
2295
+ */
2296
+ #keepForRetry(id, unwritten) {
2297
+ const sqlDP = this.sqlDPs[id];
2298
+ if (!sqlDP || this.finished || sqlDP.config?.enabled === false) {
2299
+ this.log.warn(`${unwritten.length} values of ${id} were not stored, the database is not reachable`);
2300
+ return 0;
2301
+ }
2302
+ const now = Date.now();
2303
+ const report = now - this.#keptLoggedAt >= KEPT_LOG_INTERVAL;
2304
+ if (report) {
2305
+ this.#recountKept();
2306
+ }
2307
+ const { list, dropped } = (0, write_buffer_1.requeue)(sqlDP.list, unwritten, (0, write_buffer_1.requeueCap)(sqlDP.list?.length || 0, this.#keptTotal));
2308
+ sqlDP.list = list;
2309
+ const kept = unwritten.length - dropped;
2310
+ if (kept) {
2311
+ this.#kept.set(id, (this.#kept.get(id) || 0) + kept);
2312
+ this.#keptTotal += kept;
2313
+ }
2314
+ this.#keptDropped += dropped;
2315
+ if (report) {
2316
+ this.#keptLoggedAt = now;
2317
+ const lost = this.#takeDroppedText();
2318
+ this.log.warn(`Database not reachable, ${this.#keptTotal} values of ${this.#kept.size} datapoints are kept for the next write${lost ? `; ${lost}` : ''}`);
2319
+ }
2320
+ return kept;
2321
+ }
2322
+ /**
2323
+ * Forget the kept rows of a datapoint whose buffer goes to the database now: if the write fails
2324
+ * again, {@link #keepForRetry} counts them anew.
2325
+ *
2326
+ * @param id the datapoint
2327
+ */
2328
+ #releaseKept(id) {
2329
+ const kept = this.#kept.get(id);
2330
+ if (kept) {
2331
+ this.#keptTotal -= kept;
2332
+ this.#kept.delete(id);
2333
+ }
2334
+ }
2335
+ /**
2336
+ * Count the kept rows again. A buffer can also be emptied by the `delete` message, and a datapoint
2337
+ * can be removed while it still has kept rows; without this the total would only ever grow.
2338
+ */
2339
+ #recountKept() {
2340
+ this.#keptTotal = 0;
2341
+ for (const [id, count] of this.#kept) {
2342
+ const kept = Math.min(count, this.sqlDPs[id]?.list?.length || 0);
2343
+ if (kept) {
2344
+ this.#kept.set(id, kept);
2345
+ this.#keptTotal += kept;
2346
+ }
2347
+ else {
2348
+ this.#kept.delete(id);
2349
+ }
2350
+ }
2351
+ }
2352
+ /** The rows dropped because of the limits since the last warning as text, and reset the count */
2353
+ #takeDroppedText() {
2354
+ if (!this.#keptDropped) {
2355
+ return '';
2356
+ }
2357
+ const text = `${this.#keptDropped} older values were dropped (at most ${write_buffer_1.MAX_REQUEUED_ROWS} per datapoint and ${write_buffer_1.MAX_KEPT_ROWS} in total are kept)`;
2358
+ this.#keptDropped = 0;
2359
+ return text;
2360
+ }
2361
+ /** Rows kept for a retry, per datapoint */
2362
+ #kept = new Map();
2363
+ /** Rows kept for a retry, all datapoints together */
2364
+ #keptTotal = 0;
2365
+ /** Kept rows that were dropped because of the limits since the last warning */
2366
+ #keptDropped = 0;
2367
+ /** When the warning about kept values was logged last */
2368
+ #keptLoggedAt = 0;
2369
+ /** Whether the removed `NO_BACKSLASH_ESCAPES` was logged; the pool opens a new connection every minute */
2370
+ #sqlModeLogged = false;
2371
+ /** Writes started by storeCached() that have not called back yet */
2372
+ #writesInFlight = 0;
2373
+ /** Waiting for #writesInFlight to reach 0 (the stop, before the pool is closed) */
2374
+ #onWritesDone = null;
2375
+ #writeFinished() {
2376
+ if (--this.#writesInFlight <= 0) {
2377
+ this.#writesInFlight = 0;
2378
+ const done = this.#onWritesDone;
2379
+ this.#onWritesDone = null;
2380
+ done?.();
2381
+ }
2382
+ }
2383
+ /** Errors of failed inserts whose rows were kept for a retry; weak, so they go with the error */
2384
+ #keptErrors = new WeakSet();
2157
2385
  storeCached(onlyId, cb) {
2158
2386
  let count = 0;
2159
2387
  for (const id in this.sqlDPs) {
@@ -2169,11 +2397,33 @@ class SqlAdapter extends adapter_core_1.Adapter {
2169
2397
  this.sqlDPs[id].inFlight ||= {};
2170
2398
  this.sqlDPs[id].inFlight[inFlightId] = this.sqlDPs[id].list;
2171
2399
  this.sqlDPs[id].list = [];
2400
+ this.#releaseKept(id);
2172
2401
  count++;
2173
- this.pushValuesIntoDB(id, this.sqlDPs[id].inFlight[inFlightId], (err) => {
2402
+ this.#writesInFlight++;
2403
+ this.pushValuesIntoDB(id, this.sqlDPs[id].inFlight[inFlightId], (err, unwritten) => {
2404
+ this.#writeFinished();
2174
2405
  if (this.sqlDPs[id]?.inFlight?.[inFlightId]) {
2175
2406
  delete this.sqlDPs[id].inFlight[inFlightId];
2176
2407
  }
2408
+ if (err && unwritten?.length) {
2409
+ const kept = this.#keepForRetry(id, unwritten);
2410
+ if (kept) {
2411
+ // the other callbacks of a merged insert (#queueInsert) get the same error
2412
+ // object, but not the rows: they are kept with this one
2413
+ this.#keptErrors.add(err);
2414
+ // storeState answers with this error: a caller that sends the values again
2415
+ // would store them twice where the table has no unique key
2416
+ err = new Error(`${err.message}; ${kept} values are kept and written with the next write, do not send them again`, { cause: err });
2417
+ }
2418
+ }
2419
+ else if (err && this.#keptErrors.has(err)) {
2420
+ // rows of this flush were merged into an insert whose rows are kept (see above)
2421
+ err = new Error(`${err.message}; the values are kept and written with the next write, do not send them again`, { cause: err });
2422
+ }
2423
+ else if (!err && this.#keptDropped) {
2424
+ // the database is back before the next warning was due: report the dropped rows now
2425
+ this.log.warn(`While the database was not reachable, ${this.#takeDroppedText()}`);
2426
+ }
2177
2427
  if (!--count && cb) {
2178
2428
  cb?.(err);
2179
2429
  cb = null;
@@ -2196,19 +2446,82 @@ class SqlAdapter extends adapter_core_1.Adapter {
2196
2446
  return;
2197
2447
  }
2198
2448
  if (!this.multiRequests) {
2199
- if (this.tasks.length > MAX_TASKS) {
2200
- const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2201
- this.log.error(error);
2202
- cb?.(new Error(error));
2449
+ this.#queueInsert(id, list, cb);
2450
+ }
2451
+ else {
2452
+ this._insertValuesIntoDB(list, this.sqlDPs[id].index, id, cb);
2453
+ }
2454
+ }
2455
+ /**
2456
+ * Queue the rows of a datapoint for the task queue (SQLite, or `multiRequests` off).
2457
+ *
2458
+ * A queued insert of the same datapoint takes the rows instead of a new task, so there is at most
2459
+ * one waiting insert per datapoint between two tasks that change data. That is why inserts do not
2460
+ * count for `MAX_TASKS`: with more than 100 datapoints, every flush of the buffers (every 10 minutes
2461
+ * and on stop) hit the limit and the values of the remaining datapoints were dropped (#587).
2462
+ *
2463
+ * The rows never join an insert that waits before a task changing data (a `delete`/`update`
2464
+ * message, a retention delete, a user query): they would be written before it, although they
2465
+ * arrived after it, and e.g. `deleteAll` would remove values that came in after the request.
2466
+ * Reading tasks (`select`) do not matter.
2467
+ *
2468
+ * @param id the datapoint
2469
+ * @param list the rows to write
2470
+ * @param cb the result of the write
2471
+ */
2472
+ #queueInsert(id, list, cb) {
2473
+ const index = this.sqlDPs[id].index;
2474
+ // from the end, up to the last task that changes data; the first task is being written while
2475
+ // the queue is locked, it must not grow
2476
+ for (let i = this.tasks.length - 1; i >= (this.lockTasks ? 1 : 0); i--) {
2477
+ const task = this.tasks[i];
2478
+ if (task.operation !== 'insert') {
2479
+ if (task.operation === 'select') {
2480
+ continue;
2481
+ }
2482
+ break;
2483
+ }
2484
+ if (task.index === index) {
2485
+ task.list = task.list.concat(list);
2486
+ const previous = task.callback;
2487
+ // the rows of both are written together: the first callback gets the unwritten rows
2488
+ // of all of them (see processTasks), the second only the error
2489
+ task.callback = previous
2490
+ ? (err, unwritten) => {
2491
+ previous(err, unwritten);
2492
+ cb?.(err);
2493
+ }
2494
+ : cb;
2495
+ return;
2203
2496
  }
2204
- else {
2205
- this.tasks.push({ operation: 'insert', index: this.sqlDPs[id].index, list, id, callback: cb });
2206
- this.tasks.length === 1 && this.processTasks();
2497
+ }
2498
+ this.tasks.push({ operation: 'insert', index, list, id, callback: cb });
2499
+ this.tasks.length === 1 && this.processTasks();
2500
+ }
2501
+ /** Whether the task queue is full; queued inserts are not counted, see #queueInsert() */
2502
+ #queueFull() {
2503
+ let count = 0;
2504
+ for (const task of this.tasks) {
2505
+ if (task.operation !== 'insert') {
2506
+ count++;
2207
2507
  }
2208
2508
  }
2509
+ return count > MAX_TASKS;
2510
+ }
2511
+ /**
2512
+ * Start the next task of the queue.
2513
+ *
2514
+ * With a pause between the requests (`requestInterval`) after that pause, otherwise right away.
2515
+ * `setTimeout(fn, 0)` waits for the next timer tick, which is about 15 ms on Windows: with one
2516
+ * insert task per datapoint, flushing 600 datapoints took about 9 s of the 10 s `stopTimeout`
2517
+ * there, on top of the writes themselves.
2518
+ */
2519
+ #nextTask() {
2520
+ if (this.config.requestInterval) {
2521
+ setTimeout(() => this.processTasks(), this.config.requestInterval);
2522
+ }
2209
2523
  else {
2210
- const queries = this.sqlFuncs.insert(this.config.dbname, this.sqlDPs[id].index, list);
2211
- this._insertValuesIntoDB(queries, id, cb);
2524
+ setImmediate(() => this.processTasks());
2212
2525
  }
2213
2526
  }
2214
2527
  processTasks() {
@@ -2224,7 +2537,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2224
2537
  this.tasks.shift();
2225
2538
  this.lockTasks = false;
2226
2539
  if (this.tasks.length) {
2227
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2540
+ this.#nextTask();
2228
2541
  }
2229
2542
  });
2230
2543
  }
@@ -2247,13 +2560,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
2247
2560
  }
2248
2561
  }
2249
2562
  }
2250
- const queries = this.sqlFuncs.insert(this.config.dbname, this.tasks[0].index, this.tasks[0].list);
2251
- this._insertValuesIntoDB(queries, this.tasks[0].id, () => {
2252
- callbacks.forEach(cb => cb());
2563
+ this._insertValuesIntoDB(this.tasks[0].list, this.tasks[0].index, this.tasks[0].id, (err, unwritten) => {
2564
+ // the lists of all merged tasks were written together: the first callback gets the
2565
+ // unwritten rows of all of them, the others only the error
2566
+ callbacks.forEach((cb, i) => cb(err, i ? undefined : unwritten));
2253
2567
  this.tasks.shift();
2254
2568
  this.lockTasks = false;
2255
2569
  if (this.tasks.length) {
2256
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2570
+ this.#nextTask();
2257
2571
  }
2258
2572
  });
2259
2573
  }
@@ -2264,7 +2578,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2264
2578
  this.tasks.shift();
2265
2579
  this.lockTasks = false;
2266
2580
  if (this.tasks.length) {
2267
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2581
+ this.#nextTask();
2268
2582
  }
2269
2583
  });
2270
2584
  }
@@ -2274,7 +2588,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2274
2588
  this.tasks.shift();
2275
2589
  this.lockTasks = false;
2276
2590
  if (this.tasks.length) {
2277
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2591
+ this.#nextTask();
2278
2592
  }
2279
2593
  });
2280
2594
  }
@@ -2284,7 +2598,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2284
2598
  this.tasks.shift();
2285
2599
  this.lockTasks = false;
2286
2600
  if (this.tasks.length) {
2287
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2601
+ this.#nextTask();
2288
2602
  }
2289
2603
  });
2290
2604
  }
@@ -2294,7 +2608,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2294
2608
  this.tasks.shift();
2295
2609
  this.lockTasks = false;
2296
2610
  if (this.tasks.length) {
2297
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2611
+ this.#nextTask();
2298
2612
  }
2299
2613
  }
2300
2614
  }
@@ -2302,7 +2616,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2302
2616
  // may be it is required to cache all the data in memory
2303
2617
  getId(id, type, cb) {
2304
2618
  let query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
2305
- this.log.debug(query);
2619
+ this.#debugStatement(query);
2306
2620
  this.borrowClientFromPool((err, client) => {
2307
2621
  if (err || !client) {
2308
2622
  this.returnClientToPool(client);
@@ -2317,38 +2631,45 @@ class SqlAdapter extends adapter_core_1.Adapter {
2317
2631
  }
2318
2632
  if (err) {
2319
2633
  this.returnClientToPool(client);
2320
- this.log.error(`Cannot select ${query}: ${err}`);
2634
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
2321
2635
  cb?.(err, id);
2322
2636
  return;
2323
2637
  }
2324
- if (!rows?.length) {
2638
+ // the lookup can also return the row of an ID that differs only in case (#588)
2639
+ const row = (0, names_1.pickRowByName)(rows, id);
2640
+ if (!row) {
2325
2641
  if (type !== null && type !== undefined) {
2326
2642
  // insert
2327
2643
  query = this.sqlFuncs.getIdInsert(this.config.dbname, id, type);
2328
- this.log.debug(query);
2644
+ this.#debugStatement(query);
2329
2645
  client.execute(query, (err /* , rows, fields */) => {
2330
2646
  if (err) {
2331
2647
  this.returnClientToPool(client);
2332
- this.log.error(`Cannot insert ${query}: ${err}`);
2648
+ this.log.error(`Cannot insert ${(0, statement_1.statementToString)(query)}: ${err}`);
2333
2649
  cb?.(err, id);
2334
2650
  }
2335
2651
  else {
2336
2652
  query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
2337
- this.log.debug(query);
2653
+ this.#debugStatement(query);
2338
2654
  client.execute(query, (err, rows /* , fields */) => {
2339
2655
  this.returnClientToPool(client);
2340
- if (err) {
2341
- this.log.error(`Cannot select ${query}: ${err}`);
2656
+ const row = (0, names_1.pickRowByName)(rows, id);
2657
+ if (!this.sqlDPs[id]) {
2658
+ // disabled or deleted while the row was created
2659
+ cb?.(new Error(`ID ${id} no longer active`), id);
2660
+ }
2661
+ else if (err) {
2662
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
2342
2663
  cb?.(err, id);
2343
2664
  }
2344
- else if (rows?.[0]) {
2345
- this.sqlDPs[id].index = rows[0].id;
2346
- this.sqlDPs[id].type = rows[0].type;
2665
+ else if (row) {
2666
+ this.sqlDPs[id].index = row.id;
2667
+ this.sqlDPs[id].type = row.type;
2347
2668
  cb?.(null, id);
2348
2669
  }
2349
2670
  else {
2350
- this.log.error(`No result for select ${query}: after insert`);
2351
- cb?.(new Error(`No result for select ${query}: after insert`), id);
2671
+ this.log.error(`No result for select ${(0, statement_1.statementToString)(query)}: after insert`);
2672
+ cb?.(new Error(`No result for select ${(0, statement_1.statementToString)(query)}: after insert`), id);
2352
2673
  }
2353
2674
  });
2354
2675
  }
@@ -2360,15 +2681,15 @@ class SqlAdapter extends adapter_core_1.Adapter {
2360
2681
  }
2361
2682
  }
2362
2683
  else {
2363
- this.sqlDPs[id].index = rows[0].id;
2364
- if (rows[0].type === null || typeof rows[0].type !== 'number') {
2684
+ this.sqlDPs[id].index = row.id;
2685
+ if (row.type === null || typeof row.type !== 'number') {
2365
2686
  this.sqlDPs[id].type = type === null ? 1 : type; // default string
2366
2687
  const query = this.sqlFuncs.getIdUpdate(this.config.dbname, this.sqlDPs[id].index, this.sqlDPs[id].type);
2367
- this.log.debug(query);
2688
+ this.#debugStatement(query);
2368
2689
  client.execute(query, err => {
2369
2690
  this.returnClientToPool(client);
2370
2691
  if (err) {
2371
- this.log.error(`error updating history config for ${id} to pin datatype: ${query}: ${err}`);
2692
+ this.log.error(`error updating history config for ${id} to pin datatype: ${(0, statement_1.statementToString)(query)}: ${err}`);
2372
2693
  }
2373
2694
  else {
2374
2695
  this.log.info(`changed history configuration to pin detected datatype for ${id}`);
@@ -2378,7 +2699,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2378
2699
  }
2379
2700
  else {
2380
2701
  this.returnClientToPool(client);
2381
- this.sqlDPs[id].type = rows[0].type;
2702
+ this.sqlDPs[id].type = row.type;
2382
2703
  cb?.(null, id);
2383
2704
  }
2384
2705
  }
@@ -2389,7 +2710,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2389
2710
  getFrom(_from, cb) {
2390
2711
  // const sources = (this.config.dbtype !== 'postgresql' ? (this.config.dbname + '.') : '') + 'sources';
2391
2712
  let query = this.sqlFuncs.getFromSelect(this.config.dbname, _from);
2392
- this.log.debug(query);
2713
+ this.#debugStatement(query);
2393
2714
  this.borrowClientFromPool((err, client) => {
2394
2715
  if (err || !client) {
2395
2716
  this.returnClientToPool(client);
@@ -2398,35 +2719,38 @@ class SqlAdapter extends adapter_core_1.Adapter {
2398
2719
  client.execute(query, (err, rows /* , fields */) => {
2399
2720
  if (err) {
2400
2721
  this.returnClientToPool(client);
2401
- this.log.error(`Cannot select ${query}: ${err}`);
2722
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
2402
2723
  return cb?.(err, _from);
2403
2724
  }
2404
- if (!rows?.length) {
2725
+ // the lookup can also return the row of a source that differs only in case (#588)
2726
+ const row = (0, names_1.pickRowByName)(rows, _from);
2727
+ if (!row) {
2405
2728
  // insert
2406
2729
  query = this.sqlFuncs.getFromInsert(this.config.dbname, _from);
2407
- this.log.debug(query);
2730
+ this.#debugStatement(query);
2408
2731
  client.execute(query, err => {
2409
2732
  if (err) {
2410
2733
  this.returnClientToPool(client);
2411
- this.log.error(`Cannot insert ${query}: ${err}`);
2734
+ this.log.error(`Cannot insert ${(0, statement_1.statementToString)(query)}: ${err}`);
2412
2735
  return cb?.(err, _from);
2413
2736
  }
2414
2737
  query = this.sqlFuncs.getFromSelect(this.config.dbname, _from);
2415
- this.log.debug(query);
2738
+ this.#debugStatement(query);
2416
2739
  client.execute(query, (err, rows /* , fields */) => {
2417
2740
  this.returnClientToPool(client);
2418
- if (err || !rows?.length) {
2419
- this.log.error(`Cannot select ${query}: ${err}`);
2741
+ const row = (0, names_1.pickRowByName)(rows, _from);
2742
+ if (err || !row) {
2743
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
2420
2744
  return cb?.(err, _from);
2421
2745
  }
2422
- this.from[_from] = rows[0].id;
2746
+ this.from[_from] = row.id;
2423
2747
  cb?.(null, _from);
2424
2748
  });
2425
2749
  });
2426
2750
  }
2427
2751
  else {
2428
2752
  this.returnClientToPool(client);
2429
- this.from[_from] = rows[0].id;
2753
+ this.from[_from] = row.id;
2430
2754
  cb?.(null, _from);
2431
2755
  }
2432
2756
  });
@@ -2525,7 +2849,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2525
2849
  callback(cache, !!options.returnNewestEntries && !!options.count && cache.length >= options.count, anyInflight, earliestTs);
2526
2850
  }
2527
2851
  #getDataFromDB(query, options, callback) {
2528
- this.log.debug(query);
2852
+ this.#debugStatement(query);
2529
2853
  this.borrowClientFromPool((err, client) => {
2530
2854
  if (err || !client) {
2531
2855
  this.returnClientToPool(client);
@@ -2563,9 +2887,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
2563
2887
  }
2564
2888
  getDataFromDB(table, options, callback) {
2565
2889
  const query = this.sqlFuncs.getHistory(this.config.dbname, table, options);
2566
- this.log.debug(query);
2890
+ this.#debugStatement(query);
2567
2891
  if (!this.multiRequests) {
2568
- if (this.tasks.length > MAX_TASKS) {
2892
+ if (this.#queueFull()) {
2569
2893
  this.log.error(`Cannot queue new requests, because more than ${MAX_TASKS}`);
2570
2894
  callback?.(new Error(`Cannot queue new requests, because more than ${MAX_TASKS}`));
2571
2895
  }
@@ -2582,9 +2906,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
2582
2906
  }
2583
2907
  getCounterDataFromDB(options, callback) {
2584
2908
  const query = this.sqlFuncs.getCounterDiff(this.config.dbname, options);
2585
- this.log.debug(query);
2909
+ this.#debugStatement(query);
2586
2910
  if (!this.multiRequests) {
2587
- if (this.tasks.length > MAX_TASKS) {
2911
+ if (this.#queueFull()) {
2588
2912
  const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2589
2913
  this.log.error(error);
2590
2914
  callback?.(new Error(error));
@@ -2601,10 +2925,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
2601
2925
  }
2602
2926
  }
2603
2927
  getCounterDiff(msg) {
2604
- const id = msg.message.id;
2605
- const start = msg.message.options.start || 0;
2606
- const end = msg.message.options.end || Date.now() + 5000000;
2607
- if (!this.sqlDPs[id]) {
2928
+ const id = msg.message?.id;
2929
+ const opts = msg.message?.options || {};
2930
+ const start = opts.start ? (0, messages_1.toTimestamp)(opts.start) : 0;
2931
+ const end = opts.end ? (0, messages_1.toTimestamp)(opts.end) : Date.now() + 5000000;
2932
+ if (!(0, messages_1.isId)(id) || start === undefined || end === undefined) {
2933
+ this.sendTo(msg.from, msg.command, { result: [], step: null, error: `Invalid call: ${JSON.stringify(msg.message)}` }, msg.callback);
2934
+ }
2935
+ else if (!this.sqlDPs[id]) {
2608
2936
  this.sendTo(msg.from, msg.command, { result: [], step: null, error: 'Not enabled' }, msg.callback);
2609
2937
  }
2610
2938
  else {
@@ -2635,6 +2963,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
2635
2963
  else {
2636
2964
  ignoreNull = false; // include nulls
2637
2965
  }
2966
+ if (msg.message.id !== '*' && !(0, messages_1.isId)(msg.message.id)) {
2967
+ return this.sendTo(msg.from, msg.command, { result: [], step: null, error: `Invalid call: ID missing in ${JSON.stringify(msg.message)}` }, msg.callback);
2968
+ }
2638
2969
  const logId = (msg.message.id ? msg.message.id : 'all') + Date.now() + Math.random();
2639
2970
  const options = {
2640
2971
  id: msg.message.id === '*' ? null : msg.message.id,
@@ -2676,25 +3007,30 @@ class SqlAdapter extends adapter_core_1.Adapter {
2676
3007
  options.count = 500;
2677
3008
  }
2678
3009
  }
2679
- try {
2680
- if (options.start && typeof options.start !== 'number') {
2681
- options.start = new Date(options.start).getTime();
3010
+ // `new Date()` never throws: an unparsable date gave NaN, which reached the database as `ts >= NaN`.
3011
+ // A numeric string ("1700000000000") is a timestamp too - as a date it is NaN as well.
3012
+ if (options.start) {
3013
+ options.start = (0, messages_1.toTimestamp)(options.start);
3014
+ if (options.start === undefined) {
3015
+ return this.sendTo(msg.from, msg.command, {
3016
+ error: `Invalid call. Start date ${JSON.stringify(msg.message.options.start)} is not a valid date`,
3017
+ }, msg.callback);
2682
3018
  }
2683
3019
  }
2684
- catch {
2685
- return this.sendTo(msg.from, msg.command, {
2686
- error: `Invalid call. Start date ${JSON.stringify(options.start)} is not a valid date`,
2687
- }, msg.callback);
3020
+ options.end = (0, messages_1.toTimestamp)(options.end);
3021
+ if (options.end === undefined) {
3022
+ return this.sendTo(msg.from, msg.command, { error: `Invalid call. End date ${JSON.stringify(msg.message.options.end)} is not a valid date` }, msg.callback);
2688
3023
  }
2689
- try {
2690
- if (options.end && typeof options.end !== 'number') {
2691
- options.end = new Date(options.end).getTime();
2692
- }
3024
+ if (options.count < 0 || options.limit < 0) {
3025
+ return this.sendTo(msg.from, msg.command, { error: `Invalid call. count and limit must not be negative` }, msg.callback);
2693
3026
  }
2694
- catch {
2695
- return this.sendTo(msg.from, msg.command, {
2696
- error: `Invalid call. End date ${JSON.stringify(options.end)} is not a valid date`,
2697
- }, msg.callback);
3027
+ // The client can send the borders of the intervals itself, e.g. the local days of a chart: a fixed step does
3028
+ // not fit a day with 23 or 25 hours. The database must then be read for exactly the range they cover.
3029
+ const intervalBorders = (0, aggregate_1.parseIntervalBorders)(msg.message.options.intervalBorders, options.limit);
3030
+ if (intervalBorders) {
3031
+ options.intervalBorders = intervalBorders;
3032
+ options.start = intervalBorders[0];
3033
+ options.end = intervalBorders[intervalBorders.length - 1];
2698
3034
  }
2699
3035
  if (!options.start && options.count) {
2700
3036
  options.returnNewestEntries = true;
@@ -2899,13 +3235,22 @@ class SqlAdapter extends adapter_core_1.Adapter {
2899
3235
  for (let i = res.length - 1; i >= 0; i--) {
2900
3236
  if (res[i].state.ts === state.ts) {
2901
3237
  if (state.val !== undefined) {
2902
- res[i].state.val = state.val;
3238
+ const val = (0, messages_1.valueForTable)(res[i].table, state.val);
3239
+ if (val instanceof Error) {
3240
+ cb?.(new Error(`Cannot update ${id}: ${val.message}`));
3241
+ return;
3242
+ }
3243
+ res[i].state.val = val;
2903
3244
  }
2904
3245
  if (state.q !== undefined && res[i].state.q !== undefined) {
2905
3246
  res[i].state.q = state.q;
2906
3247
  }
2907
3248
  if (state.from !== undefined && res[i].from !== undefined) {
2908
3249
  res[i].state.from = state.from;
3250
+ // `from` is stored by its number (see `pushValueIntoDB`), not by the name
3251
+ if (this.from[state.from] !== undefined) {
3252
+ res[i].from = this.from[state.from];
3253
+ }
2909
3254
  }
2910
3255
  if (state.ack !== undefined) {
2911
3256
  res[i].state.ack = state.ack;
@@ -2950,7 +3295,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
2950
3295
  }
2951
3296
  /** Build and execute the UPDATE query for one entry of one datapoint */
2952
3297
  #updateInDb(id, table, index, state, cb) {
2953
- const query = this.sqlFuncs.update(this.config.dbname, index, state, this.from[state.from], table);
3298
+ // the dialects write numbers and booleans into the statement as they are: check the value first
3299
+ const val = state.val === undefined ? undefined : (0, messages_1.valueForTable)(table, state.val);
3300
+ if (val instanceof Error) {
3301
+ cb?.(new Error(`Cannot update ${id}: ${val.message}`));
3302
+ return;
3303
+ }
3304
+ const query = this.sqlFuncs.update(this.config.dbname, index, { ts: state.ts, val, q: state.q, ack: state.ack }, state.from !== undefined ? this.from[state.from] : undefined, table);
2954
3305
  this.#executeQueries(id, [query], cb);
2955
3306
  }
2956
3307
  #delete(id, state, cb) {
@@ -2959,26 +3310,16 @@ class SqlAdapter extends adapter_core_1.Adapter {
2959
3310
  if (this.sqlDPs[id]) {
2960
3311
  const res = this.sqlDPs[id].list;
2961
3312
  if (res) {
2962
- if (!state.ts && !state.start && !state.end) {
3313
+ if (state.mode === 'all') {
2963
3314
  this.sqlDPs[id].list = [];
2964
3315
  }
2965
3316
  else {
2966
3317
  for (let i = res.length - 1; i >= 0; i--) {
2967
- if (state.start && state.end) {
3318
+ if (state.mode === 'range') {
2968
3319
  if (res[i].state.ts >= state.start && res[i].state.ts <= state.end) {
2969
3320
  res.splice(i, 1);
2970
3321
  }
2971
3322
  }
2972
- else if (state.start) {
2973
- if (res[i].state.ts >= state.start) {
2974
- res.splice(i, 1);
2975
- }
2976
- }
2977
- else if (state.end) {
2978
- if (res[i].state.ts <= state.end) {
2979
- res.splice(i, 1);
2980
- }
2981
- }
2982
3323
  else if (res[i].state.ts === state.ts) {
2983
3324
  res.splice(i, 1);
2984
3325
  found = true;
@@ -3018,13 +3359,18 @@ class SqlAdapter extends adapter_core_1.Adapter {
3018
3359
  * (or no longer) enabled for logging, i.e., that are not in `sqlDPs`.
3019
3360
  */
3020
3361
  #readIdIndexAndType(id, cb) {
3362
+ if (!(0, messages_1.isId)(id)) {
3363
+ // without a name `getIdSelect` returns every datapoint, and the first row would be taken
3364
+ setImmediate(() => cb(new Error('No ID given')));
3365
+ return;
3366
+ }
3021
3367
  if (!this.clientPool) {
3022
3368
  this.log.warn(`No connection to the database, cannot look up "${id}"`);
3023
3369
  setImmediate(() => cb(new Error('No Connection to database')));
3024
3370
  return;
3025
3371
  }
3026
3372
  const query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
3027
- this.log.debug(query);
3373
+ this.#debugStatement(query);
3028
3374
  this.borrowClientFromPool((err, client) => {
3029
3375
  if (err || !client) {
3030
3376
  this.returnClientToPool(client);
@@ -3034,7 +3380,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3034
3380
  client.execute(query, (err, rows) => {
3035
3381
  this.returnClientToPool(client);
3036
3382
  if (err) {
3037
- this.log.error(`Cannot select ${query}: ${err}`);
3383
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3038
3384
  cb(err);
3039
3385
  }
3040
3386
  else if (!rows?.length) {
@@ -3060,13 +3406,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
3060
3406
  }
3061
3407
  /** Build the DELETE query for one table of one datapoint */
3062
3408
  #buildDeleteQuery(table, index, state) {
3063
- if (state.start && state.end) {
3409
+ // The mode is explicit: with `if (state.start && state.end)` an unparsable start (NaN) or a
3410
+ // start of 0 fell through to "delete every entry of the datapoint".
3411
+ if (state.mode === 'range') {
3064
3412
  return this.sqlFuncs.deleteFromTable(this.config.dbname, table, index, state.start, state.end);
3065
3413
  }
3066
- if (state.ts) {
3414
+ if (state.mode === 'one') {
3067
3415
  return this.sqlFuncs.deleteFromTable(this.config.dbname, table, index, state.ts);
3068
3416
  }
3069
- // delete all entries for ID
3070
3417
  return this.sqlFuncs.deleteFromTable(this.config.dbname, table, index);
3071
3418
  }
3072
3419
  /** Execute the given queries one after another and stop at the first error */
@@ -3084,7 +3431,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3084
3431
  this.#executeQueries(id, queries, cb);
3085
3432
  };
3086
3433
  if (!this.multiRequests) {
3087
- if (this.tasks.length > MAX_TASKS) {
3434
+ if (this.#queueFull()) {
3088
3435
  const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
3089
3436
  this.log.error(error);
3090
3437
  cb?.(new Error(error));
@@ -3098,204 +3445,84 @@ class SqlAdapter extends adapter_core_1.Adapter {
3098
3445
  this._executeQuery(query, id, next);
3099
3446
  }
3100
3447
  }
3101
- updateState(msg) {
3102
- if (!msg.message) {
3103
- this.log.error('updateState called with invalid data');
3104
- return this.sendTo(msg.from, msg.command, {
3105
- error: `Invalid call: ${JSON.stringify(msg)}`,
3106
- }, msg.callback);
3107
- }
3108
- let id;
3109
- if (Array.isArray(msg.message)) {
3110
- this.log.debug(`updateState ${msg.message.length} items`);
3111
- for (let i = 0; i < msg.message.length; i++) {
3112
- id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
3113
- if (msg.message[i].state && typeof msg.message[i].state === 'object') {
3114
- this.update(id, msg.message[i].state);
3115
- }
3116
- else {
3117
- this.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
3118
- }
3448
+ /**
3449
+ * Execute the requests of one `update`/`delete`/`deleteAll` message and answer it once, after the last
3450
+ * one has finished. Entries the parser refused and entries the database refused are both reported;
3451
+ * before, a list of entries was answered with `success: true` while the writes were still running.
3452
+ */
3453
+ #runRequests(msg, parsed, run) {
3454
+ const errors = [...parsed.errors];
3455
+ const answer = () => {
3456
+ if (!msg.callback) {
3457
+ return;
3119
3458
  }
3120
- }
3121
- else if (msg.message.state && Array.isArray(msg.message.state)) {
3122
- this.log.debug(`updateState ${msg.message.state.length} items`);
3123
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3124
- for (let j = 0; j < msg.message.state.length; j++) {
3125
- if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
3126
- this.update(id, msg.message.state[j]);
3127
- }
3128
- else {
3129
- this.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
3459
+ this.sendTo(msg.from, msg.command, errors.length
3460
+ ? {
3461
+ error: errors.length === 1 ? errors[0] : `${errors.length} errors: ${errors.join('; ')}`,
3462
+ errors,
3463
+ sqlConnected: !!this.clientPool,
3130
3464
  }
3465
+ : { success: true, sqlConnected: !!this.clientPool }, msg.callback);
3466
+ };
3467
+ if (!parsed.requests.length) {
3468
+ if (errors.length) {
3469
+ this.log.warn(`${msg.command}: ${errors.join('; ')}`);
3131
3470
  }
3471
+ answer();
3472
+ return;
3132
3473
  }
3133
- else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
3134
- this.log.debug('updateState 1 item');
3135
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3136
- return this.update(id, msg.message.state, err => this.sendTo(msg.from, msg.command, err
3137
- ? { error: err.message, sqlConnected: !!this.clientPool }
3138
- : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3139
- }
3140
- else {
3141
- this.log.error('updateState called with invalid data');
3142
- return this.sendTo(msg.from, msg.command, {
3143
- error: `Invalid call: ${JSON.stringify(msg)}`,
3144
- }, msg.callback);
3145
- }
3146
- this.sendTo(msg.from, msg.command, {
3147
- success: true,
3148
- sqlConnected: !!this.clientPool,
3149
- }, msg.callback);
3150
- }
3151
- deleteHistoryEntry(msg) {
3152
- if (!msg.message) {
3153
- this.log.error('deleteHistoryEntry called with invalid data');
3154
- return this.sendTo(msg.from, msg.command, {
3155
- error: `Invalid call: ${JSON.stringify(msg)}`,
3156
- }, msg.callback);
3157
- }
3158
- let id;
3159
- if (Array.isArray(msg.message)) {
3160
- this.log.debug(`deleteHistoryEntry ${msg.message.length} items`);
3161
- for (let i = 0; i < msg.message.length; i++) {
3162
- id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
3163
- // {id: 'blabla', ts: 892}
3164
- if (msg.message[i].ts) {
3165
- this.#delete(id, { ts: msg.message[i].ts });
3166
- }
3167
- else if (msg.message[i].start) {
3168
- if (typeof msg.message[i].start === 'string') {
3169
- msg.message[i].start = new Date(msg.message[i].start).getTime();
3170
- }
3171
- if (typeof msg.message[i].end === 'string') {
3172
- msg.message[i].end = new Date(msg.message[i].end).getTime();
3173
- }
3174
- this.#delete(id, { start: msg.message[i].start, end: msg.message[i].end || Date.now() });
3175
- }
3176
- else if (typeof msg.message[i].state === 'object' &&
3177
- msg.message[i].state &&
3178
- msg.message[i].state.ts) {
3179
- this.#delete(id, { ts: msg.message[i].state.ts });
3180
- }
3181
- else if (typeof msg.message[i].state === 'object' &&
3182
- msg.message[i].state &&
3183
- msg.message[i].state.start) {
3184
- if (typeof msg.message[i].state.start === 'string') {
3185
- msg.message[i].state.start = new Date(msg.message[i].state.start).getTime();
3186
- }
3187
- if (typeof msg.message[i].state.end === 'string') {
3188
- msg.message[i].state.end = new Date(msg.message[i].state.end).getTime();
3189
- }
3190
- this.#delete(id, {
3191
- start: msg.message[i].state.start,
3192
- end: msg.message[i].state.end || Date.now(),
3193
- });
3194
- }
3195
- else {
3196
- this.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
3474
+ this.log.debug(`${msg.command} ${parsed.requests.length} items`);
3475
+ let pending = parsed.requests.length;
3476
+ for (const request of parsed.requests) {
3477
+ run(request, err => {
3478
+ if (err) {
3479
+ errors.push(err.message);
3197
3480
  }
3198
- }
3199
- }
3200
- else if (msg.message.state && Array.isArray(msg.message.state)) {
3201
- this.log.debug(`deleteHistoryEntry ${msg.message.state.length} items`);
3202
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3203
- for (let j = 0; j < msg.message.state.length; j++) {
3204
- if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
3205
- if (msg.message.state[j].ts) {
3206
- this.#delete(id, { ts: msg.message.state[j].ts });
3207
- }
3208
- else if (msg.message.state[j].start) {
3209
- if (typeof msg.message.state[j].start === 'string') {
3210
- msg.message.state[j].start = new Date(msg.message.state[j].start).getTime();
3211
- }
3212
- if (typeof msg.message.state[j].end === 'string') {
3213
- msg.message.state[j].end = new Date(msg.message.state[j].end).getTime();
3214
- }
3215
- this.#delete(id, {
3216
- start: msg.message.state[j].start,
3217
- end: msg.message.state[j].end || Date.now(),
3218
- });
3481
+ if (!--pending) {
3482
+ if (errors.length) {
3483
+ this.log.warn(`${msg.command}: ${errors.join('; ')}`);
3219
3484
  }
3485
+ answer();
3220
3486
  }
3221
- else if (msg.message.state[j] && typeof msg.message.state[j] === 'number') {
3222
- this.#delete(id, { ts: msg.message.state[j] });
3223
- }
3224
- else {
3225
- this.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
3226
- }
3227
- }
3228
- }
3229
- else if (msg.message.ts && Array.isArray(msg.message.ts)) {
3230
- this.log.debug(`deleteHistoryEntry ${msg.message.ts.length} items`);
3231
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3232
- for (let j = 0; j < msg.message.ts.length; j++) {
3233
- if (msg.message.ts[j] && typeof msg.message.ts[j] === 'number') {
3234
- this.#delete(id, { ts: msg.message.ts[j] });
3235
- }
3236
- else {
3237
- this.log.warn(`Invalid state for ${JSON.stringify(msg.message.ts[j])}`);
3238
- }
3239
- }
3240
- }
3241
- else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
3242
- this.log.debug('deleteHistoryEntry 1 item');
3243
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3244
- return this.#delete(id, { ts: msg.message.state.ts }, err => this.sendTo(msg.from, msg.command, err
3245
- ? { error: err.message, sqlConnected: !!this.clientPool }
3246
- : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3247
- }
3248
- else if (msg.message.id && msg.message.ts && typeof msg.message.ts === 'number') {
3249
- this.log.debug('deleteHistoryEntry 1 item');
3250
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3251
- return this.#delete(id, { ts: msg.message.ts }, err => this.sendTo(msg.from, msg.command, err
3252
- ? { error: err.message, sqlConnected: !!this.clientPool }
3253
- : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3254
- }
3255
- else {
3256
- this.log.error('deleteHistoryEntry called with invalid data');
3257
- return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
3487
+ });
3258
3488
  }
3259
- this.sendTo(msg.from, msg.command, {
3260
- success: true,
3261
- sqlConnected: !!this.clientPool,
3262
- }, msg.callback);
3489
+ }
3490
+ updateState(msg) {
3491
+ this.#runRequests(msg, (0, messages_1.parseUpdateRequests)(msg.message, id => this.aliasMap[id] || id), (request, cb) => this.update(request.id, request.state, cb));
3492
+ }
3493
+ deleteHistoryEntry(msg) {
3494
+ this.#runRequests(msg, (0, messages_1.parseDeleteRequests)(msg.message, false, Date.now(), id => this.aliasMap[id] || id), (request, cb) => this.#delete(request.id, this.#deleteRange(request), cb));
3263
3495
  }
3264
3496
  deleteStateAll(msg) {
3265
- if (!msg.message) {
3266
- this.log.error('deleteStateAll called with invalid data');
3267
- return this.sendTo(msg.from, msg.command, {
3268
- error: `Invalid call: ${JSON.stringify(msg)}`,
3269
- }, msg.callback);
3270
- }
3271
- let id;
3272
- if (Array.isArray(msg.message)) {
3273
- this.log.debug(`deleteStateAll ${msg.message.length} items`);
3274
- for (let i = 0; i < msg.message.length; i++) {
3275
- id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
3276
- this.#delete(id, {});
3277
- }
3278
- }
3279
- else if (msg.message.id) {
3280
- this.log.debug('deleteStateAll 1 item');
3281
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3282
- return this.#delete(id, {}, err => this.sendTo(msg.from, msg.command, err
3283
- ? { error: err.message, sqlConnected: !!this.clientPool }
3284
- : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3497
+ this.#runRequests(msg, (0, messages_1.parseDeleteRequests)(msg.message, true, Date.now(), id => this.aliasMap[id] || id), (request, cb) => this.#delete(request.id, { mode: 'all' }, cb));
3498
+ }
3499
+ #deleteRange(request) {
3500
+ if ('ts' in request) {
3501
+ return { mode: 'one', ts: request.ts };
3285
3502
  }
3286
- else {
3287
- this.log.error('deleteStateAll called with invalid data');
3288
- return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
3503
+ if ('start' in request) {
3504
+ return { mode: 'range', start: request.start, end: request.end };
3289
3505
  }
3290
- this.sendTo(msg.from, msg.command, {
3291
- success: true,
3292
- sqlConnected: !!this.clientPool,
3293
- }, msg.callback);
3506
+ return { mode: 'all' };
3294
3507
  }
3295
3508
  storeStatePushData(id, state, applyRules) {
3509
+ if (!(0, messages_1.isId)(id)) {
3510
+ throw new Error(`ID ${JSON.stringify(id)} is not valid`);
3511
+ }
3296
3512
  if (!state || typeof state !== 'object') {
3297
3513
  throw new Error(`State ${JSON.stringify(state)} for ${id} is not valid`);
3298
3514
  }
3515
+ // `ts` and `q` are written into the statement as numbers: refuse anything else here, the
3516
+ // conversion in `prepareTaskReadDbId` only runs once the index of the datapoint is known
3517
+ const ts = state.ts === undefined || state.ts === null ? Date.now() : (0, messages_1.toTimestamp)(state.ts);
3518
+ if (ts === undefined) {
3519
+ throw new Error(`Timestamp ${JSON.stringify(state.ts)} for ${id} is not valid`);
3520
+ }
3521
+ const q = (0, messages_1.toQuality)(state.q);
3522
+ if (q === undefined) {
3523
+ throw new Error(`Quality ${JSON.stringify(state.q)} for ${id} is not valid`);
3524
+ }
3525
+ state = { ...state, ts, q, ack: !!state.ack, from: typeof state.from === 'string' ? state.from : '' };
3299
3526
  if (!this.sqlDPs[id]?.config) {
3300
3527
  if (applyRules) {
3301
3528
  throw new Error(`sql not enabled for ${id}, so can not apply the rules as requested`);
@@ -3407,12 +3634,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
3407
3634
  * Read the stored values of one datapoint page by page.
3408
3635
  *
3409
3636
  * In contrast to `getHistory`, the rows are returned exactly as they are in the database: no aggregation,
3410
- * no interpolation, no border values and no rounding. Together with the total number of matching entries,
3411
- * so that a table can page through them. Works for datapoints that are not (or no longer) enabled for
3412
- * logging too.
3637
+ * no interpolation, no border values and no rounding - only `ts` is always a number. Together with the total
3638
+ * number of matching entries (unless `noTotal` is set), so that a table can page through them. Works for
3639
+ * datapoints that are not (or no longer) enabled for logging too.
3413
3640
  */
3414
3641
  getRawEntries(msg) {
3415
- if (!msg.message?.id) {
3642
+ if (!(0, messages_1.isId)(msg.message?.id)) {
3416
3643
  this.log.error('getRawEntries called with invalid data');
3417
3644
  return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
3418
3645
  }
@@ -3430,6 +3657,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3430
3657
  limit: Math.min(Math.max(parseInt(msg.message.limit, 10) || 100, 1), MAX_RAW_ENTRIES),
3431
3658
  offset: Math.max(parseInt(msg.message.offset, 10) || 0, 0),
3432
3659
  sort: msg.message.sort === 'asc' ? 'asc' : 'desc',
3660
+ noTotal: msg.message.noTotal === true,
3433
3661
  };
3434
3662
  this.#readIdIndexAndType(id, (err, index, type) => {
3435
3663
  if (err || index === undefined || type === undefined) {
@@ -3441,24 +3669,22 @@ class SqlAdapter extends adapter_core_1.Adapter {
3441
3669
  this.returnClientToPool(client);
3442
3670
  return this.sendTo(msg.from, msg.command, { error: (err || new Error('No client')).message }, msg.callback);
3443
3671
  }
3444
- const countQuery = this.sqlFuncs.getRawEntriesCount(this.config.dbname, table, index, options);
3445
- this.log.debug(countQuery);
3446
- client.execute(countQuery, (err, rows) => {
3447
- if (err) {
3448
- this.returnClientToPool(client);
3449
- this.log.error(`Cannot select ${countQuery}: ${err}`);
3450
- return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3451
- }
3452
- // PostgreSQL returns the count of a bigint column as string
3453
- const total = rows?.[0] ? parseInt(rows[0].total, 10) || 0 : 0;
3672
+ const readEntries = (total) => {
3454
3673
  const query = this.sqlFuncs.getRawEntries(this.config.dbname, table, index, options);
3455
- this.log.debug(query);
3674
+ this.#debugStatement(query);
3456
3675
  client.execute(query, (err, rows) => {
3457
3676
  this.returnClientToPool(client);
3458
3677
  if (err) {
3459
- this.log.error(`Cannot select ${query}: ${err}`);
3678
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3460
3679
  return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3461
3680
  }
3681
+ // PostgreSQL and MS SQL return a bigint column as string
3682
+ const result = rows || [];
3683
+ for (const row of result) {
3684
+ if (typeof row.ts === 'string') {
3685
+ row.ts = parseInt(row.ts, 10);
3686
+ }
3687
+ }
3462
3688
  this.sendTo(msg.from, msg.command, {
3463
3689
  id: msg.message.id,
3464
3690
  index,
@@ -3468,9 +3694,25 @@ class SqlAdapter extends adapter_core_1.Adapter {
3468
3694
  limit: options.limit,
3469
3695
  offset: options.offset,
3470
3696
  sort: options.sort,
3471
- result: rows || [],
3697
+ result,
3472
3698
  }, msg.callback);
3473
3699
  });
3700
+ };
3701
+ if (options.noTotal) {
3702
+ // the count is a scan of the whole range - the export of the data browser reads it in
3703
+ // windows and counts only once, with its first request
3704
+ return readEntries(undefined);
3705
+ }
3706
+ const countQuery = this.sqlFuncs.getRawEntriesCount(this.config.dbname, table, index, options);
3707
+ this.#debugStatement(countQuery);
3708
+ client.execute(countQuery, (err, rows) => {
3709
+ if (err) {
3710
+ this.returnClientToPool(client);
3711
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(countQuery)}: ${err}`);
3712
+ return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3713
+ }
3714
+ // PostgreSQL returns the count of a bigint column as string
3715
+ readEntries(rows?.[0] ? parseInt(rows[0].total, 10) || 0 : 0);
3474
3716
  });
3475
3717
  });
3476
3718
  });
@@ -3647,7 +3889,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3647
3889
  }
3648
3890
  getDatapoints(msg) {
3649
3891
  const query = this.sqlFuncs.getIdSelect(this.config.dbname);
3650
- this.log.debug(query);
3892
+ this.#debugStatement(query);
3651
3893
  this.borrowClientFromPool((err, client) => {
3652
3894
  if (err || !client) {
3653
3895
  this.returnClientToPool(client);
@@ -3656,7 +3898,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3656
3898
  client.execute(query, (err, rows) => {
3657
3899
  this.returnClientToPool(client);
3658
3900
  if (err) {
3659
- this.log.error(`Cannot select ${query}: ${err}`);
3901
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3660
3902
  return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3661
3903
  }
3662
3904
  const result = (rows || [])
@@ -3673,20 +3915,20 @@ class SqlAdapter extends adapter_core_1.Adapter {
3673
3915
  getDpOverview(msg) {
3674
3916
  const result = [];
3675
3917
  const query = this.sqlFuncs.getIdSelect(this.config.dbname);
3676
- this.log.info(query);
3918
+ this.log.info((0, statement_1.statementToString)(query));
3677
3919
  this.borrowClientFromPool((err, client) => {
3678
3920
  if (err || !client) {
3679
3921
  this.returnClientToPool(client);
3680
3922
  return this.sendTo(msg.from, msg.command, {
3681
- error: `Cannot select ${query}: ${err || 'no client'}`,
3923
+ error: `Cannot select ${(0, statement_1.statementToString)(query)}: ${err || 'no client'}`,
3682
3924
  }, msg.callback);
3683
3925
  }
3684
3926
  client.execute(query, (err, rows /* , fields */) => {
3685
3927
  if (err) {
3686
3928
  this.returnClientToPool(client);
3687
- this.log.error(`Cannot select ${query}: ${err}`);
3929
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3688
3930
  this.sendTo(msg.from, msg.command, {
3689
- error: `Cannot select ${query}: ${err}`,
3931
+ error: `Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`,
3690
3932
  }, msg.callback);
3691
3933
  return;
3692
3934
  }
@@ -3720,13 +3962,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
3720
3962
  }
3721
3963
  else {
3722
3964
  const query = this.sqlFuncs.getFirstTs(this.config.dbname, dbNames[typeId]);
3723
- this.log.info(query);
3965
+ this.log.info((0, statement_1.statementToString)(query));
3724
3966
  client.execute(query, (err, rows /* , fields */) => {
3725
3967
  if (err) {
3726
3968
  this.returnClientToPool(client);
3727
- this.log.error(`Cannot select ${query}: ${err}`);
3969
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3728
3970
  this.sendTo(msg.from, msg.command, {
3729
- error: `Cannot select ${query}: ${err}`,
3971
+ error: `Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`,
3730
3972
  }, msg.callback);
3731
3973
  return;
3732
3974
  }
@@ -3896,7 +4138,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
3896
4138
  }
3897
4139
  if (config.maxConnections !== undefined && config.dbtype !== 'sqlite') {
3898
4140
  config.maxConnections = parseInt(config.maxConnections, 10);
3899
- if (config.maxConnections !== 0 && !config.maxConnections) {
4141
+ if (!config.maxConnections || config.maxConnections < 1) {
4142
+ // 0 is not "unlimited": every borrow would wait for a free connection that never comes
4143
+ this.log.warn(`Invalid value for maximum concurrent connections "${this.config.maxConnections}", using 100`);
3900
4144
  config.maxConnections = 100;
3901
4145
  }
3902
4146
  }