trilean-sql 2.3.0 → 3.0.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/package.json +10 -20
- package/dist/compile-test-helpers.cjs +0 -76
- package/dist/compile-test-helpers.d.cts +0 -13
- package/dist/compile-test-helpers.d.ts +0 -13
- package/dist/compile-test-helpers.js +0 -69
- package/dist/compile.cjs +0 -287
- package/dist/compile.d.cts +0 -14
- package/dist/errors.cjs +0 -80
- package/dist/errors.d.cts +0 -53
- package/dist/guard-CCet6aaa.cjs +0 -434
- package/dist/guard-test-helpers.cjs +0 -16
- package/dist/guard-test-helpers.d.cts +0 -3
- package/dist/guard-test-helpers.d.ts +0 -3
- package/dist/guard-test-helpers.js +0 -15
- package/dist/guard.cjs +0 -3
- package/dist/guard.d.cts +0 -28
- package/dist/index.cjs +0 -11
- package/dist/index.d.cts +0 -5
- package/dist/options-DOE1_Cwr.cjs +0 -126
- package/dist/options.cjs +0 -5
- package/dist/options.d.cts +0 -97
- package/dist/portable-pattern.cjs +0 -150
- package/dist/portable-pattern.d.cts +0 -17
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
const require_errors = require("./errors.cjs");
|
|
2
|
-
// src/internal/sqlite-instant.ts
|
|
3
|
-
/**
|
|
4
|
-
* How the SQLite dialect reads an instant, in one place.
|
|
5
|
-
*
|
|
6
|
-
* SQLite has no timestamp type, and its date functions read far more than an instant: the text `now` is the present time, a time of day is a date in the year 2000, a number is a Julian day. The evaluator reads none of these. So the SQL decides first, with a shape test that needs no extension, whether a stored value is an instant in exactly one grammar, and only then converts it; any other value is NULL (unknown) whatever the date functions would make of it, and the same grammar is applied to an `instantLiteral` when the tree is compiled.
|
|
7
|
-
*
|
|
8
|
-
* The grammar: four-digit year, `-`, two-digit month, `-`, two-digit day, `T` or one space, two-digit hour, `:`, minute, `:`, second, an optional `.` and one or more fractional digits, then `Z` or a sign, two-digit hours, `:` and two-digit minutes. The value must also be a real moment: a month 1 to 12, a day that exists in that month (so no `02-30`), an hour 0 to 23, a minute and second 0 to 59 (no leap second, no hour 24), and an offset of at most 23:59. Within it SQLite, PostgreSQL and the evaluator (`Date.parse`) read the same instant, to the millisecond; the fraction is truncated to three digits, as `Date.parse` does, and is not rounded as SQLite's own date functions would.
|
|
9
|
-
*/
|
|
10
|
-
/** The characters up to the seconds, in the form SQLite's `GLOB` reads: four digits, `-`, two, `-`, two, `T` or a space, two, `:`, two, `:`, two. */
|
|
11
|
-
const DATE_AND_TIME_SHAPE = "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][T ][0-9][0-9]:[0-9][0-9]:[0-9][0-9]";
|
|
12
|
-
const OFFSET_SHAPE = "[+-][0-9][0-9]:[0-9][0-9]";
|
|
13
|
-
/** The characters before the seconds end, which are the first nineteen of a value in the grammar. */
|
|
14
|
-
const SECONDS_END = 19;
|
|
15
|
-
/** Where the fraction's point, or the zone, starts (1-based). */
|
|
16
|
-
const AFTER_SECONDS = 20;
|
|
17
|
-
/** The width of a numeric offset, `+HH:MM`. */
|
|
18
|
-
const OFFSET_WIDTH = 6;
|
|
19
|
-
const MILLISECONDS_PER_SECOND = 1e3;
|
|
20
|
-
const MILLISECONDS_PER_MINUTE = 6e4;
|
|
21
|
-
const MINUTES_PER_HOUR = 60;
|
|
22
|
-
const FRACTION_DIGITS = 3;
|
|
23
|
-
/**
|
|
24
|
-
* The SQL that reads `column` (an expression of one SQLite value) as whole milliseconds since the epoch, or NULL when it is not an instant in the grammar above. `column` appears many times, so it must be a column reference or a placeholder-free expression.
|
|
25
|
-
*/
|
|
26
|
-
function sqliteInstantColumn(column) {
|
|
27
|
-
const length = `length(${column})`;
|
|
28
|
-
const isZulu = `${column} GLOB '*Z'`;
|
|
29
|
-
const fractionLength = `(${length} - ${String(AFTER_SECONDS)} - CASE WHEN ${isZulu} THEN 1 ELSE ${String(OFFSET_WIDTH)} END)`;
|
|
30
|
-
const zoneStart = `CASE WHEN ${isZulu} THEN ${length} ELSE ${length} - ${String(5)} END`;
|
|
31
|
-
const afterSeconds = `substr(${column}, ${String(AFTER_SECONDS)})`;
|
|
32
|
-
const fractionOnly = `substr(${column}, ${String(21)}, ${fractionLength})`;
|
|
33
|
-
const zoneShape = `(${afterSeconds} = 'Z' OR ${afterSeconds} GLOB '${OFFSET_SHAPE}' OR (substr(${column}, ${String(AFTER_SECONDS)}, 1) = '.' AND ${fractionLength} > 0 AND ${fractionOnly} NOT GLOB '*[^0-9]*' AND (${isZulu} OR ${column} GLOB '*${OFFSET_SHAPE}')))`;
|
|
34
|
-
const shape = `instr(CAST(${column} AS BLOB), x'00') = 0 AND ${column} GLOB '${DATE_AND_TIME_SHAPE}*' AND ${zoneShape}`;
|
|
35
|
-
const dateAndTime = `substr(${column}, 1, ${String(SECONDS_END)})`;
|
|
36
|
-
const real = [
|
|
37
|
-
`strftime('%Y-%m-%d', ${dateAndTime}) = substr(${column}, 1, 10)`,
|
|
38
|
-
`strftime('%s', ${dateAndTime}) IS NOT NULL`,
|
|
39
|
-
`substr(${column}, 12, 2) < '24'`,
|
|
40
|
-
`(${isZulu} OR (substr(${column}, ${zoneStart} + 1, 2) <= '23' AND substr(${column}, ${zoneStart} + 4, 2) <= '59'))`
|
|
41
|
-
].join(" AND ");
|
|
42
|
-
const fraction = `CASE WHEN substr(${column}, ${String(AFTER_SECONDS)}, 1) = '.' THEN CAST(substr(${fractionOnly} || '00', 1, ${String(FRACTION_DIGITS)}) AS INTEGER) ELSE 0 END`;
|
|
43
|
-
const offsetMinutes = `CASE WHEN ${isZulu} THEN 0 ELSE (CASE substr(${column}, ${zoneStart}, 1) WHEN '-' THEN -1 ELSE 1 END) * (CAST(substr(${column}, ${zoneStart} + 1, 2) AS INTEGER) * ${String(MINUTES_PER_HOUR)} + CAST(substr(${column}, ${zoneStart} + 4, 2) AS INTEGER)) END`;
|
|
44
|
-
return `(CASE WHEN ${shape} AND ${real} THEN CAST(strftime('%s', ${dateAndTime}) AS INTEGER) * ${String(MILLISECONDS_PER_SECOND)} + ${fraction} - (${offsetMinutes}) * ${String(MILLISECONDS_PER_MINUTE)} END)`;
|
|
45
|
-
}
|
|
46
|
-
const INSTANT = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})[T ](?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d+))?(?:Z|(?<sign>[+-])(?<zoneHour>\d{2}):(?<zoneMinute>\d{2}))$/u;
|
|
47
|
-
const LAST_HOUR = 23;
|
|
48
|
-
const LAST_MINUTE_OR_SECOND = 59;
|
|
49
|
-
/**
|
|
50
|
-
* The bind value of an `instantLiteral` for SQLite: the whole milliseconds since the epoch of a text in the grammar above, computed from its parts with the rules the SQL applies to a stored value, or `null` (unknown) for any other text.
|
|
51
|
-
*/
|
|
52
|
-
function sqliteInstantParameter(iso) {
|
|
53
|
-
const groups = INSTANT.exec(iso)?.groups;
|
|
54
|
-
if (groups === void 0) return null;
|
|
55
|
-
const part = (name) => Number(groups[name] ?? 0);
|
|
56
|
-
const [year, month, day] = [
|
|
57
|
-
part("year"),
|
|
58
|
-
part("month"),
|
|
59
|
-
part("day")
|
|
60
|
-
];
|
|
61
|
-
const moment = /* @__PURE__ */ new Date(0);
|
|
62
|
-
moment.setUTCFullYear(year, month - 1, day);
|
|
63
|
-
moment.setUTCHours(part("hour"), part("minute"), part("second"), 0);
|
|
64
|
-
if (!(moment.getUTCFullYear() === year && moment.getUTCMonth() === month - 1 && moment.getUTCDate() === day) || part("hour") > LAST_HOUR || part("minute") > LAST_MINUTE_OR_SECOND || part("second") > LAST_MINUTE_OR_SECOND || part("zoneHour") > LAST_HOUR || part("zoneMinute") > LAST_MINUTE_OR_SECOND) return null;
|
|
65
|
-
const milliseconds = Number(`${groups.fraction ?? ""}00`.slice(0, FRACTION_DIGITS));
|
|
66
|
-
const offset = (groups.sign === "-" ? -1 : 1) * (part("zoneHour") * MINUTES_PER_HOUR + part("zoneMinute")) * MILLISECONDS_PER_MINUTE;
|
|
67
|
-
return moment.getTime() + milliseconds - offset;
|
|
68
|
-
}
|
|
69
|
-
// src/options.ts
|
|
70
|
-
/** The PostgreSQL type each declared value kind is cast to. `timestamptz` rather than `timestamp`: trilean's `instant` is an ISO-8601 string that may carry an offset, and parsing one as a naive `timestamp` would silently discard it. */
|
|
71
|
-
const POSTGRES_TYPE_NAME = {
|
|
72
|
-
text: "text",
|
|
73
|
-
number: "double precision",
|
|
74
|
-
boolean: "boolean",
|
|
75
|
-
timestamp: "timestamptz"
|
|
76
|
-
};
|
|
77
|
-
const DIALECT_CONFIG = {
|
|
78
|
-
postgres: {
|
|
79
|
-
matches: "~",
|
|
80
|
-
notMatches: "!~",
|
|
81
|
-
portableMatches: "~",
|
|
82
|
-
portableNotMatches: "!~",
|
|
83
|
-
placeholder: (index, castTo) => `$${String(index)}::${POSTGRES_TYPE_NAME[castTo]}`,
|
|
84
|
-
emptyMemberOfNullSuffix: "::boolean",
|
|
85
|
-
instantColumn: (columnSql) => columnSql,
|
|
86
|
-
instantParameter: (iso) => iso
|
|
87
|
-
},
|
|
88
|
-
sqlite: {
|
|
89
|
-
matches: "REGEXP",
|
|
90
|
-
notMatches: "NOT REGEXP",
|
|
91
|
-
portableMatches: "GLOB",
|
|
92
|
-
portableNotMatches: "NOT GLOB",
|
|
93
|
-
placeholder: () => "?",
|
|
94
|
-
emptyMemberOfNullSuffix: "",
|
|
95
|
-
instantColumn: sqliteInstantColumn,
|
|
96
|
-
instantParameter: sqliteInstantParameter
|
|
97
|
-
}
|
|
98
|
-
};
|
|
99
|
-
/**
|
|
100
|
-
* Refuses a dialect this version does not implement, before anything indexes a per-dialect table with it.
|
|
101
|
-
*
|
|
102
|
-
* Both entry points check their own argument, because both are reachable with a name the type describes but cannot enforce -- a dialect is exactly the sort of value that arrives as a configuration string asserted into the union at the boundary. Left unchecked, that name is not caught anywhere: the compiler reads an operator off `undefined` and throws a `TypeError` naming an internal field, and the guard, whose tables are only consulted for a node it actually objects to, answers "pushable" for a tree the compiler then fails on -- the one thing `findUnpushableNodeKind` exists to decide, decided wrongly.
|
|
103
|
-
*
|
|
104
|
-
* `DIALECT_CONFIG` is the list, rather than a second constant, so implementing a dialect cannot leave this behind.
|
|
105
|
-
*/
|
|
106
|
-
function assertImplementedDialect(dialect) {
|
|
107
|
-
if (!Object.hasOwn(DIALECT_CONFIG, dialect)) throw new require_errors.UnknownDialectError(dialect, Object.keys(DIALECT_CONFIG));
|
|
108
|
-
}
|
|
109
|
-
Object.defineProperty(exports, "DIALECT_CONFIG", {
|
|
110
|
-
enumerable: true,
|
|
111
|
-
get: function() {
|
|
112
|
-
return DIALECT_CONFIG;
|
|
113
|
-
}
|
|
114
|
-
});
|
|
115
|
-
Object.defineProperty(exports, "POSTGRES_TYPE_NAME", {
|
|
116
|
-
enumerable: true,
|
|
117
|
-
get: function() {
|
|
118
|
-
return POSTGRES_TYPE_NAME;
|
|
119
|
-
}
|
|
120
|
-
});
|
|
121
|
-
Object.defineProperty(exports, "assertImplementedDialect", {
|
|
122
|
-
enumerable: true,
|
|
123
|
-
get: function() {
|
|
124
|
-
return assertImplementedDialect;
|
|
125
|
-
}
|
|
126
|
-
});
|
package/dist/options.cjs
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_options = require("./options-DOE1_Cwr.cjs");
|
|
3
|
-
exports.DIALECT_CONFIG = require_options.DIALECT_CONFIG;
|
|
4
|
-
exports.POSTGRES_TYPE_NAME = require_options.POSTGRES_TYPE_NAME;
|
|
5
|
-
exports.assertImplementedDialect = require_options.assertImplementedDialect;
|
package/dist/options.d.cts
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
/** The declared SQL value kind of a mapped column. `"timestamp"` names trilean's `instant` kind, whose values are ISO-8601 strings. */
|
|
2
|
-
export type SqlParamType = "text" | "number" | "boolean" | "timestamp";
|
|
3
|
-
/** The SQL dialects this compiler emits. A dialect is named rather than inferred: the same tree compiles to different text for each, and a caller that never said which one it meant would be relying on whichever happened to be the default. */
|
|
4
|
-
export type SqlDialect = "postgres" | "sqlite";
|
|
5
|
-
/** What a `reference` node's key maps onto in the target schema. */
|
|
6
|
-
export interface SqlColumnBinding {
|
|
7
|
-
/** The column, optionally qualified with a table or schema by dots (`"orders.total"`). Each dot-separated segment is emitted as its own double-quoted identifier, so a segment may contain any character except a dot itself. */
|
|
8
|
-
column: string;
|
|
9
|
-
/**
|
|
10
|
-
* The column's value kind, if the caller knows it. Optional, and worth supplying: it is the only thing that lets the compiler check a comparison against the column for the kind mismatches trilean itself treats as `wrong-type` -- comparing a text column with `compare` rather than `textCompare`, ordering a boolean, comparing a number against an instant. Left undeclared, those comparisons compile, and the database may coerce its way to a definite answer where trilean would have returned indeterminate.
|
|
11
|
-
*
|
|
12
|
-
* It does not affect the emitted SQL, only whether the comparison is emitted at all. Every literal placeholder is already cast to the type its own trilean kind implies (in the dialects that cast at all), and a comparison that survives the check is one whose operand kinds agree, so there is nothing left for the column's declared kind to change.
|
|
13
|
-
*/
|
|
14
|
-
paramType?: SqlParamType;
|
|
15
|
-
}
|
|
16
|
-
export interface SqlCollectionBinding {
|
|
17
|
-
/** The correlated child table, dot-qualified exactly like `SqlColumnBinding.column` -- each dot-separated segment is emitted as its own double-quoted identifier. */
|
|
18
|
-
table: string;
|
|
19
|
-
/** Raw boolean SQL relating one row of `table` to the outer row, e.g. `"attrs"."nodeId" = "graph_nodes"."id" AND "attrs"."attrName" = 'voltageLevel'`. Caller-authored rather than assembled from a join-column pair, because only the caller knows the real join shape -- a single FK, a composite key, or (the EAV driving case) an FK plus a literal discriminator. */
|
|
20
|
-
join: string;
|
|
21
|
-
/** Resolves a reference key *inside* this collection's `item`/`filter` -- swapped in for the outer `columnFor` while compiling them, mirroring how trilean's own evaluator re-points `EvaluationContext` at the collection item (see `evaluator.ts`'s `resolveParticipatingItems`). */
|
|
22
|
-
columnFor: (referenceKey: string) => SqlColumnBinding;
|
|
23
|
-
}
|
|
24
|
-
export interface SqlCompileOptions {
|
|
25
|
-
/** Which dialect to emit. It is a required field rather than a default so that a caller states the engine it is compiling for, instead of inheriting whichever one this package happened to implement first. */
|
|
26
|
-
dialect: SqlDialect;
|
|
27
|
-
/**
|
|
28
|
-
* Maps a `reference` node's key onto a column. Called once per reference occurrence.
|
|
29
|
-
*
|
|
30
|
-
* Only string reference keys reach it: trilean allows any JSON value as a key, and a non-string one is refused as unpushable before this is called. Throwing from here is how a caller rejects a key it has no column for -- the exception propagates out of `compilePredicateNode` unchanged, rather than being wrapped or swallowed.
|
|
31
|
-
*/
|
|
32
|
-
columnFor: (referenceKey: string) => SqlColumnBinding;
|
|
33
|
-
/**
|
|
34
|
-
* Maps a `some`/`every`/`fold` node's `collection` key onto a correlated table. Called once per collection occurrence.
|
|
35
|
-
*
|
|
36
|
-
* Only string collection keys reach it, for the same reason only string reference keys reach `columnFor`. A tree that never uses `some`, `every`, or `fold(max|min)` never calls this -- leaving it unset is fully backward compatible. A tree that does use one of those kinds without this set is refused with `UnsupportedNodeError`, the same refused outcome those kinds already had before this option existed. `fold(reduce)` is refused unconditionally regardless of this option: it threads an arbitrary combine expression through the collection in a caller-chosen order, which has no general SQL translation.
|
|
37
|
-
*/
|
|
38
|
-
collectionFor?: (collectionKey: string) => SqlCollectionBinding;
|
|
39
|
-
/**
|
|
40
|
-
* 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.
|
|
41
|
-
*
|
|
42
|
-
* 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.
|
|
43
|
-
*/
|
|
44
|
-
sqliteRegexpAvailable?: boolean;
|
|
45
|
-
/**
|
|
46
|
-
* Whether `matches`/`notMatches` may compile to PostgreSQL's own `~`/`!~` operators. Ignored under the SQLite dialect, whose `REGEXP` question is `sqliteRegexpAvailable`'s above.
|
|
47
|
-
*
|
|
48
|
-
* 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.
|
|
49
|
-
*
|
|
50
|
-
* 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.
|
|
51
|
-
*/
|
|
52
|
-
postgresRegexpPushdown?: boolean;
|
|
53
|
-
}
|
|
54
|
-
export interface CompiledSql {
|
|
55
|
-
/** 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. */
|
|
56
|
-
sql: string;
|
|
57
|
-
/** Positional parameters, in emission order, to pass alongside `sql`. Every caller-supplied literal in the tree is here; none is ever written into `sql`. */
|
|
58
|
-
params: unknown[];
|
|
59
|
-
}
|
|
60
|
-
/** The PostgreSQL type each declared value kind is cast to. `timestamptz` rather than `timestamp`: trilean's `instant` is an ISO-8601 string that may carry an offset, and parsing one as a naive `timestamp` would silently discard it. */
|
|
61
|
-
export declare const POSTGRES_TYPE_NAME: Readonly<Record<SqlParamType, string>>;
|
|
62
|
-
/**
|
|
63
|
-
* Everything about the emitted SQL that is a property of the dialect rather than of the tree.
|
|
64
|
-
*
|
|
65
|
-
* It is deliberately this small. Most of what the compiler emits is ANSI-standard and identical in both engines -- the six comparison operators, `=` and `<>` for `textCompare`'s `equals`/`notEquals`, `AND`/`OR`/`NOT`, `IN`/`NOT IN`, `IS NOT NULL`, and double-quoted identifiers with an embedded quote doubled -- so branching on the dialect anywhere else would be a branch that can never change the output. Three things genuinely differ, and they are the three fields below.
|
|
66
|
-
*/
|
|
67
|
-
export interface DialectConfig {
|
|
68
|
-
/** The regular-expression match operator `textCompare`'s `matches` compiles to. */
|
|
69
|
-
matches: string;
|
|
70
|
-
/** The negated regular-expression match operator `textCompare`'s `notMatches` compiles to. */
|
|
71
|
-
notMatches: string;
|
|
72
|
-
/** 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. */
|
|
73
|
-
portableMatches: string;
|
|
74
|
-
/** The negated counterpart of `portableMatches`. */
|
|
75
|
-
portableNotMatches: string;
|
|
76
|
-
/** 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. */
|
|
77
|
-
placeholder: (index: number, castTo: SqlParamType) => string;
|
|
78
|
-
/** 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. */
|
|
79
|
-
emptyMemberOfNullSuffix: string;
|
|
80
|
-
/**
|
|
81
|
-
* Renders an instant-valued column expression as the value the dialect compares. PostgreSQL's `timestamptz` already is a point in time and needs nothing; SQLite holds an instant as text in whatever form the writer chose (an offset, a `Z`, any number of fractional digits), and text compares by its characters rather than by the instant, so the text is read as a point in time first: whole milliseconds since the epoch, as an integer.
|
|
82
|
-
*/
|
|
83
|
-
instantColumn: (columnSql: string) => string;
|
|
84
|
-
/**
|
|
85
|
-
* The bind value of an `instantLiteral`, for a comparison the dialect makes with {@link DialectConfig.instantColumn}. PostgreSQL parses the text itself and casts it. SQLite compares milliseconds since the epoch, read from a text in the one grammar of `internal/sqlite-instant.ts`; a text outside the grammar of `internal/sqlite-instant.ts` is `null`, which makes the comparison unknown.
|
|
86
|
-
*/
|
|
87
|
-
instantParameter: (iso: string) => unknown;
|
|
88
|
-
}
|
|
89
|
-
export declare const DIALECT_CONFIG: Readonly<Record<SqlDialect, DialectConfig>>;
|
|
90
|
-
/**
|
|
91
|
-
* Refuses a dialect this version does not implement, before anything indexes a per-dialect table with it.
|
|
92
|
-
*
|
|
93
|
-
* Both entry points check their own argument, because both are reachable with a name the type describes but cannot enforce -- a dialect is exactly the sort of value that arrives as a configuration string asserted into the union at the boundary. Left unchecked, that name is not caught anywhere: the compiler reads an operator off `undefined` and throws a `TypeError` naming an internal field, and the guard, whose tables are only consulted for a node it actually objects to, answers "pushable" for a tree the compiler then fails on -- the one thing `findUnpushableNodeKind` exists to decide, decided wrongly.
|
|
94
|
-
*
|
|
95
|
-
* `DIALECT_CONFIG` is the list, rather than a second constant, so implementing a dialect cannot leave this behind.
|
|
96
|
-
*/
|
|
97
|
-
export declare function assertImplementedDialect(dialect: SqlDialect): void;
|
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
// 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
|
-
* @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
|
-
* @throws `PortablePatternUnsupportedError` if `node` uses any construct outside the reachable subset.
|
|
142
|
-
*/
|
|
143
|
-
function renderSqliteGlobPattern(node) {
|
|
144
|
-
const plan = planGlobBody(node);
|
|
145
|
-
const body = plan.body.map((atom) => renderGlobAtom(atom)).join("");
|
|
146
|
-
return `${plan.anchoredStart ? "" : "*"}${body}${plan.anchoredEnd ? "" : "*"}`.replaceAll(/\*{2,}/g, "*");
|
|
147
|
-
}
|
|
148
|
-
exports.PortablePatternUnsupportedError = PortablePatternUnsupportedError;
|
|
149
|
-
exports.renderPostgresPattern = renderPostgresPattern;
|
|
150
|
-
exports.renderSqliteGlobPattern = renderSqliteGlobPattern;
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { RegexNode } from "trilean-regex";
|
|
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
|
-
export declare class PortablePatternUnsupportedError extends Error {}
|
|
6
|
-
/**
|
|
7
|
-
* Translates a `trilean-regex` AST into PostgreSQL's own Advanced Regular Expression syntax, for binding as the pattern argument to `~`/`!~`.
|
|
8
|
-
*
|
|
9
|
-
* 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.)
|
|
10
|
-
* @throws `PortablePatternUnsupportedError` if a bounded repetition exceeds PostgreSQL's own 0-255 bound limit.
|
|
11
|
-
*/
|
|
12
|
-
export declare function renderPostgresPattern(node: RegexNode): string;
|
|
13
|
-
/**
|
|
14
|
-
* 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.
|
|
15
|
-
* @throws `PortablePatternUnsupportedError` if `node` uses any construct outside the reachable subset.
|
|
16
|
-
*/
|
|
17
|
-
export declare function renderSqliteGlobPattern(node: RegexNode): string;
|