trilean-sql 2.0.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 +27 -1
- package/dist/compile.cjs +24 -2
- package/dist/compile.js +24 -2
- package/dist/guard.cjs +22 -1
- package/dist/guard.js +22 -1
- package/dist/options.cjs +4 -0
- package/dist/options.d.cts +4 -0
- package/dist/options.d.ts +4 -0
- 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
|
@@ -102,7 +102,7 @@ Passing `options` widens the check: without them the walk is purely structural;
|
|
|
102
102
|
| `and`, `or`, `not` | `AND`, `OR`, `NOT` | same |
|
|
103
103
|
| `allOf`, `anyOf` | n-ary `AND`, `OR`; empty operands become each connective's identity, `TRUE` and `FALSE`, matching the evaluator's own fold | same |
|
|
104
104
|
| `compare` | `>`, `>=`, `<`, `<=`, `=`, `<>` | same |
|
|
105
|
-
| `textCompare` | `=`, `<>`; `matches`/`notMatches` only once `postgresRegexpPushdown` opts in, otherwise refused (see [Regular expressions](#regular-expressions)) | `=`,
|
|
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` |
|
|
106
106
|
| `memberOf` | `IN` / `NOT IN`, one parameter per candidate | same |
|
|
107
107
|
| `exists` | `IS NOT NULL` | same |
|
|
108
108
|
| `reference` | the mapped column, as a quoted identifier | same |
|
|
@@ -191,6 +191,32 @@ Both details are load-bearing rather than stylistic. Returning `null` for a NULL
|
|
|
191
191
|
|
|
192
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.
|
|
193
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
|
+
|
|
194
220
|
## Tests
|
|
195
221
|
|
|
196
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": {
|
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": {
|
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,11 +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
|
}
|
|
214
|
-
|
|
216
|
+
const dialect = options?.dialect ?? "postgres";
|
|
217
|
+
if (dialect === "postgres" && (node.op === "matches" || node.op === "notMatches") && options?.postgresRegexpPushdown !== true) return {
|
|
215
218
|
kind: node.kind,
|
|
216
219
|
path,
|
|
217
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'`
|
|
218
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
|
+
}
|
|
219
240
|
return;
|
|
220
241
|
}
|
|
221
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,11 +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
|
}
|
|
213
|
-
|
|
215
|
+
const dialect = options?.dialect ?? "postgres";
|
|
216
|
+
if (dialect === "postgres" && (node.op === "matches" || node.op === "notMatches") && options?.postgresRegexpPushdown !== true) return {
|
|
214
217
|
kind: node.kind,
|
|
215
218
|
path,
|
|
216
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'`
|
|
217
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
|
+
}
|
|
218
239
|
return;
|
|
219
240
|
}
|
|
220
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
|
@@ -56,6 +56,10 @@ interface DialectConfig {
|
|
|
56
56
|
matches: string;
|
|
57
57
|
/** The negated regular-expression match operator `textCompare`'s `notMatches` compiles to. */
|
|
58
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;
|
|
59
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. */
|
|
60
64
|
placeholder: (index: number, castTo: SqlParamType) => string;
|
|
61
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
|
@@ -56,6 +56,10 @@ interface DialectConfig {
|
|
|
56
56
|
matches: string;
|
|
57
57
|
/** The negated regular-expression match operator `textCompare`'s `notMatches` compiles to. */
|
|
58
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;
|
|
59
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. */
|
|
60
64
|
placeholder: (index: number, castTo: SqlParamType) => string;
|
|
61
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": "2.
|
|
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",
|