iobroker.sql 4.3.0 → 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 (71) hide show
  1. package/README.md +48 -6
  2. package/admin/custom/assets/{Components-CWJJ3bu1.js → Components-Biqn0PcX.js} +1 -1
  3. package/admin/custom/assets/DataBrowser-DTTVoTBj.js +7 -0
  4. package/admin/custom/assets/{_virtual_mf-localSharedImportMap___mfe_internal__SqlComponentsSet__mf_owner__1-D9xu_nUa.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__233965516817701__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-D_KAxrKJ.js → _virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-DiZBpJW2.js} +541 -303
  6. package/admin/custom/assets/{_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__233965516817701__loadShare__shared-CdBNI0v_.js → _virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__loadShare__shared-DmziGsfK.js} +2 -2
  7. package/admin/custom/assets/{_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__233965516817701__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-CH3Bc0Pg.js → _virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-CY-VVm-e.js} +5 -5
  8. package/admin/custom/assets/{_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__233965516817701__prebuild__react_mf_2_dom_mf_1_client__prebuild__-DKp49xnK.js → _virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__prebuild__react_mf_2_dom_mf_1_client__prebuild__-SIym-UC8.js} +1 -1
  9. package/admin/custom/assets/{dist-B3E7IYuQ.js → dist-ChhOvPa4.js} +1 -1
  10. package/admin/custom/assets/helpers-CwABI1ut.js +1 -0
  11. package/admin/custom/assets/hostInit-Bp3K06oA.js +1 -0
  12. package/admin/custom/assets/index-BACEccc0.js +1 -0
  13. package/admin/custom/assets/{lib-3uQoRWeQ.js → lib-BlyWjmi5.js} +1 -1
  14. package/admin/custom/assets/{mf-entry-bootstrap-0-3e3d8b70.js → mf-entry-bootstrap-0-03451604.js} +3 -3
  15. package/admin/custom/assets/pendingShares-BhtJBPS2.js +2 -0
  16. package/admin/custom/assets/{utils-Bi7ATSfV.js → utils-Cqsn1la4.js} +1 -1
  17. package/admin/custom/customComponents.js +2 -2
  18. package/admin/custom/i18n/de.json +15 -0
  19. package/admin/custom/i18n/en.json +15 -0
  20. package/admin/custom/i18n/es.json +15 -0
  21. package/admin/custom/i18n/fr.json +15 -0
  22. package/admin/custom/i18n/it.json +15 -0
  23. package/admin/custom/i18n/nl.json +15 -0
  24. package/admin/custom/i18n/pl.json +15 -0
  25. package/admin/custom/i18n/pt.json +15 -0
  26. package/admin/custom/i18n/ru.json +15 -0
  27. package/admin/custom/i18n/uk.json +15 -0
  28. package/admin/custom/i18n/zh-cn.json +15 -0
  29. package/admin/custom/mf-manifest.json +1 -1
  30. package/admin/jsonConfig.json +3 -0
  31. package/build/lib/connection-factory.js +5 -0
  32. package/build/lib/connection-factory.js.map +1 -1
  33. package/build/lib/errors.js +6 -0
  34. package/build/lib/errors.js.map +1 -1
  35. package/build/lib/messages.js +250 -0
  36. package/build/lib/messages.js.map +1 -1
  37. package/build/lib/mssql.js +19 -15
  38. package/build/lib/mssql.js.map +1 -1
  39. package/build/lib/mysql-client.js +87 -13
  40. package/build/lib/mysql-client.js.map +1 -1
  41. package/build/lib/mysql.js +186 -135
  42. package/build/lib/mysql.js.map +1 -1
  43. package/build/lib/names.js +47 -0
  44. package/build/lib/names.js.map +1 -0
  45. package/build/lib/optional-drivers.js.map +1 -1
  46. package/build/lib/postgresql.js +23 -13
  47. package/build/lib/postgresql.js.map +1 -1
  48. package/build/lib/sql-client-pool.js +7 -1
  49. package/build/lib/sql-client-pool.js.map +1 -1
  50. package/build/lib/sql-client.js +25 -5
  51. package/build/lib/sql-client.js.map +1 -1
  52. package/build/lib/sql-string.js +57 -0
  53. package/build/lib/sql-string.js.map +1 -0
  54. package/build/lib/sqlite.js +21 -14
  55. package/build/lib/sqlite.js.map +1 -1
  56. package/build/lib/statement.js +27 -0
  57. package/build/lib/statement.js.map +1 -0
  58. package/build/lib/values.js +27 -0
  59. package/build/lib/values.js.map +1 -1
  60. package/build/lib/write-buffer.js +80 -0
  61. package/build/lib/write-buffer.js.map +1 -0
  62. package/build/main.js +562 -351
  63. package/build/main.js.map +1 -1
  64. package/io-package.json +14 -14
  65. package/package.json +3 -3
  66. package/admin/custom/assets/DataBrowser-CXd6Wilm.js +0 -1
  67. package/admin/custom/assets/helpers-DE61bb74.js +0 -1
  68. package/admin/custom/assets/hostInit-DI6V2HBN.js +0 -1
  69. package/admin/custom/assets/index-DVNkzy1M.js +0 -1
  70. package/admin/custom/assets/pendingShares-Cg-jucDv.js +0 -2
  71. /package/admin/custom/assets/{_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__233965516817701__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__--SURtz9t.js → _virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__264649249385412__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__--SURtz9t.js} +0 -0
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) {
@@ -355,6 +365,19 @@ class SqlAdapter extends adapter_core_1.Adapter {
355
365
  },
356
366
  });
357
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
+ }
358
381
  borrowClientFromPool(callback) {
359
382
  if (!this.clientPool) {
360
383
  this.setConnected(false);
@@ -379,7 +402,16 @@ class SqlAdapter extends adapter_core_1.Adapter {
379
402
  // drops the flagged client on the next borrow. This just makes the reconnect
380
403
  // visible in the log.
381
404
  if (client.on && client.listenerCount && !client.listenerCount('error')) {
382
- 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
+ });
383
415
  }
384
416
  // A real, working connection was handed out - this, not the mere existence of a pool
385
417
  // object, is what info.connection reports (#374).
@@ -652,6 +684,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
652
684
  const poolOptions = {
653
685
  max_idle: this.config.dbtype === 'sqlite' ? 1 : 2,
654
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
+ }
655
695
  if (this.config.maxConnections) {
656
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
657
697
  poolOptions.max_wait = 10000; // hard code for now
@@ -752,7 +792,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
752
792
  this.clientPool = new mssql_client_1.MSSQLClientPool(poolOptions, msSQLOptions);
753
793
  }
754
794
  else if (this.config.dbtype === 'mysql' && mySQLOptions) {
755
- 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
+ });
756
801
  }
757
802
  else if (this.config.dbtype === 'sqlite' && sqLiteOptions) {
758
803
  this.clientPool = new sqlite3_client_1.SQLite3ClientPool(poolOptions, sqLiteOptions);
@@ -1003,7 +1048,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1003
1048
  // execute custom query
1004
1049
  query(msg) {
1005
1050
  if (!this.multiRequests) {
1006
- if (this.tasks.length > MAX_TASKS) {
1051
+ if (this.#queueFull()) {
1007
1052
  const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
1008
1053
  this.log.error(error);
1009
1054
  this.sendTo(msg.from, msg.command, { error }, msg.callback);
@@ -1114,6 +1159,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
1114
1159
  let datapointsPending = 0;
1115
1160
  let allDispatched = false;
1116
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
+ }
1117
1169
  if (this.clientPool) {
1118
1170
  this.clientPool.close();
1119
1171
  this.activeConnections = 0;
@@ -1165,10 +1217,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
1165
1217
  // Values this datapoint has to write before its buffer goes out, so that the boundary
1166
1218
  // markers keep their order relative to the buffered values.
1167
1219
  let pendingWrites = 0;
1220
+ let flushed = false;
1168
1221
  const flushBuffer = () => {
1169
- if (pendingWrites) {
1222
+ if (pendingWrites || flushed) {
1170
1223
  return;
1171
1224
  }
1225
+ flushed = true;
1172
1226
  const buffered = this.sqlDPs[id]?.list;
1173
1227
  // Not every entry in sqlDPs is a configured datapoint: storeState, getHistory and
1174
1228
  // the object view create stubs with `sqlDPs[id] ||= {}` just to carry an index, and
@@ -1261,31 +1315,50 @@ class SqlAdapter extends adapter_core_1.Adapter {
1261
1315
  return;
1262
1316
  }
1263
1317
  this.finished = [callback];
1264
- let dpcount = 0;
1265
- let delay = 0;
1266
- for (const id in this.sqlDPs) {
1267
- if (!Object.prototype.hasOwnProperty.call(this.sqlDPs, id)) {
1268
- continue;
1269
- }
1270
- dpcount++;
1271
- datapointsPending++;
1272
- delay += dpcount % 50 === 0 ? 1000 : 0;
1273
- setTimeout(finishId, delay, id);
1274
- }
1275
- // Only now may a datapoint reporting in finish the whole run: the dispatch above is spread
1276
- // 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.
1277
1331
  allDispatched = true;
1278
- if (!dpcount && callback) {
1332
+ if (dpcount && datapointsPending <= 0) {
1333
+ allFinished();
1334
+ }
1335
+ if (!dpcount) {
1279
1336
  if (this.clientPool) {
1280
1337
  this.clientPool.close();
1281
1338
  this.activeConnections = 0;
1282
1339
  this.clientPool = null;
1283
1340
  this.setConnected(false);
1284
1341
  }
1285
- callback();
1342
+ // so that a second finish() (stopInstance message, then unload) does not wait forever
1343
+ this.finished = true;
1344
+ callback?.();
1286
1345
  }
1287
1346
  }
1288
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) {
1289
1362
  // Answer with an error instead of dereferencing a `sqlFuncs` that is still null. Guarding
1290
1363
  // here covers every database-backed command at once; the alternative would be a check at
1291
1364
  // each of the ~30 `this.sqlFuncs!` uses, every one of which is only reachable from here
@@ -1671,6 +1744,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1671
1744
  }
1672
1745
  pushHelper(_id, state, cb) {
1673
1746
  if (!this.sqlDPs[_id] || (!this.sqlDPs[_id].state && !state)) {
1747
+ cb?.();
1674
1748
  return;
1675
1749
  }
1676
1750
  state ||= this.sqlDPs[_id].state;
@@ -1703,7 +1777,10 @@ class SqlAdapter extends adapter_core_1.Adapter {
1703
1777
  val = val ? 1 : 0;
1704
1778
  }
1705
1779
  else {
1706
- 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;
1707
1784
  }
1708
1785
  }
1709
1786
  else if (_settings.storageType === 'Boolean' && typeof val !== 'boolean') {
@@ -1719,7 +1796,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1719
1796
  }
1720
1797
  getAllIds(cb) {
1721
1798
  const query = this.sqlFuncs.getIdSelect(this.config.dbname);
1722
- this.log.debug(query);
1799
+ this.#debugStatement(query);
1723
1800
  this.borrowClientFromPool((err, client) => {
1724
1801
  if (err || !client) {
1725
1802
  this.returnClientToPool(client);
@@ -1728,7 +1805,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1728
1805
  client.execute(query, (err, rows) => {
1729
1806
  this.returnClientToPool(client);
1730
1807
  if (err) {
1731
- this.log.error(`Cannot select ${query}: ${err}`);
1808
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
1732
1809
  return cb?.(err);
1733
1810
  }
1734
1811
  if (rows?.length) {
@@ -1748,7 +1825,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1748
1825
  }
1749
1826
  getAllFroms(cb) {
1750
1827
  const query = this.sqlFuncs.getFromSelect(this.config.dbname);
1751
- this.log.debug(query);
1828
+ this.#debugStatement(query);
1752
1829
  this.borrowClientFromPool((err, client) => {
1753
1830
  if (err || !client) {
1754
1831
  this.returnClientToPool(client);
@@ -1757,7 +1834,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1757
1834
  client.execute(query, (err, rows /* , fields */) => {
1758
1835
  this.returnClientToPool(client);
1759
1836
  if (err) {
1760
- this.log.error(`Cannot select ${query}: ${err}`);
1837
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
1761
1838
  return cb?.(err);
1762
1839
  }
1763
1840
  if (rows?.length) {
@@ -1770,7 +1847,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1770
1847
  });
1771
1848
  }
1772
1849
  _checkRetention(query, cb) {
1773
- this.log.debug(query);
1850
+ this.#debugStatement(query);
1774
1851
  this.borrowClientFromPool((err, client) => {
1775
1852
  if (err || !client) {
1776
1853
  this.returnClientToPool(client);
@@ -1781,7 +1858,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1781
1858
  client.execute(query, (err) => {
1782
1859
  this.returnClientToPool(client);
1783
1860
  if (err) {
1784
- this.log.warn(`Retention: Cannot delete ${query}: ${err}`);
1861
+ this.log.warn(`Retention: Cannot delete ${(0, statement_1.statementToString)(query)}: ${err}`);
1785
1862
  }
1786
1863
  cb?.();
1787
1864
  });
@@ -1800,7 +1877,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1800
1877
  else {
1801
1878
  const query = this.sqlFuncs.retention(this.config.dbname, this.sqlDPs[id].index, dbNames[this.sqlDPs[id].type], this.sqlDPs[id].config.retention);
1802
1879
  if (!this.multiRequests) {
1803
- if (this.tasks.length > MAX_TASKS) {
1880
+ if (this.#queueFull()) {
1804
1881
  return this.log.error(`Cannot queue new requests, because more than ${MAX_TASKS}`);
1805
1882
  }
1806
1883
  const start = this.tasks.length === 1;
@@ -1830,44 +1907,64 @@ class SqlAdapter extends adapter_core_1.Adapter {
1830
1907
  /**
1831
1908
  * Write one batch of values.
1832
1909
  *
1833
- * `sqlFuncs.insert()` chunks at 500 rows per statement and emits one statement per table, so a batch
1834
- * can be more than one query. They must be sent one by one: no driver here is configured for
1835
- * multi-statement batches (mysql2 needs `multipleStatements`, node-sqlite3's run() takes a single
1836
- * statement), and enabling that would only widen the injection surface of the `query` message.
1837
- * All statements share one borrowed connection, and the first failure aborts the rest - same as the
1838
- * 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
1839
1926
  */
1840
- _insertValuesIntoDB(queries, id, cb) {
1927
+ _insertValuesIntoDB(list, index, id, cb) {
1928
+ const groups = (0, write_buffer_1.splitBatch)(list);
1841
1929
  this.borrowClientFromPool((err, client) => {
1842
1930
  if (err || !client) {
1843
1931
  this.returnClientToPool(client);
1844
- this.log.error(err ? (0, errors_1.formatError)(err) : 'No client');
1845
- 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);
1846
1935
  return;
1847
1936
  }
1848
1937
  const next = (i) => {
1849
- if (i >= queries.length) {
1938
+ if (i >= groups.length) {
1850
1939
  this.returnClientToPool(client);
1851
1940
  this.checkRetention(id);
1852
- cb?.(); // BF asked (2021.12.14): may be return here err?
1941
+ cb?.();
1853
1942
  return;
1854
1943
  }
1855
- this.log.debug(queries[i]);
1856
- client.execute(queries[i], (err /* , rows, fields */) => {
1857
- if (err) {
1858
- this.returnClientToPool(client);
1859
- this.log.error(`Cannot insert ${queries[i]}: ${err} (id: ${id})`);
1860
- 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);
1861
1948
  return;
1862
1949
  }
1863
- next(i + 1);
1864
- });
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);
1865
1962
  };
1866
1963
  next(0);
1867
1964
  });
1868
1965
  }
1869
1966
  _executeQuery(query, id, cb) {
1870
- this.log.debug(query);
1967
+ this.#debugStatement(query);
1871
1968
  this.borrowClientFromPool((err, client) => {
1872
1969
  if (err || !client) {
1873
1970
  this.returnClientToPool(client);
@@ -1878,7 +1975,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1878
1975
  client.execute(query, (err) => {
1879
1976
  this.returnClientToPool(client);
1880
1977
  if (err) {
1881
- this.log.error(`Cannot query ${query}: ${err} (id: ${id})`);
1978
+ this.log.error(`Cannot query ${(0, statement_1.statementToString)(query)}: ${err} (id: ${id})`);
1882
1979
  }
1883
1980
  cb?.(err);
1884
1981
  });
@@ -1986,7 +2083,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1986
2083
  this.sqlDPs[task.id].type !== this.sqlDPs[task.id].dbType) {
1987
2084
  this.sqlDPs[task.id].dbType = this.sqlDPs[task.id].type;
1988
2085
  const query = this.sqlFuncs.getIdUpdate(this.config.dbname, this.sqlDPs[task.id].index, this.sqlDPs[task.id].type);
1989
- this.log.debug(query);
2086
+ this.#debugStatement(query);
1990
2087
  return this.borrowClientFromPool((err, client) => {
1991
2088
  if (err || !client) {
1992
2089
  this.returnClientToPool(client);
@@ -1996,7 +2093,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1996
2093
  client.execute(query, err => {
1997
2094
  this.returnClientToPool(client);
1998
2095
  if (err) {
1999
- 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}`);
2000
2097
  }
2001
2098
  else {
2002
2099
  this.log.info(`changed history configuration to pin detected datatype for ${task.id}`);
@@ -2175,6 +2272,116 @@ class SqlAdapter extends adapter_core_1.Adapter {
2175
2272
  }
2176
2273
  });
2177
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();
2178
2385
  storeCached(onlyId, cb) {
2179
2386
  let count = 0;
2180
2387
  for (const id in this.sqlDPs) {
@@ -2190,11 +2397,33 @@ class SqlAdapter extends adapter_core_1.Adapter {
2190
2397
  this.sqlDPs[id].inFlight ||= {};
2191
2398
  this.sqlDPs[id].inFlight[inFlightId] = this.sqlDPs[id].list;
2192
2399
  this.sqlDPs[id].list = [];
2400
+ this.#releaseKept(id);
2193
2401
  count++;
2194
- 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();
2195
2405
  if (this.sqlDPs[id]?.inFlight?.[inFlightId]) {
2196
2406
  delete this.sqlDPs[id].inFlight[inFlightId];
2197
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
+ }
2198
2427
  if (!--count && cb) {
2199
2428
  cb?.(err);
2200
2429
  cb = null;
@@ -2217,19 +2446,82 @@ class SqlAdapter extends adapter_core_1.Adapter {
2217
2446
  return;
2218
2447
  }
2219
2448
  if (!this.multiRequests) {
2220
- if (this.tasks.length > MAX_TASKS) {
2221
- const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2222
- this.log.error(error);
2223
- 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;
2224
2496
  }
2225
- else {
2226
- this.tasks.push({ operation: 'insert', index: this.sqlDPs[id].index, list, id, callback: cb });
2227
- 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++;
2228
2507
  }
2229
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
+ }
2230
2523
  else {
2231
- const queries = this.sqlFuncs.insert(this.config.dbname, this.sqlDPs[id].index, list);
2232
- this._insertValuesIntoDB(queries, id, cb);
2524
+ setImmediate(() => this.processTasks());
2233
2525
  }
2234
2526
  }
2235
2527
  processTasks() {
@@ -2245,7 +2537,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2245
2537
  this.tasks.shift();
2246
2538
  this.lockTasks = false;
2247
2539
  if (this.tasks.length) {
2248
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2540
+ this.#nextTask();
2249
2541
  }
2250
2542
  });
2251
2543
  }
@@ -2268,13 +2560,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
2268
2560
  }
2269
2561
  }
2270
2562
  }
2271
- const queries = this.sqlFuncs.insert(this.config.dbname, this.tasks[0].index, this.tasks[0].list);
2272
- this._insertValuesIntoDB(queries, this.tasks[0].id, () => {
2273
- 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));
2274
2567
  this.tasks.shift();
2275
2568
  this.lockTasks = false;
2276
2569
  if (this.tasks.length) {
2277
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2570
+ this.#nextTask();
2278
2571
  }
2279
2572
  });
2280
2573
  }
@@ -2285,7 +2578,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2285
2578
  this.tasks.shift();
2286
2579
  this.lockTasks = false;
2287
2580
  if (this.tasks.length) {
2288
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2581
+ this.#nextTask();
2289
2582
  }
2290
2583
  });
2291
2584
  }
@@ -2295,7 +2588,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2295
2588
  this.tasks.shift();
2296
2589
  this.lockTasks = false;
2297
2590
  if (this.tasks.length) {
2298
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2591
+ this.#nextTask();
2299
2592
  }
2300
2593
  });
2301
2594
  }
@@ -2305,7 +2598,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2305
2598
  this.tasks.shift();
2306
2599
  this.lockTasks = false;
2307
2600
  if (this.tasks.length) {
2308
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2601
+ this.#nextTask();
2309
2602
  }
2310
2603
  });
2311
2604
  }
@@ -2315,7 +2608,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2315
2608
  this.tasks.shift();
2316
2609
  this.lockTasks = false;
2317
2610
  if (this.tasks.length) {
2318
- setTimeout(() => this.processTasks(), this.config.requestInterval);
2611
+ this.#nextTask();
2319
2612
  }
2320
2613
  }
2321
2614
  }
@@ -2323,7 +2616,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2323
2616
  // may be it is required to cache all the data in memory
2324
2617
  getId(id, type, cb) {
2325
2618
  let query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
2326
- this.log.debug(query);
2619
+ this.#debugStatement(query);
2327
2620
  this.borrowClientFromPool((err, client) => {
2328
2621
  if (err || !client) {
2329
2622
  this.returnClientToPool(client);
@@ -2338,42 +2631,45 @@ class SqlAdapter extends adapter_core_1.Adapter {
2338
2631
  }
2339
2632
  if (err) {
2340
2633
  this.returnClientToPool(client);
2341
- this.log.error(`Cannot select ${query}: ${err}`);
2634
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
2342
2635
  cb?.(err, id);
2343
2636
  return;
2344
2637
  }
2345
- 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) {
2346
2641
  if (type !== null && type !== undefined) {
2347
2642
  // insert
2348
2643
  query = this.sqlFuncs.getIdInsert(this.config.dbname, id, type);
2349
- this.log.debug(query);
2644
+ this.#debugStatement(query);
2350
2645
  client.execute(query, (err /* , rows, fields */) => {
2351
2646
  if (err) {
2352
2647
  this.returnClientToPool(client);
2353
- this.log.error(`Cannot insert ${query}: ${err}`);
2648
+ this.log.error(`Cannot insert ${(0, statement_1.statementToString)(query)}: ${err}`);
2354
2649
  cb?.(err, id);
2355
2650
  }
2356
2651
  else {
2357
2652
  query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
2358
- this.log.debug(query);
2653
+ this.#debugStatement(query);
2359
2654
  client.execute(query, (err, rows /* , fields */) => {
2360
2655
  this.returnClientToPool(client);
2656
+ const row = (0, names_1.pickRowByName)(rows, id);
2361
2657
  if (!this.sqlDPs[id]) {
2362
2658
  // disabled or deleted while the row was created
2363
2659
  cb?.(new Error(`ID ${id} no longer active`), id);
2364
2660
  }
2365
2661
  else if (err) {
2366
- this.log.error(`Cannot select ${query}: ${err}`);
2662
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
2367
2663
  cb?.(err, id);
2368
2664
  }
2369
- else if (rows?.[0]) {
2370
- this.sqlDPs[id].index = rows[0].id;
2371
- 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;
2372
2668
  cb?.(null, id);
2373
2669
  }
2374
2670
  else {
2375
- this.log.error(`No result for select ${query}: after insert`);
2376
- 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);
2377
2673
  }
2378
2674
  });
2379
2675
  }
@@ -2385,15 +2681,15 @@ class SqlAdapter extends adapter_core_1.Adapter {
2385
2681
  }
2386
2682
  }
2387
2683
  else {
2388
- this.sqlDPs[id].index = rows[0].id;
2389
- 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') {
2390
2686
  this.sqlDPs[id].type = type === null ? 1 : type; // default string
2391
2687
  const query = this.sqlFuncs.getIdUpdate(this.config.dbname, this.sqlDPs[id].index, this.sqlDPs[id].type);
2392
- this.log.debug(query);
2688
+ this.#debugStatement(query);
2393
2689
  client.execute(query, err => {
2394
2690
  this.returnClientToPool(client);
2395
2691
  if (err) {
2396
- 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}`);
2397
2693
  }
2398
2694
  else {
2399
2695
  this.log.info(`changed history configuration to pin detected datatype for ${id}`);
@@ -2403,7 +2699,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2403
2699
  }
2404
2700
  else {
2405
2701
  this.returnClientToPool(client);
2406
- this.sqlDPs[id].type = rows[0].type;
2702
+ this.sqlDPs[id].type = row.type;
2407
2703
  cb?.(null, id);
2408
2704
  }
2409
2705
  }
@@ -2414,7 +2710,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2414
2710
  getFrom(_from, cb) {
2415
2711
  // const sources = (this.config.dbtype !== 'postgresql' ? (this.config.dbname + '.') : '') + 'sources';
2416
2712
  let query = this.sqlFuncs.getFromSelect(this.config.dbname, _from);
2417
- this.log.debug(query);
2713
+ this.#debugStatement(query);
2418
2714
  this.borrowClientFromPool((err, client) => {
2419
2715
  if (err || !client) {
2420
2716
  this.returnClientToPool(client);
@@ -2423,35 +2719,38 @@ class SqlAdapter extends adapter_core_1.Adapter {
2423
2719
  client.execute(query, (err, rows /* , fields */) => {
2424
2720
  if (err) {
2425
2721
  this.returnClientToPool(client);
2426
- this.log.error(`Cannot select ${query}: ${err}`);
2722
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
2427
2723
  return cb?.(err, _from);
2428
2724
  }
2429
- 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) {
2430
2728
  // insert
2431
2729
  query = this.sqlFuncs.getFromInsert(this.config.dbname, _from);
2432
- this.log.debug(query);
2730
+ this.#debugStatement(query);
2433
2731
  client.execute(query, err => {
2434
2732
  if (err) {
2435
2733
  this.returnClientToPool(client);
2436
- this.log.error(`Cannot insert ${query}: ${err}`);
2734
+ this.log.error(`Cannot insert ${(0, statement_1.statementToString)(query)}: ${err}`);
2437
2735
  return cb?.(err, _from);
2438
2736
  }
2439
2737
  query = this.sqlFuncs.getFromSelect(this.config.dbname, _from);
2440
- this.log.debug(query);
2738
+ this.#debugStatement(query);
2441
2739
  client.execute(query, (err, rows /* , fields */) => {
2442
2740
  this.returnClientToPool(client);
2443
- if (err || !rows?.length) {
2444
- 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}`);
2445
2744
  return cb?.(err, _from);
2446
2745
  }
2447
- this.from[_from] = rows[0].id;
2746
+ this.from[_from] = row.id;
2448
2747
  cb?.(null, _from);
2449
2748
  });
2450
2749
  });
2451
2750
  }
2452
2751
  else {
2453
2752
  this.returnClientToPool(client);
2454
- this.from[_from] = rows[0].id;
2753
+ this.from[_from] = row.id;
2455
2754
  cb?.(null, _from);
2456
2755
  }
2457
2756
  });
@@ -2550,7 +2849,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2550
2849
  callback(cache, !!options.returnNewestEntries && !!options.count && cache.length >= options.count, anyInflight, earliestTs);
2551
2850
  }
2552
2851
  #getDataFromDB(query, options, callback) {
2553
- this.log.debug(query);
2852
+ this.#debugStatement(query);
2554
2853
  this.borrowClientFromPool((err, client) => {
2555
2854
  if (err || !client) {
2556
2855
  this.returnClientToPool(client);
@@ -2588,9 +2887,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
2588
2887
  }
2589
2888
  getDataFromDB(table, options, callback) {
2590
2889
  const query = this.sqlFuncs.getHistory(this.config.dbname, table, options);
2591
- this.log.debug(query);
2890
+ this.#debugStatement(query);
2592
2891
  if (!this.multiRequests) {
2593
- if (this.tasks.length > MAX_TASKS) {
2892
+ if (this.#queueFull()) {
2594
2893
  this.log.error(`Cannot queue new requests, because more than ${MAX_TASKS}`);
2595
2894
  callback?.(new Error(`Cannot queue new requests, because more than ${MAX_TASKS}`));
2596
2895
  }
@@ -2607,9 +2906,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
2607
2906
  }
2608
2907
  getCounterDataFromDB(options, callback) {
2609
2908
  const query = this.sqlFuncs.getCounterDiff(this.config.dbname, options);
2610
- this.log.debug(query);
2909
+ this.#debugStatement(query);
2611
2910
  if (!this.multiRequests) {
2612
- if (this.tasks.length > MAX_TASKS) {
2911
+ if (this.#queueFull()) {
2613
2912
  const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2614
2913
  this.log.error(error);
2615
2914
  callback?.(new Error(error));
@@ -2626,10 +2925,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
2626
2925
  }
2627
2926
  }
2628
2927
  getCounterDiff(msg) {
2629
- const id = msg.message.id;
2630
- const start = msg.message.options.start || 0;
2631
- const end = msg.message.options.end || Date.now() + 5000000;
2632
- 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]) {
2633
2936
  this.sendTo(msg.from, msg.command, { result: [], step: null, error: 'Not enabled' }, msg.callback);
2634
2937
  }
2635
2938
  else {
@@ -2660,6 +2963,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
2660
2963
  else {
2661
2964
  ignoreNull = false; // include nulls
2662
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
+ }
2663
2969
  const logId = (msg.message.id ? msg.message.id : 'all') + Date.now() + Math.random();
2664
2970
  const options = {
2665
2971
  id: msg.message.id === '*' ? null : msg.message.id,
@@ -2701,25 +3007,22 @@ class SqlAdapter extends adapter_core_1.Adapter {
2701
3007
  options.count = 500;
2702
3008
  }
2703
3009
  }
2704
- try {
2705
- if (options.start && typeof options.start !== 'number') {
2706
- 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);
2707
3018
  }
2708
3019
  }
2709
- catch {
2710
- return this.sendTo(msg.from, msg.command, {
2711
- error: `Invalid call. Start date ${JSON.stringify(options.start)} is not a valid date`,
2712
- }, msg.callback);
2713
- }
2714
- try {
2715
- if (options.end && typeof options.end !== 'number') {
2716
- options.end = new Date(options.end).getTime();
2717
- }
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);
2718
3023
  }
2719
- catch {
2720
- return this.sendTo(msg.from, msg.command, {
2721
- error: `Invalid call. End date ${JSON.stringify(options.end)} is not a valid date`,
2722
- }, msg.callback);
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);
2723
3026
  }
2724
3027
  // The client can send the borders of the intervals itself, e.g. the local days of a chart: a fixed step does
2725
3028
  // not fit a day with 23 or 25 hours. The database must then be read for exactly the range they cover.
@@ -2932,13 +3235,22 @@ class SqlAdapter extends adapter_core_1.Adapter {
2932
3235
  for (let i = res.length - 1; i >= 0; i--) {
2933
3236
  if (res[i].state.ts === state.ts) {
2934
3237
  if (state.val !== undefined) {
2935
- 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;
2936
3244
  }
2937
3245
  if (state.q !== undefined && res[i].state.q !== undefined) {
2938
3246
  res[i].state.q = state.q;
2939
3247
  }
2940
3248
  if (state.from !== undefined && res[i].from !== undefined) {
2941
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
+ }
2942
3254
  }
2943
3255
  if (state.ack !== undefined) {
2944
3256
  res[i].state.ack = state.ack;
@@ -2983,7 +3295,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
2983
3295
  }
2984
3296
  /** Build and execute the UPDATE query for one entry of one datapoint */
2985
3297
  #updateInDb(id, table, index, state, cb) {
2986
- 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);
2987
3305
  this.#executeQueries(id, [query], cb);
2988
3306
  }
2989
3307
  #delete(id, state, cb) {
@@ -2992,26 +3310,16 @@ class SqlAdapter extends adapter_core_1.Adapter {
2992
3310
  if (this.sqlDPs[id]) {
2993
3311
  const res = this.sqlDPs[id].list;
2994
3312
  if (res) {
2995
- if (!state.ts && !state.start && !state.end) {
3313
+ if (state.mode === 'all') {
2996
3314
  this.sqlDPs[id].list = [];
2997
3315
  }
2998
3316
  else {
2999
3317
  for (let i = res.length - 1; i >= 0; i--) {
3000
- if (state.start && state.end) {
3318
+ if (state.mode === 'range') {
3001
3319
  if (res[i].state.ts >= state.start && res[i].state.ts <= state.end) {
3002
3320
  res.splice(i, 1);
3003
3321
  }
3004
3322
  }
3005
- else if (state.start) {
3006
- if (res[i].state.ts >= state.start) {
3007
- res.splice(i, 1);
3008
- }
3009
- }
3010
- else if (state.end) {
3011
- if (res[i].state.ts <= state.end) {
3012
- res.splice(i, 1);
3013
- }
3014
- }
3015
3323
  else if (res[i].state.ts === state.ts) {
3016
3324
  res.splice(i, 1);
3017
3325
  found = true;
@@ -3051,13 +3359,18 @@ class SqlAdapter extends adapter_core_1.Adapter {
3051
3359
  * (or no longer) enabled for logging, i.e., that are not in `sqlDPs`.
3052
3360
  */
3053
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
+ }
3054
3367
  if (!this.clientPool) {
3055
3368
  this.log.warn(`No connection to the database, cannot look up "${id}"`);
3056
3369
  setImmediate(() => cb(new Error('No Connection to database')));
3057
3370
  return;
3058
3371
  }
3059
3372
  const query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
3060
- this.log.debug(query);
3373
+ this.#debugStatement(query);
3061
3374
  this.borrowClientFromPool((err, client) => {
3062
3375
  if (err || !client) {
3063
3376
  this.returnClientToPool(client);
@@ -3067,7 +3380,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3067
3380
  client.execute(query, (err, rows) => {
3068
3381
  this.returnClientToPool(client);
3069
3382
  if (err) {
3070
- this.log.error(`Cannot select ${query}: ${err}`);
3383
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3071
3384
  cb(err);
3072
3385
  }
3073
3386
  else if (!rows?.length) {
@@ -3093,13 +3406,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
3093
3406
  }
3094
3407
  /** Build the DELETE query for one table of one datapoint */
3095
3408
  #buildDeleteQuery(table, index, state) {
3096
- 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') {
3097
3412
  return this.sqlFuncs.deleteFromTable(this.config.dbname, table, index, state.start, state.end);
3098
3413
  }
3099
- if (state.ts) {
3414
+ if (state.mode === 'one') {
3100
3415
  return this.sqlFuncs.deleteFromTable(this.config.dbname, table, index, state.ts);
3101
3416
  }
3102
- // delete all entries for ID
3103
3417
  return this.sqlFuncs.deleteFromTable(this.config.dbname, table, index);
3104
3418
  }
3105
3419
  /** Execute the given queries one after another and stop at the first error */
@@ -3117,7 +3431,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3117
3431
  this.#executeQueries(id, queries, cb);
3118
3432
  };
3119
3433
  if (!this.multiRequests) {
3120
- if (this.tasks.length > MAX_TASKS) {
3434
+ if (this.#queueFull()) {
3121
3435
  const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
3122
3436
  this.log.error(error);
3123
3437
  cb?.(new Error(error));
@@ -3131,204 +3445,84 @@ class SqlAdapter extends adapter_core_1.Adapter {
3131
3445
  this._executeQuery(query, id, next);
3132
3446
  }
3133
3447
  }
3134
- updateState(msg) {
3135
- if (!msg.message) {
3136
- this.log.error('updateState called with invalid data');
3137
- return this.sendTo(msg.from, msg.command, {
3138
- error: `Invalid call: ${JSON.stringify(msg)}`,
3139
- }, msg.callback);
3140
- }
3141
- let id;
3142
- if (Array.isArray(msg.message)) {
3143
- this.log.debug(`updateState ${msg.message.length} items`);
3144
- for (let i = 0; i < msg.message.length; i++) {
3145
- id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
3146
- if (msg.message[i].state && typeof msg.message[i].state === 'object') {
3147
- this.update(id, msg.message[i].state);
3148
- }
3149
- else {
3150
- this.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
3151
- }
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;
3152
3458
  }
3153
- }
3154
- else if (msg.message.state && Array.isArray(msg.message.state)) {
3155
- this.log.debug(`updateState ${msg.message.state.length} items`);
3156
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3157
- for (let j = 0; j < msg.message.state.length; j++) {
3158
- if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
3159
- this.update(id, msg.message.state[j]);
3160
- }
3161
- else {
3162
- 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,
3163
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('; ')}`);
3164
3470
  }
3471
+ answer();
3472
+ return;
3165
3473
  }
3166
- else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
3167
- this.log.debug('updateState 1 item');
3168
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3169
- return this.update(id, msg.message.state, err => this.sendTo(msg.from, msg.command, err
3170
- ? { error: err.message, sqlConnected: !!this.clientPool }
3171
- : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3172
- }
3173
- else {
3174
- this.log.error('updateState called with invalid data');
3175
- return this.sendTo(msg.from, msg.command, {
3176
- error: `Invalid call: ${JSON.stringify(msg)}`,
3177
- }, msg.callback);
3178
- }
3179
- this.sendTo(msg.from, msg.command, {
3180
- success: true,
3181
- sqlConnected: !!this.clientPool,
3182
- }, msg.callback);
3183
- }
3184
- deleteHistoryEntry(msg) {
3185
- if (!msg.message) {
3186
- this.log.error('deleteHistoryEntry called with invalid data');
3187
- return this.sendTo(msg.from, msg.command, {
3188
- error: `Invalid call: ${JSON.stringify(msg)}`,
3189
- }, msg.callback);
3190
- }
3191
- let id;
3192
- if (Array.isArray(msg.message)) {
3193
- this.log.debug(`deleteHistoryEntry ${msg.message.length} items`);
3194
- for (let i = 0; i < msg.message.length; i++) {
3195
- id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
3196
- // {id: 'blabla', ts: 892}
3197
- if (msg.message[i].ts) {
3198
- this.#delete(id, { ts: msg.message[i].ts });
3199
- }
3200
- else if (msg.message[i].start) {
3201
- if (typeof msg.message[i].start === 'string') {
3202
- msg.message[i].start = new Date(msg.message[i].start).getTime();
3203
- }
3204
- if (typeof msg.message[i].end === 'string') {
3205
- msg.message[i].end = new Date(msg.message[i].end).getTime();
3206
- }
3207
- this.#delete(id, { start: msg.message[i].start, end: msg.message[i].end || Date.now() });
3208
- }
3209
- else if (typeof msg.message[i].state === 'object' &&
3210
- msg.message[i].state &&
3211
- msg.message[i].state.ts) {
3212
- this.#delete(id, { ts: msg.message[i].state.ts });
3213
- }
3214
- else if (typeof msg.message[i].state === 'object' &&
3215
- msg.message[i].state &&
3216
- msg.message[i].state.start) {
3217
- if (typeof msg.message[i].state.start === 'string') {
3218
- msg.message[i].state.start = new Date(msg.message[i].state.start).getTime();
3219
- }
3220
- if (typeof msg.message[i].state.end === 'string') {
3221
- msg.message[i].state.end = new Date(msg.message[i].state.end).getTime();
3222
- }
3223
- this.#delete(id, {
3224
- start: msg.message[i].state.start,
3225
- end: msg.message[i].state.end || Date.now(),
3226
- });
3227
- }
3228
- else {
3229
- 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);
3230
3480
  }
3231
- }
3232
- }
3233
- else if (msg.message.state && Array.isArray(msg.message.state)) {
3234
- this.log.debug(`deleteHistoryEntry ${msg.message.state.length} items`);
3235
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3236
- for (let j = 0; j < msg.message.state.length; j++) {
3237
- if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
3238
- if (msg.message.state[j].ts) {
3239
- this.#delete(id, { ts: msg.message.state[j].ts });
3481
+ if (!--pending) {
3482
+ if (errors.length) {
3483
+ this.log.warn(`${msg.command}: ${errors.join('; ')}`);
3240
3484
  }
3241
- else if (msg.message.state[j].start) {
3242
- if (typeof msg.message.state[j].start === 'string') {
3243
- msg.message.state[j].start = new Date(msg.message.state[j].start).getTime();
3244
- }
3245
- if (typeof msg.message.state[j].end === 'string') {
3246
- msg.message.state[j].end = new Date(msg.message.state[j].end).getTime();
3247
- }
3248
- this.#delete(id, {
3249
- start: msg.message.state[j].start,
3250
- end: msg.message.state[j].end || Date.now(),
3251
- });
3252
- }
3253
- }
3254
- else if (msg.message.state[j] && typeof msg.message.state[j] === 'number') {
3255
- this.#delete(id, { ts: msg.message.state[j] });
3485
+ answer();
3256
3486
  }
3257
- else {
3258
- this.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
3259
- }
3260
- }
3261
- }
3262
- else if (msg.message.ts && Array.isArray(msg.message.ts)) {
3263
- this.log.debug(`deleteHistoryEntry ${msg.message.ts.length} items`);
3264
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3265
- for (let j = 0; j < msg.message.ts.length; j++) {
3266
- if (msg.message.ts[j] && typeof msg.message.ts[j] === 'number') {
3267
- this.#delete(id, { ts: msg.message.ts[j] });
3268
- }
3269
- else {
3270
- this.log.warn(`Invalid state for ${JSON.stringify(msg.message.ts[j])}`);
3271
- }
3272
- }
3273
- }
3274
- else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
3275
- this.log.debug('deleteHistoryEntry 1 item');
3276
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3277
- return this.#delete(id, { ts: msg.message.state.ts }, err => this.sendTo(msg.from, msg.command, err
3278
- ? { error: err.message, sqlConnected: !!this.clientPool }
3279
- : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3280
- }
3281
- else if (msg.message.id && msg.message.ts && typeof msg.message.ts === 'number') {
3282
- this.log.debug('deleteHistoryEntry 1 item');
3283
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3284
- return this.#delete(id, { ts: msg.message.ts }, err => this.sendTo(msg.from, msg.command, err
3285
- ? { error: err.message, sqlConnected: !!this.clientPool }
3286
- : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3287
- }
3288
- else {
3289
- this.log.error('deleteHistoryEntry called with invalid data');
3290
- return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
3487
+ });
3291
3488
  }
3292
- this.sendTo(msg.from, msg.command, {
3293
- success: true,
3294
- sqlConnected: !!this.clientPool,
3295
- }, 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));
3296
3495
  }
3297
3496
  deleteStateAll(msg) {
3298
- if (!msg.message) {
3299
- this.log.error('deleteStateAll called with invalid data');
3300
- return this.sendTo(msg.from, msg.command, {
3301
- error: `Invalid call: ${JSON.stringify(msg)}`,
3302
- }, msg.callback);
3303
- }
3304
- let id;
3305
- if (Array.isArray(msg.message)) {
3306
- this.log.debug(`deleteStateAll ${msg.message.length} items`);
3307
- for (let i = 0; i < msg.message.length; i++) {
3308
- id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
3309
- this.#delete(id, {});
3310
- }
3311
- }
3312
- else if (msg.message.id) {
3313
- this.log.debug('deleteStateAll 1 item');
3314
- id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3315
- return this.#delete(id, {}, err => this.sendTo(msg.from, msg.command, err
3316
- ? { error: err.message, sqlConnected: !!this.clientPool }
3317
- : { 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 };
3318
3502
  }
3319
- else {
3320
- this.log.error('deleteStateAll called with invalid data');
3321
- 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 };
3322
3505
  }
3323
- this.sendTo(msg.from, msg.command, {
3324
- success: true,
3325
- sqlConnected: !!this.clientPool,
3326
- }, msg.callback);
3506
+ return { mode: 'all' };
3327
3507
  }
3328
3508
  storeStatePushData(id, state, applyRules) {
3509
+ if (!(0, messages_1.isId)(id)) {
3510
+ throw new Error(`ID ${JSON.stringify(id)} is not valid`);
3511
+ }
3329
3512
  if (!state || typeof state !== 'object') {
3330
3513
  throw new Error(`State ${JSON.stringify(state)} for ${id} is not valid`);
3331
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 : '' };
3332
3526
  if (!this.sqlDPs[id]?.config) {
3333
3527
  if (applyRules) {
3334
3528
  throw new Error(`sql not enabled for ${id}, so can not apply the rules as requested`);
@@ -3440,12 +3634,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
3440
3634
  * Read the stored values of one datapoint page by page.
3441
3635
  *
3442
3636
  * In contrast to `getHistory`, the rows are returned exactly as they are in the database: no aggregation,
3443
- * no interpolation, no border values and no rounding. Together with the total number of matching entries,
3444
- * so that a table can page through them. Works for datapoints that are not (or no longer) enabled for
3445
- * 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.
3446
3640
  */
3447
3641
  getRawEntries(msg) {
3448
- if (!msg.message?.id) {
3642
+ if (!(0, messages_1.isId)(msg.message?.id)) {
3449
3643
  this.log.error('getRawEntries called with invalid data');
3450
3644
  return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
3451
3645
  }
@@ -3463,6 +3657,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3463
3657
  limit: Math.min(Math.max(parseInt(msg.message.limit, 10) || 100, 1), MAX_RAW_ENTRIES),
3464
3658
  offset: Math.max(parseInt(msg.message.offset, 10) || 0, 0),
3465
3659
  sort: msg.message.sort === 'asc' ? 'asc' : 'desc',
3660
+ noTotal: msg.message.noTotal === true,
3466
3661
  };
3467
3662
  this.#readIdIndexAndType(id, (err, index, type) => {
3468
3663
  if (err || index === undefined || type === undefined) {
@@ -3474,24 +3669,22 @@ class SqlAdapter extends adapter_core_1.Adapter {
3474
3669
  this.returnClientToPool(client);
3475
3670
  return this.sendTo(msg.from, msg.command, { error: (err || new Error('No client')).message }, msg.callback);
3476
3671
  }
3477
- const countQuery = this.sqlFuncs.getRawEntriesCount(this.config.dbname, table, index, options);
3478
- this.log.debug(countQuery);
3479
- client.execute(countQuery, (err, rows) => {
3480
- if (err) {
3481
- this.returnClientToPool(client);
3482
- this.log.error(`Cannot select ${countQuery}: ${err}`);
3483
- return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3484
- }
3485
- // PostgreSQL returns the count of a bigint column as string
3486
- const total = rows?.[0] ? parseInt(rows[0].total, 10) || 0 : 0;
3672
+ const readEntries = (total) => {
3487
3673
  const query = this.sqlFuncs.getRawEntries(this.config.dbname, table, index, options);
3488
- this.log.debug(query);
3674
+ this.#debugStatement(query);
3489
3675
  client.execute(query, (err, rows) => {
3490
3676
  this.returnClientToPool(client);
3491
3677
  if (err) {
3492
- this.log.error(`Cannot select ${query}: ${err}`);
3678
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3493
3679
  return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3494
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
+ }
3495
3688
  this.sendTo(msg.from, msg.command, {
3496
3689
  id: msg.message.id,
3497
3690
  index,
@@ -3501,9 +3694,25 @@ class SqlAdapter extends adapter_core_1.Adapter {
3501
3694
  limit: options.limit,
3502
3695
  offset: options.offset,
3503
3696
  sort: options.sort,
3504
- result: rows || [],
3697
+ result,
3505
3698
  }, msg.callback);
3506
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);
3507
3716
  });
3508
3717
  });
3509
3718
  });
@@ -3680,7 +3889,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3680
3889
  }
3681
3890
  getDatapoints(msg) {
3682
3891
  const query = this.sqlFuncs.getIdSelect(this.config.dbname);
3683
- this.log.debug(query);
3892
+ this.#debugStatement(query);
3684
3893
  this.borrowClientFromPool((err, client) => {
3685
3894
  if (err || !client) {
3686
3895
  this.returnClientToPool(client);
@@ -3689,7 +3898,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
3689
3898
  client.execute(query, (err, rows) => {
3690
3899
  this.returnClientToPool(client);
3691
3900
  if (err) {
3692
- this.log.error(`Cannot select ${query}: ${err}`);
3901
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3693
3902
  return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3694
3903
  }
3695
3904
  const result = (rows || [])
@@ -3706,20 +3915,20 @@ class SqlAdapter extends adapter_core_1.Adapter {
3706
3915
  getDpOverview(msg) {
3707
3916
  const result = [];
3708
3917
  const query = this.sqlFuncs.getIdSelect(this.config.dbname);
3709
- this.log.info(query);
3918
+ this.log.info((0, statement_1.statementToString)(query));
3710
3919
  this.borrowClientFromPool((err, client) => {
3711
3920
  if (err || !client) {
3712
3921
  this.returnClientToPool(client);
3713
3922
  return this.sendTo(msg.from, msg.command, {
3714
- error: `Cannot select ${query}: ${err || 'no client'}`,
3923
+ error: `Cannot select ${(0, statement_1.statementToString)(query)}: ${err || 'no client'}`,
3715
3924
  }, msg.callback);
3716
3925
  }
3717
3926
  client.execute(query, (err, rows /* , fields */) => {
3718
3927
  if (err) {
3719
3928
  this.returnClientToPool(client);
3720
- this.log.error(`Cannot select ${query}: ${err}`);
3929
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3721
3930
  this.sendTo(msg.from, msg.command, {
3722
- error: `Cannot select ${query}: ${err}`,
3931
+ error: `Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`,
3723
3932
  }, msg.callback);
3724
3933
  return;
3725
3934
  }
@@ -3753,13 +3962,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
3753
3962
  }
3754
3963
  else {
3755
3964
  const query = this.sqlFuncs.getFirstTs(this.config.dbname, dbNames[typeId]);
3756
- this.log.info(query);
3965
+ this.log.info((0, statement_1.statementToString)(query));
3757
3966
  client.execute(query, (err, rows /* , fields */) => {
3758
3967
  if (err) {
3759
3968
  this.returnClientToPool(client);
3760
- this.log.error(`Cannot select ${query}: ${err}`);
3969
+ this.log.error(`Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`);
3761
3970
  this.sendTo(msg.from, msg.command, {
3762
- error: `Cannot select ${query}: ${err}`,
3971
+ error: `Cannot select ${(0, statement_1.statementToString)(query)}: ${err}`,
3763
3972
  }, msg.callback);
3764
3973
  return;
3765
3974
  }
@@ -3929,7 +4138,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
3929
4138
  }
3930
4139
  if (config.maxConnections !== undefined && config.dbtype !== 'sqlite') {
3931
4140
  config.maxConnections = parseInt(config.maxConnections, 10);
3932
- 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`);
3933
4144
  config.maxConnections = 100;
3934
4145
  }
3935
4146
  }