@lunora/sql-store 1.0.0-alpha.23 → 1.0.0-alpha.230

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