trilean-sql 1.0.1 → 1.1.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 +63 -24
- package/dist/compile.cjs +28 -16
- package/dist/compile.d.cts +2 -1
- package/dist/compile.d.ts +2 -1
- package/dist/compile.js +28 -16
- package/dist/errors.cjs +20 -2
- package/dist/errors.d.cts +15 -3
- package/dist/errors.d.ts +15 -3
- package/dist/errors.js +20 -3
- package/dist/guard.cjs +44 -21
- package/dist/guard.d.cts +4 -0
- package/dist/guard.d.ts +4 -0
- package/dist/guard.js +44 -21
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/options.cjs +27 -0
- package/dist/options.d.cts +32 -6
- package/dist/options.d.ts +32 -6
- package/dist/options.js +26 -1
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -65,13 +65,13 @@ The fragment is a self-contained boolean expression with no `WHERE` keyword of i
|
|
|
65
65
|
|
|
66
66
|
Returns `{ sql, params }`. Throws rather than approximating; see [Refusal](#refusal).
|
|
67
67
|
|
|
68
|
-
`options.dialect` is `"postgres"`. It is required rather than defaulted so that a
|
|
68
|
+
`options.dialect` is `"postgres"` or `"sqlite"`. It is required rather than defaulted so that a caller states the engine it is compiling for, instead of inheriting whichever one this package happened to implement first. See [Dialects](#dialects) for what differs between them; the tree, the refusals, and the three-valued guarantee do not.
|
|
69
69
|
|
|
70
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
71
|
|
|
72
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
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
|
|
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 the database would coerce into a definite answer where trilean returns `indeterminate` compiles silently.
|
|
75
75
|
|
|
76
76
|
### `findUnpushableNodeKind(node, options?)`
|
|
77
77
|
|
|
@@ -92,22 +92,43 @@ Passing `options` widens the check: without them the walk is purely structural;
|
|
|
92
92
|
|
|
93
93
|
## What compiles
|
|
94
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` |
|
|
95
|
+
| Node | PostgreSQL | SQLite |
|
|
96
|
+
| --- | --- | --- |
|
|
97
|
+
| `and`, `or`, `not` | `AND`, `OR`, `NOT` | same |
|
|
98
|
+
| `allOf`, `anyOf` | n-ary `AND`, `OR`; empty operands become each connective's identity, `TRUE` and `FALSE`, matching the evaluator's own fold | same |
|
|
99
|
+
| `compare` | `>`, `>=`, `<`, `<=`, `=`, `<>` | same |
|
|
100
|
+
| `textCompare` | `=`, `<>`, and `~` / `!~` for `matches` / `notMatches` | `=`, `<>`, and `REGEXP` / `NOT REGEXP` |
|
|
101
|
+
| `memberOf` | `IN` / `NOT IN`, one parameter per candidate | same |
|
|
102
|
+
| `exists` | `IS NOT NULL` | same |
|
|
103
|
+
| `reference` | the mapped column, as a quoted identifier | same |
|
|
104
|
+
| `textLiteral`, `numberLiteral`, `booleanLiteral`, `instantLiteral` | a bind parameter, cast to `text`, `double precision`, `boolean`, `timestamptz` | a bare `?`, uncast |
|
|
105
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.
|
|
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. Identifier quoting is the same in both: each dot-separated segment double-quoted with any embedded quote doubled, which is ANSI-standard and not a per-dialect rule.
|
|
107
107
|
|
|
108
|
-
|
|
108
|
+
PostgreSQL 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. SQLite placeholders carry neither a number nor a cast, because there is nothing to write: parameters bind by the order they appear, and there is no type to annotate. It answers a comparison between two bare `?` from the bound values themselves.
|
|
109
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)
|
|
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)`, 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`.
|
|
111
|
+
|
|
112
|
+
## Dialects
|
|
113
|
+
|
|
114
|
+
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.
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
const { sql, params } = compilePredicateNode(rule, { dialect: "sqlite", columnFor });
|
|
118
|
+
// sql: (("age" >= ?) AND ("email" REGEXP ?))
|
|
119
|
+
// params: [18, "@example[.]com$"]
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
What compiles, what is refused, and the row-for-row agreement with `evaluatePredicate` are the same in both. The refusals in particular are not PostgreSQL caution carried over untested: SQLite's type affinity produces the same silent definite answers where trilean returns `wrong-type`, and `test/integration/sqlite.test.ts` measures each one against a real connection. A `TEXT`-affinity column compared to the number `5` is compared *as text*, so `'9' > 5` is true there while `'10' > 5` is not; a boolean is an integer, so `gt` on one answers by integer ordering; and `'abc' > 5`, with no column involved at all, answers `true` rather than erroring.
|
|
123
|
+
|
|
124
|
+
Two things a SQLite caller has to supply that a PostgreSQL caller does not, both of which fail loudly rather than silently:
|
|
125
|
+
|
|
126
|
+
- **A `REGEXP` function**, if the tree uses `matches` or `notMatches`. See [Regular expressions](#regular-expressions).
|
|
127
|
+
- **Booleans bound as `0`/`1`.** SQLite has no boolean type, and drivers do not agree on whether a JS boolean is bindable at all — better-sqlite3 rejects one outright (*"SQLite3 can only bind numbers, strings, bigints, buffers, and null"*). `params` carries the tree's own literals unchanged in every dialect, so converting them is the binding caller's job: `params.map((v) => (typeof v === "boolean" ? Number(v) : v))`.
|
|
128
|
+
|
|
129
|
+
A dialect this version does not implement is refused by name, from `compilePredicateNode` and `findUnpushableNodeKind` alike, with `UnknownDialectError`. `SqlDialect` is a closed union so TypeScript source cannot reach that, but a dialect read from configuration and asserted into the union at the boundary can, and reporting such a tree as pushable would promise a compilation that cannot happen.
|
|
130
|
+
|
|
131
|
+
Instants are the one place to be deliberate rather than merely careful. SQLite has no timestamp type either, so an `instantLiteral` is compared as text against whatever text the column holds. Offset-bearing ISO-8601 in a single common offset (`2020-01-01T00:00:00Z`) sorts chronologically as a string and compares correctly; mixed offsets, or a format that is not ISO-8601, do not. This is the SQLite counterpart of the PostgreSQL session-time-zone caveat under [Refusal](#refusal), and the same advice resolves both.
|
|
111
132
|
|
|
112
133
|
## Refusal
|
|
113
134
|
|
|
@@ -117,30 +138,48 @@ The check is an allow-list walk rather than a deny-list, so a node kind added to
|
|
|
117
138
|
|
|
118
139
|
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
140
|
|
|
120
|
-
|
|
141
|
+
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.
|
|
142
|
+
|
|
143
|
+
**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.
|
|
121
144
|
|
|
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
|
|
145
|
+
**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.
|
|
123
146
|
|
|
124
|
-
**Operand pairings the
|
|
147
|
+
**Operand pairings the engines would answer differently.** These are the reason to declare `paramType`, and they are only detectable where it is declared:
|
|
125
148
|
|
|
126
|
-
- A `compare` against text. trilean returns `wrong-type` and directs you to `textCompare
|
|
127
|
-
- An ordering `compare` (`gt`/`gte`/`lt`/`lte`) against a boolean. trilean has no order for booleans; PostgreSQL orders `false` before `true
|
|
149
|
+
- A `compare` against text. trilean returns `wrong-type` and directs you to `textCompare`. PostgreSQL orders the operand by collation and answers definitely; SQLite applies the text operand's own affinity to the other side and compares lexicographically, which is worse rather than better — `'9' > 5` is true and `'10' > 5` is not.
|
|
150
|
+
- 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.
|
|
128
151
|
- 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`;
|
|
152
|
+
- 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.
|
|
130
153
|
|
|
131
154
|
Left undeclared, these compile, and the divergence is real but invisible. That is the whole argument for supplying `paramType`.
|
|
132
155
|
|
|
133
156
|
## Regular expressions
|
|
134
157
|
|
|
135
|
-
`matches` and `notMatches` compile to
|
|
158
|
+
Under PostgreSQL, `matches` and `notMatches` compile to `~` 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.
|
|
159
|
+
|
|
160
|
+
Under SQLite there is no built-in regular-expression support at all. `REGEXP` is reserved syntax for a `regexp(pattern, value)` function the connection has to register itself — `X REGEXP Y` is exactly `regexp(Y, X)`, pattern first — and the dialect emits `REGEXP` / `NOT REGEXP` for the same two operators. An unregistered one is a query error, `no such function: REGEXP`, rather than a fragment that quietly matches nothing, so this is a documented environment requirement in the same class as the caveats above and not a hole in the compile-time guarantee. The upside is that the pattern is then matched by your own `RegExp`, so the ECMAScript-versus-server-dialect divergence above does not arise.
|
|
161
|
+
|
|
162
|
+
With better-sqlite3:
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
db.function("regexp", (pattern, text) =>
|
|
166
|
+
typeof pattern !== "string" || typeof text !== "string"
|
|
167
|
+
? null
|
|
168
|
+
: new RegExp(pattern).test(text)
|
|
169
|
+
? 1
|
|
170
|
+
: 0,
|
|
171
|
+
);
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Both details are load-bearing rather than stylistic. Returning `null` for a NULL argument is what keeps the third value intact: SQLite does not propagate NULL through a user function on its own, so one answering `0` for a NULL value would make `NOT REGEXP` answer `TRUE` for a row whose value is unknown — the two-valued collapse this package exists to avoid. Returning `1`/`0` rather than a JS boolean is what better-sqlite3 accepts; a boolean is rejected from a user function (*"returned an invalid value"*) for the same reason it is rejected as a bound parameter.
|
|
136
175
|
|
|
137
176
|
## Tests
|
|
138
177
|
|
|
139
178
|
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
179
|
|
|
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.
|
|
180
|
+
So the integration suite (`pnpm test:integration`) runs the same fixture against a real engine, once per implementation: PostgreSQL in an ephemeral container, PGlite in process, and SQLite in memory through better-sqlite3. Each 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
181
|
|
|
143
|
-
|
|
182
|
+
`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. `sqlite.test.ts` likewise needs nothing beyond Node, and also measures the divergences the guard's refusals exist to prevent — the NaN-to-NULL binding substitution, the lexicographic text comparison, the integer boolean ordering — rather than only asserting that each refusal fires, since inheriting PostgreSQL's refusal set would be worth nothing if SQLite happened to agree with trilean where PostgreSQL does not.
|
|
144
183
|
|
|
145
184
|
## Licence
|
|
146
185
|
|
package/dist/compile.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_errors = require("./errors.cjs");
|
|
3
|
-
const require_guard = require("./guard.cjs");
|
|
4
3
|
const require_options = require("./options.cjs");
|
|
4
|
+
const require_guard = require("./guard.cjs");
|
|
5
5
|
//#region src/compile.ts
|
|
6
6
|
const COMPARISON_SQL = {
|
|
7
7
|
gt: ">",
|
|
@@ -11,19 +11,23 @@ const COMPARISON_SQL = {
|
|
|
11
11
|
eq: "=",
|
|
12
12
|
neq: "<>"
|
|
13
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
14
|
/**
|
|
22
|
-
* The
|
|
15
|
+
* The operator each `textCompare` op emits, for one dialect.
|
|
23
16
|
*
|
|
24
|
-
*
|
|
17
|
+
* `=` and `<>` are ANSI-standard equality and identical everywhere; only the two pattern operators are the dialect's own. Built as a complete record rather than resolved per node so that a `TextComparisonOperator` added to trilean later is a compile error here, instead of an undefined operator spliced into the emitted SQL.
|
|
18
|
+
*/
|
|
19
|
+
function textComparisonSqlFor(dialect) {
|
|
20
|
+
return {
|
|
21
|
+
equals: "=",
|
|
22
|
+
notEquals: "<>",
|
|
23
|
+
matches: dialect.matches,
|
|
24
|
+
notMatches: dialect.notMatches
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The value kind a literal placeholder is rendered for: the one implied by the literal's own trilean kind. What a dialect does with it -- PostgreSQL casts the placeholder to the corresponding type, SQLite ignores it -- is `DialectConfig.placeholder`'s business.
|
|
25
29
|
*
|
|
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
|
|
30
|
+
* A mapped column's declared `paramType` deliberately does not override this. It cannot differ: the guard has already refused any comparison whose operand kinds disagree, and each declared kind implies the same SQL type as the literal kind it must then match. Consulting it here would be a branch that can never change the output.
|
|
27
31
|
*/
|
|
28
32
|
const PARAM_TYPE_OF_LITERAL = {
|
|
29
33
|
textLiteral: "text",
|
|
@@ -33,10 +37,10 @@ const PARAM_TYPE_OF_LITERAL = {
|
|
|
33
37
|
};
|
|
34
38
|
function placeholder(context, value, castTo) {
|
|
35
39
|
context.params.push(value);
|
|
36
|
-
return
|
|
40
|
+
return context.dialect.placeholder(context.params.length, castTo);
|
|
37
41
|
}
|
|
38
42
|
/**
|
|
39
|
-
* Renders a column as a
|
|
43
|
+
* Renders a column as a SQL identifier: each dot-separated segment double-quoted, with any embedded double quote doubled. Double-quoting is ANSI-standard and means the same thing in both dialects, so this needs no per-dialect branch.
|
|
40
44
|
*
|
|
41
45
|
* 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
46
|
*/
|
|
@@ -97,11 +101,14 @@ function compilePredicate(node, context) {
|
|
|
97
101
|
case "textCompare": {
|
|
98
102
|
const left = compileExpression(node.left, context);
|
|
99
103
|
const right = compileExpression(node.right, context);
|
|
100
|
-
return `(${left} ${
|
|
104
|
+
return `(${left} ${context.textComparison[node.op]} ${right})`;
|
|
101
105
|
}
|
|
102
106
|
case "memberOf": {
|
|
103
107
|
const operand = compileExpression(node.operand, context);
|
|
104
|
-
if (node.candidates.length === 0)
|
|
108
|
+
if (node.candidates.length === 0) {
|
|
109
|
+
const nullLiteral = `NULL${context.dialect.emptyMemberOfNullSuffix}`;
|
|
110
|
+
return node.op === "in" ? `(${operand} IS NULL AND ${nullLiteral})` : `(${operand} IS NOT NULL OR ${nullLiteral})`;
|
|
111
|
+
}
|
|
105
112
|
const candidates = node.candidates.map((candidate) => compileExpression(candidate, context)).join(", ");
|
|
106
113
|
return `(${operand} ${node.op === "in" ? "IN" : "NOT IN"} (${candidates}))`;
|
|
107
114
|
}
|
|
@@ -110,16 +117,18 @@ function compilePredicate(node, context) {
|
|
|
110
117
|
return refuse(node.kind, "predicate");
|
|
111
118
|
}
|
|
112
119
|
/**
|
|
113
|
-
* Compiles a trilean predicate tree into a parameterised
|
|
120
|
+
* Compiles a trilean predicate tree into a parameterised boolean expression in the dialect `options` names.
|
|
114
121
|
*
|
|
115
122
|
* 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
123
|
*
|
|
117
124
|
* Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
|
|
118
125
|
*
|
|
126
|
+
* @throws {UnknownDialectError} if `options.dialect` names a dialect this version does not implement.
|
|
119
127
|
* @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
128
|
* @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
|
|
121
129
|
*/
|
|
122
130
|
function compilePredicateNode(node, options) {
|
|
131
|
+
require_options.assertImplementedDialect(options.dialect);
|
|
123
132
|
const bindings = /* @__PURE__ */ new Map();
|
|
124
133
|
const memoised = {
|
|
125
134
|
dialect: options.dialect,
|
|
@@ -133,8 +142,11 @@ function compilePredicateNode(node, options) {
|
|
|
133
142
|
};
|
|
134
143
|
const unpushable = require_guard.findUnpushableNodeKind(node, memoised);
|
|
135
144
|
if (unpushable !== void 0) throw new require_errors.UnsupportedNodeError(unpushable);
|
|
145
|
+
const dialect = require_options.DIALECT_CONFIG[options.dialect];
|
|
136
146
|
const context = {
|
|
137
147
|
options: memoised,
|
|
148
|
+
dialect,
|
|
149
|
+
textComparison: textComparisonSqlFor(dialect),
|
|
138
150
|
params: []
|
|
139
151
|
};
|
|
140
152
|
return {
|
package/dist/compile.d.cts
CHANGED
|
@@ -2,12 +2,13 @@ import { CompiledSql, SqlCompileOptions } from "./options.cjs";
|
|
|
2
2
|
import { PredicateNode } from "trilean";
|
|
3
3
|
//#region src/compile.d.ts
|
|
4
4
|
/**
|
|
5
|
-
* Compiles a trilean predicate tree into a parameterised
|
|
5
|
+
* Compiles a trilean predicate tree into a parameterised boolean expression in the dialect `options` names.
|
|
6
6
|
*
|
|
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
10
|
*
|
|
11
|
+
* @throws {UnknownDialectError} if `options.dialect` names a dialect this version does not implement.
|
|
11
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.
|
|
12
13
|
* @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
|
|
13
14
|
*/
|
package/dist/compile.d.ts
CHANGED
|
@@ -2,12 +2,13 @@ import { CompiledSql, SqlCompileOptions } from "./options.js";
|
|
|
2
2
|
import { PredicateNode } from "trilean";
|
|
3
3
|
//#region src/compile.d.ts
|
|
4
4
|
/**
|
|
5
|
-
* Compiles a trilean predicate tree into a parameterised
|
|
5
|
+
* Compiles a trilean predicate tree into a parameterised boolean expression in the dialect `options` names.
|
|
6
6
|
*
|
|
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
10
|
*
|
|
11
|
+
* @throws {UnknownDialectError} if `options.dialect` names a dialect this version does not implement.
|
|
11
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.
|
|
12
13
|
* @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
|
|
13
14
|
*/
|
package/dist/compile.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { InvalidColumnError, UnsupportedNodeError } from "./errors.js";
|
|
2
|
+
import { DIALECT_CONFIG, assertImplementedDialect } from "./options.js";
|
|
2
3
|
import { findUnpushableNodeKind } from "./guard.js";
|
|
3
|
-
import { POSTGRES_TYPE_NAME } from "./options.js";
|
|
4
4
|
//#region src/compile.ts
|
|
5
5
|
const COMPARISON_SQL = {
|
|
6
6
|
gt: ">",
|
|
@@ -10,19 +10,23 @@ const COMPARISON_SQL = {
|
|
|
10
10
|
eq: "=",
|
|
11
11
|
neq: "<>"
|
|
12
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
13
|
/**
|
|
21
|
-
* The
|
|
14
|
+
* The operator each `textCompare` op emits, for one dialect.
|
|
22
15
|
*
|
|
23
|
-
*
|
|
16
|
+
* `=` and `<>` are ANSI-standard equality and identical everywhere; only the two pattern operators are the dialect's own. Built as a complete record rather than resolved per node so that a `TextComparisonOperator` added to trilean later is a compile error here, instead of an undefined operator spliced into the emitted SQL.
|
|
17
|
+
*/
|
|
18
|
+
function textComparisonSqlFor(dialect) {
|
|
19
|
+
return {
|
|
20
|
+
equals: "=",
|
|
21
|
+
notEquals: "<>",
|
|
22
|
+
matches: dialect.matches,
|
|
23
|
+
notMatches: dialect.notMatches
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The value kind a literal placeholder is rendered for: the one implied by the literal's own trilean kind. What a dialect does with it -- PostgreSQL casts the placeholder to the corresponding type, SQLite ignores it -- is `DialectConfig.placeholder`'s business.
|
|
24
28
|
*
|
|
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
|
|
29
|
+
* A mapped column's declared `paramType` deliberately does not override this. It cannot differ: the guard has already refused any comparison whose operand kinds disagree, and each declared kind implies the same SQL type as the literal kind it must then match. Consulting it here would be a branch that can never change the output.
|
|
26
30
|
*/
|
|
27
31
|
const PARAM_TYPE_OF_LITERAL = {
|
|
28
32
|
textLiteral: "text",
|
|
@@ -32,10 +36,10 @@ const PARAM_TYPE_OF_LITERAL = {
|
|
|
32
36
|
};
|
|
33
37
|
function placeholder(context, value, castTo) {
|
|
34
38
|
context.params.push(value);
|
|
35
|
-
return
|
|
39
|
+
return context.dialect.placeholder(context.params.length, castTo);
|
|
36
40
|
}
|
|
37
41
|
/**
|
|
38
|
-
* Renders a column as a
|
|
42
|
+
* Renders a column as a SQL identifier: each dot-separated segment double-quoted, with any embedded double quote doubled. Double-quoting is ANSI-standard and means the same thing in both dialects, so this needs no per-dialect branch.
|
|
39
43
|
*
|
|
40
44
|
* 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
45
|
*/
|
|
@@ -96,11 +100,14 @@ function compilePredicate(node, context) {
|
|
|
96
100
|
case "textCompare": {
|
|
97
101
|
const left = compileExpression(node.left, context);
|
|
98
102
|
const right = compileExpression(node.right, context);
|
|
99
|
-
return `(${left} ${
|
|
103
|
+
return `(${left} ${context.textComparison[node.op]} ${right})`;
|
|
100
104
|
}
|
|
101
105
|
case "memberOf": {
|
|
102
106
|
const operand = compileExpression(node.operand, context);
|
|
103
|
-
if (node.candidates.length === 0)
|
|
107
|
+
if (node.candidates.length === 0) {
|
|
108
|
+
const nullLiteral = `NULL${context.dialect.emptyMemberOfNullSuffix}`;
|
|
109
|
+
return node.op === "in" ? `(${operand} IS NULL AND ${nullLiteral})` : `(${operand} IS NOT NULL OR ${nullLiteral})`;
|
|
110
|
+
}
|
|
104
111
|
const candidates = node.candidates.map((candidate) => compileExpression(candidate, context)).join(", ");
|
|
105
112
|
return `(${operand} ${node.op === "in" ? "IN" : "NOT IN"} (${candidates}))`;
|
|
106
113
|
}
|
|
@@ -109,16 +116,18 @@ function compilePredicate(node, context) {
|
|
|
109
116
|
return refuse(node.kind, "predicate");
|
|
110
117
|
}
|
|
111
118
|
/**
|
|
112
|
-
* Compiles a trilean predicate tree into a parameterised
|
|
119
|
+
* Compiles a trilean predicate tree into a parameterised boolean expression in the dialect `options` names.
|
|
113
120
|
*
|
|
114
121
|
* 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
122
|
*
|
|
116
123
|
* Every caller-supplied literal becomes a bind parameter. Nothing but structure, operators, and quoted column identifiers is ever written into the returned `sql`.
|
|
117
124
|
*
|
|
125
|
+
* @throws {UnknownDialectError} if `options.dialect` names a dialect this version does not implement.
|
|
118
126
|
* @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
127
|
* @throws {InvalidColumnError} if `columnFor` returns a column that cannot be rendered as an identifier.
|
|
120
128
|
*/
|
|
121
129
|
function compilePredicateNode(node, options) {
|
|
130
|
+
assertImplementedDialect(options.dialect);
|
|
122
131
|
const bindings = /* @__PURE__ */ new Map();
|
|
123
132
|
const memoised = {
|
|
124
133
|
dialect: options.dialect,
|
|
@@ -132,8 +141,11 @@ function compilePredicateNode(node, options) {
|
|
|
132
141
|
};
|
|
133
142
|
const unpushable = findUnpushableNodeKind(node, memoised);
|
|
134
143
|
if (unpushable !== void 0) throw new UnsupportedNodeError(unpushable);
|
|
144
|
+
const dialect = DIALECT_CONFIG[options.dialect];
|
|
135
145
|
const context = {
|
|
136
146
|
options: memoised,
|
|
147
|
+
dialect,
|
|
148
|
+
textComparison: textComparisonSqlFor(dialect),
|
|
137
149
|
params: []
|
|
138
150
|
};
|
|
139
151
|
return {
|
package/dist/errors.cjs
CHANGED
|
@@ -10,7 +10,7 @@ var TrileanSqlError = class extends Error {
|
|
|
10
10
|
/**
|
|
11
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
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
|
|
13
|
+
* That guarantee is about the tree's *structure*, and it stops at two things whose meaning is a property of the operand's own content rather than of any node kind: a `matches`/`notMatches` pattern, which the server matches under its own regular-expression language rather than ECMAScript's, and an `instantLiteral` string the database reads differently from trilean or cannot read at all (which fails as a query error at execution time, not as this exception). Both are covered in README.md; neither is detectable by a walk over node kinds.
|
|
14
14
|
*
|
|
15
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
16
|
*/
|
|
@@ -27,7 +27,24 @@ var UnsupportedNodeError = class extends TrileanSqlError {
|
|
|
27
27
|
}
|
|
28
28
|
};
|
|
29
29
|
/**
|
|
30
|
-
* A
|
|
30
|
+
* A dialect this version does not implement.
|
|
31
|
+
*
|
|
32
|
+
* `SqlDialect` is a closed union, so a caller who names a dialect in TypeScript source cannot reach this. A dialect read from configuration and asserted into the type at the boundary can, which is the case it exists for: without it the unimplemented name surfaces later as an internal `TypeError` from a table lookup that found nothing, naming neither the dialect nor the field it was reached from. Refusing by name at the entry point is the same convention `InvalidColumnError` applies to a `columnFor` result and the node walk applies to an unrecognised kind -- an input the type system describes but cannot enforce is checked once, where it arrives.
|
|
33
|
+
*
|
|
34
|
+
* `dialect` is the offending name and `implemented` lists the ones this version does compile.
|
|
35
|
+
*/
|
|
36
|
+
var UnknownDialectError = class extends TrileanSqlError {
|
|
37
|
+
dialect;
|
|
38
|
+
implemented;
|
|
39
|
+
constructor(dialect, implemented) {
|
|
40
|
+
super(`unknown dialect ${JSON.stringify(dialect)}: this version compiles ${implemented.map((name) => JSON.stringify(name)).join(", ")}`);
|
|
41
|
+
this.name = "UnknownDialectError";
|
|
42
|
+
this.dialect = dialect;
|
|
43
|
+
this.implemented = implemented;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* A `columnFor` result whose `column` cannot be rendered as a SQL identifier.
|
|
31
48
|
*
|
|
32
49
|
* A column name is an identifier, not a value, so it is the one part of the emitted SQL that cannot be parameterised -- it has to be written into the statement text. It is always emitted double-quoted with any embedded quote doubled, which makes an arbitrary string safe, so this is not the injection defence; it rejects the two shapes that quoting cannot rescue into a valid identifier, an empty name and an empty dot-separated segment.
|
|
33
50
|
*/
|
|
@@ -44,4 +61,5 @@ var InvalidColumnError = class extends TrileanSqlError {
|
|
|
44
61
|
//#endregion
|
|
45
62
|
exports.InvalidColumnError = InvalidColumnError;
|
|
46
63
|
exports.TrileanSqlError = TrileanSqlError;
|
|
64
|
+
exports.UnknownDialectError = UnknownDialectError;
|
|
47
65
|
exports.UnsupportedNodeError = UnsupportedNodeError;
|
package/dist/errors.d.cts
CHANGED
|
@@ -6,7 +6,7 @@ declare class TrileanSqlError extends Error {
|
|
|
6
6
|
/**
|
|
7
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
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
|
|
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 its own regular-expression language rather than ECMAScript's, and an `instantLiteral` string the database reads differently from trilean or cannot read at all (which fails as a query error at execution time, not as this exception). Both are covered in README.md; neither is detectable by a walk over node kinds.
|
|
10
10
|
*
|
|
11
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
12
|
*/
|
|
@@ -21,7 +21,19 @@ declare class UnsupportedNodeError extends TrileanSqlError {
|
|
|
21
21
|
}>);
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
|
-
* A
|
|
24
|
+
* A dialect this version does not implement.
|
|
25
|
+
*
|
|
26
|
+
* `SqlDialect` is a closed union, so a caller who names a dialect in TypeScript source cannot reach this. A dialect read from configuration and asserted into the type at the boundary can, which is the case it exists for: without it the unimplemented name surfaces later as an internal `TypeError` from a table lookup that found nothing, naming neither the dialect nor the field it was reached from. Refusing by name at the entry point is the same convention `InvalidColumnError` applies to a `columnFor` result and the node walk applies to an unrecognised kind -- an input the type system describes but cannot enforce is checked once, where it arrives.
|
|
27
|
+
*
|
|
28
|
+
* `dialect` is the offending name and `implemented` lists the ones this version does compile.
|
|
29
|
+
*/
|
|
30
|
+
declare class UnknownDialectError extends TrileanSqlError {
|
|
31
|
+
readonly dialect: string;
|
|
32
|
+
readonly implemented: readonly string[];
|
|
33
|
+
constructor(dialect: string, implemented: readonly string[]);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A `columnFor` result whose `column` cannot be rendered as a SQL identifier.
|
|
25
37
|
*
|
|
26
38
|
* 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
39
|
*/
|
|
@@ -31,4 +43,4 @@ declare class InvalidColumnError extends TrileanSqlError {
|
|
|
31
43
|
constructor(referenceKey: string, column: string, reason: string);
|
|
32
44
|
}
|
|
33
45
|
//#endregion
|
|
34
|
-
export { InvalidColumnError, TrileanSqlError, UnsupportedNodeError };
|
|
46
|
+
export { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError };
|
package/dist/errors.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ declare class TrileanSqlError extends Error {
|
|
|
6
6
|
/**
|
|
7
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
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
|
|
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 its own regular-expression language rather than ECMAScript's, and an `instantLiteral` string the database reads differently from trilean or cannot read at all (which fails as a query error at execution time, not as this exception). Both are covered in README.md; neither is detectable by a walk over node kinds.
|
|
10
10
|
*
|
|
11
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
12
|
*/
|
|
@@ -21,7 +21,19 @@ declare class UnsupportedNodeError extends TrileanSqlError {
|
|
|
21
21
|
}>);
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
|
-
* A
|
|
24
|
+
* A dialect this version does not implement.
|
|
25
|
+
*
|
|
26
|
+
* `SqlDialect` is a closed union, so a caller who names a dialect in TypeScript source cannot reach this. A dialect read from configuration and asserted into the type at the boundary can, which is the case it exists for: without it the unimplemented name surfaces later as an internal `TypeError` from a table lookup that found nothing, naming neither the dialect nor the field it was reached from. Refusing by name at the entry point is the same convention `InvalidColumnError` applies to a `columnFor` result and the node walk applies to an unrecognised kind -- an input the type system describes but cannot enforce is checked once, where it arrives.
|
|
27
|
+
*
|
|
28
|
+
* `dialect` is the offending name and `implemented` lists the ones this version does compile.
|
|
29
|
+
*/
|
|
30
|
+
declare class UnknownDialectError extends TrileanSqlError {
|
|
31
|
+
readonly dialect: string;
|
|
32
|
+
readonly implemented: readonly string[];
|
|
33
|
+
constructor(dialect: string, implemented: readonly string[]);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A `columnFor` result whose `column` cannot be rendered as a SQL identifier.
|
|
25
37
|
*
|
|
26
38
|
* 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
39
|
*/
|
|
@@ -31,4 +43,4 @@ declare class InvalidColumnError extends TrileanSqlError {
|
|
|
31
43
|
constructor(referenceKey: string, column: string, reason: string);
|
|
32
44
|
}
|
|
33
45
|
//#endregion
|
|
34
|
-
export { InvalidColumnError, TrileanSqlError, UnsupportedNodeError };
|
|
46
|
+
export { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError };
|
package/dist/errors.js
CHANGED
|
@@ -9,7 +9,7 @@ var TrileanSqlError = class extends Error {
|
|
|
9
9
|
/**
|
|
10
10
|
* 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.
|
|
11
11
|
*
|
|
12
|
-
* 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
|
|
12
|
+
* That guarantee is about the tree's *structure*, and it stops at two things whose meaning is a property of the operand's own content rather than of any node kind: a `matches`/`notMatches` pattern, which the server matches under its own regular-expression language rather than ECMAScript's, and an `instantLiteral` string the database reads differently from trilean or cannot read at all (which fails as a query error at execution time, not as this exception). Both are covered in README.md; neither is detectable by a walk over node kinds.
|
|
13
13
|
*
|
|
14
14
|
* `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).
|
|
15
15
|
*/
|
|
@@ -26,7 +26,24 @@ var UnsupportedNodeError = class extends TrileanSqlError {
|
|
|
26
26
|
}
|
|
27
27
|
};
|
|
28
28
|
/**
|
|
29
|
-
* A
|
|
29
|
+
* A dialect this version does not implement.
|
|
30
|
+
*
|
|
31
|
+
* `SqlDialect` is a closed union, so a caller who names a dialect in TypeScript source cannot reach this. A dialect read from configuration and asserted into the type at the boundary can, which is the case it exists for: without it the unimplemented name surfaces later as an internal `TypeError` from a table lookup that found nothing, naming neither the dialect nor the field it was reached from. Refusing by name at the entry point is the same convention `InvalidColumnError` applies to a `columnFor` result and the node walk applies to an unrecognised kind -- an input the type system describes but cannot enforce is checked once, where it arrives.
|
|
32
|
+
*
|
|
33
|
+
* `dialect` is the offending name and `implemented` lists the ones this version does compile.
|
|
34
|
+
*/
|
|
35
|
+
var UnknownDialectError = class extends TrileanSqlError {
|
|
36
|
+
dialect;
|
|
37
|
+
implemented;
|
|
38
|
+
constructor(dialect, implemented) {
|
|
39
|
+
super(`unknown dialect ${JSON.stringify(dialect)}: this version compiles ${implemented.map((name) => JSON.stringify(name)).join(", ")}`);
|
|
40
|
+
this.name = "UnknownDialectError";
|
|
41
|
+
this.dialect = dialect;
|
|
42
|
+
this.implemented = implemented;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* A `columnFor` result whose `column` cannot be rendered as a SQL identifier.
|
|
30
47
|
*
|
|
31
48
|
* 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.
|
|
32
49
|
*/
|
|
@@ -41,4 +58,4 @@ var InvalidColumnError = class extends TrileanSqlError {
|
|
|
41
58
|
}
|
|
42
59
|
};
|
|
43
60
|
//#endregion
|
|
44
|
-
export { InvalidColumnError, TrileanSqlError, UnsupportedNodeError };
|
|
61
|
+
export { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError };
|
package/dist/guard.cjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_options = require("./options.cjs");
|
|
2
3
|
//#region src/guard.ts
|
|
3
4
|
const STATIC_KIND_OF_PARAM_TYPE = {
|
|
4
5
|
text: "text",
|
|
@@ -6,7 +7,7 @@ const STATIC_KIND_OF_PARAM_TYPE = {
|
|
|
6
7
|
boolean: "boolean",
|
|
7
8
|
timestamp: "instant"
|
|
8
9
|
};
|
|
9
|
-
/** The comparison operators that impose an ordering, as opposed to testing equality. trilean refuses these on booleans -- `true > false` is not a fact about the domain -- while
|
|
10
|
+
/** The comparison operators that impose an ordering, as opposed to testing equality. trilean refuses these on booleans -- `true > false` is not a fact about the domain -- while both dialects answer them, so a boolean operand under one of these is a real divergence rather than a stylistic one. */
|
|
10
11
|
const ORDERING_OPERATORS = /* @__PURE__ */ new Set([
|
|
11
12
|
"gt",
|
|
12
13
|
"gte",
|
|
@@ -20,13 +21,29 @@ const STATIC_KIND_OF_LITERAL = {
|
|
|
20
21
|
booleanLiteral: "boolean",
|
|
21
22
|
instantLiteral: "instant"
|
|
22
23
|
};
|
|
24
|
+
const DIALECT_DIVERGENCE = {
|
|
25
|
+
postgres: {
|
|
26
|
+
complexNumbers: "PostgreSQL has no complex number type",
|
|
27
|
+
nan: "NaN is equal to nothing in trilean, not even itself, whereas PostgreSQL defines NaN as equal to itself and greater than every other double",
|
|
28
|
+
crossKindCoercion: "PostgreSQL may coerce one to the other and answer definitely",
|
|
29
|
+
textOrdering: (operandPath) => `PostgreSQL would order the text operand at ${operandPath} collation-wise and answer definitely`,
|
|
30
|
+
booleanOrdering: "PostgreSQL orders false before true"
|
|
31
|
+
},
|
|
32
|
+
sqlite: {
|
|
33
|
+
complexNumbers: "SQLite has no complex number type",
|
|
34
|
+
nan: "NaN is equal to nothing in trilean, not even itself, whereas SQLite has no NaN at all and a driver binding one substitutes SQL NULL -- so 'NaN = NaN' is indeterminate there rather than definitely false, and its negation matches every row instead of none",
|
|
35
|
+
crossKindCoercion: "SQLite's type affinity may coerce one to the other and answer definitely",
|
|
36
|
+
textOrdering: (operandPath) => `SQLite would answer definitely for the text operand at ${operandPath}, comparing it under the text affinity it applies to the other side ('9' > 5 is true there, while '10' > 5 is not)`,
|
|
37
|
+
booleanOrdering: "SQLite stores booleans as the integers 0 and 1 and orders them as integers"
|
|
38
|
+
}
|
|
39
|
+
};
|
|
23
40
|
function staticValueKindOf(node, options) {
|
|
24
41
|
if (node.kind !== "reference") return STATIC_KIND_OF_LITERAL[node.kind];
|
|
25
42
|
if (options === void 0 || typeof node.key !== "string") return void 0;
|
|
26
43
|
const paramType = options.columnFor(node.key).paramType;
|
|
27
44
|
return paramType === void 0 ? void 0 : STATIC_KIND_OF_PARAM_TYPE[paramType];
|
|
28
45
|
}
|
|
29
|
-
function findUnpushableExpression(node, path) {
|
|
46
|
+
function findUnpushableExpression(node, path, divergence) {
|
|
30
47
|
const unrecognisedKind = node.kind;
|
|
31
48
|
switch (node.kind) {
|
|
32
49
|
case "reference":
|
|
@@ -50,7 +67,7 @@ function findUnpushableExpression(node, path) {
|
|
|
50
67
|
if (Number.isNaN(node.value)) return {
|
|
51
68
|
kind: node.kind,
|
|
52
69
|
path,
|
|
53
|
-
reason:
|
|
70
|
+
reason: divergence.nan
|
|
54
71
|
};
|
|
55
72
|
return;
|
|
56
73
|
case "textLiteral":
|
|
@@ -64,7 +81,7 @@ function findUnpushableExpression(node, path) {
|
|
|
64
81
|
case "complexLiteral": return {
|
|
65
82
|
kind: node.kind,
|
|
66
83
|
path,
|
|
67
|
-
reason:
|
|
84
|
+
reason: divergence.complexNumbers
|
|
68
85
|
};
|
|
69
86
|
case "arithmetic":
|
|
70
87
|
case "negate": return {
|
|
@@ -114,8 +131,8 @@ function findUnpushableExpression(node, path) {
|
|
|
114
131
|
};
|
|
115
132
|
}
|
|
116
133
|
}
|
|
117
|
-
/** Checks the operands of a comparison-shaped predicate for a kind pairing trilean and
|
|
118
|
-
function findKindDivergence(kind, path, operands, options) {
|
|
134
|
+
/** Checks the operands of a comparison-shaped predicate for a kind pairing trilean and the target engine would answer differently. Returns the objection against `path` itself, since the divergence is a property of the pairing rather than of either operand alone. */
|
|
135
|
+
function findKindDivergence(kind, path, operands, options, divergence) {
|
|
119
136
|
const known = operands.map((operand) => ({
|
|
120
137
|
path: operand.path,
|
|
121
138
|
staticKind: staticValueKindOf(operand.node, options)
|
|
@@ -126,19 +143,19 @@ function findKindDivergence(kind, path, operands, options) {
|
|
|
126
143
|
if (mismatched !== void 0) return {
|
|
127
144
|
kind,
|
|
128
145
|
path,
|
|
129
|
-
reason: `trilean treats a comparison between a '${first.staticKind}' value (${first.path}) and a '${mismatched.staticKind}' value (${mismatched.path}) as wrong-type, whereas
|
|
146
|
+
reason: `trilean treats a comparison between a '${first.staticKind}' value (${first.path}) and a '${mismatched.staticKind}' value (${mismatched.path}) as wrong-type, whereas ${divergence.crossKindCoercion}`
|
|
130
147
|
};
|
|
131
148
|
}
|
|
132
|
-
function findUnpushablePredicate(node, path, options) {
|
|
149
|
+
function findUnpushablePredicate(node, path, options, divergence) {
|
|
133
150
|
const unrecognisedKind = node.kind;
|
|
134
151
|
switch (node.kind) {
|
|
135
|
-
case "not": return findUnpushablePredicate(node.operand, `${path}.operand`, options);
|
|
152
|
+
case "not": return findUnpushablePredicate(node.operand, `${path}.operand`, options, divergence);
|
|
136
153
|
case "and":
|
|
137
|
-
case "or": return findUnpushablePredicate(node.left, `${path}.left`, options) ?? findUnpushablePredicate(node.right, `${path}.right`, options);
|
|
154
|
+
case "or": return findUnpushablePredicate(node.left, `${path}.left`, options, divergence) ?? findUnpushablePredicate(node.right, `${path}.right`, options, divergence);
|
|
138
155
|
case "allOf":
|
|
139
156
|
case "anyOf":
|
|
140
157
|
for (const [index, operand] of node.operands.entries()) {
|
|
141
|
-
const unpushable = findUnpushablePredicate(operand, `${path}.operands[${String(index)}]`, options);
|
|
158
|
+
const unpushable = findUnpushablePredicate(operand, `${path}.operands[${String(index)}]`, options, divergence);
|
|
142
159
|
if (unpushable !== void 0) return unpushable;
|
|
143
160
|
}
|
|
144
161
|
return;
|
|
@@ -151,22 +168,22 @@ function findUnpushablePredicate(node, path, options) {
|
|
|
151
168
|
path: `${path}.right`
|
|
152
169
|
}];
|
|
153
170
|
for (const operand of operands) {
|
|
154
|
-
const unpushable = findUnpushableExpression(operand.node, operand.path);
|
|
171
|
+
const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
|
|
155
172
|
if (unpushable !== void 0) return unpushable;
|
|
156
173
|
}
|
|
157
|
-
const
|
|
158
|
-
if (
|
|
174
|
+
const mismatch = findKindDivergence(node.kind, path, operands, options, divergence);
|
|
175
|
+
if (mismatch !== void 0) return mismatch;
|
|
159
176
|
for (const operand of operands) {
|
|
160
177
|
const staticKind = staticValueKindOf(operand.node, options);
|
|
161
178
|
if (staticKind === "text") return {
|
|
162
179
|
kind: node.kind,
|
|
163
180
|
path,
|
|
164
|
-
reason: `'compare' never compares text in trilean -- it returns wrong-type and directs the caller to 'textCompare' -- but
|
|
181
|
+
reason: `'compare' never compares text in trilean -- it returns wrong-type and directs the caller to 'textCompare' -- but ${divergence.textOrdering(operand.path)}`
|
|
165
182
|
};
|
|
166
183
|
if (staticKind === "boolean" && ORDERING_OPERATORS.has(node.op)) return {
|
|
167
184
|
kind: node.kind,
|
|
168
185
|
path,
|
|
169
|
-
reason: `booleans have no ordering in trilean, so '${node.op}' against the boolean operand at ${operand.path} is wrong-type there, whereas
|
|
186
|
+
reason: `booleans have no ordering in trilean, so '${node.op}' against the boolean operand at ${operand.path} is wrong-type there, whereas ${divergence.booleanOrdering}`
|
|
170
187
|
};
|
|
171
188
|
}
|
|
172
189
|
return;
|
|
@@ -180,7 +197,7 @@ function findUnpushablePredicate(node, path, options) {
|
|
|
180
197
|
path: `${path}.right`
|
|
181
198
|
}];
|
|
182
199
|
for (const operand of operands) {
|
|
183
|
-
const unpushable = findUnpushableExpression(operand.node, operand.path);
|
|
200
|
+
const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
|
|
184
201
|
if (unpushable !== void 0) return unpushable;
|
|
185
202
|
const staticKind = staticValueKindOf(operand.node, options);
|
|
186
203
|
if (staticKind !== void 0 && staticKind !== "text") return {
|
|
@@ -200,12 +217,12 @@ function findUnpushablePredicate(node, path, options) {
|
|
|
200
217
|
path: `${path}.candidates[${String(index)}]`
|
|
201
218
|
}))];
|
|
202
219
|
for (const operand of operands) {
|
|
203
|
-
const unpushable = findUnpushableExpression(operand.node, operand.path);
|
|
220
|
+
const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
|
|
204
221
|
if (unpushable !== void 0) return unpushable;
|
|
205
222
|
}
|
|
206
|
-
return findKindDivergence(node.kind, path, operands, options);
|
|
223
|
+
return findKindDivergence(node.kind, path, operands, options, divergence);
|
|
207
224
|
}
|
|
208
|
-
case "exists": return findUnpushableExpression(node.operand, `${path}.operand
|
|
225
|
+
case "exists": return findUnpushableExpression(node.operand, `${path}.operand`, divergence);
|
|
209
226
|
case "some":
|
|
210
227
|
case "every": return {
|
|
211
228
|
kind: node.kind,
|
|
@@ -232,9 +249,15 @@ function findUnpushablePredicate(node, path, options) {
|
|
|
232
249
|
* `compilePredicateNode` runs this first and throws `UnsupportedNodeError` on any result, so calling it separately is only necessary to *decide* between pushdown and in-process evaluation without provoking an exception.
|
|
233
250
|
*
|
|
234
251
|
* 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`).
|
|
252
|
+
*
|
|
253
|
+
* 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.
|
|
254
|
+
*
|
|
255
|
+
* @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.
|
|
235
256
|
*/
|
|
236
257
|
function findUnpushableNodeKind(node, options) {
|
|
237
|
-
|
|
258
|
+
const dialect = options?.dialect ?? "postgres";
|
|
259
|
+
require_options.assertImplementedDialect(dialect);
|
|
260
|
+
return findUnpushablePredicate(node, "$", options, DIALECT_DIVERGENCE[dialect]);
|
|
238
261
|
}
|
|
239
262
|
//#endregion
|
|
240
263
|
exports.findUnpushableNodeKind = findUnpushableNodeKind;
|
package/dist/guard.d.cts
CHANGED
|
@@ -16,6 +16,10 @@ interface UnpushableNode {
|
|
|
16
16
|
* `compilePredicateNode` runs this first and throws `UnsupportedNodeError` on any result, so calling it separately is only necessary to *decide* between pushdown and in-process evaluation without provoking an exception.
|
|
17
17
|
*
|
|
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
|
+
*
|
|
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.
|
|
19
23
|
*/
|
|
20
24
|
declare function findUnpushableNodeKind(node: PredicateNode, options?: SqlCompileOptions): UnpushableNode | undefined;
|
|
21
25
|
//#endregion
|
package/dist/guard.d.ts
CHANGED
|
@@ -16,6 +16,10 @@ interface UnpushableNode {
|
|
|
16
16
|
* `compilePredicateNode` runs this first and throws `UnsupportedNodeError` on any result, so calling it separately is only necessary to *decide* between pushdown and in-process evaluation without provoking an exception.
|
|
17
17
|
*
|
|
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
|
+
*
|
|
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.
|
|
19
23
|
*/
|
|
20
24
|
declare function findUnpushableNodeKind(node: PredicateNode, options?: SqlCompileOptions): UnpushableNode | undefined;
|
|
21
25
|
//#endregion
|
package/dist/guard.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assertImplementedDialect } from "./options.js";
|
|
1
2
|
//#region src/guard.ts
|
|
2
3
|
const STATIC_KIND_OF_PARAM_TYPE = {
|
|
3
4
|
text: "text",
|
|
@@ -5,7 +6,7 @@ const STATIC_KIND_OF_PARAM_TYPE = {
|
|
|
5
6
|
boolean: "boolean",
|
|
6
7
|
timestamp: "instant"
|
|
7
8
|
};
|
|
8
|
-
/** The comparison operators that impose an ordering, as opposed to testing equality. trilean refuses these on booleans -- `true > false` is not a fact about the domain -- while
|
|
9
|
+
/** The comparison operators that impose an ordering, as opposed to testing equality. trilean refuses these on booleans -- `true > false` is not a fact about the domain -- while both dialects answer them, so a boolean operand under one of these is a real divergence rather than a stylistic one. */
|
|
9
10
|
const ORDERING_OPERATORS = /* @__PURE__ */ new Set([
|
|
10
11
|
"gt",
|
|
11
12
|
"gte",
|
|
@@ -19,13 +20,29 @@ const STATIC_KIND_OF_LITERAL = {
|
|
|
19
20
|
booleanLiteral: "boolean",
|
|
20
21
|
instantLiteral: "instant"
|
|
21
22
|
};
|
|
23
|
+
const DIALECT_DIVERGENCE = {
|
|
24
|
+
postgres: {
|
|
25
|
+
complexNumbers: "PostgreSQL has no complex number type",
|
|
26
|
+
nan: "NaN is equal to nothing in trilean, not even itself, whereas PostgreSQL defines NaN as equal to itself and greater than every other double",
|
|
27
|
+
crossKindCoercion: "PostgreSQL may coerce one to the other and answer definitely",
|
|
28
|
+
textOrdering: (operandPath) => `PostgreSQL would order the text operand at ${operandPath} collation-wise and answer definitely`,
|
|
29
|
+
booleanOrdering: "PostgreSQL orders false before true"
|
|
30
|
+
},
|
|
31
|
+
sqlite: {
|
|
32
|
+
complexNumbers: "SQLite has no complex number type",
|
|
33
|
+
nan: "NaN is equal to nothing in trilean, not even itself, whereas SQLite has no NaN at all and a driver binding one substitutes SQL NULL -- so 'NaN = NaN' is indeterminate there rather than definitely false, and its negation matches every row instead of none",
|
|
34
|
+
crossKindCoercion: "SQLite's type affinity may coerce one to the other and answer definitely",
|
|
35
|
+
textOrdering: (operandPath) => `SQLite would answer definitely for the text operand at ${operandPath}, comparing it under the text affinity it applies to the other side ('9' > 5 is true there, while '10' > 5 is not)`,
|
|
36
|
+
booleanOrdering: "SQLite stores booleans as the integers 0 and 1 and orders them as integers"
|
|
37
|
+
}
|
|
38
|
+
};
|
|
22
39
|
function staticValueKindOf(node, options) {
|
|
23
40
|
if (node.kind !== "reference") return STATIC_KIND_OF_LITERAL[node.kind];
|
|
24
41
|
if (options === void 0 || typeof node.key !== "string") return void 0;
|
|
25
42
|
const paramType = options.columnFor(node.key).paramType;
|
|
26
43
|
return paramType === void 0 ? void 0 : STATIC_KIND_OF_PARAM_TYPE[paramType];
|
|
27
44
|
}
|
|
28
|
-
function findUnpushableExpression(node, path) {
|
|
45
|
+
function findUnpushableExpression(node, path, divergence) {
|
|
29
46
|
const unrecognisedKind = node.kind;
|
|
30
47
|
switch (node.kind) {
|
|
31
48
|
case "reference":
|
|
@@ -49,7 +66,7 @@ function findUnpushableExpression(node, path) {
|
|
|
49
66
|
if (Number.isNaN(node.value)) return {
|
|
50
67
|
kind: node.kind,
|
|
51
68
|
path,
|
|
52
|
-
reason:
|
|
69
|
+
reason: divergence.nan
|
|
53
70
|
};
|
|
54
71
|
return;
|
|
55
72
|
case "textLiteral":
|
|
@@ -63,7 +80,7 @@ function findUnpushableExpression(node, path) {
|
|
|
63
80
|
case "complexLiteral": return {
|
|
64
81
|
kind: node.kind,
|
|
65
82
|
path,
|
|
66
|
-
reason:
|
|
83
|
+
reason: divergence.complexNumbers
|
|
67
84
|
};
|
|
68
85
|
case "arithmetic":
|
|
69
86
|
case "negate": return {
|
|
@@ -113,8 +130,8 @@ function findUnpushableExpression(node, path) {
|
|
|
113
130
|
};
|
|
114
131
|
}
|
|
115
132
|
}
|
|
116
|
-
/** Checks the operands of a comparison-shaped predicate for a kind pairing trilean and
|
|
117
|
-
function findKindDivergence(kind, path, operands, options) {
|
|
133
|
+
/** Checks the operands of a comparison-shaped predicate for a kind pairing trilean and the target engine would answer differently. Returns the objection against `path` itself, since the divergence is a property of the pairing rather than of either operand alone. */
|
|
134
|
+
function findKindDivergence(kind, path, operands, options, divergence) {
|
|
118
135
|
const known = operands.map((operand) => ({
|
|
119
136
|
path: operand.path,
|
|
120
137
|
staticKind: staticValueKindOf(operand.node, options)
|
|
@@ -125,19 +142,19 @@ function findKindDivergence(kind, path, operands, options) {
|
|
|
125
142
|
if (mismatched !== void 0) return {
|
|
126
143
|
kind,
|
|
127
144
|
path,
|
|
128
|
-
reason: `trilean treats a comparison between a '${first.staticKind}' value (${first.path}) and a '${mismatched.staticKind}' value (${mismatched.path}) as wrong-type, whereas
|
|
145
|
+
reason: `trilean treats a comparison between a '${first.staticKind}' value (${first.path}) and a '${mismatched.staticKind}' value (${mismatched.path}) as wrong-type, whereas ${divergence.crossKindCoercion}`
|
|
129
146
|
};
|
|
130
147
|
}
|
|
131
|
-
function findUnpushablePredicate(node, path, options) {
|
|
148
|
+
function findUnpushablePredicate(node, path, options, divergence) {
|
|
132
149
|
const unrecognisedKind = node.kind;
|
|
133
150
|
switch (node.kind) {
|
|
134
|
-
case "not": return findUnpushablePredicate(node.operand, `${path}.operand`, options);
|
|
151
|
+
case "not": return findUnpushablePredicate(node.operand, `${path}.operand`, options, divergence);
|
|
135
152
|
case "and":
|
|
136
|
-
case "or": return findUnpushablePredicate(node.left, `${path}.left`, options) ?? findUnpushablePredicate(node.right, `${path}.right`, options);
|
|
153
|
+
case "or": return findUnpushablePredicate(node.left, `${path}.left`, options, divergence) ?? findUnpushablePredicate(node.right, `${path}.right`, options, divergence);
|
|
137
154
|
case "allOf":
|
|
138
155
|
case "anyOf":
|
|
139
156
|
for (const [index, operand] of node.operands.entries()) {
|
|
140
|
-
const unpushable = findUnpushablePredicate(operand, `${path}.operands[${String(index)}]`, options);
|
|
157
|
+
const unpushable = findUnpushablePredicate(operand, `${path}.operands[${String(index)}]`, options, divergence);
|
|
141
158
|
if (unpushable !== void 0) return unpushable;
|
|
142
159
|
}
|
|
143
160
|
return;
|
|
@@ -150,22 +167,22 @@ function findUnpushablePredicate(node, path, options) {
|
|
|
150
167
|
path: `${path}.right`
|
|
151
168
|
}];
|
|
152
169
|
for (const operand of operands) {
|
|
153
|
-
const unpushable = findUnpushableExpression(operand.node, operand.path);
|
|
170
|
+
const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
|
|
154
171
|
if (unpushable !== void 0) return unpushable;
|
|
155
172
|
}
|
|
156
|
-
const
|
|
157
|
-
if (
|
|
173
|
+
const mismatch = findKindDivergence(node.kind, path, operands, options, divergence);
|
|
174
|
+
if (mismatch !== void 0) return mismatch;
|
|
158
175
|
for (const operand of operands) {
|
|
159
176
|
const staticKind = staticValueKindOf(operand.node, options);
|
|
160
177
|
if (staticKind === "text") return {
|
|
161
178
|
kind: node.kind,
|
|
162
179
|
path,
|
|
163
|
-
reason: `'compare' never compares text in trilean -- it returns wrong-type and directs the caller to 'textCompare' -- but
|
|
180
|
+
reason: `'compare' never compares text in trilean -- it returns wrong-type and directs the caller to 'textCompare' -- but ${divergence.textOrdering(operand.path)}`
|
|
164
181
|
};
|
|
165
182
|
if (staticKind === "boolean" && ORDERING_OPERATORS.has(node.op)) return {
|
|
166
183
|
kind: node.kind,
|
|
167
184
|
path,
|
|
168
|
-
reason: `booleans have no ordering in trilean, so '${node.op}' against the boolean operand at ${operand.path} is wrong-type there, whereas
|
|
185
|
+
reason: `booleans have no ordering in trilean, so '${node.op}' against the boolean operand at ${operand.path} is wrong-type there, whereas ${divergence.booleanOrdering}`
|
|
169
186
|
};
|
|
170
187
|
}
|
|
171
188
|
return;
|
|
@@ -179,7 +196,7 @@ function findUnpushablePredicate(node, path, options) {
|
|
|
179
196
|
path: `${path}.right`
|
|
180
197
|
}];
|
|
181
198
|
for (const operand of operands) {
|
|
182
|
-
const unpushable = findUnpushableExpression(operand.node, operand.path);
|
|
199
|
+
const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
|
|
183
200
|
if (unpushable !== void 0) return unpushable;
|
|
184
201
|
const staticKind = staticValueKindOf(operand.node, options);
|
|
185
202
|
if (staticKind !== void 0 && staticKind !== "text") return {
|
|
@@ -199,12 +216,12 @@ function findUnpushablePredicate(node, path, options) {
|
|
|
199
216
|
path: `${path}.candidates[${String(index)}]`
|
|
200
217
|
}))];
|
|
201
218
|
for (const operand of operands) {
|
|
202
|
-
const unpushable = findUnpushableExpression(operand.node, operand.path);
|
|
219
|
+
const unpushable = findUnpushableExpression(operand.node, operand.path, divergence);
|
|
203
220
|
if (unpushable !== void 0) return unpushable;
|
|
204
221
|
}
|
|
205
|
-
return findKindDivergence(node.kind, path, operands, options);
|
|
222
|
+
return findKindDivergence(node.kind, path, operands, options, divergence);
|
|
206
223
|
}
|
|
207
|
-
case "exists": return findUnpushableExpression(node.operand, `${path}.operand
|
|
224
|
+
case "exists": return findUnpushableExpression(node.operand, `${path}.operand`, divergence);
|
|
208
225
|
case "some":
|
|
209
226
|
case "every": return {
|
|
210
227
|
kind: node.kind,
|
|
@@ -231,9 +248,15 @@ function findUnpushablePredicate(node, path, options) {
|
|
|
231
248
|
* `compilePredicateNode` runs this first and throws `UnsupportedNodeError` on any result, so calling it separately is only necessary to *decide* between pushdown and in-process evaluation without provoking an exception.
|
|
232
249
|
*
|
|
233
250
|
* 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`).
|
|
251
|
+
*
|
|
252
|
+
* 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.
|
|
253
|
+
*
|
|
254
|
+
* @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.
|
|
234
255
|
*/
|
|
235
256
|
function findUnpushableNodeKind(node, options) {
|
|
236
|
-
|
|
257
|
+
const dialect = options?.dialect ?? "postgres";
|
|
258
|
+
assertImplementedDialect(dialect);
|
|
259
|
+
return findUnpushablePredicate(node, "$", options, DIALECT_DIVERGENCE[dialect]);
|
|
237
260
|
}
|
|
238
261
|
//#endregion
|
|
239
262
|
export { findUnpushableNodeKind };
|
package/dist/index.cjs
CHANGED
|
@@ -4,6 +4,7 @@ const require_guard = require("./guard.cjs");
|
|
|
4
4
|
const require_compile = require("./compile.cjs");
|
|
5
5
|
exports.InvalidColumnError = require_errors.InvalidColumnError;
|
|
6
6
|
exports.TrileanSqlError = require_errors.TrileanSqlError;
|
|
7
|
+
exports.UnknownDialectError = require_errors.UnknownDialectError;
|
|
7
8
|
exports.UnsupportedNodeError = require_errors.UnsupportedNodeError;
|
|
8
9
|
exports.compilePredicateNode = require_compile.compilePredicateNode;
|
|
9
10
|
exports.findUnpushableNodeKind = require_guard.findUnpushableNodeKind;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CompiledSql, SqlColumnBinding, SqlCompileOptions, SqlParamType } from "./options.cjs";
|
|
1
|
+
import { CompiledSql, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType } from "./options.cjs";
|
|
2
2
|
import { compilePredicateNode } from "./compile.cjs";
|
|
3
|
-
import { InvalidColumnError, TrileanSqlError, UnsupportedNodeError } from "./errors.cjs";
|
|
3
|
+
import { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError } from "./errors.cjs";
|
|
4
4
|
import { UnpushableNode, findUnpushableNodeKind } from "./guard.cjs";
|
|
5
|
-
export { type CompiledSql, InvalidColumnError, type SqlColumnBinding, type SqlCompileOptions, type SqlParamType, TrileanSqlError, type UnpushableNode, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
|
|
5
|
+
export { type CompiledSql, InvalidColumnError, type SqlColumnBinding, type SqlCompileOptions, type SqlDialect, type SqlParamType, TrileanSqlError, UnknownDialectError, type UnpushableNode, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CompiledSql, SqlColumnBinding, SqlCompileOptions, SqlParamType } from "./options.js";
|
|
1
|
+
import { CompiledSql, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType } from "./options.js";
|
|
2
2
|
import { compilePredicateNode } from "./compile.js";
|
|
3
|
-
import { InvalidColumnError, TrileanSqlError, UnsupportedNodeError } from "./errors.js";
|
|
3
|
+
import { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError } from "./errors.js";
|
|
4
4
|
import { UnpushableNode, findUnpushableNodeKind } from "./guard.js";
|
|
5
|
-
export { type CompiledSql, InvalidColumnError, type SqlColumnBinding, type SqlCompileOptions, type SqlParamType, TrileanSqlError, type UnpushableNode, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
|
|
5
|
+
export { type CompiledSql, InvalidColumnError, type SqlColumnBinding, type SqlCompileOptions, type SqlDialect, type SqlParamType, TrileanSqlError, UnknownDialectError, type UnpushableNode, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { InvalidColumnError, TrileanSqlError, UnsupportedNodeError } from "./errors.js";
|
|
1
|
+
import { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError } from "./errors.js";
|
|
2
2
|
import { findUnpushableNodeKind } from "./guard.js";
|
|
3
3
|
import { compilePredicateNode } from "./compile.js";
|
|
4
|
-
export { InvalidColumnError, TrileanSqlError, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
|
|
4
|
+
export { InvalidColumnError, TrileanSqlError, UnknownDialectError, UnsupportedNodeError, compilePredicateNode, findUnpushableNodeKind };
|
package/dist/options.cjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_errors = require("./errors.cjs");
|
|
2
3
|
//#region src/options.ts
|
|
3
4
|
/** The PostgreSQL type each declared value kind is cast to. `timestamptz` rather than `timestamp`: trilean's `instant` is an ISO-8601 string that may carry an offset, and parsing one as a naive `timestamp` would silently discard it. */
|
|
4
5
|
const POSTGRES_TYPE_NAME = {
|
|
@@ -7,5 +8,31 @@ const POSTGRES_TYPE_NAME = {
|
|
|
7
8
|
boolean: "boolean",
|
|
8
9
|
timestamp: "timestamptz"
|
|
9
10
|
};
|
|
11
|
+
const DIALECT_CONFIG = {
|
|
12
|
+
postgres: {
|
|
13
|
+
matches: "~",
|
|
14
|
+
notMatches: "!~",
|
|
15
|
+
placeholder: (index, castTo) => `$${String(index)}::${POSTGRES_TYPE_NAME[castTo]}`,
|
|
16
|
+
emptyMemberOfNullSuffix: "::boolean"
|
|
17
|
+
},
|
|
18
|
+
sqlite: {
|
|
19
|
+
matches: "REGEXP",
|
|
20
|
+
notMatches: "NOT REGEXP",
|
|
21
|
+
placeholder: () => "?",
|
|
22
|
+
emptyMemberOfNullSuffix: ""
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Refuses a dialect this version does not implement, before anything indexes a per-dialect table with it.
|
|
27
|
+
*
|
|
28
|
+
* Both entry points check their own argument, because both are reachable with a name the type describes but cannot enforce -- a dialect is exactly the sort of value that arrives as a configuration string asserted into the union at the boundary. Left unchecked, that name is not caught anywhere: the compiler reads an operator off `undefined` and throws a `TypeError` naming an internal field, and the guard, whose tables are only consulted for a node it actually objects to, answers "pushable" for a tree the compiler then fails on -- the one thing `findUnpushableNodeKind` exists to decide, decided wrongly.
|
|
29
|
+
*
|
|
30
|
+
* `DIALECT_CONFIG` is the list, rather than a second constant, so implementing a dialect cannot leave this behind.
|
|
31
|
+
*/
|
|
32
|
+
function assertImplementedDialect(dialect) {
|
|
33
|
+
if (!Object.hasOwn(DIALECT_CONFIG, dialect)) throw new require_errors.UnknownDialectError(dialect, Object.keys(DIALECT_CONFIG));
|
|
34
|
+
}
|
|
10
35
|
//#endregion
|
|
36
|
+
exports.DIALECT_CONFIG = DIALECT_CONFIG;
|
|
11
37
|
exports.POSTGRES_TYPE_NAME = POSTGRES_TYPE_NAME;
|
|
38
|
+
exports.assertImplementedDialect = assertImplementedDialect;
|
package/dist/options.d.cts
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
//#region src/options.d.ts
|
|
2
2
|
/** The declared SQL value kind of a mapped column. `"timestamp"` names trilean's `instant` kind, whose values are ISO-8601 strings. */
|
|
3
3
|
type SqlParamType = "text" | "number" | "boolean" | "timestamp";
|
|
4
|
+
/** The SQL dialects this compiler emits. A dialect is named rather than inferred: the same tree compiles to different text for each, and a caller that never said which one it meant would be relying on whichever happened to be the default. */
|
|
5
|
+
type SqlDialect = "postgres" | "sqlite";
|
|
4
6
|
/** What a `reference` node's key maps onto in the target schema. */
|
|
5
7
|
interface SqlColumnBinding {
|
|
6
8
|
/** The column, optionally qualified with a table or schema by dots (`"orders.total"`). Each dot-separated segment is emitted as its own double-quoted identifier, so a segment may contain any character except a dot itself. */
|
|
7
9
|
column: string;
|
|
8
10
|
/**
|
|
9
|
-
* The column's value kind, if the caller knows it. Optional, and worth supplying: it is the only thing that lets the compiler check a comparison against the column for the kind mismatches trilean itself treats as `wrong-type` -- comparing a text column with `compare` rather than `textCompare`, ordering a boolean, comparing a number against an instant. Left undeclared, those comparisons compile, and
|
|
11
|
+
* The column's value kind, if the caller knows it. Optional, and worth supplying: it is the only thing that lets the compiler check a comparison against the column for the kind mismatches trilean itself treats as `wrong-type` -- comparing a text column with `compare` rather than `textCompare`, ordering a boolean, comparing a number against an instant. Left undeclared, those comparisons compile, and the database may coerce its way to a definite answer where trilean would have returned indeterminate.
|
|
10
12
|
*
|
|
11
|
-
* It does not affect the emitted SQL, only whether the comparison is emitted at all. Every literal placeholder is already cast to the type its own trilean kind implies, and a comparison that survives the check is one whose operand kinds agree, so there is nothing left for the column's declared kind to change.
|
|
13
|
+
* It does not affect the emitted SQL, only whether the comparison is emitted at all. Every literal placeholder is already cast to the type its own trilean kind implies (in the dialects that cast at all), and a comparison that survives the check is one whose operand kinds agree, so there is nothing left for the column's declared kind to change.
|
|
12
14
|
*/
|
|
13
15
|
paramType?: SqlParamType;
|
|
14
16
|
}
|
|
15
17
|
interface SqlCompileOptions {
|
|
16
|
-
/**
|
|
17
|
-
dialect:
|
|
18
|
+
/** 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
|
+
dialect: SqlDialect;
|
|
18
20
|
/**
|
|
19
21
|
* Maps a `reference` node's key onto a column. Called once per reference occurrence.
|
|
20
22
|
*
|
|
@@ -25,10 +27,34 @@ interface SqlCompileOptions {
|
|
|
25
27
|
interface CompiledSql {
|
|
26
28
|
/** A self-contained boolean expression, always parenthesised, suitable for dropping straight into a `WHERE` clause (or a `CHECK`, a `HAVING`, or a filtered index predicate). It carries no `WHERE` keyword of its own. */
|
|
27
29
|
sql: string;
|
|
28
|
-
/** Positional parameters, in
|
|
30
|
+
/** Positional parameters, in emission order, to pass alongside `sql`. Every caller-supplied literal in the tree is here; none is ever written into `sql`. */
|
|
29
31
|
params: unknown[];
|
|
30
32
|
}
|
|
31
33
|
/** The PostgreSQL type each declared value kind is cast to. `timestamptz` rather than `timestamp`: trilean's `instant` is an ISO-8601 string that may carry an offset, and parsing one as a naive `timestamp` would silently discard it. */
|
|
32
34
|
declare const POSTGRES_TYPE_NAME: Readonly<Record<SqlParamType, string>>;
|
|
35
|
+
/**
|
|
36
|
+
* Everything about the emitted SQL that is a property of the dialect rather than of the tree.
|
|
37
|
+
*
|
|
38
|
+
* It is deliberately this small. Most of what the compiler emits is ANSI-standard and identical in both engines -- the six comparison operators, `=` and `<>` for `textCompare`'s `equals`/`notEquals`, `AND`/`OR`/`NOT`, `IN`/`NOT IN`, `IS NOT NULL`, and double-quoted identifiers with an embedded quote doubled -- so branching on the dialect anywhere else would be a branch that can never change the output. Three things genuinely differ, and they are the three fields below.
|
|
39
|
+
*/
|
|
40
|
+
interface DialectConfig {
|
|
41
|
+
/** The regular-expression match operator `textCompare`'s `matches` compiles to. */
|
|
42
|
+
matches: string;
|
|
43
|
+
/** The negated regular-expression match operator `textCompare`'s `notMatches` compiles to. */
|
|
44
|
+
notMatches: string;
|
|
45
|
+
/** Renders the `index`-th (1-based) bind placeholder, for a literal whose own trilean kind implies `castTo`. A dialect that does not need the cast ignores both arguments. */
|
|
46
|
+
placeholder: (index: number, castTo: SqlParamType) => string;
|
|
47
|
+
/** Appended to the bare `NULL` in the two forms an empty `memberOf` candidate list compiles to, for a dialect that needs the resulting expression annotated with a boolean type. */
|
|
48
|
+
emptyMemberOfNullSuffix: string;
|
|
49
|
+
}
|
|
50
|
+
declare const DIALECT_CONFIG: Readonly<Record<SqlDialect, DialectConfig>>;
|
|
51
|
+
/**
|
|
52
|
+
* Refuses a dialect this version does not implement, before anything indexes a per-dialect table with it.
|
|
53
|
+
*
|
|
54
|
+
* Both entry points check their own argument, because both are reachable with a name the type describes but cannot enforce -- a dialect is exactly the sort of value that arrives as a configuration string asserted into the union at the boundary. Left unchecked, that name is not caught anywhere: the compiler reads an operator off `undefined` and throws a `TypeError` naming an internal field, and the guard, whose tables are only consulted for a node it actually objects to, answers "pushable" for a tree the compiler then fails on -- the one thing `findUnpushableNodeKind` exists to decide, decided wrongly.
|
|
55
|
+
*
|
|
56
|
+
* `DIALECT_CONFIG` is the list, rather than a second constant, so implementing a dialect cannot leave this behind.
|
|
57
|
+
*/
|
|
58
|
+
declare function assertImplementedDialect(dialect: SqlDialect): void;
|
|
33
59
|
//#endregion
|
|
34
|
-
export { CompiledSql, POSTGRES_TYPE_NAME, SqlColumnBinding, SqlCompileOptions, SqlParamType };
|
|
60
|
+
export { CompiledSql, DIALECT_CONFIG, DialectConfig, POSTGRES_TYPE_NAME, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType, assertImplementedDialect };
|
package/dist/options.d.ts
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
//#region src/options.d.ts
|
|
2
2
|
/** The declared SQL value kind of a mapped column. `"timestamp"` names trilean's `instant` kind, whose values are ISO-8601 strings. */
|
|
3
3
|
type SqlParamType = "text" | "number" | "boolean" | "timestamp";
|
|
4
|
+
/** The SQL dialects this compiler emits. A dialect is named rather than inferred: the same tree compiles to different text for each, and a caller that never said which one it meant would be relying on whichever happened to be the default. */
|
|
5
|
+
type SqlDialect = "postgres" | "sqlite";
|
|
4
6
|
/** What a `reference` node's key maps onto in the target schema. */
|
|
5
7
|
interface SqlColumnBinding {
|
|
6
8
|
/** The column, optionally qualified with a table or schema by dots (`"orders.total"`). Each dot-separated segment is emitted as its own double-quoted identifier, so a segment may contain any character except a dot itself. */
|
|
7
9
|
column: string;
|
|
8
10
|
/**
|
|
9
|
-
* The column's value kind, if the caller knows it. Optional, and worth supplying: it is the only thing that lets the compiler check a comparison against the column for the kind mismatches trilean itself treats as `wrong-type` -- comparing a text column with `compare` rather than `textCompare`, ordering a boolean, comparing a number against an instant. Left undeclared, those comparisons compile, and
|
|
11
|
+
* The column's value kind, if the caller knows it. Optional, and worth supplying: it is the only thing that lets the compiler check a comparison against the column for the kind mismatches trilean itself treats as `wrong-type` -- comparing a text column with `compare` rather than `textCompare`, ordering a boolean, comparing a number against an instant. Left undeclared, those comparisons compile, and the database may coerce its way to a definite answer where trilean would have returned indeterminate.
|
|
10
12
|
*
|
|
11
|
-
* It does not affect the emitted SQL, only whether the comparison is emitted at all. Every literal placeholder is already cast to the type its own trilean kind implies, and a comparison that survives the check is one whose operand kinds agree, so there is nothing left for the column's declared kind to change.
|
|
13
|
+
* It does not affect the emitted SQL, only whether the comparison is emitted at all. Every literal placeholder is already cast to the type its own trilean kind implies (in the dialects that cast at all), and a comparison that survives the check is one whose operand kinds agree, so there is nothing left for the column's declared kind to change.
|
|
12
14
|
*/
|
|
13
15
|
paramType?: SqlParamType;
|
|
14
16
|
}
|
|
15
17
|
interface SqlCompileOptions {
|
|
16
|
-
/**
|
|
17
|
-
dialect:
|
|
18
|
+
/** 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
|
+
dialect: SqlDialect;
|
|
18
20
|
/**
|
|
19
21
|
* Maps a `reference` node's key onto a column. Called once per reference occurrence.
|
|
20
22
|
*
|
|
@@ -25,10 +27,34 @@ interface SqlCompileOptions {
|
|
|
25
27
|
interface CompiledSql {
|
|
26
28
|
/** A self-contained boolean expression, always parenthesised, suitable for dropping straight into a `WHERE` clause (or a `CHECK`, a `HAVING`, or a filtered index predicate). It carries no `WHERE` keyword of its own. */
|
|
27
29
|
sql: string;
|
|
28
|
-
/** Positional parameters, in
|
|
30
|
+
/** Positional parameters, in emission order, to pass alongside `sql`. Every caller-supplied literal in the tree is here; none is ever written into `sql`. */
|
|
29
31
|
params: unknown[];
|
|
30
32
|
}
|
|
31
33
|
/** The PostgreSQL type each declared value kind is cast to. `timestamptz` rather than `timestamp`: trilean's `instant` is an ISO-8601 string that may carry an offset, and parsing one as a naive `timestamp` would silently discard it. */
|
|
32
34
|
declare const POSTGRES_TYPE_NAME: Readonly<Record<SqlParamType, string>>;
|
|
35
|
+
/**
|
|
36
|
+
* Everything about the emitted SQL that is a property of the dialect rather than of the tree.
|
|
37
|
+
*
|
|
38
|
+
* It is deliberately this small. Most of what the compiler emits is ANSI-standard and identical in both engines -- the six comparison operators, `=` and `<>` for `textCompare`'s `equals`/`notEquals`, `AND`/`OR`/`NOT`, `IN`/`NOT IN`, `IS NOT NULL`, and double-quoted identifiers with an embedded quote doubled -- so branching on the dialect anywhere else would be a branch that can never change the output. Three things genuinely differ, and they are the three fields below.
|
|
39
|
+
*/
|
|
40
|
+
interface DialectConfig {
|
|
41
|
+
/** The regular-expression match operator `textCompare`'s `matches` compiles to. */
|
|
42
|
+
matches: string;
|
|
43
|
+
/** The negated regular-expression match operator `textCompare`'s `notMatches` compiles to. */
|
|
44
|
+
notMatches: string;
|
|
45
|
+
/** Renders the `index`-th (1-based) bind placeholder, for a literal whose own trilean kind implies `castTo`. A dialect that does not need the cast ignores both arguments. */
|
|
46
|
+
placeholder: (index: number, castTo: SqlParamType) => string;
|
|
47
|
+
/** Appended to the bare `NULL` in the two forms an empty `memberOf` candidate list compiles to, for a dialect that needs the resulting expression annotated with a boolean type. */
|
|
48
|
+
emptyMemberOfNullSuffix: string;
|
|
49
|
+
}
|
|
50
|
+
declare const DIALECT_CONFIG: Readonly<Record<SqlDialect, DialectConfig>>;
|
|
51
|
+
/**
|
|
52
|
+
* Refuses a dialect this version does not implement, before anything indexes a per-dialect table with it.
|
|
53
|
+
*
|
|
54
|
+
* Both entry points check their own argument, because both are reachable with a name the type describes but cannot enforce -- a dialect is exactly the sort of value that arrives as a configuration string asserted into the union at the boundary. Left unchecked, that name is not caught anywhere: the compiler reads an operator off `undefined` and throws a `TypeError` naming an internal field, and the guard, whose tables are only consulted for a node it actually objects to, answers "pushable" for a tree the compiler then fails on -- the one thing `findUnpushableNodeKind` exists to decide, decided wrongly.
|
|
55
|
+
*
|
|
56
|
+
* `DIALECT_CONFIG` is the list, rather than a second constant, so implementing a dialect cannot leave this behind.
|
|
57
|
+
*/
|
|
58
|
+
declare function assertImplementedDialect(dialect: SqlDialect): void;
|
|
33
59
|
//#endregion
|
|
34
|
-
export { CompiledSql, POSTGRES_TYPE_NAME, SqlColumnBinding, SqlCompileOptions, SqlParamType };
|
|
60
|
+
export { CompiledSql, DIALECT_CONFIG, DialectConfig, POSTGRES_TYPE_NAME, SqlColumnBinding, SqlCompileOptions, SqlDialect, SqlParamType, assertImplementedDialect };
|
package/dist/options.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { UnknownDialectError } from "./errors.js";
|
|
1
2
|
//#region src/options.ts
|
|
2
3
|
/** The PostgreSQL type each declared value kind is cast to. `timestamptz` rather than `timestamp`: trilean's `instant` is an ISO-8601 string that may carry an offset, and parsing one as a naive `timestamp` would silently discard it. */
|
|
3
4
|
const POSTGRES_TYPE_NAME = {
|
|
@@ -6,5 +7,29 @@ const POSTGRES_TYPE_NAME = {
|
|
|
6
7
|
boolean: "boolean",
|
|
7
8
|
timestamp: "timestamptz"
|
|
8
9
|
};
|
|
10
|
+
const DIALECT_CONFIG = {
|
|
11
|
+
postgres: {
|
|
12
|
+
matches: "~",
|
|
13
|
+
notMatches: "!~",
|
|
14
|
+
placeholder: (index, castTo) => `$${String(index)}::${POSTGRES_TYPE_NAME[castTo]}`,
|
|
15
|
+
emptyMemberOfNullSuffix: "::boolean"
|
|
16
|
+
},
|
|
17
|
+
sqlite: {
|
|
18
|
+
matches: "REGEXP",
|
|
19
|
+
notMatches: "NOT REGEXP",
|
|
20
|
+
placeholder: () => "?",
|
|
21
|
+
emptyMemberOfNullSuffix: ""
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Refuses a dialect this version does not implement, before anything indexes a per-dialect table with it.
|
|
26
|
+
*
|
|
27
|
+
* Both entry points check their own argument, because both are reachable with a name the type describes but cannot enforce -- a dialect is exactly the sort of value that arrives as a configuration string asserted into the union at the boundary. Left unchecked, that name is not caught anywhere: the compiler reads an operator off `undefined` and throws a `TypeError` naming an internal field, and the guard, whose tables are only consulted for a node it actually objects to, answers "pushable" for a tree the compiler then fails on -- the one thing `findUnpushableNodeKind` exists to decide, decided wrongly.
|
|
28
|
+
*
|
|
29
|
+
* `DIALECT_CONFIG` is the list, rather than a second constant, so implementing a dialect cannot leave this behind.
|
|
30
|
+
*/
|
|
31
|
+
function assertImplementedDialect(dialect) {
|
|
32
|
+
if (!Object.hasOwn(DIALECT_CONFIG, dialect)) throw new UnknownDialectError(dialect, Object.keys(DIALECT_CONFIG));
|
|
33
|
+
}
|
|
9
34
|
//#endregion
|
|
10
|
-
export { POSTGRES_TYPE_NAME };
|
|
35
|
+
export { DIALECT_CONFIG, POSTGRES_TYPE_NAME, assertImplementedDialect };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trilean-sql",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.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": {
|
|
@@ -70,6 +70,7 @@
|
|
|
70
70
|
"keywords": [
|
|
71
71
|
"sql",
|
|
72
72
|
"postgres",
|
|
73
|
+
"sqlite",
|
|
73
74
|
"predicate",
|
|
74
75
|
"three-valued-logic",
|
|
75
76
|
"query-builder",
|
|
@@ -82,9 +83,11 @@
|
|
|
82
83
|
"@electric-sql/pglite": "^0.5.8",
|
|
83
84
|
"@exadev/eslint-config": "^2.10.2",
|
|
84
85
|
"@testcontainers/postgresql": "^12.1.0",
|
|
86
|
+
"@types/better-sqlite3": "^9.6.0",
|
|
85
87
|
"@types/node": "^26.4.0",
|
|
86
88
|
"@types/pg": "^8.15.6",
|
|
87
89
|
"@vitest/coverage-v8": "^4.1.11",
|
|
90
|
+
"better-sqlite3": "^12.11.1",
|
|
88
91
|
"eslint": "^10.9.1",
|
|
89
92
|
"eslint-config-prettier": "^10.1.8",
|
|
90
93
|
"eslint-plugin-prettier": "^5.5.6",
|