@lunora/sql-store 1.0.0-alpha.20 → 1.0.0-alpha.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -103,3 +103,9 @@ Unless required by applicable law or agreed to in writing, software distributed
103
103
  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
104
  CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
105
  specific language governing permissions and limitations under the License.
106
+
107
+ <!-- DEPENDENCIES -->
108
+ <!-- /DEPENDENCIES -->
109
+
110
+ <!-- TYPE_DEPENDENCIES -->
111
+ <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -57,12 +57,13 @@ hand-rolled rewriting.
57
57
 
58
58
  The small per-engine `SqlDialect` value object carries only what drizzle can't
59
59
  infer from a dynamic, column-per-field schema: the framework columns every
60
- global table carries, column and companion-table types, value encode/decode
61
- (every engine stores SQLite-shaped values), `RETURNING` availability (with an
62
- affected-rows fallback for MySQL), unique-violation detection, the MySQL index
63
- key-prefix, and the system-catalog (`tableExists`) probe. Full-text search is
64
- not part of the dialect — the core probes FTS5 availability on the `exec` at
65
- runtime.
60
+ global table carries, column and companion-table types, `RETURNING` availability
61
+ (with an affected-rows fallback for MySQL), unique-violation detection, the MySQL index
62
+ key-prefix, and the system-catalog (`tableExists`) probe. The value codec is
63
+ **not** a dialect member — every engine stores SQLite-shaped values through the
64
+ core's own `sqliteEncode`/`sqliteDecode`. Full-text search is declared, not
65
+ probed: the dialect carries `supportsFts5`, and the core picks the FTS5 or
66
+ portable inverted-index layout from it.
66
67
 
67
68
  Reactivity is engine-independent: the writer is injected as `globalDb` into
68
69
  `createShardCtxDb`, whose `broadcast` hook drives live queries no matter which
@@ -83,8 +84,9 @@ seam from the root); consumers import everything from the root `@lunora/sql-stor
83
84
  - Migration runners (each takes `(exec, schema, dialect)`, or `(exec, dialect)`
84
85
  for CDC): `runSqlGlobalTableMigrations`, `runSqlAggregateMigrations`,
85
86
  `runSqlRankMigrations`, `runSqlSearchMigrations`, `runSqlCdcMigration`.
86
- - CDC log helpers: `readSqlCdcChanges`, `trimSqlCdcChanges`.
87
- - Value codec building blocks a dialect reuses for `encode`/`decode`:
87
+ - CDC log helpers: `readSqlCdcChanges`, `readSqlCdcChangedTables`,
88
+ `readSqlCdcFloor`, `sweepSqlCdcRetention`.
89
+ - Value codec building blocks (the core runs these on every engine):
88
90
  `sqliteEncode`, `sqliteDecode`, `decodeBigint`, `tryJsonParse`,
89
91
  `effectiveColumnKind`.
90
92
  - Types: `SqlCtxDbOptions`, `SqlCtxExec`, `SqlDialect`, `SqlExec`,
@@ -1,3 +1,4 @@
1
+ import { RenderedSql } from '@lunora/shard-engine';
1
2
  import { SQL } from 'drizzle-orm';
2
3
  /** Outcome of a non-`SELECT` statement: the row count it changed (for MySQL OCC, which lacks `RETURNING`). */
3
4
  interface SqlRunResult {
@@ -5,20 +6,50 @@ interface SqlRunResult {
5
6
  rowsAffected: number;
6
7
  }
7
8
  /**
8
- * The async SQL surface the store core consumes. Satisfied by a
9
- * `D1Session`/`D1Client` (D1), a `node:sqlite` adapter (tests), or a
10
- * Hyperdrive-backed `postgres`/`pg`/`mysql2` driver (PlanetScale).
11
- *
12
- * `all` runs a row-returning statement (incl. `... RETURNING ...`); `run` runs a
13
- * write and reports `rowsAffected` — the matched-rows count that drives the
14
- * MySQL optimistic-concurrency guard (which has no `RETURNING`).
15
- *
16
- * Note: companion writes (aggregate/rank/FTS/CDC) run as separate sequential
17
- * statements after the row write on every engine, so they share D1's
18
- * at-least-once caveat — there is no cross-statement transaction here.
19
- */
9
+ * The async SQL surface the store core consumes. Satisfied by a
10
+ * `D1Session`/`D1Client` (D1), a `node:sqlite` adapter (tests), or a
11
+ * Hyperdrive-backed `postgres`/`pg`/`mysql2` driver (PlanetScale).
12
+ *
13
+ * `all` runs a row-returning statement (incl. `... RETURNING ...`); `run` runs a
14
+ * write and reports `rowsAffected` — the matched-rows count that drives the
15
+ * MySQL optimistic-concurrency guard (which has no `RETURNING`).
16
+ *
17
+ * Note: companion writes (aggregate/rank/FTS/CDC) run as separate sequential
18
+ * statements after the row write on every engine, so they share D1's
19
+ * at-least-once caveat — there is no cross-statement transaction here.
20
+ */
20
21
  interface SqlExec {
21
22
  all: (sql: string, params: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
23
+ /**
24
+ * Optional: run several write statements as one round trip instead of
25
+ * `run()` called once per statement in sequence. Statements MUST be
26
+ * mutually independent — an implementation MAY reorder or parallelize
27
+ * across elements, so callers must never rely on array order between
28
+ * elements (e.g. a purge-then-insert pair belongs in separate sequential
29
+ * `queryRun`/`run` calls, not one `batch`).
30
+ *
31
+ * Absent, the store core falls back to its historical sequential `run()`
32
+ * loop, so an exec that doesn't implement this keeps working unchanged.
33
+ *
34
+ * D1's `client.batch` executes the whole array atomically (all-or-nothing)
35
+ * in one request, preserving array order — an actual atomicity improvement
36
+ * over the sequential fallback, not just a round-trip one. The Hyperdrive
37
+ * `postgres`/`pg` adapters instead dispatch every statement concurrently
38
+ * (`Promise.all`) over the same connection/pool rather than awaiting each
39
+ * in turn — still "at-least-once, non-atomic" like the fallback, but no
40
+ * longer serialized one full RTT at a time, and with no ordering between
41
+ * elements. Safe only for statements whose effects don't depend on each
42
+ * other (distinct-keyed rows), which is what every current caller batches.
43
+ *
44
+ * The one exception is the `sqlite` dialect, whose engines ship FTS5: there
45
+ * an implementation MUST run the array in order, as one transaction, as
46
+ * D1's does. The FTS5 search companion's writes are ordered statement
47
+ * lists that must not interleave with another writer's (`runInOrder`).
48
+ */
49
+ batch?: (statements: ReadonlyArray<{
50
+ params: ReadonlyArray<unknown>;
51
+ sql: string;
52
+ }>) => Promise<void>;
22
53
  run: (sql: string, params: ReadonlyArray<unknown>) => Promise<SqlRunResult>;
23
54
  }
24
55
  /** Everything engine-specific the store core needs. One value per engine; `sqliteDialect` (in `@lunora/d1`) is the reference, Postgres/MySQL live in `@lunora/hyperdrive/global`. */
@@ -26,19 +57,38 @@ interface SqlDialect {
26
57
  /** Affected-rows extractor for the OCC fallback when `supportsReturning` is false (MySQL). */
27
58
  affectedRows?: (result: SqlRunResult) => number;
28
59
  /**
29
- * Storage SQL column type for a validator `kind`. SQLite affinity
30
- * (`TEXT`/`INTEGER`/`REAL`/`BLOB`); Postgres `TEXT`/`DOUBLE PRECISION`/
31
- * `BOOLEAN`/`JSONB`/`BYTEA`; MySQL `VARCHAR(255)`/`TEXT`/`DOUBLE`/
32
- * `TINYINT(1)`/`JSON`/`LONGBLOB`.
33
- */
34
- columnType: (kind: string | undefined) => string;
60
+ * Storage SQL column type for a validator `kind`. Every engine stores
61
+ * SQLite-shaped values (see `value-codec.ts`), so the types are the ones
62
+ * those forms fit, not the engine's richest equivalent:
63
+ *
64
+ * - SQLite affinity: `TEXT`/`INTEGER`/`REAL`/`BLOB`.
65
+ * - Postgres: `DOUBLE PRECISION` (number/date/timestamp), `BYTEA` (bytes),
66
+ * `INTEGER` (boolean, stored 1/0), `TEXT` for everything else — including
67
+ * the composites, which are JSON text rather than `JSONB`.
68
+ * - MySQL: `DOUBLE`, `LONGBLOB`, `TINYINT`, `VARCHAR(64)` (bigint as a
69
+ * decimal string), and `LONGTEXT` for everything else — strings unbounded
70
+ * so they never truncate, composites because their wire-marked form is not
71
+ * valid JSON and a `JSON` column would reject it on insert.
72
+ *
73
+ * `unique` says the column carries a `.unique()` constraint, so the type has
74
+ * to be one the engine can index in FULL. It exists for MySQL: InnoDB cannot
75
+ * index a `LONGTEXT` without a key prefix, and a prefixed UNIQUE index
76
+ * enforces uniqueness of the PREFIX — two distinct 200-character emails
77
+ * sharing their first 191 characters collided as a duplicate. A bounded
78
+ * `VARCHAR` indexes whole, so the constraint means what it says; a value
79
+ * past the bound is a loud write error rather than a wrong conflict. SQLite
80
+ * and Postgres index text of any length and ignore the flag.
81
+ */
82
+ columnType: (kind: string | undefined, options?: {
83
+ unique?: boolean;
84
+ }) => string;
35
85
  /**
36
- * Engine SQL types for the **internal companion tables** (aggregate / rank /
37
- * CDC), which are built from raw SQL types, not validator kinds. SQLite uses
38
- * `TEXT`/`REAL`/`INTEGER`/`BLOB` and `INTEGER PRIMARY KEY AUTOINCREMENT`;
39
- * Postgres `TEXT`/`DOUBLE PRECISION`/`INTEGER`/`BYTEA` + `BIGSERIAL`; MySQL
40
- * needs a bounded `VARCHAR` key, `DOUBLE`, `LONGBLOB`, `AUTO_INCREMENT`.
41
- */
86
+ * Engine SQL types for the **internal companion tables** (aggregate / rank /
87
+ * CDC), which are built from raw SQL types, not validator kinds. SQLite uses
88
+ * `TEXT`/`REAL`/`INTEGER`/`BLOB` and `INTEGER PRIMARY KEY AUTOINCREMENT`;
89
+ * Postgres `TEXT`/`DOUBLE PRECISION`/`INTEGER`/`BYTEA` + `BIGSERIAL`; MySQL
90
+ * needs a bounded `VARCHAR` key, `DOUBLE`, `LONGBLOB`, `AUTO_INCREMENT`.
91
+ */
42
92
  companionTypes: {
43
93
  autoincrementPrimaryKey: string;
44
94
  integer: string;
@@ -46,37 +96,110 @@ interface SqlDialect {
46
96
  real: string;
47
97
  text: string;
48
98
  };
49
- /** Map a stored value back to its JS form, by effective validator `kind` (inverse of `encode`). */
50
- decode: (value: unknown, kind: string | undefined) => unknown;
51
- /** Map a JS value to its bound storage form (boolean→1/0, bigint→string, object→JSON on SQLite; mostly native on PG). */
52
- encode: (value: unknown) => unknown;
53
99
  /** The framework columns every global table carries — the `id` primary key and `_creationTime` — as `{ name, type }` so the DDL builder can quote each name through the engine's dialect. */
54
100
  frameworkColumns: () => ReadonlyArray<{
55
101
  name: string;
56
102
  type: string;
57
103
  }>;
58
104
  /**
59
- * Optional: the key-prefix length an indexed column of this `kind` needs.
60
- * MySQL/InnoDB can't index a `TEXT`/`LONGTEXT`/`BLOB` column without a prefix
61
- * (the store appends `(&lt;n>)` to the column reference); SQLite/Postgres index
62
- * text columns directly and omit this hook (or return `undefined`). `kind` is
63
- * the column's effective validator kind.
64
- */
105
+ * Optional: the key-prefix length an indexed column of this `kind` needs.
106
+ * MySQL/InnoDB can't index a `TEXT`/`LONGTEXT`/`BLOB` column without a prefix
107
+ * (the store appends `(<n>)` to the column reference); SQLite/Postgres index
108
+ * text columns directly and omit this hook (or return `undefined`). `kind` is
109
+ * the column's effective validator kind.
110
+ */
65
111
  indexKeyPrefix?: (kind: string | undefined) => number | undefined;
66
112
  /** True when an `error` thrown by a write is a UNIQUE-constraint breach (mapped to a 409 ConflictError). */
67
113
  isUniqueViolation: (error: unknown) => boolean;
68
- /** A short engine tag for diagnostics/branching (`"sqlite" | "postgres" | "mysql"`). The store core selects drizzle's matching dialect for rendering off this. */
114
+ /**
115
+ * Most columns one table may carry on this engine, framework columns
116
+ * included. Omit it and the DDL builder does not check — the right answer
117
+ * for an engine whose ceiling is high enough that no real schema reaches it.
118
+ *
119
+ * Declared because the ceilings differ by more than an order of magnitude:
120
+ * D1 runs Workerd's SQLite build, which caps a table at 100 columns, where
121
+ * Postgres allows 1,600 and MySQL 4,096. A fixed number here would either
122
+ * miss the D1 failure or reject schemas the other two engines run happily.
123
+ */
124
+ maxTableColumns?: number;
125
+ /** A short engine tag for diagnostics/branching (`"sqlite" | "postgres" | "mysql"`). */
69
126
  readonly name: "mysql" | "postgres" | "sqlite";
127
+ /**
128
+ * Optional: the engine's own full-text index, opted into per search index
129
+ * with `.searchIndex({ strategy: "native" })`.
130
+ *
131
+ * Only Postgres supplies one today (`tsvector` + GIN + `to_tsquery`). It
132
+ * scales sublinearly where the portable inverted companion aggregates every
133
+ * matching token row, but it ranks with the engine's formula rather than the
134
+ * shared scorer — which is why it is opt-in and why the parity suite asserts
135
+ * matching, not order, for indexes that use it.
136
+ *
137
+ * Recall still matches the portable path: the stored form is built from the
138
+ * tokens Lunora's analyzer already produced, under a configuration that adds
139
+ * no stemming or stopwords of the engine's own.
140
+ *
141
+ * Every member returns a *statement*, not a fragment, so no engine grammar
142
+ * reaches the store core: Postgres matches with `@@` against a `tsvector`
143
+ * column while MySQL would use `MATCH … AGAINST` against a text column, and
144
+ * both fit here without the caller knowing which.
145
+ */
146
+ nativeTextSearch?: {
147
+ /** DDL for the companion table holding the engine's indexed form, keyed by document id. */
148
+ createCompanion: (companion: string, keyType: string) => SQL;
149
+ /** DDL for the indexes that make the match fast. */
150
+ createIndexes: (companion: string) => SQL[];
151
+ /**
152
+ * Replace one document's row, given its already-analyzed token stream,
153
+ * only where `guard` holds. One idempotent statement: two writers of one
154
+ * id converge on one row, never raise a key conflict, and a writer whose
155
+ * `guard` fails writes nothing.
156
+ */
157
+ indexDocument: (companion: string, id: string, analyzed: string, guard: SQL) => SQL;
158
+ /** The `WHERE` predicate matching a query's analyzed terms, final term as a prefix. */
159
+ matches: (companion: string, terms: ReadonlyArray<string>) => SQL;
160
+ /** The `ORDER BY` expression, best first. */
161
+ rank: (companion: string, terms: ReadonlyArray<string>) => SQL;
162
+ };
163
+ /** Render a composable drizzle `SQL` to this engine's `{ sql, params }`. Each dialect imports only its own drizzle dialect, so a bundle carries one engine's renderer. */
164
+ render: (query: SQL) => RenderedSql;
165
+ /**
166
+ * How an operator completes a search index that is still backfilling on
167
+ * this backend, in words, for the refusal a read against it raises: each
168
+ * backend's entry point differs. Absent, the refusal says only to retry
169
+ * once the backfill finishes.
170
+ */
171
+ searchBackfillHint?: string;
172
+ /**
173
+ * True when the engine ships SQLite's FTS5 module, which decides whether a
174
+ * search index is stored as an FTS5 shadow or as the portable inverted
175
+ * companion.
176
+ *
177
+ * A static property of the engine, so it is declared rather than probed:
178
+ * the previous `CREATE VIRTUAL TABLE` capability probe spent a round trip
179
+ * (and an error in the database's log) on every fresh connection to
180
+ * rediscover something the dialect already knows. Tests that want the
181
+ * portable layout override this instead of intercepting SQL strings.
182
+ */
183
+ supportsFts5: boolean;
70
184
  /** True when the engine supports `UPDATE/DELETE ... RETURNING` (SQLite/PG yes, MySQL no → use `affectedRows`). */
71
185
  supportsReturning: boolean;
72
186
  /**
73
- * The catalog probe for whether a physical `table` exists — backs the opt-in
74
- * companion-table (`__agg_`/`__rank_`) existence checks. Returns a drizzle
75
- * {@link SQL} (a non-empty result ⇒ the table exists) so it renders through
76
- * the same per-engine path as every other statement, never a hand-built
77
- * placeholder string. SQLite reads `sqlite_master`; Postgres/MySQL read
78
- * `information_schema.tables`.
79
- */
187
+ * The catalog probe for whether a physical `table` exists — backs the opt-in
188
+ * companion-table (`__agg_`/`__rank_`) existence checks. Returns a drizzle
189
+ * {@link SQL} (a non-empty result ⇒ the table exists) so it renders through
190
+ * the same per-engine path as every other statement, never a hand-built
191
+ * placeholder string. SQLite reads `sqlite_master`; Postgres/MySQL read
192
+ * `information_schema.tables`.
193
+ */
80
194
  tableExists: (table: string) => SQL;
195
+ /**
196
+ * Optional: btree operator class appended to an indexed text column so a
197
+ * `LIKE 'prefix%'` scan can use the index whatever the database collation.
198
+ * Postgres needs `text_pattern_ops` (a default `text_ops` btree built under
199
+ * e.g. `en_US.UTF-8` is useless to `LIKE`); SQLite and MySQL index prefix
200
+ * matches off the plain index and omit this. Only the search companion's
201
+ * token index reads it.
202
+ */
203
+ textPatternOperatorClass?: string;
81
204
  }
82
205
  export { SqlDialect, SqlExec, SqlRunResult };
package/dist/dialect.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { RenderedSql } from '@lunora/shard-engine';
1
2
  import { SQL } from 'drizzle-orm';
2
3
  /** Outcome of a non-`SELECT` statement: the row count it changed (for MySQL OCC, which lacks `RETURNING`). */
3
4
  interface SqlRunResult {
@@ -5,20 +6,50 @@ interface SqlRunResult {
5
6
  rowsAffected: number;
6
7
  }
7
8
  /**
8
- * The async SQL surface the store core consumes. Satisfied by a
9
- * `D1Session`/`D1Client` (D1), a `node:sqlite` adapter (tests), or a
10
- * Hyperdrive-backed `postgres`/`pg`/`mysql2` driver (PlanetScale).
11
- *
12
- * `all` runs a row-returning statement (incl. `... RETURNING ...`); `run` runs a
13
- * write and reports `rowsAffected` — the matched-rows count that drives the
14
- * MySQL optimistic-concurrency guard (which has no `RETURNING`).
15
- *
16
- * Note: companion writes (aggregate/rank/FTS/CDC) run as separate sequential
17
- * statements after the row write on every engine, so they share D1's
18
- * at-least-once caveat — there is no cross-statement transaction here.
19
- */
9
+ * The async SQL surface the store core consumes. Satisfied by a
10
+ * `D1Session`/`D1Client` (D1), a `node:sqlite` adapter (tests), or a
11
+ * Hyperdrive-backed `postgres`/`pg`/`mysql2` driver (PlanetScale).
12
+ *
13
+ * `all` runs a row-returning statement (incl. `... RETURNING ...`); `run` runs a
14
+ * write and reports `rowsAffected` — the matched-rows count that drives the
15
+ * MySQL optimistic-concurrency guard (which has no `RETURNING`).
16
+ *
17
+ * Note: companion writes (aggregate/rank/FTS/CDC) run as separate sequential
18
+ * statements after the row write on every engine, so they share D1's
19
+ * at-least-once caveat — there is no cross-statement transaction here.
20
+ */
20
21
  interface SqlExec {
21
22
  all: (sql: string, params: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
23
+ /**
24
+ * Optional: run several write statements as one round trip instead of
25
+ * `run()` called once per statement in sequence. Statements MUST be
26
+ * mutually independent — an implementation MAY reorder or parallelize
27
+ * across elements, so callers must never rely on array order between
28
+ * elements (e.g. a purge-then-insert pair belongs in separate sequential
29
+ * `queryRun`/`run` calls, not one `batch`).
30
+ *
31
+ * Absent, the store core falls back to its historical sequential `run()`
32
+ * loop, so an exec that doesn't implement this keeps working unchanged.
33
+ *
34
+ * D1's `client.batch` executes the whole array atomically (all-or-nothing)
35
+ * in one request, preserving array order — an actual atomicity improvement
36
+ * over the sequential fallback, not just a round-trip one. The Hyperdrive
37
+ * `postgres`/`pg` adapters instead dispatch every statement concurrently
38
+ * (`Promise.all`) over the same connection/pool rather than awaiting each
39
+ * in turn — still "at-least-once, non-atomic" like the fallback, but no
40
+ * longer serialized one full RTT at a time, and with no ordering between
41
+ * elements. Safe only for statements whose effects don't depend on each
42
+ * other (distinct-keyed rows), which is what every current caller batches.
43
+ *
44
+ * The one exception is the `sqlite` dialect, whose engines ship FTS5: there
45
+ * an implementation MUST run the array in order, as one transaction, as
46
+ * D1's does. The FTS5 search companion's writes are ordered statement
47
+ * lists that must not interleave with another writer's (`runInOrder`).
48
+ */
49
+ batch?: (statements: ReadonlyArray<{
50
+ params: ReadonlyArray<unknown>;
51
+ sql: string;
52
+ }>) => Promise<void>;
22
53
  run: (sql: string, params: ReadonlyArray<unknown>) => Promise<SqlRunResult>;
23
54
  }
24
55
  /** Everything engine-specific the store core needs. One value per engine; `sqliteDialect` (in `@lunora/d1`) is the reference, Postgres/MySQL live in `@lunora/hyperdrive/global`. */
@@ -26,19 +57,38 @@ interface SqlDialect {
26
57
  /** Affected-rows extractor for the OCC fallback when `supportsReturning` is false (MySQL). */
27
58
  affectedRows?: (result: SqlRunResult) => number;
28
59
  /**
29
- * Storage SQL column type for a validator `kind`. SQLite affinity
30
- * (`TEXT`/`INTEGER`/`REAL`/`BLOB`); Postgres `TEXT`/`DOUBLE PRECISION`/
31
- * `BOOLEAN`/`JSONB`/`BYTEA`; MySQL `VARCHAR(255)`/`TEXT`/`DOUBLE`/
32
- * `TINYINT(1)`/`JSON`/`LONGBLOB`.
33
- */
34
- columnType: (kind: string | undefined) => string;
60
+ * Storage SQL column type for a validator `kind`. Every engine stores
61
+ * SQLite-shaped values (see `value-codec.ts`), so the types are the ones
62
+ * those forms fit, not the engine's richest equivalent:
63
+ *
64
+ * - SQLite affinity: `TEXT`/`INTEGER`/`REAL`/`BLOB`.
65
+ * - Postgres: `DOUBLE PRECISION` (number/date/timestamp), `BYTEA` (bytes),
66
+ * `INTEGER` (boolean, stored 1/0), `TEXT` for everything else — including
67
+ * the composites, which are JSON text rather than `JSONB`.
68
+ * - MySQL: `DOUBLE`, `LONGBLOB`, `TINYINT`, `VARCHAR(64)` (bigint as a
69
+ * decimal string), and `LONGTEXT` for everything else — strings unbounded
70
+ * so they never truncate, composites because their wire-marked form is not
71
+ * valid JSON and a `JSON` column would reject it on insert.
72
+ *
73
+ * `unique` says the column carries a `.unique()` constraint, so the type has
74
+ * to be one the engine can index in FULL. It exists for MySQL: InnoDB cannot
75
+ * index a `LONGTEXT` without a key prefix, and a prefixed UNIQUE index
76
+ * enforces uniqueness of the PREFIX — two distinct 200-character emails
77
+ * sharing their first 191 characters collided as a duplicate. A bounded
78
+ * `VARCHAR` indexes whole, so the constraint means what it says; a value
79
+ * past the bound is a loud write error rather than a wrong conflict. SQLite
80
+ * and Postgres index text of any length and ignore the flag.
81
+ */
82
+ columnType: (kind: string | undefined, options?: {
83
+ unique?: boolean;
84
+ }) => string;
35
85
  /**
36
- * Engine SQL types for the **internal companion tables** (aggregate / rank /
37
- * CDC), which are built from raw SQL types, not validator kinds. SQLite uses
38
- * `TEXT`/`REAL`/`INTEGER`/`BLOB` and `INTEGER PRIMARY KEY AUTOINCREMENT`;
39
- * Postgres `TEXT`/`DOUBLE PRECISION`/`INTEGER`/`BYTEA` + `BIGSERIAL`; MySQL
40
- * needs a bounded `VARCHAR` key, `DOUBLE`, `LONGBLOB`, `AUTO_INCREMENT`.
41
- */
86
+ * Engine SQL types for the **internal companion tables** (aggregate / rank /
87
+ * CDC), which are built from raw SQL types, not validator kinds. SQLite uses
88
+ * `TEXT`/`REAL`/`INTEGER`/`BLOB` and `INTEGER PRIMARY KEY AUTOINCREMENT`;
89
+ * Postgres `TEXT`/`DOUBLE PRECISION`/`INTEGER`/`BYTEA` + `BIGSERIAL`; MySQL
90
+ * needs a bounded `VARCHAR` key, `DOUBLE`, `LONGBLOB`, `AUTO_INCREMENT`.
91
+ */
42
92
  companionTypes: {
43
93
  autoincrementPrimaryKey: string;
44
94
  integer: string;
@@ -46,37 +96,110 @@ interface SqlDialect {
46
96
  real: string;
47
97
  text: string;
48
98
  };
49
- /** Map a stored value back to its JS form, by effective validator `kind` (inverse of `encode`). */
50
- decode: (value: unknown, kind: string | undefined) => unknown;
51
- /** Map a JS value to its bound storage form (boolean→1/0, bigint→string, object→JSON on SQLite; mostly native on PG). */
52
- encode: (value: unknown) => unknown;
53
99
  /** The framework columns every global table carries — the `id` primary key and `_creationTime` — as `{ name, type }` so the DDL builder can quote each name through the engine's dialect. */
54
100
  frameworkColumns: () => ReadonlyArray<{
55
101
  name: string;
56
102
  type: string;
57
103
  }>;
58
104
  /**
59
- * Optional: the key-prefix length an indexed column of this `kind` needs.
60
- * MySQL/InnoDB can't index a `TEXT`/`LONGTEXT`/`BLOB` column without a prefix
61
- * (the store appends `(&lt;n>)` to the column reference); SQLite/Postgres index
62
- * text columns directly and omit this hook (or return `undefined`). `kind` is
63
- * the column's effective validator kind.
64
- */
105
+ * Optional: the key-prefix length an indexed column of this `kind` needs.
106
+ * MySQL/InnoDB can't index a `TEXT`/`LONGTEXT`/`BLOB` column without a prefix
107
+ * (the store appends `(<n>)` to the column reference); SQLite/Postgres index
108
+ * text columns directly and omit this hook (or return `undefined`). `kind` is
109
+ * the column's effective validator kind.
110
+ */
65
111
  indexKeyPrefix?: (kind: string | undefined) => number | undefined;
66
112
  /** True when an `error` thrown by a write is a UNIQUE-constraint breach (mapped to a 409 ConflictError). */
67
113
  isUniqueViolation: (error: unknown) => boolean;
68
- /** A short engine tag for diagnostics/branching (`"sqlite" | "postgres" | "mysql"`). The store core selects drizzle's matching dialect for rendering off this. */
114
+ /**
115
+ * Most columns one table may carry on this engine, framework columns
116
+ * included. Omit it and the DDL builder does not check — the right answer
117
+ * for an engine whose ceiling is high enough that no real schema reaches it.
118
+ *
119
+ * Declared because the ceilings differ by more than an order of magnitude:
120
+ * D1 runs Workerd's SQLite build, which caps a table at 100 columns, where
121
+ * Postgres allows 1,600 and MySQL 4,096. A fixed number here would either
122
+ * miss the D1 failure or reject schemas the other two engines run happily.
123
+ */
124
+ maxTableColumns?: number;
125
+ /** A short engine tag for diagnostics/branching (`"sqlite" | "postgres" | "mysql"`). */
69
126
  readonly name: "mysql" | "postgres" | "sqlite";
127
+ /**
128
+ * Optional: the engine's own full-text index, opted into per search index
129
+ * with `.searchIndex({ strategy: "native" })`.
130
+ *
131
+ * Only Postgres supplies one today (`tsvector` + GIN + `to_tsquery`). It
132
+ * scales sublinearly where the portable inverted companion aggregates every
133
+ * matching token row, but it ranks with the engine's formula rather than the
134
+ * shared scorer — which is why it is opt-in and why the parity suite asserts
135
+ * matching, not order, for indexes that use it.
136
+ *
137
+ * Recall still matches the portable path: the stored form is built from the
138
+ * tokens Lunora's analyzer already produced, under a configuration that adds
139
+ * no stemming or stopwords of the engine's own.
140
+ *
141
+ * Every member returns a *statement*, not a fragment, so no engine grammar
142
+ * reaches the store core: Postgres matches with `@@` against a `tsvector`
143
+ * column while MySQL would use `MATCH … AGAINST` against a text column, and
144
+ * both fit here without the caller knowing which.
145
+ */
146
+ nativeTextSearch?: {
147
+ /** DDL for the companion table holding the engine's indexed form, keyed by document id. */
148
+ createCompanion: (companion: string, keyType: string) => SQL;
149
+ /** DDL for the indexes that make the match fast. */
150
+ createIndexes: (companion: string) => SQL[];
151
+ /**
152
+ * Replace one document's row, given its already-analyzed token stream,
153
+ * only where `guard` holds. One idempotent statement: two writers of one
154
+ * id converge on one row, never raise a key conflict, and a writer whose
155
+ * `guard` fails writes nothing.
156
+ */
157
+ indexDocument: (companion: string, id: string, analyzed: string, guard: SQL) => SQL;
158
+ /** The `WHERE` predicate matching a query's analyzed terms, final term as a prefix. */
159
+ matches: (companion: string, terms: ReadonlyArray<string>) => SQL;
160
+ /** The `ORDER BY` expression, best first. */
161
+ rank: (companion: string, terms: ReadonlyArray<string>) => SQL;
162
+ };
163
+ /** Render a composable drizzle `SQL` to this engine's `{ sql, params }`. Each dialect imports only its own drizzle dialect, so a bundle carries one engine's renderer. */
164
+ render: (query: SQL) => RenderedSql;
165
+ /**
166
+ * How an operator completes a search index that is still backfilling on
167
+ * this backend, in words, for the refusal a read against it raises: each
168
+ * backend's entry point differs. Absent, the refusal says only to retry
169
+ * once the backfill finishes.
170
+ */
171
+ searchBackfillHint?: string;
172
+ /**
173
+ * True when the engine ships SQLite's FTS5 module, which decides whether a
174
+ * search index is stored as an FTS5 shadow or as the portable inverted
175
+ * companion.
176
+ *
177
+ * A static property of the engine, so it is declared rather than probed:
178
+ * the previous `CREATE VIRTUAL TABLE` capability probe spent a round trip
179
+ * (and an error in the database's log) on every fresh connection to
180
+ * rediscover something the dialect already knows. Tests that want the
181
+ * portable layout override this instead of intercepting SQL strings.
182
+ */
183
+ supportsFts5: boolean;
70
184
  /** True when the engine supports `UPDATE/DELETE ... RETURNING` (SQLite/PG yes, MySQL no → use `affectedRows`). */
71
185
  supportsReturning: boolean;
72
186
  /**
73
- * The catalog probe for whether a physical `table` exists — backs the opt-in
74
- * companion-table (`__agg_`/`__rank_`) existence checks. Returns a drizzle
75
- * {@link SQL} (a non-empty result ⇒ the table exists) so it renders through
76
- * the same per-engine path as every other statement, never a hand-built
77
- * placeholder string. SQLite reads `sqlite_master`; Postgres/MySQL read
78
- * `information_schema.tables`.
79
- */
187
+ * The catalog probe for whether a physical `table` exists — backs the opt-in
188
+ * companion-table (`__agg_`/`__rank_`) existence checks. Returns a drizzle
189
+ * {@link SQL} (a non-empty result ⇒ the table exists) so it renders through
190
+ * the same per-engine path as every other statement, never a hand-built
191
+ * placeholder string. SQLite reads `sqlite_master`; Postgres/MySQL read
192
+ * `information_schema.tables`.
193
+ */
80
194
  tableExists: (table: string) => SQL;
195
+ /**
196
+ * Optional: btree operator class appended to an indexed text column so a
197
+ * `LIKE 'prefix%'` scan can use the index whatever the database collation.
198
+ * Postgres needs `text_pattern_ops` (a default `text_ops` btree built under
199
+ * e.g. `en_US.UTF-8` is useless to `LIKE`); SQLite and MySQL index prefix
200
+ * matches off the plain index and omit this. Only the search companion's
201
+ * token index reads it.
202
+ */
203
+ textPatternOperatorClass?: string;
81
204
  }
82
205
  export { SqlDialect, SqlExec, SqlRunResult };
package/dist/dialect.mjs CHANGED
@@ -1 +0,0 @@
1
-