@aaqu/fromcubes-db 0.0.0-stage → 0.1.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.
Files changed (54) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +24 -0
  3. package/README.md +442 -2
  4. package/SECURITY.md +75 -0
  5. package/THIRD-PARTY-NOTICES.md +151 -0
  6. package/examples/Quick Start/All Databases.json +1719 -0
  7. package/examples/Quick Start/ClickHouse.json +278 -0
  8. package/examples/Quick Start/CockroachDB.json +280 -0
  9. package/examples/Quick Start/Firebird.json +278 -0
  10. package/examples/Quick Start/MariaDB.json +281 -0
  11. package/examples/Quick Start/MySQL.json +281 -0
  12. package/examples/Quick Start/Oracle.json +280 -0
  13. package/examples/Quick Start/PostgreSQL.json +280 -0
  14. package/examples/Quick Start/SQL Server.json +282 -0
  15. package/examples/Quick Start/SQLite.json +278 -0
  16. package/examples/Quick Start/TiDB.json +281 -0
  17. package/examples/Quick Start/YugabyteDB.json +280 -0
  18. package/examples/SQLite Sensor Log With Portal.json +391 -0
  19. package/examples/Select With Parameters.json +130 -0
  20. package/index.js +32 -0
  21. package/lib/adapters/clickhouse.js +254 -0
  22. package/lib/adapters/firebird.js +416 -0
  23. package/lib/adapters/index.js +37 -0
  24. package/lib/adapters/mssql.js +178 -0
  25. package/lib/adapters/mysql.js +171 -0
  26. package/lib/adapters/oracle.js +272 -0
  27. package/lib/adapters/postgres.js +161 -0
  28. package/lib/adapters/read.js +57 -0
  29. package/lib/adapters/sqlite.js +193 -0
  30. package/lib/adapters/time.js +89 -0
  31. package/lib/bound.js +29 -0
  32. package/lib/editor-api.js +134 -0
  33. package/lib/editor-preview.js +191 -0
  34. package/lib/errors.js +66 -0
  35. package/lib/params.js +966 -0
  36. package/lib/pool.js +391 -0
  37. package/lib/settings.js +302 -0
  38. package/lib/sql/compile.js +160 -0
  39. package/lib/sql/dialect.js +194 -0
  40. package/lib/sql/parse.js +202 -0
  41. package/lib/sql/types.js +1071 -0
  42. package/lib/sqlite-files.js +137 -0
  43. package/nodes/connection.html +728 -0
  44. package/nodes/connection.js +179 -0
  45. package/nodes/editor/ark-pixel.LICENSE.txt +96 -0
  46. package/nodes/editor/ark-pixel.woff2 +0 -0
  47. package/nodes/editor/mark.svg +5 -0
  48. package/nodes/editor/sql-editor.css +604 -0
  49. package/nodes/editor/sql-editor.js +1490 -0
  50. package/nodes/editor/sql-model.js +203 -0
  51. package/nodes/icons/fromcubes-db.svg +24 -0
  52. package/nodes/query.html +662 -0
  53. package/nodes/query.js +195 -0
  54. package/package.json +81 -4
@@ -0,0 +1,416 @@
1
+ "use strict";
2
+
3
+ const {
4
+ ConnectionError,
5
+ QueryError,
6
+ TimeoutError,
7
+ UniqueViolationError,
8
+ ForeignKeyViolationError,
9
+ NotNullViolationError,
10
+ CheckViolationError,
11
+ } = require("../errors");
12
+
13
+ const { Bound } = require("../bound");
14
+ const { exactNumber } = require("./read");
15
+
16
+ const DIALECT = "firebird";
17
+
18
+ // Firebird status vector codes (gds codes), as node-firebird reports them on
19
+ // `err.gdscode`. https://www.firebirdsql.org/file/documentation/html/en/refdocs/fblangref50/firebird-50-language-reference.html#fblangref50-appx02-sqlcodes
20
+ const GDS = {
21
+ 335544665: UniqueViolationError, // unique_key_violation (PRIMARY KEY / UNIQUE constraint)
22
+ 335544349: UniqueViolationError, // no_dup (unique index)
23
+ 335544466: ForeignKeyViolationError, // foreign_key
24
+ 335544838: ForeignKeyViolationError, // foreign_key_target_doesnt_exist
25
+ 335544839: ForeignKeyViolationError, // foreign_key_references_present
26
+ 335544347: NotNullViolationError, // not_valid — "validation error for column …, value "*** null ***""
27
+ 335544558: CheckViolationError, // check_constraint
28
+ 335545294: TimeoutError, // cfg_stmt_timeout
29
+ 335545295: TimeoutError, // att_stmt_timeout
30
+ 335545296: TimeoutError, // req_stmt_timeout
31
+ };
32
+
33
+ const CONNECTION_GDS = new Set([
34
+ 335544721, // network_error
35
+ 335544472, // login
36
+ 335544344, // io_error (database file cannot be opened)
37
+ 335544375, // unavailable
38
+ 335544648, // conn_lost
39
+ 335544741, // lost_db_connection
40
+ 335544856, // att_shutdown
41
+ ]);
42
+
43
+ const CONNECTION_CODES = new Set(["ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "EHOSTUNREACH", "ECONNRESET", "EPIPE"]);
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Dates as UTC, on this package's connections only.
47
+ //
48
+ // node-firebird reads DATE and TIMESTAMP into the process's local time, and
49
+ // writes every date, time and timestamp parameter the same way: through a JS
50
+ // Date (milliseconds only, local wall clock, the zone dropped), sent as a
51
+ // plain TIMESTAMP. Firebird keeps a fourth fractional digit and a zone. So:
52
+ //
53
+ // - reading: DATE and TIMESTAMP decode as UTC;
54
+ // - writing: once the statement is prepared, the driver knows each
55
+ // parameter's type; a value for a date/time parameter is encoded here,
56
+ // exactly, as that type (blr_sql_date, blr_sql_time, blr_timestamp and
57
+ // their WITH TIME ZONE forms, zone as a displacement or UTC).
58
+ //
59
+ // Both act only for connections whose options carry `fromcubesUtc`; every
60
+ // other node-firebird user in the process gets the driver's own behaviour.
61
+ // ---------------------------------------------------------------------------
62
+ const DAYS_1858_TO_1970 = 40587; // Firebird counts days from 1858-11-17
63
+ const MS_PER_DAY = 86400000;
64
+ const TICKS_PER_DAY = MS_PER_DAY * 10; // 1/10000 s
65
+ const UTC_ZONE = 65535; // Firebird's id for the UTC region
66
+ const ONE_DAY_MINUTES = 1439; // displacement zone id = 1439 + offset in minutes
67
+ const WIRE = Symbol("fromcubes-db firebird wire value");
68
+
69
+ const T = {
70
+ TIMESTAMP: 510,
71
+ TIME: 560,
72
+ DATE: 570,
73
+ TIMESTAMP_TZ: 32754,
74
+ TIMESTAMP_TZ_EX: 32748,
75
+ TIME_TZ: 32756,
76
+ TIME_TZ_EX: 32750,
77
+ };
78
+ const BLR = { date: 12, time: 13, timestamp: 35, time_tz: 28, timestamp_tz: 29 };
79
+
80
+ const OFFSET_RE = /\s*(?:(Z|UTC)|([+-])(\d{2}):?(\d{2}))$/i;
81
+ const TIME_RE = /^(\d{1,2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?$/;
82
+ const STAMP_RE = /^([+-]?\d{4,6})-(\d{2})-(\d{2})(?:[T\s]+(\d{1,2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?$/;
83
+
84
+ /** Splits a trailing zone off a text value: `{ body, zone }`, zone null when none was written. */
85
+ function splitZone(text) {
86
+ const m = OFFSET_RE.exec(text);
87
+ if (!m || !/\d/.test(text.slice(0, m.index))) return { body: text, zone: null };
88
+ const body = text.slice(0, m.index).trim();
89
+ if (m[1]) return { body, zone: { id: UTC_ZONE, minutes: 0 } };
90
+ const minutes = (m[2] === "-" ? -1 : 1) * (Number(m[3]) * 60 + Number(m[4]));
91
+ return { body, zone: { id: ONE_DAY_MINUTES + minutes, minutes } };
92
+ }
93
+
94
+ const ticksOf = (h, mi, s, frac) =>
95
+ ((Number(h) * 60 + Number(mi)) * 60 + Number(s || 0)) * 10000 + Number((frac || "").padEnd(4, "0").slice(0, 4));
96
+
97
+ /**
98
+ * A text or Date value as `{ days, ticks, zone }` in UTC, or null when it is
99
+ * not one. Naive text is UTC, as on every product; an offset is honoured and
100
+ * kept as the zone.
101
+ */
102
+ function wireParts(value) {
103
+ if (value instanceof Date) {
104
+ const ms = value.getTime();
105
+ if (Number.isNaN(ms)) return null;
106
+ const day = Math.floor(ms / MS_PER_DAY);
107
+ return { days: day + DAYS_1858_TO_1970, ticks: (ms - day * MS_PER_DAY) * 10, zone: null, hasDate: true };
108
+ }
109
+ if (typeof value !== "string") return null;
110
+ const { body, zone } = splitZone(value.trim());
111
+ const time = TIME_RE.exec(body);
112
+ if (time) {
113
+ const [, h, mi, s, frac] = time;
114
+ if (Number(h) > 23 || Number(mi) > 59 || Number(s || 0) > 59) return null;
115
+ let ticks = ticksOf(h, mi, s, frac) - (zone ? zone.minutes * 600000 : 0);
116
+ ticks = ((ticks % TICKS_PER_DAY) + TICKS_PER_DAY) % TICKS_PER_DAY;
117
+ return { days: null, ticks, zone, hasDate: false };
118
+ }
119
+ const stamp = STAMP_RE.exec(body);
120
+ if (!stamp) return null;
121
+ const [, y, mo, d, h = "0", mi = "0", s = "0", frac = ""] = stamp;
122
+ const probe = new Date(Date.UTC(2000, Number(mo) - 1, Number(d)));
123
+ probe.setUTCFullYear(Number(y));
124
+ if (probe.getUTCMonth() !== Number(mo) - 1 || probe.getUTCDate() !== Number(d)) return null;
125
+ let days = Math.round(probe.getTime() / MS_PER_DAY) + DAYS_1858_TO_1970;
126
+ let ticks = ticksOf(h, mi, s, frac) - (zone ? zone.minutes * 600000 : 0);
127
+ if (ticks < 0) {
128
+ ticks += TICKS_PER_DAY;
129
+ days -= 1;
130
+ } else if (ticks >= TICKS_PER_DAY) {
131
+ ticks -= TICKS_PER_DAY;
132
+ days += 1;
133
+ }
134
+ return { days, ticks, zone, hasDate: true };
135
+ }
136
+
137
+ /** The exact wire value for a parameter of Firebird type `type`, or null to leave it to the driver. */
138
+ function wireValueFor(type, value) {
139
+ const parts = wireParts(value);
140
+ if (!parts) return null;
141
+ const zone = parts.zone ? parts.zone.id : UTC_ZONE;
142
+ let wire;
143
+ switch (type) {
144
+ case T.DATE:
145
+ if (!parts.hasDate) return null;
146
+ wire = { blr: "date", days: parts.days };
147
+ break;
148
+ case T.TIME:
149
+ wire = { blr: "time", ticks: parts.ticks };
150
+ break;
151
+ case T.TIME_TZ:
152
+ case T.TIME_TZ_EX:
153
+ wire = { blr: "time_tz", ticks: parts.ticks, zone };
154
+ break;
155
+ case T.TIMESTAMP:
156
+ if (!parts.hasDate) return null;
157
+ wire = { blr: "timestamp", days: parts.days, ticks: parts.ticks };
158
+ break;
159
+ case T.TIMESTAMP_TZ:
160
+ case T.TIMESTAMP_TZ_EX:
161
+ if (!parts.hasDate) return null;
162
+ wire = { blr: "timestamp_tz", days: parts.days, ticks: parts.ticks, zone };
163
+ break;
164
+ default:
165
+ return null;
166
+ }
167
+ // A Date, because that is what the driver hands to its date encoder as is.
168
+ const carrier = new Date(0);
169
+ carrier[WIRE] = wire;
170
+ return carrier;
171
+ }
172
+
173
+ const pad2 = (n) => String(n).padStart(2, "0");
174
+
175
+ /** `HH:MM:SS.ffff` from 1/10000 s since midnight. */
176
+ function timeText(ticks) {
177
+ const seconds = Math.floor(ticks / 10000);
178
+ const frac = String(ticks % 10000).padStart(4, "0");
179
+ return `${pad2(Math.floor(seconds / 3600))}:${pad2(Math.floor(seconds / 60) % 60)}:${pad2(seconds % 60)}.${frac}`;
180
+ }
181
+
182
+ let driverPatched = false;
183
+
184
+ function patchDriver() {
185
+ if (driverPatched) return;
186
+ const xsqlvar = require("node-firebird/lib/wire/xsqlvar");
187
+ const Connection = require("node-firebird/lib/wire/connection");
188
+ const date = xsqlvar.SQLVarDate && xsqlvar.SQLVarDate.prototype;
189
+ const stamp = xsqlvar.SQLVarTimeStamp && xsqlvar.SQLVarTimeStamp.prototype;
190
+ const param = xsqlvar.SQLParamDate && xsqlvar.SQLParamDate.prototype;
191
+ const conn = Connection && Connection.prototype;
192
+ if (
193
+ ![date, stamp, param, conn].every(Boolean) ||
194
+ typeof date.decode !== "function" ||
195
+ typeof stamp.decode !== "function" ||
196
+ typeof param.encode !== "function" ||
197
+ typeof param.calcBlr !== "function" ||
198
+ typeof conn.executeStatement !== "function"
199
+ ) {
200
+ throw new Error("node-firebird changed its internals; fromcubes-db cannot exchange dates as UTC");
201
+ }
202
+
203
+ const ownDate = date.decode;
204
+ date.decode = function (data, lowerV13, options) {
205
+ if (!options || !options.fromcubesUtc) return ownDate.call(this, data, lowerV13, options);
206
+ const days = data.readInt();
207
+ if (!lowerV13 || !data.readInt()) return new Date((days - DAYS_1858_TO_1970) * MS_PER_DAY);
208
+ return null;
209
+ };
210
+ const ownStamp = stamp.decode;
211
+ stamp.decode = function (data, lowerV13, options) {
212
+ if (!options || !options.fromcubesUtc) return ownStamp.call(this, data, lowerV13, options);
213
+ const days = data.readInt();
214
+ const ticks = data.readUInt();
215
+ if (!lowerV13 || !data.readInt()) {
216
+ return new Date((days - DAYS_1858_TO_1970) * MS_PER_DAY + Math.floor(ticks / 10));
217
+ }
218
+ return null;
219
+ };
220
+
221
+ // TIME is a time of day, not a point in time: text, as PostgreSQL gives it,
222
+ // rather than the driver's Date on 1 January 1970 in the local zone. WITH
223
+ // TIME ZONE keeps its zone as an offset (UTC and named regions as +00:00 —
224
+ // the same instant; the adapter carries no region table).
225
+ const time = xsqlvar.SQLVarTime && xsqlvar.SQLVarTime.prototype;
226
+ const timeTz = xsqlvar.SQLVarTimeTz && xsqlvar.SQLVarTimeTz.prototype;
227
+ if (time && typeof time.decode === "function") {
228
+ const ownTime = time.decode;
229
+ time.decode = function (data, lowerV13, options) {
230
+ if (!options || !options.fromcubesUtc) return ownTime.call(this, data, lowerV13, options);
231
+ const ticks = data.readUInt();
232
+ if (!lowerV13 || !data.readInt()) return timeText(ticks);
233
+ return null;
234
+ };
235
+ }
236
+ if (timeTz && typeof timeTz.decode === "function") {
237
+ const ownTimeTz = timeTz.decode;
238
+ timeTz.decode = function (data, lowerV13, options) {
239
+ if (!options || !options.fromcubesUtc) return ownTimeTz.call(this, data, lowerV13, options);
240
+ const ticks = data.readUInt();
241
+ const zone = data.readInt();
242
+ if (!lowerV13 || !data.readInt()) {
243
+ const minutes = zone >= 0 && zone <= 2 * ONE_DAY_MINUTES ? zone - ONE_DAY_MINUTES : 0;
244
+ const local = (((ticks + minutes * 600000) % TICKS_PER_DAY) + TICKS_PER_DAY) % TICKS_PER_DAY;
245
+ const sign = minutes < 0 ? "-" : "+";
246
+ const abs = Math.abs(minutes);
247
+ return `${timeText(local)}${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;
248
+ }
249
+ return null;
250
+ };
251
+ }
252
+
253
+ // Only a carrier made by wireValueFor has WIRE; any other Date is the driver's.
254
+ const ownEncode = param.encode;
255
+ param.encode = function (data) {
256
+ const wire = this.value && this.value[WIRE];
257
+ if (!wire) return ownEncode.call(this, data);
258
+ if (wire.days !== undefined) data.addInt(wire.days);
259
+ if (wire.ticks !== undefined) data.addUInt(wire.ticks);
260
+ if (wire.zone !== undefined) data.addInt(wire.zone);
261
+ };
262
+ const ownBlr = param.calcBlr;
263
+ param.calcBlr = function (blr) {
264
+ const wire = this.value && this.value[WIRE];
265
+ if (!wire) return ownBlr.call(this, blr);
266
+ blr.addByte(BLR[wire.blr]);
267
+ };
268
+
269
+ const ownExecute = conn.executeStatement;
270
+ conn.executeStatement = function (transaction, statement, params, callback, custom) {
271
+ if (this.options && this.options.fromcubesUtc && Array.isArray(params) && statement && statement.input) {
272
+ params = params.map((value, i) => {
273
+ const meta = statement.input[i];
274
+ return (meta && wireValueFor(meta.type, value)) || value;
275
+ });
276
+ }
277
+ return ownExecute.call(this, transaction, statement, params, callback, custom);
278
+ };
279
+
280
+ driverPatched = true;
281
+ }
282
+
283
+ /**
284
+ * The value node-firebird should get. Dates and times stay as they came —
285
+ * text or Date — and are encoded once the parameter's type is known (above).
286
+ * JSON is text: Firebird has no JSON type, it lives in a text BLOB or VARCHAR.
287
+ */
288
+ function toFirebird(value) {
289
+ if (value instanceof Bound) {
290
+ const v = value.value;
291
+ if (v === null || v === undefined) return v;
292
+ if (value.spec.category === "json") return JSON.stringify(v);
293
+ return toFirebird(v);
294
+ }
295
+ if (typeof value === "bigint") return value.toString();
296
+ return value;
297
+ }
298
+
299
+ async function createPool(config) {
300
+ patchDriver();
301
+ const Firebird = require("node-firebird");
302
+
303
+ const options = {
304
+ host: config.host,
305
+ port: config.port,
306
+ database: config.database,
307
+ user: config.user,
308
+ password: config.password,
309
+ role: config.role || undefined,
310
+ encoding: "UTF8",
311
+ lowercase_keys: false,
312
+ // Exact numbers as text — the default decodes BIGINT, NUMERIC and DECIMAL
313
+ // through a double; exactNumber turns the text back into a number when the
314
+ // double would be that number.
315
+ numericMode: "string",
316
+ // Text BLOBs as strings rather than an asynchronous fetch function nobody
317
+ // downstream can call.
318
+ blobAsText: true,
319
+ retryConnectionInterval: 1000,
320
+ pageSize: 4096,
321
+ fromcubesUtc: true,
322
+ ...config.options,
323
+ };
324
+
325
+ const pool = Firebird.pool(Math.max(1, config.poolMax || 1), options);
326
+ pool.__fcOptions = options;
327
+
328
+ // Fail now on a wrong host or password, as the other adapters do.
329
+ const probe = await getConnection(pool);
330
+ probe.detach();
331
+ return pool;
332
+ }
333
+
334
+ function getConnection(pool) {
335
+ return new Promise((resolve, reject) => {
336
+ pool.get((err, db) => (err ? reject(err) : resolve(db)));
337
+ });
338
+ }
339
+
340
+ /** Every session runs in UTC, so CURRENT_TIMESTAMP and WITH TIME ZONE casts agree with the values sent. */
341
+ async function utcSession(db) {
342
+ if (db.__fcUtc) return;
343
+ try {
344
+ await db.queryAsync("SET TIME ZONE 'UTC'", []);
345
+ } catch {
346
+ // Firebird 3 has no time zones; there is nothing to set.
347
+ }
348
+ db.__fcUtc = true;
349
+ }
350
+
351
+ /** A binary BLOB arrives as a fetch function; this reads it into a Buffer. */
352
+ function readBlob(fetch) {
353
+ return new Promise((resolve, reject) => {
354
+ fetch((err, _name, stream) => {
355
+ if (err) return reject(err);
356
+ const chunks = [];
357
+ stream.on("data", (chunk) => chunks.push(chunk));
358
+ stream.on("end", () => resolve(Buffer.concat(chunks)));
359
+ stream.on("error", reject);
360
+ });
361
+ });
362
+ }
363
+
364
+ async function fromFirebirdRow(row, fields) {
365
+ const out = {};
366
+ for (const [key, value] of Object.entries(row)) {
367
+ const field = fields && fields.find((f) => (f.alias || f.field) === key);
368
+ if (typeof value === "function") out[key] = await readBlob(value);
369
+ else if (typeof value === "string" && field && /^(INT64|INT128|LONG|SHORT)$/.test(field.typeName || "")) {
370
+ out[key] = exactNumber(value);
371
+ } else out[key] = value;
372
+ }
373
+ return out;
374
+ }
375
+
376
+ async function execute(pool, compiled) {
377
+ const db = await getConnection(pool);
378
+ try {
379
+ await utcSession(db);
380
+ const result = await db.queryAsync(compiled.text, compiled.values.map(toFirebird), { withMeta: true });
381
+ const rows = Array.isArray(result.rows) ? result.rows : result.rows ? [result.rows] : [];
382
+ const out = [];
383
+ for (const row of rows) out.push(await fromFirebirdRow(row, result.fields));
384
+ const isSelect = out.length > 0 || (result.fields && result.fields.length > 0);
385
+ return {
386
+ rows: out,
387
+ rowCount: isSelect ? out.length : typeof result.affectedRows === "number" ? result.affectedRows : 0,
388
+ };
389
+ } finally {
390
+ db.detach();
391
+ }
392
+ }
393
+
394
+ async function closePool(pool) {
395
+ await new Promise((resolve) => {
396
+ try {
397
+ pool.destroy(() => resolve());
398
+ } catch {
399
+ resolve();
400
+ }
401
+ });
402
+ }
403
+
404
+ function translateError(err) {
405
+ if (!err || typeof err !== "object") {
406
+ return new QueryError(String(err), { dialect: DIALECT });
407
+ }
408
+ const code = err.gdscode;
409
+ const options = { dialect: DIALECT, driverCode: code ?? err.code, cause: err };
410
+ const Specific = GDS[code];
411
+ if (Specific) return new Specific(err.message, options);
412
+ if (CONNECTION_GDS.has(code) || CONNECTION_CODES.has(err.code)) return new ConnectionError(err.message, options);
413
+ return new QueryError(err.message, options);
414
+ }
415
+
416
+ module.exports = { dialect: DIALECT, createPool, execute, closePool, translateError, toFirebird, wireValueFor, WIRE };
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+
3
+ const { ParameterError } = require("../errors");
4
+ const { byDatabase, PRODUCT_IDS } = require("../sql/dialect");
5
+
6
+ // Required lazily: loading four database drivers when a flow uses one of them
7
+ // wastes memory and startup time in a Node-RED process.
8
+ //
9
+ // Keyed by engine. A product that needs its own driver — say MariaDB moving off
10
+ // mysql2 — gets an entry under its own id here and byDatabase prefers it.
11
+ const LOADERS = {
12
+ postgres: () => require("./postgres"),
13
+ mysql: () => require("./mysql"),
14
+ mssql: () => require("./mssql"),
15
+ oracle: () => require("./oracle"),
16
+ sqlite: () => require("./sqlite"),
17
+ firebird: () => require("./firebird"),
18
+ clickhouse: () => require("./clickhouse"),
19
+ };
20
+
21
+ const cache = new Map();
22
+
23
+ function adapterFor(dialect) {
24
+ const cached = cache.get(dialect);
25
+ if (cached) return cached;
26
+
27
+ const load = byDatabase(LOADERS, dialect);
28
+ if (!load) {
29
+ throw new ParameterError(`Unknown dialect "${dialect}". Expected one of: ${PRODUCT_IDS.join(", ")}`);
30
+ }
31
+
32
+ const adapter = load();
33
+ cache.set(dialect, adapter);
34
+ return adapter;
35
+ }
36
+
37
+ module.exports = { adapterFor };
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+
3
+ const {
4
+ ConnectionError,
5
+ QueryError,
6
+ TimeoutError,
7
+ UniqueViolationError,
8
+ ForeignKeyViolationError,
9
+ NotNullViolationError,
10
+ CheckViolationError,
11
+ } = require("../errors");
12
+
13
+ const { Bound } = require("../bound");
14
+ const { utcWallClock, hasOffset } = require("./time");
15
+ const { exactNumber } = require("./read");
16
+
17
+ const DIALECT = "mssql";
18
+
19
+ const ERROR_NUMBERS = {
20
+ 2601: UniqueViolationError, // duplicate key in unique index
21
+ 2627: UniqueViolationError, // unique constraint
22
+ 547: ForeignKeyViolationError, // also raised for CHECK, refined below
23
+ 515: NotNullViolationError,
24
+ 1205: QueryError, // deadlock victim
25
+ };
26
+
27
+ const CONNECTION_CODES = new Set(["ELOGIN", "ESOCKET", "ECONNCLOSED", "ENOTOPEN", "ENOCONN", "EINSTLOOKUP"]);
28
+
29
+ async function createPool(config) {
30
+ const sql = require("mssql");
31
+
32
+ const pool = new sql.ConnectionPool({
33
+ server: config.host,
34
+ port: config.port,
35
+ database: config.database,
36
+ user: config.user,
37
+ password: config.password,
38
+ connectionTimeout: config.connectTimeoutMs,
39
+ requestTimeout: config.queryTimeoutMs,
40
+ pool: {
41
+ max: config.poolMax,
42
+ min: config.poolMin,
43
+ idleTimeoutMillis: config.idleTimeoutMs,
44
+ acquireTimeoutMillis: config.connectTimeoutMs,
45
+ },
46
+ options: {
47
+ // Azure and SQL Server 2022 default to encrypted connections; the
48
+ // self-signed certificate case has to be opted into explicitly.
49
+ encrypt: true,
50
+ trustServerCertificate: false,
51
+ ...(config.options && config.options.options),
52
+ },
53
+ ...stripOptions(config.options),
54
+ });
55
+
56
+ const onError = (err) => config.onPoolError(translateError(err));
57
+ pool.on("error", onError);
58
+ pool.__onError = onError;
59
+
60
+ await pool.connect();
61
+ return pool;
62
+ }
63
+
64
+ /**
65
+ * The type and value to hand `request.input()`. Left to itself, mssql infers
66
+ * the type from the JS value, and the inference is wrong in ways that corrupt
67
+ * data rather than fail: every Date becomes the legacy DATETIME (1753 onwards,
68
+ * 1/300 s — so datetime2 receives .1233333 for .123), an object is refused,
69
+ * and a NULL is an nvarchar NULL that a varbinary column will not take.
70
+ *
71
+ * A declared column type decides instead. Text the server converts itself —
72
+ * an exact decimal, a time of day, a timestamp with more digits than a Date —
73
+ * goes as nvarchar, which SQL Server converts without loss.
74
+ *
75
+ * @returns {[unknown, unknown] | [unknown]} `[type, value]`, or `[value]` to let mssql infer
76
+ */
77
+ function mssqlInput(sql, value) {
78
+ if (!(value instanceof Bound)) {
79
+ if (value instanceof Date) return [sql.DateTime2(7), value];
80
+ if (typeof value === "bigint") return [sql.NVarChar(40), String(value)];
81
+ if (value !== null && typeof value === "object" && !Buffer.isBuffer(value)) {
82
+ return [sql.NVarChar(sql.MAX), JSON.stringify(value)];
83
+ }
84
+ return [value];
85
+ }
86
+
87
+ const v = value.value;
88
+ const { category } = value.spec;
89
+ const isNull = v === null || v === undefined;
90
+
91
+ if (category === "json" || category === "vector") return [sql.NVarChar(sql.MAX), isNull ? null : JSON.stringify(v)];
92
+ if (category === "binary" || value.type === "rowversion") return [sql.VarBinary(sql.MAX), isNull ? null : v];
93
+ if (category === "boolean") return [sql.Bit, isNull ? null : v];
94
+ if (category === "date") {
95
+ // As text, converted by the server into the column's own type. tedious's
96
+ // typed dates validate against their own idea of the range (9999-12-31
97
+ // 23:59:59.999 is "out of range" for date) and shift by the local zone.
98
+ if (isNull) return [sql.NVarChar(64), null];
99
+ // datetimeoffset keeps the offset it was given; everything else is the UTC
100
+ // wall clock, in the ISO 8601 form SQL Server reads regardless of
101
+ // DATEFORMAT or language.
102
+ if (value.type === "datetimeoffset") {
103
+ return [sql.NVarChar(64), hasOffset(v) ? v : `${utcWallClock(v, { separator: "T" })}Z`];
104
+ }
105
+ const wall = utcWallClock(v, { separator: "T" });
106
+ return [sql.NVarChar(64), value.type === "date" ? wall.slice(0, wall.indexOf("T")) : wall];
107
+ }
108
+ if (category === "integer" && !isNull) {
109
+ if (typeof v === "bigint") return [sql.NVarChar(40), String(v)];
110
+ const INT_TYPES = { tinyint: sql.TinyInt, smallint: sql.SmallInt, int: sql.Int, bigint: sql.BigInt };
111
+ return [INT_TYPES[value.type] || sql.BigInt, v];
112
+ }
113
+ // nvarchar(max) is refused where a value must fit in a row (sql_variant).
114
+ if (typeof v === "string") return [sql.NVarChar(v.length <= 4000 ? 4000 : sql.MAX), v];
115
+ if (typeof v === "bigint") return [sql.NVarChar(40), String(v)];
116
+ if (isNull) return [sql.NVarChar(sql.MAX), null];
117
+ return [v];
118
+ }
119
+
120
+ async function execute(pool, compiled) {
121
+ const sql = require("mssql");
122
+ const request = pool.request();
123
+ // Every value goes through request.input(), never into the statement text.
124
+ for (const [key, value] of Object.entries(compiled.values)) {
125
+ request.input(key, ...mssqlInput(sql, value));
126
+ }
127
+
128
+ const result = await request.query(compiled.text);
129
+ const rows = result.recordset || [];
130
+ // tedious hands every BIGINT over as text, even 42. Read it the way every
131
+ // other product does: a number when that is exactly the value, else text.
132
+ const bigints = Object.values((result.recordset && result.recordset.columns) || {})
133
+ .filter((column) => column.type === sql.BigInt)
134
+ .map((column) => column.name);
135
+ if (bigints.length) {
136
+ for (const row of rows) for (const name of bigints) row[name] = exactNumber(row[name]);
137
+ }
138
+ const affected = Array.isArray(result.rowsAffected) ? result.rowsAffected.reduce((a, b) => a + b, 0) : 0;
139
+
140
+ return { rows, rowCount: rows.length > 0 ? rows.length : affected };
141
+ }
142
+
143
+ async function closePool(pool) {
144
+ if (pool.__onError) pool.removeListener("error", pool.__onError);
145
+ await pool.close();
146
+ }
147
+
148
+ function translateError(err) {
149
+ if (!err || typeof err !== "object") {
150
+ return new QueryError(String(err), { dialect: DIALECT });
151
+ }
152
+ const number = err.number ?? (err.originalError && err.originalError.number);
153
+ const options = { dialect: DIALECT, driverCode: number ?? err.code, cause: err };
154
+ const message = err.message || String(err);
155
+
156
+ if (err.code === "ETIMEOUT" || err.code === "ETIMEDOUT") {
157
+ return new TimeoutError(message, options);
158
+ }
159
+ if (number === 547) {
160
+ return /CHECK constraint/i.test(message)
161
+ ? new CheckViolationError(message, options)
162
+ : new ForeignKeyViolationError(message, options);
163
+ }
164
+ const Specific = ERROR_NUMBERS[number];
165
+ if (Specific) return new Specific(message, options);
166
+ if (CONNECTION_CODES.has(err.code)) return new ConnectionError(message, options);
167
+ return new QueryError(message, options);
168
+ }
169
+
170
+ /** `options` is a reserved mssql config key; the nested part is merged separately. */
171
+ function stripOptions(extra) {
172
+ if (!extra) return {};
173
+ const copy = { ...extra };
174
+ delete copy.options;
175
+ return copy;
176
+ }
177
+
178
+ module.exports = { dialect: DIALECT, createPool, execute, closePool, translateError, mssqlInput };