iobroker.sql 4.7.0 → 4.8.1

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.
package/build/main.js CHANGED
@@ -50,6 +50,7 @@ const values_1 = require("./lib/values");
50
50
  const password_1 = require("./lib/password");
51
51
  const names_1 = require("./lib/names");
52
52
  const statement_1 = require("./lib/statement");
53
+ const sql_string_1 = require("./lib/sql-string");
53
54
  const statistics_1 = require("./lib/statistics");
54
55
  const postgresql_client_1 = require("./lib/postgresql-client");
55
56
  const sqlite3_client_1 = require("./lib/sqlite3-client");
@@ -200,6 +201,22 @@ const STAT_TABLES = ['ts_number', 'ts_string', 'ts_bool', 'ts_counter'];
200
201
  const MAX_TASKS = 100;
201
202
  /** Milliseconds a pooled connection may be idle before it is replaced (`max_age` of the pool) */
202
203
  const POOL_MAX_IDLE_AGE = 60_000;
204
+ /**
205
+ * Connections the inserts use at most at the same time (or `maxConnections`, if lower). The flush of
206
+ * all buffers (every 10 minutes and on stop) starts one insert per datapoint; with the default of 100
207
+ * connections it opened up to 100 connections at once, and the pool closed all but two right after.
208
+ * Hosted databases often allow fewer connections per user ("Too many connections"). The other inserts
209
+ * wait and get a returned connection directly (#587).
210
+ */
211
+ const INSERT_CONNECTIONS = 10;
212
+ /**
213
+ * Milliseconds after a failed connect in which no new connect is tried: the writes in between keep
214
+ * their rows for the next write at once, instead of every value starting a connect and waiting for
215
+ * its timeout while the database is down (#587).
216
+ */
217
+ const UNREACHABLE_RETRY_DELAY = 5_000;
218
+ /** Code of the error a borrow fails with while the database is known to be unreachable */
219
+ const DB_UNREACHABLE = 'IOB_DB_UNREACHABLE';
203
220
  /** Milliseconds between two warnings about values kept while the database is not reachable */
204
221
  const KEPT_LOG_INTERVAL = 60_000;
205
222
  /**
@@ -209,6 +226,8 @@ const KEPT_LOG_INTERVAL = 60_000;
209
226
  const MAX_RAW_ENTRIES = 5000;
210
227
  /** How often an unchanged connection error is repeated as error in the log */
211
228
  const REPEATED_ERROR_INTERVAL = 3_600_000;
229
+ /** Rows per batch when an aggregated PostgreSQL read is streamed instead of buffered */
230
+ const STREAM_BATCH_SIZE = 2000;
212
231
  /** How long `aggregate` and `lastChange` wait for the answer of the own `getHistory` */
213
232
  const STANDARD_TIMEOUT = 120_000;
214
233
  function sortByTs(a, b) {
@@ -227,6 +246,8 @@ class SqlAdapter extends adapter_core_1.Adapter {
227
246
  finished = false;
228
247
  sqlConnected = null;
229
248
  multiRequests = true;
249
+ /** The driver cannot stream (pg-native, or pg-cursor not installed): read buffered without trying again */
250
+ streamingUnavailable = false;
230
251
  subscribeAll = false;
231
252
  clientPool = null;
232
253
  reconnectTimeout = null;
@@ -235,7 +256,10 @@ class SqlAdapter extends adapter_core_1.Adapter {
235
256
  bufferChecker = null;
236
257
  activeConnections = 0;
237
258
  poolBorrowGuard = []; // required until https://github.com/intellinote/sql-client/issues/7 is fixed
238
- logConnectionUsage = true;
259
+ /** Borrow/return of every connection on debug level; the texts are only built when debug is on. */
260
+ get logConnectionUsage() {
261
+ return this.#isDebug();
262
+ }
239
263
  postgresDbCreated = false;
240
264
  lockTasks = false;
241
265
  sqlFuncs = null;
@@ -370,6 +394,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
370
394
  },
371
395
  });
372
396
  }
397
+ /**
398
+ * Whether debug lines are written at all. A template string passed to `log.debug()` is built before the
399
+ * call, also when the level is `info`; on the paths that run for every value, check this first.
400
+ */
401
+ #isDebug() {
402
+ return this.log.level === 'debug' || this.log.level === 'silly';
403
+ }
373
404
  /**
374
405
  * Log a statement on debug level.
375
406
  *
@@ -379,18 +410,42 @@ class SqlAdapter extends adapter_core_1.Adapter {
379
410
  * @param statement plain SQL or SQL with values
380
411
  */
381
412
  #debugStatement(statement) {
382
- if (this.log.level === 'debug' || this.log.level === 'silly') {
413
+ if (this.#isDebug()) {
383
414
  this.log.debug((0, statement_1.statementToString)(statement));
384
415
  }
385
416
  }
386
- borrowClientFromPool(callback) {
417
+ /**
418
+ * Borrow a connection, at most `limit` at the same time; beyond that the callback waits for a
419
+ * returned connection.
420
+ *
421
+ * After a failed connect the database counts as unreachable: for {@link UNREACHABLE_RETRY_DELAY}
422
+ * every borrow fails at once with the error code {@link DB_UNREACHABLE}, then one borrow at a time
423
+ * checks whether the server is back.
424
+ *
425
+ * @param callback gets the connection, or the error
426
+ * @param limit connections at the same time, `maxConnections` by default
427
+ */
428
+ borrowClientFromPool(callback, limit = this.config.maxConnections) {
387
429
  if (!this.clientPool) {
388
430
  this.setConnected(false);
389
431
  return callback(new Error('No database connection'));
390
432
  }
391
- if (this.activeConnections >= this.config.maxConnections) {
433
+ let probe = false;
434
+ if (this.#unreachable) {
435
+ if (this.#probing || Date.now() - this.#unreachable.since < UNREACHABLE_RETRY_DELAY) {
436
+ return callback(this.#unreachableError());
437
+ }
438
+ // this borrow checks whether the server is back, the others fail at once until it is done
439
+ this.#probing = probe = true;
440
+ }
441
+ if (this.activeConnections >= limit) {
392
442
  if (this.logConnectionUsage) {
393
- this.log.debug(`Borrow connection not possible: ${this.activeConnections} >= Max - Store for Later`);
443
+ this.log.debug(`Borrow connection not possible: ${this.activeConnections} >= ${limit} - Store for Later`);
444
+ }
445
+ if (probe) {
446
+ // the connections in use may be connects that are still waiting for their timeout
447
+ this.#probing = false;
448
+ return callback(this.#unreachableError());
394
449
  }
395
450
  this.poolBorrowGuard.push(callback);
396
451
  return;
@@ -400,6 +455,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
400
455
  this.log.debug(`Borrow connection from pool: ${this.activeConnections} now`);
401
456
  }
402
457
  this.clientPool.borrow((err, client) => {
458
+ if (probe) {
459
+ this.#probing = false;
460
+ }
403
461
  if (!err && client) {
404
462
  // Log connection-level driver errors (ECONNRESET, PROTOCOL_CONNECTION_LOST). The
405
463
  // crash safety itself does not depend on this listener: SQLClient handles the
@@ -418,6 +476,10 @@ class SqlAdapter extends adapter_core_1.Adapter {
418
476
  }
419
477
  });
420
478
  }
479
+ if (this.#unreachable) {
480
+ this.#unreachable = null;
481
+ this.resetConnectionError();
482
+ }
421
483
  // A real, working connection was handed out - this, not the mere existence of a pool
422
484
  // object, is what info.connection reports (#374).
423
485
  this.consecutiveBorrowFailures = 0;
@@ -430,10 +492,41 @@ class SqlAdapter extends adapter_core_1.Adapter {
430
492
  if (++this.consecutiveBorrowFailures >= 5) {
431
493
  this.setConnected(false);
432
494
  }
495
+ const error = err || new Error('No client');
496
+ this.#unreachable = { since: Date.now(), error };
497
+ // The callbacks waiting for a connection were only served by a returned working
498
+ // connection, so after a failed connect they waited until the server was back and the
499
+ // next write returned one: their rows stayed in memory outside the limits of
500
+ // #keepForRetry, and the stop waited for them until the stopTimeout. They would fail
501
+ // the same way now.
502
+ this.#failWaiters();
433
503
  }
434
504
  callback(err, client);
435
505
  });
436
506
  }
507
+ /** Set after a failed connect, cleared by the next connection that works */
508
+ #unreachable = null;
509
+ /** Whether a borrow is checking if the unreachable server is back */
510
+ #probing = false;
511
+ /** The error of a borrow while the database is known to be unreachable */
512
+ #unreachableError() {
513
+ const cause = this.#unreachable?.error;
514
+ return Object.assign(new Error(`Database not reachable${cause ? `: ${(0, errors_1.formatError)(cause)}` : ''}`, { cause }), {
515
+ code: DB_UNREACHABLE,
516
+ });
517
+ }
518
+ /** Fail every callback that waits for a connection; there will be none to hand them */
519
+ #failWaiters() {
520
+ if (!this.poolBorrowGuard.length) {
521
+ return;
522
+ }
523
+ const waiters = this.poolBorrowGuard;
524
+ this.poolBorrowGuard = [];
525
+ const error = this.clientPool ? this.#unreachableError() : new Error('No database connection');
526
+ for (const waiter of waiters) {
527
+ waiter(error);
528
+ }
529
+ }
437
530
  returnClientToPool(client) {
438
531
  if (client) {
439
532
  this.activeConnections--;
@@ -687,7 +780,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
687
780
  let mySQLOptions;
688
781
  let postgreSQLOptions;
689
782
  const poolOptions = {
690
- max_idle: this.config.dbtype === 'sqlite' ? 1 : 2,
783
+ // the connections of a flush are reused by the next inserts instead of being closed and opened
784
+ // again; idle ones are still closed after `max_age`
785
+ max_idle: this.config.dbtype === 'sqlite' ? 1 : Math.min(this.config.maxConnections, INSERT_CONNECTIONS) || 2,
691
786
  };
692
787
  if (this.config.dbtype !== 'sqlite') {
693
788
  // A connection that was idle for a while is opened anew instead of being reused: servers
@@ -771,7 +866,9 @@ class SqlAdapter extends adapter_core_1.Adapter {
771
866
  }, 30000);
772
867
  return;
773
868
  }
774
- _client.execute(`CREATE DATABASE ${this.config.dbname};`, (err) => {
869
+ // quoted: unquoted, PostgreSQL folds the name to lower case and refuses `-`
870
+ const create = `CREATE DATABASE ${(0, sql_string_1.quotePgIdentifier)(this.config.dbname)};`;
871
+ _client.execute(create, (err) => {
775
872
  _client.disconnect();
776
873
  const typedError = err;
777
874
  if (typedError && typedError.code !== '42P04') {
@@ -824,6 +921,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
824
921
  this.activeConnections = 0;
825
922
  if (err) {
826
923
  this.clientPool = null;
924
+ this.#failWaiters();
827
925
  this.setConnected(false);
828
926
  // JSON.stringify(Error) is "{}", and toString() of an AggregateError is just
829
927
  // "AggregateError" - formatError() digs the real reason out of both
@@ -848,6 +946,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
848
946
  this.log.debug(ex.stack);
849
947
  }
850
948
  this.clientPool = null;
949
+ this.#failWaiters();
851
950
  this.activeConnections = 0;
852
951
  this.setConnected(false);
853
952
  this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
@@ -871,7 +970,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
871
970
  this.resetConnectionError();
872
971
  this.log.info(`Connected to ${this.config.dbtype}`);
873
972
  // read all DB IDs and all FROM ids
874
- this.getAllIds(() => this.getAllFroms(callback));
973
+ this.#readNameColumnTypes(() => this.getAllIds(() => this.getAllFroms(callback)));
875
974
  }
876
975
  });
877
976
  }
@@ -1084,6 +1183,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1084
1183
  this.clientPool?.close();
1085
1184
  this.activeConnections = 0;
1086
1185
  this.clientPool = null;
1186
+ this.#failWaiters();
1087
1187
  this.setConnected(false);
1088
1188
  this.logConnectionError(err || 'No database connection');
1089
1189
  return cb?.(err || new Error('No database connection'));
@@ -1182,6 +1282,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1182
1282
  this.clientPool.close();
1183
1283
  this.activeConnections = 0;
1184
1284
  this.clientPool = null;
1285
+ this.#failWaiters();
1185
1286
  this.setConnected(false);
1186
1287
  }
1187
1288
  if (typeof this.finished === 'object') {
@@ -1349,6 +1450,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1349
1450
  this.clientPool.close();
1350
1451
  this.activeConnections = 0;
1351
1452
  this.clientPool = null;
1453
+ this.#failWaiters();
1352
1454
  this.setConnected(false);
1353
1455
  }
1354
1456
  // so that a second finish() (stopInstance message, then unload) does not wait forever
@@ -1818,6 +1920,39 @@ class SqlAdapter extends adapter_core_1.Adapter {
1818
1920
  // the converted value must not replace it.
1819
1921
  this.pushValueIntoDB(_id, { ...state, val }, false, false, cb);
1820
1922
  }
1923
+ /**
1924
+ * MS SQL: find out whether the `name` columns are still `varchar` (tables created before #588), so that the names
1925
+ * are compared with the right kind of literal (see `varcharNames` in lib/mssql.ts). Other databases: nothing to do.
1926
+ * An error is logged and the start goes on with `N'...'` literals, as for new tables.
1927
+ *
1928
+ * @param cb called when done
1929
+ */
1930
+ #readNameColumnTypes(cb) {
1931
+ if (this.config.dbtype !== 'mssql') {
1932
+ return cb();
1933
+ }
1934
+ const query = MSSQL.getNameColumnTypes(this.config.dbname);
1935
+ this.borrowClientFromPool((err, client) => {
1936
+ if (err || !client) {
1937
+ this.returnClientToPool(client);
1938
+ this.log.warn(`Cannot read the column types of the tables: ${err?.message || 'no client'}`);
1939
+ return cb();
1940
+ }
1941
+ client.execute(query, (err, rows) => {
1942
+ this.returnClientToPool(client);
1943
+ if (err) {
1944
+ this.log.warn(`Cannot read the column types of the tables: ${err.message}`);
1945
+ }
1946
+ else {
1947
+ MSSQL.setNameColumnTypes(this.config.dbname, rows || []);
1948
+ if (rows?.some(row => !String(row.type).toLowerCase().startsWith('n'))) {
1949
+ this.log.debug('The tables were created by an older version (varchar names). Names with characters outside the code page of the database are stored as "?". The README explains how to convert the tables.');
1950
+ }
1951
+ }
1952
+ cb();
1953
+ });
1954
+ });
1955
+ }
1821
1956
  getAllIds(cb) {
1822
1957
  const query = this.sqlFuncs.getIdSelect(this.config.dbname);
1823
1958
  this.#debugStatement(query);
@@ -1950,11 +2085,16 @@ class SqlAdapter extends adapter_core_1.Adapter {
1950
2085
  */
1951
2086
  _insertValuesIntoDB(list, index, id, cb) {
1952
2087
  const groups = (0, write_buffer_1.splitBatch)(list);
2088
+ const limit = Math.min(this.config.maxConnections, INSERT_CONNECTIONS);
1953
2089
  this.borrowClientFromPool((err, client) => {
1954
2090
  if (err || !client) {
1955
2091
  this.returnClientToPool(client);
1956
2092
  const error = err || new Error('No client');
1957
- this.log.error((0, errors_1.formatError)(error));
2093
+ // While the database is down every write fails: the failed connect is logged (once,
2094
+ // repeated hourly), the rows kept for the next write are reported by #keepForRetry.
2095
+ if (error.code !== DB_UNREACHABLE) {
2096
+ this.logConnectionError(error);
2097
+ }
1958
2098
  cb?.(error, list);
1959
2099
  return;
1960
2100
  }
@@ -1985,7 +2125,7 @@ class SqlAdapter extends adapter_core_1.Adapter {
1985
2125
  run(0);
1986
2126
  };
1987
2127
  next(0);
1988
- });
2128
+ }, limit);
1989
2129
  }
1990
2130
  _executeQuery(query, id, cb) {
1991
2131
  this.#debugStatement(query);
@@ -2128,10 +2268,14 @@ class SqlAdapter extends adapter_core_1.Adapter {
2128
2268
  }
2129
2269
  task.cb?.();
2130
2270
  task.cb = null;
2131
- setTimeout(() => {
2271
+ // The queue has one entry per value, not per datapoint: every value that arrives before the type
2272
+ // of its datapoint is known waits here. A pause of 50 ms per entry limited the start with many
2273
+ // datapoints to 20 values per second (2000 datapoints: more than a minute and a half, with the
2274
+ // values piling up in memory). The lookups still run one after the other.
2275
+ setImmediate(() => {
2132
2276
  this.tasksReadType.shift();
2133
2277
  this.processReadTypes();
2134
- }, 50);
2278
+ });
2135
2279
  }
2136
2280
  prepareTaskReadDbId(id, state, isCounter, cb) {
2137
2281
  if (!this.sqlDPs[id]) {
@@ -2263,12 +2407,17 @@ class SqlAdapter extends adapter_core_1.Adapter {
2263
2407
  if (!this.sqlDPs[id] || !state) {
2264
2408
  return cb?.();
2265
2409
  }
2266
- this.log.debug(`pushValueIntoDB called for ${id} (type: ${this.sqlDPs[id].type}, ID: ${this.sqlDPs[id].index}) and state: ${JSON.stringify(state)}`);
2410
+ // runs for every value: no JSON.stringify unless the line is written
2411
+ if (this.#isDebug()) {
2412
+ this.log.debug(`pushValueIntoDB called for ${id} (type: ${this.sqlDPs[id].type}, ID: ${this.sqlDPs[id].index}) and state: ${JSON.stringify(state)}`);
2413
+ }
2267
2414
  this.prepareTaskCheckTypeAndDbId(id, state, isCounter, (err) => {
2268
2415
  if (!this.sqlDPs[id]) {
2269
2416
  return cb?.();
2270
2417
  }
2271
- this.log.debug(`pushValueIntoDB-prepareTaskCheckTypeAndDbId RESULT for ${id} (type: ${this.sqlDPs[id].type}, ID: ${this.sqlDPs[id].index}) and state: ${JSON.stringify(state)}: ${err}`);
2418
+ if (this.#isDebug()) {
2419
+ this.log.debug(`pushValueIntoDB-prepareTaskCheckTypeAndDbId RESULT for ${id} (type: ${this.sqlDPs[id].type}, ID: ${this.sqlDPs[id].index}) and state: ${JSON.stringify(state)}: ${err}`);
2420
+ }
2272
2421
  if (err) {
2273
2422
  return cb?.(err);
2274
2423
  }
@@ -2408,8 +2557,16 @@ class SqlAdapter extends adapter_core_1.Adapter {
2408
2557
  #keptErrors = new WeakSet();
2409
2558
  storeCached(onlyId, cb) {
2410
2559
  let count = 0;
2411
- for (const id in this.sqlDPs) {
2412
- if (!Object.prototype.hasOwnProperty.call(this.sqlDPs, id) || (onlyId !== undefined && onlyId !== id)) {
2560
+ // With `onlyId` (a full buffer, for every value with maxLength 0) only that datapoint: looping
2561
+ // over all datapoints to find it cost O(n) per value.
2562
+ const ids = onlyId !== undefined
2563
+ ? Object.prototype.hasOwnProperty.call(this.sqlDPs, onlyId)
2564
+ ? [onlyId]
2565
+ : []
2566
+ : Object.keys(this.sqlDPs);
2567
+ for (const id of ids) {
2568
+ // `ids` is a snapshot; `for...in` skipped datapoints that were deleted during the loop
2569
+ if (!this.sqlDPs[id]) {
2413
2570
  continue;
2414
2571
  }
2415
2572
  const _settings = this.sqlDPs[id].config || {};
@@ -2883,32 +3040,153 @@ class SqlAdapter extends adapter_core_1.Adapter {
2883
3040
  client.execute(query, (err, rows /* , fields */) => {
2884
3041
  this.returnClientToPool(client);
2885
3042
  if (!err && rows) {
2886
- for (let c = 0; c < rows.length; c++) {
2887
- if (typeof rows[c].ts === 'string') {
2888
- rows[c].ts = parseInt(rows[c].ts, 10);
2889
- }
2890
- if (this.common?.loglevel === 'debug') {
2891
- rows[c].date = new Date(rows[c].ts);
2892
- }
2893
- if (options.ack) {
2894
- rows[c].ack = !!rows[c].ack;
2895
- }
2896
- if (typeof rows[c].val === 'number' && isFinite(rows[c].val) && options.round) {
2897
- rows[c].val = Math.round(rows[c].val * options.round) / options.round;
2898
- }
2899
- if (options.id && this.sqlDPs[options.id] && this.sqlDPs[options.id].type === 2) {
2900
- // 2 === boolean
2901
- rows[c].val = !!rows[c].val;
2902
- }
2903
- if (options.addId && !rows[c].id && options.id) {
2904
- rows[c].id = options.id;
2905
- }
2906
- }
3043
+ this.#normalizeRows(rows, options);
2907
3044
  }
2908
3045
  callback?.(err, rows);
2909
3046
  });
2910
3047
  });
2911
3048
  }
3049
+ /**
3050
+ * Prepare the rows of a history read in place: numeric `ts`, `date` for the debug log, `ack` as boolean,
3051
+ * rounding, boolean values of boolean datapoints and `id` for `addId`. The buffered and the streamed
3052
+ * read use the same code, so both deliver the same rows.
3053
+ *
3054
+ * @param rows rows as the driver returned them
3055
+ * @param options options of the read
3056
+ */
3057
+ #normalizeRows(rows, options) {
3058
+ const isDebug = this.common?.loglevel === 'debug';
3059
+ const isBoolean = !!(options.id && this.sqlDPs[options.id] && this.sqlDPs[options.id].type === 2);
3060
+ for (let c = 0; c < rows.length; c++) {
3061
+ if (typeof rows[c].ts === 'string') {
3062
+ rows[c].ts = parseInt(rows[c].ts, 10);
3063
+ }
3064
+ if (isDebug) {
3065
+ rows[c].date = new Date(rows[c].ts);
3066
+ }
3067
+ if (options.ack) {
3068
+ rows[c].ack = !!rows[c].ack;
3069
+ }
3070
+ if (typeof rows[c].val === 'number' && isFinite(rows[c].val) && options.round) {
3071
+ rows[c].val = Math.round(rows[c].val * options.round) / options.round;
3072
+ }
3073
+ if (isBoolean) {
3074
+ // 2 === boolean
3075
+ rows[c].val = !!rows[c].val;
3076
+ }
3077
+ if (options.addId && !rows[c].id && options.id) {
3078
+ rows[c].id = options.id;
3079
+ }
3080
+ }
3081
+ }
3082
+ /**
3083
+ * Whether an aggregated read of one datapoint can be streamed from PostgreSQL instead of buffered (#516).
3084
+ *
3085
+ * The query of an aggregated read with a start returns every row in one `ORDER BY ts`, with at most one
3086
+ * row before the start and one after the end. Fed batch by batch, `aggregation()` then produces exactly
3087
+ * what it produces for the whole array, because all its state lives in the options. Values from the RAM
3088
+ * cache would have to be merged in by time, so a read with cached values stays buffered.
3089
+ *
3090
+ * `integralTotal` stays buffered: `aggregation()` adds a row from far before the start at the end of the
3091
+ * call that contains it, and `integralTotal` keeps one series in the order the rows were added.
3092
+ *
3093
+ * @param options options of the read
3094
+ * @param cachedValues number of values of this datapoint in the RAM cache
3095
+ * @param includesInFlightData whether values are being written right now
3096
+ */
3097
+ #canStream(options, cachedValues, includesInFlightData) {
3098
+ return (this.config.dbtype === 'postgresql' &&
3099
+ this.multiRequests &&
3100
+ !this.streamingUnavailable &&
3101
+ !!options.start &&
3102
+ !cachedValues &&
3103
+ !includesInFlightData &&
3104
+ !!options.aggregate &&
3105
+ options.aggregate !== 'none' &&
3106
+ options.aggregate !== 'onchange' &&
3107
+ options.aggregate !== 'integralTotal');
3108
+ }
3109
+ /**
3110
+ * Aggregated read of one datapoint, streamed from PostgreSQL in batches of `STREAM_BATCH_SIZE` rows, so the
3111
+ * memory of the adapter does not grow with the requested range (#516). Each batch is folded into the
3112
+ * aggregation right away. The answer is the one `sendResponse()` builds for the whole array.
3113
+ *
3114
+ * @param table table of the datapoint
3115
+ * @param options options of the read
3116
+ * @param msg the request
3117
+ * @param startTime when the request arrived
3118
+ * @param debugLog whether to log the aggregation steps
3119
+ * @param logId prefix of the debug log
3120
+ * @param readBuffered the buffered read, used when the driver cannot stream
3121
+ */
3122
+ #getAggregatedDataStreamed(table, options, msg, startTime, debugLog, logId, readBuffered) {
3123
+ const query = this.sqlFuncs.getHistory(this.config.dbname, table, options);
3124
+ if (typeof query !== 'string') {
3125
+ readBuffered();
3126
+ return;
3127
+ }
3128
+ this.#debugStatement(query);
3129
+ // like sendResponse(): the step of the request, before initAggregate() calculates one
3130
+ const responseStep = options.step || 0;
3131
+ const log = debugLog ? (text) => this.log.debug(`${logId}: ${text}`) : undefined;
3132
+ // Initialized with the first batch: if the driver cannot stream, `options` stays untouched for the buffered read
3133
+ let aggOptions;
3134
+ let rowCount = 0;
3135
+ let batches = 0;
3136
+ // An exception must not escape into the callback of the cursor: the connection would never be returned
3137
+ let aggError = null;
3138
+ this.borrowClientFromPool((err, client) => {
3139
+ if (err || !client) {
3140
+ this.returnClientToPool(client);
3141
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, (err || new Error('No client')).toString(), startTime);
3142
+ return;
3143
+ }
3144
+ client.executeStreamed(query, STREAM_BATCH_SIZE, rows => {
3145
+ if (aggError) {
3146
+ return;
3147
+ }
3148
+ try {
3149
+ aggOptions ??= (0, aggregate_1.initAggregate)(options, options.id, undefined, log);
3150
+ this.#normalizeRows(rows, options);
3151
+ rowCount += rows.length;
3152
+ batches++;
3153
+ (0, aggregate_1.aggregation)(aggOptions, rows);
3154
+ }
3155
+ catch (e) {
3156
+ aggError = e instanceof Error ? e : new Error(String(e));
3157
+ }
3158
+ }, (streamErr, streamed) => {
3159
+ this.returnClientToPool(client);
3160
+ if (!streamed) {
3161
+ if (!streamErr) {
3162
+ // pg-native, or pg-cursor is not installed: that does not change while the adapter runs
3163
+ this.streamingUnavailable = true;
3164
+ this.log.debug('PostgreSQL reads are not streamed: pg-native is used or pg-cursor is missing');
3165
+ }
3166
+ readBuffered();
3167
+ return;
3168
+ }
3169
+ if (streamErr || aggError) {
3170
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, (streamErr || aggError).toString(), startTime);
3171
+ return;
3172
+ }
3173
+ if (!aggOptions) {
3174
+ // no rows: the same "No Data" answer as for an empty buffered read
3175
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, [], startTime);
3176
+ return;
3177
+ }
3178
+ try {
3179
+ (0, aggregate_1.finishAggregation)(aggOptions);
3180
+ const result = aggOptions.result;
3181
+ this.log.debug(`Send after aggregation (streamed in ${batches} batches): ${result.length} of: ${rowCount} in: ${Date.now() - startTime}ms`);
3182
+ this.sendTo(msg.from, msg.command, { result, step: responseStep, sessionId: options.sessionId }, msg.callback);
3183
+ }
3184
+ catch (e) {
3185
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, e.toString(), startTime);
3186
+ }
3187
+ });
3188
+ });
3189
+ }
2912
3190
  getDataFromDB(table, options, callback) {
2913
3191
  const query = this.sqlFuncs.getHistory(this.config.dbname, table, options);
2914
3192
  this.#debugStatement(query);
@@ -3182,53 +3460,61 @@ class SqlAdapter extends adapter_core_1.Adapter {
3182
3460
  }, msg.callback);
3183
3461
  }
3184
3462
  else {
3185
- const origEnd = options.end;
3186
- if (includesInFlightData && earliestTs) {
3187
- options.end = earliestTs;
3188
- }
3189
- // if not all data read
3190
- this.getDataFromDB(dbNames[type], options, (err, data) => {
3191
- if (!err && data) {
3192
- options.end = origEnd;
3193
- if (options.aggregate === 'none' && options.count && options.returnNewestEntries) {
3194
- cacheData = cacheData.reverse();
3195
- data = cacheData.concat(data);
3196
- }
3197
- else {
3198
- data = data.concat(cacheData);
3199
- }
3200
- if (debugLog) {
3201
- this.log.debug(`${logId} after getDataFromDB: length = ${data.length}`);
3202
- }
3203
- if (options.count &&
3204
- data.length > options.count &&
3205
- options.aggregate === 'none' &&
3206
- !options.returnNewestEntries) {
3207
- if (options.start) {
3208
- for (let i = 0; i < data.length; i++) {
3209
- if (data[i].ts < options.start) {
3210
- data.splice(i, 1);
3211
- i--;
3212
- }
3213
- else {
3214
- break;
3215
- }
3216
- }
3463
+ const readBuffered = () => {
3464
+ const origEnd = options.end;
3465
+ if (includesInFlightData && earliestTs) {
3466
+ options.end = earliestTs;
3467
+ }
3468
+ // if not all data read
3469
+ this.getDataFromDB(dbNames[type], options, (err, data) => {
3470
+ if (!err && data) {
3471
+ options.end = origEnd;
3472
+ if (options.aggregate === 'none' && options.count && options.returnNewestEntries) {
3473
+ cacheData = cacheData.reverse();
3474
+ data = cacheData.concat(data);
3475
+ }
3476
+ else {
3477
+ data = data.concat(cacheData);
3217
3478
  }
3218
- data.splice(options.count);
3219
3479
  if (debugLog) {
3220
- this.log.debug(`${logId} pre-cut data to ${options.count} oldest values`);
3480
+ this.log.debug(`${logId} after getDataFromDB: length = ${data.length}`);
3221
3481
  }
3482
+ if (options.count &&
3483
+ data.length > options.count &&
3484
+ options.aggregate === 'none' &&
3485
+ !options.returnNewestEntries) {
3486
+ if (options.start) {
3487
+ for (let i = 0; i < data.length; i++) {
3488
+ if (data[i].ts < options.start) {
3489
+ data.splice(i, 1);
3490
+ i--;
3491
+ }
3492
+ else {
3493
+ break;
3494
+ }
3495
+ }
3496
+ }
3497
+ data.splice(options.count);
3498
+ if (debugLog) {
3499
+ this.log.debug(`${logId} pre-cut data to ${options.count} oldest values`);
3500
+ }
3501
+ }
3502
+ data.sort(sortByTs);
3222
3503
  }
3223
- data.sort(sortByTs);
3224
- }
3225
- try {
3226
- (0, aggregate_1.sendResponse)(this, msg, options.id, options, err?.toString() || data || [], startTime, debugLog ? logId : undefined);
3227
- }
3228
- catch (e) {
3229
- (0, aggregate_1.sendResponse)(this, msg, options.id, options, e.toString(), startTime);
3230
- }
3231
- });
3504
+ try {
3505
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, err?.toString() || data || [], startTime, debugLog ? logId : undefined);
3506
+ }
3507
+ catch (e) {
3508
+ (0, aggregate_1.sendResponse)(this, msg, options.id, options, e.toString(), startTime);
3509
+ }
3510
+ });
3511
+ };
3512
+ if (this.#canStream(options, cacheData.length, includesInFlightData)) {
3513
+ this.#getAggregatedDataStreamed(dbNames[type], options, msg, startTime, debugLog, logId, readBuffered);
3514
+ }
3515
+ else {
3516
+ readBuffered();
3517
+ }
3232
3518
  }
3233
3519
  });
3234
3520
  }