iobroker.sql 4.0.4 → 4.1.3

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 (56) hide show
  1. package/README.md +96 -14
  2. package/admin/custom/assets/Components-nTLElZ7y.js +1 -0
  3. package/admin/custom/assets/DataBrowser-CyjKP_L-.js +1 -0
  4. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__SqlComponentsSet__mf_owner__1-BKlHk-3o.js +1 -0
  5. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-1_ecMmwM.js +1243 -0
  6. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-BJcL2b_b.js +1494 -0
  7. package/admin/custom/assets/_virtual_mf___mfe_internal__SqlComponentsSet__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-DOWbo5mU.js +9 -0
  8. package/admin/custom/assets/hostInit-CJsaB1F7.js +1 -0
  9. package/admin/custom/assets/index-D4ovp6PK.js +1 -0
  10. package/admin/custom/assets/lib-B-9Z42f0.js +3 -0
  11. package/admin/custom/assets/mf-entry-bootstrap-0-9382e792.js +41 -0
  12. package/admin/custom/assets/rolldown-runtime-C0FnF6B9.js +1 -0
  13. package/admin/custom/assets/virtualExposes-C4J_LR3_.js +1 -0
  14. package/admin/custom/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__SqlComponentsSet__customComponents_js-C7xpzcn4.js +1 -0
  15. package/admin/custom/assets/virtual_mf-exposes___mfe_internal__SqlComponentsSet__customComponents_js-DBI8_iGe.js +2 -0
  16. package/admin/custom/assets/vite-preload-helper-B7qeedMF.js +1 -0
  17. package/admin/custom/customComponents.js +12 -0
  18. package/admin/custom/i18n/de.json +30 -0
  19. package/admin/custom/i18n/en.json +30 -0
  20. package/admin/custom/i18n/es.json +30 -0
  21. package/admin/custom/i18n/fr.json +30 -0
  22. package/admin/custom/i18n/it.json +30 -0
  23. package/admin/custom/i18n/nl.json +30 -0
  24. package/admin/custom/i18n/pl.json +30 -0
  25. package/admin/custom/i18n/pt.json +30 -0
  26. package/admin/custom/i18n/ru.json +30 -0
  27. package/admin/custom/i18n/zh-cn.json +30 -0
  28. package/admin/custom/mf-manifest.json +1 -0
  29. package/admin/i18n/{de/translations.json → de.json} +7 -1
  30. package/admin/i18n/{en/translations.json → en.json} +7 -1
  31. package/admin/i18n/{es/translations.json → es.json} +7 -1
  32. package/admin/i18n/{fr/translations.json → fr.json} +7 -1
  33. package/admin/i18n/{it/translations.json → it.json} +7 -1
  34. package/admin/i18n/{nl/translations.json → nl.json} +7 -1
  35. package/admin/i18n/{pl/translations.json → pl.json} +7 -1
  36. package/admin/i18n/{pt/translations.json → pt.json} +7 -1
  37. package/admin/i18n/{ru/translations.json → ru.json} +7 -1
  38. package/admin/i18n/{zh-cn/translations.json → zh-cn.json} +7 -1
  39. package/admin/jsonConfig.json +14 -0
  40. package/admin/jsonCustom.json +18 -0
  41. package/build/lib/errors.js +115 -0
  42. package/build/lib/errors.js.map +1 -0
  43. package/build/lib/mssql.js +22 -0
  44. package/build/lib/mssql.js.map +1 -1
  45. package/build/lib/mysql.js +22 -0
  46. package/build/lib/mysql.js.map +1 -1
  47. package/build/lib/postgresql.js +22 -0
  48. package/build/lib/postgresql.js.map +1 -1
  49. package/build/lib/sqlite.js +22 -0
  50. package/build/lib/sqlite.js.map +1 -1
  51. package/build/main.js +375 -99
  52. package/build/main.js.map +1 -1
  53. package/io-package.json +40 -40
  54. package/package.json +14 -7
  55. package/build/lib/aggregate.js +0 -1490
  56. package/build/lib/aggregate.js.map +0 -1
package/build/main.js CHANGED
@@ -35,7 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.SqlAdapter = void 0;
37
37
  const adapter_core_1 = require("@iobroker/adapter-core"); // Get common adapter utils
38
- const aggregate_1 = require("./lib/aggregate");
38
+ const aggregate_1 = require("@iobroker/aggregate");
39
39
  const node_fs_1 = require("node:fs");
40
40
  const node_path_1 = require("node:path");
41
41
  const MSSQL = __importStar(require("./lib/mssql"));
@@ -46,6 +46,7 @@ const mssql_client_1 = require("./lib/mssql-client");
46
46
  const mysql_client_1 = require("./lib/mysql-client");
47
47
  const postgresql_client_1 = require("./lib/postgresql-client");
48
48
  const sqlite3_client_1 = require("./lib/sqlite3-client");
49
+ const errors_1 = require("./lib/errors");
49
50
  const SQLFuncs = {
50
51
  mssql: {
51
52
  init: MSSQL.init,
@@ -62,6 +63,8 @@ const SQLFuncs = {
62
63
  getHistory: MSSQL.getHistory,
63
64
  deleteFromTable: MSSQL.deleteFromTable,
64
65
  update: MSSQL.update,
66
+ getRawEntries: MSSQL.getRawEntries,
67
+ getRawEntriesCount: MSSQL.getRawEntriesCount,
65
68
  },
66
69
  mysql: {
67
70
  init: MySQL.init,
@@ -78,6 +81,8 @@ const SQLFuncs = {
78
81
  getHistory: MySQL.getHistory,
79
82
  deleteFromTable: MySQL.deleteFromTable,
80
83
  update: MySQL.update,
84
+ getRawEntries: MySQL.getRawEntries,
85
+ getRawEntriesCount: MySQL.getRawEntriesCount,
81
86
  },
82
87
  postgresql: {
83
88
  init: PostgreSQL.init,
@@ -94,6 +99,8 @@ const SQLFuncs = {
94
99
  getHistory: PostgreSQL.getHistory,
95
100
  deleteFromTable: PostgreSQL.deleteFromTable,
96
101
  update: PostgreSQL.update,
102
+ getRawEntries: PostgreSQL.getRawEntries,
103
+ getRawEntriesCount: PostgreSQL.getRawEntriesCount,
97
104
  },
98
105
  sqlite: {
99
106
  init: SQLite.init,
@@ -110,6 +117,8 @@ const SQLFuncs = {
110
117
  getHistory: SQLite.getHistory,
111
118
  deleteFromTable: SQLite.deleteFromTable,
112
119
  update: SQLite.update,
120
+ getRawEntries: SQLite.getRawEntries,
121
+ getRawEntriesCount: SQLite.getRawEntriesCount,
113
122
  },
114
123
  };
115
124
  const clients = {
@@ -165,6 +174,10 @@ function isEqual(a, b) {
165
174
  return true;
166
175
  }
167
176
  const MAX_TASKS = 100;
177
+ /** Maximal number of rows one `getRawEntries` call may return */
178
+ const MAX_RAW_ENTRIES = 2000;
179
+ /** How often an unchanged connection error is repeated as error in the log */
180
+ const REPEATED_ERROR_INTERVAL = 3_600_000;
168
181
  function sortByTs(a, b) {
169
182
  const aTs = a.ts;
170
183
  const bTs = b.ts;
@@ -193,6 +206,10 @@ class SqlAdapter extends adapter_core_1.Adapter {
193
206
  postgresDbCreated = false;
194
207
  lockTasks = false;
195
208
  sqlFuncs = null;
209
+ /** Last connection error already written to the log, to not repeat it on every reconnect attempt */
210
+ lastConnectionError = null;
211
+ lastConnectionErrorTs = 0;
212
+ connectionErrorCount = 0;
196
213
  constructor(options = {}) {
197
214
  super({
198
215
  ...options,
@@ -338,7 +355,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
338
355
  if (!err && client) {
339
356
  // make sure we always have at least one error listener to prevent crashes
340
357
  if (client.on && client.listenerCount && !client.listenerCount('error')) {
341
- client.on('error', (err) => this.log.warn(`SQL client error: ${err}`));
358
+ client.on('error', (err) => this.log.warn(`SQL client error: ${(0, errors_1.formatError)(err)}`));
342
359
  }
343
360
  }
344
361
  else if (!client) {
@@ -536,6 +553,46 @@ class SqlAdapter extends adapter_core_1.Adapter {
536
553
  void this.setState('info.connection', this.sqlConnected, true);
537
554
  }
538
555
  }
556
+ /**
557
+ * Log a connection error without flooding the log.
558
+ *
559
+ * `connect()` retries every 30 seconds, so a database that is simply switched off would otherwise
560
+ * write the very same line 2880 times a day. The first occurrence is logged as error, repetitions of
561
+ * the identical message go to debug, and once an hour a reminder is logged that the database is
562
+ * still unreachable.
563
+ *
564
+ * @param err error to report
565
+ * @param prefix optional text in front of the error message
566
+ */
567
+ logConnectionError(err, prefix) {
568
+ const text = `${prefix ? `${prefix}: ` : ''}${(0, errors_1.formatError)(err)}`;
569
+ const now = Date.now();
570
+ if (text === this.lastConnectionError) {
571
+ this.connectionErrorCount++;
572
+ if (now - this.lastConnectionErrorTs >= REPEATED_ERROR_INTERVAL) {
573
+ this.lastConnectionErrorTs = now;
574
+ this.log.error(`${text} (still failing, ${this.connectionErrorCount} attempts)`);
575
+ }
576
+ else {
577
+ this.log.debug(`${text} (attempt ${this.connectionErrorCount})`);
578
+ }
579
+ }
580
+ else {
581
+ this.lastConnectionError = text;
582
+ this.lastConnectionErrorTs = now;
583
+ this.connectionErrorCount = 1;
584
+ this.log.error(text);
585
+ }
586
+ }
587
+ /** Forget the last connection error, so a new outage is logged again as error */
588
+ resetConnectionError() {
589
+ if (this.connectionErrorCount > 1) {
590
+ this.log.info(`Database is reachable again after ${this.connectionErrorCount} failed attempts`);
591
+ }
592
+ this.lastConnectionError = null;
593
+ this.lastConnectionErrorTs = 0;
594
+ this.connectionErrorCount = 0;
595
+ }
539
596
  connect(callback) {
540
597
  if (this.reconnectTimeout) {
541
598
  clearTimeout(this.reconnectTimeout);
@@ -608,10 +665,10 @@ class SqlAdapter extends adapter_core_1.Adapter {
608
665
  // connect first to DB postgres and create iobroker DB
609
666
  this.log.info(`Postgres connection options: ${JSON.stringify(postgreSQLOptions).replace(postgreSQLOptions.password || '******', '****')}`);
610
667
  const _client = new postgresql_client_1.PostgreSQLClient(postgreSQLOptions);
611
- _client.on?.('error', (err) => this.log.warn(`SQL client error: ${err}`));
668
+ _client.on?.('error', (err) => this.log.warn(`SQL client error: ${(0, errors_1.formatError)(err)}`));
612
669
  return _client.connect((err) => {
613
670
  if (err) {
614
- this.log.error(err.toString());
671
+ this.logConnectionError(err, `Cannot connect to ${this.config.host}`);
615
672
  if (this.reconnectTimeout) {
616
673
  clearTimeout(this.reconnectTimeout);
617
674
  }
@@ -637,7 +694,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
637
694
  if (typedError && typedError.code !== '42P04') {
638
695
  // if error not about yet exists
639
696
  this.postgresDbCreated = false;
640
- this.log.error(JSON.stringify(typedError));
697
+ this.logConnectionError(typedError, `Cannot create database ${this.config.dbname}`);
641
698
  this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
642
699
  this.reconnectTimeout = setTimeout(() => {
643
700
  this.reconnectTimeout = null;
@@ -681,8 +738,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
681
738
  if (err) {
682
739
  this.clientPool = null;
683
740
  this.setConnected(false);
684
- // JSON.stringify(Error) is "{}" and would swallow the message
685
- this.log.error(err.message || err.toString());
741
+ // JSON.stringify(Error) is "{}", and toString() of an AggregateError is just
742
+ // "AggregateError" - formatError() digs the real reason out of both
743
+ this.logConnectionError(err);
686
744
  this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
687
745
  this.reconnectTimeout = setTimeout(() => {
688
746
  this.reconnectTimeout = null;
@@ -698,8 +756,10 @@ class SqlAdapter extends adapter_core_1.Adapter {
698
756
  });
699
757
  }
700
758
  catch (ex) {
701
- this.log.error(ex.toString());
702
- this.log.error(ex.stack);
759
+ this.logConnectionError(ex);
760
+ if (ex.stack) {
761
+ this.log.debug(ex.stack);
762
+ }
703
763
  this.clientPool = null;
704
764
  this.activeConnections = 0;
705
765
  this.setConnected(false);
@@ -721,6 +781,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
721
781
  }, 30000);
722
782
  }
723
783
  else {
784
+ this.resetConnectionError();
724
785
  this.log.info(`Connected to ${this.config.dbtype}`);
725
786
  // read all DB IDs and all FROM ids
726
787
  this.getAllIds(() => this.getAllFroms(callback));
@@ -820,7 +881,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
820
881
  this.sendTo(msg.from, msg.command, { error: 'Unknown DB type' }, msg.callback);
821
882
  return;
822
883
  }
823
- client.on?.('error', (err) => this.log.warn(`SQL client error: ${err}`));
884
+ client.on?.('error', (err) => this.log.warn(`SQL client error: ${(0, errors_1.formatError)(err)}`));
824
885
  this.testConnectTimeout = setTimeout(() => {
825
886
  this.testConnectTimeout = null;
826
887
  this.sendTo(msg.from, msg.command, { error: 'connect timeout' }, msg.callback);
@@ -831,7 +892,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
831
892
  clearTimeout(this.testConnectTimeout);
832
893
  this.testConnectTimeout = null;
833
894
  }
834
- this.sendTo(msg.from, msg.command, { error: `${err.code} ${err.toString()}` }, msg.callback);
895
+ this.sendTo(msg.from, msg.command, { error: (0, errors_1.formatError)(err) }, msg.callback);
835
896
  return;
836
897
  }
837
898
  client.execute('SELECT 2 + 3 AS x', (err /* , rows, fields */) => {
@@ -842,7 +903,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
842
903
  if (this.testConnectTimeout) {
843
904
  clearTimeout(this.testConnectTimeout);
844
905
  this.testConnectTimeout = null;
845
- this.sendTo(msg.from, msg.command, { error: err?.toString() || null }, msg.callback);
906
+ this.sendTo(msg.from, msg.command, { error: err ? (0, errors_1.formatError)(err) : null }, msg.callback);
846
907
  return;
847
908
  }
848
909
  }
@@ -888,7 +949,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
888
949
  this.log.debug(msg.message);
889
950
  this.borrowClientFromPool((err, client) => {
890
951
  if (err || !client) {
891
- this.sendTo(msg.from, msg.command, { error: err?.toString() || 'No client' }, msg.callback);
952
+ this.sendTo(msg.from, msg.command, { error: err ? (0, errors_1.formatError)(err) : 'No client' }, msg.callback);
892
953
  this.returnClientToPool(client);
893
954
  callback?.();
894
955
  }
@@ -940,7 +1001,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
940
1001
  this.activeConnections = 0;
941
1002
  this.clientPool = null;
942
1003
  this.setConnected(false);
943
- this.log.error(err?.toString() || 'No database connection');
1004
+ this.logConnectionError(err || 'No database connection');
944
1005
  return cb?.(err || new Error('No database connection'));
945
1006
  }
946
1007
  this.log.debug(script);
@@ -1200,6 +1261,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
1200
1261
  else if (msg.command === 'storeState') {
1201
1262
  this.storeState(msg).catch(e => this.log.error(`Cannot store state: ${e}`));
1202
1263
  }
1264
+ else if (msg.command === 'getRawEntries') {
1265
+ this.getRawEntries(msg);
1266
+ }
1267
+ else if (msg.command === 'getDatapoints') {
1268
+ this.getDatapoints(msg);
1269
+ }
1203
1270
  else if (msg.command === 'getDpOverview') {
1204
1271
  this.getDpOverview(msg);
1205
1272
  }
@@ -1622,7 +1689,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1622
1689
  this.borrowClientFromPool((err, client) => {
1623
1690
  if (err || !client) {
1624
1691
  this.returnClientToPool(client);
1625
- this.log.error(err?.toString() || 'No client');
1692
+ this.log.error(err ? (0, errors_1.formatError)(err) : 'No client');
1626
1693
  cb?.();
1627
1694
  }
1628
1695
  else {
@@ -1689,7 +1756,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1689
1756
  this.borrowClientFromPool((err, client) => {
1690
1757
  if (err || !client) {
1691
1758
  this.returnClientToPool(client);
1692
- this.log.error(err?.toString() || 'No client');
1759
+ this.log.error(err ? (0, errors_1.formatError)(err) : 'No client');
1693
1760
  cb?.(); // BF asked (2021.12.14): may be return here err?
1694
1761
  return;
1695
1762
  }
@@ -1719,8 +1786,8 @@ class SqlAdapter extends adapter_core_1.Adapter {
1719
1786
  this.borrowClientFromPool((err, client) => {
1720
1787
  if (err || !client) {
1721
1788
  this.returnClientToPool(client);
1722
- this.log.error(err?.toString() || 'No client');
1723
- cb?.();
1789
+ this.log.error(err ? (0, errors_1.formatError)(err) : 'No client');
1790
+ cb?.(err || new Error('No client'));
1724
1791
  }
1725
1792
  else {
1726
1793
  client.execute(query, (err) => {
@@ -1728,7 +1795,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1728
1795
  if (err) {
1729
1796
  this.log.error(`Cannot query ${query}: ${err} (id: ${id})`);
1730
1797
  }
1731
- cb?.();
1798
+ cb?.(err);
1732
1799
  });
1733
1800
  }
1734
1801
  });
@@ -2081,8 +2148,8 @@ class SqlAdapter extends adapter_core_1.Adapter {
2081
2148
  if (this.tasks.length) {
2082
2149
  if (this.tasks[0].operation === 'query') {
2083
2150
  const taskQuery = this.tasks[0];
2084
- this._executeQuery(taskQuery.query, this.tasks[0].id, () => {
2085
- taskQuery.callback?.();
2151
+ this._executeQuery(taskQuery.query, this.tasks[0].id, err => {
2152
+ taskQuery.callback?.(err);
2086
2153
  this.tasks.shift();
2087
2154
  this.lockTasks = false;
2088
2155
  if (this.tasks.length) {
@@ -2778,32 +2845,42 @@ class SqlAdapter extends adapter_core_1.Adapter {
2778
2845
  }
2779
2846
  }
2780
2847
  }
2781
- if (!found) {
2782
- this.prepareTaskCheckTypeAndDbId(id, state, false, (err) => {
2783
- if (err) {
2784
- return cb?.(err);
2785
- }
2786
- const type = this.sqlDPs[id].type;
2787
- const query = this.sqlFuncs.update(this.config.dbname, this.sqlDPs[id].index, state, this.from[state.from], dbNames[type]);
2788
- if (!this.multiRequests) {
2789
- if (this.tasks.length > MAX_TASKS) {
2790
- const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2791
- this.log.error(error);
2792
- cb?.(new Error(error));
2793
- }
2794
- else {
2795
- this.tasks.push({ operation: 'query', query, id, callback: cb });
2796
- this.tasks.length === 1 && this.processTasks();
2797
- }
2848
+ if (found) {
2849
+ cb?.();
2850
+ return;
2851
+ }
2852
+ if (!this.sqlDPs[id]) {
2853
+ // Logging is not (or no longer) enabled for this ID, so neither the type nor the index are known
2854
+ // in RAM. Read both from the `datapoints` table, so stored values can still be changed.
2855
+ this.#readIdIndexAndType(id, (err, index, type) => {
2856
+ if (err || index === undefined || type === undefined) {
2857
+ cb?.(err || new Error(`Unknown ID: ${id}`));
2858
+ return;
2798
2859
  }
2799
- else {
2800
- this._executeQuery(query, id, cb);
2860
+ // the source is only known if it was used before, otherwise `_from` stays unchanged
2861
+ if (state.from && this.from[state.from] === undefined) {
2862
+ return this.getFrom(state.from, err => {
2863
+ if (err) {
2864
+ this.log.warn(`Cannot get "from" for "${state.from}": ${err}`);
2865
+ }
2866
+ this.#updateInDb(id, dbNames[type], index, state, cb);
2867
+ });
2801
2868
  }
2869
+ this.#updateInDb(id, dbNames[type], index, state, cb);
2802
2870
  });
2871
+ return;
2803
2872
  }
2804
- else {
2805
- cb?.();
2806
- }
2873
+ this.prepareTaskCheckTypeAndDbId(id, state, false, (err) => {
2874
+ if (err) {
2875
+ return cb?.(err);
2876
+ }
2877
+ this.#updateInDb(id, dbNames[this.sqlDPs[id].type], this.sqlDPs[id].index, state, cb);
2878
+ });
2879
+ }
2880
+ /** Build and execute the UPDATE query for one entry of one datapoint */
2881
+ #updateInDb(id, table, index, state, cb) {
2882
+ const query = this.sqlFuncs.update(this.config.dbname, index, state, this.from[state.from], table);
2883
+ this.#executeQueries(id, [query], cb);
2807
2884
  }
2808
2885
  #delete(id, state, cb) {
2809
2886
  // first try to find the value in not yet saved data
@@ -2840,41 +2917,114 @@ class SqlAdapter extends adapter_core_1.Adapter {
2840
2917
  }
2841
2918
  }
2842
2919
  }
2843
- if (!found) {
2844
- this.prepareTaskCheckTypeAndDbId(id, state, false, err => {
2845
- if (err) {
2846
- return cb?.(err);
2847
- }
2848
- const type = this.sqlDPs[id].type;
2849
- let query;
2850
- if (state.start && state.end) {
2851
- query = this.sqlFuncs.deleteFromTable(this.config.dbname, dbNames[type], this.sqlDPs[id].index, state.start, state.end);
2920
+ if (found) {
2921
+ cb?.();
2922
+ return;
2923
+ }
2924
+ if (!this.sqlDPs[id]) {
2925
+ // Logging is not (or no longer) enabled for this ID, so neither the type nor the index are known
2926
+ // in RAM. Read both from the `datapoints` table, so the already stored values can still be deleted.
2927
+ this.#readIdIndexAndType(id, (err, index, type) => {
2928
+ if (err || index === undefined || type === undefined) {
2929
+ cb?.(err || new Error(`Unknown ID: ${id}`));
2930
+ return;
2852
2931
  }
2853
- else if (state.ts) {
2854
- query = this.sqlFuncs.deleteFromTable(this.config.dbname, dbNames[type], this.sqlDPs[id].index, state.ts);
2932
+ this.#deleteFromDb(id, dbNames[type], index, state, cb);
2933
+ });
2934
+ return;
2935
+ }
2936
+ this.prepareTaskCheckTypeAndDbId(id, state, false, err => {
2937
+ if (err) {
2938
+ return cb?.(err);
2939
+ }
2940
+ this.#deleteFromDb(id, dbNames[this.sqlDPs[id].type], this.sqlDPs[id].index, state, cb);
2941
+ });
2942
+ }
2943
+ /**
2944
+ * Read the index and the stored data type of one datapoint from the `datapoints` table.
2945
+ *
2946
+ * In contrast to `getId`, this never creates or modifies anything and it works for IDs that are not
2947
+ * (or no longer) enabled for logging, i.e., that are not in `sqlDPs`.
2948
+ */
2949
+ #readIdIndexAndType(id, cb) {
2950
+ if (!this.clientPool) {
2951
+ this.log.warn('No Connection to database');
2952
+ setImmediate(() => cb(new Error('No Connection to database')));
2953
+ return;
2954
+ }
2955
+ const query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
2956
+ this.log.debug(query);
2957
+ this.borrowClientFromPool((err, client) => {
2958
+ if (err || !client) {
2959
+ this.returnClientToPool(client);
2960
+ cb(err || new Error('No client'));
2961
+ return;
2962
+ }
2963
+ client.execute(query, (err, rows) => {
2964
+ this.returnClientToPool(client);
2965
+ if (err) {
2966
+ this.log.error(`Cannot select ${query}: ${err}`);
2967
+ cb(err);
2855
2968
  }
2856
- else {
2857
- // delete all entries for ID
2858
- query = this.sqlFuncs.deleteFromTable(this.config.dbname, dbNames[type], this.sqlDPs[id].index);
2969
+ else if (!rows?.length) {
2970
+ cb(new Error(`Unknown ID: ${id}`));
2859
2971
  }
2860
- if (!this.multiRequests) {
2861
- if (this.tasks.length > MAX_TASKS) {
2862
- const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
2863
- this.log.error(error);
2864
- cb?.(new Error(error));
2865
- }
2866
- else {
2867
- this.tasks.push({ operation: 'query', query, id, callback: cb });
2868
- this.tasks.length === 1 && this.processTasks();
2869
- }
2972
+ else if (typeof rows[0].type !== 'number' || !dbNames[rows[0].type]) {
2973
+ cb(new Error(`No valid data type stored for ${id}: ${rows[0].type}`));
2870
2974
  }
2871
2975
  else {
2872
- this._executeQuery(query, id, cb);
2976
+ cb(null, rows[0].id, rows[0].type);
2873
2977
  }
2874
2978
  });
2979
+ });
2980
+ }
2981
+ /** Build and execute the DELETE query for one datapoint */
2982
+ #deleteFromDb(id, table, index, state, cb) {
2983
+ const queries = [this.#buildDeleteQuery(table, index, state)];
2984
+ // the counter values of a numeric datapoint are stored in an own table (like in `checkRetention`)
2985
+ if (table === 'ts_number') {
2986
+ queries.push(this.#buildDeleteQuery('ts_counter', index, state));
2875
2987
  }
2876
- else {
2988
+ this.#executeQueries(id, queries, cb);
2989
+ }
2990
+ /** Build the DELETE query for one table of one datapoint */
2991
+ #buildDeleteQuery(table, index, state) {
2992
+ if (state.start && state.end) {
2993
+ return this.sqlFuncs.deleteFromTable(this.config.dbname, table, index, state.start, state.end);
2994
+ }
2995
+ if (state.ts) {
2996
+ return this.sqlFuncs.deleteFromTable(this.config.dbname, table, index, state.ts);
2997
+ }
2998
+ // delete all entries for ID
2999
+ return this.sqlFuncs.deleteFromTable(this.config.dbname, table, index);
3000
+ }
3001
+ /** Execute the given queries one after another and stop at the first error */
3002
+ #executeQueries(id, queries, cb) {
3003
+ const query = queries.shift();
3004
+ if (!query) {
2877
3005
  cb?.();
3006
+ return;
3007
+ }
3008
+ const next = (err) => {
3009
+ if (err || !queries.length) {
3010
+ cb?.(err);
3011
+ return;
3012
+ }
3013
+ this.#executeQueries(id, queries, cb);
3014
+ };
3015
+ if (!this.multiRequests) {
3016
+ if (this.tasks.length > MAX_TASKS) {
3017
+ const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
3018
+ this.log.error(error);
3019
+ cb?.(new Error(error));
3020
+ }
3021
+ else {
3022
+ this.tasks.push({ operation: 'query', query, id, callback: next });
3023
+ this.tasks.length === 1 && this.processTasks();
3024
+ }
3025
+ }
3026
+ else {
3027
+ this._executeQuery(query, id, next);
2878
3028
  }
2879
3029
  }
2880
3030
  updateState(msg) {
@@ -2912,10 +3062,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
2912
3062
  else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
2913
3063
  this.log.debug('updateState 1 item');
2914
3064
  id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
2915
- return this.update(id, msg.message.state, () => this.sendTo(msg.from, msg.command, {
2916
- success: true,
2917
- sqlConnected: !!this.clientPool,
2918
- }, msg.callback));
3065
+ return this.update(id, msg.message.state, err => this.sendTo(msg.from, msg.command, err
3066
+ ? { error: err.message, sqlConnected: !!this.clientPool }
3067
+ : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
2919
3068
  }
2920
3069
  else {
2921
3070
  this.log.error('updateState called with invalid data');
@@ -3021,18 +3170,16 @@ class SqlAdapter extends adapter_core_1.Adapter {
3021
3170
  else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
3022
3171
  this.log.debug('deleteHistoryEntry 1 item');
3023
3172
  id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3024
- return this.#delete(id, { ts: msg.message.state.ts }, () => this.sendTo(msg.from, msg.command, {
3025
- success: true,
3026
- sqlConnected: !!this.clientPool,
3027
- }, msg.callback));
3173
+ return this.#delete(id, { ts: msg.message.state.ts }, err => this.sendTo(msg.from, msg.command, err
3174
+ ? { error: err.message, sqlConnected: !!this.clientPool }
3175
+ : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3028
3176
  }
3029
3177
  else if (msg.message.id && msg.message.ts && typeof msg.message.ts === 'number') {
3030
3178
  this.log.debug('deleteHistoryEntry 1 item');
3031
3179
  id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3032
- return this.#delete(id, { ts: msg.message.ts }, () => this.sendTo(msg.from, msg.command, {
3033
- success: true,
3034
- sqlConnected: !!this.clientPool,
3035
- }, msg.callback));
3180
+ return this.#delete(id, { ts: msg.message.ts }, err => this.sendTo(msg.from, msg.command, err
3181
+ ? { error: err.message, sqlConnected: !!this.clientPool }
3182
+ : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3036
3183
  }
3037
3184
  else {
3038
3185
  this.log.error('deleteHistoryEntry called with invalid data');
@@ -3061,10 +3208,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
3061
3208
  else if (msg.message.id) {
3062
3209
  this.log.debug('deleteStateAll 1 item');
3063
3210
  id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
3064
- return this.#delete(id, {}, () => this.sendTo(msg.from, msg.command, {
3065
- success: true,
3066
- sqlConnected: !!this.clientPool,
3067
- }, msg.callback));
3211
+ return this.#delete(id, {}, err => this.sendTo(msg.from, msg.command, err
3212
+ ? { error: err.message, sqlConnected: !!this.clientPool }
3213
+ : { success: true, sqlConnected: !!this.clientPool }, msg.callback));
3068
3214
  }
3069
3215
  else {
3070
3216
  this.log.error('deleteStateAll called with invalid data');
@@ -3087,20 +3233,36 @@ class SqlAdapter extends adapter_core_1.Adapter {
3087
3233
  this.sqlDPs[id].realId = id;
3088
3234
  }
3089
3235
  return new Promise((resolve, reject) => {
3090
- if (applyRules) {
3091
- this.pushHistory(id, state);
3092
- resolve(true);
3093
- }
3094
- else {
3095
- this.pushHelper(id, state, err => {
3096
- if (err) {
3097
- reject(new Error(`Error writing state for ${id}: ${err.message}, Data: ${JSON.stringify(state)}`));
3098
- }
3099
- else {
3100
- resolve(true);
3101
- }
3236
+ const push = () => {
3237
+ if (applyRules) {
3238
+ this.pushHistory(id, state);
3239
+ resolve(true);
3240
+ }
3241
+ else {
3242
+ this.pushHelper(id, state, err => {
3243
+ if (err) {
3244
+ reject(new Error(`Error writing state for ${id}: ${err.message}, Data: ${JSON.stringify(state)}`));
3245
+ }
3246
+ else {
3247
+ resolve(true);
3248
+ }
3249
+ });
3250
+ }
3251
+ };
3252
+ // Without a configuration, the type would be guessed from the value and could then even overwrite
3253
+ // the type in the `datapoints` table. Use the stored type of an already known datapoint instead.
3254
+ if (!this.sqlDPs[id].config && this.sqlDPs[id].type === undefined) {
3255
+ this.#readIdIndexAndType(id, (err, index, type) => {
3256
+ if (!err && index !== undefined && type !== undefined) {
3257
+ this.sqlDPs[id].index = index;
3258
+ this.sqlDPs[id].type = type;
3259
+ this.sqlDPs[id].dbType = type;
3260
+ }
3261
+ push();
3102
3262
  });
3263
+ return;
3103
3264
  }
3265
+ push();
3104
3266
  });
3105
3267
  }
3106
3268
  async storeState(msg) {
@@ -3170,6 +3332,110 @@ class SqlAdapter extends adapter_core_1.Adapter {
3170
3332
  sqlConnected: !!this.clientPool,
3171
3333
  }, msg.callback);
3172
3334
  }
3335
+ /**
3336
+ * Read the stored values of one datapoint page by page.
3337
+ *
3338
+ * In contrast to `getHistory`, the rows are returned exactly as they are in the database: no aggregation,
3339
+ * no interpolation, no border values and no rounding. Together with the total number of matching entries,
3340
+ * so that a table can page through them. Works for datapoints that are not (or no longer) enabled for
3341
+ * logging too.
3342
+ */
3343
+ getRawEntries(msg) {
3344
+ if (!msg.message?.id) {
3345
+ this.log.error('getRawEntries called with invalid data');
3346
+ return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
3347
+ }
3348
+ const toTs = (value) => {
3349
+ if (value === undefined || value === null || value === '') {
3350
+ return undefined;
3351
+ }
3352
+ const ts = typeof value === 'number' ? value : new Date(value).getTime();
3353
+ return isFinite(ts) ? ts : undefined;
3354
+ };
3355
+ const id = this.aliasMap[msg.message.id] || msg.message.id;
3356
+ const options = {
3357
+ start: toTs(msg.message.start),
3358
+ end: toTs(msg.message.end),
3359
+ limit: Math.min(Math.max(parseInt(msg.message.limit, 10) || 100, 1), MAX_RAW_ENTRIES),
3360
+ offset: Math.max(parseInt(msg.message.offset, 10) || 0, 0),
3361
+ sort: msg.message.sort === 'asc' ? 'asc' : 'desc',
3362
+ };
3363
+ this.#readIdIndexAndType(id, (err, index, type) => {
3364
+ if (err || index === undefined || type === undefined) {
3365
+ return this.sendTo(msg.from, msg.command, { error: (err || new Error(`Unknown ID: ${id}`)).message }, msg.callback);
3366
+ }
3367
+ const table = dbNames[type];
3368
+ this.borrowClientFromPool((err, client) => {
3369
+ if (err || !client) {
3370
+ this.returnClientToPool(client);
3371
+ return this.sendTo(msg.from, msg.command, { error: (err || new Error('No client')).message }, msg.callback);
3372
+ }
3373
+ const countQuery = this.sqlFuncs.getRawEntriesCount(this.config.dbname, table, index, options);
3374
+ this.log.debug(countQuery);
3375
+ client.execute(countQuery, (err, rows) => {
3376
+ if (err) {
3377
+ this.returnClientToPool(client);
3378
+ this.log.error(`Cannot select ${countQuery}: ${err}`);
3379
+ return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3380
+ }
3381
+ // PostgreSQL returns the count of a bigint column as string
3382
+ const total = rows?.[0] ? parseInt(rows[0].total, 10) || 0 : 0;
3383
+ const query = this.sqlFuncs.getRawEntries(this.config.dbname, table, index, options);
3384
+ this.log.debug(query);
3385
+ client.execute(query, (err, rows) => {
3386
+ this.returnClientToPool(client);
3387
+ if (err) {
3388
+ this.log.error(`Cannot select ${query}: ${err}`);
3389
+ return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3390
+ }
3391
+ this.sendTo(msg.from, msg.command, {
3392
+ id: msg.message.id,
3393
+ index,
3394
+ type: storageTypes[type],
3395
+ table,
3396
+ total,
3397
+ limit: options.limit,
3398
+ offset: options.offset,
3399
+ sort: options.sort,
3400
+ result: rows || [],
3401
+ }, msg.callback);
3402
+ });
3403
+ });
3404
+ });
3405
+ });
3406
+ }
3407
+ /**
3408
+ * Return all datapoints that have an entry in the `datapoints` table - no matter whether their logging is
3409
+ * still enabled or not.
3410
+ *
3411
+ * In contrast to `getDpOverview`, this is only one SELECT and answers immediately: `getDpOverview`
3412
+ * additionally determines the first timestamp of every datapoint and pauses 5 seconds between the types.
3413
+ */
3414
+ getDatapoints(msg) {
3415
+ const query = this.sqlFuncs.getIdSelect(this.config.dbname);
3416
+ this.log.debug(query);
3417
+ this.borrowClientFromPool((err, client) => {
3418
+ if (err || !client) {
3419
+ this.returnClientToPool(client);
3420
+ return this.sendTo(msg.from, msg.command, { error: (err || new Error('No client')).message }, msg.callback);
3421
+ }
3422
+ client.execute(query, (err, rows) => {
3423
+ this.returnClientToPool(client);
3424
+ if (err) {
3425
+ this.log.error(`Cannot select ${query}: ${err}`);
3426
+ return this.sendTo(msg.from, msg.command, { error: err.message }, msg.callback);
3427
+ }
3428
+ const result = (rows || [])
3429
+ .map(row => ({
3430
+ id: row.name,
3431
+ index: row.id,
3432
+ type: typeof row.type === 'number' ? storageTypes[row.type] : null,
3433
+ }))
3434
+ .sort((a, b) => (a.id > b.id ? 1 : a.id < b.id ? -1 : 0));
3435
+ this.sendTo(msg.from, msg.command, { success: true, result }, msg.callback);
3436
+ });
3437
+ });
3438
+ }
3173
3439
  getDpOverview(msg) {
3174
3440
  const result = [];
3175
3441
  const query = this.sqlFuncs.getIdSelect(this.config.dbname);
@@ -3528,7 +3794,18 @@ class SqlAdapter extends adapter_core_1.Adapter {
3528
3794
  await this.createUserInDocker();
3529
3795
  }
3530
3796
  if (config.dbtype === 'sqlite' || this.config.host) {
3531
- this.connect(() => {
3797
+ this.connect(async () => {
3798
+ // `enableHistory` only writes the object and leaves the activation to `objectChange`, so
3799
+ // subscribing after the view was read left a gap: a message that arrived in between was
3800
+ // answered with `success: true` and then silently lost, because nothing delivered its
3801
+ // object change. Registering the subscription *before* the view is read closes the gap -
3802
+ // every write now either lands in the snapshot below or arrives as an object change.
3803
+ try {
3804
+ await this.subscribeForeignObjectsAsync('*');
3805
+ }
3806
+ catch (e) {
3807
+ this.log.error(`Cannot subscribe to objects: ${e}`);
3808
+ }
3532
3809
  // read all custom settings
3533
3810
  this.getObjectView('system', 'custom', {}, (err, doc) => {
3534
3811
  let count = 0;
@@ -3604,7 +3881,6 @@ class SqlAdapter extends adapter_core_1.Adapter {
3604
3881
  this.subscribeAll = true;
3605
3882
  this.subscribeForeignStates('*');
3606
3883
  }
3607
- this.subscribeForeignObjects('*');
3608
3884
  this.log.debug('Initialization done');
3609
3885
  this.setConnected(true);
3610
3886
  this.processStartValues();