iobroker.sql 4.6.0 → 4.7.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.
package/README.md CHANGED
@@ -240,6 +240,10 @@ Structure:
240
240
  ## Messages for scripts and AI agents
241
241
  `sendTo('sql.0', 'help', {})` answers `{help, commands}`: a description of all messages and of the tables for AI agents (e.g. ioBroker.pi-agent) and script authors, and the list of all commands with `write: true` for the ones that change something.
242
242
 
243
+ `getHistory`, `aggregate` and `lastChange` are standard commands of the shared catalog of sendTo commands (family `history`, marked with `standard` in the answer of `help`), the same in history, sql, influxdb and recorder:
244
+ - `aggregate {id, start, end?, fn, value?}` answers one number for a period, `{value, ts?, unit?, count}`. `fn`: `min`, `max`, `avg`, `sum`, `count` (with `value`: how often the state became it), `delta` (how much a counter rose, resets included), `first`, `last`, `integral` (value × hours, W gives Wh), `duration` (with `value`: seconds the state had it).
245
+ - `lastChange {id, value?, before?}` answers when the state last changed (to `value`): `{ts, val}`.
246
+
243
247
  ## Access values from Javascript adapter
244
248
  The sorted values can be accessed from JavaScript adapter.
245
249
 
@@ -667,6 +671,10 @@ sendTo('sql.0', 'getEnabledDPs', {}, function (result) {
667
671
  -->
668
672
 
669
673
  ## Changelog
674
+ ### 4.7.0 (2026-11-23)
675
+ * (@GermanBluefox) Fixed: getHistory checks the range of `percentile` (0-100) and `quantile` (0-1) only for these aggregates (misplaced parentheses in the check)
676
+ * (@GermanBluefox) Added the standard commands of the shared catalog: history.aggregate (one number for a period: min, max, avg, sum, count, delta, first, last, integral, duration) and history.lastChange; getHistory is marked as history.getHistory
677
+
670
678
  ### 4.6.0 (2026-11-19)
671
679
  * (@GermanBluefox) Added the message "help": a description of all messages for AI agents (e.g. pi-agent), and `common.supportedMessages.help`
672
680
 
@@ -684,21 +692,6 @@ sendTo('sql.0', 'getEnabledDPs', {}, function (result) {
684
692
  * (@GermanBluefox) phpMyAdmin container: new instances listen on `127.0.0.1` by default instead of on all network interfaces. Existing instances keep their setting; to reach phpMyAdmin from another machine, choose the IP in the instance settings (#587)
685
693
  * (@Schimi1983) PostgreSQL: text values, datapoint IDs and sources are written as escape string literals (`E'...'`), so a backslash can no longer end a value early when `standard_conforming_strings` is off for the database or the user (#587)
686
694
 
687
- ### 4.4.0 (2026-11-05)
688
- * (@Schimi1983) Booleans are stored the same in all databases: `on`/`yes`/`true`/`1` as true, `off`/`no`/`false`/`0` and an empty text as false, any other text as NULL. Before, PostgreSQL failed the whole batch on such a text or a number, SQLite and MS SQL stored `off` as true. `storeState` says "values are kept, do not send them again" also when its values were written together with others of the same datapoint (#587)
689
- * (@Schimi1983) Messages are checked before they reach the database: `update`, `delete`, `deleteRange`, `deleteAll`, `storeState`, `getHistory` and `getCounter` refuse an entry without an ID, with a timestamp that is not a point in time, or with a value that does not fit the stored type, and report it in the answer instead of writing it into the SQL. Before, a `deleteRange` with an unparsable `start` deleted the whole history of the datapoint, a `delete` without an ID the history of the first datapoint of the table, a `start` given as a numeric string became `NaN`, and a value with a quote or a quote in a datapoint ID broke the statement (PostgreSQL, SQLite, MSSQL: quotes are now stored as they are instead of being removed, `Infinity` is stored as NULL). `storeState` with a value that is not a number for a numeric datapoint is answered again instead of waiting forever; a list of entries is answered after the last entry was written, with the errors of the entries that failed; a message with an unexpected shape no longer stops the adapter; "Maximum concurrent connections" of 0 no longer blocks every write (#587)
690
- * (@Schimi1983) MySQL: if the server's `sql_mode` contains `NO_BACKSLASH_ESCAPES`, the adapter removes it for its own connections and says so in the log - with that mode, values with `'` or `\` cannot be stored safely. The server's setting and other clients are not changed. Booleans: `on`/`yes`/`true`/`1` are stored as true, `off`/`no`/`false`/`0` and an empty text as false, any other text as NULL instead of true; a number is true unless it is 0 (#587)
691
- * (@Schimi1983) Stopping with many datapoints no longer loses values: the buffers of all datapoints are written at once instead of 50 per second, which did not finish within the 10 s stop timeout beyond about 450 datapoints. SQLite: buffered values of more than 100 datapoints no longer hit the task limit ("Cannot queue new requests"), a datapoint has one queued insert that takes further values (#587)
692
- * (@Schimi1983) MySQL: values, datapoint IDs and sources are passed as bound parameters instead of being inlined. Text values keep their single quotes (`it's` was stored as `its`), a value ending with a backslash no longer makes the whole batch fail, and the `delete`/`update`/`storeState` messages cannot inject SQL any more. `NaN`/`Infinity` are stored as NULL instead of failing the batch (#587)
693
- * (copilot) Adapter requires node.js >= 22.19.0 now
694
- * (@GermanBluefox) Fixed: values stored without `from` were missing in `getHistory` with `from: true`, e.g. in the history data of admin
695
- * (@Schimi1983) A failed write is no longer silently dropped: the error is passed on, so `storeState` reports it instead of `success: true`. If the database was not reachable, the values are kept and written with the next write of the datapoint (at most 2000 per datapoint, the oldest are dropped first, with a warning). Pooled connections that were idle for more than 60 s are closed and replaced, so a server-side `wait_timeout` no longer resets them; the warning "SQL connection lost" every few minutes on hosted databases is gone (#587)
696
- * (@GermanBluefox) The values kept while the database is not reachable are also limited to 200000 for all datapoints together (about 70 MB), so a long outage with many datapoints can no longer exhaust the memory. The warning about them is one line per minute for all datapoints instead of one per datapoint, and the error of `storeState` says when the values were kept, so they are not sent twice (#587)
697
- * (@GermanBluefox) Data browser: the values of a datapoint can be exported as CSV (e.g. for Excel) or as JSON (the format of `storeState`) for the selected time range. `getRawEntries` returns up to 5000 entries per call and accepts `noTotal` to skip the count
698
- * (@GermanBluefox) Data browser: PostgreSQL and MS SQL showed the time of a value as a bare number, because `getRawEntries` returned `ts` as string there
699
- * (@GermanBluefox) MySQL/MariaDB and MS SQL: datapoints whose IDs differ only in case (e.g. `alias.0.Licht` and `alias.0.licht`) or by trailing spaces no longer write into one series with the type of the first one. The second one gets its own row from now on; values that were already mixed stay where they are (#588)
700
- * (@GermanBluefox) MS SQL: `@azure/msal-node`, a dependency of the driver, was updated to 7.2.0 because of CVE-2026-109461 (GHSA-xcx6-jx8p-x3h5). It concerns the Azure authorization code flow, which the adapter does not use
701
-
702
695
  [Older changelogs can be found there](CHANGELOG_OLD.md)
703
696
 
704
697
  ## License
package/build/lib/help.js CHANGED
@@ -5,11 +5,17 @@
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.HELP = exports.COMMANDS = void 0;
8
- /** Every command `#dispatchMessage` answers; `write` = it changes data, settings or the instance */
8
+ /**
9
+ * Every command `#dispatchMessage` answers; `write` = it changes data, settings or the instance; `standard` = it
10
+ * follows the shared catalog of sendTo commands (HELP.md of ioBroker.assistant), the same in history, sql, influxdb
11
+ * and recorder
12
+ */
9
13
  exports.COMMANDS = [
10
14
  { command: 'help', write: false },
11
- { command: 'getHistory', write: false },
15
+ { command: 'getHistory', write: false, standard: 'history.getHistory' },
12
16
  { command: 'getCounter', write: false },
17
+ { command: 'aggregate', write: false, standard: 'history.aggregate' },
18
+ { command: 'lastChange', write: false, standard: 'history.lastChange' },
13
19
  { command: 'getEnabledDPs', write: false },
14
20
  { command: 'getDatapoints', write: false },
15
21
  { command: 'getDpOverview', write: false },
@@ -48,7 +54,8 @@ Tables (native.dbname of the instance, default "iobroker", qualifies them in MyS
48
54
  strings in single quotes. Example (MySQL): SELECT ts, val FROM \`iobroker\`.ts_number WHERE id = (SELECT id
49
55
  FROM \`iobroker\`.datapoints WHERE name = 'hm-rpc.0.ABC.1.TEMPERATURE') ORDER BY ts DESC LIMIT 10
50
56
 
51
- Commands (sendTo sql.0):
57
+ Commands (sendTo sql.0): getHistory, aggregate and lastChange are standard commands of the shared catalog of
58
+ ioBroker (family history): the same names, parameters and answers in history, sql, influxdb and recorder.
52
59
  - getHistory {id, options: {start?, end?, aggregate?, count?, step?, ...}}: the course of one state:
53
60
  {result: [{ts, val, ack?, from?, q?, id?}], step, sessionId}, on an error {result: [], error}. options is
54
61
  required (may be {}).
@@ -69,6 +76,15 @@ Commands (sendTo sql.0):
69
76
  - getCounter {id, options?: {start?, end?}}: how much a counter (a rising meter reading, e.g. kWh) rose between
70
77
  start (default: the beginning) and end (default now), a reset or a replaced meter included (setting "counter"
71
78
  of the state): {result: number}. Only for a logged state, else {error: "Not enabled"}.
79
+ - aggregate {id, start, end?, fn, value?}: one number for a period: {value, ts?, unit?, count}. fn: min, max (ts =
80
+ when), avg (the mean of the stored values), sum, count (with value: how often the state became it, e.g. true),
81
+ delta (how much a counter rose, resets included), first, last, integral (value × hours: W gives Wh), duration
82
+ (with value: how many seconds the state had it). end: default now. count: the stored values in the period, at
83
+ most 50000 (else reason TOO_MANY_VALUES). Errors: {error, reason} (reason BAD_REQUEST for a wrong parameter).
84
+ Computed from the values of getHistory (aggregate none).
85
+ - lastChange {id, value?, before?}: when the state last changed (to value): {ts, val}; before: only the values
86
+ before this time. A value logged again does not count as a change. Reason NOT_FOUND if it never had the value;
87
+ only the newest 10000 stored values are searched: limited true = it had it already then.
72
88
  - getEnabledDPs {}: the states this instance logs: {[id]: their settings (enabled, changesOnly, debounceTime,
73
89
  blockTime, changesMinDelta, changesRelogInterval, retention in s, maxLength, counter, storageType, aliasId,
74
90
  ...)}.
@@ -110,8 +126,10 @@ How to talk to the user:
110
126
  - Find the state first (search the objects); name states by their name, give times in local time and values
111
127
  with their unit.
112
128
  - A state has a history only if it is or was logged (getEnabledDPs, getDatapoints). For a longer period request
113
- one value per interval (e.g. aggregate average with count 24 to 200) instead of every stored value. Prefer
114
- getHistory; write a SELECT only for what it cannot answer, and read dbtype and dbname from the instance first.
129
+ one value per interval (e.g. aggregate average with count 24 to 200) instead of every stored value. For one
130
+ number of a period (the highest value, how often, how long, how much) use the command aggregate, for "when was
131
+ it last ..." lastChange. Prefer these and getHistory; write a SELECT only for what they cannot answer, and read
132
+ dbtype and dbname from the instance first.
115
133
  - Send only SELECT statements with query. Any other statement only on the user's explicit request.
116
134
  - query (other than SELECT), delete, deleteRange, deleteAll, update, storeState, cleanupOrphaned, destroy,
117
135
  enableHistory, disableHistory and stopInstance change the database, the settings or the instance: never
@@ -1 +1 @@
1
- {"version":3,"file":"help.js","sourceRoot":"","sources":["../../src/lib/help.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,oGAAoG;AACvF,QAAA,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AE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,IAAI,EAAE;IACzC,EAAE,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,IAAI,EAAE;IAC1C,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,IAAI,EAAE;IACtC,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE;IAClC,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE;IAClC,EAAE,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,IAAI,EAAE;IACvC,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,IAAI,EAAE;IACrC,EAAE,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,IAAI,EAAE;IAC3C,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE;IACnC,EAAE,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,IAAI,EAAE;CAC3C,CAAC;AAEW,QAAA,IAAI,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sCAoGkB,CAAC"}
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+ /**
3
+ * The commands `aggregate` and `lastChange` of the shared catalog of sendTo commands (family "history", see HELP.md
4
+ * of ioBroker.assistant): one number for a period, and the time of the last change of a state. Both are computed
5
+ * from the stored values as the adapter reads them anyway (for `getHistory` or `getRawEntries`), so they need no
6
+ * database query of their own.
7
+ *
8
+ * The same file is used by ioBroker.history, ioBroker.sql, ioBroker.influxdb and ioBroker.recorder: keep it identical.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.MAX_SCAN = exports.MAX_VALUES = exports.AGGREGATE_FUNCTIONS = void 0;
12
+ exports.aggregate = aggregate;
13
+ exports.lastChange = lastChange;
14
+ exports.readThroughGetHistory = readThroughGetHistory;
15
+ /** The values of `fn` of `aggregate` */
16
+ exports.AGGREGATE_FUNCTIONS = [
17
+ 'min',
18
+ 'max',
19
+ 'avg',
20
+ 'sum',
21
+ 'count',
22
+ 'delta',
23
+ 'first',
24
+ 'last',
25
+ 'integral',
26
+ 'duration',
27
+ ];
28
+ /** `aggregate` reads at most so many values: a longer period gives the error TOO_MANY_VALUES */
29
+ exports.MAX_VALUES = 50_000;
30
+ /** `lastChange` reads the values backwards in pages of this size ... */
31
+ const PAGE = 1_000;
32
+ /** ... and stops after so many values */
33
+ exports.MAX_SCAN = 10_000;
34
+ const HOUR = 3_600_000;
35
+ function fail(error, reason) {
36
+ return { error, reason };
37
+ }
38
+ /** ms since 1970 from a number, a numeric text or a date text (a text without a zone is local time) */
39
+ function toTimestamp(value) {
40
+ if (typeof value === 'number') {
41
+ return Number.isFinite(value) ? value : undefined;
42
+ }
43
+ if (typeof value !== 'string' || !value.trim()) {
44
+ return undefined;
45
+ }
46
+ const text = value.trim();
47
+ if (/^\d+$/.test(text)) {
48
+ return parseInt(text, 10);
49
+ }
50
+ // Date reads a date without a time as UTC, the catalog means the local midnight
51
+ const ts = new Date(/^\d{4}-\d{2}-\d{2}$/.test(text) ? `${text}T00:00` : text).getTime();
52
+ return Number.isFinite(ts) ? ts : undefined;
53
+ }
54
+ function isGiven(value) {
55
+ return value !== undefined && value !== null && value !== '';
56
+ }
57
+ /** A value as number (true = 1, false = 0, a numeric text), null if it is none */
58
+ function toNumber(val) {
59
+ if (typeof val === 'boolean') {
60
+ return val ? 1 : 0;
61
+ }
62
+ const n = typeof val === 'number' ? val : typeof val === 'string' && val.trim() ? Number(val) : NaN;
63
+ return Number.isFinite(n) ? n : null;
64
+ }
65
+ /** A value to compare: true, 1 and "true" are the same, as are 5 and "5"; texts without case */
66
+ function comparable(val) {
67
+ if (typeof val === 'boolean') {
68
+ return val ? 1 : 0;
69
+ }
70
+ if (typeof val === 'string') {
71
+ const text = val.trim().toLowerCase();
72
+ if (text === 'true' || text === 'false') {
73
+ return text === 'true' ? 1 : 0;
74
+ }
75
+ return text && Number.isFinite(Number(text)) ? Number(text) : text;
76
+ }
77
+ return val;
78
+ }
79
+ function same(a, b) {
80
+ return comparable(a) === comparable(b);
81
+ }
82
+ function round(value) {
83
+ return Math.round(value * 1000) / 1000;
84
+ }
85
+ /** The values in [start, end] without the gaps (null), sorted by ts */
86
+ function inRange(values, start, end) {
87
+ return values
88
+ .filter(v => v && v.ts >= start && v.ts <= end && v.val !== null && v.val !== undefined)
89
+ .sort((a, b) => a.ts - b.ts);
90
+ }
91
+ function errorText(e) {
92
+ return e instanceof Error ? e.message : String(e);
93
+ }
94
+ /** The value of one function; `before` = the last value before start, `end` = the end, but not after now */
95
+ function compute(fn, values, before, wanted, start, end) {
96
+ const numbers = values
97
+ .map(v => ({ ts: v.ts, n: toNumber(v.val) }))
98
+ .filter((v) => v.n !== null);
99
+ const sum = numbers.reduce((total, v) => total + v.n, 0);
100
+ switch (fn) {
101
+ case 'first':
102
+ case 'last': {
103
+ const v = fn === 'first' ? values[0] : values[values.length - 1];
104
+ return v ? { value: v.val, ts: v.ts } : { value: null };
105
+ }
106
+ case 'min':
107
+ case 'max': {
108
+ let best;
109
+ for (const v of numbers) {
110
+ if (!best || (fn === 'min' ? v.n < best.n : v.n > best.n)) {
111
+ best = v;
112
+ }
113
+ }
114
+ return best ? { value: best.n, ts: best.ts } : { value: null };
115
+ }
116
+ case 'avg':
117
+ return { value: numbers.length ? round(sum / numbers.length) : null };
118
+ case 'sum':
119
+ return { value: round(sum) };
120
+ case 'count': {
121
+ if (!isGiven(wanted)) {
122
+ return { value: values.length };
123
+ }
124
+ // how often the state became the value: the values before it do not count again
125
+ let count = 0;
126
+ let previous = before?.val;
127
+ for (const v of values) {
128
+ if (same(v.val, wanted) && (previous === undefined || !same(previous, wanted))) {
129
+ count++;
130
+ }
131
+ previous = v.val;
132
+ }
133
+ return { value: count };
134
+ }
135
+ case 'delta': {
136
+ // how much a counter rose: a value below the one before is a reset, it rose from 0 to this value
137
+ const series = (before ? [before, ...values] : values)
138
+ .map(v => toNumber(v.val))
139
+ .filter((n) => n !== null);
140
+ let rise = 0;
141
+ for (let i = 1; i < series.length; i++) {
142
+ rise += series[i] >= series[i - 1] ? series[i] - series[i - 1] : series[i];
143
+ }
144
+ return { value: series.length ? round(rise) : null };
145
+ }
146
+ default: {
147
+ // integral and duration: every value holds until the next one, the last one until the end
148
+ const line = before ? [{ ts: start, val: before.val }, ...values] : values;
149
+ let total = 0;
150
+ for (let i = 0; i < line.length; i++) {
151
+ const from = Math.max(line[i].ts, start);
152
+ const to = Math.min(i + 1 < line.length ? line[i + 1].ts : end, end);
153
+ if (to > from) {
154
+ if (fn === 'duration') {
155
+ total += same(line[i].val, wanted) ? to - from : 0;
156
+ }
157
+ else {
158
+ total += (toNumber(line[i].val) ?? 0) * (to - from);
159
+ }
160
+ }
161
+ }
162
+ if (!line.length) {
163
+ return { value: null };
164
+ }
165
+ return { value: fn === 'duration' ? Math.round(total / 1000) : round(total / HOUR) };
166
+ }
167
+ }
168
+ }
169
+ /**
170
+ * `aggregate {id, start, end?, fn, value?}`: one number for a period, `{value, ts?, unit?, count}`.
171
+ * fn: min, max (ts = when), avg, sum, count (with value: how often the state became it), delta (how much a counter
172
+ * rose, resets included), first, last (ts = when), integral (value × hours, e.g. W → Wh), duration (with value:
173
+ * seconds the state had it). count = the number of stored values in the period.
174
+ *
175
+ * @param message the message of sendTo
176
+ * @param source the stored values
177
+ * @param now the current time
178
+ */
179
+ async function aggregate(message, source, now = Date.now()) {
180
+ const m = (message && typeof message === 'object' ? message : {});
181
+ const id = m.id;
182
+ const fn = m.fn;
183
+ if (typeof id !== 'string' || !id) {
184
+ return fail('id is missing', 'BAD_REQUEST');
185
+ }
186
+ if (typeof fn !== 'string' || !exports.AGGREGATE_FUNCTIONS.includes(fn)) {
187
+ return fail(`fn must be one of ${exports.AGGREGATE_FUNCTIONS.join(', ')}`, 'BAD_REQUEST');
188
+ }
189
+ const start = toTimestamp(m.start);
190
+ const end = isGiven(m.end) ? toTimestamp(m.end) : now;
191
+ if (start === undefined || end === undefined || start > end) {
192
+ return fail('start and end must be times (ms or a date text) and start not after end', 'BAD_REQUEST');
193
+ }
194
+ if (fn === 'duration' && !isGiven(m.value)) {
195
+ return fail('fn duration needs the value', 'BAD_REQUEST');
196
+ }
197
+ try {
198
+ const read = await source.read(id, { start, end, count: exports.MAX_VALUES + 1 });
199
+ if (read.length > exports.MAX_VALUES) {
200
+ return fail(`More than ${exports.MAX_VALUES} stored values in this period: ask for a shorter one`, 'TOO_MANY_VALUES');
201
+ }
202
+ const values = inRange(read, start, end);
203
+ // what the state was at start, for the changes, the counter and the time line
204
+ let before;
205
+ if ((fn === 'count' && isGiven(m.value)) || fn === 'delta' || fn === 'integral' || fn === 'duration') {
206
+ before = inRange(await source.read(id, { end: start - 1, count: 10 }), -Infinity, start - 1).pop();
207
+ }
208
+ const result = compute(fn, values, before, m.value, start, Math.min(end, now));
209
+ const answer = { value: result.value, count: values.length };
210
+ if (result.ts !== undefined) {
211
+ answer.ts = result.ts;
212
+ }
213
+ const unit = fn === 'duration' ? 's' : fn === 'count' ? undefined : await source.unit?.(id);
214
+ if (unit) {
215
+ answer.unit = fn === 'integral' ? `${unit}h` : unit;
216
+ }
217
+ return answer;
218
+ }
219
+ catch (e) {
220
+ return { error: errorText(e) };
221
+ }
222
+ }
223
+ /**
224
+ * `lastChange {id, value?, before?}`: when the state last changed (to value), `{ts, val}`: the first of the newest
225
+ * stored values that are the same as the newest one (or as value). before: only the values before this time.
226
+ * At most MAX_SCAN values are read: if the state had the value longer, ts is the oldest one read and limited true.
227
+ *
228
+ * @param message the message of sendTo
229
+ * @param source the stored values
230
+ * @param now the current time
231
+ */
232
+ async function lastChange(message, source, now = Date.now()) {
233
+ const m = (message && typeof message === 'object' ? message : {});
234
+ const id = m.id;
235
+ if (typeof id !== 'string' || !id) {
236
+ return fail('id is missing', 'BAD_REQUEST');
237
+ }
238
+ let end = isGiven(m.before) ? toTimestamp(m.before) : now;
239
+ if (end === undefined) {
240
+ return fail('before must be a time (ms or a date text)', 'BAD_REQUEST');
241
+ }
242
+ let wanted = m.value;
243
+ // the oldest value read of the newest run of values that are the same as the wanted one
244
+ let run;
245
+ try {
246
+ for (let scanned = 0; scanned < exports.MAX_SCAN;) {
247
+ const page = await source.read(id, { end, count: PAGE });
248
+ const values = inRange(page, -Infinity, end);
249
+ for (let i = values.length - 1; i >= 0; i--) {
250
+ if (!isGiven(wanted)) {
251
+ wanted = values[i].val;
252
+ }
253
+ if (same(values[i].val, wanted)) {
254
+ run = values[i];
255
+ }
256
+ else if (run) {
257
+ return { ts: run.ts, val: run.val };
258
+ }
259
+ }
260
+ if (page.length < PAGE) {
261
+ // no older values: the state has had it since the first stored value
262
+ return run ? { ts: run.ts, val: run.val } : fail(`${id} has no such stored value`, 'NOT_FOUND');
263
+ }
264
+ scanned += page.length;
265
+ end = Math.min(...page.map(v => v.ts)) - 1;
266
+ }
267
+ }
268
+ catch (e) {
269
+ return { error: errorText(e) };
270
+ }
271
+ return run
272
+ ? { ts: run.ts, val: run.val, limited: true }
273
+ : fail(`${id} has no such value in its newest ${exports.MAX_SCAN} stored values`, 'NOT_FOUND');
274
+ }
275
+ /**
276
+ * The `read` of a `ValueSource` through the adapter's own `getHistory` (aggregate none, without border values).
277
+ *
278
+ * @param ask sends `getHistory` with this message to the own instance and resolves with the answer
279
+ */
280
+ function readThroughGetHistory(ask) {
281
+ return async (id, query) => {
282
+ const answer = (await ask({
283
+ id,
284
+ options: {
285
+ start: query.start,
286
+ end: query.end,
287
+ count: query.count,
288
+ limit: query.count,
289
+ aggregate: 'none',
290
+ returnNewestEntries: query.start === undefined,
291
+ removeBorderValues: true,
292
+ },
293
+ }));
294
+ if (answer instanceof Error) {
295
+ throw answer;
296
+ }
297
+ if (answer?.error) {
298
+ throw new Error(typeof answer.error === 'string' ? answer.error : JSON.stringify(answer.error));
299
+ }
300
+ return Array.isArray(answer?.result) ? answer.result : [];
301
+ };
302
+ }
303
+ //# sourceMappingURL=standardHistory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standardHistory.js","sourceRoot":"","sources":["../../src/lib/standardHistory.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AA4MH,8BAkDC;AAWD,gCA4CC;AAOD,sDAwBC;AA9TD,wCAAwC;AAC3B,QAAA,mBAAmB,GAAG;IAC/B,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,OAAO;IACP,OAAO;IACP,OAAO;IACP,MAAM;IACN,UAAU;IACV,UAAU;CACb,CAAC;AAEF,gGAAgG;AACnF,QAAA,UAAU,GAAG,MAAM,CAAC;AACjC,wEAAwE;AACxE,MAAM,IAAI,GAAG,KAAK,CAAC;AACnB,yCAAyC;AAC5B,QAAA,QAAQ,GAAG,MAAM,CAAC;AAC/B,MAAM,IAAI,GAAG,SAAS,CAAC;AAEvB,SAAS,IAAI,CAAC,KAAa,EAAE,MAAc;IACvC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAC7B,CAAC;AAED,uGAAuG;AACvG,SAAS,WAAW,CAAC,KAAc;IAC/B,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACtD,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC;QAC7C,OAAO,SAAS,CAAC;IACrB,CAAC;IACD,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC1B,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACrB,OAAO,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IAC9B,CAAC;IACD,gFAAgF;IAChF,MAAM,EAAE,GAA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,CAAC,IAAI,CAAC,GAAG,EAAE,oCAAoC,gBAAQ,gBAAgB,EAAE,WAAW,CAAC,CAAC;AAC/F,CAAC;AAED;;;;GAIG;AACH,SAAgB,qBAAqB,CACjC,GAAoF;IAEpF,OAAO,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE;QACvB,MAAM,MAAM,GAAG,CAAC,MAAM,GAAG,CAAC;YACtB,EAAE;YACF,OAAO,EAAE;gBACL,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,GAAG,EAAE,KAAK,CAAC,GAAG;gBACd,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,SAAS,EAAE,MAAM;gBACjB,mBAAmB,EAAE,KAAK,CAAC,KAAK,KAAK,SAAS;gBAC9C,kBAAkB,EAAE,IAAI;aAC3B;SACJ,CAAC,CAA2E,CAAC;QAC9E,IAAI,MAAM,YAAY,KAAK,EAAE,CAAC;YAC1B,MAAM,MAAM,CAAC;QACjB,CAAC;QACD,IAAI,MAAM,EAAE,KAAK,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACpG,CAAC;QACD,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;IAC9D,CAAC,CAAC;AACN,CAAC"}
package/build/main.js CHANGED
@@ -55,6 +55,7 @@ const postgresql_client_1 = require("./lib/postgresql-client");
55
55
  const sqlite3_client_1 = require("./lib/sqlite3-client");
56
56
  const errors_1 = require("./lib/errors");
57
57
  const help_1 = require("./lib/help");
58
+ const standardHistory_1 = require("./lib/standardHistory");
58
59
  const write_buffer_1 = require("./lib/write-buffer");
59
60
  const SQLFuncs = {
60
61
  mssql: {
@@ -208,6 +209,8 @@ const KEPT_LOG_INTERVAL = 60_000;
208
209
  const MAX_RAW_ENTRIES = 5000;
209
210
  /** How often an unchanged connection error is repeated as error in the log */
210
211
  const REPEATED_ERROR_INTERVAL = 3_600_000;
212
+ /** How long `aggregate` and `lastChange` wait for the answer of the own `getHistory` */
213
+ const STANDARD_TIMEOUT = 120_000;
211
214
  function sortByTs(a, b) {
212
215
  const aTs = a.ts;
213
216
  const bTs = b.ts;
@@ -1394,6 +1397,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
1394
1397
  else if (msg.command === 'getCounter') {
1395
1398
  this.getCounterDiff(msg);
1396
1399
  }
1400
+ else if (msg.command === 'aggregate') {
1401
+ void this.answerStandard(msg, standardHistory_1.aggregate);
1402
+ }
1403
+ else if (msg.command === 'lastChange') {
1404
+ void this.answerStandard(msg, standardHistory_1.lastChange);
1405
+ }
1397
1406
  else if (msg.command === 'test') {
1398
1407
  void this.testConnection(msg);
1399
1408
  }
@@ -2939,6 +2948,19 @@ class SqlAdapter extends adapter_core_1.Adapter {
2939
2948
  this.#getDataFromDB(query, options, callback);
2940
2949
  }
2941
2950
  }
2951
+ /**
2952
+ * Answer `aggregate` or `lastChange` of the shared catalog of sendTo commands (family history): computed from the
2953
+ * stored values, read with the own `getHistory` (as a message to this instance, so getHistory stays as it is)
2954
+ */
2955
+ async answerStandard(msg, command) {
2956
+ const answer = await command(msg.message, {
2957
+ read: (0, standardHistory_1.readThroughGetHistory)(message => this.sendToAsync(this.namespace, 'getHistory', message, { timeout: STANDARD_TIMEOUT })),
2958
+ unit: async (id) => (await this.getForeignObjectAsync(id))?.common?.unit,
2959
+ });
2960
+ if (msg.callback) {
2961
+ this.sendTo(msg.from, msg.command, answer, msg.callback);
2962
+ }
2963
+ }
2942
2964
  getCounterDiff(msg) {
2943
2965
  const id = msg.message?.id;
2944
2966
  const opts = msg.message?.options || {};
@@ -3070,11 +3092,11 @@ class SqlAdapter extends adapter_core_1.Adapter {
3070
3092
  else {
3071
3093
  options.round = configuredRound;
3072
3094
  }
3073
- if ((options.aggregate === 'percentile' && options.percentile < 0) || options.percentile > 100) {
3095
+ if (options.aggregate === 'percentile' && (options.percentile < 0 || options.percentile > 100)) {
3074
3096
  this.log.error(`Invalid percentile value: ${options.percentile}, use 50 as default`);
3075
3097
  options.percentile = 50;
3076
3098
  }
3077
- if ((options.aggregate === 'quantile' && options.quantile < 0) || options.quantile > 1) {
3099
+ if (options.aggregate === 'quantile' && (options.quantile < 0 || options.quantile > 1)) {
3078
3100
  this.log.error(`Invalid quantile value: ${options.quantile}, use 0.5 as default`);
3079
3101
  options.quantile = 0.5;
3080
3102
  }