@minnowdb/core 0.7.0 → 0.7.1

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