iobroker.sql 4.6.0 → 4.8.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
@@ -54,6 +54,18 @@ Most of these values can be pre-defined in the instance settings and are then pr
54
54
  Use `localhost\instance` for the host and check TCP/IP connections enabled.
55
55
  https://msdn.microsoft.com/en-us/library/bb909712(v=vs.90).aspx
56
56
 
57
+ SQL Server 2012 or newer is needed.
58
+
59
+ Tables that the adapter creates now store every character (e.g. Cyrillic letters or emojis, before they became `?`) and keep IDs apart that differ only in upper/lower case. Tables that already exist are not changed automatically and keep working as before.
60
+
61
+ To convert existing tables: stop the SQL instance and make a backup of the database. Datapoints whose ID already contains a `?` instead of a special character (look for `?` in the `name` column of `datapoints`) would get a new, empty history after the conversion; rename them first with the correct ID, e.g. `UPDATE [iobroker].dbo.datapoints SET name = N'alias.0.Кухня' WHERE id = 12;`. Then run these commands (replace `iobroker` with the name of your database) and start the instance again. The last command rewrites the whole `ts_string` table, which takes a while on a large database. Characters in values that were already stored as `?` cannot be restored.
62
+
63
+ ```sql
64
+ ALTER TABLE [iobroker].dbo.datapoints ALTER COLUMN name nvarchar(255) COLLATE Latin1_General_100_CS_AS_SC;
65
+ ALTER TABLE [iobroker].dbo.sources ALTER COLUMN name nvarchar(255) COLLATE Latin1_General_100_CS_AS_SC;
66
+ ALTER TABLE [iobroker].dbo.ts_string ALTER COLUMN val nvarchar(max);
67
+ ```
68
+
57
69
  ### SQLite:
58
70
  is a "file"-DB and cannot manage too many events. If you have a big amount of data, use the real DB, like PostgreSQL and co.
59
71
 
@@ -240,6 +252,10 @@ Structure:
240
252
  ## Messages for scripts and AI agents
241
253
  `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
254
 
255
+ `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:
256
+ - `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).
257
+ - `lastChange {id, value?, before?}` answers when the state last changed (to `value`): `{ts, val}`.
258
+
243
259
  ## Access values from Javascript adapter
244
260
  The sorted values can be accessed from JavaScript adapter.
245
261
 
@@ -667,6 +683,15 @@ sendTo('sql.0', 'getEnabledDPs', {}, function (result) {
667
683
  -->
668
684
 
669
685
  ## Changelog
686
+ ### 4.8.0 (2026-11-28)
687
+ * (@DutchmanNL) PostgreSQL: an aggregated `getHistory` of one datapoint reads the rows in batches of 2000 (pg-cursor) and aggregates them batch by batch, instead of holding the whole range in memory first. The answer stays the same; without pg-cursor, with pg-native, and for `integralTotal` the values are read as before (#516)
688
+ * (@Schimi1983) MS SQL: new tables store names and string values as Unicode (`nvarchar`, `N'...'`), so Cyrillic letters or emojis no longer become `?`, and the names compare case-sensitively. The database name is put in brackets, so a name like `io-broker` works. Existing tables are not changed; the README explains how to convert them (#588)
689
+ * (@Schimi1983) Faster start with many datapoints: the first value of each datapoint no longer waits 50 ms in the type lookup, and debug texts with the value are only built when debug logging is on (#587)
690
+
691
+ ### 4.7.0 (2026-11-23)
692
+ * (@GermanBluefox) Fixed: getHistory checks the range of `percentile` (0-100) and `quantile` (0-1) only for these aggregates (misplaced parentheses in the check)
693
+ * (@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
694
+
670
695
  ### 4.6.0 (2026-11-19)
671
696
  * (@GermanBluefox) Added the message "help": a description of all messages for AI agents (e.g. pi-agent), and `common.supportedMessages.help`
672
697
 
@@ -678,27 +703,6 @@ sendTo('sql.0', 'getEnabledDPs', {}, function (result) {
678
703
  * (@Schimi1983) The database password is stored encrypted (`encryptedNative`). A password saved with an older version is encrypted once on the first start, the instance then restarts by itself. Note: after going back to 4.4.1 or older, enter the password in the instance settings again (#587)
679
704
  * (@DutchmanNL) PostgreSQL: new opt-in setting "Relax PostgreSQL commit durability" runs the adapter's connections with `synchronous_commit=off`, so commits no longer wait for the disk flush. This strongly reduces disk I/O and wear. A crash of the PostgreSQL server can lose the values of the last few hundred milliseconds; the database cannot be corrupted (#516)
680
705
 
681
- ### 4.4.1 (2026-11-08)
682
- * (@GermanBluefox) `getDpOverview` with an empty `datapoints` table answers again and returns its connection. Before, the request never got an answer and the connection stayed borrowed, which with SQLite (one connection) blocked every further request (#587)
683
- * (@GermanBluefox) "Round real to" of a datapoint now applies to `getHistory`. Before, the field was shown but had no effect, only the setting of the instance counted. As with the instance setting, the values are rounded when read, the stored values stay as they are (#587)
684
- * (@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
- * (@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
-
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
706
  [Older changelogs can be found there](CHANGELOG_OLD.md)
703
707
 
704
708
  ## License
@@ -7,6 +7,25 @@ class ConnectionFactory {
7
7
  * statement with values is rejected instead of running it without them.
8
8
  */
9
9
  supportsParams = false;
10
+ /**
11
+ * Read the rows of a query in batches instead of buffering the whole result in RAM.
12
+ *
13
+ * `streamed` in the callback says whether streaming took place. `false` means this driver cannot
14
+ * stream (or the connection could not be used for it), and the caller has to read the buffered
15
+ * way with `execute()`. `onRows` is only called while streaming really takes place, so a caller
16
+ * can start any per-request work lazily on the first batch.
17
+ *
18
+ * The default reports "not supported"; only a driver that overrides it streams.
19
+ *
20
+ * @param _connection the open connection
21
+ * @param _sql plain SQL without bound values
22
+ * @param _batchSize maximum number of rows per `onRows` call
23
+ * @param _onRows receives the rows batch by batch, in the order of the query
24
+ * @param callback called once at the end
25
+ */
26
+ executeStreamed(_connection, _sql, _batchSize, _onRows, callback) {
27
+ callback(null, false);
28
+ }
10
29
  }
11
30
  exports.ConnectionFactory = ConnectionFactory;
12
31
  //# sourceMappingURL=connection-factory.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection-factory.js","sourceRoot":"","sources":["../../src/lib/connection-factory.ts"],"names":[],"mappings":";;;AAIA,MAAsB,iBAAiB;IACnC;;;OAGG;IACM,cAAc,GAAY,KAAK,CAAC;CAU5C;AAfD,8CAeC"}
1
+ {"version":3,"file":"connection-factory.js","sourceRoot":"","sources":["../../src/lib/connection-factory.ts"],"names":[],"mappings":";;;AAIA,MAAsB,iBAAiB;IACnC;;;OAGG;IACM,cAAc,GAAY,KAAK,CAAC;IAWzC;;;;;;;;;;;;;;;OAeG;IACH,eAAe,CACX,WAA0B,EAC1B,IAAY,EACZ,UAAkB,EAClB,OAAiC,EACjC,QAAoE;QAEpE,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC1B,CAAC;CACJ;AAzCD,8CAyCC"}
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,QAAQ,GAA0C;IAC3D,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE;IACjC,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE;IACvC,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE;IACvC,EAAE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,EAAE;IAC1C,EAAE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,EAAE;IAC1C,EAAE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,EAAE;IAC1C,EAAE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,EAAE;IAC1C,EAAE,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,KAAK,EAAE;IAC5C,EAAE,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAAE;IACrC,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE;IACjC,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE;IACjC,EAAE,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sCAwFkB,CAAC"}
1
+ {"version":3,"file":"help.js","sourceRoot":"","sources":["../../src/lib/help.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH;;;;GAIG;AACU,QAAA,QAAQ,GAA6D;IAC9E,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE;IACjC,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,oBAAoB,EAAE;IACvE,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE;IACvC,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,mBAAmB,EAAE;IACrE,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,oBAAoB,EAAE;IACvE,EAAE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,EAAE;IAC1C,EAAE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,EAAE;IAC1C,EAAE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,EAAE;IAC1C,EAAE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,EAAE;IAC1C,EAAE,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,KAAK,EAAE;IAC5C,EAAE,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAAE;IACrC,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE;IACjC,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE;IACjC,EAAE,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"}
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getNameColumnTypes = getNameColumnTypes;
4
+ exports.setNameColumnTypes = setNameColumnTypes;
3
5
  exports.init = init;
4
6
  exports.destroy = destroy;
5
7
  exports.getFirstTs = getFirstTs;
@@ -20,21 +22,84 @@ exports.update = update;
20
22
  exports.getRawEntries = getRawEntries;
21
23
  exports.getRawEntriesCount = getRawEntriesCount;
22
24
  const sql_string_1 = require("./sql-string");
25
+ /**
26
+ * Per database: the `name` columns that are still `varchar` (tables created before #588, unless converted by hand).
27
+ *
28
+ * Such a column keeps only the code page of its collation: `alias.0.Кухня` is stored as `alias.0.?????`. A plain
29
+ * literal is converted the same way and finds that row. With an `N'...'` literal SQL Server converts the column to
30
+ * `nvarchar` instead, the row is not found, the insert stores `?????` again, the select after it finds nothing, and
31
+ * every value of the datapoint is lost while `datapoints` grows. So these columns keep plain literals.
32
+ */
33
+ const varcharNames = new Map();
34
+ /**
35
+ * Statement that reads the type of the `name` columns of `datapoints` and `sources` (see `setNameColumnTypes()`).
36
+ *
37
+ * @param dbName name of the database
38
+ */
39
+ function getNameColumnTypes(dbName) {
40
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
41
+ return (`SELECT t.name AS tbl, TYPE_NAME(c.user_type_id) AS type FROM ${db}.sys.columns c ` +
42
+ `JOIN ${db}.sys.tables t ON t.object_id = c.object_id ` +
43
+ `WHERE c.name = 'name' AND t.name IN ('datapoints', 'sources');`);
44
+ }
45
+ /**
46
+ * Remember which `name` columns of a database are still `varchar`, from the rows of `getNameColumnTypes()`.
47
+ *
48
+ * @param dbName name of the database
49
+ * @param rows the rows returned by `getNameColumnTypes()`
50
+ */
51
+ function setNameColumnTypes(dbName, rows) {
52
+ const varchar = new Set();
53
+ for (const row of rows) {
54
+ if ((row.tbl === 'datapoints' || row.tbl === 'sources') && !String(row.type).toLowerCase().startsWith('n')) {
55
+ varchar.add(row.tbl);
56
+ }
57
+ }
58
+ varcharNames.set(dbName, varchar);
59
+ }
60
+ /**
61
+ * A name as literal for the `name` column of `table`: `N'...'` for `nvarchar`, plain for a `varchar` column of an
62
+ * older table (see `varcharNames`).
63
+ *
64
+ * @param dbName name of the database
65
+ * @param table `datapoints` or `sources`
66
+ * @param name the name
67
+ */
68
+ function nameLiteral(dbName, table, name) {
69
+ return varcharNames.get(dbName)?.has(table) ? (0, sql_string_1.quoteSqlString)(name) : (0, sql_string_1.quoteNString)(name);
70
+ }
71
+ /**
72
+ * `nvarchar` keeps every character: `varchar` stores only the code page of the collation, so `alias.0.Кухня`
73
+ * or an emoji came back as `?`. The collation compares case-sensitively like ioBroker IDs (#588); `_SC`
74
+ * makes 4-byte characters (emojis) compare as one character. Trailing spaces are still ignored by `=` (SQL
75
+ * Server pads every comparison), so `pickRowByName()` keeps `alias.0.Tor` and `alias.0.Tor ` apart.
76
+ */
77
+ const NAME = 'nvarchar(255) COLLATE Latin1_General_100_CS_AS_SC';
78
+ /**
79
+ * Statements that create the database (unless it exists already) and the tables of the adapter.
80
+ *
81
+ * Only new tables get `NAME` and `nvarchar(max)` for `ts_string`; existing tables are not changed. The README
82
+ * explains how to convert them by hand.
83
+ *
84
+ * @param dbName name of the database
85
+ * @param doNotCreateDatabase the database was created outside the adapter (e.g. by a hoster)
86
+ */
23
87
  function init(dbName, doNotCreateDatabase) {
88
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
24
89
  const commands = [
25
- `CREATE TABLE ${dbName}.dbo.sources (id INTEGER NOT NULL PRIMARY KEY IDENTITY(1,1), name varchar(255));`,
26
- `CREATE TABLE ${dbName}.dbo.datapoints (id INTEGER NOT NULL PRIMARY KEY IDENTITY(1,1), name varchar(255), type INTEGER);`,
27
- `CREATE TABLE ${dbName}.dbo.ts_number (id INTEGER, ts BIGINT, val REAL, ack BIT, _from INTEGER, q INTEGER);`,
28
- `CREATE INDEX i_id on ${dbName}.dbo.ts_number (id, ts);`,
29
- `CREATE TABLE ${dbName}.dbo.ts_string (id INTEGER, ts BIGINT, val TEXT, ack BIT, _from INTEGER, q INTEGER);`,
30
- `CREATE INDEX i_id on ${dbName}.dbo.ts_string (id, ts);`,
31
- `CREATE TABLE ${dbName}.dbo.ts_bool (id INTEGER, ts BIGINT, val BIT, ack BIT, _from INTEGER, q INTEGER);`,
32
- `CREATE INDEX i_id on ${dbName}.dbo.ts_bool (id, ts);`,
33
- `CREATE TABLE ${dbName}.dbo.ts_counter (id INTEGER, ts BIGINT, val REAL);`,
34
- `CREATE INDEX i_id on ${dbName}.dbo.ts_counter (id, ts);`,
90
+ `CREATE TABLE ${db}.dbo.sources (id INTEGER NOT NULL PRIMARY KEY IDENTITY(1,1), name ${NAME});`,
91
+ `CREATE TABLE ${db}.dbo.datapoints (id INTEGER NOT NULL PRIMARY KEY IDENTITY(1,1), name ${NAME}, type INTEGER);`,
92
+ `CREATE TABLE ${db}.dbo.ts_number (id INTEGER, ts BIGINT, val REAL, ack BIT, _from INTEGER, q INTEGER);`,
93
+ `CREATE INDEX i_id on ${db}.dbo.ts_number (id, ts);`,
94
+ `CREATE TABLE ${db}.dbo.ts_string (id INTEGER, ts BIGINT, val nvarchar(max), ack BIT, _from INTEGER, q INTEGER);`,
95
+ `CREATE INDEX i_id on ${db}.dbo.ts_string (id, ts);`,
96
+ `CREATE TABLE ${db}.dbo.ts_bool (id INTEGER, ts BIGINT, val BIT, ack BIT, _from INTEGER, q INTEGER);`,
97
+ `CREATE INDEX i_id on ${db}.dbo.ts_bool (id, ts);`,
98
+ `CREATE TABLE ${db}.dbo.ts_counter (id INTEGER, ts BIGINT, val REAL);`,
99
+ `CREATE INDEX i_id on ${db}.dbo.ts_counter (id, ts);`,
35
100
  ];
36
101
  if (!doNotCreateDatabase) {
37
- commands.unshift(`CREATE DATABASE ${dbName};`);
102
+ commands.unshift(`CREATE DATABASE ${db};`);
38
103
  }
39
104
  return commands;
40
105
  }
@@ -46,23 +111,25 @@ function init(dbName, doNotCreateDatabase) {
46
111
  * because the adapter could not create the database again and other tables in it would be lost.
47
112
  */
48
113
  function destroy(dbName, doNotCreateDatabase) {
114
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
49
115
  const commands = [
50
- `DROP TABLE ${dbName}.dbo.ts_counter;`,
51
- `DROP TABLE ${dbName}.dbo.ts_number;`,
52
- `DROP TABLE ${dbName}.dbo.ts_string;`,
53
- `DROP TABLE ${dbName}.dbo.ts_bool;`,
54
- `DROP TABLE ${dbName}.dbo.sources;`,
55
- `DROP TABLE ${dbName}.dbo.datapoints;`,
116
+ `DROP TABLE ${db}.dbo.ts_counter;`,
117
+ `DROP TABLE ${db}.dbo.ts_number;`,
118
+ `DROP TABLE ${db}.dbo.ts_string;`,
119
+ `DROP TABLE ${db}.dbo.ts_bool;`,
120
+ `DROP TABLE ${db}.dbo.sources;`,
121
+ `DROP TABLE ${db}.dbo.datapoints;`,
56
122
  ];
57
123
  if (!doNotCreateDatabase) {
58
- commands.push(`DROP DATABASE ${dbName};`);
124
+ commands.push(`DROP DATABASE ${db};`);
59
125
  // needs ALTER SERVER STATE, which a user of an existing (hosted) database usually lacks
60
126
  commands.push('DBCC FREEPROCCACHE;');
61
127
  }
62
128
  return commands;
63
129
  }
64
130
  function getFirstTs(dbName, table) {
65
- return `SELECT id, MIN(ts) AS ts FROM ${dbName}.dbo.${table} GROUP BY id;`;
131
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
132
+ return `SELECT id, MIN(ts) AS ts FROM ${db}.dbo.${table} GROUP BY id;`;
66
133
  }
67
134
  /**
68
135
  * Count the rows and the covered time range per datapoint index.
@@ -74,7 +141,8 @@ function getFirstTs(dbName, table) {
74
141
  * @param table the time series table to summarize
75
142
  */
76
143
  function getIdCounts(dbName, table) {
77
- return `SELECT id, COUNT(*) AS cnt, MIN(ts) AS first_ts, MAX(ts) AS last_ts FROM ${dbName}.dbo.${table} GROUP BY id;`;
144
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
145
+ return `SELECT id, COUNT(*) AS cnt, MIN(ts) AS first_ts, MAX(ts) AS last_ts FROM ${db}.dbo.${table} GROUP BY id;`;
78
146
  }
79
147
  /**
80
148
  * Average bytes per row and total bytes of one time series table.
@@ -87,10 +155,12 @@ function getIdCounts(dbName, table) {
87
155
  * @param table the time series table to measure
88
156
  */
89
157
  function getTableSize(dbName, table) {
158
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
90
159
  // Pages are 8 KB; used_page_count covers data and indexes.
91
- return `SELECT CASE WHEN SUM(p.row_count) > 0 THEN SUM(p.used_page_count) * 8192 / SUM(p.row_count) ELSE 0 END AS avg_row_length, SUM(p.used_page_count) * 8192 AS total_bytes FROM ${dbName}.sys.dm_db_partition_stats p WHERE p.object_id = OBJECT_ID('${dbName}.dbo.${table}') AND p.index_id IN (0, 1);`;
160
+ return `SELECT CASE WHEN SUM(p.row_count) > 0 THEN SUM(p.used_page_count) * 8192 / SUM(p.row_count) ELSE 0 END AS avg_row_length, SUM(p.used_page_count) * 8192 AS total_bytes FROM ${db}.sys.dm_db_partition_stats p WHERE p.object_id = OBJECT_ID(${(0, sql_string_1.quoteNString)(`${db}.dbo.${table}`)}) AND p.index_id IN (0, 1);`;
92
161
  }
93
162
  function insert(dbName, index, values) {
163
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
94
164
  const insertValues = {};
95
165
  values.forEach(original => {
96
166
  // work on a copy: the caller keeps `state` as the reference value for "record changes only" (#295),
@@ -102,7 +172,7 @@ function insert(dbName, index, values) {
102
172
  value.state.val = 'NULL';
103
173
  }
104
174
  else if (value.table === 'ts_string') {
105
- value.state.val = (0, sql_string_1.quoteSqlString)(value.state.val);
175
+ value.state.val = (0, sql_string_1.quoteNString)(value.state.val);
106
176
  }
107
177
  else if (value.table === 'ts_bool') {
108
178
  value.state.val = (0, sql_string_1.boolOrNull)(value.state.val, true);
@@ -126,59 +196,66 @@ function insert(dbName, index, values) {
126
196
  for (const table in insertValues) {
127
197
  if (table === 'ts_counter') {
128
198
  while (insertValues[table].length) {
129
- query.push(`INSERT INTO ${dbName}.dbo.ts_counter (id, ts, val) VALUES ${insertValues[table].splice(0, 500).join(',')};`);
199
+ query.push(`INSERT INTO ${db}.dbo.ts_counter (id, ts, val) VALUES ${insertValues[table].splice(0, 500).join(',')};`);
130
200
  }
131
201
  }
132
202
  else {
133
203
  while (insertValues[table].length) {
134
- query.push(`INSERT INTO ${dbName}.dbo.${table} (id, ts, val, ack, _from, q) VALUES ${insertValues[table].splice(0, 500).join(',')};`);
204
+ query.push(`INSERT INTO ${db}.dbo.${table} (id, ts, val, ack, _from, q) VALUES ${insertValues[table].splice(0, 500).join(',')};`);
135
205
  }
136
206
  }
137
207
  }
138
208
  return query;
139
209
  }
140
210
  function retention(dbName, index, table, retention) {
211
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
141
212
  const d = new Date();
142
213
  d.setSeconds(-retention);
143
- let query = `DELETE FROM ${dbName}.dbo.${table} WHERE`;
214
+ let query = `DELETE FROM ${db}.dbo.${table} WHERE`;
144
215
  query += ` id=${index}`;
145
216
  query += ` AND ts < ${d.getTime()}`;
146
217
  query += ';';
147
218
  return query;
148
219
  }
149
220
  function getIdSelect(dbName, name) {
221
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
150
222
  if (!name) {
151
- return `SELECT id, type, name FROM ${dbName}.dbo.datapoints;`;
223
+ return `SELECT id, type, name FROM ${db}.dbo.datapoints;`;
152
224
  }
153
- return `SELECT id, type, name FROM ${dbName}.dbo.datapoints WHERE name=${(0, sql_string_1.quoteSqlString)(name)};`;
225
+ return `SELECT id, type, name FROM ${db}.dbo.datapoints WHERE name=${nameLiteral(dbName, 'datapoints', name)};`;
154
226
  }
155
227
  function getIdInsert(dbName, name, type) {
156
- return `INSERT INTO ${dbName}.dbo.datapoints (name, type) VALUES(${(0, sql_string_1.quoteSqlString)(name)}, ${type});`;
228
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
229
+ return `INSERT INTO ${db}.dbo.datapoints (name, type) VALUES(${nameLiteral(dbName, 'datapoints', name)}, ${type});`;
157
230
  }
158
231
  function getIdUpdate(dbName, id, type) {
159
- return `UPDATE ${dbName}.dbo.datapoints SET type=${type} WHERE id=${id};`;
232
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
233
+ return `UPDATE ${db}.dbo.datapoints SET type=${type} WHERE id=${id};`;
160
234
  }
161
235
  function getFromSelect(dbName, name) {
236
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
162
237
  if (name) {
163
- return `SELECT id, name FROM ${dbName}.dbo.sources WHERE name=${(0, sql_string_1.quoteSqlString)(name)};`;
238
+ return `SELECT id, name FROM ${db}.dbo.sources WHERE name=${nameLiteral(dbName, 'sources', name)};`;
164
239
  }
165
- return `SELECT id, name FROM ${dbName}.dbo.sources;`;
240
+ return `SELECT id, name FROM ${db}.dbo.sources;`;
166
241
  }
167
242
  function getFromInsert(dbName, values) {
168
- return `INSERT INTO ${dbName}.dbo.sources (name) VALUES(${(0, sql_string_1.quoteSqlString)(values)});`;
243
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
244
+ return `INSERT INTO ${db}.dbo.sources (name) VALUES(${nameLiteral(dbName, 'sources', values)});`;
169
245
  }
170
246
  function getCounterDiff(dbName, options) {
247
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
171
248
  // Take first real value after start
172
- const subQueryStart = `SELECT TOP 1 val, ts FROM ${dbName}.dbo.ts_number WHERE ${dbName}.dbo.ts_number.id=${options.index} AND ${dbName}.dbo.ts_number.ts>=${options.start} AND ${dbName}.dbo.ts_number.ts<${options.end} AND ${dbName}.dbo.ts_number.val IS NOT NULL ORDER BY ${dbName}.dbo.ts_number.ts ASC`;
249
+ const subQueryStart = `SELECT TOP 1 val, ts FROM ${db}.dbo.ts_number WHERE ${db}.dbo.ts_number.id=${options.index} AND ${db}.dbo.ts_number.ts>=${options.start} AND ${db}.dbo.ts_number.ts<${options.end} AND ${db}.dbo.ts_number.val IS NOT NULL ORDER BY ${db}.dbo.ts_number.ts ASC`;
173
250
  // Take last real value before the end
174
- const subQueryEnd = `SELECT TOP 1 val, ts FROM ${dbName}.dbo.ts_number WHERE ${dbName}.dbo.ts_number.id=${options.index} AND ${dbName}.dbo.ts_number.ts>=${options.start} AND ${dbName}.dbo.ts_number.ts<${options.end} AND ${dbName}.dbo.ts_number.val IS NOT NULL ORDER BY ${dbName}.dbo.ts_number.ts DESC`;
251
+ const subQueryEnd = `SELECT TOP 1 val, ts FROM ${db}.dbo.ts_number WHERE ${db}.dbo.ts_number.id=${options.index} AND ${db}.dbo.ts_number.ts>=${options.start} AND ${db}.dbo.ts_number.ts<${options.end} AND ${db}.dbo.ts_number.val IS NOT NULL ORDER BY ${db}.dbo.ts_number.ts DESC`;
175
252
  // Take last value before start
176
- const subQueryFirst = `SELECT TOP 1 val, ts FROM ${dbName}.dbo.ts_number WHERE ${dbName}.dbo.ts_number.id=${options.index} AND ${dbName}.dbo.ts_number.ts< ${options.start} ORDER BY ${dbName}.dbo.ts_number.ts DESC`;
253
+ const subQueryFirst = `SELECT TOP 1 val, ts FROM ${db}.dbo.ts_number WHERE ${db}.dbo.ts_number.id=${options.index} AND ${db}.dbo.ts_number.ts< ${options.start} ORDER BY ${db}.dbo.ts_number.ts DESC`;
177
254
  // Take next value after end
178
- const subQueryLast = `SELECT TOP 1 val, ts FROM ${dbName}.dbo.ts_number WHERE ${dbName}.dbo.ts_number.id=${options.index} AND ${dbName}.dbo.ts_number.ts>=${options.end} ORDER BY ${dbName}.dbo.ts_number.ts ASC`;
255
+ const subQueryLast = `SELECT TOP 1 val, ts FROM ${db}.dbo.ts_number WHERE ${db}.dbo.ts_number.id=${options.index} AND ${db}.dbo.ts_number.ts>=${options.end} ORDER BY ${db}.dbo.ts_number.ts ASC`;
179
256
  // get values from counters where counter values changed. No ORDER BY here: T-SQL forbids it in a
180
257
  // union member without TOP, and the outer ORDER BY sorts the combined result anyway.
181
- const subQueryCounterChanges = `SELECT val, ts FROM ${dbName}.dbo.ts_counter WHERE ${dbName}.dbo.ts_counter.id=${options.index} AND ${dbName}.dbo.ts_counter.ts>${options.start} AND ${dbName}.dbo.ts_counter.ts<${options.end} AND ${dbName}.dbo.ts_counter.val IS NOT NULL`;
258
+ const subQueryCounterChanges = `SELECT val, ts FROM ${db}.dbo.ts_counter WHERE ${db}.dbo.ts_counter.id=${options.index} AND ${db}.dbo.ts_counter.ts>${options.start} AND ${db}.dbo.ts_counter.ts<${options.end} AND ${db}.dbo.ts_counter.val IS NOT NULL`;
182
259
  // Same shape as the other dialects: DISTINCT over the union, ordered by ts in the OUTER query -
183
260
  // sendResponseCounter consumes the rows positionally, so the order must be guaranteed here.
184
261
  return (`SELECT DISTINCT a.ts, a.val FROM ((${subQueryFirst})\n` +
@@ -188,25 +265,26 @@ function getCounterDiff(dbName, options) {
188
265
  `UNION ALL (${subQueryCounterChanges})) a ORDER BY a.ts;`);
189
266
  }
190
267
  function getHistory(dbName, table, options) {
268
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
191
269
  let query = 'SELECT * FROM (SELECT ';
192
270
  if ((!options.start && options.count) || (options.aggregate === 'none' && options.count)) {
193
271
  query += ` TOP ${options.count}`;
194
272
  }
195
- query += ` ts, val${options.index === null ? `, ${table}.id as id` : ''}${options.ack ? `, ack` : ''}${options.from ? `, ${dbName}.dbo.sources.name as 'from'` : ''}${options.q ? `, q` : ''} FROM ${dbName}.dbo.${table}`;
273
+ query += ` ts, val${options.index === null ? `, ${table}.id as id` : ''}${options.ack ? `, ack` : ''}${options.from ? `, ${db}.dbo.sources.name as 'from'` : ''}${options.q ? `, q` : ''} FROM ${db}.dbo.${table}`;
196
274
  // LEFT JOIN: a value stored without `from` has `_from` = 0, which has no row in `sources`.
197
275
  // With an INNER JOIN, such values were missing from every query that asked for `from`.
198
276
  if (options.from) {
199
- query += ` LEFT OUTER JOIN ${dbName}.dbo.sources ON ${dbName}.dbo.sources.id=${dbName}.dbo.${table}._from`;
277
+ query += ` LEFT OUTER JOIN ${db}.dbo.sources ON ${db}.dbo.sources.id=${db}.dbo.${table}._from`;
200
278
  }
201
279
  let where = '';
202
280
  if (options.index !== null) {
203
- where += ` ${dbName}.dbo.${table}.id=${options.index}`;
281
+ where += ` ${db}.dbo.${table}.id=${options.index}`;
204
282
  }
205
283
  if (options.end) {
206
- where += `${where ? ` AND` : ''} ${dbName}.dbo.${table}.ts < ${options.end}`;
284
+ where += `${where ? ` AND` : ''} ${db}.dbo.${table}.ts < ${options.end}`;
207
285
  }
208
286
  if (options.start) {
209
- where += `${where ? ` AND` : ''} ${dbName}.dbo.${table}.ts >= ${options.start}`;
287
+ where += `${where ? ` AND` : ''} ${db}.dbo.${table}.ts >= ${options.start}`;
210
288
  }
211
289
  if ((!options.start && options.count) || (options.aggregate === 'none' && options.count)) {
212
290
  where += ` ORDER BY ts`;
@@ -223,40 +301,40 @@ function getHistory(dbName, table, options) {
223
301
  // add last value before start
224
302
  let subQuery;
225
303
  let subWhere;
226
- subQuery = ` SELECT TOP 1 ts, val${options.index === null ? `, ${table}.id as id` : ''}${options.ack ? `, ack` : ''}${options.from ? `, ${dbName}.dbo.sources.name as 'from'` : ''}${options.q ? `, q` : ''} FROM ${dbName}.dbo.${table}`;
304
+ subQuery = ` SELECT TOP 1 ts, val${options.index === null ? `, ${table}.id as id` : ''}${options.ack ? `, ack` : ''}${options.from ? `, ${db}.dbo.sources.name as 'from'` : ''}${options.q ? `, q` : ''} FROM ${db}.dbo.${table}`;
227
305
  if (options.from) {
228
- subQuery += ` LEFT OUTER JOIN ${dbName}.dbo.sources ON ${dbName}.dbo.sources.id=${dbName}.dbo.${table}._from`;
306
+ subQuery += ` LEFT OUTER JOIN ${db}.dbo.sources ON ${db}.dbo.sources.id=${db}.dbo.${table}._from`;
229
307
  }
230
308
  subWhere = '';
231
309
  if (options.index !== null) {
232
- subWhere += ` ${dbName}.dbo.${table}.id=${options.index}`;
310
+ subWhere += ` ${db}.dbo.${table}.id=${options.index}`;
233
311
  }
234
312
  if (options.ignoreNull) {
235
313
  //subWhere += (subWhere ? ` AND` : '') + ` val <> NULL`;
236
314
  }
237
- subWhere += `${subWhere ? ` AND` : ''} ${dbName}.dbo.${table}.ts < ${options.start}`;
315
+ subWhere += `${subWhere ? ` AND` : ''} ${db}.dbo.${table}.ts < ${options.start}`;
238
316
  if (subWhere) {
239
317
  subQuery += ` WHERE ${subWhere}`;
240
318
  }
241
- subQuery += ` ORDER BY ${dbName}.dbo.${table}.ts DESC`;
319
+ subQuery += ` ORDER BY ${db}.dbo.${table}.ts DESC`;
242
320
  where += ` UNION ALL SELECT * FROM (${subQuery}) a`;
243
321
  // add next value after end
244
- subQuery = ` SELECT TOP 1 ts, val${options.index === null ? `, ${table}.id as id` : ''}${options.ack ? `, ack` : ''}${options.from ? `, ${dbName}.dbo.sources.name as 'from'` : ''}${options.q ? `, q` : ''} FROM ${dbName}.dbo.${table}`;
322
+ subQuery = ` SELECT TOP 1 ts, val${options.index === null ? `, ${table}.id as id` : ''}${options.ack ? `, ack` : ''}${options.from ? `, ${db}.dbo.sources.name as 'from'` : ''}${options.q ? `, q` : ''} FROM ${db}.dbo.${table}`;
245
323
  if (options.from) {
246
- subQuery += ` LEFT OUTER JOIN ${dbName}.dbo.sources ON ${dbName}.dbo.sources.id=${dbName}.dbo.${table}._from`;
324
+ subQuery += ` LEFT OUTER JOIN ${db}.dbo.sources ON ${db}.dbo.sources.id=${db}.dbo.${table}._from`;
247
325
  }
248
326
  subWhere = '';
249
327
  if (options.index !== null) {
250
- subWhere += ` ${dbName}.dbo.${table}.id=${options.index}`;
328
+ subWhere += ` ${db}.dbo.${table}.id=${options.index}`;
251
329
  }
252
330
  if (options.ignoreNull) {
253
331
  //subWhere += (subWhere ? ` AND` : '') + ` val <> NULL`;
254
332
  }
255
- subWhere += `${subWhere ? ` AND` : ''} ${dbName}.dbo.${table}.ts >= ${options.end}`;
333
+ subWhere += `${subWhere ? ` AND` : ''} ${db}.dbo.${table}.ts >= ${options.end}`;
256
334
  if (subWhere) {
257
335
  subQuery += ` WHERE ${subWhere}`;
258
336
  }
259
- subQuery += ` ORDER BY ${dbName}.dbo.${table}.ts ASC`;
337
+ subQuery += ` ORDER BY ${db}.dbo.${table}.ts ASC`;
260
338
  where += ` UNION ALL SELECT * FROM (${subQuery}) b`;
261
339
  }
262
340
  if (where) {
@@ -274,13 +352,14 @@ function getHistory(dbName, table, options) {
274
352
  return query;
275
353
  }
276
354
  function deleteFromTable(dbName, table, index, start, end) {
277
- let query = `DELETE FROM ${dbName}.dbo.${table} WHERE`;
355
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
356
+ let query = `DELETE FROM ${db}.dbo.${table} WHERE`;
278
357
  query += ` id=${index}`;
279
358
  if (start && end) {
280
- query += ` AND ${dbName}.dbo.${table}.ts>=${start} AND ${dbName}.dbo.${table}.ts<=${end}`;
359
+ query += ` AND ${db}.dbo.${table}.ts>=${start} AND ${db}.dbo.${table}.ts<=${end}`;
281
360
  }
282
361
  else if (start) {
283
- query += ` AND ${dbName}.dbo.${table}.ts=${start}`;
362
+ query += ` AND ${db}.dbo.${table}.ts=${start}`;
284
363
  }
285
364
  query += ';';
286
365
  return query;
@@ -295,9 +374,11 @@ function deleteFromTable(dbName, table, index, start, end) {
295
374
  * @param index the integer key of the datapoint
296
375
  */
297
376
  function deleteDatapoint(dbName, index) {
298
- return `DELETE FROM ${dbName}.dbo.datapoints WHERE id=${index};`;
377
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
378
+ return `DELETE FROM ${db}.dbo.datapoints WHERE id=${index};`;
299
379
  }
300
380
  function update(dbName, index, originalState, from, table) {
381
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
301
382
  // copy, so the caller's state object is not changed (see insert())
302
383
  const state = { ...originalState };
303
384
  if (!state || state.val === null || state.val === undefined) {
@@ -307,12 +388,12 @@ function update(dbName, index, originalState, from, table) {
307
388
  state.val = (0, sql_string_1.boolOrNull)(state.val, true);
308
389
  }
309
390
  else if (table === 'ts_string') {
310
- state.val = (0, sql_string_1.quoteSqlString)(state.val);
391
+ state.val = (0, sql_string_1.quoteNString)(state.val);
311
392
  }
312
393
  else if (table === 'ts_number' || table === 'ts_counter') {
313
394
  state.val = (0, sql_string_1.numberOrNull)(state.val);
314
395
  }
315
- let query = `UPDATE ${dbName}.dbo.${table} SET `;
396
+ let query = `UPDATE ${db}.dbo.${table} SET `;
316
397
  const vals = [];
317
398
  if (state.val !== undefined) {
318
399
  vals.push(`val=${state.val}`);
@@ -331,23 +412,26 @@ function update(dbName, index, originalState, from, table) {
331
412
  return query;
332
413
  }
333
414
  function rawEntriesWhere(dbName, table, index, options) {
334
- let where = `${dbName}.dbo.${table}.id=${index}`;
415
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
416
+ let where = `${db}.dbo.${table}.id=${index}`;
335
417
  if (options.start) {
336
- where += ` AND ${dbName}.dbo.${table}.ts>=${options.start}`;
418
+ where += ` AND ${db}.dbo.${table}.ts>=${options.start}`;
337
419
  }
338
420
  if (options.end) {
339
- where += ` AND ${dbName}.dbo.${table}.ts<=${options.end}`;
421
+ where += ` AND ${db}.dbo.${table}.ts<=${options.end}`;
340
422
  }
341
423
  return where;
342
424
  }
343
425
  function getRawEntries(dbName, table, index, options) {
344
- return (`SELECT ${dbName}.dbo.${table}.ts, ${dbName}.dbo.${table}.val, ${dbName}.dbo.${table}.ack, ${dbName}.dbo.${table}.q, ${dbName}.dbo.sources.name AS 'from' FROM ${dbName}.dbo.${table}` +
345
- ` LEFT OUTER JOIN ${dbName}.dbo.sources ON ${dbName}.dbo.sources.id=${dbName}.dbo.${table}._from` +
426
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
427
+ return (`SELECT ${db}.dbo.${table}.ts, ${db}.dbo.${table}.val, ${db}.dbo.${table}.ack, ${db}.dbo.${table}.q, ${db}.dbo.sources.name AS 'from' FROM ${db}.dbo.${table}` +
428
+ ` LEFT OUTER JOIN ${db}.dbo.sources ON ${db}.dbo.sources.id=${db}.dbo.${table}._from` +
346
429
  ` WHERE ${rawEntriesWhere(dbName, table, index, options)}` +
347
- ` ORDER BY ${dbName}.dbo.${table}.ts ${options.sort === 'asc' ? 'ASC' : 'DESC'}` +
430
+ ` ORDER BY ${db}.dbo.${table}.ts ${options.sort === 'asc' ? 'ASC' : 'DESC'}` +
348
431
  ` OFFSET ${options.offset} ROWS FETCH NEXT ${options.limit} ROWS ONLY;`);
349
432
  }
350
433
  function getRawEntriesCount(dbName, table, index, options) {
351
- return `SELECT COUNT(*) AS total FROM ${dbName}.dbo.${table} WHERE ${rawEntriesWhere(dbName, table, index, options)};`;
434
+ const db = (0, sql_string_1.quoteMsIdentifier)(dbName);
435
+ return `SELECT COUNT(*) AS total FROM ${db}.dbo.${table} WHERE ${rawEntriesWhere(dbName, table, index, options)};`;
352
436
  }
353
437
  //# sourceMappingURL=mssql.js.map