trilean-sql 2.2.41 → 2.3.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/dist/guard.js CHANGED
@@ -1,342 +1 @@
1
- import { assertImplementedDialect } from "./options.js";
2
- import { renderPostgresPattern, renderSqliteGlobPattern } from "./portable-pattern.js";
3
- import { parseRegex } from "trilean-regex";
4
- // src/guard.ts
5
- const STATIC_KIND_OF_PARAM_TYPE = {
6
- text: "text",
7
- number: "number",
8
- boolean: "boolean",
9
- timestamp: "instant"
10
- };
11
- /** The comparison operators that impose an ordering, as opposed to testing equality. trilean refuses these on booleans -- `true > false` is not a fact about the domain -- while both dialects answer them, so a boolean operand under one of these is a real divergence rather than a stylistic one. */
12
- const ORDERING_OPERATORS = /* @__PURE__ */ new Set([
13
- "gt",
14
- "gte",
15
- "lt",
16
- "lte"
17
- ]);
18
- /** A literal's own node kind is its value's kind. Written as a lookup rather than a switch so that every other expression kind falls out as "not statically knowable" by absence, which is the honest answer for all of them, rather than needing a branch each. */
19
- const STATIC_KIND_OF_LITERAL = {
20
- textLiteral: "text",
21
- numberLiteral: "number",
22
- booleanLiteral: "boolean",
23
- instantLiteral: "instant"
24
- };
25
- const DIALECT_DIVERGENCE = {
26
- postgres: {
27
- complexNumbers: "PostgreSQL has no complex number type",
28
- nan: "NaN is equal to nothing in trilean, not even itself, whereas PostgreSQL defines NaN as equal to itself and greater than every other double",
29
- crossKindCoercion: "PostgreSQL may coerce one to the other and answer definitely",
30
- textOrdering: (operandPath) => `PostgreSQL would order the text operand at ${operandPath} collation-wise and answer definitely`,
31
- booleanOrdering: "PostgreSQL orders false before true"
32
- },
33
- sqlite: {
34
- complexNumbers: "SQLite has no complex number type",
35
- nan: "NaN is equal to nothing in trilean, not even itself, whereas SQLite has no NaN at all and a driver binding one substitutes SQL NULL -- so 'NaN = NaN' is indeterminate there rather than definitely false, and its negation matches every row instead of none",
36
- crossKindCoercion: "SQLite's type affinity may coerce one to the other and answer definitely",
37
- textOrdering: (operandPath) => `SQLite would answer definitely for the text operand at ${operandPath}, comparing it under the text affinity it applies to the other side ('9' > 5 is true there, while '10' > 5 is not)`,
38
- booleanOrdering: "SQLite stores booleans as the integers 0 and 1 and orders them as integers"
39
- }
40
- };
41
- function staticValueKindOf(node, options) {
42
- if (node.kind !== "reference") return STATIC_KIND_OF_LITERAL[node.kind];
43
- if (options === void 0 || typeof node.key !== "string") return void 0;
44
- const paramType = options.columnFor(node.key).paramType;
45
- return paramType === void 0 ? void 0 : STATIC_KIND_OF_PARAM_TYPE[paramType];
46
- }
47
- /**
48
- * Resolves a `some`/`every`/`fold` node's `collection` onto the options a walk of its `item`/`filter` should use, or explains why it cannot be resolved.
49
- *
50
- * `options === undefined` is the one case that is not a refusal: a purely structural walk (no `options` at all) has no `columnFor` either, and every other options-dependent check in this file already answers "cannot tell, assume it passes" in that mode (see `staticValueKindOf`) -- refusing collection resolution specifically would make this the one exception to that convention rather than a consistent extension of it.
51
- */
52
- function resolveCollectionForGuard(kind, collection, path, options) {
53
- if (typeof collection !== "string") return {
54
- kind,
55
- path,
56
- reason: "only a string collection key can be mapped to a correlated table; this collection is a non-string JSON value"
57
- };
58
- if (options === void 0) return { itemOptions: void 0 };
59
- if (options.collectionFor === void 0) return {
60
- kind,
61
- path,
62
- reason: "no 'collectionFor' option is set: describe how this collection maps onto a correlated table ({ table, join, columnFor }) to compile this node, or it falls back to in-process evaluation"
63
- };
64
- const binding = options.collectionFor(collection);
65
- return { itemOptions: {
66
- ...options,
67
- columnFor: binding.columnFor
68
- } };
69
- }
70
- function findUnpushableExpression(node, path, divergence, options) {
71
- const unrecognisedKind = node.kind;
72
- switch (node.kind) {
73
- case "reference":
74
- if (typeof node.key !== "string") return {
75
- kind: node.kind,
76
- path,
77
- reason: "only a string reference key can be mapped to a column; this key is a non-string JSON value"
78
- };
79
- if (node.unit !== void 0) return {
80
- kind: node.kind,
81
- path,
82
- reason: "a reference declaring a unit asserts that the resolved value carries that same unit, and a SQL column carries no unit for that assertion to be checked against"
83
- };
84
- return;
85
- case "numberLiteral":
86
- if (node.unit !== void 0) return {
87
- kind: node.kind,
88
- path,
89
- reason: "a unit-tagged number is only comparable with an operand of the same unit, and SQL has no unit to compare"
90
- };
91
- if (Number.isNaN(node.value)) return {
92
- kind: node.kind,
93
- path,
94
- reason: divergence.nan
95
- };
96
- return;
97
- case "textLiteral":
98
- case "booleanLiteral":
99
- case "instantLiteral": return;
100
- case "durationLiteral": return {
101
- kind: node.kind,
102
- path,
103
- reason: "trilean compares two durations in whichever unit each carries, and a column holds no unit to carry"
104
- };
105
- case "complexLiteral": return {
106
- kind: node.kind,
107
- path,
108
- reason: divergence.complexNumbers
109
- };
110
- case "arithmetic":
111
- case "negate": return {
112
- kind: node.kind,
113
- path,
114
- reason: "arithmetic carries and combines units, and pushing it down would drop that dimensional analysis without saying so"
115
- };
116
- case "call": return {
117
- kind: node.kind,
118
- path,
119
- reason: "a function's implementation lives in the caller's FunctionRegistry, not in the database"
120
- };
121
- case "lookup": return {
122
- kind: node.kind,
123
- path,
124
- reason: "a lookup table is resolved by the caller's resolvers"
125
- };
126
- case "conditional": return {
127
- kind: node.kind,
128
- path,
129
- reason: "conditional evaluation is not implemented in this version of the compiler"
130
- };
131
- case "fold": {
132
- if (node.combiner.mode === "reduce") return {
133
- kind: node.kind,
134
- path,
135
- reason: "a 'reduce' fold threads an arbitrary combine expression through the collection in a caller-chosen order, which has no general SQL translation"
136
- };
137
- const resolved = resolveCollectionForGuard(node.kind, node.collection, path, options);
138
- if ("reason" in resolved) return resolved;
139
- const { itemOptions } = resolved;
140
- if (node.filter !== void 0) {
141
- const unpushableFilter = findUnpushablePredicate(node.filter, `${path}.filter`, itemOptions, divergence);
142
- if (unpushableFilter !== void 0) return unpushableFilter;
143
- }
144
- const itemPath = `${path}.combiner.item`;
145
- const unpushableItem = findUnpushableExpression(node.combiner.item, itemPath, divergence, itemOptions);
146
- if (unpushableItem !== void 0) return unpushableItem;
147
- const itemKind = staticValueKindOf(node.combiner.item, itemOptions);
148
- if (itemKind === "text") return {
149
- kind: node.kind,
150
- path: itemPath,
151
- reason: `a '${node.combiner.mode}' fold orders participating items by comparing them, and trilean never orders text values ('compare' returns wrong-type for text; use 'textCompare') -- but ${divergence.textOrdering(itemPath)}`
152
- };
153
- if (itemKind === "boolean") return {
154
- kind: node.kind,
155
- path: itemPath,
156
- reason: `a '${node.combiner.mode}' fold orders participating items by comparing them, and booleans have no ordering in trilean -- whereas ${divergence.booleanOrdering}`
157
- };
158
- return;
159
- }
160
- case "accumulator": return {
161
- kind: node.kind,
162
- path,
163
- reason: "an accumulator is only meaningful inside a reduce fold"
164
- };
165
- case "delegate": return {
166
- kind: node.kind,
167
- path,
168
- reason: "a delegated decision is made by an external system"
169
- };
170
- case "treeReference": return {
171
- kind: node.kind,
172
- path,
173
- reason: "a referenced tree is resolved by the caller's resolvers; inline it before compiling"
174
- };
175
- default: return {
176
- kind: unrecognisedKind,
177
- path,
178
- reason: "unrecognised expression node kind"
179
- };
180
- }
181
- }
182
- /** Checks the operands of a comparison-shaped predicate for a kind pairing trilean and the target engine would answer differently. Returns the objection against `path` itself, since the divergence is a property of the pairing rather than of either operand alone. */
183
- function findKindDivergence(kind, path, operands, options, divergence) {
184
- const known = operands.map((operand) => ({
185
- path: operand.path,
186
- staticKind: staticValueKindOf(operand.node, options)
187
- })).filter((entry) => entry.staticKind !== void 0);
188
- const first = known[0];
189
- if (first === void 0) return void 0;
190
- const mismatched = known.find((entry) => entry.staticKind !== first.staticKind);
191
- if (mismatched !== void 0) return {
192
- kind,
193
- path,
194
- reason: `trilean treats a comparison between a '${first.staticKind}' value (${first.path}) and a '${mismatched.staticKind}' value (${mismatched.path}) as wrong-type, whereas ${divergence.crossKindCoercion}`
195
- };
196
- }
197
- function findUnpushablePredicate(node, path, options, divergence) {
198
- const unrecognisedKind = node.kind;
199
- switch (node.kind) {
200
- case "not": return findUnpushablePredicate(node.operand, `${path}.operand`, options, divergence);
201
- case "and":
202
- case "or": return findUnpushablePredicate(node.left, `${path}.left`, options, divergence) ?? findUnpushablePredicate(node.right, `${path}.right`, options, divergence);
203
- case "allOf":
204
- case "anyOf":
205
- for (const [index, operand] of node.operands.entries()) {
206
- const unpushable = findUnpushablePredicate(operand, `${path}.operands[${String(index)}]`, options, divergence);
207
- if (unpushable !== void 0) return unpushable;
208
- }
209
- return;
210
- case "compare": {
211
- const operands = [{
212
- node: node.left,
213
- path: `${path}.left`
214
- }, {
215
- node: node.right,
216
- path: `${path}.right`
217
- }];
218
- for (const operand of operands) {
219
- const unpushable = findUnpushableExpression(operand.node, operand.path, divergence, options);
220
- if (unpushable !== void 0) return unpushable;
221
- }
222
- const mismatch = findKindDivergence(node.kind, path, operands, options, divergence);
223
- if (mismatch !== void 0) return mismatch;
224
- for (const operand of operands) {
225
- const staticKind = staticValueKindOf(operand.node, options);
226
- if (staticKind === "text") return {
227
- kind: node.kind,
228
- path,
229
- reason: `'compare' never compares text in trilean -- it returns wrong-type and directs the caller to 'textCompare' -- but ${divergence.textOrdering(operand.path)}`
230
- };
231
- if (staticKind === "boolean" && ORDERING_OPERATORS.has(node.op)) return {
232
- kind: node.kind,
233
- path,
234
- reason: `booleans have no ordering in trilean, so '${node.op}' against the boolean operand at ${operand.path} is wrong-type there, whereas ${divergence.booleanOrdering}`
235
- };
236
- }
237
- return;
238
- }
239
- case "textCompare": {
240
- if ((node.op === "matches" || node.op === "notMatches") && options?.dialect === "sqlite" && options.sqliteRegexpAvailable === false) return {
241
- kind: node.kind,
242
- path,
243
- reason: `options.sqliteRegexpAvailable is false: the caller has stated no regexp(pattern, value) function can be registered on this SQLite target, so '${node.op}' would compile to SQL that fails at query execution time with "no such function: REGEXP" instead of at compile time`
244
- };
245
- const operands = [{
246
- node: node.left,
247
- path: `${path}.left`
248
- }, {
249
- node: node.right,
250
- path: `${path}.right`
251
- }];
252
- for (const operand of operands) {
253
- const unpushable = findUnpushableExpression(operand.node, operand.path, divergence, options);
254
- if (unpushable !== void 0) return unpushable;
255
- const staticKind = staticValueKindOf(operand.node, options);
256
- if (staticKind !== void 0 && staticKind !== "text") return {
257
- kind: node.kind,
258
- path,
259
- reason: `'textCompare' requires text operands in trilean, and the operand at ${operand.path} is a '${staticKind}' value`
260
- };
261
- }
262
- const dialect = options?.dialect ?? "postgres";
263
- if (dialect === "postgres" && (node.op === "matches" || node.op === "notMatches") && options?.postgresRegexpPushdown !== true) return {
264
- kind: node.kind,
265
- path,
266
- reason: `'${node.op}' matches trilean's own ECMAScript 'RegExp' against the pattern, whereas PostgreSQL's '~'/'!~' would match it under PostgreSQL's own regular-expression dialect (POSIX ARE) -- a different language that can silently answer a different set of rows for the same pattern and data (for example, PostgreSQL's '.' matches a newline by default where ECMAScript's does not, and PostgreSQL's '\\w' follows the database's locale where ECMAScript's is ASCII-only) -- so this is refused unless 'postgresRegexpPushdown' is explicitly set 'true'`
267
- };
268
- if (node.op === "portableMatches" || node.op === "portableNotMatches") {
269
- if (node.right.kind !== "textLiteral") return {
270
- kind: node.kind,
271
- path,
272
- reason: "a 'portableMatches'/'portableNotMatches' pattern must be a literal, known at compile time -- translating it into this dialect's own pattern syntax happens once, at compile time, not per row"
273
- };
274
- try {
275
- const ast = parseRegex(node.right.value);
276
- if (dialect === "postgres") renderPostgresPattern(ast);
277
- else renderSqliteGlobPattern(ast);
278
- } catch (error) {
279
- return {
280
- kind: node.kind,
281
- path: `${path}.right`,
282
- reason: error instanceof Error ? error.message : String(error)
283
- };
284
- }
285
- }
286
- return;
287
- }
288
- case "memberOf": {
289
- const operands = [{
290
- node: node.operand,
291
- path: `${path}.operand`
292
- }, ...node.candidates.map((candidate, index) => ({
293
- node: candidate,
294
- path: `${path}.candidates[${String(index)}]`
295
- }))];
296
- for (const operand of operands) {
297
- const unpushable = findUnpushableExpression(operand.node, operand.path, divergence, options);
298
- if (unpushable !== void 0) return unpushable;
299
- }
300
- return findKindDivergence(node.kind, path, operands, options, divergence);
301
- }
302
- case "exists": return findUnpushableExpression(node.operand, `${path}.operand`, divergence, options);
303
- case "some":
304
- case "every": {
305
- const resolved = resolveCollectionForGuard(node.kind, node.collection, path, options);
306
- if ("reason" in resolved) return resolved;
307
- const { itemOptions } = resolved;
308
- const unpushableItem = findUnpushablePredicate(node.item, `${path}.item`, itemOptions, divergence);
309
- if (unpushableItem !== void 0) return unpushableItem;
310
- if (node.filter === void 0) return void 0;
311
- return findUnpushablePredicate(node.filter, `${path}.filter`, itemOptions, divergence);
312
- }
313
- case "treeReference": return {
314
- kind: node.kind,
315
- path,
316
- reason: "a referenced tree is resolved by the caller's resolvers; inline it before compiling"
317
- };
318
- default: return {
319
- kind: unrecognisedKind,
320
- path,
321
- reason: "unrecognised predicate node kind"
322
- };
323
- }
324
- }
325
- /**
326
- * Walks the tree against the allow-list of what this compiler translates, and reports the first node it will not.
327
- *
328
- * The walk is an allow-list rather than a deny-list on purpose: a node kind added to trilean after this package was written is refused by default, instead of falling through to whatever branch happened to be last. That is the difference between a caller learning it must evaluate in process and a caller silently receiving a `WHERE` clause that answers a different question.
329
- *
330
- * `compilePredicateNode` runs this first and throws `UnsupportedNodeError` on any result, so calling it separately is only necessary to *decide* between pushdown and in-process evaluation without provoking an exception.
331
- *
332
- * Passing `options` widens the check: without them the walk is purely structural, and with them it also applies the operand-kind rules that depend on each mapped column's declared `paramType` (and therefore calls `columnFor`).
333
- *
334
- * Which nodes are refused does not depend on the dialect -- every divergence refused here is real in both -- so a structural walk given no `options` refuses exactly what a walk given them would. What `options` also settles is which engine each `reason` describes; with none to read a dialect from, the reasons describe PostgreSQL, the dialect these refusals were first derived against.
335
- * @throws `UnknownDialectError` if `options` names a dialect this version does not implement. Reporting a tree as pushable is a promise that `compilePredicateNode` will compile it, and under a dialect that does not exist it cannot -- so this is refused here rather than left to surface from the compiler, which is the one caller this function's answer is for.
336
- */
337
- function findUnpushableNodeKind(node, options) {
338
- const dialect = options?.dialect ?? "postgres";
339
- assertImplementedDialect(dialect);
340
- return findUnpushablePredicate(node, "$", options, DIALECT_DIVERGENCE[dialect]);
341
- }
342
- export { findUnpushableNodeKind };
1
+ export { t as findUnpushableNodeKind } from "./guard-D4CIUc5h.js";
package/dist/index.cjs CHANGED
@@ -1,7 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_guard = require("./guard.cjs");
2
+ const require_guard = require("./guard-CCet6aaa.cjs");
3
3
  const require_compile = require("./compile.cjs");
4
4
  const require_errors = require("./errors.cjs");
5
+ exports.InvalidCollectionTableError = require_errors.InvalidCollectionTableError;
5
6
  exports.InvalidColumnError = require_errors.InvalidColumnError;
6
7
  exports.TrileanSqlError = require_errors.TrileanSqlError;
7
8
  exports.UnknownDialectError = require_errors.UnknownDialectError;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CompiledSql, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType } from "./options.cjs";
2
2
  import { UnpushableNode, findUnpushableNodeKind } from "./guard.cjs";
3
3
  import { compilePredicateNode } from "./compile.cjs";
4
- import { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError } from "./errors.cjs";
5
- export { type CompiledSql, InvalidColumnError, type SqlColumnBinding, type SqlCompileOptions, type SqlDialect, type SqlParamType, TrileanSqlError, UnknownDialectError, type UnpushableNode, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
4
+ import { InvalidCollectionTableError, InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError } from "./errors.cjs";
5
+ export { type CompiledSql, InvalidCollectionTableError, InvalidColumnError, type SqlColumnBinding, type SqlCompileOptions, type SqlDialect, type SqlParamType, TrileanSqlError, UnknownDialectError, type UnpushableNode, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CompiledSql, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType } from "./options.js";
2
2
  import { UnpushableNode, findUnpushableNodeKind } from "./guard.js";
3
3
  import { compilePredicateNode } from "./compile.js";
4
- import { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError } from "./errors.js";
5
- export { type CompiledSql, InvalidColumnError, type SqlColumnBinding, type SqlCompileOptions, type SqlDialect, type SqlParamType, TrileanSqlError, UnknownDialectError, type UnpushableNode, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
4
+ import { InvalidCollectionTableError, InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError } from "./errors.js";
5
+ export { type CompiledSql, InvalidCollectionTableError, InvalidColumnError, type SqlColumnBinding, type SqlCompileOptions, type SqlDialect, type SqlParamType, TrileanSqlError, UnknownDialectError, type UnpushableNode, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { findUnpushableNodeKind } from "./guard.js";
1
+ import { t as findUnpushableNodeKind } from "./guard-D4CIUc5h.js";
2
2
  import { compilePredicateNode } from "./compile.js";
3
- import { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError } from "./errors.js";
4
- export { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
3
+ import { InvalidCollectionTableError, InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError } from "./errors.js";
4
+ export { InvalidCollectionTableError, InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
@@ -0,0 +1,126 @@
1
+ const require_errors = require("./errors.cjs");
2
+ // src/internal/sqlite-instant.ts
3
+ /**
4
+ * How the SQLite dialect reads an instant, in one place.
5
+ *
6
+ * SQLite has no timestamp type, and its date functions read far more than an instant: the text `now` is the present time, a time of day is a date in the year 2000, a number is a Julian day. The evaluator reads none of these. So the SQL decides first, with a shape test that needs no extension, whether a stored value is an instant in exactly one grammar, and only then converts it; any other value is NULL (unknown) whatever the date functions would make of it, and the same grammar is applied to an `instantLiteral` when the tree is compiled.
7
+ *
8
+ * The grammar: four-digit year, `-`, two-digit month, `-`, two-digit day, `T` or one space, two-digit hour, `:`, minute, `:`, second, an optional `.` and one or more fractional digits, then `Z` or a sign, two-digit hours, `:` and two-digit minutes. The value must also be a real moment: a month 1 to 12, a day that exists in that month (so no `02-30`), an hour 0 to 23, a minute and second 0 to 59 (no leap second, no hour 24), and an offset of at most 23:59. Within it SQLite, PostgreSQL and the evaluator (`Date.parse`) read the same instant, to the millisecond; the fraction is truncated to three digits, as `Date.parse` does, and is not rounded as SQLite's own date functions would.
9
+ */
10
+ /** The characters up to the seconds, in the form SQLite's `GLOB` reads: four digits, `-`, two, `-`, two, `T` or a space, two, `:`, two, `:`, two. */
11
+ const DATE_AND_TIME_SHAPE = "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]";
12
+ const OFFSET_SHAPE = "[+-][0-9][0-9]:[0-9][0-9]";
13
+ /** The characters before the seconds end, which are the first nineteen of a value in the grammar. */
14
+ const SECONDS_END = 19;
15
+ /** Where the fraction's point, or the zone, starts (1-based). */
16
+ const AFTER_SECONDS = 20;
17
+ /** The width of a numeric offset, `+HH:MM`. */
18
+ const OFFSET_WIDTH = 6;
19
+ const MILLISECONDS_PER_SECOND = 1e3;
20
+ const MILLISECONDS_PER_MINUTE = 6e4;
21
+ const MINUTES_PER_HOUR = 60;
22
+ const FRACTION_DIGITS = 3;
23
+ /**
24
+ * The SQL that reads `column` (an expression of one SQLite value) as whole milliseconds since the epoch, or NULL when it is not an instant in the grammar above. `column` appears many times, so it must be a column reference or a placeholder-free expression.
25
+ */
26
+ function sqliteInstantColumn(column) {
27
+ const length = `length(${column})`;
28
+ const isZulu = `${column} GLOB '*Z'`;
29
+ const fractionLength = `(${length} - ${String(AFTER_SECONDS)} - CASE WHEN ${isZulu} THEN 1 ELSE ${String(OFFSET_WIDTH)} END)`;
30
+ const zoneStart = `CASE WHEN ${isZulu} THEN ${length} ELSE ${length} - ${String(5)} END`;
31
+ const afterSeconds = `substr(${column}, ${String(AFTER_SECONDS)})`;
32
+ const fractionOnly = `substr(${column}, ${String(21)}, ${fractionLength})`;
33
+ const zoneShape = `(${afterSeconds} = 'Z' OR ${afterSeconds} GLOB '${OFFSET_SHAPE}' OR (substr(${column}, ${String(AFTER_SECONDS)}, 1) = '.' AND ${fractionLength} > 0 AND ${fractionOnly} NOT GLOB '*[^0-9]*' AND (${isZulu} OR ${column} GLOB '*${OFFSET_SHAPE}')))`;
34
+ const shape = `instr(CAST(${column} AS BLOB), x'00') = 0 AND ${column} GLOB '${DATE_AND_TIME_SHAPE}*' AND ${zoneShape}`;
35
+ const dateAndTime = `substr(${column}, 1, ${String(SECONDS_END)})`;
36
+ const real = [
37
+ `strftime('%Y-%m-%d', ${dateAndTime}) = substr(${column}, 1, 10)`,
38
+ `strftime('%s', ${dateAndTime}) IS NOT NULL`,
39
+ `substr(${column}, 12, 2) < '24'`,
40
+ `(${isZulu} OR (substr(${column}, ${zoneStart} + 1, 2) <= '23' AND substr(${column}, ${zoneStart} + 4, 2) <= '59'))`
41
+ ].join(" AND ");
42
+ const fraction = `CASE WHEN substr(${column}, ${String(AFTER_SECONDS)}, 1) = '.' THEN CAST(substr(${fractionOnly} || '00', 1, ${String(FRACTION_DIGITS)}) AS INTEGER) ELSE 0 END`;
43
+ const offsetMinutes = `CASE WHEN ${isZulu} THEN 0 ELSE (CASE substr(${column}, ${zoneStart}, 1) WHEN '-' THEN -1 ELSE 1 END) * (CAST(substr(${column}, ${zoneStart} + 1, 2) AS INTEGER) * ${String(MINUTES_PER_HOUR)} + CAST(substr(${column}, ${zoneStart} + 4, 2) AS INTEGER)) END`;
44
+ return `(CASE WHEN ${shape} AND ${real} THEN CAST(strftime('%s', ${dateAndTime}) AS INTEGER) * ${String(MILLISECONDS_PER_SECOND)} + ${fraction} - (${offsetMinutes}) * ${String(MILLISECONDS_PER_MINUTE)} END)`;
45
+ }
46
+ const INSTANT = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})[T ](?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d+))?(?:Z|(?<sign>[+-])(?<zoneHour>\d{2}):(?<zoneMinute>\d{2}))$/u;
47
+ const LAST_HOUR = 23;
48
+ const LAST_MINUTE_OR_SECOND = 59;
49
+ /**
50
+ * The bind value of an `instantLiteral` for SQLite: the whole milliseconds since the epoch of a text in the grammar above, computed from its parts with the rules the SQL applies to a stored value, or `null` (unknown) for any other text.
51
+ */
52
+ function sqliteInstantParameter(iso) {
53
+ const groups = INSTANT.exec(iso)?.groups;
54
+ if (groups === void 0) return null;
55
+ const part = (name) => Number(groups[name] ?? 0);
56
+ const [year, month, day] = [
57
+ part("year"),
58
+ part("month"),
59
+ part("day")
60
+ ];
61
+ const moment = /* @__PURE__ */ new Date(0);
62
+ moment.setUTCFullYear(year, month - 1, day);
63
+ moment.setUTCHours(part("hour"), part("minute"), part("second"), 0);
64
+ if (!(moment.getUTCFullYear() === year && moment.getUTCMonth() === month - 1 && moment.getUTCDate() === day) || part("hour") > LAST_HOUR || part("minute") > LAST_MINUTE_OR_SECOND || part("second") > LAST_MINUTE_OR_SECOND || part("zoneHour") > LAST_HOUR || part("zoneMinute") > LAST_MINUTE_OR_SECOND) return null;
65
+ const milliseconds = Number(`${groups.fraction ?? ""}00`.slice(0, FRACTION_DIGITS));
66
+ const offset = (groups.sign === "-" ? -1 : 1) * (part("zoneHour") * MINUTES_PER_HOUR + part("zoneMinute")) * MILLISECONDS_PER_MINUTE;
67
+ return moment.getTime() + milliseconds - offset;
68
+ }
69
+ // src/options.ts
70
+ /** The PostgreSQL type each declared value kind is cast to. `timestamptz` rather than `timestamp`: trilean's `instant` is an ISO-8601 string that may carry an offset, and parsing one as a naive `timestamp` would silently discard it. */
71
+ const POSTGRES_TYPE_NAME = {
72
+ text: "text",
73
+ number: "double precision",
74
+ boolean: "boolean",
75
+ timestamp: "timestamptz"
76
+ };
77
+ const DIALECT_CONFIG = {
78
+ postgres: {
79
+ matches: "~",
80
+ notMatches: "!~",
81
+ portableMatches: "~",
82
+ portableNotMatches: "!~",
83
+ placeholder: (index, castTo) => `$${String(index)}::${POSTGRES_TYPE_NAME[castTo]}`,
84
+ emptyMemberOfNullSuffix: "::boolean",
85
+ instantColumn: (columnSql) => columnSql,
86
+ instantParameter: (iso) => iso
87
+ },
88
+ sqlite: {
89
+ matches: "REGEXP",
90
+ notMatches: "NOT REGEXP",
91
+ portableMatches: "GLOB",
92
+ portableNotMatches: "NOT GLOB",
93
+ placeholder: () => "?",
94
+ emptyMemberOfNullSuffix: "",
95
+ instantColumn: sqliteInstantColumn,
96
+ instantParameter: sqliteInstantParameter
97
+ }
98
+ };
99
+ /**
100
+ * Refuses a dialect this version does not implement, before anything indexes a per-dialect table with it.
101
+ *
102
+ * Both entry points check their own argument, because both are reachable with a name the type describes but cannot enforce -- a dialect is exactly the sort of value that arrives as a configuration string asserted into the union at the boundary. Left unchecked, that name is not caught anywhere: the compiler reads an operator off `undefined` and throws a `TypeError` naming an internal field, and the guard, whose tables are only consulted for a node it actually objects to, answers "pushable" for a tree the compiler then fails on -- the one thing `findUnpushableNodeKind` exists to decide, decided wrongly.
103
+ *
104
+ * `DIALECT_CONFIG` is the list, rather than a second constant, so implementing a dialect cannot leave this behind.
105
+ */
106
+ function assertImplementedDialect(dialect) {
107
+ if (!Object.hasOwn(DIALECT_CONFIG, dialect)) throw new require_errors.UnknownDialectError(dialect, Object.keys(DIALECT_CONFIG));
108
+ }
109
+ Object.defineProperty(exports, "DIALECT_CONFIG", {
110
+ enumerable: true,
111
+ get: function() {
112
+ return DIALECT_CONFIG;
113
+ }
114
+ });
115
+ Object.defineProperty(exports, "POSTGRES_TYPE_NAME", {
116
+ enumerable: true,
117
+ get: function() {
118
+ return POSTGRES_TYPE_NAME;
119
+ }
120
+ });
121
+ Object.defineProperty(exports, "assertImplementedDialect", {
122
+ enumerable: true,
123
+ get: function() {
124
+ return assertImplementedDialect;
125
+ }
126
+ });
@@ -0,0 +1,109 @@
1
+ import { UnknownDialectError } from "./errors.js";
2
+ // src/internal/sqlite-instant.ts
3
+ /**
4
+ * How the SQLite dialect reads an instant, in one place.
5
+ *
6
+ * SQLite has no timestamp type, and its date functions read far more than an instant: the text `now` is the present time, a time of day is a date in the year 2000, a number is a Julian day. The evaluator reads none of these. So the SQL decides first, with a shape test that needs no extension, whether a stored value is an instant in exactly one grammar, and only then converts it; any other value is NULL (unknown) whatever the date functions would make of it, and the same grammar is applied to an `instantLiteral` when the tree is compiled.
7
+ *
8
+ * The grammar: four-digit year, `-`, two-digit month, `-`, two-digit day, `T` or one space, two-digit hour, `:`, minute, `:`, second, an optional `.` and one or more fractional digits, then `Z` or a sign, two-digit hours, `:` and two-digit minutes. The value must also be a real moment: a month 1 to 12, a day that exists in that month (so no `02-30`), an hour 0 to 23, a minute and second 0 to 59 (no leap second, no hour 24), and an offset of at most 23:59. Within it SQLite, PostgreSQL and the evaluator (`Date.parse`) read the same instant, to the millisecond; the fraction is truncated to three digits, as `Date.parse` does, and is not rounded as SQLite's own date functions would.
9
+ */
10
+ /** The characters up to the seconds, in the form SQLite's `GLOB` reads: four digits, `-`, two, `-`, two, `T` or a space, two, `:`, two, `:`, two. */
11
+ const DATE_AND_TIME_SHAPE = "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]";
12
+ const OFFSET_SHAPE = "[+-][0-9][0-9]:[0-9][0-9]";
13
+ /** The characters before the seconds end, which are the first nineteen of a value in the grammar. */
14
+ const SECONDS_END = 19;
15
+ /** Where the fraction's point, or the zone, starts (1-based). */
16
+ const AFTER_SECONDS = 20;
17
+ /** The width of a numeric offset, `+HH:MM`. */
18
+ const OFFSET_WIDTH = 6;
19
+ const MILLISECONDS_PER_SECOND = 1e3;
20
+ const MILLISECONDS_PER_MINUTE = 6e4;
21
+ const MINUTES_PER_HOUR = 60;
22
+ const FRACTION_DIGITS = 3;
23
+ /**
24
+ * The SQL that reads `column` (an expression of one SQLite value) as whole milliseconds since the epoch, or NULL when it is not an instant in the grammar above. `column` appears many times, so it must be a column reference or a placeholder-free expression.
25
+ */
26
+ function sqliteInstantColumn(column) {
27
+ const length = `length(${column})`;
28
+ const isZulu = `${column} GLOB '*Z'`;
29
+ const fractionLength = `(${length} - ${String(AFTER_SECONDS)} - CASE WHEN ${isZulu} THEN 1 ELSE ${String(OFFSET_WIDTH)} END)`;
30
+ const zoneStart = `CASE WHEN ${isZulu} THEN ${length} ELSE ${length} - ${String(5)} END`;
31
+ const afterSeconds = `substr(${column}, ${String(AFTER_SECONDS)})`;
32
+ const fractionOnly = `substr(${column}, ${String(21)}, ${fractionLength})`;
33
+ const zoneShape = `(${afterSeconds} = 'Z' OR ${afterSeconds} GLOB '${OFFSET_SHAPE}' OR (substr(${column}, ${String(AFTER_SECONDS)}, 1) = '.' AND ${fractionLength} > 0 AND ${fractionOnly} NOT GLOB '*[^0-9]*' AND (${isZulu} OR ${column} GLOB '*${OFFSET_SHAPE}')))`;
34
+ const shape = `instr(CAST(${column} AS BLOB), x'00') = 0 AND ${column} GLOB '${DATE_AND_TIME_SHAPE}*' AND ${zoneShape}`;
35
+ const dateAndTime = `substr(${column}, 1, ${String(SECONDS_END)})`;
36
+ const real = [
37
+ `strftime('%Y-%m-%d', ${dateAndTime}) = substr(${column}, 1, 10)`,
38
+ `strftime('%s', ${dateAndTime}) IS NOT NULL`,
39
+ `substr(${column}, 12, 2) < '24'`,
40
+ `(${isZulu} OR (substr(${column}, ${zoneStart} + 1, 2) <= '23' AND substr(${column}, ${zoneStart} + 4, 2) <= '59'))`
41
+ ].join(" AND ");
42
+ const fraction = `CASE WHEN substr(${column}, ${String(AFTER_SECONDS)}, 1) = '.' THEN CAST(substr(${fractionOnly} || '00', 1, ${String(FRACTION_DIGITS)}) AS INTEGER) ELSE 0 END`;
43
+ const offsetMinutes = `CASE WHEN ${isZulu} THEN 0 ELSE (CASE substr(${column}, ${zoneStart}, 1) WHEN '-' THEN -1 ELSE 1 END) * (CAST(substr(${column}, ${zoneStart} + 1, 2) AS INTEGER) * ${String(MINUTES_PER_HOUR)} + CAST(substr(${column}, ${zoneStart} + 4, 2) AS INTEGER)) END`;
44
+ return `(CASE WHEN ${shape} AND ${real} THEN CAST(strftime('%s', ${dateAndTime}) AS INTEGER) * ${String(MILLISECONDS_PER_SECOND)} + ${fraction} - (${offsetMinutes}) * ${String(MILLISECONDS_PER_MINUTE)} END)`;
45
+ }
46
+ const INSTANT = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})[T ](?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d+))?(?:Z|(?<sign>[+-])(?<zoneHour>\d{2}):(?<zoneMinute>\d{2}))$/u;
47
+ const LAST_HOUR = 23;
48
+ const LAST_MINUTE_OR_SECOND = 59;
49
+ /**
50
+ * The bind value of an `instantLiteral` for SQLite: the whole milliseconds since the epoch of a text in the grammar above, computed from its parts with the rules the SQL applies to a stored value, or `null` (unknown) for any other text.
51
+ */
52
+ function sqliteInstantParameter(iso) {
53
+ const groups = INSTANT.exec(iso)?.groups;
54
+ if (groups === void 0) return null;
55
+ const part = (name) => Number(groups[name] ?? 0);
56
+ const [year, month, day] = [
57
+ part("year"),
58
+ part("month"),
59
+ part("day")
60
+ ];
61
+ const moment = /* @__PURE__ */ new Date(0);
62
+ moment.setUTCFullYear(year, month - 1, day);
63
+ moment.setUTCHours(part("hour"), part("minute"), part("second"), 0);
64
+ if (!(moment.getUTCFullYear() === year && moment.getUTCMonth() === month - 1 && moment.getUTCDate() === day) || part("hour") > LAST_HOUR || part("minute") > LAST_MINUTE_OR_SECOND || part("second") > LAST_MINUTE_OR_SECOND || part("zoneHour") > LAST_HOUR || part("zoneMinute") > LAST_MINUTE_OR_SECOND) return null;
65
+ const milliseconds = Number(`${groups.fraction ?? ""}00`.slice(0, FRACTION_DIGITS));
66
+ const offset = (groups.sign === "-" ? -1 : 1) * (part("zoneHour") * MINUTES_PER_HOUR + part("zoneMinute")) * MILLISECONDS_PER_MINUTE;
67
+ return moment.getTime() + milliseconds - offset;
68
+ }
69
+ // src/options.ts
70
+ /** The PostgreSQL type each declared value kind is cast to. `timestamptz` rather than `timestamp`: trilean's `instant` is an ISO-8601 string that may carry an offset, and parsing one as a naive `timestamp` would silently discard it. */
71
+ const POSTGRES_TYPE_NAME = {
72
+ text: "text",
73
+ number: "double precision",
74
+ boolean: "boolean",
75
+ timestamp: "timestamptz"
76
+ };
77
+ const DIALECT_CONFIG = {
78
+ postgres: {
79
+ matches: "~",
80
+ notMatches: "!~",
81
+ portableMatches: "~",
82
+ portableNotMatches: "!~",
83
+ placeholder: (index, castTo) => `$${String(index)}::${POSTGRES_TYPE_NAME[castTo]}`,
84
+ emptyMemberOfNullSuffix: "::boolean",
85
+ instantColumn: (columnSql) => columnSql,
86
+ instantParameter: (iso) => iso
87
+ },
88
+ sqlite: {
89
+ matches: "REGEXP",
90
+ notMatches: "NOT REGEXP",
91
+ portableMatches: "GLOB",
92
+ portableNotMatches: "NOT GLOB",
93
+ placeholder: () => "?",
94
+ emptyMemberOfNullSuffix: "",
95
+ instantColumn: sqliteInstantColumn,
96
+ instantParameter: sqliteInstantParameter
97
+ }
98
+ };
99
+ /**
100
+ * Refuses a dialect this version does not implement, before anything indexes a per-dialect table with it.
101
+ *
102
+ * Both entry points check their own argument, because both are reachable with a name the type describes but cannot enforce -- a dialect is exactly the sort of value that arrives as a configuration string asserted into the union at the boundary. Left unchecked, that name is not caught anywhere: the compiler reads an operator off `undefined` and throws a `TypeError` naming an internal field, and the guard, whose tables are only consulted for a node it actually objects to, answers "pushable" for a tree the compiler then fails on -- the one thing `findUnpushableNodeKind` exists to decide, decided wrongly.
103
+ *
104
+ * `DIALECT_CONFIG` is the list, rather than a second constant, so implementing a dialect cannot leave this behind.
105
+ */
106
+ function assertImplementedDialect(dialect) {
107
+ if (!Object.hasOwn(DIALECT_CONFIG, dialect)) throw new UnknownDialectError(dialect, Object.keys(DIALECT_CONFIG));
108
+ }
109
+ export { POSTGRES_TYPE_NAME as n, assertImplementedDialect as r, DIALECT_CONFIG as t };