trilean-sql 2.1.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -80,6 +80,8 @@ Returns `{ sql, params }`. Throws rather than approximating; see [Refusal](#refu
80
80
 
81
81
  `options.postgresRegexpPushdown`, `false` by default, governs whether `matches`/`notMatches` may compile to PostgreSQL's own `~`/`!~` at all. See [Regular expressions](#regular-expressions) for why the default refuses them.
82
82
 
83
+ `options.collectionFor(collectionKey)` maps a `some`/`every`/`fold` node's `collection` key onto `{ table, join, columnFor }` — see [Collections](#collections). Optional: a tree that never uses one of those kinds never calls it, and leaving it unset is fully backward compatible with every version before it existed.
84
+
83
85
  ### `findUnpushableNodeKind(node, options?)`
84
86
 
85
87
  Returns `{ kind, path, reason }` for the first node the compiler will not translate, or `undefined` if the whole tree is pushable. `compilePredicateNode` runs it first and throws on any result, so call it yourself only to *choose* between pushdown and in-process evaluation without provoking an exception:
@@ -95,7 +97,7 @@ Passing `options` widens the check: without them the walk is purely structural;
95
97
 
96
98
  ### Errors
97
99
 
98
- `UnsupportedNodeError` (carrying `nodeKind`, `path`, `reason`) and `InvalidColumnError` (carrying `referenceKey`, `column`), both extending `TrileanSqlError`.
100
+ `UnsupportedNodeError` (carrying `nodeKind`, `path`, `reason`), `InvalidColumnError` (carrying `referenceKey`, `column`) and `InvalidCollectionTableError` (carrying `collectionKey`, `table`), all extending `TrileanSqlError`.
99
101
 
100
102
  ## What compiles
101
103
 
@@ -107,6 +109,8 @@ Passing `options` widens the check: without them the walk is purely structural;
107
109
  | `textCompare` | `=`, `<>`; `matches`/`notMatches` only once `postgresRegexpPushdown` opts in, otherwise refused (see [Regular expressions](#regular-expressions)); `~`/`!~` against a translated pattern for `portableMatches`/`portableNotMatches`, no opt-in needed | `=`, `<>`; `REGEXP`/`NOT REGEXP` for `matches`/`notMatches`; `GLOB`/`NOT GLOB` against a translated pattern for `portableMatches`/`portableNotMatches` |
108
110
  | `memberOf` | `IN` / `NOT IN`, one parameter per candidate | same |
109
111
  | `exists` | `IS NOT NULL` | same |
112
+ | `some`, `every` | a correlated scalar subquery over `collectionFor`'s table, combining each participating row's own vote with `MAX`/`CASE` to match the evaluator's OR/AND-fold absorption exactly (see [Collections](#collections)); refused unless `collectionFor` maps the `collection` key | same |
113
+ | `fold` (`max`/`min`) | the same correlated subquery, aggregating each participating item's own projected value with `MAX`/`MIN`, `NULL` the moment any participating item (or its `filter`) is indeterminate (see [Collections](#collections)); refused unless `collectionFor` maps the `collection` key. `fold` (`reduce`) is always refused — see [Refusal](#refusal) | same |
110
114
  | `reference` | the mapped column, as a quoted identifier | same |
111
115
  | `textLiteral`, `numberLiteral`, `booleanLiteral`, `instantLiteral` | a bind parameter, cast to `text`, `double precision`, `boolean`, `timestamptz` | a bare `?`, uncast |
112
116
 
@@ -116,6 +120,26 @@ PostgreSQL placeholders are always cast. That is not decoration: PostgreSQL reje
116
120
 
117
121
  An empty `memberOf` candidate list is worth a note, because `IN ()` is a syntax error and the two constants it is tempting to fold to are both wrong. An empty `in` is false and an empty `notIn` is true only once the operand itself is known, and both stay unknown while it is `NULL`. The compiled forms — `(x IS NULL AND NULL::boolean)` and `(x IS NOT NULL OR NULL::boolean)`, and the same two without the cast under SQLite, which has no boolean type to annotate — reproduce that exactly, which a bare `FALSE`/`TRUE` would not, most visibly under a surrounding `NOT`.
118
122
 
123
+ ## Collections
124
+
125
+ `some`, `every`, and `fold` (`max`/`min`) range over a `collection` the caller's resolvers supply — in `trilean` itself an opaque key resolved to an arbitrary in-memory list at evaluation time, with no assumption it is this query's row set at all. This package can push one down only when the caller states that the collection *is* a correlated table: `options.collectionFor(collectionKey)` returns
126
+
127
+ ```ts
128
+ interface SqlCollectionBinding {
129
+ table: string; // dot-qualified, quoted exactly like a mapped column's `column`
130
+ join: string; // raw boolean SQL relating one row of `table` to the outer row
131
+ columnFor: (referenceKey: string) => SqlColumnBinding; // resolves a reference *inside* item/filter
132
+ }
133
+ ```
134
+
135
+ `join` is caller-authored rather than assembled from a join-column pair, because only the caller knows the real join shape — a single foreign key, a composite key, or an entity-attribute-value table's foreign key plus a literal discriminator (`"attrs"."nodeId" = "graph_nodes"."id" AND "attrs"."attrName" = 'voltageLevel'`). `columnFor` is a second, independent mapping from the outer one: it resolves a reference inside the collection's own `item`/`filter`, exactly as trilean's own evaluator re-points its `EvaluationContext` at the collection item before evaluating either. A tree that never uses `some`, `every`, or `fold(max|min)` never calls `collectionFor` — leaving it unset is fully backward compatible. A tree that does use one of those kinds without it set is refused with `UnsupportedNodeError`, the same refused outcome those kinds had before this option existed.
136
+
137
+ `some`/`every` compile to a correlated scalar subquery: `SELECT filter, item FROM table WHERE join`, filtered down to the participating rows (`filter IS NULL OR filter`, dropping only the rows `filter` excluded outright), then combined with `MAX`/`CASE` to match the evaluator's own OR/AND-fold absorption exactly — `some` is true the moment any participating row's `item` is true, regardless of another row's indeterminacy; indeterminate only once no row voted true and at least one participated indeterminately (an indeterminate `filter`, or an indeterminate `item`); false once neither, including an empty participating set (no rows, or every row filtered out), which is `some`'s own identity. `every` is the mirror image: false the moment any participating row's `item` is definitely false, indeterminate only once neither that nor "every row voted true" holds, and true — including on an empty participating set — otherwise.
138
+
139
+ `fold(max|min)` compiles the same correlated subquery over the projected value instead of a predicate, and aggregates with `MAX`/`MIN` directly: `NULL` (indeterminate) the moment any participating row's `filter` or projected value is itself indeterminate — matching the evaluator's `firstFilterIndeterminate`/per-item short-circuit exactly, which has no absorbing value the way `some`/`every`'s OR/AND does — and the aggregate otherwise, including `NULL` from an empty participating set, matching the evaluator's own `domain-error` indeterminate for a fold with nothing to seed a running extremum from. `fold(reduce)` is always refused, with or without `collectionFor` set: it threads an arbitrary combine expression through the collection in a caller-chosen order, which has no general SQL translation.
140
+
141
+ A `fold(max|min)` whose projected item is statically known to be text or boolean is refused, the same way a `compare` against one of those kinds is (see [Refusal](#refusal)): trilean's own ordering (`compareValues`) refuses to order either, for exactly one item it would happily return definite, but the moment a second item participates it goes indeterminate — a divergence undetectable from a fixed pair of operands the way `compare`'s is, since a collection's real cardinality is only known at query time, so it is refused unconditionally rather than only when two or more rows are proven to participate.
142
+
119
143
  ## Dialects
120
144
 
121
145
  The dialects differ in three places, and nowhere else. `matches`/`notMatches` compile to each engine's own regular-expression operator; placeholders are `$N::type` under PostgreSQL and a bare `?` under SQLite; and the bare `NULL` in an empty `memberOf` carries a `::boolean` annotation only where there is a boolean type to annotate. Everything else the compiler emits — the connectives, the six comparison operators, `=`/`<>`, `IN`/`NOT IN`, `IS NOT NULL`, quoted identifiers — is ANSI-standard and identical.
@@ -149,7 +173,7 @@ A `matches`/`notMatches` pattern would be the same kind of limit — matched by
149
173
 
150
174
  Every refusal below applies to both dialects. What changes with the dialect is the `reason` text, which names the mechanism that actually applies to the engine you are compiling for — a `findUnpushableNodeKind` call given no `options` has no dialect to read and describes PostgreSQL, the one these refusals were first derived against.
151
175
 
152
- **Kinds this version does not translate.** `some`, `every`, `fold`: these range over a collection the caller's resolvers supply, which is not the query's row set. `lookup`, `call`, `delegate`, `treeReference`: each is resolved by something the database has no access to — the caller's resolvers, its function registry, an external system. `conditional`: not implemented here. `accumulator`: only meaningful inside a `reduce` fold. `arithmetic` and `negate`: these carry and combine units, and pushing them down would drop that dimensional analysis without saying so. `durationLiteral`: trilean compares durations by normalising both operands to milliseconds, with no column-level equivalent to normalise against. `complexLiteral`: neither engine has a complex type.
176
+ **Kinds this version does not translate.** `some`, `every`, `fold(max|min)`: refused unless `options.collectionFor` maps the `collection` key onto a correlated table — see [Collections](#collections). `fold(reduce)`: always refused, `collectionFor` or not — it threads an arbitrary combine expression through the collection in a caller-chosen order, which has no general SQL translation. `lookup`, `call`, `delegate`, `treeReference`: each is resolved by something the database has no access to — the caller's resolvers, its function registry, an external system. `conditional`: not implemented here. `accumulator`: only meaningful inside a `reduce` fold. `arithmetic` and `negate`: these carry and combine units, and pushing them down would drop that dimensional analysis without saying so. `durationLiteral`: trilean compares durations by normalising both operands to milliseconds, with no column-level equivalent to normalise against. `complexLiteral`: neither engine has a complex type.
153
177
 
154
178
  **Shapes refused despite a supported kind.** A `reference` whose key is not a string, since there is nothing to map. A `reference` or `numberLiteral` carrying a `unit`: a unit on a reference asserts that the resolved value carries the same one, and a column has no unit for that assertion to be checked against. A `numberLiteral` of `NaN`, which trilean compares with `===` — under which NaN equals nothing including itself — and neither engine reproduces, for opposite reasons. PostgreSQL defines NaN as equal to itself and greater than every other double, so `NaN = NaN` selects every row there and none here. SQLite has no NaN at all and a driver binding one substitutes SQL `NULL`, so the same comparison is *indeterminate* there and matches nothing — which looks like agreement until you negate it, at which point trilean's definite `true` matches every row and SQLite's `NULL` still matches none. Infinities are not refused alongside it; every engine here orders them identically.
155
179
 
@@ -159,6 +183,7 @@ Every refusal below applies to both dialects. What changes with the dialect is t
159
183
  - An ordering `compare` (`gt`/`gte`/`lt`/`lte`) against a boolean. trilean has no order for booleans; PostgreSQL orders `false` before `true`, and SQLite orders the integers 0 and 1 it stores them as.
160
184
  - A `textCompare` against a non-text operand, which trilean treats as `wrong-type`.
161
185
  - Any comparison whose operands are of different declared kinds — a number against an instant, say. trilean calls that `wrong-type`; both engines may coerce one to the other and answer definitely.
186
+ - A `fold(max|min)`'s projected item against text or boolean. trilean has no order for either (`compareValues` returns `wrong-type` the moment a second item is compared); `MAX`/`MIN` happily orders text lexicographically and booleans as `0`/`1` the moment two or more rows participate. Unlike the other pairings above, this one is refused unconditionally rather than only when a fixed pair of operands proves the mismatch, because a collection's real cardinality is only known at query time.
162
187
 
163
188
  Left undeclared, these compile, and the divergence is real but invisible. That is the whole argument for supplying `paramType`.
164
189
 
@@ -0,0 +1,75 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_compile = require("./compile.cjs");
3
+ //#region src/test-support/columns.ts
4
+ /**
5
+ * The schema the unit tests and every integration suite compile against, so a fragment asserted as a string in one is the same fragment executed against a real engine in the others.
6
+ *
7
+ * `age`, `name`, `active` and `joined` each declare a `paramType`; `note` deliberately does not, which is what exercises the compiler's undeclared-column path (no operand-kind checking, and literal placeholders rendered by their own kind instead of the column's).
8
+ */
9
+ const SUBJECT_COLUMNS = {
10
+ age: {
11
+ column: "age",
12
+ paramType: "number"
13
+ },
14
+ name: {
15
+ column: "name",
16
+ paramType: "text"
17
+ },
18
+ active: {
19
+ column: "active",
20
+ paramType: "boolean"
21
+ },
22
+ joined: {
23
+ column: "joined",
24
+ paramType: "timestamp"
25
+ },
26
+ note: { column: "note" }
27
+ };
28
+ function columnForSubject(referenceKey) {
29
+ const binding = SUBJECT_COLUMNS[referenceKey];
30
+ if (binding === void 0) throw new Error(`no column mapped for reference key '${referenceKey}'`);
31
+ return binding;
32
+ }
33
+ const subjectOptions = {
34
+ dialect: "postgres",
35
+ columnFor: columnForSubject
36
+ };
37
+ /** The same mapping compiled for SQLite. Sharing `columnFor` is the point: a column mapping is a property of the schema, not of the dialect, so the only difference between the two suites' options is the dialect they name. */
38
+ const sqliteSubjectOptions = {
39
+ dialect: "sqlite",
40
+ columnFor: columnForSubject
41
+ };
42
+ ({ ...subjectOptions });
43
+ ({ ...subjectOptions });
44
+ ({ ...sqliteSubjectOptions });
45
+ //#endregion
46
+ //#region src/compile-test-helpers.ts
47
+ /** Compiles against `subjectOptions` by default, so each split `compile.*.test.ts` file below only has to name a dialect/column configuration explicitly when it actually differs from the shared default. */
48
+ function compile(node, options = subjectOptions) {
49
+ return require_compile.compilePredicateNode(node, options);
50
+ }
51
+ const ADULT_AGE = 18;
52
+ const SAMPLE_AGE = 40;
53
+ const EXCLUDED_AGE = 7;
54
+ const LOWER_BOUND = 1;
55
+ const UPPER_BOUND = 4;
56
+ const ageOver = {
57
+ kind: "compare",
58
+ op: "gt",
59
+ left: {
60
+ kind: "reference",
61
+ key: "age"
62
+ },
63
+ right: {
64
+ kind: "numberLiteral",
65
+ value: 18
66
+ }
67
+ };
68
+ //#endregion
69
+ exports.ADULT_AGE = ADULT_AGE;
70
+ exports.EXCLUDED_AGE = EXCLUDED_AGE;
71
+ exports.LOWER_BOUND = LOWER_BOUND;
72
+ exports.SAMPLE_AGE = SAMPLE_AGE;
73
+ exports.UPPER_BOUND = UPPER_BOUND;
74
+ exports.ageOver = ageOver;
75
+ exports.compile = compile;
@@ -0,0 +1,13 @@
1
+ import { CompiledSql, SqlCompileOptions } from "./options.cjs";
2
+ import { PredicateNode } from "trilean";
3
+ //#region src/compile-test-helpers.d.ts
4
+ /** Compiles against `subjectOptions` by default, so each split `compile.*.test.ts` file below only has to name a dialect/column configuration explicitly when it actually differs from the shared default. */
5
+ declare function compile(node: PredicateNode, options?: Readonly<SqlCompileOptions>): CompiledSql;
6
+ declare const ADULT_AGE = 18;
7
+ declare const SAMPLE_AGE = 40;
8
+ declare const EXCLUDED_AGE = 7;
9
+ declare const LOWER_BOUND = 1;
10
+ declare const UPPER_BOUND = 4;
11
+ declare const ageOver: PredicateNode;
12
+ //#endregion
13
+ export { ADULT_AGE, EXCLUDED_AGE, LOWER_BOUND, SAMPLE_AGE, UPPER_BOUND, ageOver, compile };
@@ -0,0 +1,13 @@
1
+ import { CompiledSql, SqlCompileOptions } from "./options.js";
2
+ import { PredicateNode } from "trilean";
3
+ //#region src/compile-test-helpers.d.ts
4
+ /** Compiles against `subjectOptions` by default, so each split `compile.*.test.ts` file below only has to name a dialect/column configuration explicitly when it actually differs from the shared default. */
5
+ declare function compile(node: PredicateNode, options?: Readonly<SqlCompileOptions>): CompiledSql;
6
+ declare const ADULT_AGE = 18;
7
+ declare const SAMPLE_AGE = 40;
8
+ declare const EXCLUDED_AGE = 7;
9
+ declare const LOWER_BOUND = 1;
10
+ declare const UPPER_BOUND = 4;
11
+ declare const ageOver: PredicateNode;
12
+ //#endregion
13
+ export { ADULT_AGE, EXCLUDED_AGE, LOWER_BOUND, SAMPLE_AGE, UPPER_BOUND, ageOver, compile };
@@ -0,0 +1,68 @@
1
+ import { compilePredicateNode } from "./compile.js";
2
+ //#region src/test-support/columns.ts
3
+ /**
4
+ * The schema the unit tests and every integration suite compile against, so a fragment asserted as a string in one is the same fragment executed against a real engine in the others.
5
+ *
6
+ * `age`, `name`, `active` and `joined` each declare a `paramType`; `note` deliberately does not, which is what exercises the compiler's undeclared-column path (no operand-kind checking, and literal placeholders rendered by their own kind instead of the column's).
7
+ */
8
+ const SUBJECT_COLUMNS = {
9
+ age: {
10
+ column: "age",
11
+ paramType: "number"
12
+ },
13
+ name: {
14
+ column: "name",
15
+ paramType: "text"
16
+ },
17
+ active: {
18
+ column: "active",
19
+ paramType: "boolean"
20
+ },
21
+ joined: {
22
+ column: "joined",
23
+ paramType: "timestamp"
24
+ },
25
+ note: { column: "note" }
26
+ };
27
+ function columnForSubject(referenceKey) {
28
+ const binding = SUBJECT_COLUMNS[referenceKey];
29
+ if (binding === void 0) throw new Error(`no column mapped for reference key '${referenceKey}'`);
30
+ return binding;
31
+ }
32
+ const subjectOptions = {
33
+ dialect: "postgres",
34
+ columnFor: columnForSubject
35
+ };
36
+ /** The same mapping compiled for SQLite. Sharing `columnFor` is the point: a column mapping is a property of the schema, not of the dialect, so the only difference between the two suites' options is the dialect they name. */
37
+ const sqliteSubjectOptions = {
38
+ dialect: "sqlite",
39
+ columnFor: columnForSubject
40
+ };
41
+ ({ ...subjectOptions });
42
+ ({ ...subjectOptions });
43
+ ({ ...sqliteSubjectOptions });
44
+ //#endregion
45
+ //#region src/compile-test-helpers.ts
46
+ /** Compiles against `subjectOptions` by default, so each split `compile.*.test.ts` file below only has to name a dialect/column configuration explicitly when it actually differs from the shared default. */
47
+ function compile(node, options = subjectOptions) {
48
+ return compilePredicateNode(node, options);
49
+ }
50
+ const ADULT_AGE = 18;
51
+ const SAMPLE_AGE = 40;
52
+ const EXCLUDED_AGE = 7;
53
+ const LOWER_BOUND = 1;
54
+ const UPPER_BOUND = 4;
55
+ const ageOver = {
56
+ kind: "compare",
57
+ op: "gt",
58
+ left: {
59
+ kind: "reference",
60
+ key: "age"
61
+ },
62
+ right: {
63
+ kind: "numberLiteral",
64
+ value: 18
65
+ }
66
+ };
67
+ //#endregion
68
+ export { ADULT_AGE, EXCLUDED_AGE, LOWER_BOUND, SAMPLE_AGE, UPPER_BOUND, ageOver, compile };
package/dist/compile.cjs CHANGED
@@ -53,6 +53,16 @@ function quoteColumn(referenceKey, binding) {
53
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
54
  return segments.map((segment) => `"${segment.replaceAll("\"", "\"\"")}"`).join(".");
55
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
+ }
56
66
  function bindingOf(context, node) {
57
67
  if (node.kind !== "reference" || typeof node.key !== "string") return;
58
68
  return {
@@ -73,6 +83,30 @@ function refuse(kind, layer) {
73
83
  });
74
84
  }
75
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
+ /**
76
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.
77
111
  *
78
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.
@@ -101,6 +135,13 @@ function compileExpression(node, context) {
101
135
  case "numberLiteral":
102
136
  case "booleanLiteral":
103
137
  case "instantLiteral": return placeholder(context, node.value, PARAM_TYPE_OF_LITERAL[node.kind]);
138
+ case "fold": {
139
+ if (node.combiner.mode === "reduce") return refuse(node.kind, "expression");
140
+ const { table, join, itemContext, filterSql } = compileCollection(node, context, "expression");
141
+ const itemValueSql = compileExpression(node.combiner.item, itemContext);
142
+ 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"`;
143
+ 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")`;
144
+ }
104
145
  }
105
146
  return refuse(node.kind, "expression");
106
147
  }
@@ -135,6 +176,14 @@ function compilePredicate(node, context) {
135
176
  return `(${operand} ${node.op === "in" ? "IN" : "NOT IN"} (${candidates}))`;
136
177
  }
137
178
  case "exists": return `(${compileExpression(node.operand, context)} IS NOT NULL)`;
179
+ case "some":
180
+ case "every": {
181
+ const { table, join, itemContext, filterSql } = compileCollection(node, context, "predicate");
182
+ const itemSql = compilePredicate(node.item, itemContext);
183
+ 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"`;
184
+ 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")`;
185
+ 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")`;
186
+ }
138
187
  }
139
188
  return refuse(node.kind, "predicate");
140
189
  }
@@ -144,14 +193,15 @@ function compilePredicate(node, context) {
144
193
  * 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.
145
194
  *
146
195
  * Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
147
- *
148
- * @throws {UnknownDialectError} if `options.dialect` names a dialect this version does not implement.
149
- * @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.
150
- * @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
196
+ * @throws `UnknownDialectError` if `options.dialect` names a dialect this version does not implement.
197
+ * @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.
198
+ * @throws `InvalidColumnError` if `columnFor` returns a column that cannot be rendered as an identifier.
151
199
  */
152
200
  function compilePredicateNode(node, options) {
153
201
  require_options.assertImplementedDialect(options.dialect);
154
202
  const bindings = /* @__PURE__ */ new Map();
203
+ const collectionBindings = /* @__PURE__ */ new Map();
204
+ const collectionFor = options.collectionFor;
155
205
  const memoised = {
156
206
  dialect: options.dialect,
157
207
  postgresRegexpPushdown: options.postgresRegexpPushdown,
@@ -162,7 +212,26 @@ function compilePredicateNode(node, options) {
162
212
  bindings.set(referenceKey, binding);
163
213
  return binding;
164
214
  },
165
- sqliteRegexpAvailable: options.sqliteRegexpAvailable
215
+ sqliteRegexpAvailable: options.sqliteRegexpAvailable,
216
+ ...collectionFor !== void 0 && { collectionFor: (collectionKey) => {
217
+ const cached = collectionBindings.get(collectionKey);
218
+ if (cached !== void 0) return cached;
219
+ const binding = collectionFor(collectionKey);
220
+ const columnBindings = /* @__PURE__ */ new Map();
221
+ const memoisedBinding = {
222
+ table: binding.table,
223
+ join: binding.join,
224
+ columnFor: (referenceKey) => {
225
+ const cachedColumn = columnBindings.get(referenceKey);
226
+ if (cachedColumn !== void 0) return cachedColumn;
227
+ const columnBinding = binding.columnFor(referenceKey);
228
+ columnBindings.set(referenceKey, columnBinding);
229
+ return columnBinding;
230
+ }
231
+ };
232
+ collectionBindings.set(collectionKey, memoisedBinding);
233
+ return memoisedBinding;
234
+ } }
166
235
  };
167
236
  const unpushable = require_guard.findUnpushableNodeKind(node, memoised);
168
237
  if (unpushable !== void 0) throw new require_errors.UnsupportedNodeError(unpushable);
@@ -7,10 +7,9 @@ import { PredicateNode } from "trilean";
7
7
  * 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.
8
8
  *
9
9
  * Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
10
- *
11
- * @throws {UnknownDialectError} if `options.dialect` names a dialect this version does not implement.
12
- * @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.
13
- * @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
10
+ * @throws `UnknownDialectError` if `options.dialect` names a dialect this version does not implement.
11
+ * @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.
12
+ * @throws `InvalidColumnError` if `columnFor` returns a column that cannot be rendered as an identifier.
14
13
  */
15
14
  declare function compilePredicateNode(node: PredicateNode, options: Readonly<SqlCompileOptions>): CompiledSql;
16
15
  //#endregion
package/dist/compile.d.ts CHANGED
@@ -7,10 +7,9 @@ import { PredicateNode } from "trilean";
7
7
  * 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.
8
8
  *
9
9
  * Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
10
- *
11
- * @throws {UnknownDialectError} if `options.dialect` names a dialect this version does not implement.
12
- * @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.
13
- * @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
10
+ * @throws `UnknownDialectError` if `options.dialect` names a dialect this version does not implement.
11
+ * @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.
12
+ * @throws `InvalidColumnError` if `columnFor` returns a column that cannot be rendered as an identifier.
14
13
  */
15
14
  declare function compilePredicateNode(node: PredicateNode, options: Readonly<SqlCompileOptions>): CompiledSql;
16
15
  //#endregion
package/dist/compile.js CHANGED
@@ -1,4 +1,4 @@
1
- import { InvalidColumnError, UnsupportedNodeError } from "./errors.js";
1
+ import { InvalidCollectionTableError, InvalidColumnError, UnsupportedNodeError } from "./errors.js";
2
2
  import { DIALECT_CONFIG, assertImplementedDialect } from "./options.js";
3
3
  import { renderPostgresPattern, renderSqliteGlobPattern } from "./portable-pattern.js";
4
4
  import { findUnpushableNodeKind } from "./guard.js";
@@ -52,6 +52,16 @@ function quoteColumn(referenceKey, binding) {
52
52
  if (segments.some((segment) => segment.length === 0)) throw new InvalidColumnError(referenceKey, binding.column, binding.column.length === 0 ? "the name is empty" : "a dot-separated segment is empty");
53
53
  return segments.map((segment) => `"${segment.replaceAll("\"", "\"\"")}"`).join(".");
54
54
  }
55
+ /**
56
+ * 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.
57
+ *
58
+ * 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.
59
+ */
60
+ function quoteTable(collectionKey, table) {
61
+ const segments = table.split(".");
62
+ if (segments.some((segment) => segment.length === 0)) throw new InvalidCollectionTableError(collectionKey, table, table.length === 0 ? "the name is empty" : "a dot-separated segment is empty");
63
+ return segments.map((segment) => `"${segment.replaceAll("\"", "\"\"")}"`).join(".");
64
+ }
55
65
  function bindingOf(context, node) {
56
66
  if (node.kind !== "reference" || typeof node.key !== "string") return;
57
67
  return {
@@ -72,6 +82,30 @@ function refuse(kind, layer) {
72
82
  });
73
83
  }
74
84
  /**
85
+ * 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.
86
+ *
87
+ * 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.
88
+ */
89
+ function compileCollection(node, context, layer) {
90
+ if (typeof node.collection !== "string" || context.options.collectionFor === void 0) return refuse(node.kind, layer);
91
+ const binding = context.options.collectionFor(node.collection);
92
+ const table = quoteTable(node.collection, binding.table);
93
+ const itemContext = {
94
+ ...context,
95
+ options: {
96
+ ...context.options,
97
+ columnFor: binding.columnFor
98
+ }
99
+ };
100
+ const filterSql = node.filter === void 0 ? void 0 : compilePredicate(node.filter, itemContext);
101
+ return {
102
+ table,
103
+ join: binding.join,
104
+ itemContext,
105
+ filterSql
106
+ };
107
+ }
108
+ /**
75
109
  * 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.
76
110
  *
77
111
  * `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.
@@ -100,6 +134,13 @@ function compileExpression(node, context) {
100
134
  case "numberLiteral":
101
135
  case "booleanLiteral":
102
136
  case "instantLiteral": return placeholder(context, node.value, PARAM_TYPE_OF_LITERAL[node.kind]);
137
+ case "fold": {
138
+ if (node.combiner.mode === "reduce") return refuse(node.kind, "expression");
139
+ const { table, join, itemContext, filterSql } = compileCollection(node, context, "expression");
140
+ const itemValueSql = compileExpression(node.combiner.item, itemContext);
141
+ 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"`;
142
+ 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")`;
143
+ }
103
144
  }
104
145
  return refuse(node.kind, "expression");
105
146
  }
@@ -134,6 +175,14 @@ function compilePredicate(node, context) {
134
175
  return `(${operand} ${node.op === "in" ? "IN" : "NOT IN"} (${candidates}))`;
135
176
  }
136
177
  case "exists": return `(${compileExpression(node.operand, context)} IS NOT NULL)`;
178
+ case "some":
179
+ case "every": {
180
+ const { table, join, itemContext, filterSql } = compileCollection(node, context, "predicate");
181
+ const itemSql = compilePredicate(node.item, itemContext);
182
+ 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"`;
183
+ 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")`;
184
+ 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")`;
185
+ }
137
186
  }
138
187
  return refuse(node.kind, "predicate");
139
188
  }
@@ -143,14 +192,15 @@ function compilePredicate(node, context) {
143
192
  * 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.
144
193
  *
145
194
  * Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
146
- *
147
- * @throws {UnknownDialectError} if `options.dialect` names a dialect this version does not implement.
148
- * @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.
149
- * @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
195
+ * @throws `UnknownDialectError` if `options.dialect` names a dialect this version does not implement.
196
+ * @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.
197
+ * @throws `InvalidColumnError` if `columnFor` returns a column that cannot be rendered as an identifier.
150
198
  */
151
199
  function compilePredicateNode(node, options) {
152
200
  assertImplementedDialect(options.dialect);
153
201
  const bindings = /* @__PURE__ */ new Map();
202
+ const collectionBindings = /* @__PURE__ */ new Map();
203
+ const collectionFor = options.collectionFor;
154
204
  const memoised = {
155
205
  dialect: options.dialect,
156
206
  postgresRegexpPushdown: options.postgresRegexpPushdown,
@@ -161,7 +211,26 @@ function compilePredicateNode(node, options) {
161
211
  bindings.set(referenceKey, binding);
162
212
  return binding;
163
213
  },
164
- sqliteRegexpAvailable: options.sqliteRegexpAvailable
214
+ sqliteRegexpAvailable: options.sqliteRegexpAvailable,
215
+ ...collectionFor !== void 0 && { collectionFor: (collectionKey) => {
216
+ const cached = collectionBindings.get(collectionKey);
217
+ if (cached !== void 0) return cached;
218
+ const binding = collectionFor(collectionKey);
219
+ const columnBindings = /* @__PURE__ */ new Map();
220
+ const memoisedBinding = {
221
+ table: binding.table,
222
+ join: binding.join,
223
+ columnFor: (referenceKey) => {
224
+ const cachedColumn = columnBindings.get(referenceKey);
225
+ if (cachedColumn !== void 0) return cachedColumn;
226
+ const columnBinding = binding.columnFor(referenceKey);
227
+ columnBindings.set(referenceKey, columnBinding);
228
+ return columnBinding;
229
+ }
230
+ };
231
+ collectionBindings.set(collectionKey, memoisedBinding);
232
+ return memoisedBinding;
233
+ } }
165
234
  };
166
235
  const unpushable = findUnpushableNodeKind(node, memoised);
167
236
  if (unpushable !== void 0) throw new UnsupportedNodeError(unpushable);
package/dist/errors.cjs CHANGED
@@ -58,7 +58,23 @@ var InvalidColumnError = class extends TrileanSqlError {
58
58
  this.column = column;
59
59
  }
60
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
+ };
61
76
  //#endregion
77
+ exports.InvalidCollectionTableError = InvalidCollectionTableError;
62
78
  exports.InvalidColumnError = InvalidColumnError;
63
79
  exports.TrileanSqlError = TrileanSqlError;
64
80
  exports.UnknownDialectError = UnknownDialectError;
package/dist/errors.d.cts CHANGED
@@ -42,5 +42,15 @@ declare class InvalidColumnError extends TrileanSqlError {
42
42
  readonly column: string;
43
43
  constructor(referenceKey: string, column: string, reason: string);
44
44
  }
45
+ /**
46
+ * A `collectionFor` result whose `table` cannot be rendered as a SQL identifier.
47
+ *
48
+ * 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.
49
+ */
50
+ declare class InvalidCollectionTableError extends TrileanSqlError {
51
+ readonly collectionKey: string;
52
+ readonly table: string;
53
+ constructor(collectionKey: string, table: string, reason: string);
54
+ }
45
55
  //#endregion
46
- export { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError };
56
+ export { InvalidCollectionTableError, InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError };
package/dist/errors.d.ts CHANGED
@@ -42,5 +42,15 @@ declare class InvalidColumnError extends TrileanSqlError {
42
42
  readonly column: string;
43
43
  constructor(referenceKey: string, column: string, reason: string);
44
44
  }
45
+ /**
46
+ * A `collectionFor` result whose `table` cannot be rendered as a SQL identifier.
47
+ *
48
+ * 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.
49
+ */
50
+ declare class InvalidCollectionTableError extends TrileanSqlError {
51
+ readonly collectionKey: string;
52
+ readonly table: string;
53
+ constructor(collectionKey: string, table: string, reason: string);
54
+ }
45
55
  //#endregion
46
- export { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError };
56
+ export { InvalidCollectionTableError, InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError };
package/dist/errors.js CHANGED
@@ -57,5 +57,20 @@ var InvalidColumnError = class extends TrileanSqlError {
57
57
  this.column = column;
58
58
  }
59
59
  };
60
+ /**
61
+ * A `collectionFor` result whose `table` cannot be rendered as a SQL identifier.
62
+ *
63
+ * 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.
64
+ */
65
+ var InvalidCollectionTableError = class extends TrileanSqlError {
66
+ collectionKey;
67
+ table;
68
+ constructor(collectionKey, table, reason) {
69
+ super(`collectionFor(${JSON.stringify(collectionKey)}) returned ${JSON.stringify(table)}, which is not a usable table identifier: ${reason}`);
70
+ this.name = "InvalidCollectionTableError";
71
+ this.collectionKey = collectionKey;
72
+ this.table = table;
73
+ }
74
+ };
60
75
  //#endregion
61
- export { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError };
76
+ export { InvalidCollectionTableError, InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError };
@@ -0,0 +1,17 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region 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
+ //#endregion
17
+ exports.ageOver = ageOver;
@@ -0,0 +1,6 @@
1
+ import { PredicateNode } from "trilean";
2
+ //#region src/guard-test-helpers.d.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
+ declare const ageOver: PredicateNode;
5
+ //#endregion
6
+ export { ageOver };
@@ -0,0 +1,6 @@
1
+ import { PredicateNode } from "trilean";
2
+ //#region src/guard-test-helpers.d.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
+ declare const ageOver: PredicateNode;
5
+ //#endregion
6
+ export { ageOver };
@@ -0,0 +1,16 @@
1
+ //#region 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
+ //#endregion
16
+ export { ageOver };
package/dist/guard.cjs CHANGED
@@ -45,7 +45,30 @@ function staticValueKindOf(node, options) {
45
45
  const paramType = options.columnFor(node.key).paramType;
46
46
  return paramType === void 0 ? void 0 : STATIC_KIND_OF_PARAM_TYPE[paramType];
47
47
  }
48
- function findUnpushableExpression(node, path, divergence) {
48
+ /**
49
+ * 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.
50
+ *
51
+ * `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.
52
+ */
53
+ function resolveCollectionForGuard(kind, collection, path, options) {
54
+ if (typeof collection !== "string") return {
55
+ kind,
56
+ path,
57
+ reason: "only a string collection key can be mapped to a correlated table; this collection is a non-string JSON value"
58
+ };
59
+ if (options === void 0) return { itemOptions: void 0 };
60
+ if (options.collectionFor === void 0) return {
61
+ kind,
62
+ path,
63
+ 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"
64
+ };
65
+ const binding = options.collectionFor(collection);
66
+ return { itemOptions: {
67
+ ...options,
68
+ columnFor: binding.columnFor
69
+ } };
70
+ }
71
+ function findUnpushableExpression(node, path, divergence, options) {
49
72
  const unrecognisedKind = node.kind;
50
73
  switch (node.kind) {
51
74
  case "reference":
@@ -106,11 +129,35 @@ function findUnpushableExpression(node, path, divergence) {
106
129
  path,
107
130
  reason: "conditional evaluation is not implemented in this version of the compiler"
108
131
  };
109
- case "fold": return {
110
- kind: node.kind,
111
- path,
112
- reason: "a fold ranges over a collection the caller's resolvers supply, which is not this query's row set"
113
- };
132
+ case "fold": {
133
+ if (node.combiner.mode === "reduce") return {
134
+ kind: node.kind,
135
+ path,
136
+ reason: "a 'reduce' fold threads an arbitrary combine expression through the collection in a caller-chosen order, which has no general SQL translation"
137
+ };
138
+ const resolved = resolveCollectionForGuard(node.kind, node.collection, path, options);
139
+ if ("reason" in resolved) return resolved;
140
+ const { itemOptions } = resolved;
141
+ if (node.filter !== void 0) {
142
+ const unpushableFilter = findUnpushablePredicate(node.filter, `${path}.filter`, itemOptions, divergence);
143
+ if (unpushableFilter !== void 0) return unpushableFilter;
144
+ }
145
+ const itemPath = `${path}.combiner.item`;
146
+ const unpushableItem = findUnpushableExpression(node.combiner.item, itemPath, divergence, itemOptions);
147
+ if (unpushableItem !== void 0) return unpushableItem;
148
+ const itemKind = staticValueKindOf(node.combiner.item, itemOptions);
149
+ if (itemKind === "text") return {
150
+ kind: node.kind,
151
+ path: itemPath,
152
+ 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)}`
153
+ };
154
+ if (itemKind === "boolean") return {
155
+ kind: node.kind,
156
+ path: itemPath,
157
+ reason: `a '${node.combiner.mode}' fold orders participating items by comparing them, and booleans have no ordering in trilean -- whereas ${divergence.booleanOrdering}`
158
+ };
159
+ return;
160
+ }
114
161
  case "accumulator": return {
115
162
  kind: node.kind,
116
163
  path,
@@ -170,7 +217,7 @@ function findUnpushablePredicate(node, path, options, divergence) {
170
217
  path: `${path}.right`
171
218
  }];
172
219
  for (const operand of operands) {
173
- const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
220
+ const unpushable = findUnpushableExpression(operand.node, operand.path, divergence, options);
174
221
  if (unpushable !== void 0) return unpushable;
175
222
  }
176
223
  const mismatch = findKindDivergence(node.kind, path, operands, options, divergence);
@@ -204,7 +251,7 @@ function findUnpushablePredicate(node, path, options, divergence) {
204
251
  path: `${path}.right`
205
252
  }];
206
253
  for (const operand of operands) {
207
- const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
254
+ const unpushable = findUnpushableExpression(operand.node, operand.path, divergence, options);
208
255
  if (unpushable !== void 0) return unpushable;
209
256
  const staticKind = staticValueKindOf(operand.node, options);
210
257
  if (staticKind !== void 0 && staticKind !== "text") return {
@@ -248,18 +295,22 @@ function findUnpushablePredicate(node, path, options, divergence) {
248
295
  path: `${path}.candidates[${String(index)}]`
249
296
  }))];
250
297
  for (const operand of operands) {
251
- const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
298
+ const unpushable = findUnpushableExpression(operand.node, operand.path, divergence, options);
252
299
  if (unpushable !== void 0) return unpushable;
253
300
  }
254
301
  return findKindDivergence(node.kind, path, operands, options, divergence);
255
302
  }
256
- case "exists": return findUnpushableExpression(node.operand, `${path}.operand`, divergence);
303
+ case "exists": return findUnpushableExpression(node.operand, `${path}.operand`, divergence, options);
257
304
  case "some":
258
- case "every": return {
259
- kind: node.kind,
260
- path,
261
- reason: "quantification ranges over a collection the caller's resolvers supply, which is not this query's row set"
262
- };
305
+ case "every": {
306
+ const resolved = resolveCollectionForGuard(node.kind, node.collection, path, options);
307
+ if ("reason" in resolved) return resolved;
308
+ const { itemOptions } = resolved;
309
+ const unpushableItem = findUnpushablePredicate(node.item, `${path}.item`, itemOptions, divergence);
310
+ if (unpushableItem !== void 0) return unpushableItem;
311
+ if (node.filter === void 0) return void 0;
312
+ return findUnpushablePredicate(node.filter, `${path}.filter`, itemOptions, divergence);
313
+ }
263
314
  case "treeReference": return {
264
315
  kind: node.kind,
265
316
  path,
@@ -282,8 +333,7 @@ function findUnpushablePredicate(node, path, options, divergence) {
282
333
  * 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`).
283
334
  *
284
335
  * 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.
285
- *
286
- * @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
+ * @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.
287
337
  */
288
338
  function findUnpushableNodeKind(node, options) {
289
339
  const dialect = options?.dialect ?? "postgres";
package/dist/guard.d.cts CHANGED
@@ -18,8 +18,7 @@ interface UnpushableNode {
18
18
  * 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`).
19
19
  *
20
20
  * 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.
21
- *
22
- * @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
+ * @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.
23
22
  */
24
23
  declare function findUnpushableNodeKind(node: PredicateNode, options?: SqlCompileOptions): UnpushableNode | undefined;
25
24
  //#endregion
package/dist/guard.d.ts CHANGED
@@ -18,8 +18,7 @@ interface UnpushableNode {
18
18
  * 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`).
19
19
  *
20
20
  * 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.
21
- *
22
- * @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
+ * @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.
23
22
  */
24
23
  declare function findUnpushableNodeKind(node: PredicateNode, options?: SqlCompileOptions): UnpushableNode | undefined;
25
24
  //#endregion
package/dist/guard.js CHANGED
@@ -44,7 +44,30 @@ function staticValueKindOf(node, options) {
44
44
  const paramType = options.columnFor(node.key).paramType;
45
45
  return paramType === void 0 ? void 0 : STATIC_KIND_OF_PARAM_TYPE[paramType];
46
46
  }
47
- function findUnpushableExpression(node, path, divergence) {
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) {
48
71
  const unrecognisedKind = node.kind;
49
72
  switch (node.kind) {
50
73
  case "reference":
@@ -105,11 +128,35 @@ function findUnpushableExpression(node, path, divergence) {
105
128
  path,
106
129
  reason: "conditional evaluation is not implemented in this version of the compiler"
107
130
  };
108
- case "fold": return {
109
- kind: node.kind,
110
- path,
111
- reason: "a fold ranges over a collection the caller's resolvers supply, which is not this query's row set"
112
- };
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
+ }
113
160
  case "accumulator": return {
114
161
  kind: node.kind,
115
162
  path,
@@ -169,7 +216,7 @@ function findUnpushablePredicate(node, path, options, divergence) {
169
216
  path: `${path}.right`
170
217
  }];
171
218
  for (const operand of operands) {
172
- const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
219
+ const unpushable = findUnpushableExpression(operand.node, operand.path, divergence, options);
173
220
  if (unpushable !== void 0) return unpushable;
174
221
  }
175
222
  const mismatch = findKindDivergence(node.kind, path, operands, options, divergence);
@@ -203,7 +250,7 @@ function findUnpushablePredicate(node, path, options, divergence) {
203
250
  path: `${path}.right`
204
251
  }];
205
252
  for (const operand of operands) {
206
- const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
253
+ const unpushable = findUnpushableExpression(operand.node, operand.path, divergence, options);
207
254
  if (unpushable !== void 0) return unpushable;
208
255
  const staticKind = staticValueKindOf(operand.node, options);
209
256
  if (staticKind !== void 0 && staticKind !== "text") return {
@@ -247,18 +294,22 @@ function findUnpushablePredicate(node, path, options, divergence) {
247
294
  path: `${path}.candidates[${String(index)}]`
248
295
  }))];
249
296
  for (const operand of operands) {
250
- const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
297
+ const unpushable = findUnpushableExpression(operand.node, operand.path, divergence, options);
251
298
  if (unpushable !== void 0) return unpushable;
252
299
  }
253
300
  return findKindDivergence(node.kind, path, operands, options, divergence);
254
301
  }
255
- case "exists": return findUnpushableExpression(node.operand, `${path}.operand`, divergence);
302
+ case "exists": return findUnpushableExpression(node.operand, `${path}.operand`, divergence, options);
256
303
  case "some":
257
- case "every": return {
258
- kind: node.kind,
259
- path,
260
- reason: "quantification ranges over a collection the caller's resolvers supply, which is not this query's row set"
261
- };
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
+ }
262
313
  case "treeReference": return {
263
314
  kind: node.kind,
264
315
  path,
@@ -281,8 +332,7 @@ function findUnpushablePredicate(node, path, options, divergence) {
281
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`).
282
333
  *
283
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.
284
- *
285
- * @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.
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.
286
336
  */
287
337
  function findUnpushableNodeKind(node, options) {
288
338
  const dialect = options?.dialect ?? "postgres";
@@ -14,6 +14,14 @@ interface SqlColumnBinding {
14
14
  */
15
15
  paramType?: SqlParamType;
16
16
  }
17
+ interface SqlCollectionBinding {
18
+ /** The correlated child table, dot-qualified exactly like `SqlColumnBinding.column` -- each dot-separated segment is emitted as its own double-quoted identifier. */
19
+ table: string;
20
+ /** Raw boolean SQL relating one row of `table` to the outer row, e.g. `"attrs"."nodeId" = "graph_nodes"."id" AND "attrs"."attrName" = 'voltageLevel'`. Caller-authored rather than assembled from a join-column pair, because only the caller knows the real join shape -- a single FK, a composite key, or (the EAV driving case) an FK plus a literal discriminator. */
21
+ join: string;
22
+ /** Resolves a reference key *inside* this collection's `item`/`filter` -- swapped in for the outer `columnFor` while compiling them, mirroring how trilean's own evaluator re-points `EvaluationContext` at the collection item (see `evaluator.ts`'s `resolveParticipatingItems`). */
23
+ columnFor: (referenceKey: string) => SqlColumnBinding;
24
+ }
17
25
  interface SqlCompileOptions {
18
26
  /** Which dialect to emit. It is a required field rather than a default so that a caller states the engine it is compiling for, instead of inheriting whichever one this package happened to implement first. */
19
27
  dialect: SqlDialect;
@@ -23,6 +31,12 @@ interface SqlCompileOptions {
23
31
  * Only string reference keys reach it: trilean allows any JSON value as a key, and a non-string one is refused as unpushable before this is called. Throwing from here is how a caller rejects a key it has no column for -- the exception propagates out of `compilePredicateNode` unchanged, rather than being wrapped or swallowed.
24
32
  */
25
33
  columnFor: (referenceKey: string) => SqlColumnBinding;
34
+ /**
35
+ * Maps a `some`/`every`/`fold` node's `collection` key onto a correlated table. Called once per collection occurrence.
36
+ *
37
+ * Only string collection keys reach it, for the same reason only string reference keys reach `columnFor`. A tree that never uses `some`, `every`, or `fold(max|min)` never calls this -- leaving it unset is fully backward compatible. A tree that does use one of those kinds without this set is refused with `UnsupportedNodeError`, the same refused outcome those kinds already had before this option existed. `fold(reduce)` is refused unconditionally regardless of this option: it threads an arbitrary combine expression through the collection in a caller-chosen order, which has no general SQL translation.
38
+ */
39
+ collectionFor?: (collectionKey: string) => SqlCollectionBinding;
26
40
  /**
27
41
  * Whether the SQLite target can resolve a `regexp(pattern, value)` function for `textCompare`'s `matches`/`notMatches` to compile to. Ignored under the `postgres` dialect, which has its own separate `postgresRegexpPushdown` gate below.
28
42
  *
@@ -75,4 +89,4 @@ declare const DIALECT_CONFIG: Readonly<Record<SqlDialect, DialectConfig>>;
75
89
  */
76
90
  declare function assertImplementedDialect(dialect: SqlDialect): void;
77
91
  //#endregion
78
- export { CompiledSql, DIALECT_CONFIG, DialectConfig, POSTGRES_TYPE_NAME, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType, assertImplementedDialect };
92
+ export { CompiledSql, DIALECT_CONFIG, DialectConfig, POSTGRES_TYPE_NAME, SqlCollectionBinding, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType, assertImplementedDialect };
package/dist/options.d.ts CHANGED
@@ -14,6 +14,14 @@ interface SqlColumnBinding {
14
14
  */
15
15
  paramType?: SqlParamType;
16
16
  }
17
+ interface SqlCollectionBinding {
18
+ /** The correlated child table, dot-qualified exactly like `SqlColumnBinding.column` -- each dot-separated segment is emitted as its own double-quoted identifier. */
19
+ table: string;
20
+ /** Raw boolean SQL relating one row of `table` to the outer row, e.g. `"attrs"."nodeId" = "graph_nodes"."id" AND "attrs"."attrName" = 'voltageLevel'`. Caller-authored rather than assembled from a join-column pair, because only the caller knows the real join shape -- a single FK, a composite key, or (the EAV driving case) an FK plus a literal discriminator. */
21
+ join: string;
22
+ /** Resolves a reference key *inside* this collection's `item`/`filter` -- swapped in for the outer `columnFor` while compiling them, mirroring how trilean's own evaluator re-points `EvaluationContext` at the collection item (see `evaluator.ts`'s `resolveParticipatingItems`). */
23
+ columnFor: (referenceKey: string) => SqlColumnBinding;
24
+ }
17
25
  interface SqlCompileOptions {
18
26
  /** Which dialect to emit. It is a required field rather than a default so that a caller states the engine it is compiling for, instead of inheriting whichever one this package happened to implement first. */
19
27
  dialect: SqlDialect;
@@ -23,6 +31,12 @@ interface SqlCompileOptions {
23
31
  * Only string reference keys reach it: trilean allows any JSON value as a key, and a non-string one is refused as unpushable before this is called. Throwing from here is how a caller rejects a key it has no column for -- the exception propagates out of `compilePredicateNode` unchanged, rather than being wrapped or swallowed.
24
32
  */
25
33
  columnFor: (referenceKey: string) => SqlColumnBinding;
34
+ /**
35
+ * Maps a `some`/`every`/`fold` node's `collection` key onto a correlated table. Called once per collection occurrence.
36
+ *
37
+ * Only string collection keys reach it, for the same reason only string reference keys reach `columnFor`. A tree that never uses `some`, `every`, or `fold(max|min)` never calls this -- leaving it unset is fully backward compatible. A tree that does use one of those kinds without this set is refused with `UnsupportedNodeError`, the same refused outcome those kinds already had before this option existed. `fold(reduce)` is refused unconditionally regardless of this option: it threads an arbitrary combine expression through the collection in a caller-chosen order, which has no general SQL translation.
38
+ */
39
+ collectionFor?: (collectionKey: string) => SqlCollectionBinding;
26
40
  /**
27
41
  * Whether the SQLite target can resolve a `regexp(pattern, value)` function for `textCompare`'s `matches`/`notMatches` to compile to. Ignored under the `postgres` dialect, which has its own separate `postgresRegexpPushdown` gate below.
28
42
  *
@@ -75,4 +89,4 @@ declare const DIALECT_CONFIG: Readonly<Record<SqlDialect, DialectConfig>>;
75
89
  */
76
90
  declare function assertImplementedDialect(dialect: SqlDialect): void;
77
91
  //#endregion
78
- export { CompiledSql, DIALECT_CONFIG, DialectConfig, POSTGRES_TYPE_NAME, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType, assertImplementedDialect };
92
+ export { CompiledSql, DIALECT_CONFIG, DialectConfig, POSTGRES_TYPE_NAME, SqlCollectionBinding, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType, assertImplementedDialect };
@@ -60,8 +60,7 @@ function renderPostgresSubcomponent(node) {
60
60
  * Translates a `trilean-regex` AST into PostgreSQL's own Advanced Regular Expression syntax, for binding as the pattern argument to `~`/`!~`.
61
61
  *
62
62
  * Every construct this grammar accepts translates structurally, `.` included: measured directly against a real PostgreSQL 17 server (see the "PostgreSQL's own engine treats '.' as matching a newline" case in `test/integration/postgres.test.ts`), PostgreSQL's `.` matches a newline by default in the mode this compiler's `~`/`!~` operators run under -- the same as this grammar's own `.` (see trilean-regex's README) -- so no rewriting is needed here. (PostgreSQL's own prose documentation reads, in isolation, as though newline-sensitive matching were the default; it is not the one this operator uses, and the fact was confirmed against the real server rather than trusted from the prose alone -- see the "Verify this assumption" principle this compiler otherwise applies to every other construct too.)
63
- *
64
- * @throws {PortablePatternUnsupportedError} if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
63
+ * @throws `PortablePatternUnsupportedError` if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
65
64
  */
66
65
  function renderPostgresPattern(node) {
67
66
  switch (node.kind) {
@@ -139,8 +138,7 @@ function planGlobBody(node) {
139
138
  }
140
139
  /**
141
140
  * Translates a `trilean-regex` AST into a `GLOB` pattern, for binding as `GLOB`/`NOT GLOB`'s right-hand argument. See the "reachable subset" doc comment above for exactly what this does and does not translate.
142
- *
143
- * @throws {PortablePatternUnsupportedError} if `node` uses any construct outside the reachable subset.
141
+ * @throws `PortablePatternUnsupportedError` if `node` uses any construct outside the reachable subset.
144
142
  */
145
143
  function renderSqliteGlobPattern(node) {
146
144
  const plan = planGlobBody(node);
@@ -8,14 +8,12 @@ declare class PortablePatternUnsupportedError extends Error {}
8
8
  * Translates a `trilean-regex` AST into PostgreSQL's own Advanced Regular Expression syntax, for binding as the pattern argument to `~`/`!~`.
9
9
  *
10
10
  * Every construct this grammar accepts translates structurally, `.` included: measured directly against a real PostgreSQL 17 server (see the "PostgreSQL's own engine treats '.' as matching a newline" case in `test/integration/postgres.test.ts`), PostgreSQL's `.` matches a newline by default in the mode this compiler's `~`/`!~` operators run under -- the same as this grammar's own `.` (see trilean-regex's README) -- so no rewriting is needed here. (PostgreSQL's own prose documentation reads, in isolation, as though newline-sensitive matching were the default; it is not the one this operator uses, and the fact was confirmed against the real server rather than trusted from the prose alone -- see the "Verify this assumption" principle this compiler otherwise applies to every other construct too.)
11
- *
12
- * @throws {PortablePatternUnsupportedError} if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
11
+ * @throws `PortablePatternUnsupportedError` if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
13
12
  */
14
13
  declare function renderPostgresPattern(node: RegexNode): string;
15
14
  /**
16
15
  * Translates a `trilean-regex` AST into a `GLOB` pattern, for binding as `GLOB`/`NOT GLOB`'s right-hand argument. See the "reachable subset" doc comment above for exactly what this does and does not translate.
17
- *
18
- * @throws {PortablePatternUnsupportedError} if `node` uses any construct outside the reachable subset.
16
+ * @throws `PortablePatternUnsupportedError` if `node` uses any construct outside the reachable subset.
19
17
  */
20
18
  declare function renderSqliteGlobPattern(node: RegexNode): string;
21
19
  //#endregion
@@ -8,14 +8,12 @@ declare class PortablePatternUnsupportedError extends Error {}
8
8
  * Translates a `trilean-regex` AST into PostgreSQL's own Advanced Regular Expression syntax, for binding as the pattern argument to `~`/`!~`.
9
9
  *
10
10
  * Every construct this grammar accepts translates structurally, `.` included: measured directly against a real PostgreSQL 17 server (see the "PostgreSQL's own engine treats '.' as matching a newline" case in `test/integration/postgres.test.ts`), PostgreSQL's `.` matches a newline by default in the mode this compiler's `~`/`!~` operators run under -- the same as this grammar's own `.` (see trilean-regex's README) -- so no rewriting is needed here. (PostgreSQL's own prose documentation reads, in isolation, as though newline-sensitive matching were the default; it is not the one this operator uses, and the fact was confirmed against the real server rather than trusted from the prose alone -- see the "Verify this assumption" principle this compiler otherwise applies to every other construct too.)
11
- *
12
- * @throws {PortablePatternUnsupportedError} if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
11
+ * @throws `PortablePatternUnsupportedError` if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
13
12
  */
14
13
  declare function renderPostgresPattern(node: RegexNode): string;
15
14
  /**
16
15
  * Translates a `trilean-regex` AST into a `GLOB` pattern, for binding as `GLOB`/`NOT GLOB`'s right-hand argument. See the "reachable subset" doc comment above for exactly what this does and does not translate.
17
- *
18
- * @throws {PortablePatternUnsupportedError} if `node` uses any construct outside the reachable subset.
16
+ * @throws `PortablePatternUnsupportedError` if `node` uses any construct outside the reachable subset.
19
17
  */
20
18
  declare function renderSqliteGlobPattern(node: RegexNode): string;
21
19
  //#endregion
@@ -59,8 +59,7 @@ function renderPostgresSubcomponent(node) {
59
59
  * Translates a `trilean-regex` AST into PostgreSQL's own Advanced Regular Expression syntax, for binding as the pattern argument to `~`/`!~`.
60
60
  *
61
61
  * Every construct this grammar accepts translates structurally, `.` included: measured directly against a real PostgreSQL 17 server (see the "PostgreSQL's own engine treats '.' as matching a newline" case in `test/integration/postgres.test.ts`), PostgreSQL's `.` matches a newline by default in the mode this compiler's `~`/`!~` operators run under -- the same as this grammar's own `.` (see trilean-regex's README) -- so no rewriting is needed here. (PostgreSQL's own prose documentation reads, in isolation, as though newline-sensitive matching were the default; it is not the one this operator uses, and the fact was confirmed against the real server rather than trusted from the prose alone -- see the "Verify this assumption" principle this compiler otherwise applies to every other construct too.)
62
- *
63
- * @throws {PortablePatternUnsupportedError} if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
62
+ * @throws `PortablePatternUnsupportedError` if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
64
63
  */
65
64
  function renderPostgresPattern(node) {
66
65
  switch (node.kind) {
@@ -138,8 +137,7 @@ function planGlobBody(node) {
138
137
  }
139
138
  /**
140
139
  * Translates a `trilean-regex` AST into a `GLOB` pattern, for binding as `GLOB`/`NOT GLOB`'s right-hand argument. See the "reachable subset" doc comment above for exactly what this does and does not translate.
141
- *
142
- * @throws {PortablePatternUnsupportedError} if `node` uses any construct outside the reachable subset.
140
+ * @throws `PortablePatternUnsupportedError` if `node` uses any construct outside the reachable subset.
143
141
  */
144
142
  function renderSqliteGlobPattern(node) {
145
143
  const plan = planGlobBody(node);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trilean-sql",
3
- "version": "2.1.2",
3
+ "version": "2.2.0",
4
4
  "description": "Compiles a trilean predicate tree into a parameterised SQL WHERE fragment, pushing three-valued logic down onto the database's own NULL propagation instead of evaluating it in process.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -82,7 +82,7 @@
82
82
  "devDependencies": {
83
83
  "@arethetypeswrong/cli": "^0.18.5",
84
84
  "@electric-sql/pglite": "^0.5.8",
85
- "@exadev/eslint-config": "^2.10.2",
85
+ "@exadev/eslint-config": "2.12.1",
86
86
  "@testcontainers/postgresql": "^12.1.0",
87
87
  "@types/better-sqlite3": "^9.6.0",
88
88
  "@types/node": "^26.4.0",