trilean-sql 1.2.0 → 2.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 +45 -3
- package/dist/compile.cjs +25 -2
- package/dist/compile.js +25 -2
- package/dist/guard.cjs +26 -0
- package/dist/guard.js +26 -0
- package/dist/options.cjs +4 -0
- package/dist/options.d.cts +13 -1
- package/dist/options.d.ts +13 -1
- package/dist/options.js +4 -0
- package/dist/portable-pattern.cjs +153 -0
- package/dist/portable-pattern.d.cts +22 -0
- package/dist/portable-pattern.d.ts +22 -0
- package/dist/portable-pattern.js +150 -0
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -45,6 +45,9 @@ const columns = {
|
|
|
45
45
|
|
|
46
46
|
const { sql, params } = compilePredicateNode(rule, {
|
|
47
47
|
dialect: "postgres",
|
|
48
|
+
// `matches` is refused by default -- see "Regular expressions" -- and opted into here because
|
|
49
|
+
// "@example[.]com$" uses nothing outside the syntax portable between ECMAScript and PostgreSQL.
|
|
50
|
+
postgresRegexpPushdown: true,
|
|
48
51
|
columnFor: (key) => {
|
|
49
52
|
const binding = columns[key as keyof typeof columns];
|
|
50
53
|
if (binding === undefined) throw new Error(`no column for ${key}`);
|
|
@@ -73,6 +76,8 @@ Returns `{ sql, params }`. Throws rather than approximating; see [Refusal](#refu
|
|
|
73
76
|
|
|
74
77
|
`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
78
|
|
|
79
|
+
`options.postgresRegexpPushdown`, `false` by default, governs whether `matches`/`notMatches` may compile to PostgreSQL's own `~`/`!~` at all. See [Regular expressions](#regular-expressions) for why the default refuses them.
|
|
80
|
+
|
|
76
81
|
### `findUnpushableNodeKind(node, options?)`
|
|
77
82
|
|
|
78
83
|
Returns `{ kind, path, reason }` for the first node the compiler will not translate, or `undefined` if the whole tree is pushable. `compilePredicateNode` runs it first and throws on any result, so call it yourself only to *choose* between pushdown and in-process evaluation without provoking an exception:
|
|
@@ -97,7 +102,7 @@ Passing `options` widens the check: without them the walk is purely structural;
|
|
|
97
102
|
| `and`, `or`, `not` | `AND`, `OR`, `NOT` | same |
|
|
98
103
|
| `allOf`, `anyOf` | n-ary `AND`, `OR`; empty operands become each connective's identity, `TRUE` and `FALSE`, matching the evaluator's own fold | same |
|
|
99
104
|
| `compare` | `>`, `>=`, `<`, `<=`, `=`, `<>` | same |
|
|
100
|
-
| `textCompare` | `=`,
|
|
105
|
+
| `textCompare` | `=`, `<>`; `matches`/`notMatches` only once `postgresRegexpPushdown` opts in, otherwise refused (see [Regular expressions](#regular-expressions)); `~`/`!~` against a translated pattern for `portableMatches`/`portableNotMatches`, no opt-in needed | `=`, `<>`; `REGEXP`/`NOT REGEXP` for `matches`/`notMatches`; `GLOB`/`NOT GLOB` against a translated pattern for `portableMatches`/`portableNotMatches` |
|
|
101
106
|
| `memberOf` | `IN` / `NOT IN`, one parameter per candidate | same |
|
|
102
107
|
| `exists` | `IS NOT NULL` | same |
|
|
103
108
|
| `reference` | the mapped column, as a quoted identifier | same |
|
|
@@ -136,7 +141,9 @@ The compiler never degrades. There is no best-effort fragment, no silently dropp
|
|
|
136
141
|
|
|
137
142
|
The check is an allow-list walk rather than a deny-list, so a node kind added to trilean after this version was written is refused by default instead of falling through to whatever branch happened to be last.
|
|
138
143
|
|
|
139
|
-
That guarantee is about the tree's structure, and it has
|
|
144
|
+
That guarantee is about the tree's structure, and it has one remaining limit that is about the *content* of a string operand rather than any node's kind, and is not reachable by a walk over kinds: 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.
|
|
145
|
+
|
|
146
|
+
A `matches`/`notMatches` pattern would be the same kind of limit — matched by the server in PostgreSQL's own regular-expression language, not ECMAScript's — which is why it is refused rather than pushed down by default; see [Regular expressions](#regular-expressions). Setting `postgresRegexpPushdown: true` opts back into that limit deliberately, for patterns already known to be portable.
|
|
140
147
|
|
|
141
148
|
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
149
|
|
|
@@ -155,7 +162,16 @@ Left undeclared, these compile, and the divergence is real but invisible. That i
|
|
|
155
162
|
|
|
156
163
|
## Regular expressions
|
|
157
164
|
|
|
158
|
-
Under PostgreSQL, `matches` and `notMatches` compile to `~` and `!~`, so the pattern is matched by the server
|
|
165
|
+
Under PostgreSQL, `matches` and `notMatches` *can* compile to `~` and `!~`, so the pattern is matched by the server rather than in process — but only once `postgresRegexpPushdown: true` is passed in `SqlCompileOptions`. Left at its default (`false`, or simply omitted), both are refused by `findUnpushableNodeKind`/`compilePredicateNode` and the caller evaluates them in process instead, exactly like any other unpushable node.
|
|
166
|
+
|
|
167
|
+
This is the one node kind refused by default for a reason that is not structural: trilean's evaluator matches a pattern as an ECMAScript `RegExp`, and PostgreSQL's `~`/`!~` match under PostgreSQL's own regular-expression dialect (POSIX Advanced Regular Expressions, "ARE"). The two are close — literals, character classes, basic quantifiers, alternation, non-greedy quantifiers, numbered backreferences, and even lookahead/lookbehind are portable — but they are separate implementations, and measuring them directly (PostgreSQL's own docs against MDN's `RegExp` reference, each point checked against a real PostgreSQL engine via PGlite rather than trusted from documentation alone) turns up real divergence in both directions:
|
|
168
|
+
|
|
169
|
+
- **Silent divergence — the compiled fragment executes cleanly under both engines and still answers a different row set for the same pattern and data, with no error anywhere to catch it.** `.` matches a newline under PostgreSQL's default (newline-insensitive) mode; ECMAScript's `.` does not unless the pattern carries the `s` flag, which trilean's evaluator never sets (`new RegExp(pattern)`, no flags) — so `a.b` matches `"a\nb"` under PostgreSQL and not under trilean. `\w`/`\d`/`\s` (and their negations) are locale-dependent under PostgreSQL — in a UTF8 database, `\w` matches an accented letter like `é` — while ECMAScript's are ASCII-only by default (no `u` flag) — so `^\w+$` matches `"café"` under PostgreSQL and not under trilean. Neither is a syntax difference a validator could reject; the identical pattern text is valid and meaningful in both languages, just with different meaning.
|
|
170
|
+
- **Loud divergence — the pattern compiles clean here and fails only when PostgreSQL executes the query.** Named capture groups (`(?<name>...)`) and named backreferences (`\k<name>`) are ECMAScript syntax with no ARE equivalent (`invalid regular expression: quantifier operand invalid` from PostgreSQL, since ARE reads `(?<` as the start of a lookbehind and then finds no valid lookbehind body). Unicode property escapes (`\p{...}`/`\P{...}`) are likewise ECMAScript-only (`invalid regular expression: invalid escape \ sequence`). Character class subtraction (`[a-z-[aeiou]]`, from other regex dialects, not valid ECMAScript either but sometimes reached for) also fails under ARE.
|
|
171
|
+
|
|
172
|
+
Given the silent class exists at all, a validated "portable subset" of pattern syntax cannot close this gap on its own: the offending constructs here are not unusual syntax to ban, they are two of the most ordinary regex idioms there are (`.` and `\w`), and the difference is in what the database's locale and newline-handling settings mean, not in what characters appear in the pattern text. That is why this compiles to in-process evaluation by default rather than to a syntax-restricted pushdown — and why opting in with `postgresRegexpPushdown: true` is a deliberate, whole-compilation decision rather than a per-pattern one: it is only safe once every pattern reaching this option is known, by the caller, to avoid both the syntax PostgreSQL cannot parse at all and the constructs (`.` against data that may contain newlines, `\w`/`\d`/`\s` against data that may contain non-ASCII text) whose meaning quietly differs.
|
|
173
|
+
|
|
174
|
+
Sources: PostgreSQL's own [pattern-matching documentation](https://www.postgresql.org/docs/current/functions-matching.html) (POSIX ARE support, its embedded-option flags, and its own comparison against XQuery's regular expressions); MDN's [regular expressions reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions) for ECMAScript's semantics; the divergence points above were each executed against a real PostgreSQL engine (`@electric-sql/pglite`) and Node's own `RegExp`, not inferred from documentation alone.
|
|
159
175
|
|
|
160
176
|
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
177
|
|
|
@@ -175,6 +191,32 @@ Both details are load-bearing rather than stylistic. Returning `null` for a NULL
|
|
|
175
191
|
|
|
176
192
|
Some SQLite-wire-compatible targets have no way to register a function at all — Cloudflare D1's Workers Binding API is the motivating case, with no hook for it in its API and [cloudflare/workers-sdk#2802](https://github.com/cloudflare/workers-sdk/issues/2802) still open. Against a target like that, the registration above is simply not possible, and compiling `matches`/`notMatches` to `REGEXP`/`NOT REGEXP` anyway produces SQL that always fails at query execution with `no such function: REGEXP` rather than failing at compile time the way every other unpushable shape does. Set `sqliteRegexpAvailable: false` in `SqlCompileOptions` for a target like this, and the SQLite dialect refuses `matches`/`notMatches` with `UnsupportedNodeError` — and `findUnpushableNodeKind` reports them unpushable — at compile time instead, so the caller falls back to in-process evaluation the same way it would for any other unpushable node. It defaults to `true`, so a caller with a registered function (better-sqlite3, say) sees no change. It has no effect under the `postgres` dialect, which never needs a registered function in the first place.
|
|
177
193
|
|
|
194
|
+
`portableMatches`/`portableNotMatches` below need neither flag: D1 is exactly the target `GLOB` was chosen for, since it needs no function registration at all, and PostgreSQL's own translation is proven equivalent by this package's integration tests rather than passed through and hoped to be portable, so there is no divergence for `postgresRegexpPushdown` to gate.
|
|
195
|
+
|
|
196
|
+
## `portableMatches`/`portableNotMatches`
|
|
197
|
+
|
|
198
|
+
`matches`/`notMatches` above carry a real cost: PostgreSQL's advanced regular expressions and ECMAScript's are close but not identical languages, and SQLite has no regular-expression support to push down to at all, `REGEXP` registration notwithstanding. [`trilean-regex`](https://www.npmjs.com/package/trilean-regex) exists to close both gaps with a small grammar that is a true regular language — no backreferences, no lookaround — and `portableMatches`/`portableNotMatches` are the two `textCompare` operators that use it instead of native regex syntax.
|
|
199
|
+
|
|
200
|
+
The pattern (`textCompare`'s `right` operand) must be a **compile-time literal** — a bare `textLiteral`, never a column reference or a computed expression. This is a structural requirement, not a stylistic preference: translating a pattern into a dialect's own syntax happens once, in JavaScript, while `compilePredicateNode` runs, and there is nothing to translate if the pattern is only known per row at query time. A non-literal pattern is refused by the guard with a reason naming this directly, the same as any other unpushable shape.
|
|
201
|
+
|
|
202
|
+
**PostgreSQL** translates the parsed pattern into PostgreSQL's own Advanced Regular Expression syntax and binds it to `~`/`!~` — the same operators `matches`/`notMatches` already use, but now matched against a pattern PostgreSQL itself defines the syntax of, rather than one written for ECMAScript and hoped to be close enough. Every construct in `trilean-regex`'s grammar translates structurally (confirmed against a real PostgreSQL 17 server in `test/integration/postgres.test.ts`, including `.`, whose default newline-matching behaviour agrees with `trilean-regex`'s own despite reading otherwise from PostgreSQL's prose documentation alone). The one genuine limit is PostgreSQL's own: a bounded repetition (`{n}`/`{n,m}`) whose bound exceeds 255 has no PostgreSQL-native equivalent and is refused.
|
|
203
|
+
|
|
204
|
+
**SQLite** translates the pattern into a `GLOB` wildcard pattern and binds it to `GLOB`/`NOT GLOB` — a core SQLite feature needing no function registration, which is the whole reason a portable grammar is worth having for this dialect at all. `GLOB`'s wildcard vocabulary is much narrower than a regular language, though, so only a reachable subset translates: literal runs, `.` as `?`, a star of `.` as `*`, an anchor at the very start/end of the whole pattern (translated into a leading/trailing `*` standing in for "the rest, unconstrained," reproducing `portableMatches`'s own substring-search default), and a character class that is neither negated nor contains `]`/`^`/`-`/`[` as a member (SQLite's own documentation does not confirm an escape mechanism for those inside a bracket expression, so this compiler does not guess at one). Alternation, bounded/optional/one-or-more repetition, and anything using an unsafe class member are refused, falling back to in-process evaluation. `LIKE` is never used as a target even for the wildcard shapes it could express: it is case-insensitive for ASCII by default, while `trilean-regex` matching is always case-sensitive; `GLOB` matches that exactly.
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
const { sql, params } = compilePredicateNode(
|
|
208
|
+
{
|
|
209
|
+
kind: "textCompare",
|
|
210
|
+
op: "portableMatches",
|
|
211
|
+
left: { kind: "reference", key: "code" },
|
|
212
|
+
right: { kind: "textLiteral", value: "^ENA-[0-9].*$" },
|
|
213
|
+
},
|
|
214
|
+
{ dialect: "sqlite", columnFor },
|
|
215
|
+
);
|
|
216
|
+
// sql: ("code" GLOB ?)
|
|
217
|
+
// params: ["ENA-[0-9]*"]
|
|
218
|
+
```
|
|
219
|
+
|
|
178
220
|
## Tests
|
|
179
221
|
|
|
180
222
|
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.
|
package/dist/compile.cjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_errors = require("./errors.cjs");
|
|
3
3
|
const require_options = require("./options.cjs");
|
|
4
|
+
const require_portable_pattern = require("./portable-pattern.cjs");
|
|
4
5
|
const require_guard = require("./guard.cjs");
|
|
6
|
+
let trilean_regex = require("trilean-regex");
|
|
5
7
|
//#region src/compile.ts
|
|
6
8
|
const COMPARISON_SQL = {
|
|
7
9
|
gt: ">",
|
|
@@ -21,7 +23,9 @@ function textComparisonSqlFor(dialect) {
|
|
|
21
23
|
equals: "=",
|
|
22
24
|
notEquals: "<>",
|
|
23
25
|
matches: dialect.matches,
|
|
24
|
-
notMatches: dialect.notMatches
|
|
26
|
+
notMatches: dialect.notMatches,
|
|
27
|
+
portableMatches: dialect.portableMatches,
|
|
28
|
+
portableNotMatches: dialect.portableNotMatches
|
|
25
29
|
};
|
|
26
30
|
}
|
|
27
31
|
/**
|
|
@@ -68,6 +72,24 @@ function refuse(kind, layer) {
|
|
|
68
72
|
reason: `the ${layer} passed the pushability check but has no compiler branch`
|
|
69
73
|
});
|
|
70
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* Compiles a `portableMatches`/`portableNotMatches` node's pattern operand: parses `node.right`'s text as a `trilean-regex` pattern and translates it into this compilation's own dialect's native pattern syntax (see `portable-pattern.ts`), binding the *translated* string as the placeholder rather than the original pattern text -- from the database's point of view this is an ordinary match against a pattern in its own syntax, not `trilean-regex`'s.
|
|
77
|
+
*
|
|
78
|
+
* `findUnpushableNodeKind` already ran this exact parse-and-translate step before compilation started and refused the tree if it threw (see `guard.ts`), so a throw reaching here means the guard's allow-list has drifted from what this function actually accepts -- wrapped into `UnsupportedNodeError` as the same "passed the pushability check but has no compiler branch" safety net `refuse` provides elsewhere in this file, not an outcome reachable through this module's own public API.
|
|
79
|
+
*/
|
|
80
|
+
function compilePortablePattern(node, context) {
|
|
81
|
+
if (node.right.kind !== "textLiteral") return refuse(node.right.kind, "expression");
|
|
82
|
+
try {
|
|
83
|
+
const ast = (0, trilean_regex.parseRegex)(node.right.value);
|
|
84
|
+
return placeholder(context, context.options.dialect === "postgres" ? require_portable_pattern.renderPostgresPattern(ast) : require_portable_pattern.renderSqliteGlobPattern(ast), "text");
|
|
85
|
+
} catch (error) {
|
|
86
|
+
throw new require_errors.UnsupportedNodeError({
|
|
87
|
+
kind: node.right.kind,
|
|
88
|
+
path: "$.right",
|
|
89
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
71
93
|
function compileExpression(node, context) {
|
|
72
94
|
switch (node.kind) {
|
|
73
95
|
case "reference": {
|
|
@@ -100,7 +122,7 @@ function compilePredicate(node, context) {
|
|
|
100
122
|
}
|
|
101
123
|
case "textCompare": {
|
|
102
124
|
const left = compileExpression(node.left, context);
|
|
103
|
-
const right = compileExpression(node.right, context);
|
|
125
|
+
const right = node.op === "portableMatches" || node.op === "portableNotMatches" ? compilePortablePattern(node, context) : compileExpression(node.right, context);
|
|
104
126
|
return `(${left} ${context.textComparison[node.op]} ${right})`;
|
|
105
127
|
}
|
|
106
128
|
case "memberOf": {
|
|
@@ -132,6 +154,7 @@ function compilePredicateNode(node, options) {
|
|
|
132
154
|
const bindings = /* @__PURE__ */ new Map();
|
|
133
155
|
const memoised = {
|
|
134
156
|
dialect: options.dialect,
|
|
157
|
+
postgresRegexpPushdown: options.postgresRegexpPushdown,
|
|
135
158
|
columnFor: (referenceKey) => {
|
|
136
159
|
const cached = bindings.get(referenceKey);
|
|
137
160
|
if (cached !== void 0) return cached;
|
package/dist/compile.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { InvalidColumnError, UnsupportedNodeError } from "./errors.js";
|
|
2
2
|
import { DIALECT_CONFIG, assertImplementedDialect } from "./options.js";
|
|
3
|
+
import { renderPostgresPattern, renderSqliteGlobPattern } from "./portable-pattern.js";
|
|
3
4
|
import { findUnpushableNodeKind } from "./guard.js";
|
|
5
|
+
import { parseRegex } from "trilean-regex";
|
|
4
6
|
//#region src/compile.ts
|
|
5
7
|
const COMPARISON_SQL = {
|
|
6
8
|
gt: ">",
|
|
@@ -20,7 +22,9 @@ function textComparisonSqlFor(dialect) {
|
|
|
20
22
|
equals: "=",
|
|
21
23
|
notEquals: "<>",
|
|
22
24
|
matches: dialect.matches,
|
|
23
|
-
notMatches: dialect.notMatches
|
|
25
|
+
notMatches: dialect.notMatches,
|
|
26
|
+
portableMatches: dialect.portableMatches,
|
|
27
|
+
portableNotMatches: dialect.portableNotMatches
|
|
24
28
|
};
|
|
25
29
|
}
|
|
26
30
|
/**
|
|
@@ -67,6 +71,24 @@ function refuse(kind, layer) {
|
|
|
67
71
|
reason: `the ${layer} passed the pushability check but has no compiler branch`
|
|
68
72
|
});
|
|
69
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Compiles a `portableMatches`/`portableNotMatches` node's pattern operand: parses `node.right`'s text as a `trilean-regex` pattern and translates it into this compilation's own dialect's native pattern syntax (see `portable-pattern.ts`), binding the *translated* string as the placeholder rather than the original pattern text -- from the database's point of view this is an ordinary match against a pattern in its own syntax, not `trilean-regex`'s.
|
|
76
|
+
*
|
|
77
|
+
* `findUnpushableNodeKind` already ran this exact parse-and-translate step before compilation started and refused the tree if it threw (see `guard.ts`), so a throw reaching here means the guard's allow-list has drifted from what this function actually accepts -- wrapped into `UnsupportedNodeError` as the same "passed the pushability check but has no compiler branch" safety net `refuse` provides elsewhere in this file, not an outcome reachable through this module's own public API.
|
|
78
|
+
*/
|
|
79
|
+
function compilePortablePattern(node, context) {
|
|
80
|
+
if (node.right.kind !== "textLiteral") return refuse(node.right.kind, "expression");
|
|
81
|
+
try {
|
|
82
|
+
const ast = parseRegex(node.right.value);
|
|
83
|
+
return placeholder(context, context.options.dialect === "postgres" ? renderPostgresPattern(ast) : renderSqliteGlobPattern(ast), "text");
|
|
84
|
+
} catch (error) {
|
|
85
|
+
throw new UnsupportedNodeError({
|
|
86
|
+
kind: node.right.kind,
|
|
87
|
+
path: "$.right",
|
|
88
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
70
92
|
function compileExpression(node, context) {
|
|
71
93
|
switch (node.kind) {
|
|
72
94
|
case "reference": {
|
|
@@ -99,7 +121,7 @@ function compilePredicate(node, context) {
|
|
|
99
121
|
}
|
|
100
122
|
case "textCompare": {
|
|
101
123
|
const left = compileExpression(node.left, context);
|
|
102
|
-
const right = compileExpression(node.right, context);
|
|
124
|
+
const right = node.op === "portableMatches" || node.op === "portableNotMatches" ? compilePortablePattern(node, context) : compileExpression(node.right, context);
|
|
103
125
|
return `(${left} ${context.textComparison[node.op]} ${right})`;
|
|
104
126
|
}
|
|
105
127
|
case "memberOf": {
|
|
@@ -131,6 +153,7 @@ function compilePredicateNode(node, options) {
|
|
|
131
153
|
const bindings = /* @__PURE__ */ new Map();
|
|
132
154
|
const memoised = {
|
|
133
155
|
dialect: options.dialect,
|
|
156
|
+
postgresRegexpPushdown: options.postgresRegexpPushdown,
|
|
134
157
|
columnFor: (referenceKey) => {
|
|
135
158
|
const cached = bindings.get(referenceKey);
|
|
136
159
|
if (cached !== void 0) return cached;
|
package/dist/guard.cjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_options = require("./options.cjs");
|
|
3
|
+
const require_portable_pattern = require("./portable-pattern.cjs");
|
|
4
|
+
let trilean_regex = require("trilean-regex");
|
|
3
5
|
//#region src/guard.ts
|
|
4
6
|
const STATIC_KIND_OF_PARAM_TYPE = {
|
|
5
7
|
text: "text",
|
|
@@ -211,6 +213,30 @@ function findUnpushablePredicate(node, path, options, divergence) {
|
|
|
211
213
|
reason: `'textCompare' requires text operands in trilean, and the operand at ${operand.path} is a '${staticKind}' value`
|
|
212
214
|
};
|
|
213
215
|
}
|
|
216
|
+
const dialect = options?.dialect ?? "postgres";
|
|
217
|
+
if (dialect === "postgres" && (node.op === "matches" || node.op === "notMatches") && options?.postgresRegexpPushdown !== true) return {
|
|
218
|
+
kind: node.kind,
|
|
219
|
+
path,
|
|
220
|
+
reason: `'${node.op}' matches trilean's own ECMAScript 'RegExp' against the pattern, whereas PostgreSQL's '~'/'!~' would match it under PostgreSQL's own regular-expression dialect (POSIX ARE) -- a different language that can silently answer a different set of rows for the same pattern and data (for example, PostgreSQL's '.' matches a newline by default where ECMAScript's does not, and PostgreSQL's '\\w' follows the database's locale where ECMAScript's is ASCII-only) -- so this is refused unless 'postgresRegexpPushdown' is explicitly set 'true'`
|
|
221
|
+
};
|
|
222
|
+
if (node.op === "portableMatches" || node.op === "portableNotMatches") {
|
|
223
|
+
if (node.right.kind !== "textLiteral") return {
|
|
224
|
+
kind: node.kind,
|
|
225
|
+
path,
|
|
226
|
+
reason: "a 'portableMatches'/'portableNotMatches' pattern must be a literal, known at compile time -- translating it into this dialect's own pattern syntax happens once, at compile time, not per row"
|
|
227
|
+
};
|
|
228
|
+
try {
|
|
229
|
+
const ast = (0, trilean_regex.parseRegex)(node.right.value);
|
|
230
|
+
if (dialect === "postgres") require_portable_pattern.renderPostgresPattern(ast);
|
|
231
|
+
else require_portable_pattern.renderSqliteGlobPattern(ast);
|
|
232
|
+
} catch (error) {
|
|
233
|
+
return {
|
|
234
|
+
kind: node.kind,
|
|
235
|
+
path: `${path}.right`,
|
|
236
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
}
|
|
214
240
|
return;
|
|
215
241
|
}
|
|
216
242
|
case "memberOf": {
|
package/dist/guard.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { assertImplementedDialect } from "./options.js";
|
|
2
|
+
import { renderPostgresPattern, renderSqliteGlobPattern } from "./portable-pattern.js";
|
|
3
|
+
import { parseRegex } from "trilean-regex";
|
|
2
4
|
//#region src/guard.ts
|
|
3
5
|
const STATIC_KIND_OF_PARAM_TYPE = {
|
|
4
6
|
text: "text",
|
|
@@ -210,6 +212,30 @@ function findUnpushablePredicate(node, path, options, divergence) {
|
|
|
210
212
|
reason: `'textCompare' requires text operands in trilean, and the operand at ${operand.path} is a '${staticKind}' value`
|
|
211
213
|
};
|
|
212
214
|
}
|
|
215
|
+
const dialect = options?.dialect ?? "postgres";
|
|
216
|
+
if (dialect === "postgres" && (node.op === "matches" || node.op === "notMatches") && options?.postgresRegexpPushdown !== true) return {
|
|
217
|
+
kind: node.kind,
|
|
218
|
+
path,
|
|
219
|
+
reason: `'${node.op}' matches trilean's own ECMAScript 'RegExp' against the pattern, whereas PostgreSQL's '~'/'!~' would match it under PostgreSQL's own regular-expression dialect (POSIX ARE) -- a different language that can silently answer a different set of rows for the same pattern and data (for example, PostgreSQL's '.' matches a newline by default where ECMAScript's does not, and PostgreSQL's '\\w' follows the database's locale where ECMAScript's is ASCII-only) -- so this is refused unless 'postgresRegexpPushdown' is explicitly set 'true'`
|
|
220
|
+
};
|
|
221
|
+
if (node.op === "portableMatches" || node.op === "portableNotMatches") {
|
|
222
|
+
if (node.right.kind !== "textLiteral") return {
|
|
223
|
+
kind: node.kind,
|
|
224
|
+
path,
|
|
225
|
+
reason: "a 'portableMatches'/'portableNotMatches' pattern must be a literal, known at compile time -- translating it into this dialect's own pattern syntax happens once, at compile time, not per row"
|
|
226
|
+
};
|
|
227
|
+
try {
|
|
228
|
+
const ast = parseRegex(node.right.value);
|
|
229
|
+
if (dialect === "postgres") renderPostgresPattern(ast);
|
|
230
|
+
else renderSqliteGlobPattern(ast);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
return {
|
|
233
|
+
kind: node.kind,
|
|
234
|
+
path: `${path}.right`,
|
|
235
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
213
239
|
return;
|
|
214
240
|
}
|
|
215
241
|
case "memberOf": {
|
package/dist/options.cjs
CHANGED
|
@@ -12,12 +12,16 @@ const DIALECT_CONFIG = {
|
|
|
12
12
|
postgres: {
|
|
13
13
|
matches: "~",
|
|
14
14
|
notMatches: "!~",
|
|
15
|
+
portableMatches: "~",
|
|
16
|
+
portableNotMatches: "!~",
|
|
15
17
|
placeholder: (index, castTo) => `$${String(index)}::${POSTGRES_TYPE_NAME[castTo]}`,
|
|
16
18
|
emptyMemberOfNullSuffix: "::boolean"
|
|
17
19
|
},
|
|
18
20
|
sqlite: {
|
|
19
21
|
matches: "REGEXP",
|
|
20
22
|
notMatches: "NOT REGEXP",
|
|
23
|
+
portableMatches: "GLOB",
|
|
24
|
+
portableNotMatches: "NOT GLOB",
|
|
21
25
|
placeholder: () => "?",
|
|
22
26
|
emptyMemberOfNullSuffix: ""
|
|
23
27
|
}
|
package/dist/options.d.cts
CHANGED
|
@@ -24,11 +24,19 @@ interface SqlCompileOptions {
|
|
|
24
24
|
*/
|
|
25
25
|
columnFor: (referenceKey: string) => SqlColumnBinding;
|
|
26
26
|
/**
|
|
27
|
-
* Whether the SQLite target can resolve a `regexp(pattern, value)` function for `textCompare`'s `matches`/`notMatches` to compile to. Ignored under the `postgres` dialect, which
|
|
27
|
+
* Whether the SQLite target can resolve a `regexp(pattern, value)` function for `textCompare`'s `matches`/`notMatches` to compile to. Ignored under the `postgres` dialect, which has its own separate `postgresRegexpPushdown` gate below.
|
|
28
28
|
*
|
|
29
29
|
* Defaults to `true`, preserving the historical behaviour of always compiling to `REGEXP`/`NOT REGEXP`, which is correct for a driver a caller can register a function on (better-sqlite3, for instance). Set explicitly to `false` for a SQLite-wire-compatible target with no such registration hook -- Cloudflare D1 is the motivating case -- so `matches`/`notMatches` are refused by `UnsupportedNodeError` at compile time instead of compiling to SQL that fails at query execution with "no such function: REGEXP". See the "Regular expressions" section in README.md.
|
|
30
30
|
*/
|
|
31
31
|
sqliteRegexpAvailable?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Whether `matches`/`notMatches` may compile to PostgreSQL's own `~`/`!~` operators. Ignored under the SQLite dialect, whose `REGEXP` question is `sqliteRegexpAvailable`'s above.
|
|
34
|
+
*
|
|
35
|
+
* trilean's evaluator matches a pattern as an ECMAScript `RegExp`; PostgreSQL matches the same pattern text under its own regular-expression dialect (POSIX ARE plus extensions), a different language that is close but not identical. The divergence is not always a syntax error the compiler could catch ahead of time: `.` matches a newline under PostgreSQL's default but not ECMAScript's, and `\w`/`\d` follow the database's locale under PostgreSQL rather than ASCII -- both compile and execute cleanly under either engine and can still answer a different set of rows for the same data. Named groups (`(?<name>...)`), named backreferences (`\k<name>`) and Unicode property escapes (`\p{...}`) are ECMAScript syntax PostgreSQL's ARE does not have at all, so a pattern using them compiles here but fails as a PostgreSQL query error at execution time rather than as a compile-time refusal.
|
|
36
|
+
*
|
|
37
|
+
* Defaults to `false`: `matches`/`notMatches` are refused as unpushable and fall back to in-process evaluation, which is always correct because that is exactly the language the pattern is defined against. Set it to `true` only once every pattern that reaches this option is known to use nothing outside the portable syntax README.md's "Regular expressions" section describes -- it is one switch for the whole compilation, not a per-pattern one, so setting it accepts that same risk for every `matches`/`notMatches` node the tree contains.
|
|
38
|
+
*/
|
|
39
|
+
postgresRegexpPushdown?: boolean;
|
|
32
40
|
}
|
|
33
41
|
interface CompiledSql {
|
|
34
42
|
/** 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. */
|
|
@@ -48,6 +56,10 @@ interface DialectConfig {
|
|
|
48
56
|
matches: string;
|
|
49
57
|
/** The negated regular-expression match operator `textCompare`'s `notMatches` compiles to. */
|
|
50
58
|
notMatches: string;
|
|
59
|
+
/** The operator `textCompare`'s `portableMatches` compiles to, once its `trilean-regex` pattern has been translated into this dialect's own pattern syntax (see `portable-pattern.ts`). PostgreSQL reuses its native regex operator (`~`) here, since a translated pattern is still POSIX ARE text; SQLite uses `GLOB` instead of `REGEXP`, since the translation targets GLOB wildcards, not a regex engine. */
|
|
60
|
+
portableMatches: string;
|
|
61
|
+
/** The negated counterpart of `portableMatches`. */
|
|
62
|
+
portableNotMatches: string;
|
|
51
63
|
/** 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. */
|
|
52
64
|
placeholder: (index: number, castTo: SqlParamType) => string;
|
|
53
65
|
/** 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. */
|
package/dist/options.d.ts
CHANGED
|
@@ -24,11 +24,19 @@ interface SqlCompileOptions {
|
|
|
24
24
|
*/
|
|
25
25
|
columnFor: (referenceKey: string) => SqlColumnBinding;
|
|
26
26
|
/**
|
|
27
|
-
* Whether the SQLite target can resolve a `regexp(pattern, value)` function for `textCompare`'s `matches`/`notMatches` to compile to. Ignored under the `postgres` dialect, which
|
|
27
|
+
* Whether the SQLite target can resolve a `regexp(pattern, value)` function for `textCompare`'s `matches`/`notMatches` to compile to. Ignored under the `postgres` dialect, which has its own separate `postgresRegexpPushdown` gate below.
|
|
28
28
|
*
|
|
29
29
|
* Defaults to `true`, preserving the historical behaviour of always compiling to `REGEXP`/`NOT REGEXP`, which is correct for a driver a caller can register a function on (better-sqlite3, for instance). Set explicitly to `false` for a SQLite-wire-compatible target with no such registration hook -- Cloudflare D1 is the motivating case -- so `matches`/`notMatches` are refused by `UnsupportedNodeError` at compile time instead of compiling to SQL that fails at query execution with "no such function: REGEXP". See the "Regular expressions" section in README.md.
|
|
30
30
|
*/
|
|
31
31
|
sqliteRegexpAvailable?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Whether `matches`/`notMatches` may compile to PostgreSQL's own `~`/`!~` operators. Ignored under the SQLite dialect, whose `REGEXP` question is `sqliteRegexpAvailable`'s above.
|
|
34
|
+
*
|
|
35
|
+
* trilean's evaluator matches a pattern as an ECMAScript `RegExp`; PostgreSQL matches the same pattern text under its own regular-expression dialect (POSIX ARE plus extensions), a different language that is close but not identical. The divergence is not always a syntax error the compiler could catch ahead of time: `.` matches a newline under PostgreSQL's default but not ECMAScript's, and `\w`/`\d` follow the database's locale under PostgreSQL rather than ASCII -- both compile and execute cleanly under either engine and can still answer a different set of rows for the same data. Named groups (`(?<name>...)`), named backreferences (`\k<name>`) and Unicode property escapes (`\p{...}`) are ECMAScript syntax PostgreSQL's ARE does not have at all, so a pattern using them compiles here but fails as a PostgreSQL query error at execution time rather than as a compile-time refusal.
|
|
36
|
+
*
|
|
37
|
+
* Defaults to `false`: `matches`/`notMatches` are refused as unpushable and fall back to in-process evaluation, which is always correct because that is exactly the language the pattern is defined against. Set it to `true` only once every pattern that reaches this option is known to use nothing outside the portable syntax README.md's "Regular expressions" section describes -- it is one switch for the whole compilation, not a per-pattern one, so setting it accepts that same risk for every `matches`/`notMatches` node the tree contains.
|
|
38
|
+
*/
|
|
39
|
+
postgresRegexpPushdown?: boolean;
|
|
32
40
|
}
|
|
33
41
|
interface CompiledSql {
|
|
34
42
|
/** 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. */
|
|
@@ -48,6 +56,10 @@ interface DialectConfig {
|
|
|
48
56
|
matches: string;
|
|
49
57
|
/** The negated regular-expression match operator `textCompare`'s `notMatches` compiles to. */
|
|
50
58
|
notMatches: string;
|
|
59
|
+
/** The operator `textCompare`'s `portableMatches` compiles to, once its `trilean-regex` pattern has been translated into this dialect's own pattern syntax (see `portable-pattern.ts`). PostgreSQL reuses its native regex operator (`~`) here, since a translated pattern is still POSIX ARE text; SQLite uses `GLOB` instead of `REGEXP`, since the translation targets GLOB wildcards, not a regex engine. */
|
|
60
|
+
portableMatches: string;
|
|
61
|
+
/** The negated counterpart of `portableMatches`. */
|
|
62
|
+
portableNotMatches: string;
|
|
51
63
|
/** 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. */
|
|
52
64
|
placeholder: (index: number, castTo: SqlParamType) => string;
|
|
53
65
|
/** 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. */
|
package/dist/options.js
CHANGED
|
@@ -11,12 +11,16 @@ const DIALECT_CONFIG = {
|
|
|
11
11
|
postgres: {
|
|
12
12
|
matches: "~",
|
|
13
13
|
notMatches: "!~",
|
|
14
|
+
portableMatches: "~",
|
|
15
|
+
portableNotMatches: "!~",
|
|
14
16
|
placeholder: (index, castTo) => `$${String(index)}::${POSTGRES_TYPE_NAME[castTo]}`,
|
|
15
17
|
emptyMemberOfNullSuffix: "::boolean"
|
|
16
18
|
},
|
|
17
19
|
sqlite: {
|
|
18
20
|
matches: "REGEXP",
|
|
19
21
|
notMatches: "NOT REGEXP",
|
|
22
|
+
portableMatches: "GLOB",
|
|
23
|
+
portableNotMatches: "NOT GLOB",
|
|
20
24
|
placeholder: () => "?",
|
|
21
25
|
emptyMemberOfNullSuffix: ""
|
|
22
26
|
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/portable-pattern.ts
|
|
3
|
+
/**
|
|
4
|
+
* A `trilean-regex` pattern (or a specific construct within one) this module will not translate for a given target. Distinct from `UnsupportedNodeError`: that class names an unpushable `PredicateNode`/`ExpressionNode`, whereas this names an unpushable construct *inside* a pattern's own AST -- a different tree, one level down. `guard.ts` catches this and folds its `message` into the `textCompare` node's own `UnpushableNode.reason`, so a caller never sees this class directly; it exists to let a compile-time refusal carry a real reason across that boundary without weakening the outer type.
|
|
5
|
+
*/
|
|
6
|
+
var PortablePatternUnsupportedError = class extends Error {};
|
|
7
|
+
/** Metacharacters outside a bracket expression, in PostgreSQL's Advanced Regular Expression syntax -- the same set ECMAScript uses, confirmed against PostgreSQL's own "Regular Expression Details" documentation. */
|
|
8
|
+
const POSTGRES_METACHARS = /* @__PURE__ */ new Set([
|
|
9
|
+
".",
|
|
10
|
+
"*",
|
|
11
|
+
"+",
|
|
12
|
+
"?",
|
|
13
|
+
"(",
|
|
14
|
+
")",
|
|
15
|
+
"[",
|
|
16
|
+
"]",
|
|
17
|
+
"{",
|
|
18
|
+
"}",
|
|
19
|
+
"|",
|
|
20
|
+
"^",
|
|
21
|
+
"$",
|
|
22
|
+
"\\"
|
|
23
|
+
]);
|
|
24
|
+
/** Characters that are special *inside* a bracket expression and need a backslash to appear literally -- confirmed against PostgreSQL's documentation: unlike POSIX ERE/BRE, an ARE's `\` is honoured inside `[...]` too. */
|
|
25
|
+
const POSTGRES_CLASS_METACHARS = /* @__PURE__ */ new Set([
|
|
26
|
+
"]",
|
|
27
|
+
"\\",
|
|
28
|
+
"^",
|
|
29
|
+
"-"
|
|
30
|
+
]);
|
|
31
|
+
/** PostgreSQL's own bound limit: "The numbers m and n within a bound are ... with permissible values from 0 to 255 inclusive" (PostgreSQL documentation). A pattern whose `{n}`/`{n,m}` exceeds this has no PostgreSQL-native equivalent at all -- there is no rewriting that preserves the bound past this ceiling -- so it is refused rather than silently clamped or expanded. */
|
|
32
|
+
const POSTGRES_MAX_BOUND = 255;
|
|
33
|
+
function escapePostgresLiteral(codeUnit) {
|
|
34
|
+
const char = String.fromCharCode(codeUnit);
|
|
35
|
+
return POSTGRES_METACHARS.has(char) ? `\\${char}` : char;
|
|
36
|
+
}
|
|
37
|
+
function escapePostgresClassChar(codeUnit) {
|
|
38
|
+
const char = String.fromCharCode(codeUnit);
|
|
39
|
+
return POSTGRES_CLASS_METACHARS.has(char) ? `\\${char}` : char;
|
|
40
|
+
}
|
|
41
|
+
function renderPostgresClass(node) {
|
|
42
|
+
const body = node.ranges.map((range) => range.from === range.to ? escapePostgresClassChar(range.from) : `${escapePostgresClassChar(range.from)}-${escapePostgresClassChar(range.to)}`).join("");
|
|
43
|
+
return `[${node.negated ? "^" : ""}${body}]`;
|
|
44
|
+
}
|
|
45
|
+
function renderPostgresBound(min, max) {
|
|
46
|
+
if (min > POSTGRES_MAX_BOUND || max !== void 0 && max > POSTGRES_MAX_BOUND) throw new PortablePatternUnsupportedError(`PostgreSQL's regular expressions permit a bound of at most ${String(POSTGRES_MAX_BOUND)}; {${String(min)}${max === void 0 ? "," : max === min ? "" : `,${String(max)}`}} exceeds it`);
|
|
47
|
+
if (max === void 0) return `{${String(min)},}`;
|
|
48
|
+
if (max === min) return `{${String(min)}}`;
|
|
49
|
+
return `{${String(min)},${String(max)}}`;
|
|
50
|
+
}
|
|
51
|
+
/** Whether `node`'s own rendering needs `(?:...)` wrapping to render safely as one operand: a `concat` or `alternation` renders as more than one syntactic unit, so without wrapping, a quantifier immediately after it would bind only to its last unit instead of the whole thing. Used for every `concat` operand and quantifier operand, including a nested `concat` (where flattening would in fact be safe too, concatenation being associative) -- wrapping unconditionally here is a deliberately simple, always-correct rule rather than a minimal one; the one place flattening is relied on instead is `alternation`'s own branches below, which are never wrapped. */
|
|
52
|
+
function needsPostgresGrouping(node) {
|
|
53
|
+
return node.kind === "concat" || node.kind === "alternation";
|
|
54
|
+
}
|
|
55
|
+
function renderPostgresSubcomponent(node) {
|
|
56
|
+
const rendered = renderPostgresPattern(node);
|
|
57
|
+
return needsPostgresGrouping(node) ? `(?:${rendered})` : rendered;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Translates a `trilean-regex` AST into PostgreSQL's own Advanced Regular Expression syntax, for binding as the pattern argument to `~`/`!~`.
|
|
61
|
+
*
|
|
62
|
+
* Every construct this grammar accepts translates structurally, `.` included: measured directly against a real PostgreSQL 17 server (see the "PostgreSQL's own engine treats '.' as matching a newline" case in `test/integration/postgres.test.ts`), PostgreSQL's `.` matches a newline by default in the mode this compiler's `~`/`!~` operators run under -- the same as this grammar's own `.` (see trilean-regex's README) -- so no rewriting is needed here. (PostgreSQL's own prose documentation reads, in isolation, as though newline-sensitive matching were the default; it is not the one this operator uses, and the fact was confirmed against the real server rather than trusted from the prose alone -- see the "Verify this assumption" principle this compiler otherwise applies to every other construct too.)
|
|
63
|
+
*
|
|
64
|
+
* @throws {PortablePatternUnsupportedError} if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
|
|
65
|
+
*/
|
|
66
|
+
function renderPostgresPattern(node) {
|
|
67
|
+
switch (node.kind) {
|
|
68
|
+
case "literal": return escapePostgresLiteral(node.codeUnit);
|
|
69
|
+
case "anyChar": return ".";
|
|
70
|
+
case "charClass": return renderPostgresClass(node);
|
|
71
|
+
case "anchorStart": return "^";
|
|
72
|
+
case "anchorEnd": return "$";
|
|
73
|
+
case "concat": return node.operands.map((operand) => renderPostgresSubcomponent(operand)).join("");
|
|
74
|
+
case "alternation": return node.branches.map((branch) => renderPostgresPattern(branch)).join("|");
|
|
75
|
+
case "star": return `${renderPostgresSubcomponent(node.operand)}*`;
|
|
76
|
+
case "plus": return `${renderPostgresSubcomponent(node.operand)}+`;
|
|
77
|
+
case "optional": return `${renderPostgresSubcomponent(node.operand)}?`;
|
|
78
|
+
case "repeat": return `${renderPostgresSubcomponent(node.operand)}${renderPostgresBound(node.min, node.max)}`;
|
|
79
|
+
default: throw new Error("unreachable regex node kind");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The reachable subset this compiler translates to `GLOB`: literal runs, `.` as `?`, `star` of `.` as `*`, an optional `^`/`$` at the very edges of the whole pattern, and a character class that is neither negated nor contains `]`/`^`/`-`/`[` as a member. Everything else -- alternation (GLOB has no such operator), bounded/optional/one-or-more repetition (GLOB's only quantity wildcard is `*`, "zero or more"), a negated or `]`/`^`/`-`/`[`-containing class (SQLite's own GLOB documentation does not confirm a backslash-escape mechanism inside a bracket expression, so this compiler does not guess at one), and an anchor anywhere but the very start/end -- is refused, falling back to in-process evaluation.
|
|
84
|
+
*
|
|
85
|
+
* `LIKE` is deliberately never used as a target even though it can express the same wildcard shapes as `?`/`%`: SQLite's `LIKE` is case-insensitive for ASCII by default, while trilean-regex matching (like `matches`/`notMatches`) is always case-sensitive -- a `LIKE` translation would silently accept differently-cased input the reference matcher rejects. `GLOB` is case-sensitive, matching this grammar exactly.
|
|
86
|
+
*
|
|
87
|
+
* Unlike PostgreSQL's regular expressions, `GLOB`'s pattern always matches the *whole* value -- there is no implicit "appears anywhere" search the way `matches`/`portableMatches`'s own default semantics provide. An unanchored portion of the pattern is therefore translated with a leading and/or trailing `*` standing in for "anything, including nothing" on that side, exactly reproducing the substring-search semantics `trilean-regex`'s own reference matcher gives an unanchored pattern.
|
|
88
|
+
*/
|
|
89
|
+
const GLOB_UNSAFE_CLASS_MEMBERS = new Set([
|
|
90
|
+
"]",
|
|
91
|
+
"^",
|
|
92
|
+
"-",
|
|
93
|
+
"[",
|
|
94
|
+
"!"
|
|
95
|
+
].map((char) => char.charCodeAt(0)));
|
|
96
|
+
function rangeContainsAnyOf(range, codeUnits) {
|
|
97
|
+
for (const codeUnit of codeUnits) if (codeUnit >= range.from && codeUnit <= range.to) return true;
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
function escapeGlobLiteral(codeUnit) {
|
|
101
|
+
const char = String.fromCharCode(codeUnit);
|
|
102
|
+
return char === "*" || char === "?" || char === "[" ? `[${char}]` : char;
|
|
103
|
+
}
|
|
104
|
+
function renderGlobClass(node) {
|
|
105
|
+
if (node.negated) throw new PortablePatternUnsupportedError("this compiler does not translate a negated character class to GLOB: SQLite's own documentation does not confirm which of the common '[^...]'/'[!...]' conventions (if either) it implements");
|
|
106
|
+
if (node.ranges.some((range) => rangeContainsAnyOf(range, GLOB_UNSAFE_CLASS_MEMBERS))) throw new PortablePatternUnsupportedError("this character class includes ']', '^', '-', or '[' as a member, and GLOB's bracket expressions have no confirmed escape mechanism for them");
|
|
107
|
+
return `[${node.ranges.map((range) => range.from === range.to ? String.fromCharCode(range.from) : `${String.fromCharCode(range.from)}-${String.fromCharCode(range.to)}`).join("")}]`;
|
|
108
|
+
}
|
|
109
|
+
function renderGlobAtom(node) {
|
|
110
|
+
switch (node.kind) {
|
|
111
|
+
case "literal": return escapeGlobLiteral(node.codeUnit);
|
|
112
|
+
case "anyChar": return "?";
|
|
113
|
+
case "charClass": return renderGlobClass(node);
|
|
114
|
+
case "concat": return node.operands.map((operand) => renderGlobAtom(operand)).join("");
|
|
115
|
+
case "star":
|
|
116
|
+
if (node.operand.kind === "anyChar") return "*";
|
|
117
|
+
throw new PortablePatternUnsupportedError("GLOB's only quantity wildcard is '*' ('zero or more of any character'); a star of anything narrower has no GLOB equivalent");
|
|
118
|
+
case "alternation": throw new PortablePatternUnsupportedError("GLOB has no alternation operator");
|
|
119
|
+
case "plus": throw new PortablePatternUnsupportedError("GLOB has no 'one or more' wildcard distinct from '*'");
|
|
120
|
+
case "optional": throw new PortablePatternUnsupportedError("GLOB has no 'zero or one' wildcard");
|
|
121
|
+
case "repeat": throw new PortablePatternUnsupportedError("GLOB has no bounded-repetition wildcard");
|
|
122
|
+
case "anchorStart":
|
|
123
|
+
case "anchorEnd": throw new PortablePatternUnsupportedError("an anchor is only expressible for GLOB at the very start or end of the whole pattern");
|
|
124
|
+
default: throw new Error("unreachable regex node kind");
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function planGlobBody(node) {
|
|
128
|
+
const operands = node.kind === "concat" ? [...node.operands] : [node];
|
|
129
|
+
const anchoredStart = operands[0]?.kind === "anchorStart";
|
|
130
|
+
if (anchoredStart) operands.shift();
|
|
131
|
+
const anchoredEnd = operands.at(-1)?.kind === "anchorEnd";
|
|
132
|
+
if (anchoredEnd) operands.pop();
|
|
133
|
+
for (const operand of operands) if (operand.kind === "anchorStart" || operand.kind === "anchorEnd") throw new PortablePatternUnsupportedError("an anchor is only expressible for GLOB at the very start or end of the whole pattern");
|
|
134
|
+
return {
|
|
135
|
+
anchoredStart,
|
|
136
|
+
anchoredEnd,
|
|
137
|
+
body: operands
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Translates a `trilean-regex` AST into a `GLOB` pattern, for binding as `GLOB`/`NOT GLOB`'s right-hand argument. See the "reachable subset" doc comment above for exactly what this does and does not translate.
|
|
142
|
+
*
|
|
143
|
+
* @throws {PortablePatternUnsupportedError} if `node` uses any construct outside the reachable subset.
|
|
144
|
+
*/
|
|
145
|
+
function renderSqliteGlobPattern(node) {
|
|
146
|
+
const plan = planGlobBody(node);
|
|
147
|
+
const body = plan.body.map((atom) => renderGlobAtom(atom)).join("");
|
|
148
|
+
return `${plan.anchoredStart ? "" : "*"}${body}${plan.anchoredEnd ? "" : "*"}`.replaceAll(/\*{2,}/g, "*");
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
exports.PortablePatternUnsupportedError = PortablePatternUnsupportedError;
|
|
152
|
+
exports.renderPostgresPattern = renderPostgresPattern;
|
|
153
|
+
exports.renderSqliteGlobPattern = renderSqliteGlobPattern;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { RegexNode } from "trilean-regex";
|
|
2
|
+
//#region src/portable-pattern.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* A `trilean-regex` pattern (or a specific construct within one) this module will not translate for a given target. Distinct from `UnsupportedNodeError`: that class names an unpushable `PredicateNode`/`ExpressionNode`, whereas this names an unpushable construct *inside* a pattern's own AST -- a different tree, one level down. `guard.ts` catches this and folds its `message` into the `textCompare` node's own `UnpushableNode.reason`, so a caller never sees this class directly; it exists to let a compile-time refusal carry a real reason across that boundary without weakening the outer type.
|
|
5
|
+
*/
|
|
6
|
+
declare class PortablePatternUnsupportedError extends Error {}
|
|
7
|
+
/**
|
|
8
|
+
* Translates a `trilean-regex` AST into PostgreSQL's own Advanced Regular Expression syntax, for binding as the pattern argument to `~`/`!~`.
|
|
9
|
+
*
|
|
10
|
+
* Every construct this grammar accepts translates structurally, `.` included: measured directly against a real PostgreSQL 17 server (see the "PostgreSQL's own engine treats '.' as matching a newline" case in `test/integration/postgres.test.ts`), PostgreSQL's `.` matches a newline by default in the mode this compiler's `~`/`!~` operators run under -- the same as this grammar's own `.` (see trilean-regex's README) -- so no rewriting is needed here. (PostgreSQL's own prose documentation reads, in isolation, as though newline-sensitive matching were the default; it is not the one this operator uses, and the fact was confirmed against the real server rather than trusted from the prose alone -- see the "Verify this assumption" principle this compiler otherwise applies to every other construct too.)
|
|
11
|
+
*
|
|
12
|
+
* @throws {PortablePatternUnsupportedError} if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
|
|
13
|
+
*/
|
|
14
|
+
declare function renderPostgresPattern(node: RegexNode): string;
|
|
15
|
+
/**
|
|
16
|
+
* Translates a `trilean-regex` AST into a `GLOB` pattern, for binding as `GLOB`/`NOT GLOB`'s right-hand argument. See the "reachable subset" doc comment above for exactly what this does and does not translate.
|
|
17
|
+
*
|
|
18
|
+
* @throws {PortablePatternUnsupportedError} if `node` uses any construct outside the reachable subset.
|
|
19
|
+
*/
|
|
20
|
+
declare function renderSqliteGlobPattern(node: RegexNode): string;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { PortablePatternUnsupportedError, renderPostgresPattern, renderSqliteGlobPattern };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { RegexNode } from "trilean-regex";
|
|
2
|
+
//#region src/portable-pattern.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* A `trilean-regex` pattern (or a specific construct within one) this module will not translate for a given target. Distinct from `UnsupportedNodeError`: that class names an unpushable `PredicateNode`/`ExpressionNode`, whereas this names an unpushable construct *inside* a pattern's own AST -- a different tree, one level down. `guard.ts` catches this and folds its `message` into the `textCompare` node's own `UnpushableNode.reason`, so a caller never sees this class directly; it exists to let a compile-time refusal carry a real reason across that boundary without weakening the outer type.
|
|
5
|
+
*/
|
|
6
|
+
declare class PortablePatternUnsupportedError extends Error {}
|
|
7
|
+
/**
|
|
8
|
+
* Translates a `trilean-regex` AST into PostgreSQL's own Advanced Regular Expression syntax, for binding as the pattern argument to `~`/`!~`.
|
|
9
|
+
*
|
|
10
|
+
* Every construct this grammar accepts translates structurally, `.` included: measured directly against a real PostgreSQL 17 server (see the "PostgreSQL's own engine treats '.' as matching a newline" case in `test/integration/postgres.test.ts`), PostgreSQL's `.` matches a newline by default in the mode this compiler's `~`/`!~` operators run under -- the same as this grammar's own `.` (see trilean-regex's README) -- so no rewriting is needed here. (PostgreSQL's own prose documentation reads, in isolation, as though newline-sensitive matching were the default; it is not the one this operator uses, and the fact was confirmed against the real server rather than trusted from the prose alone -- see the "Verify this assumption" principle this compiler otherwise applies to every other construct too.)
|
|
11
|
+
*
|
|
12
|
+
* @throws {PortablePatternUnsupportedError} if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
|
|
13
|
+
*/
|
|
14
|
+
declare function renderPostgresPattern(node: RegexNode): string;
|
|
15
|
+
/**
|
|
16
|
+
* Translates a `trilean-regex` AST into a `GLOB` pattern, for binding as `GLOB`/`NOT GLOB`'s right-hand argument. See the "reachable subset" doc comment above for exactly what this does and does not translate.
|
|
17
|
+
*
|
|
18
|
+
* @throws {PortablePatternUnsupportedError} if `node` uses any construct outside the reachable subset.
|
|
19
|
+
*/
|
|
20
|
+
declare function renderSqliteGlobPattern(node: RegexNode): string;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { PortablePatternUnsupportedError, renderPostgresPattern, renderSqliteGlobPattern };
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
//#region src/portable-pattern.ts
|
|
2
|
+
/**
|
|
3
|
+
* A `trilean-regex` pattern (or a specific construct within one) this module will not translate for a given target. Distinct from `UnsupportedNodeError`: that class names an unpushable `PredicateNode`/`ExpressionNode`, whereas this names an unpushable construct *inside* a pattern's own AST -- a different tree, one level down. `guard.ts` catches this and folds its `message` into the `textCompare` node's own `UnpushableNode.reason`, so a caller never sees this class directly; it exists to let a compile-time refusal carry a real reason across that boundary without weakening the outer type.
|
|
4
|
+
*/
|
|
5
|
+
var PortablePatternUnsupportedError = class extends Error {};
|
|
6
|
+
/** Metacharacters outside a bracket expression, in PostgreSQL's Advanced Regular Expression syntax -- the same set ECMAScript uses, confirmed against PostgreSQL's own "Regular Expression Details" documentation. */
|
|
7
|
+
const POSTGRES_METACHARS = /* @__PURE__ */ new Set([
|
|
8
|
+
".",
|
|
9
|
+
"*",
|
|
10
|
+
"+",
|
|
11
|
+
"?",
|
|
12
|
+
"(",
|
|
13
|
+
")",
|
|
14
|
+
"[",
|
|
15
|
+
"]",
|
|
16
|
+
"{",
|
|
17
|
+
"}",
|
|
18
|
+
"|",
|
|
19
|
+
"^",
|
|
20
|
+
"$",
|
|
21
|
+
"\\"
|
|
22
|
+
]);
|
|
23
|
+
/** Characters that are special *inside* a bracket expression and need a backslash to appear literally -- confirmed against PostgreSQL's documentation: unlike POSIX ERE/BRE, an ARE's `\` is honoured inside `[...]` too. */
|
|
24
|
+
const POSTGRES_CLASS_METACHARS = /* @__PURE__ */ new Set([
|
|
25
|
+
"]",
|
|
26
|
+
"\\",
|
|
27
|
+
"^",
|
|
28
|
+
"-"
|
|
29
|
+
]);
|
|
30
|
+
/** PostgreSQL's own bound limit: "The numbers m and n within a bound are ... with permissible values from 0 to 255 inclusive" (PostgreSQL documentation). A pattern whose `{n}`/`{n,m}` exceeds this has no PostgreSQL-native equivalent at all -- there is no rewriting that preserves the bound past this ceiling -- so it is refused rather than silently clamped or expanded. */
|
|
31
|
+
const POSTGRES_MAX_BOUND = 255;
|
|
32
|
+
function escapePostgresLiteral(codeUnit) {
|
|
33
|
+
const char = String.fromCharCode(codeUnit);
|
|
34
|
+
return POSTGRES_METACHARS.has(char) ? `\\${char}` : char;
|
|
35
|
+
}
|
|
36
|
+
function escapePostgresClassChar(codeUnit) {
|
|
37
|
+
const char = String.fromCharCode(codeUnit);
|
|
38
|
+
return POSTGRES_CLASS_METACHARS.has(char) ? `\\${char}` : char;
|
|
39
|
+
}
|
|
40
|
+
function renderPostgresClass(node) {
|
|
41
|
+
const body = node.ranges.map((range) => range.from === range.to ? escapePostgresClassChar(range.from) : `${escapePostgresClassChar(range.from)}-${escapePostgresClassChar(range.to)}`).join("");
|
|
42
|
+
return `[${node.negated ? "^" : ""}${body}]`;
|
|
43
|
+
}
|
|
44
|
+
function renderPostgresBound(min, max) {
|
|
45
|
+
if (min > POSTGRES_MAX_BOUND || max !== void 0 && max > POSTGRES_MAX_BOUND) throw new PortablePatternUnsupportedError(`PostgreSQL's regular expressions permit a bound of at most ${String(POSTGRES_MAX_BOUND)}; {${String(min)}${max === void 0 ? "," : max === min ? "" : `,${String(max)}`}} exceeds it`);
|
|
46
|
+
if (max === void 0) return `{${String(min)},}`;
|
|
47
|
+
if (max === min) return `{${String(min)}}`;
|
|
48
|
+
return `{${String(min)},${String(max)}}`;
|
|
49
|
+
}
|
|
50
|
+
/** Whether `node`'s own rendering needs `(?:...)` wrapping to render safely as one operand: a `concat` or `alternation` renders as more than one syntactic unit, so without wrapping, a quantifier immediately after it would bind only to its last unit instead of the whole thing. Used for every `concat` operand and quantifier operand, including a nested `concat` (where flattening would in fact be safe too, concatenation being associative) -- wrapping unconditionally here is a deliberately simple, always-correct rule rather than a minimal one; the one place flattening is relied on instead is `alternation`'s own branches below, which are never wrapped. */
|
|
51
|
+
function needsPostgresGrouping(node) {
|
|
52
|
+
return node.kind === "concat" || node.kind === "alternation";
|
|
53
|
+
}
|
|
54
|
+
function renderPostgresSubcomponent(node) {
|
|
55
|
+
const rendered = renderPostgresPattern(node);
|
|
56
|
+
return needsPostgresGrouping(node) ? `(?:${rendered})` : rendered;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Translates a `trilean-regex` AST into PostgreSQL's own Advanced Regular Expression syntax, for binding as the pattern argument to `~`/`!~`.
|
|
60
|
+
*
|
|
61
|
+
* Every construct this grammar accepts translates structurally, `.` included: measured directly against a real PostgreSQL 17 server (see the "PostgreSQL's own engine treats '.' as matching a newline" case in `test/integration/postgres.test.ts`), PostgreSQL's `.` matches a newline by default in the mode this compiler's `~`/`!~` operators run under -- the same as this grammar's own `.` (see trilean-regex's README) -- so no rewriting is needed here. (PostgreSQL's own prose documentation reads, in isolation, as though newline-sensitive matching were the default; it is not the one this operator uses, and the fact was confirmed against the real server rather than trusted from the prose alone -- see the "Verify this assumption" principle this compiler otherwise applies to every other construct too.)
|
|
62
|
+
*
|
|
63
|
+
* @throws {PortablePatternUnsupportedError} if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
|
|
64
|
+
*/
|
|
65
|
+
function renderPostgresPattern(node) {
|
|
66
|
+
switch (node.kind) {
|
|
67
|
+
case "literal": return escapePostgresLiteral(node.codeUnit);
|
|
68
|
+
case "anyChar": return ".";
|
|
69
|
+
case "charClass": return renderPostgresClass(node);
|
|
70
|
+
case "anchorStart": return "^";
|
|
71
|
+
case "anchorEnd": return "$";
|
|
72
|
+
case "concat": return node.operands.map((operand) => renderPostgresSubcomponent(operand)).join("");
|
|
73
|
+
case "alternation": return node.branches.map((branch) => renderPostgresPattern(branch)).join("|");
|
|
74
|
+
case "star": return `${renderPostgresSubcomponent(node.operand)}*`;
|
|
75
|
+
case "plus": return `${renderPostgresSubcomponent(node.operand)}+`;
|
|
76
|
+
case "optional": return `${renderPostgresSubcomponent(node.operand)}?`;
|
|
77
|
+
case "repeat": return `${renderPostgresSubcomponent(node.operand)}${renderPostgresBound(node.min, node.max)}`;
|
|
78
|
+
default: throw new Error("unreachable regex node kind");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The reachable subset this compiler translates to `GLOB`: literal runs, `.` as `?`, `star` of `.` as `*`, an optional `^`/`$` at the very edges of the whole pattern, and a character class that is neither negated nor contains `]`/`^`/`-`/`[` as a member. Everything else -- alternation (GLOB has no such operator), bounded/optional/one-or-more repetition (GLOB's only quantity wildcard is `*`, "zero or more"), a negated or `]`/`^`/`-`/`[`-containing class (SQLite's own GLOB documentation does not confirm a backslash-escape mechanism inside a bracket expression, so this compiler does not guess at one), and an anchor anywhere but the very start/end -- is refused, falling back to in-process evaluation.
|
|
83
|
+
*
|
|
84
|
+
* `LIKE` is deliberately never used as a target even though it can express the same wildcard shapes as `?`/`%`: SQLite's `LIKE` is case-insensitive for ASCII by default, while trilean-regex matching (like `matches`/`notMatches`) is always case-sensitive -- a `LIKE` translation would silently accept differently-cased input the reference matcher rejects. `GLOB` is case-sensitive, matching this grammar exactly.
|
|
85
|
+
*
|
|
86
|
+
* Unlike PostgreSQL's regular expressions, `GLOB`'s pattern always matches the *whole* value -- there is no implicit "appears anywhere" search the way `matches`/`portableMatches`'s own default semantics provide. An unanchored portion of the pattern is therefore translated with a leading and/or trailing `*` standing in for "anything, including nothing" on that side, exactly reproducing the substring-search semantics `trilean-regex`'s own reference matcher gives an unanchored pattern.
|
|
87
|
+
*/
|
|
88
|
+
const GLOB_UNSAFE_CLASS_MEMBERS = new Set([
|
|
89
|
+
"]",
|
|
90
|
+
"^",
|
|
91
|
+
"-",
|
|
92
|
+
"[",
|
|
93
|
+
"!"
|
|
94
|
+
].map((char) => char.charCodeAt(0)));
|
|
95
|
+
function rangeContainsAnyOf(range, codeUnits) {
|
|
96
|
+
for (const codeUnit of codeUnits) if (codeUnit >= range.from && codeUnit <= range.to) return true;
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
function escapeGlobLiteral(codeUnit) {
|
|
100
|
+
const char = String.fromCharCode(codeUnit);
|
|
101
|
+
return char === "*" || char === "?" || char === "[" ? `[${char}]` : char;
|
|
102
|
+
}
|
|
103
|
+
function renderGlobClass(node) {
|
|
104
|
+
if (node.negated) throw new PortablePatternUnsupportedError("this compiler does not translate a negated character class to GLOB: SQLite's own documentation does not confirm which of the common '[^...]'/'[!...]' conventions (if either) it implements");
|
|
105
|
+
if (node.ranges.some((range) => rangeContainsAnyOf(range, GLOB_UNSAFE_CLASS_MEMBERS))) throw new PortablePatternUnsupportedError("this character class includes ']', '^', '-', or '[' as a member, and GLOB's bracket expressions have no confirmed escape mechanism for them");
|
|
106
|
+
return `[${node.ranges.map((range) => range.from === range.to ? String.fromCharCode(range.from) : `${String.fromCharCode(range.from)}-${String.fromCharCode(range.to)}`).join("")}]`;
|
|
107
|
+
}
|
|
108
|
+
function renderGlobAtom(node) {
|
|
109
|
+
switch (node.kind) {
|
|
110
|
+
case "literal": return escapeGlobLiteral(node.codeUnit);
|
|
111
|
+
case "anyChar": return "?";
|
|
112
|
+
case "charClass": return renderGlobClass(node);
|
|
113
|
+
case "concat": return node.operands.map((operand) => renderGlobAtom(operand)).join("");
|
|
114
|
+
case "star":
|
|
115
|
+
if (node.operand.kind === "anyChar") return "*";
|
|
116
|
+
throw new PortablePatternUnsupportedError("GLOB's only quantity wildcard is '*' ('zero or more of any character'); a star of anything narrower has no GLOB equivalent");
|
|
117
|
+
case "alternation": throw new PortablePatternUnsupportedError("GLOB has no alternation operator");
|
|
118
|
+
case "plus": throw new PortablePatternUnsupportedError("GLOB has no 'one or more' wildcard distinct from '*'");
|
|
119
|
+
case "optional": throw new PortablePatternUnsupportedError("GLOB has no 'zero or one' wildcard");
|
|
120
|
+
case "repeat": throw new PortablePatternUnsupportedError("GLOB has no bounded-repetition wildcard");
|
|
121
|
+
case "anchorStart":
|
|
122
|
+
case "anchorEnd": throw new PortablePatternUnsupportedError("an anchor is only expressible for GLOB at the very start or end of the whole pattern");
|
|
123
|
+
default: throw new Error("unreachable regex node kind");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function planGlobBody(node) {
|
|
127
|
+
const operands = node.kind === "concat" ? [...node.operands] : [node];
|
|
128
|
+
const anchoredStart = operands[0]?.kind === "anchorStart";
|
|
129
|
+
if (anchoredStart) operands.shift();
|
|
130
|
+
const anchoredEnd = operands.at(-1)?.kind === "anchorEnd";
|
|
131
|
+
if (anchoredEnd) operands.pop();
|
|
132
|
+
for (const operand of operands) if (operand.kind === "anchorStart" || operand.kind === "anchorEnd") throw new PortablePatternUnsupportedError("an anchor is only expressible for GLOB at the very start or end of the whole pattern");
|
|
133
|
+
return {
|
|
134
|
+
anchoredStart,
|
|
135
|
+
anchoredEnd,
|
|
136
|
+
body: operands
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Translates a `trilean-regex` AST into a `GLOB` pattern, for binding as `GLOB`/`NOT GLOB`'s right-hand argument. See the "reachable subset" doc comment above for exactly what this does and does not translate.
|
|
141
|
+
*
|
|
142
|
+
* @throws {PortablePatternUnsupportedError} if `node` uses any construct outside the reachable subset.
|
|
143
|
+
*/
|
|
144
|
+
function renderSqliteGlobPattern(node) {
|
|
145
|
+
const plan = planGlobBody(node);
|
|
146
|
+
const body = plan.body.map((atom) => renderGlobAtom(atom)).join("");
|
|
147
|
+
return `${plan.anchoredStart ? "" : "*"}${body}${plan.anchoredEnd ? "" : "*"}`.replaceAll(/\*{2,}/g, "*");
|
|
148
|
+
}
|
|
149
|
+
//#endregion
|
|
150
|
+
export { PortablePatternUnsupportedError, renderPostgresPattern, renderSqliteGlobPattern };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trilean-sql",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "2.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": {
|
|
@@ -47,7 +47,8 @@
|
|
|
47
47
|
},
|
|
48
48
|
"license": "MIT",
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"trilean": "workspace:^"
|
|
50
|
+
"trilean": "workspace:^",
|
|
51
|
+
"trilean-regex": "workspace:^"
|
|
51
52
|
},
|
|
52
53
|
"scripts": {
|
|
53
54
|
"build": "turbo run _build",
|