iobroker.sql 4.1.6 → 4.2.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 (83) hide show
  1. package/README.md +17 -5
  2. package/admin/custom/assets/Components-CYBqz3DR.js +1 -0
  3. package/admin/custom/assets/DataBrowser-CQWCId83.js +1 -0
  4. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__SqlComponentsSet__mf_owner__1-BhenO-eY.js +1 -0
  5. package/admin/custom/assets/{_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__45000407818393__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BhkczXIL.js → _virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__173647931027197__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BXkVrp-h.js} +56 -56
  6. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__173647931027197__loadShare__shared-D7KMOV5W.js +2 -0
  7. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__173647931027197__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-CUnqgVSc.js +122 -0
  8. package/admin/custom/assets/{_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__45000407818393__prebuild__react_mf_2_dom_mf_1_client__prebuild__-DdEgwb91.js → _virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__173647931027197__prebuild__react_mf_2_dom_mf_1_client__prebuild__-YkkLtJg3.js} +1 -1
  9. package/admin/custom/assets/{dist-CcO6wD-W.js → dist-CzitsFi7.js} +1 -1
  10. package/admin/custom/assets/helpers-BZgjFQNf.js +1 -0
  11. package/admin/custom/assets/hostInit-DIOUH9oj.js +1 -0
  12. package/admin/custom/assets/index-D6PAQQ9J.js +1 -0
  13. package/admin/custom/assets/{lib-Bm71NwS-.js → lib-CbSOBh3z.js} +2 -2
  14. package/admin/custom/assets/{mf-entry-bootstrap-0-75c1e504.js → mf-entry-bootstrap-0-e018258d.js} +3 -3
  15. package/admin/custom/assets/pendingShares-yWRueDAR.js +2 -0
  16. package/admin/custom/assets/{utils-BH7Z2GoV.js → utils-DUKzLJUz.js} +1 -1
  17. package/admin/custom/customComponents.js +2 -2
  18. package/admin/custom/i18n/de.json +25 -1
  19. package/admin/custom/i18n/en.json +25 -1
  20. package/admin/custom/i18n/es.json +25 -1
  21. package/admin/custom/i18n/fr.json +25 -1
  22. package/admin/custom/i18n/it.json +25 -1
  23. package/admin/custom/i18n/nl.json +25 -1
  24. package/admin/custom/i18n/pl.json +25 -1
  25. package/admin/custom/i18n/pt.json +25 -1
  26. package/admin/custom/i18n/ru.json +25 -1
  27. package/admin/custom/i18n/uk.json +54 -0
  28. package/admin/custom/i18n/zh-cn.json +25 -1
  29. package/admin/custom/mf-manifest.json +1 -1
  30. package/admin/i18n/de.json +20 -1
  31. package/admin/i18n/en.json +20 -1
  32. package/admin/i18n/es.json +20 -1
  33. package/admin/i18n/fr.json +20 -1
  34. package/admin/i18n/it.json +20 -1
  35. package/admin/i18n/nl.json +20 -1
  36. package/admin/i18n/pl.json +20 -1
  37. package/admin/i18n/pt.json +20 -1
  38. package/admin/i18n/ru.json +20 -1
  39. package/admin/i18n/uk.json +98 -0
  40. package/admin/i18n/zh-cn.json +20 -1
  41. package/admin/jsonConfig.json +29 -5
  42. package/build/lib/connection-options.js +38 -0
  43. package/build/lib/connection-options.js.map +1 -0
  44. package/build/lib/errors.js +17 -0
  45. package/build/lib/errors.js.map +1 -1
  46. package/build/lib/messages.js +52 -0
  47. package/build/lib/messages.js.map +1 -0
  48. package/build/lib/mssql.js +41 -0
  49. package/build/lib/mssql.js.map +1 -1
  50. package/build/lib/mysql-client.js +2 -1
  51. package/build/lib/mysql-client.js.map +1 -1
  52. package/build/lib/mysql.js +42 -0
  53. package/build/lib/mysql.js.map +1 -1
  54. package/build/lib/optional-drivers.js +37 -0
  55. package/build/lib/optional-drivers.js.map +1 -0
  56. package/build/lib/postgresql.js +42 -0
  57. package/build/lib/postgresql.js.map +1 -1
  58. package/build/lib/sql-client-pool.js +7 -0
  59. package/build/lib/sql-client-pool.js.map +1 -1
  60. package/build/lib/sql-client.js +68 -8
  61. package/build/lib/sql-client.js.map +1 -1
  62. package/build/lib/sqlite.js +42 -0
  63. package/build/lib/sqlite.js.map +1 -1
  64. package/build/lib/sqlite3-client.js +2 -1
  65. package/build/lib/sqlite3-client.js.map +1 -1
  66. package/build/lib/statistics.js +90 -0
  67. package/build/lib/statistics.js.map +1 -0
  68. package/build/lib/values.js +51 -0
  69. package/build/lib/values.js.map +1 -0
  70. package/build/main.js +353 -107
  71. package/build/main.js.map +1 -1
  72. package/io-package.json +15 -14
  73. package/package.json +3 -4
  74. package/admin/custom/assets/Components-BdA5LPyZ.js +0 -1
  75. package/admin/custom/assets/DataBrowser-B58dmY7z.js +0 -1
  76. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__SqlComponentsSet__mf_owner__1-Ck14nhXC.js +0 -1
  77. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__45000407818393__loadShare__shared-CW0J4wsL.js +0 -2
  78. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__45000407818393__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-rYhVwVDZ.js +0 -122
  79. package/admin/custom/assets/helpers-Cn4fdICb.js +0 -1
  80. package/admin/custom/assets/hostInit-BcHgEp_u.js +0 -1
  81. package/admin/custom/assets/index-CPb0o_Am.js +0 -1
  82. package/admin/custom/assets/pendingShares-B0rqjI4o.js +0 -2
  83. /package/admin/custom/assets/{_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__45000407818393__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__-B_v57Qfr.js → _virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__173647931027197__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__-B_v57Qfr.js} +0 -0
package/build/main.js CHANGED
@@ -44,6 +44,10 @@ const PostgreSQL = __importStar(require("./lib/postgresql"));
44
44
  const SQLite = __importStar(require("./lib/sqlite"));
45
45
  const mssql_client_1 = require("./lib/mssql-client");
46
46
  const mysql_client_1 = require("./lib/mysql-client");
47
+ const connection_options_1 = require("./lib/connection-options");
48
+ const messages_1 = require("./lib/messages");
49
+ const values_1 = require("./lib/values");
50
+ const statistics_1 = require("./lib/statistics");
47
51
  const postgresql_client_1 = require("./lib/postgresql-client");
48
52
  const sqlite3_client_1 = require("./lib/sqlite3-client");
49
53
  const errors_1 = require("./lib/errors");
@@ -52,6 +56,9 @@ const SQLFuncs = {
52
56
  init: MSSQL.init,
53
57
  destroy: MSSQL.destroy,
54
58
  getFirstTs: MSSQL.getFirstTs,
59
+ getIdCounts: MSSQL.getIdCounts,
60
+ deleteDatapoint: MSSQL.deleteDatapoint,
61
+ getTableSize: MSSQL.getTableSize,
55
62
  insert: MSSQL.insert,
56
63
  retention: MSSQL.retention,
57
64
  getIdSelect: MSSQL.getIdSelect,
@@ -70,6 +77,9 @@ const SQLFuncs = {
70
77
  init: MySQL.init,
71
78
  destroy: MySQL.destroy,
72
79
  getFirstTs: MySQL.getFirstTs,
80
+ getIdCounts: MySQL.getIdCounts,
81
+ deleteDatapoint: MySQL.deleteDatapoint,
82
+ getTableSize: MySQL.getTableSize,
73
83
  insert: MySQL.insert,
74
84
  retention: MySQL.retention,
75
85
  getIdSelect: MySQL.getIdSelect,
@@ -88,6 +98,9 @@ const SQLFuncs = {
88
98
  init: PostgreSQL.init,
89
99
  destroy: PostgreSQL.destroy,
90
100
  getFirstTs: PostgreSQL.getFirstTs,
101
+ getIdCounts: PostgreSQL.getIdCounts,
102
+ deleteDatapoint: PostgreSQL.deleteDatapoint,
103
+ getTableSize: PostgreSQL.getTableSize,
91
104
  insert: PostgreSQL.insert,
92
105
  retention: PostgreSQL.retention,
93
106
  getIdSelect: PostgreSQL.getIdSelect,
@@ -106,6 +119,9 @@ const SQLFuncs = {
106
119
  init: SQLite.init,
107
120
  destroy: SQLite.destroy,
108
121
  getFirstTs: SQLite.getFirstTs,
122
+ getIdCounts: SQLite.getIdCounts,
123
+ deleteDatapoint: SQLite.deleteDatapoint,
124
+ getTableSize: SQLite.getTableSize,
109
125
  insert: SQLite.insert,
110
126
  retention: SQLite.retention,
111
127
  getIdSelect: SQLite.getIdSelect,
@@ -173,6 +189,8 @@ function isEqual(a, b) {
173
189
  // are considered equivalent
174
190
  return true;
175
191
  }
192
+ /** Every time series table the statistics and the cleanup have to look at */
193
+ const STAT_TABLES = ['ts_number', 'ts_string', 'ts_bool', 'ts_counter'];
176
194
  const MAX_TASKS = 100;
177
195
  /** Maximal number of rows one `getRawEntries` call may return */
178
196
  const MAX_RAW_ENTRIES = 2000;
@@ -210,6 +228,8 @@ class SqlAdapter extends adapter_core_1.Adapter {
210
228
  lastConnectionError = null;
211
229
  lastConnectionErrorTs = 0;
212
230
  connectionErrorCount = 0;
231
+ /** consecutive pool-borrow failures; at 5 info.connection turns false instead of staying true forever (#374) */
232
+ consecutiveBorrowFailures = 0;
213
233
  constructor(options = {}) {
214
234
  super({
215
235
  ...options,
@@ -339,7 +359,6 @@ class SqlAdapter extends adapter_core_1.Adapter {
339
359
  this.setConnected(false);
340
360
  return callback(new Error('No database connection'));
341
361
  }
342
- this.setConnected(true);
343
362
  if (this.activeConnections >= this.config.maxConnections) {
344
363
  if (this.logConnectionUsage) {
345
364
  this.log.debug(`Borrow connection not possible: ${this.activeConnections} >= Max - Store for Later`);
@@ -353,13 +372,26 @@ class SqlAdapter extends adapter_core_1.Adapter {
353
372
  }
354
373
  this.clientPool.borrow((err, client) => {
355
374
  if (!err && client) {
356
- // make sure we always have at least one error listener to prevent crashes
375
+ // Log connection-level driver errors (ECONNRESET, PROTOCOL_CONNECTION_LOST). The
376
+ // crash safety itself does not depend on this listener: SQLClient handles the
377
+ // driver's `error` event and only re-emits when someone is listening, and the pool
378
+ // drops the flagged client on the next borrow. This just makes the reconnect
379
+ // visible in the log.
357
380
  if (client.on && client.listenerCount && !client.listenerCount('error')) {
358
- client.on('error', (err) => this.log.warn(`SQL client error: ${(0, errors_1.formatError)(err)}`));
381
+ client.on('error', (err) => this.log.warn(`SQL connection lost, will reconnect: ${(0, errors_1.formatError)(err)}`));
359
382
  }
383
+ // A real, working connection was handed out - this, not the mere existence of a pool
384
+ // object, is what info.connection reports (#374).
385
+ this.consecutiveBorrowFailures = 0;
386
+ this.setConnected(true);
360
387
  }
361
388
  else if (!client) {
362
389
  this.activeConnections--;
390
+ // Repeated borrow failures (e.g. connect ETIMEDOUT while the server is down) mean the
391
+ // database is effectively unreachable; previously info.connection stayed true forever.
392
+ if (++this.consecutiveBorrowFailures >= 5) {
393
+ this.setConnected(false);
394
+ }
363
395
  }
364
396
  callback(err, client);
365
397
  });
@@ -645,24 +677,20 @@ class SqlAdapter extends adapter_core_1.Adapter {
645
677
  };
646
678
  }
647
679
  else if (this.config.dbtype === 'mysql') {
648
- mySQLOptions = {
649
- host: this.config.host, // needed for PostgreSQL , MySQL
650
- user: this.config.user || '',
651
- password: this.config.password || '',
652
- port: this.config.port || undefined,
653
- ssl: this.config.encrypt
654
- ? {
655
- rejectUnauthorized: !!this.config.rejectUnauthorized,
656
- }
657
- : undefined,
658
- };
680
+ mySQLOptions = (0, connection_options_1.buildMySQLOptions)(this.config);
659
681
  }
660
682
  else if (this.config.dbtype === 'sqlite') {
661
683
  sqLiteOptions = { fileName: this.getSqlLiteDir(this.config.fileName) };
662
684
  }
663
- if (this.config.dbtype === 'postgresql' && !this.postgresDbCreated && postgreSQLOptions) {
685
+ if (this.config.dbtype === 'postgresql' &&
686
+ !this.config.doNotCreateDatabase &&
687
+ !this.postgresDbCreated &&
688
+ postgreSQLOptions) {
664
689
  // special solution for postgres. Connect first to Db "postgres", create new DB "iobroker" and then connect to "iobroker" DB.
665
- // connect first to DB postgres and create iobroker DB
690
+ // connect first to DB postgres and create iobroker DB.
691
+ // With "do not create database" this whole phase is skipped and the adapter connects
692
+ // straight to the configured database: a restricted role or a managed PostgreSQL often
693
+ // has no access to the maintenance DB "postgres" at all (#404, #285).
666
694
  this.log.info(`Postgres connection options: ${JSON.stringify(postgreSQLOptions).replace(postgreSQLOptions.password || '******', '****')}`);
667
695
  const _client = new postgresql_client_1.PostgreSQLClient(postgreSQLOptions);
668
696
  _client.on?.('error', (err) => this.log.warn(`SQL client error: ${(0, errors_1.formatError)(err)}`));
@@ -678,40 +706,29 @@ class SqlAdapter extends adapter_core_1.Adapter {
678
706
  }, 30000);
679
707
  return;
680
708
  }
681
- if (this.config.doNotCreateDatabase) {
709
+ _client.execute(`CREATE DATABASE ${this.config.dbname};`, (err) => {
682
710
  _client.disconnect();
683
- this.postgresDbCreated = true;
684
- this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
685
- this.reconnectTimeout = setTimeout(() => {
686
- this.reconnectTimeout = null;
687
- this.connect(callback);
688
- }, 100);
689
- }
690
- else {
691
- _client.execute(`CREATE DATABASE ${this.config.dbname};`, (err) => {
692
- _client.disconnect();
693
- const typedError = err;
694
- if (typedError && typedError.code !== '42P04') {
695
- // if error not about yet exists
696
- this.postgresDbCreated = false;
697
- this.logConnectionError(typedError, `Cannot create database ${this.config.dbname}`);
698
- this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
699
- this.reconnectTimeout = setTimeout(() => {
700
- this.reconnectTimeout = null;
701
- this.connect(callback);
702
- }, 30000);
703
- }
704
- else {
705
- // remember that DB is created
706
- this.postgresDbCreated = true;
707
- this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
708
- this.reconnectTimeout = setTimeout(() => {
709
- this.reconnectTimeout = null;
710
- this.connect(callback);
711
- }, 100);
712
- }
713
- });
714
- }
711
+ const typedError = err;
712
+ if (typedError && typedError.code !== '42P04') {
713
+ // if error not about yet exists
714
+ this.postgresDbCreated = false;
715
+ this.logConnectionError(typedError, `Cannot create database ${this.config.dbname}`);
716
+ this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
717
+ this.reconnectTimeout = setTimeout(() => {
718
+ this.reconnectTimeout = null;
719
+ this.connect(callback);
720
+ }, 30000);
721
+ }
722
+ else {
723
+ // remember that DB is created
724
+ this.postgresDbCreated = true;
725
+ this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
726
+ this.reconnectTimeout = setTimeout(() => {
727
+ this.reconnectTimeout = null;
728
+ this.connect(callback);
729
+ }, 100);
730
+ }
731
+ });
715
732
  });
716
733
  }
717
734
  if (this.config.dbtype === 'postgresql' && postgreSQLOptions) {
@@ -806,8 +823,11 @@ class SqlAdapter extends adapter_core_1.Adapter {
806
823
  }
807
824
  async testConnection(msg) {
808
825
  if (!msg?.message?.config) {
826
+ // Not a database problem: the request reached us without any settings. The admin builds
827
+ // the payload from a template and drops it silently when the result does not parse, so
828
+ // "invalid config" sent people looking at settings that were fine (#355).
809
829
  if (msg.callback) {
810
- this.sendTo(msg.from, msg.command, { error: 'invalid config' }, msg.callback);
830
+ this.sendTo(msg.from, msg.command, { error: 'The test request arrived without a configuration' }, msg.callback);
811
831
  }
812
832
  return;
813
833
  }
@@ -827,7 +847,11 @@ class SqlAdapter extends adapter_core_1.Adapter {
827
847
  user: config.user || '',
828
848
  password: config.password || '',
829
849
  port: config.port || undefined,
830
- database: 'postgres',
850
+ // With "do not create database" the configured database must be tested directly: a
851
+ // restricted role or a managed PostgreSQL may have no access to the maintenance DB
852
+ // "postgres" at all, so testing against it reports a failure for a perfectly good
853
+ // configuration (#404, #285).
854
+ database: config.doNotCreateDatabase ? config.dbname || 'iobroker' : 'postgres',
831
855
  ssl: config.encrypt
832
856
  ? {
833
857
  rejectUnauthorized: !!config.rejectUnauthorized,
@@ -848,17 +872,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
848
872
  };
849
873
  }
850
874
  else if (config.dbtype === 'mysql') {
851
- mySQLOptions = {
852
- host: config.host, // needed for PostgreSQL , MySQL
853
- user: config.user || '',
854
- password: config.password || '',
855
- port: config.port || undefined,
856
- ssl: config.encrypt
857
- ? {
858
- rejectUnauthorized: !!config.rejectUnauthorized,
859
- }
860
- : undefined,
861
- };
875
+ mySQLOptions = (0, connection_options_1.buildMySQLOptions)(config);
862
876
  }
863
877
  else if (config.dbtype === 'sqlite') {
864
878
  sqLiteOptions = { fileName: this.getSqlLiteDir(config.fileName) };
@@ -1080,8 +1094,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
1080
1094
  }
1081
1095
  }
1082
1096
  finish(callback) {
1083
- let count = 0;
1084
1097
  const now = Date.now();
1098
+ // How many datapoints still have to report in. `allFinished()` used to be reached through a
1099
+ // counter shared by every write of every datapoint, which fired it as soon as any one of
1100
+ // them happened to finish last - see #577.
1101
+ let datapointsPending = 0;
1102
+ let allDispatched = false;
1085
1103
  const allFinished = () => {
1086
1104
  if (this.clientPool) {
1087
1105
  this.clientPool.close();
@@ -1098,9 +1116,29 @@ class SqlAdapter extends adapter_core_1.Adapter {
1098
1116
  this.finished = true;
1099
1117
  }
1100
1118
  };
1119
+ const datapointDone = () => {
1120
+ datapointsPending--;
1121
+ if (allDispatched && datapointsPending <= 0) {
1122
+ allFinished();
1123
+ }
1124
+ };
1125
+ /**
1126
+ * Write out everything one datapoint still holds, then report it done.
1127
+ *
1128
+ * The buffered values are flushed unconditionally. They used to be written only from inside
1129
+ * the `skipped` and `writeNulls` branches, so a datapoint with neither - every SQLite
1130
+ * instance, since writeNulls is forced off there - lost its buffer (#577).
1131
+ *
1132
+ * The counter is per datapoint. It used to be shared across all of them, so the flush ran on
1133
+ * whichever callback happened to bring the shared count to zero and only that one datapoint's
1134
+ * buffer was written; the same counter also let `allFinished()` close the pool while later
1135
+ * datapoints were still being dispatched.
1136
+ *
1137
+ * @param id the datapoint to finish
1138
+ */
1101
1139
  const finishId = (id) => {
1102
1140
  if (!this.sqlDPs[id]) {
1103
- return;
1141
+ return datapointDone();
1104
1142
  }
1105
1143
  if (this.sqlDPs[id].relogTimeout) {
1106
1144
  clearTimeout(this.sqlDPs[id].relogTimeout);
@@ -1111,16 +1149,31 @@ class SqlAdapter extends adapter_core_1.Adapter {
1111
1149
  this.sqlDPs[id].timeout = null;
1112
1150
  }
1113
1151
  const state = this.sqlDPs[id].state ? { ...this.sqlDPs[id].state } : null;
1152
+ // Values this datapoint has to write before its buffer goes out, so that the boundary
1153
+ // markers keep their order relative to the buffered values.
1154
+ let pendingWrites = 0;
1155
+ const flushBuffer = () => {
1156
+ if (pendingWrites) {
1157
+ return;
1158
+ }
1159
+ const buffered = this.sqlDPs[id]?.list;
1160
+ // Not every entry in sqlDPs is a configured datapoint: storeState, getHistory and
1161
+ // the object view create stubs with `sqlDPs[id] ||= {}` just to carry an index, and
1162
+ // those have no buffer. The datapoint can also disappear while the writes above are
1163
+ // still in flight.
1164
+ if (!buffered?.length) {
1165
+ return datapointDone();
1166
+ }
1167
+ this.pushValuesIntoDB(id, buffered, () => datapointDone());
1168
+ };
1169
+ const writeDone = () => {
1170
+ pendingWrites--;
1171
+ flushBuffer();
1172
+ };
1114
1173
  if (this.sqlDPs[id].skipped &&
1115
1174
  !(this.sqlDPs[id].config && this.sqlDPs[id].config.disableSkippedValueLogging)) {
1116
- count++;
1117
- this.pushValueIntoDB(id, this.sqlDPs[id].skipped, false, true, () => {
1118
- if (!--count) {
1119
- this.pushValuesIntoDB(id, this.sqlDPs[id].list, () => {
1120
- allFinished();
1121
- });
1122
- }
1123
- });
1175
+ pendingWrites++;
1176
+ this.pushValueIntoDB(id, this.sqlDPs[id].skipped, false, true, writeDone);
1124
1177
  this.sqlDPs[id].skipped = null;
1125
1178
  }
1126
1179
  const nullValue = {
@@ -1132,40 +1185,28 @@ class SqlAdapter extends adapter_core_1.Adapter {
1132
1185
  from: `system.adapter.${this.namespace}`,
1133
1186
  };
1134
1187
  if (this.sqlDPs[id].config && this.config.writeNulls) {
1188
+ pendingWrites++;
1135
1189
  if (this.sqlDPs[id].config.changesOnly && state && state.val !== null) {
1136
- count++;
1137
- ((_id, _state, _nullValue) => {
1138
- _state.ts = now;
1139
- _state.from = `system.adapter.${this.namespace}`;
1140
- nullValue.ts += 4;
1141
- nullValue.lc += 4; // because of MS SQL
1142
- this.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
1143
- this.pushValueIntoDB(_id, _state, false, true, () => {
1144
- // terminate values with null to indicate adapter stop. timestamp + 1
1145
- this.log.debug(`Write 2/2 "null" _id: ${_id}`);
1146
- this.pushValueIntoDB(_id, _nullValue, false, true, () => {
1147
- if (!--count) {
1148
- this.pushValuesIntoDB(id, this.sqlDPs[id].list, () => {
1149
- allFinished();
1150
- });
1151
- }
1152
- });
1153
- });
1154
- })(id, state, nullValue);
1190
+ state.ts = now;
1191
+ state.from = `system.adapter.${this.namespace}`;
1192
+ nullValue.ts += 4;
1193
+ nullValue.lc += 4; // because of MS SQL
1194
+ this.log.debug(`Write 1/2 "${state.val}" _id: ${id}`);
1195
+ this.pushValueIntoDB(id, state, false, true, () => {
1196
+ // terminate values with null to indicate adapter stop. timestamp + 1
1197
+ this.log.debug(`Write 2/2 "null" _id: ${id}`);
1198
+ this.pushValueIntoDB(id, nullValue, false, true, writeDone);
1199
+ });
1155
1200
  }
1156
1201
  else {
1157
1202
  // terminate values with null to indicate adapter stop. timestamp + 1
1158
- count++;
1159
1203
  this.log.debug(`Write 0 NULL _id: ${id}`);
1160
- this.pushValueIntoDB(id, nullValue, false, true, () => {
1161
- if (!--count) {
1162
- this.pushValuesIntoDB(id, this.sqlDPs[id].list, () => {
1163
- allFinished();
1164
- });
1165
- }
1166
- });
1204
+ this.pushValueIntoDB(id, nullValue, false, true, writeDone);
1167
1205
  }
1168
1206
  }
1207
+ // Runs straight away when this datapoint had nothing else to write, otherwise the last
1208
+ // writeDone() gets here.
1209
+ flushBuffer();
1169
1210
  };
1170
1211
  if (!this.subscribeAll) {
1171
1212
  for (const _id in this.sqlDPs) {
@@ -1214,9 +1255,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
1214
1255
  continue;
1215
1256
  }
1216
1257
  dpcount++;
1258
+ datapointsPending++;
1217
1259
  delay += dpcount % 50 === 0 ? 1000 : 0;
1218
1260
  setTimeout(finishId, delay, id);
1219
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.
1264
+ allDispatched = true;
1220
1265
  if (!dpcount && callback) {
1221
1266
  if (this.clientPool) {
1222
1267
  this.clientPool.close();
@@ -1228,6 +1273,17 @@ class SqlAdapter extends adapter_core_1.Adapter {
1228
1273
  }
1229
1274
  }
1230
1275
  processMessage(msg) {
1276
+ // Answer with an error instead of dereferencing a `sqlFuncs` that is still null. Guarding
1277
+ // here covers every database-backed command at once; the alternative would be a check at
1278
+ // each of the ~30 `this.sqlFuncs!` uses, every one of which is only reachable from here
1279
+ // during this window. The decision itself lives in src/lib/messages.ts so that it can be
1280
+ // unit tested without importing this file - see the comment there.
1281
+ const notInitialized = (0, messages_1.guardUninitialized)(msg.command, !!this.sqlFuncs);
1282
+ if (notInitialized) {
1283
+ this.log.warn(`Cannot process "${msg.command}": the adapter is not initialized yet`);
1284
+ this.sendTo(msg.from, msg.command, notInitialized, msg.callback);
1285
+ return;
1286
+ }
1231
1287
  if (msg.command === 'features') {
1232
1288
  this.sendTo(msg.from, msg.command, { supportedFeatures: ['update', 'delete', 'deleteRange', 'deleteAll', 'storeState'] }, msg.callback);
1233
1289
  }
@@ -1267,6 +1323,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
1267
1323
  else if (msg.command === 'getDatapoints') {
1268
1324
  this.getDatapoints(msg);
1269
1325
  }
1326
+ else if (msg.command === 'getDpStatistics') {
1327
+ this.getDpStatistics(msg);
1328
+ }
1329
+ else if (msg.command === 'cleanupOrphaned') {
1330
+ this.cleanupOrphaned(msg);
1331
+ }
1270
1332
  else if (msg.command === 'getDpOverview') {
1271
1333
  this.getDpOverview(msg);
1272
1334
  }
@@ -1424,7 +1486,10 @@ class SqlAdapter extends adapter_core_1.Adapter {
1424
1486
  }
1425
1487
  if (this.sqlDPs[id].state && settings.changesOnly) {
1426
1488
  if (!settings.changesRelogInterval) {
1427
- if ((this.sqlDPs[id].state.val !== null || state.val === null) && state.ts !== state.lc) {
1489
+ // Compare the value, not `ts !== lc`: an alias carries the lc of its
1490
+ // source, so a source change its read converter rounds away still arrives
1491
+ // with ts === lc (#295).
1492
+ if ((0, values_1.isSameValue)(this.sqlDPs[id].state.val, state.val)) {
1428
1493
  // remember new timestamp
1429
1494
  if (!valueUnstable && !settings.disableSkippedValueLogging) {
1430
1495
  this.sqlDPs[id].skipped = state;
@@ -1435,8 +1500,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1435
1500
  }
1436
1501
  }
1437
1502
  else if (this.sqlDPs[id].lastLogTime) {
1438
- if ((this.sqlDPs[id].state.val !== null || state.val === null) &&
1439
- state.ts !== state.lc &&
1503
+ if ((0, values_1.isSameValue)(this.sqlDPs[id].state.val, state.val) &&
1440
1504
  Math.abs(this.sqlDPs[id].lastLogTime - state.ts) < settings.changesRelogInterval * 1000) {
1441
1505
  // remember new timestamp
1442
1506
  if (!valueUnstable && !settings.disableSkippedValueLogging) {
@@ -1446,7 +1510,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1446
1510
  this.log.debug(`value not changed ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1447
1511
  return;
1448
1512
  }
1449
- if (state.ts !== state.lc) {
1513
+ if ((0, values_1.isSameValue)(this.sqlDPs[id].state.val, state.val)) {
1450
1514
  settings.enableDebugLogs &&
1451
1515
  this.log.debug(`value-not-changed-relog ${id}, value=${state.val}, lastLogTime=${this.sqlDPs[id].lastLogTime}, ts=${state.ts}`);
1452
1516
  ignoreDebounce = true;
@@ -1475,7 +1539,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
1475
1539
  }
1476
1540
  if (settings.counter && this.sqlDPs[id].state) {
1477
1541
  if (this.sqlDPs[id].type !== types.number) {
1478
- this.log.error('Counter must have type "number"!');
1542
+ // Without the ID this is unsearchable: the message fires for every value of
1543
+ // the misconfigured datapoint and says nothing about which one it is. Reported
1544
+ // once per datapoint rather than once per value, because the repetition was
1545
+ // half of the problem. See https://github.com/ioBroker/ioBroker.sql/issues/320
1546
+ if (!this.sqlDPs[id].counterTypeReported) {
1547
+ this.sqlDPs[id].counterTypeReported = true;
1548
+ this.log.error((0, errors_1.counterTypeMismatch)(id, storageTypes[this.sqlDPs[id].type] ?? this.sqlDPs[id].type));
1549
+ }
1479
1550
  }
1480
1551
  else if (state.val === null ||
1481
1552
  this.sqlDPs[id].state.val === null ||
@@ -2016,7 +2087,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2016
2087
  }
2017
2088
  // Check SQL connection
2018
2089
  if (!this.clientPool) {
2019
- this.log.warn('No Connection to database');
2090
+ this.log.warn(`No connection to the database, cannot store the value of "${id}"`);
2020
2091
  if (cb) {
2021
2092
  setImmediate(() => cb(new Error('No Connection to database')));
2022
2093
  }
@@ -2948,7 +3019,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
2948
3019
  */
2949
3020
  #readIdIndexAndType(id, cb) {
2950
3021
  if (!this.clientPool) {
2951
- this.log.warn('No Connection to database');
3022
+ this.log.warn(`No connection to the database, cannot look up "${id}"`);
2952
3023
  setImmediate(() => cb(new Error('No Connection to database')));
2953
3024
  return;
2954
3025
  }
@@ -3411,6 +3482,169 @@ class SqlAdapter extends adapter_core_1.Adapter {
3411
3482
  * In contrast to `getDpOverview`, this is only one SELECT and answers immediately: `getDpOverview`
3412
3483
  * additionally determines the first timestamp of every datapoint and pauses 5 seconds between the types.
3413
3484
  */
3485
+ /**
3486
+ * Collect per-datapoint statistics for the whole database.
3487
+ *
3488
+ * Costs one `GROUP BY id` plus one size query per time series table, not one query per
3489
+ * datapoint: a database that has collected data for years holds thousands of IDs.
3490
+ */
3491
+ async #collectStatistics() {
3492
+ const client = await new Promise((resolve, reject) => this.borrowClientFromPool((err, c) => {
3493
+ if (err || !c) {
3494
+ this.returnClientToPool(c);
3495
+ reject(err || new Error('No client'));
3496
+ }
3497
+ else {
3498
+ resolve(c);
3499
+ }
3500
+ }));
3501
+ const execute = (query) => new Promise((resolve, reject) => client.execute(query, (e, rows) => (e ? reject(e) : resolve(rows || []))));
3502
+ try {
3503
+ const datapoints = await execute(this.sqlFuncs.getIdSelect(this.config.dbname));
3504
+ const counts = {};
3505
+ const tableOfIndex = {};
3506
+ const avgRowLength = {};
3507
+ for (const table of STAT_TABLES) {
3508
+ const rows = await execute(this.sqlFuncs.getIdCounts(this.config.dbname, table));
3509
+ for (const row of rows) {
3510
+ // ts_counter mirrors values that also live in ts_number, so it must not
3511
+ // overwrite the count of the table that actually holds the series
3512
+ if (table === 'ts_counter' && counts[row.id]) {
3513
+ continue;
3514
+ }
3515
+ counts[row.id] = {
3516
+ cnt: Number(row.cnt),
3517
+ firstTs: Number(row.first_ts),
3518
+ lastTs: Number(row.last_ts),
3519
+ };
3520
+ tableOfIndex[row.id] = table;
3521
+ }
3522
+ try {
3523
+ const [size] = await execute(this.sqlFuncs.getTableSize(this.config.dbname, table));
3524
+ avgRowLength[table] = size ? Number(size.avg_row_length) : null;
3525
+ }
3526
+ catch (e) {
3527
+ // SQLite's dbstat is not compiled into every build and a restricted role may
3528
+ // not reach the catalog. Report "size unknown" rather than failing the request.
3529
+ this.log.debug(`Cannot determine the size of ${table}: ${e?.message || e}`);
3530
+ avgRowLength[table] = null;
3531
+ }
3532
+ }
3533
+ const stats = [];
3534
+ for (const dp of datapoints) {
3535
+ const measured = counts[dp.id];
3536
+ const table = tableOfIndex[dp.id] || null;
3537
+ let objectExists = false;
3538
+ try {
3539
+ objectExists = !!(await this.getForeignObjectAsync(dp.name));
3540
+ }
3541
+ catch {
3542
+ // treat an unreadable object as missing; the cleanup preview shows it either way
3543
+ }
3544
+ stats.push({
3545
+ id: dp.name,
3546
+ index: dp.id,
3547
+ type: typeof dp.type === 'number' ? storageTypes[dp.type] : null,
3548
+ table,
3549
+ count: measured?.cnt || 0,
3550
+ firstTs: measured?.firstTs ?? null,
3551
+ lastTs: measured?.lastTs ?? null,
3552
+ estimatedBytes: (0, statistics_1.estimateBytes)(measured?.cnt || 0, table ? avgRowLength[table] : null),
3553
+ status: (0, statistics_1.classifyDatapoint)(objectExists, !!this.sqlDPs[dp.name]),
3554
+ });
3555
+ }
3556
+ stats.sort((a, b) => (a.id > b.id ? 1 : a.id < b.id ? -1 : 0));
3557
+ return stats;
3558
+ }
3559
+ finally {
3560
+ this.returnClientToPool(client);
3561
+ }
3562
+ }
3563
+ /**
3564
+ * Delete every stored value of the given datapoints, and their `datapoints` rows.
3565
+ *
3566
+ * @param victims the datapoints to remove
3567
+ */
3568
+ async #deleteDatapoints(victims) {
3569
+ const client = await new Promise((resolve, reject) => this.borrowClientFromPool((err, c) => {
3570
+ if (err || !c) {
3571
+ this.returnClientToPool(c);
3572
+ reject(err || new Error('No client'));
3573
+ }
3574
+ else {
3575
+ resolve(c);
3576
+ }
3577
+ }));
3578
+ const execute = (query) => new Promise((resolve, reject) => client.execute(query, e => (e ? reject(e) : resolve())));
3579
+ try {
3580
+ let rows = 0;
3581
+ for (const victim of victims) {
3582
+ // Delete from every table, not only the one the type suggests: a datapoint whose
3583
+ // storage type was switched over the years has rows in more than one of them.
3584
+ for (const table of STAT_TABLES) {
3585
+ await execute(this.sqlFuncs.deleteFromTable(this.config.dbname, table, victim.index));
3586
+ }
3587
+ await execute(this.sqlFuncs.deleteDatapoint(this.config.dbname, victim.index));
3588
+ // Drop the in-memory mapping as well, so a state that comes back gets a fresh index
3589
+ delete this.from[victim.id];
3590
+ rows += victim.count;
3591
+ }
3592
+ return { datapoints: victims.length, rows };
3593
+ }
3594
+ finally {
3595
+ this.returnClientToPool(client);
3596
+ }
3597
+ }
3598
+ /**
3599
+ * Answer `getDpStatistics` with one row per datapoint plus totals.
3600
+ *
3601
+ * @param msg the message to answer
3602
+ */
3603
+ getDpStatistics(msg) {
3604
+ void this.#collectStatistics()
3605
+ .then(stats => this.sendTo(msg.from, msg.command, { success: true, result: stats, summary: (0, statistics_1.summarize)(stats) }, msg.callback))
3606
+ .catch(e => {
3607
+ this.log.error(`Cannot collect statistics: ${(0, errors_1.formatError)(e)}`);
3608
+ this.sendTo(msg.from, msg.command, { error: e?.message || String(e) }, msg.callback);
3609
+ });
3610
+ }
3611
+ /**
3612
+ * Answer `cleanupOrphaned`: remove the values of datapoints nobody logs any more.
3613
+ *
3614
+ * Without `confirm: true` nothing is deleted and the answer only reports what a confirmed run
3615
+ * would remove, so the GUI can show the list and the counts before anything is lost. The same
3616
+ * collection feeds both, so the preview and the deletion cannot disagree about what is
3617
+ * orphaned.
3618
+ *
3619
+ * @param msg the message to answer
3620
+ */
3621
+ cleanupOrphaned(msg) {
3622
+ const scope = msg.message?.scope || {};
3623
+ const confirmed = msg.message?.confirm === true;
3624
+ void this.#collectStatistics()
3625
+ .then(async (stats) => {
3626
+ const victims = (0, statistics_1.selectForCleanup)(stats, scope);
3627
+ const preview = {
3628
+ datapoints: victims.length,
3629
+ rows: victims.reduce((sum, v) => sum + v.count, 0),
3630
+ estimatedBytes: victims.some(v => v.estimatedBytes === null)
3631
+ ? null
3632
+ : victims.reduce((sum, v) => sum + (v.estimatedBytes || 0), 0),
3633
+ items: victims,
3634
+ };
3635
+ if (!confirmed) {
3636
+ this.sendTo(msg.from, msg.command, { success: true, dryRun: true, ...preview }, msg.callback);
3637
+ return;
3638
+ }
3639
+ const deleted = await this.#deleteDatapoints(victims);
3640
+ this.log.info(`Cleanup removed ${deleted.rows} values of ${deleted.datapoints} datapoint(s) that are not logged any more`);
3641
+ this.sendTo(msg.from, msg.command, { success: true, dryRun: false, ...preview, deleted }, msg.callback);
3642
+ })
3643
+ .catch(e => {
3644
+ this.log.error(`Cleanup failed: ${(0, errors_1.formatError)(e)}`);
3645
+ this.sendTo(msg.from, msg.command, { error: e?.message || String(e) }, msg.callback);
3646
+ });
3647
+ }
3414
3648
  getDatapoints(msg) {
3415
3649
  const query = this.sqlFuncs.getIdSelect(this.config.dbname);
3416
3650
  this.log.debug(query);
@@ -3623,6 +3857,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
3623
3857
  config.dockerMysql.port = parseInt(config.dockerMysql.port || '3306', 10) || 3306;
3624
3858
  config.port = config.dockerMysql.port;
3625
3859
  config.host = config.dockerMysql.bind || '127.0.0.1';
3860
+ // The container is reached over TCP on the published port; a socket path left over from a
3861
+ // previous manual setup would otherwise win over it in buildMySQLOptions().
3862
+ config.socketPath = '';
3626
3863
  config.multiRequests = true;
3627
3864
  config.maxConnections = 100;
3628
3865
  if (config.dockerPhpMyAdmin) {
@@ -3700,6 +3937,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
3700
3937
  config.writeNulls = false;
3701
3938
  }
3702
3939
  config.port = parseInt(config.port, 10) || 0;
3940
+ // Only MySQL can use a unix socket. The field stays visible for other dialects in older
3941
+ // configurations, so clear it rather than letting it silently change how they connect.
3942
+ config.socketPath = typeof config.socketPath === 'string' ? config.socketPath.trim() : '';
3943
+ if (config.socketPath && config.dbtype !== 'mysql') {
3944
+ this.log.warn(`A unix socket is only supported for MySQL, ignoring it for "${config.dbtype}"`);
3945
+ config.socketPath = '';
3946
+ }
3703
3947
  if (config.round !== null && config.round !== undefined && config.round !== '') {
3704
3948
  config.round = parseInt(config.round, 10);
3705
3949
  if (!isFinite(config.round) || config.round < 0) {
@@ -3793,7 +4037,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
3793
4037
  // Check that the user 'iobroker' exists
3794
4038
  await this.createUserInDocker();
3795
4039
  }
3796
- if (config.dbtype === 'sqlite' || this.config.host) {
4040
+ // A MySQL socket connection has no host, so it has to open this gate on its own - otherwise
4041
+ // the adapter would start, report nothing and never call connect() (#104).
4042
+ if (config.dbtype === 'sqlite' || this.config.host || this.config.socketPath) {
3797
4043
  this.connect(async () => {
3798
4044
  // `enableHistory` only writes the object and leaves the activation to `objectChange`, so
3799
4045
  // subscribing after the view was read left a gap: a message that arrived in between was