trilean-sql 2.2.42 → 3.0.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/compile.cjs DELETED
@@ -1,278 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_errors = require("./errors.cjs");
3
- const require_guard = require("./guard.cjs");
4
- const require_portable_pattern = require("./portable-pattern.cjs");
5
- const require_options = require("./options-DOE1_Cwr.cjs");
6
- let trilean_regex = require("trilean-regex");
7
- // src/compile.ts
8
- const COMPARISON_SQL = {
9
- gt: ">",
10
- gte: ">=",
11
- lt: "<",
12
- lte: "<=",
13
- eq: "=",
14
- neq: "<>"
15
- };
16
- /**
17
- * The operator each `textCompare` op emits, for one dialect.
18
- *
19
- * `=` and `<>` are ANSI-standard equality and identical everywhere; only the two pattern operators are the dialect's own. Built as a complete record rather than resolved per node so that a `TextComparisonOperator` added to trilean later is a compile error here, instead of an undefined operator spliced into the emitted SQL.
20
- */
21
- function textComparisonSqlFor(dialect) {
22
- return {
23
- equals: "=",
24
- notEquals: "<>",
25
- matches: dialect.matches,
26
- notMatches: dialect.notMatches,
27
- portableMatches: dialect.portableMatches,
28
- portableNotMatches: dialect.portableNotMatches
29
- };
30
- }
31
- /**
32
- * The value kind a literal placeholder is rendered for: the one implied by the literal's own trilean kind. What a dialect does with it -- PostgreSQL casts the placeholder to the corresponding type, SQLite ignores it -- is `DialectConfig.placeholder`'s business.
33
- *
34
- * A mapped column's declared `paramType` deliberately does not override this. It cannot differ: the guard has already refused any comparison whose operand kinds disagree, and each declared kind implies the same SQL type as the literal kind it must then match. Consulting it here would be a branch that can never change the output.
35
- */
36
- const PARAM_TYPE_OF_LITERAL = {
37
- textLiteral: "text",
38
- numberLiteral: "number",
39
- booleanLiteral: "boolean",
40
- instantLiteral: "timestamp"
41
- };
42
- function placeholder(context, value, castTo) {
43
- context.params.push(value);
44
- return context.dialect.placeholder(context.params.length, castTo);
45
- }
46
- /**
47
- * Renders a column as a SQL identifier: each dot-separated segment double-quoted, with any embedded double quote doubled. Double-quoting is ANSI-standard and means the same thing in both dialects, so this needs no per-dialect branch.
48
- *
49
- * A column name cannot be a bind parameter -- it is part of the statement's structure, not its data -- so it is the one caller-supplied string that reaches the SQL text. Quoting it unconditionally is what keeps that safe: the doubling makes even a name containing `"; DROP TABLE ...` a single, inert identifier that simply does not exist. Quoting also means a name is taken literally rather than case-folded, so `columnFor` must return the column's real, case-exact name.
50
- */
51
- function quoteColumn(referenceKey, binding) {
52
- const segments = binding.column.split(".");
53
- if (segments.some((segment) => segment.length === 0)) throw new require_errors.InvalidColumnError(referenceKey, binding.column, binding.column.length === 0 ? "the name is empty" : "a dot-separated segment is empty");
54
- return segments.map((segment) => `"${segment.replaceAll("\"", "\"\"")}"`).join(".");
55
- }
56
- /**
57
- * Renders a `collectionFor` result's `table` as a SQL identifier, the same way `quoteColumn` renders a column: each dot-separated segment double-quoted, with any embedded double quote doubled.
58
- *
59
- * Takes the already-resolved table string rather than the whole `SqlCollectionBinding`, since every call site here has already destructured it -- unlike `quoteColumn`, which reads `binding.column` itself because its own call site still has the whole `SqlColumnBinding` in hand.
60
- */
61
- function quoteTable(collectionKey, table) {
62
- const segments = table.split(".");
63
- if (segments.some((segment) => segment.length === 0)) throw new require_errors.InvalidCollectionTableError(collectionKey, table, table.length === 0 ? "the name is empty" : "a dot-separated segment is empty");
64
- return segments.map((segment) => `"${segment.replaceAll("\"", "\"\"")}"`).join(".");
65
- }
66
- function bindingOf(context, node) {
67
- if (node.kind !== "reference" || typeof node.key !== "string") return;
68
- return {
69
- referenceKey: node.key,
70
- binding: context.options.columnFor(node.key)
71
- };
72
- }
73
- /**
74
- * The compiler's own refusal, as distinct from the guard's.
75
- *
76
- * `compilePredicateNode` runs the guard first, so in a correct build nothing reaches here: every kind named in the unsupported branches below has already been reported with a real path and a real reason. These branches exist so that a disagreement between the guard's allow-list and this file's coverage -- the one way a node kind could ever be silently mistranslated -- is instead a loud, named failure. Every kind is spelled out rather than caught by a `default`, so adding one to trilean breaks this switch at compile time instead of falling into a catch-all.
77
- */
78
- function refuse(kind, layer) {
79
- throw new require_errors.UnsupportedNodeError({
80
- kind,
81
- path: "$",
82
- reason: `the ${layer} passed the pushability check but has no compiler branch`
83
- });
84
- }
85
- /**
86
- * The shared setup for `some`/`every`/`fold`: resolves `node.collection` to a quoted correlated table via `options.collectionFor`, builds the `CompileContext` its `item`/`filter`/`combiner.item` should compile against (the outer `columnFor` swapped for the resolved binding's own, mirroring how trilean's own evaluator re-points `EvaluationContext` at the collection item), and compiles `filter` eagerly since every caller needs it.
87
- *
88
- * The `typeof node.collection !== "string" || options.collectionFor === undefined` check is a drift safety net, not the primary defence: `findUnpushableNodeKind` already refused a non-string collection or a missing `collectionFor` before compilation ever started (see `resolveCollectionForGuard` in guard.ts), so reaching it in a correct build means the guard's allow-list has drifted from what this file actually compiles -- the same class of safety net `refuse` provides everywhere else in this module.
89
- */
90
- function compileCollection(node, context, layer) {
91
- if (typeof node.collection !== "string" || context.options.collectionFor === void 0) return refuse(node.kind, layer);
92
- const binding = context.options.collectionFor(node.collection);
93
- const table = quoteTable(node.collection, binding.table);
94
- const itemContext = {
95
- ...context,
96
- options: {
97
- ...context.options,
98
- columnFor: binding.columnFor
99
- }
100
- };
101
- const filterSql = node.filter === void 0 ? void 0 : compilePredicate(node.filter, itemContext);
102
- return {
103
- table,
104
- join: binding.join,
105
- itemContext,
106
- filterSql
107
- };
108
- }
109
- /**
110
- * Compiles a `portableMatches`/`portableNotMatches` node's pattern operand: parses `node.right`'s text as a `trilean-regex` pattern and translates it into this compilation's own dialect's native pattern syntax (see `portable-pattern.ts`), binding the *translated* string as the placeholder rather than the original pattern text -- from the database's point of view this is an ordinary match against a pattern in its own syntax, not `trilean-regex`'s.
111
- *
112
- * `findUnpushableNodeKind` already ran this exact parse-and-translate step before compilation started and refused the tree if it threw (see `guard.ts`), so a throw reaching here means the guard's allow-list has drifted from what this function actually accepts -- wrapped into `UnsupportedNodeError` as the same "passed the pushability check but has no compiler branch" safety net `refuse` provides elsewhere in this file, not an outcome reachable through this module's own public API.
113
- */
114
- function compilePortablePattern(node, context) {
115
- if (node.right.kind !== "textLiteral") return refuse(node.right.kind, "expression");
116
- try {
117
- const ast = (0, trilean_regex.parseRegex)(node.right.value);
118
- return placeholder(context, context.options.dialect === "postgres" ? require_portable_pattern.renderPostgresPattern(ast) : require_portable_pattern.renderSqliteGlobPattern(ast), "text");
119
- } catch (error) {
120
- throw new require_errors.UnsupportedNodeError({
121
- kind: node.right.kind,
122
- path: "$.right",
123
- reason: error instanceof Error ? error.message : String(error)
124
- });
125
- }
126
- }
127
- /**
128
- * Whether an operand is an instant, as far as the compiler can tell without running anything: an `instantLiteral`, a column declared `"timestamp"`, or a `fold(max|min)` over one. A comparison or membership with any such operand compares all its operands as points in time ({@link DialectConfig.instantColumn}), since the other side of a comparison the evaluator answers definitely is an instant too.
129
- */
130
- function isInstant(node, context) {
131
- if (node.kind === "instantLiteral") return true;
132
- if (node.kind === "reference") return bindingOf(context, node)?.binding.paramType === "timestamp";
133
- if (node.kind === "fold" && node.combiner.mode !== "reduce" && typeof node.collection === "string" && context.options.collectionFor !== void 0) {
134
- const binding = context.options.collectionFor(node.collection);
135
- return isInstant(node.combiner.item, {
136
- ...context,
137
- options: {
138
- ...context.options,
139
- columnFor: binding.columnFor
140
- }
141
- });
142
- }
143
- return false;
144
- }
145
- /** Whether any of the operands of a comparison or membership is an instant. */
146
- function anyInstant(nodes, context) {
147
- return nodes.some((node) => isInstant(node, context));
148
- }
149
- /**
150
- * Compiles an expression. `asInstant` renders an instant-valued operand as the dialect's comparable point in time rather than as its stored text ({@link DialectConfig.instantColumn}); it is set for every operand of a comparison or membership that has an instant operand, and reaches the item of a `fold` so a maximum or minimum is of points in time, not of text.
151
- */
152
- function compileExpression(node, context, asInstant = false) {
153
- switch (node.kind) {
154
- case "reference": {
155
- const resolved = bindingOf(context, node);
156
- if (resolved === void 0) return refuse(node.kind, "expression");
157
- const column = quoteColumn(resolved.referenceKey, resolved.binding);
158
- return asInstant ? context.dialect.instantColumn(column) : column;
159
- }
160
- case "instantLiteral": return placeholder(context, asInstant ? context.dialect.instantParameter(node.value) : node.value, PARAM_TYPE_OF_LITERAL[node.kind]);
161
- case "textLiteral":
162
- case "numberLiteral":
163
- case "booleanLiteral": return placeholder(context, node.value, PARAM_TYPE_OF_LITERAL[node.kind]);
164
- case "fold": {
165
- if (node.combiner.mode === "reduce") return refuse(node.kind, "expression");
166
- const { table, join, itemContext, filterSql } = compileCollection(node, context, "expression");
167
- const itemValueSql = compileExpression(node.combiner.item, itemContext, asInstant);
168
- const participating = `SELECT "filter_ok", "item_value" FROM (SELECT ${filterSql ?? "TRUE"} AS "filter_ok", ${itemValueSql} AS "item_value" FROM ${table} WHERE ${join}) AS "t" WHERE "filter_ok" IS NULL OR "filter_ok"`;
169
- return `(SELECT CASE WHEN MAX(CASE WHEN "filter_ok" IS NULL OR "item_value" IS NULL THEN 1 ELSE 0 END) = 1 THEN NULL ELSE ${node.combiner.mode === "max" ? "MAX" : "MIN"}("item_value") END FROM (${participating}) AS "v")`;
170
- }
171
- }
172
- return refuse(node.kind, "expression");
173
- }
174
- function compilePredicate(node, context) {
175
- switch (node.kind) {
176
- case "not": return `(NOT ${compilePredicate(node.operand, context)})`;
177
- case "and": return `(${compilePredicate(node.left, context)} AND ${compilePredicate(node.right, context)})`;
178
- case "or": return `(${compilePredicate(node.left, context)} OR ${compilePredicate(node.right, context)})`;
179
- case "allOf":
180
- case "anyOf": {
181
- if (node.operands.length === 0) return node.kind === "allOf" ? "(TRUE)" : "(FALSE)";
182
- const joiner = node.kind === "allOf" ? " AND " : " OR ";
183
- return `(${node.operands.map((operand) => compilePredicate(operand, context)).join(joiner)})`;
184
- }
185
- case "compare": {
186
- const instants = anyInstant([node.left, node.right], context);
187
- const left = compileExpression(node.left, context, instants);
188
- const right = compileExpression(node.right, context, instants);
189
- return `(${left} ${COMPARISON_SQL[node.op]} ${right})`;
190
- }
191
- case "textCompare": {
192
- const left = compileExpression(node.left, context);
193
- const right = node.op === "portableMatches" || node.op === "portableNotMatches" ? compilePortablePattern(node, context) : compileExpression(node.right, context);
194
- return `(${left} ${context.textComparison[node.op]} ${right})`;
195
- }
196
- case "memberOf": {
197
- const instants = anyInstant([node.operand, ...node.candidates], context);
198
- const operand = compileExpression(node.operand, context, instants);
199
- if (node.candidates.length === 0) {
200
- const nullLiteral = `NULL${context.dialect.emptyMemberOfNullSuffix}`;
201
- return node.op === "in" ? `(${operand} IS NULL AND ${nullLiteral})` : `(${operand} IS NOT NULL OR ${nullLiteral})`;
202
- }
203
- const candidates = node.candidates.map((candidate) => compileExpression(candidate, context, instants)).join(", ");
204
- return `(${operand} ${node.op === "in" ? "IN" : "NOT IN"} (${candidates}))`;
205
- }
206
- case "exists": return `(${compileExpression(node.operand, context)} IS NOT NULL)`;
207
- case "some":
208
- case "every": {
209
- const { table, join, itemContext, filterSql } = compileCollection(node, context, "predicate");
210
- const itemSql = compilePredicate(node.item, itemContext);
211
- const participating = `SELECT "filter_ok", "item_ok" FROM (SELECT ${filterSql ?? "TRUE"} AS "filter_ok", ${itemSql} AS "item_ok" FROM ${table} WHERE ${join}) AS "t" WHERE "filter_ok" IS NULL OR "filter_ok"`;
212
- if (node.kind === "some") return `(SELECT CASE WHEN MAX(CASE WHEN "filter_ok" AND "item_ok" THEN 1 ELSE 0 END) = 1 THEN TRUE WHEN MAX(CASE WHEN "filter_ok" IS NULL OR "item_ok" IS NULL THEN 1 ELSE 0 END) = 1 THEN NULL ELSE FALSE END FROM (${participating}) AS "v")`;
213
- return `(SELECT CASE WHEN MAX(CASE WHEN "filter_ok" AND "item_ok" IS NOT NULL AND NOT "item_ok" THEN 1 ELSE 0 END) = 1 THEN FALSE WHEN MAX(CASE WHEN "filter_ok" IS NULL OR "item_ok" IS NULL THEN 1 ELSE 0 END) = 1 THEN NULL ELSE TRUE END FROM (${participating}) AS "v")`;
214
- }
215
- }
216
- return refuse(node.kind, "predicate");
217
- }
218
- /**
219
- * Compiles a trilean predicate tree into a parameterised boolean expression in the dialect `options` names.
220
- *
221
- * Three-valued logic is not reimplemented on top of SQL; it is delegated to it. SQL's `AND`, `OR` and `NOT` over `TRUE`/`FALSE`/`NULL` are Kleene's strong three-valued tables, which are the same tables trilean's own `combineAnd`, `combineOr` and `not` implement, and a comparison against a NULL column yields `NULL` exactly where the evaluator would have returned `indeterminate` from an unresolved reference. A row excluded by `WHERE` because its condition was unknown is therefore excluded for the same reason, and by the same rule, as a subject the evaluator declines to judge. No indeterminacy column, sentinel value or `CASE` scaffolding is emitted, because none is needed.
222
- *
223
- * Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
224
- * @throws `UnknownDialectError` if `options.dialect` names a dialect this version does not implement.
225
- * @throws `UnsupportedNodeError` if any node in the tree is one this compiler will not translate -- see `findUnpushableNodeKind`, which this runs first and which a caller can run itself to choose between pushdown and in-process evaluation without provoking an exception.
226
- * @throws `InvalidColumnError` if `columnFor` returns a column that cannot be rendered as an identifier.
227
- */
228
- function compilePredicateNode(node, options) {
229
- require_options.assertImplementedDialect(options.dialect);
230
- const bindings = /* @__PURE__ */ new Map();
231
- const collectionBindings = /* @__PURE__ */ new Map();
232
- const collectionFor = options.collectionFor;
233
- const memoised = {
234
- dialect: options.dialect,
235
- postgresRegexpPushdown: options.postgresRegexpPushdown,
236
- columnFor: (referenceKey) => {
237
- const cached = bindings.get(referenceKey);
238
- if (cached !== void 0) return cached;
239
- const binding = options.columnFor(referenceKey);
240
- bindings.set(referenceKey, binding);
241
- return binding;
242
- },
243
- sqliteRegexpAvailable: options.sqliteRegexpAvailable,
244
- ...collectionFor !== void 0 && { collectionFor: (collectionKey) => {
245
- const cached = collectionBindings.get(collectionKey);
246
- if (cached !== void 0) return cached;
247
- const binding = collectionFor(collectionKey);
248
- const columnBindings = /* @__PURE__ */ new Map();
249
- const memoisedBinding = {
250
- table: binding.table,
251
- join: binding.join,
252
- columnFor: (referenceKey) => {
253
- const cachedColumn = columnBindings.get(referenceKey);
254
- if (cachedColumn !== void 0) return cachedColumn;
255
- const columnBinding = binding.columnFor(referenceKey);
256
- columnBindings.set(referenceKey, columnBinding);
257
- return columnBinding;
258
- }
259
- };
260
- collectionBindings.set(collectionKey, memoisedBinding);
261
- return memoisedBinding;
262
- } }
263
- };
264
- const unpushable = require_guard.findUnpushableNodeKind(node, memoised);
265
- if (unpushable !== void 0) throw new require_errors.UnsupportedNodeError(unpushable);
266
- const dialect = require_options.DIALECT_CONFIG[options.dialect];
267
- const context = {
268
- options: memoised,
269
- dialect,
270
- textComparison: textComparisonSqlFor(dialect),
271
- params: []
272
- };
273
- return {
274
- sql: compilePredicate(node, context),
275
- params: context.params
276
- };
277
- }
278
- exports.compilePredicateNode = compilePredicateNode;
@@ -1,13 +0,0 @@
1
- import { CompiledSql, SqlCompileOptions } from "./options.cjs";
2
- import { PredicateNode } from "trilean";
3
- /**
4
- * Compiles a trilean predicate tree into a parameterised boolean expression in the dialect `options` names.
5
- *
6
- * Three-valued logic is not reimplemented on top of SQL; it is delegated to it. SQL's `AND`, `OR` and `NOT` over `TRUE`/`FALSE`/`NULL` are Kleene's strong three-valued tables, which are the same tables trilean's own `combineAnd`, `combineOr` and `not` implement, and a comparison against a NULL column yields `NULL` exactly where the evaluator would have returned `indeterminate` from an unresolved reference. A row excluded by `WHERE` because its condition was unknown is therefore excluded for the same reason, and by the same rule, as a subject the evaluator declines to judge. No indeterminacy column, sentinel value or `CASE` scaffolding is emitted, because none is needed.
7
- *
8
- * Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
9
- * @throws `UnknownDialectError` if `options.dialect` names a dialect this version does not implement.
10
- * @throws `UnsupportedNodeError` if any node in the tree is one this compiler will not translate -- see `findUnpushableNodeKind`, which this runs first and which a caller can run itself to choose between pushdown and in-process evaluation without provoking an exception.
11
- * @throws `InvalidColumnError` if `columnFor` returns a column that cannot be rendered as an identifier.
12
- */
13
- export declare function compilePredicateNode(node: PredicateNode, options: Readonly<SqlCompileOptions>): CompiledSql;
package/dist/errors.cjs DELETED
@@ -1,80 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- // src/errors.ts
3
- /** Base class for every error this package raises, so a caller can distinguish a compilation failure from an error thrown by its own `columnFor` (which is called during compilation and whose exceptions propagate unchanged). */
4
- var TrileanSqlError = class extends Error {
5
- constructor(message) {
6
- super(message);
7
- this.name = "TrileanSqlError";
8
- }
9
- };
10
- /**
11
- * A node the compiler refuses to translate. The compiler never degrades: there is no "best effort" fragment, no silently dropped conjunct, and no approximation that answers differently from the in-process evaluator. Either the whole tree compiles to SQL that agrees with `evaluatePredicate` on every row, or this is thrown and the caller evaluates in process instead.
12
- *
13
- * That guarantee is about the tree's *structure*, and it stops at two things whose meaning is a property of the operand's own content rather than of any node kind: a `matches`/`notMatches` pattern, which the server matches under its own regular-expression language rather than ECMAScript's, and an `instantLiteral` string the database reads differently from trilean or cannot read at all (which fails as a query error at execution time, not as this exception). Both are covered in README.md; neither is detectable by a walk over node kinds.
14
- *
15
- * `nodeKind` is the offending node's own `kind`, `path` locates it inside the tree, and `reason` says why it is not pushable -- which is not always about the kind alone (a `reference` carrying a `unit`, or a `compare` whose operands are statically of different kinds, are both refused despite `reference` and `compare` being supported kinds).
16
- */
17
- var UnsupportedNodeError = class extends TrileanSqlError {
18
- nodeKind;
19
- path;
20
- reason;
21
- constructor(unpushable) {
22
- super(`cannot compile '${unpushable.kind}' at ${unpushable.path}: ${unpushable.reason}`);
23
- this.name = "UnsupportedNodeError";
24
- this.nodeKind = unpushable.kind;
25
- this.path = unpushable.path;
26
- this.reason = unpushable.reason;
27
- }
28
- };
29
- /**
30
- * A dialect this version does not implement.
31
- *
32
- * `SqlDialect` is a closed union, so a caller who names a dialect in TypeScript source cannot reach this. A dialect read from configuration and asserted into the type at the boundary can, which is the case it exists for: without it the unimplemented name surfaces later as an internal `TypeError` from a table lookup that found nothing, naming neither the dialect nor the field it was reached from. Refusing by name at the entry point is the same convention `InvalidColumnError` applies to a `columnFor` result and the node walk applies to an unrecognised kind -- an input the type system describes but cannot enforce is checked once, where it arrives.
33
- *
34
- * `dialect` is the offending name and `implemented` lists the ones this version does compile.
35
- */
36
- var UnknownDialectError = class extends TrileanSqlError {
37
- dialect;
38
- implemented;
39
- constructor(dialect, implemented) {
40
- super(`unknown dialect ${JSON.stringify(dialect)}: this version compiles ${implemented.map((name) => JSON.stringify(name)).join(", ")}`);
41
- this.name = "UnknownDialectError";
42
- this.dialect = dialect;
43
- this.implemented = implemented;
44
- }
45
- };
46
- /**
47
- * A `columnFor` result whose `column` cannot be rendered as a SQL identifier.
48
- *
49
- * A column name is an identifier, not a value, so it is the one part of the emitted SQL that cannot be parameterised -- it has to be written into the statement text. It is always emitted double-quoted with any embedded quote doubled, which makes an arbitrary string safe, so this is not the injection defence; it rejects the two shapes that quoting cannot rescue into a valid identifier, an empty name and an empty dot-separated segment.
50
- */
51
- var InvalidColumnError = class extends TrileanSqlError {
52
- referenceKey;
53
- column;
54
- constructor(referenceKey, column, reason) {
55
- super(`columnFor(${JSON.stringify(referenceKey)}) returned ${JSON.stringify(column)}, which is not a usable column identifier: ${reason}`);
56
- this.name = "InvalidColumnError";
57
- this.referenceKey = referenceKey;
58
- this.column = column;
59
- }
60
- };
61
- /**
62
- * A `collectionFor` result whose `table` cannot be rendered as a SQL identifier.
63
- *
64
- * Mirrors `InvalidColumnError` exactly, for the correlated table a `some`/`every`/`fold` node compiles against instead of a mapped column: `table` is likewise an identifier that has to be written into the statement text rather than bound as a parameter, so this rejects the same two shapes quoting cannot rescue -- an empty name and an empty dot-separated segment.
65
- */
66
- var InvalidCollectionTableError = class extends TrileanSqlError {
67
- collectionKey;
68
- table;
69
- constructor(collectionKey, table, reason) {
70
- super(`collectionFor(${JSON.stringify(collectionKey)}) returned ${JSON.stringify(table)}, which is not a usable table identifier: ${reason}`);
71
- this.name = "InvalidCollectionTableError";
72
- this.collectionKey = collectionKey;
73
- this.table = table;
74
- }
75
- };
76
- exports.InvalidCollectionTableError = InvalidCollectionTableError;
77
- exports.InvalidColumnError = InvalidColumnError;
78
- exports.TrileanSqlError = TrileanSqlError;
79
- exports.UnknownDialectError = UnknownDialectError;
80
- exports.UnsupportedNodeError = UnsupportedNodeError;
package/dist/errors.d.cts DELETED
@@ -1,53 +0,0 @@
1
- /** Base class for every error this package raises, so a caller can distinguish a compilation failure from an error thrown by its own `columnFor` (which is called during compilation and whose exceptions propagate unchanged). */
2
- export declare class TrileanSqlError extends Error {
3
- constructor(message: string);
4
- }
5
- /**
6
- * A node the compiler refuses to translate. The compiler never degrades: there is no "best effort" fragment, no silently dropped conjunct, and no approximation that answers differently from the in-process evaluator. Either the whole tree compiles to SQL that agrees with `evaluatePredicate` on every row, or this is thrown and the caller evaluates in process instead.
7
- *
8
- * That guarantee is about the tree's *structure*, and it stops at two things whose meaning is a property of the operand's own content rather than of any node kind: a `matches`/`notMatches` pattern, which the server matches under its own regular-expression language rather than ECMAScript's, and an `instantLiteral` string the database reads differently from trilean or cannot read at all (which fails as a query error at execution time, not as this exception). Both are covered in README.md; neither is detectable by a walk over node kinds.
9
- *
10
- * `nodeKind` is the offending node's own `kind`, `path` locates it inside the tree, and `reason` says why it is not pushable -- which is not always about the kind alone (a `reference` carrying a `unit`, or a `compare` whose operands are statically of different kinds, are both refused despite `reference` and `compare` being supported kinds).
11
- */
12
- export declare class UnsupportedNodeError extends TrileanSqlError {
13
- readonly nodeKind: string;
14
- readonly path: string;
15
- readonly reason: string;
16
- constructor(unpushable: Readonly<{
17
- kind: string;
18
- path: string;
19
- reason: string;
20
- }>);
21
- }
22
- /**
23
- * A dialect this version does not implement.
24
- *
25
- * `SqlDialect` is a closed union, so a caller who names a dialect in TypeScript source cannot reach this. A dialect read from configuration and asserted into the type at the boundary can, which is the case it exists for: without it the unimplemented name surfaces later as an internal `TypeError` from a table lookup that found nothing, naming neither the dialect nor the field it was reached from. Refusing by name at the entry point is the same convention `InvalidColumnError` applies to a `columnFor` result and the node walk applies to an unrecognised kind -- an input the type system describes but cannot enforce is checked once, where it arrives.
26
- *
27
- * `dialect` is the offending name and `implemented` lists the ones this version does compile.
28
- */
29
- export declare class UnknownDialectError extends TrileanSqlError {
30
- readonly dialect: string;
31
- readonly implemented: readonly string[];
32
- constructor(dialect: string, implemented: readonly string[]);
33
- }
34
- /**
35
- * A `columnFor` result whose `column` cannot be rendered as a SQL identifier.
36
- *
37
- * A column name is an identifier, not a value, so it is the one part of the emitted SQL that cannot be parameterised -- it has to be written into the statement text. It is always emitted double-quoted with any embedded quote doubled, which makes an arbitrary string safe, so this is not the injection defence; it rejects the two shapes that quoting cannot rescue into a valid identifier, an empty name and an empty dot-separated segment.
38
- */
39
- export declare class InvalidColumnError extends TrileanSqlError {
40
- readonly referenceKey: string;
41
- readonly column: string;
42
- constructor(referenceKey: string, column: string, reason: string);
43
- }
44
- /**
45
- * A `collectionFor` result whose `table` cannot be rendered as a SQL identifier.
46
- *
47
- * Mirrors `InvalidColumnError` exactly, for the correlated table a `some`/`every`/`fold` node compiles against instead of a mapped column: `table` is likewise an identifier that has to be written into the statement text rather than bound as a parameter, so this rejects the same two shapes quoting cannot rescue -- an empty name and an empty dot-separated segment.
48
- */
49
- export declare class InvalidCollectionTableError extends TrileanSqlError {
50
- readonly collectionKey: string;
51
- readonly table: string;
52
- constructor(collectionKey: string, table: string, reason: string);
53
- }
@@ -1,16 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- // src/guard-test-helpers.ts
3
- /** Shared across the split `guard.*.test.ts` files below -- a pushable comparison used as filler in trees whose real subject is something else entirely (an unrelated node kind, a collection wrapper). */
4
- const ageOver = {
5
- kind: "compare",
6
- op: "gt",
7
- left: {
8
- kind: "reference",
9
- key: "age"
10
- },
11
- right: {
12
- kind: "numberLiteral",
13
- value: 18
14
- }
15
- };
16
- exports.ageOver = ageOver;
@@ -1,3 +0,0 @@
1
- import { PredicateNode } from "trilean";
2
- /** Shared across the split `guard.*.test.ts` files below -- a pushable comparison used as filler in trees whose real subject is something else entirely (an unrelated node kind, a collection wrapper). */
3
- export declare const ageOver: PredicateNode;
@@ -1,3 +0,0 @@
1
- import { PredicateNode } from "trilean";
2
- /** Shared across the split `guard.*.test.ts` files below -- a pushable comparison used as filler in trees whose real subject is something else entirely (an unrelated node kind, a collection wrapper). */
3
- export declare const ageOver: PredicateNode;
@@ -1,15 +0,0 @@
1
- // src/guard-test-helpers.ts
2
- /** Shared across the split `guard.*.test.ts` files below -- a pushable comparison used as filler in trees whose real subject is something else entirely (an unrelated node kind, a collection wrapper). */
3
- const ageOver = {
4
- kind: "compare",
5
- op: "gt",
6
- left: {
7
- kind: "reference",
8
- key: "age"
9
- },
10
- right: {
11
- kind: "numberLiteral",
12
- value: 18
13
- }
14
- };
15
- export { ageOver };
package/dist/guard.d.cts DELETED
@@ -1,22 +0,0 @@
1
- import { SqlCompileOptions } from "./options.cjs";
2
- import { PredicateNode } from "trilean";
3
- /** Where the walk stopped, and why. `kind` is the offending node's own `kind` even when the objection is not to the kind itself. */
4
- export interface UnpushableNode {
5
- kind: string;
6
- /** A dotted path from the root of the tree, e.g. `$.operands[1].left`. */
7
- path: string;
8
- reason: string;
9
- }
10
- /**
11
- * Walks the tree against the allow-list of what this compiler translates, and reports the first node it will not.
12
- *
13
- * 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.
14
- *
15
- * `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.
16
- *
17
- * 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`).
18
- *
19
- * 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.
20
- * @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.
21
- */
22
- export declare function findUnpushableNodeKind(node: PredicateNode, options?: SqlCompileOptions): UnpushableNode | undefined;
package/dist/index.cjs DELETED
@@ -1,10 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_guard = require("./guard.cjs");
3
- const require_compile = require("./compile.cjs");
4
- const require_errors = require("./errors.cjs");
5
- exports.InvalidColumnError = require_errors.InvalidColumnError;
6
- exports.TrileanSqlError = require_errors.TrileanSqlError;
7
- exports.UnknownDialectError = require_errors.UnknownDialectError;
8
- exports.UnsupportedNodeError = require_errors.UnsupportedNodeError;
9
- exports.compilePredicateNode = require_compile.compilePredicateNode;
10
- exports.findUnpushableNodeKind = require_guard.findUnpushableNodeKind;
package/dist/index.d.cts DELETED
@@ -1,5 +0,0 @@
1
- import { CompiledSql, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType } from "./options.cjs";
2
- import { UnpushableNode, findUnpushableNodeKind } from "./guard.cjs";
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 };
@@ -1,126 +0,0 @@
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
- });