@lunora/sql-store 1.0.0-alpha.22 → 1.0.0-alpha.221

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