trilean-sql 0.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +147 -0
- package/dist/compile.cjs +146 -0
- package/dist/compile.d.cts +16 -0
- package/dist/compile.d.ts +16 -0
- package/dist/compile.js +145 -0
- package/dist/errors.cjs +47 -0
- package/dist/errors.d.cts +34 -0
- package/dist/errors.d.ts +34 -0
- package/dist/errors.js +44 -0
- package/dist/guard.cjs +240 -0
- package/dist/guard.d.cts +22 -0
- package/dist/guard.d.ts +22 -0
- package/dist/guard.js +239 -0
- package/dist/index.cjs +9 -0
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/options.cjs +11 -0
- package/dist/options.d.cts +34 -0
- package/dist/options.d.ts +34 -0
- package/dist/options.js +10 -0
- package/package.json +98 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joseph Mearman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# trilean-sql
|
|
2
|
+
|
|
3
|
+
Compiles a [trilean](https://www.npmjs.com/package/trilean) predicate tree into a parameterised SQL `WHERE` fragment, so a rule stored as data can be evaluated by the database over a whole table instead of in process, one subject at a time.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pnpm add trilean-sql
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
`trilean` is a peer concern rather than an implementation detail: this package takes its `PredicateNode` type as input and declares it as a dependency, so the tree you compile is the same tree you evaluate.
|
|
10
|
+
|
|
11
|
+
## The idea
|
|
12
|
+
|
|
13
|
+
trilean evaluates a predicate to `definite(true)`, `definite(false)`, or `indeterminate` — the third value meaning the tree could not be judged, usually because a reference resolved to nothing. Given a table of subjects and a rule to apply to all of them, the obvious approach is to fetch every row and evaluate the tree once per row. That reads the whole table to discard most of it.
|
|
14
|
+
|
|
15
|
+
The alternative is to let the database apply the rule. It already has a three-valued logic: `TRUE`, `FALSE`, and `NULL` meaning unknown, with `AND`, `OR` and `NOT` following Kleene's strong tables — the same tables trilean's own connectives implement — and a comparison against `NULL` yielding `NULL` rather than a verdict. A `WHERE` clause keeps only the rows whose condition came out `TRUE`, so a row whose condition was unknown is dropped exactly as a subject the evaluator declines to judge is not accepted.
|
|
16
|
+
|
|
17
|
+
So the third value is not reimplemented on top of SQL. It is the same third value, and the compiler's job is to translate the tree faithfully enough that it stays that way.
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { compilePredicateNode } from "trilean-sql";
|
|
21
|
+
import type { PredicateNode } from "trilean";
|
|
22
|
+
|
|
23
|
+
const rule: PredicateNode = {
|
|
24
|
+
kind: "allOf",
|
|
25
|
+
operands: [
|
|
26
|
+
{
|
|
27
|
+
kind: "compare",
|
|
28
|
+
op: "gte",
|
|
29
|
+
left: { kind: "reference", key: "age" },
|
|
30
|
+
right: { kind: "numberLiteral", value: 18 },
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
kind: "textCompare",
|
|
34
|
+
op: "matches",
|
|
35
|
+
left: { kind: "reference", key: "email" },
|
|
36
|
+
right: { kind: "textLiteral", value: "@example[.]com$" },
|
|
37
|
+
},
|
|
38
|
+
],
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const columns = {
|
|
42
|
+
age: { column: "age", paramType: "number" },
|
|
43
|
+
email: { column: "email", paramType: "text" },
|
|
44
|
+
} as const;
|
|
45
|
+
|
|
46
|
+
const { sql, params } = compilePredicateNode(rule, {
|
|
47
|
+
dialect: "postgres",
|
|
48
|
+
columnFor: (key) => {
|
|
49
|
+
const binding = columns[key as keyof typeof columns];
|
|
50
|
+
if (binding === undefined) throw new Error(`no column for ${key}`);
|
|
51
|
+
return binding;
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// sql: (("age" >= $1::double precision) AND ("email" ~ $2::text))
|
|
56
|
+
// params: [18, "@example[.]com$"]
|
|
57
|
+
await client.query(`SELECT id FROM members WHERE ${sql}`, params);
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The fragment is a self-contained boolean expression with no `WHERE` keyword of its own, so it also drops into a `HAVING`, a `CHECK`, or a partial index predicate.
|
|
61
|
+
|
|
62
|
+
## API
|
|
63
|
+
|
|
64
|
+
### `compilePredicateNode(node, options)`
|
|
65
|
+
|
|
66
|
+
Returns `{ sql, params }`. Throws rather than approximating; see [Refusal](#refusal).
|
|
67
|
+
|
|
68
|
+
`options.dialect` is `"postgres"`. It is required rather than defaulted so that a second dialect is a new value here, not a change of behaviour for callers who never said which one they meant.
|
|
69
|
+
|
|
70
|
+
`options.columnFor(referenceKey)` maps a `reference` node's key onto `{ column, paramType? }`. Only string keys reach it — trilean permits any JSON value as a key, and a non-string one is refused before the call. Throwing from `columnFor` is how you reject a key you have no column for; the exception propagates out unchanged rather than being wrapped. It is memoised for the duration of one compilation, so it is called once per distinct key however many times that key appears.
|
|
71
|
+
|
|
72
|
+
`column` may be qualified with dots (`"members.age"`); each segment is emitted as its own double-quoted identifier. Quoting is unconditional, which is what makes an arbitrary column name safe — an embedded quote is doubled, so a name carrying `"; DROP TABLE ...` becomes one inert identifier that simply does not exist. It also means the name is taken literally rather than case-folded, so return the column's real, case-exact name.
|
|
73
|
+
|
|
74
|
+
`paramType` declares the column's value kind: `"text"`, `"number"`, `"boolean"`, or `"timestamp"` (trilean's `instant`). It is optional and worth supplying — it does not change the emitted SQL, but it is the only thing that lets the compiler detect the operand-kind mismatches described under [Refusal](#refusal). Without it, a comparison PostgreSQL would coerce into a definite answer where trilean returns `indeterminate` compiles silently.
|
|
75
|
+
|
|
76
|
+
### `findUnpushableNodeKind(node, options?)`
|
|
77
|
+
|
|
78
|
+
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:
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const blocker = findUnpushableNodeKind(rule, options);
|
|
82
|
+
const rows = blocker
|
|
83
|
+
? await evaluateEveryRowInProcess(rule)
|
|
84
|
+
: await queryWith(compilePredicateNode(rule, options));
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Passing `options` widens the check: without them the walk is purely structural; with them it also applies the operand-kind rules that depend on each column's declared `paramType`.
|
|
88
|
+
|
|
89
|
+
### Errors
|
|
90
|
+
|
|
91
|
+
`UnsupportedNodeError` (carrying `nodeKind`, `path`, `reason`) and `InvalidColumnError` (carrying `referenceKey`, `column`), both extending `TrileanSqlError`.
|
|
92
|
+
|
|
93
|
+
## What compiles
|
|
94
|
+
|
|
95
|
+
| Node | PostgreSQL |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| `and`, `or`, `not` | `AND`, `OR`, `NOT` |
|
|
98
|
+
| `allOf`, `anyOf` | n-ary `AND`, `OR`; empty operands become each connective's identity, `TRUE` and `FALSE`, matching the evaluator's own fold |
|
|
99
|
+
| `compare` | `>`, `>=`, `<`, `<=`, `=`, `<>` |
|
|
100
|
+
| `textCompare` | `=`, `<>`, and `~` / `!~` for `matches` / `notMatches` |
|
|
101
|
+
| `memberOf` | `IN` / `NOT IN`, one parameter per candidate |
|
|
102
|
+
| `exists` | `IS NOT NULL` |
|
|
103
|
+
| `reference` | the mapped column, as a quoted identifier |
|
|
104
|
+
| `textLiteral`, `numberLiteral`, `booleanLiteral`, `instantLiteral` | a bind parameter, cast to `text`, `double precision`, `boolean`, `timestamptz` |
|
|
105
|
+
|
|
106
|
+
Every literal in the tree becomes a parameter. Nothing but structure, operators and quoted identifiers is ever written into the returned `sql`, so a literal's content cannot alter the statement.
|
|
107
|
+
|
|
108
|
+
Placeholders are always cast. That is not decoration: PostgreSQL rejects `$1 < $2` outright because it cannot determine either parameter's type, and casting each placeholder to the type its own literal kind implies is what makes a fragment's meaning independent of how a particular driver decided to infer an untyped parameter. `timestamptz` rather than `timestamp`, because trilean's `instant` is an ISO-8601 string that may carry an offset and parsing one as a naive timestamp would silently discard it.
|
|
109
|
+
|
|
110
|
+
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)` — reproduce that exactly, which a bare `FALSE`/`TRUE` would not, most visibly under a surrounding `NOT`.
|
|
111
|
+
|
|
112
|
+
## Refusal
|
|
113
|
+
|
|
114
|
+
The compiler never degrades. There is no best-effort fragment, no silently dropped conjunct, no approximation that answers differently from the evaluator. Either the whole tree compiles to SQL that agrees with `evaluatePredicate` row for row, or `UnsupportedNodeError` is thrown and the caller evaluates in process instead.
|
|
115
|
+
|
|
116
|
+
The check is an allow-list walk rather than a deny-list, so a node kind added to trilean after this version was written is refused by default instead of falling through to whatever branch happened to be last.
|
|
117
|
+
|
|
118
|
+
That guarantee is about the tree's structure, and it has two limits, both about the *content* of a string operand rather than any node's kind, and neither reachable by a walk over kinds. A `matches`/`notMatches` pattern is matched by the server in PostgreSQL's own regular-expression language, not ECMAScript's — see [Regular expressions](#regular-expressions), which is where the row-for-row claim actually stops. An `instantLiteral` is parsed by PostgreSQL rather than by `Date`, so one carrying no UTC offset is read in the *database session's* time zone where trilean reads it in the Node process's, and one PostgreSQL cannot parse at all raises a query error at execution time rather than this exception (trilean answers `indeterminate` for the same string). Pass instants as offset-bearing ISO-8601, which both read identically.
|
|
119
|
+
|
|
120
|
+
**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`: PostgreSQL has no complex type.
|
|
121
|
+
|
|
122
|
+
**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`: trilean compares numbers with `===`, under which NaN equals nothing including itself, while PostgreSQL defines NaN as equal to itself and greater than every other double — so `NaN = NaN` selects every row there and none here. Infinities are not refused alongside it; both engines order them identically.
|
|
123
|
+
|
|
124
|
+
**Operand pairings the two engines would answer differently.** These are the reason to declare `paramType`, and they are only detectable where it is declared:
|
|
125
|
+
|
|
126
|
+
- A `compare` against text. trilean returns `wrong-type` and directs you to `textCompare`; PostgreSQL would order the operand by collation and answer definitely.
|
|
127
|
+
- An ordering `compare` (`gt`/`gte`/`lt`/`lte`) against a boolean. trilean has no order for booleans; PostgreSQL orders `false` before `true`.
|
|
128
|
+
- A `textCompare` against a non-text operand, which trilean treats as `wrong-type`.
|
|
129
|
+
- Any comparison whose operands are of different declared kinds — a number against an instant, say. trilean calls that `wrong-type`; PostgreSQL may coerce one to the other and answer definitely.
|
|
130
|
+
|
|
131
|
+
Left undeclared, these compile, and the divergence is real but invisible. That is the whole argument for supplying `paramType`.
|
|
132
|
+
|
|
133
|
+
## Regular expressions
|
|
134
|
+
|
|
135
|
+
`matches` and `notMatches` compile to PostgreSQL's `~` and `!~`, so the pattern is matched by the server. PostgreSQL's advanced regular expressions and ECMAScript's `RegExp` are close but not the same language: shorthand classes and lookahead exist in both, and much everyday pattern syntax is portable, but they are separate implementations with their own escapes, quantifier subtleties and matching rules. A pattern that relies on ECMAScript-specific behaviour may match differently once pushed down. Keep patterns to portable syntax, or evaluate them in process.
|
|
136
|
+
|
|
137
|
+
## Tests
|
|
138
|
+
|
|
139
|
+
The unit suite asserts compiled SQL text and parameter arrays per node kind. It cannot, on its own, establish anything about three-valued behaviour: `("age" > $1)` is only indeterminate-preserving because of what PostgreSQL's planner does with a `NULL` age, which is a fact about PostgreSQL rather than about the string.
|
|
140
|
+
|
|
141
|
+
So the integration suite (`pnpm test:integration`) seeds a table whose rows carry real `NULL`s, and for every case executes the compiled fragment as a `WHERE` clause *and* evaluates the same tree through trilean's own `evaluatePredicate` once per row, asserting the two agree on which rows match and which do not. Agreement on absence matters as much as on presence: the case that distinguishes three-valued logic from two-valued is the row that appears in neither a predicate nor its negation.
|
|
142
|
+
|
|
143
|
+
That suite runs case for case against two engines. `postgres.test.ts` uses a real PostgreSQL server started as an ephemeral container, and needs a working Docker daemon. `pglite.test.ts` uses [PGlite](https://pglite.dev), which is PostgreSQL itself compiled to WebAssembly and run in process rather than a reimplementation of it, and needs nothing beyond Node — so the parity claim above is measurable on any machine, Docker or not, and PGlite is a verified target of the `postgres` dialect rather than an assumed one.
|
|
144
|
+
|
|
145
|
+
## Licence
|
|
146
|
+
|
|
147
|
+
MIT — see [LICENSE](LICENSE).
|
package/dist/compile.cjs
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
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_options = require("./options.cjs");
|
|
5
|
+
//#region src/compile.ts
|
|
6
|
+
const COMPARISON_SQL = {
|
|
7
|
+
gt: ">",
|
|
8
|
+
gte: ">=",
|
|
9
|
+
lt: "<",
|
|
10
|
+
lte: "<=",
|
|
11
|
+
eq: "=",
|
|
12
|
+
neq: "<>"
|
|
13
|
+
};
|
|
14
|
+
/** `~` and `!~` are PostgreSQL's own regular-expression match operators, so a pattern is matched by the database rather than shipped back to be matched in process. See the "Regular expressions" caveat in README.md: PostgreSQL's advanced regular expressions and ECMAScript's are close but not the same language. */
|
|
15
|
+
const TEXT_COMPARISON_SQL = {
|
|
16
|
+
equals: "=",
|
|
17
|
+
notEquals: "<>",
|
|
18
|
+
matches: "~",
|
|
19
|
+
notMatches: "!~"
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* The SQL type a literal placeholder is cast to: the one implied by the literal's own trilean kind.
|
|
23
|
+
*
|
|
24
|
+
* Casting every placeholder means a fragment's meaning never depends on how a particular driver decided to infer an untyped parameter, and it is what makes a comparison between two literals (`$1 < $2`, which PostgreSQL rejects outright as having undeterminable parameter types) compile to something executable at all.
|
|
25
|
+
*
|
|
26
|
+
* 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 maps to the same PostgreSQL type as the literal kind it must then match. Consulting it here would be a branch that can never change the output.
|
|
27
|
+
*/
|
|
28
|
+
const PARAM_TYPE_OF_LITERAL = {
|
|
29
|
+
textLiteral: "text",
|
|
30
|
+
numberLiteral: "number",
|
|
31
|
+
booleanLiteral: "boolean",
|
|
32
|
+
instantLiteral: "timestamp"
|
|
33
|
+
};
|
|
34
|
+
function placeholder(context, value, castTo) {
|
|
35
|
+
context.params.push(value);
|
|
36
|
+
return `$${String(context.params.length)}::${require_options.POSTGRES_TYPE_NAME[castTo]}`;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Renders a column as a PostgreSQL identifier: each dot-separated segment double-quoted, with any embedded double quote doubled.
|
|
40
|
+
*
|
|
41
|
+
* 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.
|
|
42
|
+
*/
|
|
43
|
+
function quoteColumn(referenceKey, binding) {
|
|
44
|
+
const segments = binding.column.split(".");
|
|
45
|
+
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");
|
|
46
|
+
return segments.map((segment) => `"${segment.replaceAll("\"", "\"\"")}"`).join(".");
|
|
47
|
+
}
|
|
48
|
+
function bindingOf(context, node) {
|
|
49
|
+
if (node.kind !== "reference" || typeof node.key !== "string") return;
|
|
50
|
+
return {
|
|
51
|
+
referenceKey: node.key,
|
|
52
|
+
binding: context.options.columnFor(node.key)
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The compiler's own refusal, as distinct from the guard's.
|
|
57
|
+
*
|
|
58
|
+
* `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.
|
|
59
|
+
*/
|
|
60
|
+
function refuse(kind, layer) {
|
|
61
|
+
throw new require_errors.UnsupportedNodeError({
|
|
62
|
+
kind,
|
|
63
|
+
path: "$",
|
|
64
|
+
reason: `the ${layer} passed the pushability check but has no compiler branch`
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function compileExpression(node, context) {
|
|
68
|
+
switch (node.kind) {
|
|
69
|
+
case "reference": {
|
|
70
|
+
const resolved = bindingOf(context, node);
|
|
71
|
+
if (resolved === void 0) return refuse(node.kind, "expression");
|
|
72
|
+
return quoteColumn(resolved.referenceKey, resolved.binding);
|
|
73
|
+
}
|
|
74
|
+
case "textLiteral":
|
|
75
|
+
case "numberLiteral":
|
|
76
|
+
case "booleanLiteral":
|
|
77
|
+
case "instantLiteral": return placeholder(context, node.value, PARAM_TYPE_OF_LITERAL[node.kind]);
|
|
78
|
+
}
|
|
79
|
+
return refuse(node.kind, "expression");
|
|
80
|
+
}
|
|
81
|
+
function compilePredicate(node, context) {
|
|
82
|
+
switch (node.kind) {
|
|
83
|
+
case "not": return `(NOT ${compilePredicate(node.operand, context)})`;
|
|
84
|
+
case "and": return `(${compilePredicate(node.left, context)} AND ${compilePredicate(node.right, context)})`;
|
|
85
|
+
case "or": return `(${compilePredicate(node.left, context)} OR ${compilePredicate(node.right, context)})`;
|
|
86
|
+
case "allOf":
|
|
87
|
+
case "anyOf": {
|
|
88
|
+
if (node.operands.length === 0) return node.kind === "allOf" ? "(TRUE)" : "(FALSE)";
|
|
89
|
+
const joiner = node.kind === "allOf" ? " AND " : " OR ";
|
|
90
|
+
return `(${node.operands.map((operand) => compilePredicate(operand, context)).join(joiner)})`;
|
|
91
|
+
}
|
|
92
|
+
case "compare": {
|
|
93
|
+
const left = compileExpression(node.left, context);
|
|
94
|
+
const right = compileExpression(node.right, context);
|
|
95
|
+
return `(${left} ${COMPARISON_SQL[node.op]} ${right})`;
|
|
96
|
+
}
|
|
97
|
+
case "textCompare": {
|
|
98
|
+
const left = compileExpression(node.left, context);
|
|
99
|
+
const right = compileExpression(node.right, context);
|
|
100
|
+
return `(${left} ${TEXT_COMPARISON_SQL[node.op]} ${right})`;
|
|
101
|
+
}
|
|
102
|
+
case "memberOf": {
|
|
103
|
+
const operand = compileExpression(node.operand, context);
|
|
104
|
+
if (node.candidates.length === 0) return node.op === "in" ? `(${operand} IS NULL AND NULL::boolean)` : `(${operand} IS NOT NULL OR NULL::boolean)`;
|
|
105
|
+
const candidates = node.candidates.map((candidate) => compileExpression(candidate, context)).join(", ");
|
|
106
|
+
return `(${operand} ${node.op === "in" ? "IN" : "NOT IN"} (${candidates}))`;
|
|
107
|
+
}
|
|
108
|
+
case "exists": return `(${compileExpression(node.operand, context)} IS NOT NULL)`;
|
|
109
|
+
}
|
|
110
|
+
return refuse(node.kind, "predicate");
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Compiles a trilean predicate tree into a parameterised PostgreSQL boolean expression.
|
|
114
|
+
*
|
|
115
|
+
* 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.
|
|
116
|
+
*
|
|
117
|
+
* Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
|
|
118
|
+
*
|
|
119
|
+
* @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.
|
|
120
|
+
* @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
|
|
121
|
+
*/
|
|
122
|
+
function compilePredicateNode(node, options) {
|
|
123
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
124
|
+
const memoised = {
|
|
125
|
+
dialect: options.dialect,
|
|
126
|
+
columnFor: (referenceKey) => {
|
|
127
|
+
const cached = bindings.get(referenceKey);
|
|
128
|
+
if (cached !== void 0) return cached;
|
|
129
|
+
const binding = options.columnFor(referenceKey);
|
|
130
|
+
bindings.set(referenceKey, binding);
|
|
131
|
+
return binding;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
const unpushable = require_guard.findUnpushableNodeKind(node, memoised);
|
|
135
|
+
if (unpushable !== void 0) throw new require_errors.UnsupportedNodeError(unpushable);
|
|
136
|
+
const context = {
|
|
137
|
+
options: memoised,
|
|
138
|
+
params: []
|
|
139
|
+
};
|
|
140
|
+
return {
|
|
141
|
+
sql: compilePredicate(node, context),
|
|
142
|
+
params: context.params
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
//#endregion
|
|
146
|
+
exports.compilePredicateNode = compilePredicateNode;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { CompiledSql, SqlCompileOptions } from "./options.cjs";
|
|
2
|
+
import { PredicateNode } from "trilean";
|
|
3
|
+
//#region src/compile.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Compiles a trilean predicate tree into a parameterised PostgreSQL boolean expression.
|
|
6
|
+
*
|
|
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
|
+
*
|
|
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 {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.
|
|
13
|
+
*/
|
|
14
|
+
declare function compilePredicateNode(node: PredicateNode, options: Readonly<SqlCompileOptions>): CompiledSql;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { compilePredicateNode };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { CompiledSql, SqlCompileOptions } from "./options.js";
|
|
2
|
+
import { PredicateNode } from "trilean";
|
|
3
|
+
//#region src/compile.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Compiles a trilean predicate tree into a parameterised PostgreSQL boolean expression.
|
|
6
|
+
*
|
|
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
|
+
*
|
|
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 {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.
|
|
13
|
+
*/
|
|
14
|
+
declare function compilePredicateNode(node: PredicateNode, options: Readonly<SqlCompileOptions>): CompiledSql;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { compilePredicateNode };
|
package/dist/compile.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { InvalidColumnError, UnsupportedNodeError } from "./errors.js";
|
|
2
|
+
import { findUnpushableNodeKind } from "./guard.js";
|
|
3
|
+
import { POSTGRES_TYPE_NAME } from "./options.js";
|
|
4
|
+
//#region src/compile.ts
|
|
5
|
+
const COMPARISON_SQL = {
|
|
6
|
+
gt: ">",
|
|
7
|
+
gte: ">=",
|
|
8
|
+
lt: "<",
|
|
9
|
+
lte: "<=",
|
|
10
|
+
eq: "=",
|
|
11
|
+
neq: "<>"
|
|
12
|
+
};
|
|
13
|
+
/** `~` and `!~` are PostgreSQL's own regular-expression match operators, so a pattern is matched by the database rather than shipped back to be matched in process. See the "Regular expressions" caveat in README.md: PostgreSQL's advanced regular expressions and ECMAScript's are close but not the same language. */
|
|
14
|
+
const TEXT_COMPARISON_SQL = {
|
|
15
|
+
equals: "=",
|
|
16
|
+
notEquals: "<>",
|
|
17
|
+
matches: "~",
|
|
18
|
+
notMatches: "!~"
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The SQL type a literal placeholder is cast to: the one implied by the literal's own trilean kind.
|
|
22
|
+
*
|
|
23
|
+
* Casting every placeholder means a fragment's meaning never depends on how a particular driver decided to infer an untyped parameter, and it is what makes a comparison between two literals (`$1 < $2`, which PostgreSQL rejects outright as having undeterminable parameter types) compile to something executable at all.
|
|
24
|
+
*
|
|
25
|
+
* 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 maps to the same PostgreSQL type as the literal kind it must then match. Consulting it here would be a branch that can never change the output.
|
|
26
|
+
*/
|
|
27
|
+
const PARAM_TYPE_OF_LITERAL = {
|
|
28
|
+
textLiteral: "text",
|
|
29
|
+
numberLiteral: "number",
|
|
30
|
+
booleanLiteral: "boolean",
|
|
31
|
+
instantLiteral: "timestamp"
|
|
32
|
+
};
|
|
33
|
+
function placeholder(context, value, castTo) {
|
|
34
|
+
context.params.push(value);
|
|
35
|
+
return `$${String(context.params.length)}::${POSTGRES_TYPE_NAME[castTo]}`;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Renders a column as a PostgreSQL identifier: each dot-separated segment double-quoted, with any embedded double quote doubled.
|
|
39
|
+
*
|
|
40
|
+
* 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.
|
|
41
|
+
*/
|
|
42
|
+
function quoteColumn(referenceKey, binding) {
|
|
43
|
+
const segments = binding.column.split(".");
|
|
44
|
+
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");
|
|
45
|
+
return segments.map((segment) => `"${segment.replaceAll("\"", "\"\"")}"`).join(".");
|
|
46
|
+
}
|
|
47
|
+
function bindingOf(context, node) {
|
|
48
|
+
if (node.kind !== "reference" || typeof node.key !== "string") return;
|
|
49
|
+
return {
|
|
50
|
+
referenceKey: node.key,
|
|
51
|
+
binding: context.options.columnFor(node.key)
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The compiler's own refusal, as distinct from the guard's.
|
|
56
|
+
*
|
|
57
|
+
* `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.
|
|
58
|
+
*/
|
|
59
|
+
function refuse(kind, layer) {
|
|
60
|
+
throw new UnsupportedNodeError({
|
|
61
|
+
kind,
|
|
62
|
+
path: "$",
|
|
63
|
+
reason: `the ${layer} passed the pushability check but has no compiler branch`
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function compileExpression(node, context) {
|
|
67
|
+
switch (node.kind) {
|
|
68
|
+
case "reference": {
|
|
69
|
+
const resolved = bindingOf(context, node);
|
|
70
|
+
if (resolved === void 0) return refuse(node.kind, "expression");
|
|
71
|
+
return quoteColumn(resolved.referenceKey, resolved.binding);
|
|
72
|
+
}
|
|
73
|
+
case "textLiteral":
|
|
74
|
+
case "numberLiteral":
|
|
75
|
+
case "booleanLiteral":
|
|
76
|
+
case "instantLiteral": return placeholder(context, node.value, PARAM_TYPE_OF_LITERAL[node.kind]);
|
|
77
|
+
}
|
|
78
|
+
return refuse(node.kind, "expression");
|
|
79
|
+
}
|
|
80
|
+
function compilePredicate(node, context) {
|
|
81
|
+
switch (node.kind) {
|
|
82
|
+
case "not": return `(NOT ${compilePredicate(node.operand, context)})`;
|
|
83
|
+
case "and": return `(${compilePredicate(node.left, context)} AND ${compilePredicate(node.right, context)})`;
|
|
84
|
+
case "or": return `(${compilePredicate(node.left, context)} OR ${compilePredicate(node.right, context)})`;
|
|
85
|
+
case "allOf":
|
|
86
|
+
case "anyOf": {
|
|
87
|
+
if (node.operands.length === 0) return node.kind === "allOf" ? "(TRUE)" : "(FALSE)";
|
|
88
|
+
const joiner = node.kind === "allOf" ? " AND " : " OR ";
|
|
89
|
+
return `(${node.operands.map((operand) => compilePredicate(operand, context)).join(joiner)})`;
|
|
90
|
+
}
|
|
91
|
+
case "compare": {
|
|
92
|
+
const left = compileExpression(node.left, context);
|
|
93
|
+
const right = compileExpression(node.right, context);
|
|
94
|
+
return `(${left} ${COMPARISON_SQL[node.op]} ${right})`;
|
|
95
|
+
}
|
|
96
|
+
case "textCompare": {
|
|
97
|
+
const left = compileExpression(node.left, context);
|
|
98
|
+
const right = compileExpression(node.right, context);
|
|
99
|
+
return `(${left} ${TEXT_COMPARISON_SQL[node.op]} ${right})`;
|
|
100
|
+
}
|
|
101
|
+
case "memberOf": {
|
|
102
|
+
const operand = compileExpression(node.operand, context);
|
|
103
|
+
if (node.candidates.length === 0) return node.op === "in" ? `(${operand} IS NULL AND NULL::boolean)` : `(${operand} IS NOT NULL OR NULL::boolean)`;
|
|
104
|
+
const candidates = node.candidates.map((candidate) => compileExpression(candidate, context)).join(", ");
|
|
105
|
+
return `(${operand} ${node.op === "in" ? "IN" : "NOT IN"} (${candidates}))`;
|
|
106
|
+
}
|
|
107
|
+
case "exists": return `(${compileExpression(node.operand, context)} IS NOT NULL)`;
|
|
108
|
+
}
|
|
109
|
+
return refuse(node.kind, "predicate");
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Compiles a trilean predicate tree into a parameterised PostgreSQL boolean expression.
|
|
113
|
+
*
|
|
114
|
+
* 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.
|
|
115
|
+
*
|
|
116
|
+
* Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
|
|
117
|
+
*
|
|
118
|
+
* @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.
|
|
119
|
+
* @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
|
|
120
|
+
*/
|
|
121
|
+
function compilePredicateNode(node, options) {
|
|
122
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
123
|
+
const memoised = {
|
|
124
|
+
dialect: options.dialect,
|
|
125
|
+
columnFor: (referenceKey) => {
|
|
126
|
+
const cached = bindings.get(referenceKey);
|
|
127
|
+
if (cached !== void 0) return cached;
|
|
128
|
+
const binding = options.columnFor(referenceKey);
|
|
129
|
+
bindings.set(referenceKey, binding);
|
|
130
|
+
return binding;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
const unpushable = findUnpushableNodeKind(node, memoised);
|
|
134
|
+
if (unpushable !== void 0) throw new UnsupportedNodeError(unpushable);
|
|
135
|
+
const context = {
|
|
136
|
+
options: memoised,
|
|
137
|
+
params: []
|
|
138
|
+
};
|
|
139
|
+
return {
|
|
140
|
+
sql: compilePredicate(node, context),
|
|
141
|
+
params: context.params
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
//#endregion
|
|
145
|
+
export { compilePredicateNode };
|
package/dist/errors.cjs
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region 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 PostgreSQL's regular-expression language rather than ECMAScript's, and an `instantLiteral` string the two engines parse differently or that PostgreSQL cannot parse 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 `columnFor` result whose `column` cannot be rendered as a PostgreSQL identifier.
|
|
31
|
+
*
|
|
32
|
+
* 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.
|
|
33
|
+
*/
|
|
34
|
+
var InvalidColumnError = class extends TrileanSqlError {
|
|
35
|
+
referenceKey;
|
|
36
|
+
column;
|
|
37
|
+
constructor(referenceKey, column, reason) {
|
|
38
|
+
super(`columnFor(${JSON.stringify(referenceKey)}) returned ${JSON.stringify(column)}, which is not a usable column identifier: ${reason}`);
|
|
39
|
+
this.name = "InvalidColumnError";
|
|
40
|
+
this.referenceKey = referenceKey;
|
|
41
|
+
this.column = column;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
//#endregion
|
|
45
|
+
exports.InvalidColumnError = InvalidColumnError;
|
|
46
|
+
exports.TrileanSqlError = TrileanSqlError;
|
|
47
|
+
exports.UnsupportedNodeError = UnsupportedNodeError;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//#region src/errors.d.ts
|
|
2
|
+
/** 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). */
|
|
3
|
+
declare class TrileanSqlError extends Error {
|
|
4
|
+
constructor(message: string);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* 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.
|
|
8
|
+
*
|
|
9
|
+
* 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 PostgreSQL's regular-expression language rather than ECMAScript's, and an `instantLiteral` string the two engines parse differently or that PostgreSQL cannot parse 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.
|
|
10
|
+
*
|
|
11
|
+
* `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).
|
|
12
|
+
*/
|
|
13
|
+
declare class UnsupportedNodeError extends TrileanSqlError {
|
|
14
|
+
readonly nodeKind: string;
|
|
15
|
+
readonly path: string;
|
|
16
|
+
readonly reason: string;
|
|
17
|
+
constructor(unpushable: Readonly<{
|
|
18
|
+
kind: string;
|
|
19
|
+
path: string;
|
|
20
|
+
reason: string;
|
|
21
|
+
}>);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A `columnFor` result whose `column` cannot be rendered as a PostgreSQL identifier.
|
|
25
|
+
*
|
|
26
|
+
* 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.
|
|
27
|
+
*/
|
|
28
|
+
declare class InvalidColumnError extends TrileanSqlError {
|
|
29
|
+
readonly referenceKey: string;
|
|
30
|
+
readonly column: string;
|
|
31
|
+
constructor(referenceKey: string, column: string, reason: string);
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { InvalidColumnError, TrileanSqlError, UnsupportedNodeError };
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//#region src/errors.d.ts
|
|
2
|
+
/** 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). */
|
|
3
|
+
declare class TrileanSqlError extends Error {
|
|
4
|
+
constructor(message: string);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* 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.
|
|
8
|
+
*
|
|
9
|
+
* 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 PostgreSQL's regular-expression language rather than ECMAScript's, and an `instantLiteral` string the two engines parse differently or that PostgreSQL cannot parse 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.
|
|
10
|
+
*
|
|
11
|
+
* `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).
|
|
12
|
+
*/
|
|
13
|
+
declare class UnsupportedNodeError extends TrileanSqlError {
|
|
14
|
+
readonly nodeKind: string;
|
|
15
|
+
readonly path: string;
|
|
16
|
+
readonly reason: string;
|
|
17
|
+
constructor(unpushable: Readonly<{
|
|
18
|
+
kind: string;
|
|
19
|
+
path: string;
|
|
20
|
+
reason: string;
|
|
21
|
+
}>);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A `columnFor` result whose `column` cannot be rendered as a PostgreSQL identifier.
|
|
25
|
+
*
|
|
26
|
+
* 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.
|
|
27
|
+
*/
|
|
28
|
+
declare class InvalidColumnError extends TrileanSqlError {
|
|
29
|
+
readonly referenceKey: string;
|
|
30
|
+
readonly column: string;
|
|
31
|
+
constructor(referenceKey: string, column: string, reason: string);
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { InvalidColumnError, TrileanSqlError, UnsupportedNodeError };
|