@minnowdb/core 0.6.8 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/date-value.d.ts +5 -0
- package/dist/date-value.js +41 -0
- package/dist/engine/database.js +1085 -81
- package/dist/engine/optimizer.js +446 -18
- package/dist/engine/point-read.d.ts +4 -2
- package/dist/engine/point-read.js +16 -6
- package/dist/engine/query.d.ts +53 -1
- package/dist/engine/query.js +1160 -239
- package/dist/engine/sql-domains.d.ts +7 -1
- package/dist/engine/sql-domains.js +38 -1
- package/dist/engine/sql-functions.d.ts +11 -0
- package/dist/engine/sql-functions.js +1186 -0
- package/dist/engine/sql-semantics.d.ts +25 -4
- package/dist/engine/sql-semantics.js +134 -1
- package/dist/engine/vector.d.ts +7 -1
- package/dist/engine/vector.js +718 -124
- package/dist/plan/model.d.ts +21 -1
- package/dist/storage/types.js +44 -18
- package/package.json +1 -1
- package/postgres-feature-profile.json +15 -5
- package/sql-feature-matrix.json +277 -6
|
@@ -0,0 +1,1186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Table-driven scalar functions: the PostgreSQL string, math, datetime, regex, and formatting
|
|
3
|
+
* functions that need no special parsing. Each entry carries its arity, its result type, and a
|
|
4
|
+
* pure evaluator over already-evaluated arguments, so the parser's arity check, schema
|
|
5
|
+
* inference, constant folding, and both executors read one definition. Anything with its own
|
|
6
|
+
* syntax (EXTRACT, CAST, TRIM ... FROM, JSON constructors) stays in the parser's own tables.
|
|
7
|
+
*/
|
|
8
|
+
import { dateIsoString, dateMilliseconds, dateUtcDate, dateUtcDay, dateUtcFullYear, dateUtcHours, dateUtcMinutes, dateUtcMonth, dateUtcSeconds, } from "../date-value.js";
|
|
9
|
+
import { MAX_SQL_SCALAR_RESULT_CHARACTERS } from "./cache-limits.js";
|
|
10
|
+
import { dateDomainValue, externalSqlDomainValue, intervalDomainValue, isDateDomainValue, protectedSqlTextValue, } from "./sql-domains.js";
|
|
11
|
+
import { compileRegexPattern, parseSqlTimestampText, stringArgument } from "./sql-semantics.js";
|
|
12
|
+
// --- Argument readers ----------------------------------------------------------------------
|
|
13
|
+
function text(name, value) {
|
|
14
|
+
const source = stringArgument(name, value);
|
|
15
|
+
if (source.length > MAX_SQL_SCALAR_RESULT_CHARACTERS) {
|
|
16
|
+
throw new RangeError(`${name} input exceeds ${String(MAX_SQL_SCALAR_RESULT_CHARACTERS)} characters`);
|
|
17
|
+
}
|
|
18
|
+
return source;
|
|
19
|
+
}
|
|
20
|
+
function number(name, value) {
|
|
21
|
+
const external = externalSqlDomainValue(value);
|
|
22
|
+
if (typeof external === "number")
|
|
23
|
+
return external;
|
|
24
|
+
if (typeof external === "string" &&
|
|
25
|
+
/^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(external)) {
|
|
26
|
+
return Number(external);
|
|
27
|
+
}
|
|
28
|
+
throw new TypeError(`${name} requires a numeric argument`);
|
|
29
|
+
}
|
|
30
|
+
function integer(name, value) {
|
|
31
|
+
const parsed = number(name, value);
|
|
32
|
+
if (!Number.isInteger(parsed))
|
|
33
|
+
throw new TypeError(`${name} requires a whole number`);
|
|
34
|
+
return parsed;
|
|
35
|
+
}
|
|
36
|
+
function datetime(name, value) {
|
|
37
|
+
if (value instanceof Date)
|
|
38
|
+
return value;
|
|
39
|
+
if (isDateDomainValue(value)) {
|
|
40
|
+
const external = externalSqlDomainValue(value);
|
|
41
|
+
if (typeof external === "string")
|
|
42
|
+
return new Date(`${external}T00:00:00.000Z`);
|
|
43
|
+
}
|
|
44
|
+
if (typeof value === "string") {
|
|
45
|
+
const parsed = parseSqlTimestampText(value);
|
|
46
|
+
if (parsed !== undefined)
|
|
47
|
+
return parsed;
|
|
48
|
+
}
|
|
49
|
+
throw new TypeError(`${name} requires a datetime argument`);
|
|
50
|
+
}
|
|
51
|
+
function bounded(value, name) {
|
|
52
|
+
if (value.length > MAX_SQL_SCALAR_RESULT_CHARACTERS) {
|
|
53
|
+
throw new RangeError(`${name} result exceeds ${String(MAX_SQL_SCALAR_RESULT_CHARACTERS)} characters`);
|
|
54
|
+
}
|
|
55
|
+
return protectedSqlTextValue(value);
|
|
56
|
+
}
|
|
57
|
+
function characters(value) {
|
|
58
|
+
return Array.from(value);
|
|
59
|
+
}
|
|
60
|
+
/** PostgreSQL's text rendering of a value inside CONCAT and FORMAT. */
|
|
61
|
+
function rendered(value) {
|
|
62
|
+
const external = externalSqlDomainValue(value);
|
|
63
|
+
if (typeof external === "string")
|
|
64
|
+
return external;
|
|
65
|
+
if (typeof external === "number")
|
|
66
|
+
return String(external);
|
|
67
|
+
if (typeof external === "boolean")
|
|
68
|
+
return external ? "t" : "f";
|
|
69
|
+
if (external instanceof Date)
|
|
70
|
+
return dateIsoString(external);
|
|
71
|
+
return String(external);
|
|
72
|
+
}
|
|
73
|
+
function finite(name, value) {
|
|
74
|
+
if (!Number.isFinite(value))
|
|
75
|
+
throw new TypeError(`${name} produced a non-finite number`);
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
// --- Datetime formatting (TO_CHAR / TO_DATE / TO_TIMESTAMP) -------------------------------
|
|
79
|
+
const MONTHS = [
|
|
80
|
+
"January",
|
|
81
|
+
"February",
|
|
82
|
+
"March",
|
|
83
|
+
"April",
|
|
84
|
+
"May",
|
|
85
|
+
"June",
|
|
86
|
+
"July",
|
|
87
|
+
"August",
|
|
88
|
+
"September",
|
|
89
|
+
"October",
|
|
90
|
+
"November",
|
|
91
|
+
"December",
|
|
92
|
+
];
|
|
93
|
+
const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
|
94
|
+
/** Template tokens, longest first, so `HH24` wins over `HH`, `YYYY` over `YY`. */
|
|
95
|
+
const DATE_TOKENS = [
|
|
96
|
+
"HH24",
|
|
97
|
+
"HH12",
|
|
98
|
+
"YYYY",
|
|
99
|
+
"MONTH",
|
|
100
|
+
"Month",
|
|
101
|
+
"month",
|
|
102
|
+
"DDD",
|
|
103
|
+
"DAY",
|
|
104
|
+
"Day",
|
|
105
|
+
"day",
|
|
106
|
+
"MON",
|
|
107
|
+
"Mon",
|
|
108
|
+
"mon",
|
|
109
|
+
"DY",
|
|
110
|
+
"Dy",
|
|
111
|
+
"dy",
|
|
112
|
+
"IW",
|
|
113
|
+
"MS",
|
|
114
|
+
"US",
|
|
115
|
+
"TZ",
|
|
116
|
+
"HH",
|
|
117
|
+
"MI",
|
|
118
|
+
"SS",
|
|
119
|
+
"YY",
|
|
120
|
+
"MM",
|
|
121
|
+
"DD",
|
|
122
|
+
"AM",
|
|
123
|
+
"PM",
|
|
124
|
+
"am",
|
|
125
|
+
"pm",
|
|
126
|
+
"A.M.",
|
|
127
|
+
"P.M.",
|
|
128
|
+
"Q",
|
|
129
|
+
"D",
|
|
130
|
+
"J",
|
|
131
|
+
];
|
|
132
|
+
/** Splits a TO_CHAR template into tokens and literal text; FM before a token disables padding. */
|
|
133
|
+
function dateTemplate(template) {
|
|
134
|
+
const items = [];
|
|
135
|
+
let index = 0;
|
|
136
|
+
let fill = false;
|
|
137
|
+
while (index < template.length) {
|
|
138
|
+
if (template[index] === '"') {
|
|
139
|
+
const close = template.indexOf('"', index + 1);
|
|
140
|
+
const end = close === -1 ? template.length : close;
|
|
141
|
+
items.push({ literal: template.slice(index + 1, end), fill: false });
|
|
142
|
+
index = end + 1;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (template.startsWith("FM", index)) {
|
|
146
|
+
fill = true;
|
|
147
|
+
index += 2;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const token = DATE_TOKENS.find((candidate) => template.startsWith(candidate, index));
|
|
151
|
+
if (token !== undefined) {
|
|
152
|
+
items.push({ token, fill });
|
|
153
|
+
fill = false;
|
|
154
|
+
index += token.length;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
items.push({ literal: template[index] ?? "", fill: false });
|
|
158
|
+
index += 1;
|
|
159
|
+
}
|
|
160
|
+
return items;
|
|
161
|
+
}
|
|
162
|
+
function pad(value, width, fill) {
|
|
163
|
+
return fill ? String(value) : String(value).padStart(width, "0");
|
|
164
|
+
}
|
|
165
|
+
function cased(name, token) {
|
|
166
|
+
if (token === token.toUpperCase())
|
|
167
|
+
return name.toUpperCase();
|
|
168
|
+
if (token === token.toLowerCase())
|
|
169
|
+
return name.toLowerCase();
|
|
170
|
+
return name;
|
|
171
|
+
}
|
|
172
|
+
function isoWeek(date) {
|
|
173
|
+
const probe = new Date(Date.UTC(dateUtcFullYear(date), dateUtcMonth(date), dateUtcDate(date)));
|
|
174
|
+
probe.setUTCDate(probe.getUTCDate() + 4 - (probe.getUTCDay() || 7));
|
|
175
|
+
const yearStart = Date.UTC(probe.getUTCFullYear(), 0, 1);
|
|
176
|
+
return Math.ceil(((probe.getTime() - yearStart) / 86_400_000 + 1) / 7);
|
|
177
|
+
}
|
|
178
|
+
function dayOfYear(date) {
|
|
179
|
+
const start = Date.UTC(dateUtcFullYear(date), 0, 1);
|
|
180
|
+
return (Math.floor((Date.UTC(dateUtcFullYear(date), dateUtcMonth(date), dateUtcDate(date)) - start) / 86_400_000) + 1);
|
|
181
|
+
}
|
|
182
|
+
function formatDatetime(date, template) {
|
|
183
|
+
const parts = [];
|
|
184
|
+
const hours = dateUtcHours(date);
|
|
185
|
+
for (const item of dateTemplate(template)) {
|
|
186
|
+
if (item.literal !== undefined) {
|
|
187
|
+
parts.push(item.literal);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const token = item.token ?? "";
|
|
191
|
+
const fill = item.fill;
|
|
192
|
+
switch (token) {
|
|
193
|
+
case "YYYY":
|
|
194
|
+
parts.push(pad(dateUtcFullYear(date), 4, fill));
|
|
195
|
+
break;
|
|
196
|
+
case "YY":
|
|
197
|
+
parts.push(pad(dateUtcFullYear(date) % 100, 2, fill));
|
|
198
|
+
break;
|
|
199
|
+
case "MM":
|
|
200
|
+
parts.push(pad(dateUtcMonth(date) + 1, 2, fill));
|
|
201
|
+
break;
|
|
202
|
+
case "DD":
|
|
203
|
+
parts.push(pad(dateUtcDate(date), 2, fill));
|
|
204
|
+
break;
|
|
205
|
+
case "DDD":
|
|
206
|
+
parts.push(pad(dayOfYear(date), 3, fill));
|
|
207
|
+
break;
|
|
208
|
+
case "D":
|
|
209
|
+
parts.push(String(dateUtcDay(date) + 1));
|
|
210
|
+
break;
|
|
211
|
+
case "Q":
|
|
212
|
+
parts.push(String(Math.floor(dateUtcMonth(date) / 3) + 1));
|
|
213
|
+
break;
|
|
214
|
+
case "IW":
|
|
215
|
+
parts.push(pad(isoWeek(date), 2, fill));
|
|
216
|
+
break;
|
|
217
|
+
case "J":
|
|
218
|
+
parts.push(String(Math.floor(dateMilliseconds(date) / 86_400_000) + 2_440_588));
|
|
219
|
+
break;
|
|
220
|
+
case "HH24":
|
|
221
|
+
parts.push(pad(hours, 2, fill));
|
|
222
|
+
break;
|
|
223
|
+
case "HH12":
|
|
224
|
+
case "HH":
|
|
225
|
+
parts.push(pad(hours % 12 === 0 ? 12 : hours % 12, 2, fill));
|
|
226
|
+
break;
|
|
227
|
+
case "MI":
|
|
228
|
+
parts.push(pad(dateUtcMinutes(date), 2, fill));
|
|
229
|
+
break;
|
|
230
|
+
case "SS":
|
|
231
|
+
parts.push(pad(dateUtcSeconds(date), 2, fill));
|
|
232
|
+
break;
|
|
233
|
+
case "MS":
|
|
234
|
+
parts.push(String(date.getUTCMilliseconds()).padStart(3, "0"));
|
|
235
|
+
break;
|
|
236
|
+
case "US":
|
|
237
|
+
parts.push(String(date.getUTCMilliseconds() * 1000).padStart(6, "0"));
|
|
238
|
+
break;
|
|
239
|
+
case "TZ":
|
|
240
|
+
parts.push("UTC");
|
|
241
|
+
break;
|
|
242
|
+
case "AM":
|
|
243
|
+
case "PM":
|
|
244
|
+
case "am":
|
|
245
|
+
case "pm":
|
|
246
|
+
parts.push(cased(hours < 12 ? "AM" : "PM", token));
|
|
247
|
+
break;
|
|
248
|
+
case "A.M.":
|
|
249
|
+
case "P.M.":
|
|
250
|
+
parts.push(hours < 12 ? "A.M." : "P.M.");
|
|
251
|
+
break;
|
|
252
|
+
case "MONTH":
|
|
253
|
+
case "Month":
|
|
254
|
+
case "month": {
|
|
255
|
+
const name = cased(MONTHS[dateUtcMonth(date)] ?? "", token);
|
|
256
|
+
parts.push(fill ? name : name.padEnd(9, " "));
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
case "MON":
|
|
260
|
+
case "Mon":
|
|
261
|
+
case "mon":
|
|
262
|
+
parts.push(cased((MONTHS[dateUtcMonth(date)] ?? "").slice(0, 3), token));
|
|
263
|
+
break;
|
|
264
|
+
case "DAY":
|
|
265
|
+
case "Day":
|
|
266
|
+
case "day": {
|
|
267
|
+
const name = cased(DAYS[dateUtcDay(date)] ?? "", token);
|
|
268
|
+
parts.push(fill ? name : name.padEnd(9, " "));
|
|
269
|
+
break;
|
|
270
|
+
}
|
|
271
|
+
case "DY":
|
|
272
|
+
case "Dy":
|
|
273
|
+
case "dy":
|
|
274
|
+
parts.push(cased((DAYS[dateUtcDay(date)] ?? "").slice(0, 3), token));
|
|
275
|
+
break;
|
|
276
|
+
default:
|
|
277
|
+
parts.push(token);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return parts.join("");
|
|
281
|
+
}
|
|
282
|
+
/** Reads datetime text against a TO_DATE / TO_TIMESTAMP template; fields not named default. */
|
|
283
|
+
function parseDatetime(name, input, template) {
|
|
284
|
+
let year = 1970;
|
|
285
|
+
let month = 1;
|
|
286
|
+
let day = 1;
|
|
287
|
+
let hours = 0;
|
|
288
|
+
let minutes = 0;
|
|
289
|
+
let seconds = 0;
|
|
290
|
+
let milliseconds = 0;
|
|
291
|
+
let pm;
|
|
292
|
+
let cursor = 0;
|
|
293
|
+
const digits = (width, label) => {
|
|
294
|
+
const match = /^\d+/.exec(input.slice(cursor, cursor + width));
|
|
295
|
+
if (match === null)
|
|
296
|
+
throw new TypeError(`${name} could not read ${label} at position ${String(cursor + 1)}`);
|
|
297
|
+
cursor += match[0].length;
|
|
298
|
+
return Number(match[0]);
|
|
299
|
+
};
|
|
300
|
+
const word = (options, label) => {
|
|
301
|
+
const rest = input.slice(cursor).toLowerCase();
|
|
302
|
+
const found = options.findIndex((option) => rest.startsWith(option.toLowerCase()));
|
|
303
|
+
if (found === -1)
|
|
304
|
+
throw new TypeError(`${name} could not read ${label} at position ${String(cursor + 1)}`);
|
|
305
|
+
cursor += options[found]?.length ?? 0;
|
|
306
|
+
return found;
|
|
307
|
+
};
|
|
308
|
+
for (const item of dateTemplate(template)) {
|
|
309
|
+
if (item.literal !== undefined) {
|
|
310
|
+
// Separators in the template match one separator in the input, whatever character it is.
|
|
311
|
+
if (cursor < input.length && !/\d/.test(input[cursor] ?? ""))
|
|
312
|
+
cursor += item.literal.length;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
switch (item.token) {
|
|
316
|
+
case "YYYY":
|
|
317
|
+
year = digits(4, "the year");
|
|
318
|
+
break;
|
|
319
|
+
case "YY":
|
|
320
|
+
year = 2000 + digits(2, "the year");
|
|
321
|
+
break;
|
|
322
|
+
case "MM":
|
|
323
|
+
month = digits(2, "the month");
|
|
324
|
+
break;
|
|
325
|
+
case "MONTH":
|
|
326
|
+
case "Month":
|
|
327
|
+
case "month":
|
|
328
|
+
month = word(MONTHS, "the month name") + 1;
|
|
329
|
+
break;
|
|
330
|
+
case "MON":
|
|
331
|
+
case "Mon":
|
|
332
|
+
case "mon":
|
|
333
|
+
month =
|
|
334
|
+
word(MONTHS.map((entry) => entry.slice(0, 3)), "the month name") + 1;
|
|
335
|
+
break;
|
|
336
|
+
case "DD":
|
|
337
|
+
day = digits(2, "the day");
|
|
338
|
+
break;
|
|
339
|
+
case "DDD": {
|
|
340
|
+
const ordinal = digits(3, "the day of year");
|
|
341
|
+
const date = new Date(Date.UTC(year, 0, ordinal));
|
|
342
|
+
month = date.getUTCMonth() + 1;
|
|
343
|
+
day = date.getUTCDate();
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
case "HH24":
|
|
347
|
+
case "HH12":
|
|
348
|
+
case "HH":
|
|
349
|
+
hours = digits(2, "the hour");
|
|
350
|
+
break;
|
|
351
|
+
case "MI":
|
|
352
|
+
minutes = digits(2, "the minutes");
|
|
353
|
+
break;
|
|
354
|
+
case "SS":
|
|
355
|
+
seconds = digits(2, "the seconds");
|
|
356
|
+
break;
|
|
357
|
+
case "MS":
|
|
358
|
+
milliseconds = digits(3, "the milliseconds");
|
|
359
|
+
break;
|
|
360
|
+
case "US":
|
|
361
|
+
milliseconds = Math.floor(digits(6, "the microseconds") / 1000);
|
|
362
|
+
break;
|
|
363
|
+
case "AM":
|
|
364
|
+
case "PM":
|
|
365
|
+
case "am":
|
|
366
|
+
case "pm":
|
|
367
|
+
pm = word(["am", "pm"], "the meridiem") === 1;
|
|
368
|
+
break;
|
|
369
|
+
case "A.M.":
|
|
370
|
+
case "P.M.":
|
|
371
|
+
pm = word(["a.m.", "p.m."], "the meridiem") === 1;
|
|
372
|
+
break;
|
|
373
|
+
case "DAY":
|
|
374
|
+
case "Day":
|
|
375
|
+
case "day":
|
|
376
|
+
word(DAYS, "the day name");
|
|
377
|
+
break;
|
|
378
|
+
case "DY":
|
|
379
|
+
case "Dy":
|
|
380
|
+
case "dy":
|
|
381
|
+
word(DAYS.map((entry) => entry.slice(0, 3)), "the day name");
|
|
382
|
+
break;
|
|
383
|
+
case "TZ":
|
|
384
|
+
cursor = input.length;
|
|
385
|
+
break;
|
|
386
|
+
default:
|
|
387
|
+
throw new TypeError(`${name} does not read the ${item.token ?? ""} template field`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
if (pm !== undefined)
|
|
391
|
+
hours = pm ? (hours % 12) + 12 : hours % 12;
|
|
392
|
+
const date = new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds, milliseconds));
|
|
393
|
+
if (!Number.isFinite(date.getTime()) ||
|
|
394
|
+
date.getUTCMonth() !== month - 1 ||
|
|
395
|
+
date.getUTCDate() !== day ||
|
|
396
|
+
hours > 23 ||
|
|
397
|
+
minutes > 59 ||
|
|
398
|
+
seconds > 59) {
|
|
399
|
+
throw new TypeError(`${name} read an invalid date from ${input}`);
|
|
400
|
+
}
|
|
401
|
+
return date;
|
|
402
|
+
}
|
|
403
|
+
// --- Numeric formatting (TO_CHAR(number, template)) ------------------------------------------
|
|
404
|
+
/**
|
|
405
|
+
* The digit templates in everyday use: 9 and 0 digit positions, a decimal point, group
|
|
406
|
+
* separators, FM to drop padding, and S / MI for an explicit sign. Other pattern letters
|
|
407
|
+
* (EEEE, RN, V, PL, L, TH) are refused rather than rendered wrongly.
|
|
408
|
+
*/
|
|
409
|
+
function formatNumber(value, template) {
|
|
410
|
+
const fill = template.includes("FM");
|
|
411
|
+
const body = template.replace(/FM/g, "");
|
|
412
|
+
const unsupported = /[^90.,SMI\s]/.exec(body);
|
|
413
|
+
if (unsupported !== null) {
|
|
414
|
+
throw new TypeError(`TO_CHAR does not support the ${unsupported[0]} numeric template element`);
|
|
415
|
+
}
|
|
416
|
+
const signStyle = body.includes("S") ? "S" : body.includes("MI") ? "MI" : "default";
|
|
417
|
+
const pattern = body.replace(/S|MI/g, "");
|
|
418
|
+
const [integerPattern = "", fractionPattern = ""] = pattern.split(".");
|
|
419
|
+
const fractionDigits = (fractionPattern.match(/[90]/g) ?? []).length;
|
|
420
|
+
const integerSlots = (integerPattern.match(/[90]/g) ?? []).length;
|
|
421
|
+
// PostgreSQL formats the double's exact binary value and breaks an exact tie to even: 0.075
|
|
422
|
+
// is a hair below the tie and renders as .07 under '9.99', while 77.25 is exact and renders
|
|
423
|
+
// as 77.2 under '9999.9'. toFixed rounds by the exact value but breaks ties upward, so ties
|
|
424
|
+
// are detected on a long exact expansion and settled here.
|
|
425
|
+
const magnitude = Math.abs(value);
|
|
426
|
+
const expansion = magnitude.toFixed(Math.min(fractionDigits + 30, 100));
|
|
427
|
+
const cut = expansion.indexOf(".") + 1 + fractionDigits;
|
|
428
|
+
const tie = /^50*$/.test(expansion.slice(cut));
|
|
429
|
+
let rounded = magnitude.toFixed(fractionDigits);
|
|
430
|
+
if (tie) {
|
|
431
|
+
const kept = expansion.slice(0, cut).replace(/\.$/, "");
|
|
432
|
+
const lastDigit = Number(kept.at(-1) ?? "0");
|
|
433
|
+
rounded =
|
|
434
|
+
lastDigit % 2 === 0
|
|
435
|
+
? Number(kept).toFixed(fractionDigits)
|
|
436
|
+
: (Number(kept) + 10 ** -fractionDigits).toFixed(fractionDigits);
|
|
437
|
+
}
|
|
438
|
+
const [wholeText = "0", fractionText = ""] = rounded.split(".");
|
|
439
|
+
if (wholeText.length > integerSlots && !(wholeText === "0" && integerSlots === 0)) {
|
|
440
|
+
return "#".repeat(pattern.length + (signStyle === "default" ? 1 : 0));
|
|
441
|
+
}
|
|
442
|
+
// A zero integer part prints nothing when the template continues with a fraction (' .5'),
|
|
443
|
+
// and a single 0 otherwise; every explicit 0 slot then forces its digit.
|
|
444
|
+
const digits = wholeText === "0" && fractionDigits > 0 ? [] : characters(wholeText);
|
|
445
|
+
const output = [];
|
|
446
|
+
let index = digits.length - 1;
|
|
447
|
+
let forced = false;
|
|
448
|
+
for (const symbol of characters(integerPattern).reverse()) {
|
|
449
|
+
if (symbol === "9" || symbol === "0") {
|
|
450
|
+
if (index >= 0) {
|
|
451
|
+
output.unshift(digits[index] ?? "0");
|
|
452
|
+
index -= 1;
|
|
453
|
+
}
|
|
454
|
+
else if (symbol === "0" || forced) {
|
|
455
|
+
output.unshift("0");
|
|
456
|
+
forced = true;
|
|
457
|
+
}
|
|
458
|
+
else if (!fill) {
|
|
459
|
+
output.unshift(" ");
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
else if (symbol === ",") {
|
|
463
|
+
const more = index >= 0 || forced;
|
|
464
|
+
if (more)
|
|
465
|
+
output.unshift(",");
|
|
466
|
+
else if (!fill)
|
|
467
|
+
output.unshift(" ");
|
|
468
|
+
}
|
|
469
|
+
else if (symbol !== " ") {
|
|
470
|
+
output.unshift(symbol);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
// The 0 slots to the left of the highest forced slot are also forced.
|
|
474
|
+
let text = output.join("");
|
|
475
|
+
if (integerPattern.includes("0")) {
|
|
476
|
+
const firstZero = characters(integerPattern).findIndex((symbol) => symbol === "0");
|
|
477
|
+
const slotsFromFirstZero = (integerPattern.slice(firstZero).match(/[90]/g) ?? []).length;
|
|
478
|
+
const rendered = text.replace(/ /g, "");
|
|
479
|
+
if (rendered.replace(/,/g, "").length < slotsFromFirstZero) {
|
|
480
|
+
const needed = slotsFromFirstZero - rendered.replace(/,/g, "").length;
|
|
481
|
+
text =
|
|
482
|
+
(fill ? "" : " ".repeat(Math.max(integerSlots - slotsFromFirstZero, 0))) +
|
|
483
|
+
"0".repeat(needed) +
|
|
484
|
+
rendered;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (fractionDigits > 0)
|
|
488
|
+
text += `.${fractionText}`;
|
|
489
|
+
// The sign is the value's, even when the digits round to zero: -0.001 and -0 render with '-'.
|
|
490
|
+
const negative = value < 0 || Object.is(value, -0);
|
|
491
|
+
if (signStyle === "MI") {
|
|
492
|
+
const result = text + (negative ? "-" : fill ? "" : " ");
|
|
493
|
+
return fill ? result.trim() : result;
|
|
494
|
+
}
|
|
495
|
+
// The sign sits directly before the first digit; padding stays to its left.
|
|
496
|
+
const leading = text.length - text.trimStart().length;
|
|
497
|
+
const sign = negative ? "-" : signStyle === "S" ? "+" : fill ? "" : " ";
|
|
498
|
+
const result = " ".repeat(leading) + sign + text.trimStart();
|
|
499
|
+
return fill ? result.trim() : result;
|
|
500
|
+
}
|
|
501
|
+
// --- FORMAT ----------------------------------------------------------------------------------
|
|
502
|
+
function formatText(template, values) {
|
|
503
|
+
let next = 0;
|
|
504
|
+
return template.replace(/%(?:(\d+)\$)?([sIL%])/g, (_, position, kind) => {
|
|
505
|
+
if (kind === "%")
|
|
506
|
+
return "%";
|
|
507
|
+
const index = position === undefined ? next++ : Number(position) - 1;
|
|
508
|
+
if (index >= values.length)
|
|
509
|
+
throw new TypeError("FORMAT has too few arguments for its template");
|
|
510
|
+
const value = values[index];
|
|
511
|
+
if (kind === "s")
|
|
512
|
+
return value === null || value === undefined ? "" : rendered(value);
|
|
513
|
+
if (kind === "I") {
|
|
514
|
+
if (value === null || value === undefined)
|
|
515
|
+
throw new TypeError("FORMAT %I does not accept NULL");
|
|
516
|
+
const name = rendered(value);
|
|
517
|
+
return /^[a-z_][a-z0-9_]*$/.test(name) ? name : `"${name.replace(/"/g, '""')}"`;
|
|
518
|
+
}
|
|
519
|
+
if (value === null || value === undefined)
|
|
520
|
+
return "NULL";
|
|
521
|
+
return `'${rendered(value).replace(/'/g, "''")}'`;
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
// --- MD5 ---------------------------------------------------------------------------------------
|
|
525
|
+
/** RFC 1321, over the UTF-8 bytes of the input, rendered as 32 lowercase hex digits. */
|
|
526
|
+
function md5Hex(input) {
|
|
527
|
+
const bytes = new TextEncoder().encode(input);
|
|
528
|
+
const words = new Uint32Array(((bytes.length + 8) >> 6) * 16 + 16);
|
|
529
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
530
|
+
words[index >> 2] = (words[index >> 2] ?? 0) | ((bytes[index] ?? 0) << ((index % 4) * 8));
|
|
531
|
+
}
|
|
532
|
+
words[bytes.length >> 2] = (words[bytes.length >> 2] ?? 0) | (0x80 << ((bytes.length % 4) * 8));
|
|
533
|
+
const bitLength = bytes.length * 8;
|
|
534
|
+
words[words.length - 2] = bitLength >>> 0;
|
|
535
|
+
words[words.length - 1] = Math.floor(bitLength / 0x1_0000_0000);
|
|
536
|
+
const shifts = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
|
|
537
|
+
const constants = Array.from({ length: 64 }, (_, index) => Math.floor(Math.abs(Math.sin(index + 1)) * 0x1_0000_0000) >>> 0);
|
|
538
|
+
let a0 = 0x67452301;
|
|
539
|
+
let b0 = 0xefcdab89;
|
|
540
|
+
let c0 = 0x98badcfe;
|
|
541
|
+
let d0 = 0x10325476;
|
|
542
|
+
for (let chunk = 0; chunk < words.length; chunk += 16) {
|
|
543
|
+
let a = a0;
|
|
544
|
+
let b = b0;
|
|
545
|
+
let c = c0;
|
|
546
|
+
let d = d0;
|
|
547
|
+
for (let round = 0; round < 64; round += 1) {
|
|
548
|
+
let f;
|
|
549
|
+
let g;
|
|
550
|
+
if (round < 16) {
|
|
551
|
+
f = (b & c) | (~b & d);
|
|
552
|
+
g = round;
|
|
553
|
+
}
|
|
554
|
+
else if (round < 32) {
|
|
555
|
+
f = (d & b) | (~d & c);
|
|
556
|
+
g = (5 * round + 1) % 16;
|
|
557
|
+
}
|
|
558
|
+
else if (round < 48) {
|
|
559
|
+
f = b ^ c ^ d;
|
|
560
|
+
g = (3 * round + 5) % 16;
|
|
561
|
+
}
|
|
562
|
+
else {
|
|
563
|
+
f = c ^ (b | ~d);
|
|
564
|
+
g = (7 * round) % 16;
|
|
565
|
+
}
|
|
566
|
+
const shift = shifts[(round >> 4) * 4 + (round % 4)] ?? 0;
|
|
567
|
+
const sum = (a + f + (constants[round] ?? 0) + (words[chunk + g] ?? 0)) >>> 0;
|
|
568
|
+
a = d;
|
|
569
|
+
d = c;
|
|
570
|
+
c = b;
|
|
571
|
+
b = (b + ((sum << shift) | (sum >>> (32 - shift)))) >>> 0;
|
|
572
|
+
}
|
|
573
|
+
a0 = (a0 + a) >>> 0;
|
|
574
|
+
b0 = (b0 + b) >>> 0;
|
|
575
|
+
c0 = (c0 + c) >>> 0;
|
|
576
|
+
d0 = (d0 + d) >>> 0;
|
|
577
|
+
}
|
|
578
|
+
return [a0, b0, c0, d0]
|
|
579
|
+
.map((word) => [0, 8, 16, 24]
|
|
580
|
+
.map((offset) => ((word >>> offset) & 0xff).toString(16).padStart(2, "0"))
|
|
581
|
+
.join(""))
|
|
582
|
+
.join("");
|
|
583
|
+
}
|
|
584
|
+
// --- Regular expressions -----------------------------------------------------------------------
|
|
585
|
+
function regexFlags(name, value) {
|
|
586
|
+
if (value === null || value === undefined)
|
|
587
|
+
return "";
|
|
588
|
+
const flags = text(name, value);
|
|
589
|
+
for (const flag of flags) {
|
|
590
|
+
if (flag !== "i" && flag !== "g" && flag !== "n" && flag !== "c") {
|
|
591
|
+
throw new TypeError(`${name} does not support the ${flag} flag`);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return flags;
|
|
595
|
+
}
|
|
596
|
+
/** PostgreSQL replacement text: \1 back-references and \& become JavaScript's $1 and $&. */
|
|
597
|
+
function replacementText(value) {
|
|
598
|
+
return value
|
|
599
|
+
.replace(/\$/g, "$$$$")
|
|
600
|
+
.replace(/\\(\d)/g, "$$$1")
|
|
601
|
+
.replace(/\\&/g, "$$&")
|
|
602
|
+
.replace(/\\\\/g, "\\");
|
|
603
|
+
}
|
|
604
|
+
/** AGE(later, earlier): the calendar difference PostgreSQL reports, in months, days, and time. */
|
|
605
|
+
function ageInterval(later, earlier) {
|
|
606
|
+
let sign = 1;
|
|
607
|
+
let a = later;
|
|
608
|
+
let b = earlier;
|
|
609
|
+
if (dateMilliseconds(a) < dateMilliseconds(b)) {
|
|
610
|
+
sign = -1;
|
|
611
|
+
[a, b] = [b, a];
|
|
612
|
+
}
|
|
613
|
+
let months = (dateUtcFullYear(a) - dateUtcFullYear(b)) * 12 + (dateUtcMonth(a) - dateUtcMonth(b));
|
|
614
|
+
let days = dateUtcDate(a) - dateUtcDate(b);
|
|
615
|
+
let milliseconds = dateMilliseconds(a) -
|
|
616
|
+
Date.UTC(dateUtcFullYear(a), dateUtcMonth(a), dateUtcDate(a)) -
|
|
617
|
+
(dateMilliseconds(b) - Date.UTC(dateUtcFullYear(b), dateUtcMonth(b), dateUtcDate(b)));
|
|
618
|
+
if (milliseconds < 0) {
|
|
619
|
+
milliseconds += 86_400_000;
|
|
620
|
+
days -= 1;
|
|
621
|
+
}
|
|
622
|
+
if (days < 0) {
|
|
623
|
+
// Borrow the length of the earlier date's month, as PostgreSQL's timestamp_age does.
|
|
624
|
+
const earlierMonthDays = new Date(Date.UTC(dateUtcFullYear(b), dateUtcMonth(b) + 1, 0)).getUTCDate();
|
|
625
|
+
days += earlierMonthDays;
|
|
626
|
+
months -= 1;
|
|
627
|
+
}
|
|
628
|
+
return intervalDomainValue(`${String(sign * months)} months ${String(sign * days)} days ${String((sign * milliseconds) / 1000)} seconds`);
|
|
629
|
+
}
|
|
630
|
+
// --- The registry --------------------------------------------------------------------------
|
|
631
|
+
function nullish(value) {
|
|
632
|
+
return value === null || value === undefined;
|
|
633
|
+
}
|
|
634
|
+
export const simpleScalarFunctions = new Map([
|
|
635
|
+
// Strings
|
|
636
|
+
[
|
|
637
|
+
"CONCAT",
|
|
638
|
+
{
|
|
639
|
+
minArgs: 1,
|
|
640
|
+
maxArgs: Number.POSITIVE_INFINITY,
|
|
641
|
+
returns: "string",
|
|
642
|
+
nullOnNull: false,
|
|
643
|
+
evaluate: (values) => bounded(values
|
|
644
|
+
.filter((value) => !nullish(value))
|
|
645
|
+
.map(rendered)
|
|
646
|
+
.join(""), "CONCAT"),
|
|
647
|
+
},
|
|
648
|
+
],
|
|
649
|
+
[
|
|
650
|
+
"CONCAT_WS",
|
|
651
|
+
{
|
|
652
|
+
minArgs: 2,
|
|
653
|
+
maxArgs: Number.POSITIVE_INFINITY,
|
|
654
|
+
returns: "string",
|
|
655
|
+
nullOnNull: false,
|
|
656
|
+
evaluate: (values) => nullish(values[0])
|
|
657
|
+
? null
|
|
658
|
+
: bounded(values
|
|
659
|
+
.slice(1)
|
|
660
|
+
.filter((value) => !nullish(value))
|
|
661
|
+
.map(rendered)
|
|
662
|
+
.join(text("CONCAT_WS", values[0])), "CONCAT_WS"),
|
|
663
|
+
},
|
|
664
|
+
],
|
|
665
|
+
[
|
|
666
|
+
"LEFT",
|
|
667
|
+
{
|
|
668
|
+
minArgs: 2,
|
|
669
|
+
maxArgs: 2,
|
|
670
|
+
returns: "string",
|
|
671
|
+
evaluate: (values) => {
|
|
672
|
+
const source = characters(text("LEFT", values[0]));
|
|
673
|
+
const count = integer("LEFT", values[1]);
|
|
674
|
+
return bounded((count >= 0
|
|
675
|
+
? source.slice(0, count)
|
|
676
|
+
: source.slice(0, Math.max(source.length + count, 0))).join(""), "LEFT");
|
|
677
|
+
},
|
|
678
|
+
},
|
|
679
|
+
],
|
|
680
|
+
[
|
|
681
|
+
"RIGHT",
|
|
682
|
+
{
|
|
683
|
+
minArgs: 2,
|
|
684
|
+
maxArgs: 2,
|
|
685
|
+
returns: "string",
|
|
686
|
+
evaluate: (values) => {
|
|
687
|
+
const source = characters(text("RIGHT", values[0]));
|
|
688
|
+
const count = integer("RIGHT", values[1]);
|
|
689
|
+
const kept = count >= 0
|
|
690
|
+
? source.slice(Math.max(source.length - count, 0))
|
|
691
|
+
: source.slice(Math.min(-count, source.length));
|
|
692
|
+
return bounded(kept.join(""), "RIGHT");
|
|
693
|
+
},
|
|
694
|
+
},
|
|
695
|
+
],
|
|
696
|
+
[
|
|
697
|
+
"REVERSE",
|
|
698
|
+
{
|
|
699
|
+
minArgs: 1,
|
|
700
|
+
maxArgs: 1,
|
|
701
|
+
returns: "string",
|
|
702
|
+
evaluate: (values) => bounded(characters(text("REVERSE", values[0])).reverse().join(""), "REVERSE"),
|
|
703
|
+
},
|
|
704
|
+
],
|
|
705
|
+
[
|
|
706
|
+
"REPEAT",
|
|
707
|
+
{
|
|
708
|
+
minArgs: 2,
|
|
709
|
+
maxArgs: 2,
|
|
710
|
+
returns: "string",
|
|
711
|
+
evaluate: (values) => {
|
|
712
|
+
const source = text("REPEAT", values[0]);
|
|
713
|
+
const count = integer("REPEAT", values[1]);
|
|
714
|
+
if (count <= 0)
|
|
715
|
+
return protectedSqlTextValue("");
|
|
716
|
+
if (source.length * count > MAX_SQL_SCALAR_RESULT_CHARACTERS) {
|
|
717
|
+
throw new RangeError(`REPEAT result exceeds ${String(MAX_SQL_SCALAR_RESULT_CHARACTERS)} characters`);
|
|
718
|
+
}
|
|
719
|
+
return protectedSqlTextValue(source.repeat(count));
|
|
720
|
+
},
|
|
721
|
+
},
|
|
722
|
+
],
|
|
723
|
+
[
|
|
724
|
+
"INITCAP",
|
|
725
|
+
{
|
|
726
|
+
minArgs: 1,
|
|
727
|
+
maxArgs: 1,
|
|
728
|
+
returns: "string",
|
|
729
|
+
evaluate: (values) => bounded(text("INITCAP", values[0])
|
|
730
|
+
.toLowerCase()
|
|
731
|
+
.replace(/(^|[^\p{L}\p{N}])(\p{L})/gu, (_, before, letter) => before + letter.toUpperCase()), "INITCAP"),
|
|
732
|
+
},
|
|
733
|
+
],
|
|
734
|
+
[
|
|
735
|
+
"SPLIT_PART",
|
|
736
|
+
{
|
|
737
|
+
minArgs: 3,
|
|
738
|
+
maxArgs: 3,
|
|
739
|
+
returns: "string",
|
|
740
|
+
evaluate: (values) => {
|
|
741
|
+
const source = text("SPLIT_PART", values[0]);
|
|
742
|
+
const delimiter = text("SPLIT_PART", values[1]);
|
|
743
|
+
const position = integer("SPLIT_PART", values[2]);
|
|
744
|
+
if (position === 0)
|
|
745
|
+
throw new TypeError("SPLIT_PART field position must not be zero");
|
|
746
|
+
const fields = delimiter === "" ? [source] : source.split(delimiter);
|
|
747
|
+
const index = position > 0 ? position - 1 : fields.length + position;
|
|
748
|
+
return protectedSqlTextValue(fields[index] ?? "");
|
|
749
|
+
},
|
|
750
|
+
},
|
|
751
|
+
],
|
|
752
|
+
[
|
|
753
|
+
"STRPOS",
|
|
754
|
+
{
|
|
755
|
+
minArgs: 2,
|
|
756
|
+
maxArgs: 2,
|
|
757
|
+
returns: "number",
|
|
758
|
+
evaluate: (values) => {
|
|
759
|
+
const haystack = text("STRPOS", values[0]);
|
|
760
|
+
const index = haystack.indexOf(text("STRPOS", values[1]));
|
|
761
|
+
return index === -1 ? 0 : characters(haystack.slice(0, index)).length + 1;
|
|
762
|
+
},
|
|
763
|
+
},
|
|
764
|
+
],
|
|
765
|
+
[
|
|
766
|
+
"STARTS_WITH",
|
|
767
|
+
{
|
|
768
|
+
minArgs: 2,
|
|
769
|
+
maxArgs: 2,
|
|
770
|
+
returns: "boolean",
|
|
771
|
+
evaluate: (values) => text("STARTS_WITH", values[0]).startsWith(text("STARTS_WITH", values[1])),
|
|
772
|
+
},
|
|
773
|
+
],
|
|
774
|
+
[
|
|
775
|
+
"TRANSLATE",
|
|
776
|
+
{
|
|
777
|
+
minArgs: 3,
|
|
778
|
+
maxArgs: 3,
|
|
779
|
+
returns: "string",
|
|
780
|
+
evaluate: (values) => {
|
|
781
|
+
const from = characters(text("TRANSLATE", values[1]));
|
|
782
|
+
const to = characters(text("TRANSLATE", values[2]));
|
|
783
|
+
const mapping = new Map(from.map((character, index) => [character, to[index] ?? ""]));
|
|
784
|
+
return bounded(characters(text("TRANSLATE", values[0]))
|
|
785
|
+
.map((character) => mapping.get(character) ?? character)
|
|
786
|
+
.join(""), "TRANSLATE");
|
|
787
|
+
},
|
|
788
|
+
},
|
|
789
|
+
],
|
|
790
|
+
[
|
|
791
|
+
"ASCII",
|
|
792
|
+
{
|
|
793
|
+
minArgs: 1,
|
|
794
|
+
maxArgs: 1,
|
|
795
|
+
returns: "number",
|
|
796
|
+
evaluate: (values) => text("ASCII", values[0]).codePointAt(0) ?? 0,
|
|
797
|
+
},
|
|
798
|
+
],
|
|
799
|
+
[
|
|
800
|
+
"CHR",
|
|
801
|
+
{
|
|
802
|
+
minArgs: 1,
|
|
803
|
+
maxArgs: 1,
|
|
804
|
+
returns: "string",
|
|
805
|
+
evaluate: (values) => {
|
|
806
|
+
const code = integer("CHR", values[0]);
|
|
807
|
+
if (code <= 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) {
|
|
808
|
+
throw new TypeError(`CHR has no character for code ${String(code)}`);
|
|
809
|
+
}
|
|
810
|
+
return protectedSqlTextValue(String.fromCodePoint(code));
|
|
811
|
+
},
|
|
812
|
+
},
|
|
813
|
+
],
|
|
814
|
+
[
|
|
815
|
+
"BTRIM",
|
|
816
|
+
{
|
|
817
|
+
minArgs: 1,
|
|
818
|
+
maxArgs: 2,
|
|
819
|
+
returns: "string",
|
|
820
|
+
evaluate: (values) => {
|
|
821
|
+
// PostgreSQL's BTRIM removes any character of the set from both ends.
|
|
822
|
+
const set = new Set(characters(nullish(values[1]) ? " " : text("BTRIM", values[1])));
|
|
823
|
+
const source = characters(text("BTRIM", values[0]));
|
|
824
|
+
let start = 0;
|
|
825
|
+
let end = source.length;
|
|
826
|
+
while (start < end && set.has(source[start] ?? ""))
|
|
827
|
+
start += 1;
|
|
828
|
+
while (end > start && set.has(source[end - 1] ?? ""))
|
|
829
|
+
end -= 1;
|
|
830
|
+
return protectedSqlTextValue(source.slice(start, end).join(""));
|
|
831
|
+
},
|
|
832
|
+
},
|
|
833
|
+
],
|
|
834
|
+
[
|
|
835
|
+
"MD5",
|
|
836
|
+
{
|
|
837
|
+
minArgs: 1,
|
|
838
|
+
maxArgs: 1,
|
|
839
|
+
returns: "string",
|
|
840
|
+
evaluate: (values) => protectedSqlTextValue(md5Hex(text("MD5", values[0]))),
|
|
841
|
+
},
|
|
842
|
+
],
|
|
843
|
+
[
|
|
844
|
+
"FORMAT",
|
|
845
|
+
{
|
|
846
|
+
minArgs: 1,
|
|
847
|
+
maxArgs: Number.POSITIVE_INFINITY,
|
|
848
|
+
returns: "string",
|
|
849
|
+
nullOnNull: false,
|
|
850
|
+
evaluate: (values) => {
|
|
851
|
+
if (nullish(values[0]))
|
|
852
|
+
return null;
|
|
853
|
+
return bounded(formatText(text("FORMAT", values[0]), values.slice(1)), "FORMAT");
|
|
854
|
+
},
|
|
855
|
+
},
|
|
856
|
+
],
|
|
857
|
+
[
|
|
858
|
+
"REGEXP_REPLACE",
|
|
859
|
+
{
|
|
860
|
+
minArgs: 3,
|
|
861
|
+
maxArgs: 4,
|
|
862
|
+
returns: "string",
|
|
863
|
+
evaluate: (values) => {
|
|
864
|
+
const flags = regexFlags("REGEXP_REPLACE", values[3]);
|
|
865
|
+
const expression = compileRegexPattern(text("REGEXP_REPLACE", values[1]), flags);
|
|
866
|
+
const replacement = replacementText(text("REGEXP_REPLACE", values[2]));
|
|
867
|
+
return bounded(text("REGEXP_REPLACE", values[0]).replace(expression, replacement), "REGEXP_REPLACE");
|
|
868
|
+
},
|
|
869
|
+
},
|
|
870
|
+
],
|
|
871
|
+
[
|
|
872
|
+
"MINNOW_REGEX_MATCH",
|
|
873
|
+
{
|
|
874
|
+
minArgs: 3,
|
|
875
|
+
maxArgs: 3,
|
|
876
|
+
returns: "boolean",
|
|
877
|
+
evaluate: (values) => compileRegexPattern(text("~", values[1]), regexFlags("~", values[2])).test(text("~", values[0])),
|
|
878
|
+
},
|
|
879
|
+
],
|
|
880
|
+
// Math
|
|
881
|
+
[
|
|
882
|
+
"EXP",
|
|
883
|
+
{
|
|
884
|
+
minArgs: 1,
|
|
885
|
+
maxArgs: 1,
|
|
886
|
+
returns: "number",
|
|
887
|
+
evaluate: (values) => finite("EXP", Math.exp(number("EXP", values[0]))),
|
|
888
|
+
},
|
|
889
|
+
],
|
|
890
|
+
[
|
|
891
|
+
"LN",
|
|
892
|
+
{
|
|
893
|
+
minArgs: 1,
|
|
894
|
+
maxArgs: 1,
|
|
895
|
+
returns: "number",
|
|
896
|
+
evaluate: (values) => {
|
|
897
|
+
const operand = number("LN", values[0]);
|
|
898
|
+
if (operand <= 0)
|
|
899
|
+
throw new TypeError("LN requires a positive number");
|
|
900
|
+
return Math.log(operand);
|
|
901
|
+
},
|
|
902
|
+
},
|
|
903
|
+
],
|
|
904
|
+
[
|
|
905
|
+
"LOG",
|
|
906
|
+
{
|
|
907
|
+
minArgs: 1,
|
|
908
|
+
maxArgs: 2,
|
|
909
|
+
returns: "number",
|
|
910
|
+
evaluate: (values) => {
|
|
911
|
+
// LOG(x) is base 10, LOG(b, x) an explicit base, as in PostgreSQL.
|
|
912
|
+
const operand = number("LOG", values.length > 1 ? values[1] : values[0]);
|
|
913
|
+
const base = values.length > 1 ? number("LOG", values[0]) : 10;
|
|
914
|
+
if (operand <= 0 || base <= 0 || base === 1)
|
|
915
|
+
throw new TypeError("LOG requires positive arguments");
|
|
916
|
+
return Math.log(operand) / Math.log(base);
|
|
917
|
+
},
|
|
918
|
+
},
|
|
919
|
+
],
|
|
920
|
+
[
|
|
921
|
+
"LOG10",
|
|
922
|
+
{
|
|
923
|
+
minArgs: 1,
|
|
924
|
+
maxArgs: 1,
|
|
925
|
+
returns: "number",
|
|
926
|
+
evaluate: (values) => {
|
|
927
|
+
const operand = number("LOG10", values[0]);
|
|
928
|
+
if (operand <= 0)
|
|
929
|
+
throw new TypeError("LOG10 requires a positive number");
|
|
930
|
+
return Math.log10(operand);
|
|
931
|
+
},
|
|
932
|
+
},
|
|
933
|
+
],
|
|
934
|
+
[
|
|
935
|
+
"SIGN",
|
|
936
|
+
{
|
|
937
|
+
minArgs: 1,
|
|
938
|
+
maxArgs: 1,
|
|
939
|
+
returns: "number",
|
|
940
|
+
evaluate: (values) => Math.sign(number("SIGN", values[0])),
|
|
941
|
+
},
|
|
942
|
+
],
|
|
943
|
+
[
|
|
944
|
+
"TRUNC",
|
|
945
|
+
{
|
|
946
|
+
minArgs: 1,
|
|
947
|
+
maxArgs: 2,
|
|
948
|
+
returns: "number",
|
|
949
|
+
evaluate: (values) => {
|
|
950
|
+
const operand = number("TRUNC", values[0]);
|
|
951
|
+
const digits = values.length > 1 ? integer("TRUNC", values[1]) : 0;
|
|
952
|
+
const scale = 10 ** digits;
|
|
953
|
+
return Math.trunc(operand * scale) / scale;
|
|
954
|
+
},
|
|
955
|
+
},
|
|
956
|
+
],
|
|
957
|
+
["PI", { minArgs: 0, maxArgs: 0, returns: "number", evaluate: () => Math.PI }],
|
|
958
|
+
[
|
|
959
|
+
"CBRT",
|
|
960
|
+
{
|
|
961
|
+
minArgs: 1,
|
|
962
|
+
maxArgs: 1,
|
|
963
|
+
returns: "number",
|
|
964
|
+
evaluate: (values) => Math.cbrt(number("CBRT", values[0])),
|
|
965
|
+
},
|
|
966
|
+
],
|
|
967
|
+
[
|
|
968
|
+
"DIV",
|
|
969
|
+
{
|
|
970
|
+
minArgs: 2,
|
|
971
|
+
maxArgs: 2,
|
|
972
|
+
returns: "number",
|
|
973
|
+
evaluate: (values) => {
|
|
974
|
+
const divisor = number("DIV", values[1]);
|
|
975
|
+
if (divisor === 0)
|
|
976
|
+
throw new TypeError("DIV by zero");
|
|
977
|
+
return Math.trunc(number("DIV", values[0]) / divisor);
|
|
978
|
+
},
|
|
979
|
+
},
|
|
980
|
+
],
|
|
981
|
+
[
|
|
982
|
+
"WIDTH_BUCKET",
|
|
983
|
+
{
|
|
984
|
+
minArgs: 4,
|
|
985
|
+
maxArgs: 4,
|
|
986
|
+
returns: "number",
|
|
987
|
+
evaluate: (values) => {
|
|
988
|
+
const operand = number("WIDTH_BUCKET", values[0]);
|
|
989
|
+
const low = number("WIDTH_BUCKET", values[1]);
|
|
990
|
+
const high = number("WIDTH_BUCKET", values[2]);
|
|
991
|
+
const count = integer("WIDTH_BUCKET", values[3]);
|
|
992
|
+
if (count <= 0)
|
|
993
|
+
throw new TypeError("WIDTH_BUCKET count must be positive");
|
|
994
|
+
if (low === high)
|
|
995
|
+
throw new TypeError("WIDTH_BUCKET bounds must differ");
|
|
996
|
+
if (low < high) {
|
|
997
|
+
if (operand < low)
|
|
998
|
+
return 0;
|
|
999
|
+
if (operand >= high)
|
|
1000
|
+
return count + 1;
|
|
1001
|
+
return Math.floor(((operand - low) / (high - low)) * count) + 1;
|
|
1002
|
+
}
|
|
1003
|
+
if (operand > low)
|
|
1004
|
+
return 0;
|
|
1005
|
+
if (operand <= high)
|
|
1006
|
+
return count + 1;
|
|
1007
|
+
return Math.floor(((low - operand) / (low - high)) * count) + 1;
|
|
1008
|
+
},
|
|
1009
|
+
},
|
|
1010
|
+
],
|
|
1011
|
+
[
|
|
1012
|
+
"SIN",
|
|
1013
|
+
{
|
|
1014
|
+
minArgs: 1,
|
|
1015
|
+
maxArgs: 1,
|
|
1016
|
+
returns: "number",
|
|
1017
|
+
evaluate: (values) => Math.sin(number("SIN", values[0])),
|
|
1018
|
+
},
|
|
1019
|
+
],
|
|
1020
|
+
[
|
|
1021
|
+
"COS",
|
|
1022
|
+
{
|
|
1023
|
+
minArgs: 1,
|
|
1024
|
+
maxArgs: 1,
|
|
1025
|
+
returns: "number",
|
|
1026
|
+
evaluate: (values) => Math.cos(number("COS", values[0])),
|
|
1027
|
+
},
|
|
1028
|
+
],
|
|
1029
|
+
[
|
|
1030
|
+
"TAN",
|
|
1031
|
+
{
|
|
1032
|
+
minArgs: 1,
|
|
1033
|
+
maxArgs: 1,
|
|
1034
|
+
returns: "number",
|
|
1035
|
+
evaluate: (values) => finite("TAN", Math.tan(number("TAN", values[0]))),
|
|
1036
|
+
},
|
|
1037
|
+
],
|
|
1038
|
+
[
|
|
1039
|
+
"ASIN",
|
|
1040
|
+
{
|
|
1041
|
+
minArgs: 1,
|
|
1042
|
+
maxArgs: 1,
|
|
1043
|
+
returns: "number",
|
|
1044
|
+
evaluate: (values) => finite("ASIN", Math.asin(number("ASIN", values[0]))),
|
|
1045
|
+
},
|
|
1046
|
+
],
|
|
1047
|
+
[
|
|
1048
|
+
"ACOS",
|
|
1049
|
+
{
|
|
1050
|
+
minArgs: 1,
|
|
1051
|
+
maxArgs: 1,
|
|
1052
|
+
returns: "number",
|
|
1053
|
+
evaluate: (values) => finite("ACOS", Math.acos(number("ACOS", values[0]))),
|
|
1054
|
+
},
|
|
1055
|
+
],
|
|
1056
|
+
[
|
|
1057
|
+
"ATAN",
|
|
1058
|
+
{
|
|
1059
|
+
minArgs: 1,
|
|
1060
|
+
maxArgs: 1,
|
|
1061
|
+
returns: "number",
|
|
1062
|
+
evaluate: (values) => Math.atan(number("ATAN", values[0])),
|
|
1063
|
+
},
|
|
1064
|
+
],
|
|
1065
|
+
[
|
|
1066
|
+
"ATAN2",
|
|
1067
|
+
{
|
|
1068
|
+
minArgs: 2,
|
|
1069
|
+
maxArgs: 2,
|
|
1070
|
+
returns: "number",
|
|
1071
|
+
evaluate: (values) => Math.atan2(number("ATAN2", values[0]), number("ATAN2", values[1])),
|
|
1072
|
+
},
|
|
1073
|
+
],
|
|
1074
|
+
[
|
|
1075
|
+
"DEGREES",
|
|
1076
|
+
{
|
|
1077
|
+
minArgs: 1,
|
|
1078
|
+
maxArgs: 1,
|
|
1079
|
+
returns: "number",
|
|
1080
|
+
evaluate: (values) => (number("DEGREES", values[0]) * 180) / Math.PI,
|
|
1081
|
+
},
|
|
1082
|
+
],
|
|
1083
|
+
[
|
|
1084
|
+
"RADIANS",
|
|
1085
|
+
{
|
|
1086
|
+
minArgs: 1,
|
|
1087
|
+
maxArgs: 1,
|
|
1088
|
+
returns: "number",
|
|
1089
|
+
evaluate: (values) => (number("RADIANS", values[0]) * Math.PI) / 180,
|
|
1090
|
+
},
|
|
1091
|
+
],
|
|
1092
|
+
// Datetime
|
|
1093
|
+
[
|
|
1094
|
+
"TO_CHAR",
|
|
1095
|
+
{
|
|
1096
|
+
minArgs: 2,
|
|
1097
|
+
maxArgs: 2,
|
|
1098
|
+
returns: "string",
|
|
1099
|
+
evaluate: (values) => {
|
|
1100
|
+
const template = text("TO_CHAR", values[1]);
|
|
1101
|
+
const external = externalSqlDomainValue(values[0]);
|
|
1102
|
+
if (typeof external === "number")
|
|
1103
|
+
return bounded(formatNumber(external, template), "TO_CHAR");
|
|
1104
|
+
if (typeof external === "string" &&
|
|
1105
|
+
!isDateDomainValue(values[0]) &&
|
|
1106
|
+
/^\s*[-+]?\d/.test(external) &&
|
|
1107
|
+
!/[-:]/.test(external.slice(1))) {
|
|
1108
|
+
return bounded(formatNumber(Number(external), template), "TO_CHAR");
|
|
1109
|
+
}
|
|
1110
|
+
return bounded(formatDatetime(datetime("TO_CHAR", values[0]), template), "TO_CHAR");
|
|
1111
|
+
},
|
|
1112
|
+
},
|
|
1113
|
+
],
|
|
1114
|
+
[
|
|
1115
|
+
"TO_DATE",
|
|
1116
|
+
{
|
|
1117
|
+
minArgs: 2,
|
|
1118
|
+
maxArgs: 2,
|
|
1119
|
+
returns: "date",
|
|
1120
|
+
evaluate: (values) => dateDomainValue(parseDatetime("TO_DATE", text("TO_DATE", values[0]), text("TO_DATE", values[1]))),
|
|
1121
|
+
},
|
|
1122
|
+
],
|
|
1123
|
+
[
|
|
1124
|
+
"TO_TIMESTAMP",
|
|
1125
|
+
{
|
|
1126
|
+
minArgs: 1,
|
|
1127
|
+
maxArgs: 2,
|
|
1128
|
+
returns: "datetime",
|
|
1129
|
+
evaluate: (values) => {
|
|
1130
|
+
if (values.length === 1) {
|
|
1131
|
+
// TO_TIMESTAMP(seconds since the epoch).
|
|
1132
|
+
const date = new Date(number("TO_TIMESTAMP", values[0]) * 1000);
|
|
1133
|
+
if (!Number.isFinite(date.getTime()))
|
|
1134
|
+
throw new TypeError("TO_TIMESTAMP epoch is out of range");
|
|
1135
|
+
return date;
|
|
1136
|
+
}
|
|
1137
|
+
return parseDatetime("TO_TIMESTAMP", text("TO_TIMESTAMP", values[0]), text("TO_TIMESTAMP", values[1]));
|
|
1138
|
+
},
|
|
1139
|
+
},
|
|
1140
|
+
],
|
|
1141
|
+
[
|
|
1142
|
+
"MAKE_DATE",
|
|
1143
|
+
{
|
|
1144
|
+
minArgs: 3,
|
|
1145
|
+
maxArgs: 3,
|
|
1146
|
+
returns: "date",
|
|
1147
|
+
evaluate: (values) => {
|
|
1148
|
+
const year = integer("MAKE_DATE", values[0]);
|
|
1149
|
+
const month = integer("MAKE_DATE", values[1]);
|
|
1150
|
+
const day = integer("MAKE_DATE", values[2]);
|
|
1151
|
+
const iso = `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
|
|
1152
|
+
return dateDomainValue(iso);
|
|
1153
|
+
},
|
|
1154
|
+
},
|
|
1155
|
+
],
|
|
1156
|
+
[
|
|
1157
|
+
"MAKE_TIMESTAMP",
|
|
1158
|
+
{
|
|
1159
|
+
minArgs: 6,
|
|
1160
|
+
maxArgs: 6,
|
|
1161
|
+
returns: "datetime",
|
|
1162
|
+
evaluate: (values) => {
|
|
1163
|
+
const [year, month, day, hour, minute] = values
|
|
1164
|
+
.slice(0, 5)
|
|
1165
|
+
.map((value) => integer("MAKE_TIMESTAMP", value));
|
|
1166
|
+
const seconds = number("MAKE_TIMESTAMP", values[5]);
|
|
1167
|
+
const date = new Date(Date.UTC(year ?? 0, (month ?? 1) - 1, day ?? 1, hour ?? 0, minute ?? 0, 0, Math.round(seconds * 1000)));
|
|
1168
|
+
if (!Number.isFinite(date.getTime()) ||
|
|
1169
|
+
date.getUTCMonth() !== (month ?? 1) - 1 ||
|
|
1170
|
+
date.getUTCDate() !== (day ?? 1)) {
|
|
1171
|
+
throw new TypeError("MAKE_TIMESTAMP fields do not form a valid timestamp");
|
|
1172
|
+
}
|
|
1173
|
+
return date;
|
|
1174
|
+
},
|
|
1175
|
+
},
|
|
1176
|
+
],
|
|
1177
|
+
[
|
|
1178
|
+
"AGE",
|
|
1179
|
+
{
|
|
1180
|
+
minArgs: 2,
|
|
1181
|
+
maxArgs: 2,
|
|
1182
|
+
returns: "interval",
|
|
1183
|
+
evaluate: (values) => ageInterval(datetime("AGE", values[0]), datetime("AGE", values[1])),
|
|
1184
|
+
},
|
|
1185
|
+
],
|
|
1186
|
+
]);
|