@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.
- package/LICENSE +201 -0
- package/NOTICE +24 -0
- package/README.md +442 -2
- package/SECURITY.md +75 -0
- package/THIRD-PARTY-NOTICES.md +151 -0
- package/examples/Quick Start/All Databases.json +1719 -0
- package/examples/Quick Start/ClickHouse.json +278 -0
- package/examples/Quick Start/CockroachDB.json +280 -0
- package/examples/Quick Start/Firebird.json +278 -0
- package/examples/Quick Start/MariaDB.json +281 -0
- package/examples/Quick Start/MySQL.json +281 -0
- package/examples/Quick Start/Oracle.json +280 -0
- package/examples/Quick Start/PostgreSQL.json +280 -0
- package/examples/Quick Start/SQL Server.json +282 -0
- package/examples/Quick Start/SQLite.json +278 -0
- package/examples/Quick Start/TiDB.json +281 -0
- package/examples/Quick Start/YugabyteDB.json +280 -0
- package/examples/SQLite Sensor Log With Portal.json +391 -0
- package/examples/Select With Parameters.json +130 -0
- package/index.js +32 -0
- package/lib/adapters/clickhouse.js +254 -0
- package/lib/adapters/firebird.js +416 -0
- package/lib/adapters/index.js +37 -0
- package/lib/adapters/mssql.js +178 -0
- package/lib/adapters/mysql.js +171 -0
- package/lib/adapters/oracle.js +272 -0
- package/lib/adapters/postgres.js +161 -0
- package/lib/adapters/read.js +57 -0
- package/lib/adapters/sqlite.js +193 -0
- package/lib/adapters/time.js +89 -0
- package/lib/bound.js +29 -0
- package/lib/editor-api.js +134 -0
- package/lib/editor-preview.js +191 -0
- package/lib/errors.js +66 -0
- package/lib/params.js +966 -0
- package/lib/pool.js +391 -0
- package/lib/settings.js +302 -0
- package/lib/sql/compile.js +160 -0
- package/lib/sql/dialect.js +194 -0
- package/lib/sql/parse.js +202 -0
- package/lib/sql/types.js +1071 -0
- package/lib/sqlite-files.js +137 -0
- package/nodes/connection.html +728 -0
- package/nodes/connection.js +179 -0
- package/nodes/editor/ark-pixel.LICENSE.txt +96 -0
- package/nodes/editor/ark-pixel.woff2 +0 -0
- package/nodes/editor/mark.svg +5 -0
- package/nodes/editor/sql-editor.css +604 -0
- package/nodes/editor/sql-editor.js +1490 -0
- package/nodes/editor/sql-model.js +203 -0
- package/nodes/icons/fromcubes-db.svg +24 -0
- package/nodes/query.html +662 -0
- package/nodes/query.js +195 -0
- package/package.json +81 -4
package/lib/params.js
ADDED
|
@@ -0,0 +1,966 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const net = require("node:net");
|
|
4
|
+
|
|
5
|
+
const { ParameterError } = require("./errors");
|
|
6
|
+
const { resolveType } = require("./sql/types");
|
|
7
|
+
const { Bound } = require("./bound");
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Optional per-parameter type checking.
|
|
11
|
+
*
|
|
12
|
+
* A parameter declared as `number` that receives `"abc"` should fail here, with
|
|
13
|
+
* the parameter name in the message, rather than three layers down as a driver
|
|
14
|
+
* error about a column nobody mentioned. Declaring the type also gives the
|
|
15
|
+
* drivers a well-formed JS value to infer their own binding type from — which
|
|
16
|
+
* matters most on SQL Server, where inference is what picks the SQL type.
|
|
17
|
+
*
|
|
18
|
+
* `auto` (the default) passes the value through untouched.
|
|
19
|
+
*
|
|
20
|
+
* A parameter can also be declared as one of the database's own column types —
|
|
21
|
+
* `varchar(50)`, `numeric(10,2)`, `varchar2(50 char)`. Then the value is
|
|
22
|
+
* checked against that type's category *and* its length or range, using
|
|
23
|
+
* `lib/sql/types.js` for the limits. None of it ever reaches the SQL text: the
|
|
24
|
+
* declaration is read here, before binding, and nowhere else.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const PARAM_TYPES = ["auto", "string", "number", "integer", "boolean", "date", "json", "buffer"];
|
|
28
|
+
|
|
29
|
+
const BOOL_WORDS = new Map([
|
|
30
|
+
["true", true],
|
|
31
|
+
["false", false],
|
|
32
|
+
["1", true],
|
|
33
|
+
["0", false],
|
|
34
|
+
["yes", true],
|
|
35
|
+
["no", false],
|
|
36
|
+
["on", true],
|
|
37
|
+
["off", false],
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
function describe(value) {
|
|
41
|
+
if (value === null) return "null";
|
|
42
|
+
if (Buffer.isBuffer(value)) return "a Buffer";
|
|
43
|
+
if (value instanceof Date) return "a Date";
|
|
44
|
+
if (Array.isArray(value)) return "an array";
|
|
45
|
+
if (typeof value === "object") return "an object";
|
|
46
|
+
return `${typeof value} ${JSON.stringify(value)}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function fail(name, expected, value) {
|
|
50
|
+
throw new ParameterError(`Parameter :${name} — expected ${expected}, got ${describe(value)}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function toString_(name, value) {
|
|
54
|
+
if (typeof value === "string") return value;
|
|
55
|
+
if (typeof value === "number" || typeof value === "bigint") return String(value);
|
|
56
|
+
if (typeof value === "boolean") return String(value);
|
|
57
|
+
if (value instanceof Date) return value.toISOString();
|
|
58
|
+
// Objects would stringify to "[object Object]", which is never what anyone
|
|
59
|
+
// meant to store. Use the json type for those.
|
|
60
|
+
return fail(name, "a string", value);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function toNumber_(name, value, integer) {
|
|
64
|
+
let n;
|
|
65
|
+
if (typeof value === "number") n = value;
|
|
66
|
+
else if (typeof value === "bigint") n = Number(value);
|
|
67
|
+
else if (typeof value === "string" && value.trim() !== "") n = Number(value);
|
|
68
|
+
else return fail(name, integer ? "an integer" : "a number", value);
|
|
69
|
+
|
|
70
|
+
if (!Number.isFinite(n)) return fail(name, integer ? "an integer" : "a number", value);
|
|
71
|
+
if (integer && !Number.isInteger(n)) return fail(name, "an integer", value);
|
|
72
|
+
return n;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const INTEGER_TEXT = /^[-+]?\d+$/;
|
|
76
|
+
const DECIMAL_TEXT = /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* A double carries 15 reliable digits, and every one of these databases has a
|
|
80
|
+
* type that carries more: bigint is 19, Oracle's NUMBER is 38, PostgreSQL's
|
|
81
|
+
* numeric is 1000. Sending such a value through `Number` does not fail — it
|
|
82
|
+
* rounds, and the row lands with a number the flow never had.
|
|
83
|
+
*
|
|
84
|
+
* So an exact type keeps its value in whatever form arrived without loss: a
|
|
85
|
+
* BigInt stays a BigInt, and a numeric string stays a string. Every driver here
|
|
86
|
+
* binds both. Values that a double does hold exactly stay plain numbers, which
|
|
87
|
+
* is what nearly every flow sends and what nearly every flow expects back.
|
|
88
|
+
*/
|
|
89
|
+
function toExactInteger_(name, value) {
|
|
90
|
+
// A BigInt that a double holds exactly is narrowed: nothing is lost, and a
|
|
91
|
+
// flow doing arithmetic on the result should not have to think about it.
|
|
92
|
+
if (typeof value === "bigint") return Number.isSafeInteger(Number(value)) ? Number(value) : value;
|
|
93
|
+
if (typeof value === "number") {
|
|
94
|
+
if (!Number.isFinite(value) || !Number.isInteger(value)) return fail(name, "an integer", value);
|
|
95
|
+
return Number.isSafeInteger(value) ? value : BigInt(value);
|
|
96
|
+
}
|
|
97
|
+
if (typeof value === "string" && INTEGER_TEXT.test(value.trim())) {
|
|
98
|
+
const text = value.trim();
|
|
99
|
+
const big = BigInt(text);
|
|
100
|
+
// Below the safe ceiling a plain number is the friendlier value to hand a
|
|
101
|
+
// flow, and it is exactly equal — nothing is lost by narrowing it.
|
|
102
|
+
return Number.isSafeInteger(Number(big)) ? Number(big) : big;
|
|
103
|
+
}
|
|
104
|
+
return fail(name, "an integer", value);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The same idea for the exact decimals: text in, text out, never a double. */
|
|
108
|
+
function toExactDecimal_(name, value) {
|
|
109
|
+
if (typeof value === "bigint") return value;
|
|
110
|
+
// Text stays text. Narrowing "1.25" to a double because this one happens to
|
|
111
|
+
// fit would make the rule depend on the value: the same column would keep its
|
|
112
|
+
// digits for one row and lose them for the next.
|
|
113
|
+
if (typeof value === "string" && DECIMAL_TEXT.test(value.trim())) return value.trim();
|
|
114
|
+
return toNumber_(name, value, false);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The digits of a value, without going near a double. Returns the digits left
|
|
119
|
+
* and right of the point, so a precision check can be made on the text of a
|
|
120
|
+
* 38-digit value that no JS number could hold.
|
|
121
|
+
*/
|
|
122
|
+
function digitsOf(value) {
|
|
123
|
+
let text = typeof value === "string" ? value.trim() : String(value);
|
|
124
|
+
if (!DECIMAL_TEXT.test(text)) return undefined;
|
|
125
|
+
text = text.replace(/^[-+]/, "");
|
|
126
|
+
|
|
127
|
+
// Exponent notation has to be expanded, or `1e25` looks like two digits.
|
|
128
|
+
const exponent = /[eE]([-+]?\d+)/.exec(text);
|
|
129
|
+
let shift = 0;
|
|
130
|
+
if (exponent) {
|
|
131
|
+
shift = Number(exponent[1]);
|
|
132
|
+
text = text.slice(0, exponent.index);
|
|
133
|
+
}
|
|
134
|
+
let [whole = "", fraction = ""] = text.split(".");
|
|
135
|
+
if (shift > 0) {
|
|
136
|
+
const moved = Math.min(shift, fraction.length);
|
|
137
|
+
whole += fraction.slice(0, moved) + "0".repeat(shift - moved);
|
|
138
|
+
fraction = fraction.slice(moved);
|
|
139
|
+
} else if (shift < 0) {
|
|
140
|
+
const moved = Math.min(-shift, whole.length);
|
|
141
|
+
fraction = whole.slice(whole.length - moved) + fraction;
|
|
142
|
+
whole = whole.slice(0, whole.length - moved);
|
|
143
|
+
if (moved < -shift) fraction = "0".repeat(-shift - moved) + fraction;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
whole = whole.replace(/^0+/, "");
|
|
147
|
+
fraction = fraction.replace(/0+$/, "");
|
|
148
|
+
return { whole, fraction };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function toBoolean_(name, value) {
|
|
152
|
+
if (typeof value === "boolean") return value;
|
|
153
|
+
if (typeof value === "number" && (value === 0 || value === 1)) return value === 1;
|
|
154
|
+
if (typeof value === "string") {
|
|
155
|
+
const word = BOOL_WORDS.get(value.trim().toLowerCase());
|
|
156
|
+
if (word !== undefined) return word;
|
|
157
|
+
}
|
|
158
|
+
return fail(name, "a boolean", value);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function toDate_(name, value) {
|
|
162
|
+
if (value instanceof Date) {
|
|
163
|
+
if (Number.isNaN(value.getTime())) return fail(name, "a valid date", value);
|
|
164
|
+
return value;
|
|
165
|
+
}
|
|
166
|
+
if (typeof value === "number" || (typeof value === "string" && value.trim() !== "")) {
|
|
167
|
+
const date = new Date(typeof value === "string" ? parseUtc(value) : value);
|
|
168
|
+
if (!Number.isNaN(date.getTime())) return date;
|
|
169
|
+
}
|
|
170
|
+
return fail(name, "a date", value);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* A date and time written without a zone means that wall clock in UTC — the
|
|
175
|
+
* zone every adapter writes in — not in whatever zone Node-RED happens to run
|
|
176
|
+
* in, which is how JavaScript reads it. "2026-11-28 10:20" is stored as 10:20.
|
|
177
|
+
*/
|
|
178
|
+
function parseUtc(text) {
|
|
179
|
+
const trimmed = text.trim();
|
|
180
|
+
const naive = /^[+-]?\d{4,6}-\d{2}-\d{2}[T\s]\d{1,2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/i.test(trimmed);
|
|
181
|
+
return Date.parse(naive ? `${trimmed.replace(/\s+/, "T")}Z` : trimmed);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function toJson_(name, value) {
|
|
185
|
+
if (typeof value === "object") return value; // arrays and plain objects pass through
|
|
186
|
+
if (typeof value === "string") {
|
|
187
|
+
try {
|
|
188
|
+
return JSON.parse(value);
|
|
189
|
+
} catch {
|
|
190
|
+
return fail(name, "valid JSON", value);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return fail(name, "an object, an array or a JSON string", value);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function toBuffer_(name, value) {
|
|
197
|
+
if (Buffer.isBuffer(value)) return value;
|
|
198
|
+
if (value instanceof Uint8Array) return Buffer.from(value);
|
|
199
|
+
// Binary arriving through a flow is usually base64 by the time it is a string.
|
|
200
|
+
if (typeof value === "string") return Buffer.from(value, "base64");
|
|
201
|
+
return fail(name, "a buffer or a base64 string", value);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function coerceOne(name, value, type) {
|
|
205
|
+
switch (type) {
|
|
206
|
+
case "string":
|
|
207
|
+
return toString_(name, value);
|
|
208
|
+
case "number":
|
|
209
|
+
return toNumber_(name, value, false);
|
|
210
|
+
case "integer":
|
|
211
|
+
return toNumber_(name, value, true);
|
|
212
|
+
case "boolean":
|
|
213
|
+
return toBoolean_(name, value);
|
|
214
|
+
case "date":
|
|
215
|
+
return toDate_(name, value);
|
|
216
|
+
case "json":
|
|
217
|
+
return toJson_(name, value);
|
|
218
|
+
case "buffer":
|
|
219
|
+
return toBuffer_(name, value);
|
|
220
|
+
default:
|
|
221
|
+
throw new ParameterError(
|
|
222
|
+
`Parameter :${name} — unknown type "${type}". Expected one of: ${PARAM_TYPES.join(", ")}`,
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Splits `varchar(50)`, `numeric(10,2)`, `varchar2(50 char)`, `varchar(max)`
|
|
229
|
+
* or `int unsigned` into its parts. Purely textual — it neither knows nor
|
|
230
|
+
* cares whether the type exists.
|
|
231
|
+
*
|
|
232
|
+
* @param {string} spec
|
|
233
|
+
* @returns {{name: string, length?: number, precision?: number, scale?: number,
|
|
234
|
+
* charSemantics?: 'char'|'byte', unsigned: boolean, isMax: boolean}}
|
|
235
|
+
*/
|
|
236
|
+
function readTypeSpec(spec) {
|
|
237
|
+
const raw = String(spec).trim();
|
|
238
|
+
const open = raw.indexOf("(");
|
|
239
|
+
|
|
240
|
+
let head = raw;
|
|
241
|
+
let args = "";
|
|
242
|
+
let tail = "";
|
|
243
|
+
if (open !== -1) {
|
|
244
|
+
const close = matchingBracket(raw, open);
|
|
245
|
+
if (close === -1) throw new ParameterError(`Type "${raw}" is missing its closing bracket`);
|
|
246
|
+
head = raw.slice(0, open);
|
|
247
|
+
args = raw.slice(open + 1, close).trim();
|
|
248
|
+
tail = raw.slice(close + 1);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const modifier = /\s+(unsigned|signed)\s*$/i;
|
|
252
|
+
let unsigned = /unsigned/i.test(tail);
|
|
253
|
+
const headModifier = modifier.exec(head);
|
|
254
|
+
if (headModifier) {
|
|
255
|
+
unsigned = unsigned || headModifier[1].toLowerCase() === "unsigned";
|
|
256
|
+
head = head.slice(0, headModifier.index);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const parsed = { name: head.trim().toLowerCase().replace(/\s+/g, " "), unsigned, isMax: false };
|
|
260
|
+
if (args === "") return parsed;
|
|
261
|
+
|
|
262
|
+
if (/^max$/i.test(args)) {
|
|
263
|
+
parsed.isMax = true;
|
|
264
|
+
return parsed;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// What is inside the brackets, as written. A type whose argument is itself a
|
|
268
|
+
// type or a list — ClickHouse's Array(Int32), Enum8('a' = 1),
|
|
269
|
+
// DateTime64(3, 'UTC') — takes it as it is (`args: "type"`); for any other
|
|
270
|
+
// type the reason it is not a size is reported by checkDeclaration.
|
|
271
|
+
parsed.inner = args;
|
|
272
|
+
|
|
273
|
+
const parts = args.split(",").map((part) => part.trim());
|
|
274
|
+
if (parts.length > 2) {
|
|
275
|
+
parsed.problem = `Type "${raw}" takes at most two arguments`;
|
|
276
|
+
return parsed;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Oracle writes the length semantics inside the brackets: VARCHAR2(50 CHAR),
|
|
280
|
+
// and leaves a vector's dimension open with a star: VECTOR(*, FLOAT32).
|
|
281
|
+
const first = /^(?:(-?\d+)(?:\s+(char|byte))?|\*)$/i.exec(parts[0]);
|
|
282
|
+
if (!first) {
|
|
283
|
+
parsed.problem = `Type "${raw}" has a length that is not a number`;
|
|
284
|
+
return parsed;
|
|
285
|
+
}
|
|
286
|
+
if (first[1] !== undefined) {
|
|
287
|
+
parsed.length = Number(first[1]);
|
|
288
|
+
parsed.precision = parsed.length;
|
|
289
|
+
}
|
|
290
|
+
if (first[2]) parsed.charSemantics = first[2].toLowerCase();
|
|
291
|
+
|
|
292
|
+
if (parts.length === 2) {
|
|
293
|
+
// A word in second place is a storage format — VECTOR(3, FLOAT32) — not a
|
|
294
|
+
// scale. Whether the type takes one is checkDeclaration's question.
|
|
295
|
+
if (/^[a-z][a-z0-9_]*$/i.test(parts[1])) parsed.format = parts[1].toLowerCase();
|
|
296
|
+
else if (!/^-?\d+$/.test(parts[1])) {
|
|
297
|
+
parsed.problem = `Type "${raw}" has a scale that is not a number`;
|
|
298
|
+
return parsed;
|
|
299
|
+
} else parsed.scale = Number(parts[1]);
|
|
300
|
+
}
|
|
301
|
+
return parsed;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Reads a declaration such as `varchar(50)`; throws on one that is not a size where a size belongs. */
|
|
305
|
+
function parseTypeSpec(spec) {
|
|
306
|
+
const parsed = readTypeSpec(spec);
|
|
307
|
+
if (parsed.problem) throw new ParameterError(parsed.problem);
|
|
308
|
+
return parsed;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Index of the bracket closing the one at `open`, skipping nested ones and quoted text; -1 if none. */
|
|
312
|
+
function matchingBracket(text, open) {
|
|
313
|
+
let depth = 0;
|
|
314
|
+
let quote = null;
|
|
315
|
+
for (let i = open; i < text.length; i++) {
|
|
316
|
+
const ch = text[i];
|
|
317
|
+
if (quote) {
|
|
318
|
+
if (ch === "\\") i++;
|
|
319
|
+
else if (ch === quote) quote = null;
|
|
320
|
+
} else if (ch === "'" || ch === '"' || ch === "`") quote = ch;
|
|
321
|
+
else if (ch === "(") depth++;
|
|
322
|
+
else if (ch === ")" && --depth === 0) return i;
|
|
323
|
+
}
|
|
324
|
+
return -1;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** How long the value is, in whatever unit the type counts. */
|
|
328
|
+
function measure(value, unit) {
|
|
329
|
+
if (Buffer.isBuffer(value)) return value.length;
|
|
330
|
+
const text = String(value);
|
|
331
|
+
if (unit === "bytes") return Buffer.byteLength(text, "utf8");
|
|
332
|
+
if (unit === "utf16units") return text.length; // what nchar/nvarchar count
|
|
333
|
+
|
|
334
|
+
// Code points, counted without materialising them: `[...text]` builds an
|
|
335
|
+
// array as long as the string, and these columns run to megabytes.
|
|
336
|
+
let count = 0;
|
|
337
|
+
for (let i = 0; i < text.length; i++) {
|
|
338
|
+
const code = text.charCodeAt(i);
|
|
339
|
+
if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) i++;
|
|
340
|
+
count++;
|
|
341
|
+
}
|
|
342
|
+
return count;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const UNIT_NAMES = { bytes: "bytes", utf16units: "byte-pairs", chars: "characters", elements: "elements" };
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* What the declaration itself is allowed to say. A type that takes no argument
|
|
349
|
+
* must reject one outright: `text(10)` is a syntax error on PostgreSQL, and
|
|
350
|
+
* `sysname(10)` silently narrowed the type before this check existed.
|
|
351
|
+
*/
|
|
352
|
+
function checkDeclaration(name, type, declared) {
|
|
353
|
+
const { spec } = type;
|
|
354
|
+
|
|
355
|
+
// A type or a list in the brackets is the server's to read, not a size.
|
|
356
|
+
if (spec.args === "type") return;
|
|
357
|
+
if (declared.problem) throw new ParameterError(declared.problem);
|
|
358
|
+
|
|
359
|
+
if (declared.format !== undefined && !(spec.formats || []).includes(declared.format)) {
|
|
360
|
+
throw new ParameterError(
|
|
361
|
+
spec.formats
|
|
362
|
+
? `Parameter :${name} — ${type.name} stores ${spec.formats.join(", ")}, not ${declared.format}`
|
|
363
|
+
: `Parameter :${name} — ${type.name} takes no storage format`,
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (declared.isMax) {
|
|
368
|
+
if (!spec.allowsMax) throw new ParameterError(`Parameter :${name} — ${type.name} has no (max) form`);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
// MySQL still parses `int(11)`. The number is a display width with no effect
|
|
372
|
+
// on what the column holds, so it is accepted and ignored rather than read as
|
|
373
|
+
// a length that would narrow the type.
|
|
374
|
+
if (spec.displayWidth && declared.scale === undefined) return;
|
|
375
|
+
if (spec.args === "none" && (declared.length !== undefined || declared.scale !== undefined)) {
|
|
376
|
+
throw new ParameterError(`Parameter :${name} — ${type.name} takes no argument`);
|
|
377
|
+
}
|
|
378
|
+
if (declared.length === undefined) return;
|
|
379
|
+
|
|
380
|
+
if (spec.args === "length") {
|
|
381
|
+
if (spec.maxLength !== undefined && declared.length > spec.maxLength) {
|
|
382
|
+
throw new ParameterError(
|
|
383
|
+
`Parameter :${name} — ${type.name}(${declared.length}) exceeds the maximum of ${spec.maxLength}`,
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
if (declared.length < (spec.minLength === undefined ? 0 : spec.minLength)) {
|
|
387
|
+
throw new ParameterError(`Parameter :${name} — ${type.name}(${declared.length}) is not a usable length`);
|
|
388
|
+
}
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// args === 'precision'
|
|
393
|
+
const { precision, scale } = declared;
|
|
394
|
+
if (spec.maxPrecision !== undefined && precision > spec.maxPrecision) {
|
|
395
|
+
throw new ParameterError(`Parameter :${name} — ${type.name} allows a precision of at most ${spec.maxPrecision}`);
|
|
396
|
+
}
|
|
397
|
+
// Firebird's DECFLOAT takes 16 or 34 and nothing in between.
|
|
398
|
+
if (spec.precisions && !spec.precisions.includes(precision)) {
|
|
399
|
+
throw new ParameterError(`Parameter :${name} — ${type.name} takes a precision of ${spec.precisions.join(" or ")}`);
|
|
400
|
+
}
|
|
401
|
+
// A fractional-second precision of 0 is legal — `datetime(0)` is a datetime
|
|
402
|
+
// with whole seconds. A numeric precision of 0 is not.
|
|
403
|
+
const floor = spec.minPrecision === undefined ? (spec.category === "number" ? 1 : 0) : spec.minPrecision;
|
|
404
|
+
if (precision < floor) {
|
|
405
|
+
throw new ParameterError(`Parameter :${name} — ${type.name} allows a precision of at least ${floor}`);
|
|
406
|
+
}
|
|
407
|
+
if (scale === undefined) return;
|
|
408
|
+
if (spec.maxScale !== undefined && scale > spec.maxScale) {
|
|
409
|
+
throw new ParameterError(`Parameter :${name} — ${type.name} allows a scale of at most ${spec.maxScale}`);
|
|
410
|
+
}
|
|
411
|
+
if (spec.minScale !== undefined && scale < spec.minScale) {
|
|
412
|
+
throw new ParameterError(`Parameter :${name} — ${type.name} allows a scale of at least ${spec.minScale}`);
|
|
413
|
+
}
|
|
414
|
+
// Everywhere but Oracle the scale may not exceed the precision: decimal(10,12)
|
|
415
|
+
// is a declaration error, not a value that happens to have no room left.
|
|
416
|
+
if (spec.scaleAtMostPrecision && scale > precision) {
|
|
417
|
+
throw new ParameterError(
|
|
418
|
+
`Parameter :${name} — ${type.name}(${precision},${scale}) needs a scale of at most ${precision}`,
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function checkLength(name, value, type, declared) {
|
|
424
|
+
const { spec } = type;
|
|
425
|
+
// (max) is the whole point of (max): 2 GB, not the 8000 a declared n may ask.
|
|
426
|
+
if (declared.isMax) return;
|
|
427
|
+
// Two different limits share one field name today. A declared length is the
|
|
428
|
+
// user's; `maxLength` on a type that takes no argument — uuid, sysname — is
|
|
429
|
+
// the type's own. A type that takes a length but was written without one
|
|
430
|
+
// (bare `varchar` on PostgreSQL) is unlimited, and `defaultLength` covers the
|
|
431
|
+
// types where the bare form means something narrower (`char` is `char(1)`).
|
|
432
|
+
let limit = declared.length;
|
|
433
|
+
if (limit === undefined) {
|
|
434
|
+
// Written without a length, a type falls back to its own ceiling — TINYTEXT
|
|
435
|
+
// is 255 characters whether or not anyone said so. Two exceptions carry a
|
|
436
|
+
// field each: `char` means `char(1)`, and a bare PostgreSQL `varchar` is
|
|
437
|
+
// unlimited rather than the 10 MB a declared one may ask for.
|
|
438
|
+
limit = spec.unboundedWhenBare ? undefined : spec.defaultLength;
|
|
439
|
+
if (limit === undefined && !spec.unboundedWhenBare) limit = spec.maxLength;
|
|
440
|
+
}
|
|
441
|
+
if (limit === undefined) return;
|
|
442
|
+
|
|
443
|
+
const unit = declared.charSemantics
|
|
444
|
+
? declared.charSemantics === "char"
|
|
445
|
+
? "chars"
|
|
446
|
+
: "bytes"
|
|
447
|
+
: spec.lengthIn || "chars";
|
|
448
|
+
|
|
449
|
+
const actual = measure(value, unit);
|
|
450
|
+
const shown = declared.length === undefined ? type.name : `${type.name}(${limit})`;
|
|
451
|
+
|
|
452
|
+
if (spec.exactLength && actual !== limit) {
|
|
453
|
+
throw new ParameterError(`Parameter :${name} — ${shown} needs exactly ${limit} ${UNIT_NAMES[unit]}, got ${actual}`);
|
|
454
|
+
}
|
|
455
|
+
if (actual > limit) {
|
|
456
|
+
throw new ParameterError(
|
|
457
|
+
`Parameter :${name} — expected at most ${limit} ${UNIT_NAMES[unit]} for ${shown}, got ${actual}`,
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function checkIntegerRange(name, value, type, declared) {
|
|
463
|
+
const unsignedWanted = declared.unsigned && type.spec.unsignedMax !== undefined;
|
|
464
|
+
const min = unsignedWanted ? type.spec.unsignedMin : type.spec.min;
|
|
465
|
+
const max = unsignedWanted ? type.spec.unsignedMax : type.spec.max;
|
|
466
|
+
if (min === undefined || max === undefined) return;
|
|
467
|
+
|
|
468
|
+
// Always in BigInt. The double comparison this replaced could not tell
|
|
469
|
+
// 2^63-1 from 2^63, so it waved through the one value it existed to catch.
|
|
470
|
+
const exact = typeof value === "bigint" ? value : BigInt(value);
|
|
471
|
+
if ((exact < min || exact > max) && !(type.spec.alsoAllowed || []).some((allowed) => allowed === exact)) {
|
|
472
|
+
throw new ParameterError(`Parameter :${name} — ${value} is outside ${type.name} (${min} to ${max})`);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** The magnitude bound of an approximate type: real overflows where float does not. */
|
|
477
|
+
function checkMagnitude(name, value, type) {
|
|
478
|
+
const { maxAbs } = type.spec;
|
|
479
|
+
if (maxAbs === undefined) return;
|
|
480
|
+
const size = Math.abs(typeof value === "number" ? value : Number(value));
|
|
481
|
+
// Oracle's NUMBER stops *below* 1.0e126, so the bound is exclusive there.
|
|
482
|
+
if (type.spec.magnitudeExclusive ? size >= maxAbs : size > maxAbs) {
|
|
483
|
+
throw new ParameterError(`Parameter :${name} — ${value} is larger than ${type.name} can hold (${maxAbs})`);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* How many digits the value needs, against how many the declaration left it.
|
|
489
|
+
* Counted on the text, because the values this exists for — 38 digits on
|
|
490
|
+
* Oracle, 65 on MySQL — are exactly the ones a double cannot carry.
|
|
491
|
+
*/
|
|
492
|
+
function checkDigits(name, value, type, declared) {
|
|
493
|
+
// Written without one, decimal on SQL Server means decimal(18,0) — a default
|
|
494
|
+
// that decides whether a 19-digit value fits.
|
|
495
|
+
const precision = declared.precision === undefined ? type.spec.defaultPrecision : declared.precision;
|
|
496
|
+
const scale = declared.precision === undefined ? type.spec.defaultScale : declared.scale;
|
|
497
|
+
if (precision === undefined) return;
|
|
498
|
+
declared = { ...declared, precision, scale };
|
|
499
|
+
// FLOAT(p) counts binary digits of mantissa on SQL Server and Oracle. Reading
|
|
500
|
+
// it as a decimal budget made float(1) reject 123.5.
|
|
501
|
+
if (type.spec.precisionIn === "binary") return;
|
|
502
|
+
|
|
503
|
+
const digits = digitsOf(value);
|
|
504
|
+
if (!digits) return;
|
|
505
|
+
const room = declared.precision - (declared.scale || 0);
|
|
506
|
+
|
|
507
|
+
// Oracle allows a scale larger than the precision, and then the column holds
|
|
508
|
+
// nothing but fractions: NUMBER(38,127) tops out at 10^-89, so the question
|
|
509
|
+
// is how far below the point the first digit is, not how many sit above it.
|
|
510
|
+
if (room <= 0) {
|
|
511
|
+
const leadingZeros = digits.fraction.length - digits.fraction.replace(/^0+/, "").length;
|
|
512
|
+
if (digits.whole !== "" || (digits.fraction !== "" && leadingZeros < -room)) {
|
|
513
|
+
throw new ParameterError(
|
|
514
|
+
`Parameter :${name} — ${value} is larger than ${type.name}(${declared.precision},${declared.scale}) holds (10^${room})`,
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
if (digits.whole.length > room) {
|
|
520
|
+
const shown = `${type.name}(${declared.precision}${declared.scale === undefined ? "" : `,${declared.scale}`})`;
|
|
521
|
+
throw new ParameterError(
|
|
522
|
+
`Parameter :${name} — ${value} needs ${digits.whole.length} digits before the point, ${shown} allows ${room}`,
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** TIME on MySQL runs to ±838 hours, which no pattern can express. */
|
|
528
|
+
function checkDuration(name, value, type) {
|
|
529
|
+
const { maxSeconds } = type.spec;
|
|
530
|
+
if (maxSeconds === undefined) return;
|
|
531
|
+
const parts = /^([-+]?)(\d{1,3}):([0-5]\d):([0-5]\d)/.exec(String(value).trim());
|
|
532
|
+
if (!parts) return;
|
|
533
|
+
const seconds = Number(parts[2]) * 3600 + Number(parts[3]) * 60 + Number(parts[4]);
|
|
534
|
+
if (seconds > maxSeconds) {
|
|
535
|
+
throw new ParameterError(`Parameter :${name} — ${value} is outside ${type.name} (±${maxSeconds} seconds)`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function checkDateRange(name, value, type, declared = {}) {
|
|
540
|
+
const { minDate, maxDate } = type.spec;
|
|
541
|
+
const sent = value.getTime();
|
|
542
|
+
let at = sent;
|
|
543
|
+
// MySQL rounds a fraction the column has no room for: 03:14:07.999 into a
|
|
544
|
+
// TIMESTAMP(0) is 03:14:08 — past the end of the range — so the check has to
|
|
545
|
+
// see the value the server will store, not the one that was sent.
|
|
546
|
+
if (type.spec.roundsFraction) {
|
|
547
|
+
const digits = declared.precision === undefined ? type.spec.defaultPrecision || 0 : declared.precision;
|
|
548
|
+
if (digits < 3) {
|
|
549
|
+
const step = 10 ** (3 - digits);
|
|
550
|
+
at = Math.round(at / step) * step;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
if ((minDate !== undefined && at < Date.parse(minDate)) || (maxDate !== undefined && at > Date.parse(maxDate))) {
|
|
554
|
+
throw new ParameterError(
|
|
555
|
+
`Parameter :${name} — ${value.toISOString()}${at === sent ? "" : ` (stored rounded as ${new Date(at).toISOString()})`}` +
|
|
556
|
+
` is outside ${type.name} (${minDate || "any"} to ${maxDate || "any"})`,
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** A text shape: a uuid, a MAC address, a bit string, a time of day. */
|
|
562
|
+
function checkPattern(name, value, type) {
|
|
563
|
+
const { pattern, patternName } = type.spec;
|
|
564
|
+
if (!pattern) return;
|
|
565
|
+
// MySQL and MariaDB read a BIT column's value as a number as readily as a
|
|
566
|
+
// string, so there the digits are checked against the width instead.
|
|
567
|
+
if (type.spec.allowsNumber && typeof value === "number") {
|
|
568
|
+
// A BIT(3) column holds 0 through 7, whichever way the value was written.
|
|
569
|
+
const width = type.declaredLength === undefined ? type.spec.defaultLength : type.declaredLength;
|
|
570
|
+
if (width !== undefined && (value < 0 || value > 2 ** width - 1)) {
|
|
571
|
+
throw new ParameterError(`Parameter :${name} — ${value} does not fit ${type.name}(${width})`);
|
|
572
|
+
}
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
// Elsewhere a shape is a property of text: `101` for a bit(3) column looks
|
|
576
|
+
// right only because JS will print it that way; the flow meant a number.
|
|
577
|
+
if (typeof value !== "string") {
|
|
578
|
+
throw new ParameterError(
|
|
579
|
+
`Parameter :${name} — expected ${patternName || type.name} as text, got ${describe(value)}`,
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
const text = value.trim();
|
|
583
|
+
if (!pattern.test(normaliseFor(type, text))) {
|
|
584
|
+
throw new ParameterError(`Parameter :${name} — ${JSON.stringify(text)} is not ${patternName || type.name}`);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** NaN and the infinities are values numeric and the floats genuinely hold. */
|
|
589
|
+
function isSpecial(spec, value) {
|
|
590
|
+
return typeof value === "string" && Boolean(spec.special) && spec.special.includes(value.trim());
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/** uuid is written five different ways; all of them are the same 32 hex digits. */
|
|
594
|
+
function normaliseFor(type, text) {
|
|
595
|
+
// MariaDB takes the hyphens anywhere or nowhere but rejects the braces that
|
|
596
|
+
// PostgreSQL accepts, so the two spellings are not one rule.
|
|
597
|
+
if (type.spec.normalise === "hyphens") return text.trim().replace(/-/g, "");
|
|
598
|
+
if (type.spec.normalise !== "uuid") return text;
|
|
599
|
+
return text
|
|
600
|
+
.trim()
|
|
601
|
+
.replace(/^urn:uuid:/i, "")
|
|
602
|
+
.replace(/^\{(.*)\}$/, "$1")
|
|
603
|
+
.replace(/-/g, "");
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Compares two decimals written as text, without a double in the way. Returns
|
|
608
|
+
* -1, 0 or 1. Used for the money bounds, which are exactly the numbers a double
|
|
609
|
+
* cannot hold: PostgreSQL's is 92233720368547758.07.
|
|
610
|
+
*/
|
|
611
|
+
function decimalCompare(a, b) {
|
|
612
|
+
const left = digitsOf(a);
|
|
613
|
+
const right = digitsOf(b);
|
|
614
|
+
if (!left || !right) return 0;
|
|
615
|
+
const negative = (text) => String(text).trim().startsWith("-");
|
|
616
|
+
const sign = (text, digits) => (digits.whole === "" && digits.fraction === "" ? 0 : negative(text) ? -1 : 1);
|
|
617
|
+
const signA = sign(a, left);
|
|
618
|
+
const signB = sign(b, right);
|
|
619
|
+
if (signA !== signB) return signA < signB ? -1 : 1;
|
|
620
|
+
|
|
621
|
+
const width = Math.max(left.fraction.length, right.fraction.length);
|
|
622
|
+
const scaled = (d) => BigInt((d.whole || "0") + d.fraction.padEnd(width, "0"));
|
|
623
|
+
const magnitude = scaled(left) === scaled(right) ? 0 : scaled(left) < scaled(right) ? -1 : 1;
|
|
624
|
+
return signA < 0 ? -magnitude : magnitude;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
const CURRENCY = /^\s*[-+]?\s*[^\d\s.,+-]?\s*|[^\d]*$/g;
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* The checks that need code rather than a regular expression. An address is the
|
|
631
|
+
* clearest case: no pattern rejects 999.1.1.1, and `node:net` already knows.
|
|
632
|
+
*/
|
|
633
|
+
function checkSyntax(name, value, type) {
|
|
634
|
+
const { check } = type.spec;
|
|
635
|
+
const text = typeof value === "string" ? value.trim() : String(value);
|
|
636
|
+
|
|
637
|
+
if (check === "ipv4" || check === "ipv6") {
|
|
638
|
+
const ok = check === "ipv4" ? net.isIPv4(text) : net.isIPv6(text);
|
|
639
|
+
if (!ok) throw new ParameterError(`Parameter :${name} — ${JSON.stringify(text)} is not an ${check} address`);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
if (check === "inet" || check === "cidr") {
|
|
644
|
+
const slash = text.indexOf("/");
|
|
645
|
+
const address = slash === -1 ? text : text.slice(0, slash);
|
|
646
|
+
const family = net.isIP(address);
|
|
647
|
+
if (family === 0) {
|
|
648
|
+
throw new ParameterError(`Parameter :${name} — ${JSON.stringify(text)} is not an IP address`);
|
|
649
|
+
}
|
|
650
|
+
if (slash === -1) {
|
|
651
|
+
// cidr always carries a netmask; inet without one means a single host.
|
|
652
|
+
if (check === "cidr") return;
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
const bits = text.slice(slash + 1);
|
|
656
|
+
const width = family === 4 ? 32 : 128;
|
|
657
|
+
if (!/^\d+$/.test(bits) || Number(bits) > width) {
|
|
658
|
+
throw new ParameterError(`Parameter :${name} — ${JSON.stringify(text)} has a netmask outside 0 to ${width}`);
|
|
659
|
+
}
|
|
660
|
+
// "It is an error to specify a network address that has bits set to the
|
|
661
|
+
// right of the specified netmask" — which is the whole difference between
|
|
662
|
+
// cidr and inet, so it is the one rule worth the arithmetic.
|
|
663
|
+
if (check === "cidr" && hostBitsSet(address, Number(bits), family)) {
|
|
664
|
+
throw new ParameterError(`Parameter :${name} — ${JSON.stringify(text)} has bits set to the right of its netmask`);
|
|
665
|
+
}
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
if (check === "money") {
|
|
670
|
+
const cleaned = text.replace(CURRENCY, "").replace(/,/g, "");
|
|
671
|
+
const signed = /^\s*-/.test(text) ? `-${cleaned}` : cleaned;
|
|
672
|
+
if (!DECIMAL_TEXT.test(signed) || cleaned === "") {
|
|
673
|
+
throw new ParameterError(`Parameter :${name} — ${JSON.stringify(text)} is not an amount`);
|
|
674
|
+
}
|
|
675
|
+
const { min, max } = type.spec;
|
|
676
|
+
if (
|
|
677
|
+
(min !== undefined && decimalCompare(signed, min) < 0) ||
|
|
678
|
+
(max !== undefined && decimalCompare(signed, max) > 0)
|
|
679
|
+
) {
|
|
680
|
+
throw new ParameterError(`Parameter :${name} — ${text} is outside ${type.name} (${min} to ${max})`);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function hostBitsSet(address, prefix, family) {
|
|
686
|
+
const bytes =
|
|
687
|
+
family === 4 ? address.split(".").map(Number) : expandIpv6(address).flatMap((group) => [group >> 8, group & 0xff]);
|
|
688
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
689
|
+
const kept = Math.min(8, Math.max(0, prefix - i * 8));
|
|
690
|
+
if (bytes[i] & (0xff >> kept)) return true;
|
|
691
|
+
}
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function expandIpv6(address) {
|
|
696
|
+
const [head, tail = ""] = address.split("::");
|
|
697
|
+
const left = head === "" ? [] : head.split(":");
|
|
698
|
+
const right = tail === "" ? [] : tail.split(":");
|
|
699
|
+
const middle = new Array(8 - left.length - right.length).fill("0");
|
|
700
|
+
return [...left, ...(address.includes("::") ? middle : []), ...right].map((g) => parseInt(g || "0", 16));
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* Checks one value against a column type of the database it is bound for and
|
|
705
|
+
* returns it in the form the driver should receive.
|
|
706
|
+
*
|
|
707
|
+
* Which checks run is decided by the fields the type carries, not by its
|
|
708
|
+
* category: category says what the value must be in JS, and a `bit` string or
|
|
709
|
+
* an `inet` needs a length or a shape while being neither of those things.
|
|
710
|
+
*/
|
|
711
|
+
function coerceNative(name, value, type, declared) {
|
|
712
|
+
const { spec } = type;
|
|
713
|
+
checkDeclaration(name, type, declared);
|
|
714
|
+
if (spec.joinsArrays) return joinMembers(name, value, type);
|
|
715
|
+
|
|
716
|
+
const coerced = coerceForCategory(name, value, spec);
|
|
717
|
+
|
|
718
|
+
if (spec.category === "integer") checkIntegerRange(name, coerced, type, declared);
|
|
719
|
+
if (spec.category === "number" && !isSpecial(spec, coerced)) {
|
|
720
|
+
checkMagnitude(name, coerced, type);
|
|
721
|
+
checkDigits(name, coerced, type, declared);
|
|
722
|
+
}
|
|
723
|
+
if (spec.category === "date") {
|
|
724
|
+
// Text kept for its precision still names a point in time that has to fit.
|
|
725
|
+
const at = coerced instanceof Date ? coerced : new Date(parseUtc(coerced));
|
|
726
|
+
if (!Number.isNaN(at.getTime())) checkDateRange(name, at, type, declared);
|
|
727
|
+
}
|
|
728
|
+
if (spec.category === "vector") checkVector(name, coerced, type, declared);
|
|
729
|
+
if (spec.maxSeconds !== undefined) checkDuration(name, coerced, type);
|
|
730
|
+
// A length, never a precision: `time(6)` says six fractional digits, and
|
|
731
|
+
// reading that as six characters rejected every clock string there is.
|
|
732
|
+
if (
|
|
733
|
+
spec.category !== "vector" &&
|
|
734
|
+
(spec.args === "length" || spec.category === "string" || spec.category === "binary")
|
|
735
|
+
) {
|
|
736
|
+
checkLength(name, coerced, type, declared);
|
|
737
|
+
}
|
|
738
|
+
checkPattern(name, coerced, { ...type, declaredLength: declared.length });
|
|
739
|
+
if (spec.check) checkSyntax(name, coerced, type);
|
|
740
|
+
return coerced;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* A SET value is one comma-separated string, so an array is the value rather
|
|
745
|
+
* than a spread list — the same exception the json types make.
|
|
746
|
+
*/
|
|
747
|
+
function joinMembers(name, value, type) {
|
|
748
|
+
const { joinsArrays, maxMembers, maxLength, lengthIn } = type.spec;
|
|
749
|
+
const members = Array.isArray(value) ? value : String(toString_(name, value)).split(joinsArrays);
|
|
750
|
+
|
|
751
|
+
if (maxMembers !== undefined && members.length > maxMembers) {
|
|
752
|
+
throw new ParameterError(
|
|
753
|
+
`Parameter :${name} — ${type.name} holds at most ${maxMembers} members, got ${members.length}`,
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
for (const [index, member] of members.entries()) {
|
|
757
|
+
if (typeof member !== "string") fail(`${name}[${index}]`, "a string", member);
|
|
758
|
+
if (Array.isArray(value) && member.includes(joinsArrays)) {
|
|
759
|
+
throw new ParameterError(
|
|
760
|
+
`Parameter :${name} — a ${type.name} member may not contain ${JSON.stringify(joinsArrays)}`,
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
// The 255 is per member, not for the joined value.
|
|
764
|
+
if (maxLength !== undefined && measure(member, lengthIn || "chars") > maxLength) {
|
|
765
|
+
throw new ParameterError(
|
|
766
|
+
`Parameter :${name} — a ${type.name} member holds at most ${maxLength} ${UNIT_NAMES[lengthIn || "chars"]}`,
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
return members.join(joinsArrays);
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* A timestamp written with an offset other than UTC. On the types that store
|
|
775
|
+
* the offset (SQL Server's datetimeoffset, Oracle's TIMESTAMP WITH TIME ZONE)
|
|
776
|
+
* a Date would keep the instant and lose the offset, so the text is kept.
|
|
777
|
+
*/
|
|
778
|
+
function carriesOffset(value) {
|
|
779
|
+
if (typeof value !== "string") return false;
|
|
780
|
+
const text = value.trim();
|
|
781
|
+
return /[T\s]\d{1,2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*[+-]\d{2}(?::?\d{2})?$/.test(text) && !Number.isNaN(parseUtc(text));
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** A vector is a list of numbers: an array, or the JSON text of one. */
|
|
785
|
+
function toVector_(name, value) {
|
|
786
|
+
let list = value;
|
|
787
|
+
if (typeof value === "string") {
|
|
788
|
+
try {
|
|
789
|
+
list = JSON.parse(value);
|
|
790
|
+
} catch {
|
|
791
|
+
return fail(name, "a vector — an array of numbers", value);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
if (ArrayBuffer.isView(list) && !(list instanceof DataView) && !Buffer.isBuffer(list)) list = Array.from(list);
|
|
795
|
+
if (!Array.isArray(list)) return fail(name, "a vector — an array of numbers", value);
|
|
796
|
+
if (list.length === 0) throw new ParameterError(`Parameter :${name} — a vector needs at least one number, got []`);
|
|
797
|
+
// A copy: the array belongs to the message, which other nodes may still read.
|
|
798
|
+
return list.map((n, i) => {
|
|
799
|
+
const number = typeof n === "string" && n.trim() !== "" ? Number(n) : n;
|
|
800
|
+
if (typeof number !== "number" || !Number.isFinite(number)) {
|
|
801
|
+
throw new ParameterError(
|
|
802
|
+
`Parameter :${name}[${i}] — expected a finite number, got ${typeof n === "number" ? String(n) : describe(n)}`,
|
|
803
|
+
);
|
|
804
|
+
}
|
|
805
|
+
return number;
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/** A declared vector(n) holds exactly n numbers; an undeclared one up to the type's ceiling. */
|
|
810
|
+
function checkVector(name, list, type, declared) {
|
|
811
|
+
const { spec } = type;
|
|
812
|
+
if (declared.length !== undefined && list.length !== declared.length) {
|
|
813
|
+
throw new ParameterError(
|
|
814
|
+
`Parameter :${name} — ${type.name}(${declared.length}) needs exactly ${declared.length} numbers, got ${list.length}`,
|
|
815
|
+
);
|
|
816
|
+
}
|
|
817
|
+
if (spec.maxLength !== undefined && list.length > spec.maxLength) {
|
|
818
|
+
throw new ParameterError(
|
|
819
|
+
`Parameter :${name} — ${type.name} holds at most ${spec.maxLength} dimensions, got ${list.length}`,
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
if (spec.maxAbs !== undefined) {
|
|
823
|
+
for (const n of list) {
|
|
824
|
+
if (Math.abs(n) > spec.maxAbs) {
|
|
825
|
+
throw new ParameterError(`Parameter :${name} — ${n} is larger than a ${type.name} element can hold`);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function carriesSubMilliseconds(value) {
|
|
832
|
+
if (typeof value !== "string") return false;
|
|
833
|
+
const fraction = /\.(\d+)/.exec(value.trim());
|
|
834
|
+
return Boolean(fraction) && fraction[1].length > 3 && !Number.isNaN(parseUtc(value));
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
function coerceForCategory(name, value, spec) {
|
|
838
|
+
switch (spec.category) {
|
|
839
|
+
// Passed on as it arrived: a bit string, an interval literal, a geometry.
|
|
840
|
+
// A pattern still gets to see it, which is what makes the difference
|
|
841
|
+
// between "we do not check this" and "we do not convert this".
|
|
842
|
+
case "other":
|
|
843
|
+
case "literal":
|
|
844
|
+
return typeof value === "string" ? value.trim() : value;
|
|
845
|
+
// Every integer column on every one of these products is at least 16 bits
|
|
846
|
+
// and at most 64, and the 64-bit ones do not fit a double — so the exact
|
|
847
|
+
// path is the only correct one here, not an option a type opts into.
|
|
848
|
+
case "integer":
|
|
849
|
+
return toExactInteger_(name, value);
|
|
850
|
+
// Approximate types are doubles by definition, so there is nothing to keep;
|
|
851
|
+
// the exact ones — numeric, decimal, Oracle's NUMBER — keep their text.
|
|
852
|
+
case "number":
|
|
853
|
+
// Only as text. `Number('1e309')` is Infinity too, but that one is an
|
|
854
|
+
// overflow the flow did not intend, not the documented spelling.
|
|
855
|
+
if (typeof value === "string" && spec.special && spec.special.includes(value.trim())) return value.trim();
|
|
856
|
+
return spec.exact ? toExactDecimal_(name, value) : coerceOne(name, value, "number");
|
|
857
|
+
case "binary":
|
|
858
|
+
return coerceOne(name, value, "buffer");
|
|
859
|
+
// A JS Date carries milliseconds. Handing one to a TIMESTAMP(9) column
|
|
860
|
+
// would drop the six digits the flow asked the column to keep, silently, so
|
|
861
|
+
// a timestamp written with more precision than a Date holds stays text.
|
|
862
|
+
case "date":
|
|
863
|
+
return spec.keepsText && (carriesSubMilliseconds(value) || (spec.keepsOffset && carriesOffset(value)))
|
|
864
|
+
? value.trim()
|
|
865
|
+
: coerceOne(name, value, "date");
|
|
866
|
+
case "vector":
|
|
867
|
+
return toVector_(name, value);
|
|
868
|
+
default:
|
|
869
|
+
return coerceOne(name, value, spec.category);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* Checks and converts one parameter value.
|
|
875
|
+
*
|
|
876
|
+
* Arrays are handled element by element, so a spread parameter
|
|
877
|
+
* (`IN (:...ids)`) declared as `integer` validates every id. The `json` type is
|
|
878
|
+
* the exception: there an array is the value itself.
|
|
879
|
+
*
|
|
880
|
+
* null and undefined pass straight through — whether a missing value is an
|
|
881
|
+
* error is decided later, by the compiler's undefinedAsNull setting.
|
|
882
|
+
*
|
|
883
|
+
* With `database` given, `type` may also be one of that database's own column
|
|
884
|
+
* types. Without it only the eight names in PARAM_TYPES are understood, which
|
|
885
|
+
* is what keeps this callable — and unchanged — from anywhere that has no
|
|
886
|
+
* connection to hand.
|
|
887
|
+
*
|
|
888
|
+
* @param {string} name
|
|
889
|
+
* @param {unknown} value
|
|
890
|
+
* @param {string} [type]
|
|
891
|
+
* @param {string} [database] product or engine id, e.g. 'mariadb'
|
|
892
|
+
* @returns {unknown}
|
|
893
|
+
*/
|
|
894
|
+
function coerceParam(name, value, type, database) {
|
|
895
|
+
if (!type || type === "auto") return value;
|
|
896
|
+
if (value === null || value === undefined) return value;
|
|
897
|
+
|
|
898
|
+
// A column type wins over a plain JS one where both spellings exist: on
|
|
899
|
+
// PostgreSQL `integer` then also checks the range, which the JS check never
|
|
900
|
+
// could. Names the database does not have — 'string', 'buffer' — fall back.
|
|
901
|
+
const native = database ? findNative(type, database) : undefined;
|
|
902
|
+
const isJson = native ? isWholeArray(native.type.spec) : type === "json";
|
|
903
|
+
|
|
904
|
+
if (Array.isArray(value) && !isJson) {
|
|
905
|
+
return value.map((item, i) =>
|
|
906
|
+
item === null || item === undefined ? item : coerceScalar(`${name}[${i}]`, item, type, native, database),
|
|
907
|
+
);
|
|
908
|
+
}
|
|
909
|
+
return coerceScalar(name, value, type, native, database);
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** Types whose value is itself an array: json, MySQL's SET, a vector. */
|
|
913
|
+
function isWholeArray(spec) {
|
|
914
|
+
return spec.category === "json" || spec.category === "vector" || Boolean(spec.joinsArrays || spec.wholeValue);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* What the query node binds: the checked value of `coerceParam`, and — when the
|
|
919
|
+
* declared type is one of the database's own — wrapped in a `Bound` that
|
|
920
|
+
* carries that type to the adapter. The adapter then binds it as that type
|
|
921
|
+
* instead of guessing from the JS value: a Date as datetime2 rather than
|
|
922
|
+
* SQL Server's legacy datetime, json as JSON rather than a PostgreSQL array, a
|
|
923
|
+
* vector as a vector. The type still never reaches the SQL text.
|
|
924
|
+
*
|
|
925
|
+
* null is wrapped as well: a typed NULL is what SQL Server needs to put a
|
|
926
|
+
* NULL into a varbinary column.
|
|
927
|
+
*
|
|
928
|
+
* @param {string} name
|
|
929
|
+
* @param {unknown} value
|
|
930
|
+
* @param {string} [type]
|
|
931
|
+
* @param {string} [database]
|
|
932
|
+
*/
|
|
933
|
+
function bindParam(name, value, type, database) {
|
|
934
|
+
const coerced = coerceParam(name, value, type, database);
|
|
935
|
+
if (!database || !type || type === "auto") return coerced;
|
|
936
|
+
const native = findNative(type, database);
|
|
937
|
+
if (!native) return coerced;
|
|
938
|
+
const wrap = (v) => new Bound(v, native.type.name, native.type.spec, native.declared);
|
|
939
|
+
if (Array.isArray(coerced) && !isWholeArray(native.type.spec)) {
|
|
940
|
+
return coerced.map((item) => (item === undefined ? item : wrap(item)));
|
|
941
|
+
}
|
|
942
|
+
return coerced === undefined ? coerced : wrap(coerced);
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
function findNative(spec, database) {
|
|
946
|
+
// Lenient here: whether the brackets must hold a size is the type's question.
|
|
947
|
+
const declared = readTypeSpec(spec);
|
|
948
|
+
const type = resolveType(database, declared.name);
|
|
949
|
+
if (!type) return undefined;
|
|
950
|
+
// Nullable(Int32) and LowCardinality(String) hold what the inner type holds.
|
|
951
|
+
if (type.spec.wraps && declared.inner) return findNative(declared.inner, database) || { type, declared };
|
|
952
|
+
// A type or a list in the brackets — Decimal32(4) is a scale, not a precision
|
|
953
|
+
// — says nothing this check reads as a size.
|
|
954
|
+
if (type.spec.args === "type") return { type, declared: { name: declared.name, unsigned: false, isMax: false } };
|
|
955
|
+
return { type, declared };
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
function coerceScalar(name, value, spec, native, database) {
|
|
959
|
+
if (native) return coerceNative(name, value, native.type, native.declared);
|
|
960
|
+
if (database && !PARAM_TYPES.includes(spec)) {
|
|
961
|
+
throw new ParameterError(`Parameter :${name} — ${database} has no type "${spec}"`);
|
|
962
|
+
}
|
|
963
|
+
return coerceOne(name, value, spec);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
module.exports = { coerceParam, bindParam, parseTypeSpec, parseUtc, PARAM_TYPES };
|