@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/dist/index.d.mts CHANGED
@@ -1,174 +1,688 @@
1
- import { ServerDefaultContextLike, DatabaseWriterLike, SchedulerLike, SchemaLike, TableDefinitionLike, ValidatorLike } from '@lunora/do';
2
- import { SqlDialect, SqlRunResult } from "./dialect.mjs";
1
+ import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
2
+ import { SqlRunResult, SqlDialect } from "./dialect.mjs";
3
3
  export type { SqlExec } from "./dialect.mjs";
4
4
  import 'drizzle-orm';
5
5
  /**
6
- * Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
7
- * Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
8
- * adapter in tests, so the query logic runs against a real SQLite engine.
9
- */
6
+ * Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
7
+ * Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
8
+ * adapter in tests, so the query logic runs against a real SQLite engine.
9
+ */
10
10
  interface SqlCtxExec {
11
11
  all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
12
+ batch?: (statements: ReadonlyArray<{
13
+ params: ReadonlyArray<unknown>;
14
+ sql: string;
15
+ }>) => Promise<void>;
12
16
  run: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<SqlRunResult | void>;
13
17
  }
18
+ /**
19
+ * Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
20
+ * preserved, and every column run through the shared {@link sqliteDecode} so the
21
+ * stored form is reversed back into its JS shape. Exported so the data-browser
22
+ * (`introspect.ts`) and admin export/import paths share the exact same decode.
23
+ *
24
+ * The decode is engine-agnostic: every backend stores SQLite-shaped values
25
+ * (boolean → 1/0, JSON → text, bigint → an order-preserving text key), and `sqliteDecode` is
26
+ * robust to a driver returning either the stored string OR a natively-parsed
27
+ * value (e.g. mysql2 returns JSON columns pre-parsed) — so the same decoder is
28
+ * correct on SQLite, Postgres and MySQL.
29
+ */
30
+ declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
31
+ /** One exported row: `doc` is reconstructed from the column tuple. */
32
+ interface ExportRow {
33
+ doc: Record<string, unknown>;
34
+ /**
35
+ * True physical source line, when the caller has it (e.g. a global row
36
+ * pulled out of an interspersed NDJSON import stream by
37
+ * `@lunora/runtime`'s `import-stream.ts`). When present this overrides the
38
+ * position-derived line below — the caller-side positions of a
39
+ * global-only subset don't line up with the original file once
40
+ * non-global rows have been filtered out. Absent for callers with no
41
+ * physical source to attribute (e.g. a fresh `exportSqlGlobalRows` roundtrip
42
+ * in tests), which keeps the positional fallback.
43
+ */
44
+ line?: number;
45
+ table: string;
46
+ }
47
+ interface ImportError {
48
+ code: string;
49
+ line: number;
50
+ message: string;
51
+ table: string;
52
+ }
53
+ interface ImportResult {
54
+ /** Skipped rows whose `_id` already exists (the default `onConflict: "skip"`). */
55
+ conflicts: number;
56
+ errors: ImportError[];
57
+ inserted: Record<string, number>;
58
+ /** Existing rows overwritten under `onConflict: "replace"`. */
59
+ replaced: number;
60
+ }
61
+ /**
62
+ * Return every `.global()` table in the schema, optionally narrowed by an
63
+ * allowlist. Shard-local tables are skipped here — they're handled by the DO
64
+ * helpers — so callers get a clean separation between the two storage planes.
65
+ */
66
+ declare const selectGlobalTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
67
+ interface ExportGlobalArgs {
68
+ batchSize?: number;
69
+ tables?: ReadonlyArray<string>;
70
+ }
71
+ /**
72
+ * Yield rows from every requested `.global()` table in batches.
73
+ *
74
+ * Keyset-paginates on the physical primary key (`id` — every `.global()` table
75
+ * carries it): `WHERE id > ? ORDER BY id LIMIT n`, carrying the last id forward.
76
+ * A plain `LIMIT/OFFSET` scan would be wrong here — no engine guarantees an
77
+ * order for an unordered SELECT and each page is a separate query, so pages
78
+ * could overlap or skip rows (and any concurrent insert/delete would shift
79
+ * offsets and silently drop/duplicate rows in the snapshot). Keyset paging is
80
+ * deterministic under concurrent writes and avoids O(n^2) OFFSET scans.
81
+ *
82
+ * Tables are provisioned first (idempotent `CREATE … IF NOT EXISTS`): `.global()`
83
+ * tables are created lazily on first write, so a fresh deployment — or any table
84
+ * never written — would otherwise abort the stream with a raw `no such table`
85
+ * instead of exporting it as empty.
86
+ */
87
+ declare const exportSqlGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, args: ExportGlobalArgs) => AsyncGenerator<ExportRow, void, undefined>;
88
+ interface ImportGlobalArgs {
89
+ /**
90
+ * Check the rows and report their shape errors, writing nothing. The conflict
91
+ * probe and the insert are skipped, so an `_id` already in use and a foreign-key
92
+ * or unique failure are only found by a real import.
93
+ */
94
+ dryRun?: boolean;
95
+ /**
96
+ * Optional direct exec handle to the same database the writer targets.
97
+ * When supplied, the conflict pre-probe issues a single
98
+ * `SELECT 1 FROM <table> WHERE id = ? LIMIT 1` against the row's declared
99
+ * table instead of falling back to an unscoped id probe, which scans every
100
+ * global table looking for the id. Strongly recommended for large schemas
101
+ * — the writer-fallback is O(N tables) per row.
102
+ */
103
+ exec?: SqlCtxExec;
104
+ /**
105
+ * What a row whose `_id` already exists in its table does: `"skip"` (the
106
+ * default) counts it as a conflict and leaves the stored row unchanged;
107
+ * `"replace"` overwrites the stored row with the snapshot's fields, keeping
108
+ * its `_id` and taking the snapshot's `_creationTime`. A dry run probes
109
+ * nothing, so the mode does not change its answer.
110
+ */
111
+ onConflict?: ImportConflictMode;
112
+ rows: ReadonlyArray<ExportRow>;
113
+ startLine?: number;
114
+ }
115
+ /**
116
+ * Import rows into `.global()` tables via the schema-aware writer. The
117
+ * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
118
+ * absent); we probe the rows' `_id`s first so a collision is reported as a
119
+ * conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
120
+ * `errors`; the rest land.
121
+ *
122
+ * With an `exec` handle the probe is batched ({@link probeIdOwners}) once for
123
+ * the whole call, not per row; a live write between that probe and a row's
124
+ * insert can still create a cross-table duplicate.
125
+ */
126
+ declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
14
127
  interface SqlCtxDbOptions {
15
128
  /**
16
- * Resolved request auth handed to `.serverDefault(fn)` column factories so
17
- * server-trusted columns (owner/tenant ids) stamp from the verified caller,
18
- * never the client. The generated worker passes the per-request identity;
19
- * absent it, server-trusted columns stamp the anonymous slice (`userId: null`).
20
- */
129
+ * Resolved request auth handed to `.serverDefault(fn)` column factories so
130
+ * server-trusted columns (owner/tenant ids) stamp from the verified caller,
131
+ * never the client. The generated worker passes the per-request identity;
132
+ * absent it, server-trusted columns stamp the anonymous slice (`userId: null`).
133
+ */
21
134
  auth?: ServerDefaultContextLike["auth"];
22
135
  /**
23
- * Opt into change-data-capture: when `true`, every committed write appends a
24
- * post-image to the `__cdc_log` table (created lazily alongside the other
25
- * companion tables). Backs CDC streaming export for `.global()` tables — the
26
- * log is for export/CDC consumers, NOT point-in-time recovery: D1's PITR is
27
- * the platform's own Time Travel (`wrangler d1 time-travel restore`), an
28
- * atomic restore, not a changelog replay. Leave undefined for zero-cost
29
- * legacy behaviour.
30
- */
136
+ * Opt into change-data-capture: when `true`, every committed write appends a
137
+ * post-image to the `__cdc_log` table (created lazily alongside the other
138
+ * companion tables). Backs CDC streaming export for `.global()` tables — the
139
+ * log is for export/CDC consumers, NOT point-in-time recovery: D1's PITR is
140
+ * the platform's own Time Travel (`wrangler d1 time-travel restore`), an
141
+ * atomic restore, not a changelog replay. Leave undefined for zero-cost
142
+ * legacy behaviour.
143
+ */
31
144
  cdc?: boolean;
145
+ /**
146
+ * How long `.global()` changelog entries are kept, in milliseconds. Absent
147
+ * (the default) means forever — the log grows for the life of the database.
148
+ *
149
+ * Opt-in for the same reason the shard-local windows are, and the reason is
150
+ * not caution: this log's streaming-export consumers hold opaque cursors
151
+ * issued outside this deployment, and nothing here can see where they sit.
152
+ * A default window would be a guess whose failure mode is silent data loss
153
+ * in someone's warehouse. A deployment that wants the log bounded states a
154
+ * window it knows covers its consumers; `.global()` shape pollers are then
155
+ * protected exactly, by the floor this read path reports rather than by the
156
+ * window. See `sweepSqlCdcRetention`.
157
+ *
158
+ * Time rather than rows because the log is SHARED: every shard in every
159
+ * region writes it, so a row count is not a bound any single consumer can
160
+ * reason about, while "older than N" is exactly what they compare their own
161
+ * lag against.
162
+ *
163
+ * Setting it costs one index write per `.global()` write: the first sweep
164
+ * builds `__cdc_log_ts` so a pass with nothing expired is one index seek
165
+ * rather than a walk of the log (on D1, a billed row written per append
166
+ * against reads of the whole log per pass).
167
+ */
168
+ cdcRetentionMs?: number;
32
169
  clock?: () => number;
33
170
  /**
34
- * Cross-shard counter for **reverse cross-backend relations** — the `_count`
35
- * mirror of the `crossShardReader` option below.
36
- */
171
+ * Cross-shard counter for **reverse cross-backend relations** — the `_count`
172
+ * mirror of the `crossShardReader` option below.
173
+ */
37
174
  crossShardCounter?: DatabaseWriterLike["count"];
38
175
  /**
39
- * Optional cross-shard reader for **reverse cross-backend relations**: a
40
- * `.global()` (D1) parent loading a shard-local (`.shardBy()`/root) child.
41
- * Such a child's rows are partitioned across every shard DO, so the local D1
42
- * writer can't resolve it. When provided, the relation loader routes the
43
- * child's read through this (the host wires it to the Query Coordinator's
44
- * RLS-correct `fanOut`, with identity forwarded so each shard applies its own
45
- * RLS). Absent it, loading such a relation throws a clear "not supported"
46
- * error (legacy behaviour). The forward direction (shard-local parent →
47
- * global child) and same-backend relations never touch this.
48
- */
49
- crossShardReader?: DatabaseWriterLike["findMany"];
176
+ * Optional cross-shard reader for **reverse cross-backend relations**: a
177
+ * `.global()` (D1) parent loading a shard-local (`.shardBy()`/root) child.
178
+ * Such a child's rows are partitioned across every shard DO, so the local D1
179
+ * writer can't resolve it. When provided, the relation loader routes the
180
+ * child's read through this (the host wires it to the Query Coordinator's
181
+ * RLS-correct `fanOut`, with identity forwarded so each shard applies its own
182
+ * RLS). Absent it, loading such a relation throws a clear "not supported"
183
+ * error (legacy behaviour). The forward direction (shard-local parent →
184
+ * global child) and same-backend relations never touch this.
185
+ *
186
+ * Takes {@link CrossShardReadArgs}, not `QueryArgs`: the hop is JSON, so the
187
+ * RLS filters are handed over as data (see that type's docblock).
188
+ */
189
+ crossShardReader?: (table: string, args: CrossShardReadArgs) => Promise<QueryPage>;
50
190
  /**
51
- * The SQL dialect that shapes every statement (identifier quoting, value
52
- * encode/decode, column types, upserts, RETURNING vs affected-rows).
53
- * `@lunora/d1` passes its `sqliteDialect`; the PlanetScale/Hyperdrive backend
54
- * passes its Postgres/MySQL dialect. Required — the core is engine-blind.
55
- */
191
+ * The SQL dialect that shapes every statement (identifier quoting, value
192
+ * encode/decode, column types, upserts, RETURNING vs affected-rows).
193
+ * `@lunora/d1` passes its `sqliteDialect`; the PlanetScale/Hyperdrive backend
194
+ * passes its Postgres/MySQL dialect. Required — the core is engine-blind.
195
+ */
56
196
  dialect: SqlDialect;
57
197
  exec: SqlCtxExec;
58
198
  idGenerator?: () => string;
59
199
  /**
60
- * Ceiling on the number of child join keys a relation-crossing `where`
61
- * predicate may materialize before the semijoin pre-resolver fails closed
62
- * (`relation predicate … exceeding the N-key limit`). D1 has no EXISTS
63
- * push-down, so an overflow here can only fail closed — never truncate the
64
- * `IN (...)` and silently mis-match. Defaults to the pre-resolver's shared
65
- * key cap when omitted.
66
- */
200
+ * Ceiling on the number of child join keys a relation-crossing `where`
201
+ * predicate may materialize before the semijoin pre-resolver fails closed
202
+ * (`relation predicate … exceeding the N-key limit`). D1 has no EXISTS
203
+ * push-down, so an overflow here can only fail closed — never truncate the
204
+ * `IN (...)` and silently mis-match. Defaults to the pre-resolver's shared
205
+ * key cap when omitted.
206
+ */
67
207
  maxRelationKeys?: number;
68
208
  /**
69
- * Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
70
- * Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
71
- * triggers on `.global()` tables need to enqueue follow-up work.
72
- */
209
+ * Object identifying the database this store provisions, so the one-shot
210
+ * `CREATE TABLE/INDEX IF NOT EXISTS` sweep is shared by every ctx-db built
211
+ * against it instead of repeating per instance.
212
+ *
213
+ * Hosts build a ctx-db **per request** (the writer captures the caller's
214
+ * identity and D1 bookmark), so without this the sweep — one round trip per
215
+ * global table plus one per index — runs again on the first `.global()`
216
+ * access of every request. On a 50-table schema that is ~1s in `lunora dev`
217
+ * and a real latency floor in production.
218
+ *
219
+ * WHAT TO PASS: something that outlives the request AND names one database
220
+ * (and one configuration). The D1 binding off `env` and the declaration
221
+ * object a host builds once both qualify; the result of a per-request
222
+ * factory does not — it keys the memo on a fresh object every time and
223
+ * shares nothing (which is silent, and looks exactly like not passing it).
224
+ *
225
+ * INVARIANT, unenforced: one scope ⇒ one `schema`, `dialect` and `cdc`. The
226
+ * memoised run closes over the FIRST writer's, so a later writer sharing a
227
+ * scope with `cdc: true` behind one with `cdc: false` never gets
228
+ * `__cdc_log`. Hosts pass app-level constants for all three, which is why
229
+ * this is a note rather than a composite key.
230
+ *
231
+ * Two behaviours change with a shared memo, both benign and both worth
232
+ * knowing: the DDL runs in the FIRST writer's D1 session, so a later
233
+ * session's first read is no longer implicitly pinned behind a write of its
234
+ * own (on a replicated binding that can mean one transient stale read on a
235
+ * freshly-provisioned database); and a database reset out from under a live
236
+ * isolate is no longer healed by the next request, since the entry lives as
237
+ * long as the scope does.
238
+ *
239
+ * The aggregate-counter and rank-companion rebuilds share the scope too, so
240
+ * a counter skewed by a lost companion write heals on the next isolate
241
+ * rather than the next request. The per-write deltas keep it exact between
242
+ * rebuilds, and a rebuild racing another isolate's write is itself what
243
+ * skews it, so rebuilding less often is the safer direction.
244
+ *
245
+ * Omit it and the memo stays per ctx-db — slower, never wrong, and what the
246
+ * tests want (they pair a fresh database with a reused schema object).
247
+ */
248
+ provisionScope?: object;
249
+ /**
250
+ * Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
251
+ * Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
252
+ * triggers on `.global()` tables need to enqueue follow-up work.
253
+ */
73
254
  scheduler?: SchedulerLike;
74
255
  schema: SchemaLike;
75
256
  }
257
+ /** Create the `__cdc_log` table. Idempotent; only run when CDC is enabled. */
258
+ declare const runSqlCdcMigration: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
76
259
  /**
77
- * Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
78
- * preserved, and every column run through the shared {@link sqliteDecode} so the
79
- * stored form is reversed back into its JS shape. Exported so the data-browser
80
- * (`introspect.ts`) and admin export/import paths share the exact same decode.
81
- *
82
- * The decode is engine-agnostic: every backend stores SQLite-shaped values
83
- * (boolean → 1/0, JSON → text, bigint → decimal string), and `sqliteDecode` is
84
- * robust to a driver returning either the stored string OR a natively-parsed
85
- * value (e.g. mysql2 returns JSON columns pre-parsed) — so the same decoder is
86
- * correct on SQLite, Postgres and MySQL.
87
- */
88
- declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
260
+ * Delete `.global()` changelog entries older than `retentionMs`, at most
261
+ * {@link GLOBAL_CDC_SWEEP_MAX_ROWS} per pass, and only if this writer wins the lease.
262
+ *
263
+ * **Time, not rows.** The shard-local twin bounds its log by row count because
264
+ * one shard owns it and a row count is a memory bound on that one object. This
265
+ * log is shared, so a row count means nothing to any individual consumer — but
266
+ * "older than N" is directly what every consumer needs to reason about, and it
267
+ * is the unit an operator can compare against their own connector's lag.
268
+ *
269
+ * **Which consumers this can strand, and what protects each:**
270
+ *
271
+ * - `.global()` shape pollers hold in-memory cursors this store cannot see. They
272
+ * are protected EXACTLY rather than approximately: {@link readSqlCdcChangedTables}
273
+ * reports the retained floor, and a poller below it treats the tick as "no
274
+ * visibility" and re-reads every shape. That is the same self-healing path a
275
+ * changelog error already takes, so a trimmed poller is slow for one tick, not
276
+ * wrong. No cursor registry, no assumption about how far behind a shard can be.
277
+ * - Streaming-export / warehouse consumers hold opaque cursors issued outside
278
+ * this deployment. Nothing here can see them, so nothing here guesses:
279
+ * {@link readSqlCdcChanges} refuses a page below the floor rather than serving
280
+ * the surviving tail, and retention stays OFF unless an operator states a
281
+ * window they know covers their connector.
282
+ */
283
+ declare const sweepSqlCdcRetention: (exec: SqlCtxExec, dialect: SqlDialect, retentionMs: number, now: number) => Promise<void>;
284
+ /** Oldest `seq` still retained in the `.global()` changelog, or `undefined` when it is empty. */
285
+ declare const readSqlCdcFloor: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<number | undefined>;
286
+ /**
287
+ * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
288
+ * (clamped to [1, 10000]); plus the cursor to resume from.
289
+ *
290
+ * On Postgres and MySQL the page also stops at the first late-commit hole: an
291
+ * allocated `seq` not yet visible, followed by a row younger than
292
+ * {@link CDC_LATE_COMMIT_WINDOW_MS} (see "Late commits" on
293
+ * {@link readSqlCdcChangedTables}). The cursor is a consumer's only record of
294
+ * what it has seen, so handing out rows past an in-flight append would skip that
295
+ * append for good. Stopping the page instead of just the cursor keeps the
296
+ * cursor the `seq` of the last change returned. A permanent hole (a failed
297
+ * append) holds the page back for one window only.
298
+ */
299
+ declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
300
+ limit?: number;
301
+ now?: number;
302
+ sinceSeq?: number;
303
+ }, dialect: SqlDialect) => Promise<{
304
+ changes: CdcChange[];
305
+ cursor: number;
306
+ }>;
307
+ /**
308
+ * Which tables the changelog recorded a write to after `sinceSeq`, plus the
309
+ * cursor to resume from. Metadata only — it reads no `doc`, so its cost is
310
+ * index seeks (on SQLite, see {@link sqliteChangedTablesSql}) rather than the
311
+ * size of the documents in it.
312
+ *
313
+ * The `.global()` shape poll asks this once per tick for the whole shard, and a
314
+ * shape whose table is absent from the answer skips its membership read
315
+ * entirely.
316
+ *
317
+ * **One statement, and the cursor comes out of the same rows as the tables.**
318
+ * Reading the head separately — in either order — opens a window where a write
319
+ * commits between the two round trips and ends up absent from `tables` while
320
+ * sitting at or below the adopted `cursor`, which loses it for good. Deriving
321
+ * the cursor as the max `seq` actually returned closes that window by
322
+ * construction: the caller can never advance past a row this scan did not see.
323
+ *
324
+ * **Late commits.** Postgres and MySQL allocate `seq` at INSERT, not at commit,
325
+ * so an append holding `N` can commit after one holding `N + 1`. A poll that
326
+ * adopts `N + 1` while `N` is still in flight skips `N` until the next resync
327
+ * pass. So on those engines the cursor stops below the first HOLE in `seq`
328
+ * rather than at the highest row seen: a hole is an allocated `seq` that is not
329
+ * (yet) visible, which is exactly what an in-flight append looks like. Tables
330
+ * above the hole are still reported, so nothing is delayed — rows past the
331
+ * cursor are just reported again next tick.
332
+ *
333
+ * A hole can also be permanent (a failed append burns its `seq`), and a cursor
334
+ * pinned under one forever would re-report everything above it on every tick.
335
+ * So a hole only holds the cursor while the first row after it is younger than
336
+ * {@link CDC_LATE_COMMIT_WINDOW_MS}: that row's append started before its own
337
+ * `seq` was allocated, which is after the hole's, so once it is that old the
338
+ * hole's owner has either committed (and is visible) or never will. An append
339
+ * slower than the window falls back to the resync interval, as before. A MySQL
340
+ * `auto_increment_increment` above 1 makes every step a hole, which holds the
341
+ * cursor one window behind the head: correct, just less narrowing.
342
+ *
343
+ * D1 skips all of this: single writer, `AUTOINCREMENT`, and `withSession` gives
344
+ * both reads one snapshot, so there is no hole to wait for — and D1 bills rows
345
+ * read.
346
+ */
347
+ declare const readSqlCdcChangedTables: (exec: SqlCtxExec, sinceSeq: number, dialect: SqlDialect, options?: {
348
+ cursorOnly?: boolean;
349
+ now?: number;
350
+ retained?: boolean;
351
+ }) => Promise<{
352
+ cursor: number;
353
+ floor?: number;
354
+ tables: string[];
355
+ }>;
356
+ declare const createSqlCtxDb: (options: SqlCtxDbOptions) => DatabaseWriterLike;
357
+ /**
358
+ * Auto-provision every `.global()` table from the schema, in as few round trips as the engine allows.
359
+ *
360
+ * `CREATE TABLE IF NOT EXISTS` with the physical `id`/`_creationTime`/row-version columns plus a typed column per declared
361
+ * field, then its secondary, default-order and `.unique()` indexes. The D1 twin of `@lunora/do`'s `runShardMigrations`: it
362
+ * makes the schema the single source of truth for global tables, so a fresh database serves them without a hand-applied
363
+ * migration. Idempotent (`IF NOT EXISTS`, `OR IGNORE`), additive only: it never drops or retypes a column.
364
+ *
365
+ * With an exec that exposes `batch` on SQLite this reads the catalog once and writes the missing DDL in a handful of
366
+ * atomic batches; otherwise, and for any table that needs more than additive DDL, it runs the original sequence.
367
+ */
89
368
  declare const runSqlGlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
90
369
  /**
91
- * Materialize the `__agg_&lt;index>` companion tables for every declared
92
- * `aggregateIndex` on a global table. Global tables in Lunora ship their own
93
- * DDL — counter tables are opt-in so production hosts can decide where they
94
- * live. Tests and dev hosts can call this once after their schema migration to
95
- * unlock O(1) counts.
96
- *
97
- * Idempotent (`CREATE TABLE IF NOT EXISTS`).
98
- */
370
+ * Materialize the `__agg_<index>` companion tables for every declared
371
+ * `aggregateIndex` on a global table. Global tables in Lunora ship their own
372
+ * DDL — counter tables are opt-in so production hosts can decide where they
373
+ * live. Tests and dev hosts can call this once after their schema migration to
374
+ * unlock O(1) counts.
375
+ *
376
+ * Idempotent (`CREATE TABLE IF NOT EXISTS`).
377
+ */
99
378
  declare const runSqlAggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
100
379
  /**
101
- * Materialize the `__rank_&lt;index>` companion tables for every declared
102
- * `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
103
- * opt-in pattern so production hosts decide whether to spend the DDL.
104
- *
105
- * Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
106
- */
380
+ * Materialize the `__rank_<index>` companion tables for every declared
381
+ * `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
382
+ * opt-in pattern so production hosts decide whether to spend the DDL.
383
+ *
384
+ * Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
385
+ */
107
386
  declare const runSqlRankMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
387
+ /** What {@link backfillSqlSearchIndexes} could not finish. */
388
+ interface SqlSearchBackfillResult {
389
+ /**
390
+ * Inverted companions that still lack their unique `(token, id)` key. Writes
391
+ * keep working without it, but two backfills racing over one row can index
392
+ * it twice; the warning logged for each says why the key was refused.
393
+ */
394
+ uniqueKeyMissing: string[];
395
+ /** A previous build's rows left unmigrated because every attempt at them lost to a concurrent write. */
396
+ unmappedSkipped: number;
397
+ }
108
398
  /**
109
- * Materialize the `__fts_&lt;index>` FTS5 shadow tables for every declared
110
- * `.searchIndex()` on a global table. Mirrors `runSqlAggregateMigrations` — same
111
- * opt-in pattern so production hosts decide whether to spend the DDL. Only runs
112
- * on engines that ship FTS5 (D1 does; the `node:sqlite` test runner doesn't,
113
- * where `.search()` transparently falls back to a scan). `__text__` holds the
114
- * indexed field; `__id__` (UNINDEXED) joins back to the row.
115
- *
116
- * Idempotent (`CREATE VIRTUAL TABLE IF NOT EXISTS`).
117
- */
399
+ * Provision the search companions, then index one bounded page of the rows that
400
+ * predate each index — unless it is declared `staged: true`, which leaves the
401
+ * whole backfill to {@link backfillSqlSearchIndexes}.
402
+ *
403
+ * Idempotent (`CREATE … IF NOT EXISTS` throughout, and the backfill resumes
404
+ * from recorded progress).
405
+ */
118
406
  declare const runSqlSearchMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
119
- /** One change-data-capture entry: a committed mutation, in monotonic `seq` order. Mirrors the DO twin. */
120
- interface CdcChange {
121
- /** Post-image document for insert/update; absent for delete (the `id` identifies the removed row). */
122
- doc?: Record<string, unknown>;
123
- id: string;
124
- op: "delete" | "insert" | "update";
125
- /** Monotonic per-database cursor — strictly increasing, never reused. */
126
- seq: number;
407
+ /**
408
+ * Run every declared search index — including the `staged: true` ones the
409
+ * migration pass skips — through to completion. The entry point a host calls
410
+ * out-of-band after deploying a search index over a table too large to index a
411
+ * page at a time.
412
+ *
413
+ * Idempotent and resumable: an index recorded as complete is skipped, and an
414
+ * interrupted run picks up from its cursor.
415
+ */
416
+ declare const backfillSqlSearchIndexes: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<SqlSearchBackfillResult>;
417
+ /** Reserved table holding one backfill-progress row per search companion. */
418
+ declare const SEARCH_STATE_TABLE = "__lunora_search_state";
419
+ /** Create the progress table. Idempotent; runs alongside the companion DDL. */
420
+ declare const migrateSearchState: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
421
+ /** A table plus its current row count. */
422
+ interface GlobalTableInfo {
423
+ name: string;
424
+ rowCount: number;
425
+ }
426
+ /** A window of rows from one table, plus the column list and total size. */
427
+ interface GlobalTablePage {
428
+ columns: string[];
429
+ /**
430
+ * Foreign-key columns (local column → referenced table) for tables that carry
431
+ * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
432
+ * Schema `.global()` tables omit this (their refs come from `describeTables`);
433
+ * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
434
+ * schema diagram can draw their global→global FK edges.
435
+ */
436
+ refs?: Record<string, string>;
437
+ rows: Record<string, unknown>[];
438
+ total: number;
439
+ }
440
+ /**
441
+ * One equality constraint a facet-value click adds to the global browser's view:
442
+ * `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
443
+ * displayed column name, validated against the table's columns and mapped to its
444
+ * physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
445
+ * value** the facet returned (a SQLite scalar — including a BLOB, which reaches
446
+ * here as bytes because the facet payload is wire-encoded), normalised by
447
+ * {@link sqliteEncode} and bound as a parameter, never interpolated.
448
+ * AND-combined with the other clauses.
449
+ *
450
+ * Only `eq` is compiled on this path. `operator` and `path` exist so that a
451
+ * request asking for anything else is refused by {@link buildEqPredicate} rather
452
+ * than read as an equality: a `has` or `contains` clause matched as `= ?` would
453
+ * return rows the caller did not ask for.
454
+ */
455
+ interface GlobalFilterClause {
456
+ column: string;
457
+ /** Must be absent or `"eq"`; any other operator is refused. */
458
+ operator?: string;
459
+ /** Must be absent or empty; a nested path is refused (D1 columns are physical). */
460
+ path?: string[];
461
+ value: unknown;
462
+ }
463
+ interface ReadGlobalTablePageOptions {
464
+ filters?: GlobalFilterClause[];
465
+ limit?: number;
466
+ offset?: number;
127
467
  table: string;
128
- /** Wall-clock millis when the change committed (the ctx-db `clock`). */
129
- ts: number;
130
468
  }
131
- /** Create the `__cdc_log` table. Idempotent; only run when CDC is enabled. */
132
- declare const runSqlCdcMigration: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
133
469
  /**
134
- * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
135
- * (clamped to [1, 10000]); plus the cursor to resume from.
136
- */
137
- declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
470
+ * Options for {@link facetSqlGlobalColumn} — the read-only "what values does this
471
+ * column hold?" summary for the global (D1) browser. `column` is the displayed
472
+ * column to group by (validated and mapped to its physical column, never
473
+ * interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
474
+ * constraints so the facet reflects the **active view** (the same rows the
475
+ * browser is previewing); `limit` caps the distinct values returned (clamped).
476
+ */
477
+ interface FacetGlobalColumnOptions {
478
+ column: string;
479
+ filters?: GlobalFilterClause[];
138
480
  limit?: number;
139
- sinceSeq?: number;
140
- }, dialect: SqlDialect) => Promise<{
141
- changes: CdcChange[];
142
- cursor: number;
143
- }>;
144
- /** Drop changelog entries at or below a checkpointed `throughSeq` (retention). */
145
- declare const trimSqlCdcChanges: (exec: SqlCtxExec, throughSeq: number, dialect: SqlDialect) => Promise<void>;
146
- declare const createSqlCtxDb: (options: SqlCtxDbOptions) => DatabaseWriterLike;
481
+ table: string;
482
+ }
483
+ /** One distinct value of a faceted global column with its row count over the active view. */
484
+ interface GlobalFacetValue {
485
+ count: number;
486
+ value: unknown;
487
+ }
488
+ /**
489
+ * Payload of a {@link facetSqlGlobalColumn} call: the top-N distinct `values` (each
490
+ * with a `count`) ordered by frequency, plus `truncated` — `true` when more
491
+ * distinct values existed beyond the cap, so the UI can say so rather than imply
492
+ * the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
493
+ */
494
+ interface GlobalFacetResult {
495
+ truncated: boolean;
496
+ values: GlobalFacetValue[];
497
+ }
498
+ /**
499
+ * List every browsable D1 table with its row count, ordered by name. Surfaces
500
+ * both the schema's `.global()` tables (provisioned first) and external tables
501
+ * (auth, etc.); internal/companion tables are excluded.
502
+ */
503
+ declare const listSqlGlobalTables: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<GlobalTableInfo[]>;
504
+ /**
505
+ * Read a page of rows from one D1 table. The table is validated against the live
506
+ * browsable-table list before its name is interpolated, so this can't be coerced
507
+ * into reading an internal table or injecting SQL. `limit` is clamped to
508
+ * `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
509
+ * matching each `column = value` eq constraint (a facet-value drill-down), bound
510
+ * through {@link buildEqPredicate} so they never inject SQL.
511
+ */
512
+ declare const readSqlGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
513
+ /**
514
+ * Summarise the distinct values of one displayed column over the **active view**
515
+ * (the same eq `filters` the global browser is previewing) — the D1 twin of the
516
+ * shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
517
+ * count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
518
+ * against the table's displayed columns (typed 404 if unknown), mapped to its
519
+ * physical column, and quoted — never interpolated from caller input. The extra
520
+ * over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
521
+ * an external (non-schema) table is never grouped — it collapses to a single
522
+ * redacted `•••` bucket — mirroring the page browser's value redaction so the
523
+ * facet can't leak credentials. The returned `value` is the raw stored scalar, so
524
+ * a click feeds it straight back as an eq filter.
525
+ *
526
+ * The payload is wire-encoded on the way out, like the page read's rows: a BLOB
527
+ * column's stored value is bytes, and `Response.json` flattens those to `{}` —
528
+ * which is not a display glitch but a broken drill-down, since the flattened
529
+ * value is what the click sends back as the filter. `needsWireEncoding` leaves a
530
+ * facet over an ordinary text/numeric column untouched.
531
+ */
532
+ declare const facetSqlGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
147
533
  /** Map a JS value onto its SQLite storage form — SQLite has no boolean, so true/false → 1/0. */
148
- declare const sqliteEncode: (value: unknown) => unknown;
534
+ declare const sqliteEncode: (value: unknown, kind?: string) => unknown;
149
535
  /** Parse `raw` as JSON, returning `raw` unchanged when it is not valid JSON. */
150
536
  declare const tryJsonParse: (raw: string) => unknown;
151
- /** Decode a `bigint` column: a decimal string back into a `BigInt`, else verbatim. */
537
+ /**
538
+ * Decode a `bigint` column: the order-preserving key {@link bigintSqlKey} writes,
539
+ * or — for a row stored by a build that wrote plain decimal text — the decimal
540
+ * string, else verbatim.
541
+ */
152
542
  declare const decodeBigint: (raw: unknown) => unknown;
153
543
  /**
154
- * Resolve the *effective* storage kind of a column validator. Encoding keys off
155
- * the runtime value's JS type, so a `v.optional(inner)` column stores its
156
- * present value exactly as `inner` would. The validator's own `kind` is
157
- * `"optional"`, which hides that — unwrap to the inner validator's kind so the
158
- * decode reverses the real storage form. The inner validator is stashed on
159
- * `_meta.inner` by `@lunora/values`' `createValidator`.
160
- */
544
+ * Resolve the *effective* storage kind of a column validator: `v.optional(inner)`
545
+ * unwrapped to `inner`'s kind, since encoding keys off the runtime value's JS
546
+ * type and the validator's own `kind` of `"optional"` hides that.
547
+ *
548
+ * A thin alias over `shared/effective-kind`, which is where the rule lives so
549
+ * the DO row store applies the identical one — it reads the same validators and
550
+ * has the same failure mode, and two copies drifted the last time.
551
+ */
161
552
  declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefined;
162
553
  /**
163
- * Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
164
- * form, driven by the field's effective validator `kind`:
165
- *
166
- * - `boolean`: 1/0 → true/false (SQLite has no boolean type).
167
- * - `bigint`: decimal string → `BigInt`.
168
- * - `object`/`array`/`record`: JSON string → parsed value.
169
- * - `union`/`any`: parsed back only when the stored string is a JSON non-scalar
170
- * (a scalar union member round-trips through SQLite's native column type).
171
- * - everything else (string/number/date/timestamp/id/literal): verbatim.
172
- */
554
+ * Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
555
+ * form, driven by the field's effective validator `kind`:
556
+ *
557
+ * - `boolean`: 1/0 → true/false (SQLite has no boolean type).
558
+ * - `bigint`: decimal string → `BigInt`.
559
+ * - `bytes`: normalizes any driver return shape to a genuine `ArrayBuffer` — a
560
+ * view (`Uint8Array`/`Buffer`/…) is sliced to its own byte window, a plain
561
+ * `ArrayBuffer` passes through, and an array of byte values is packed into a
562
+ * fresh buffer. Required because `v.bytes()` validates
563
+ * `value instanceof ArrayBuffer` and different backends return different BLOB
564
+ * shapes: the D1 binding `Array<number>`, workerd's raw SQLite `ArrayBuffer`,
565
+ * node:sqlite `Uint8Array`, pg/mysql2 `Buffer`. The D1 one is the shape only a
566
+ * real binding produces, so the array case has its test in the workerd suite.
567
+ * - `object`/`array`/`record`/`geoPoint`: JSON string → parsed value. `geoPoint`
568
+ * belongs here because {@link sqliteEncode} keys off the runtime JS type and
569
+ * stores the `{ lat, lng }` object as JSON in a TEXT column; without the case
570
+ * it fell through to `default:` and every client read back the raw JSON text.
571
+ * - `union`/`any`/`from`: parsed back when the stored string is a JSON
572
+ * non-scalar, or when it carries the {@link WIRE_PREFIX} marker.
573
+ * A `number` or `boolean` does NOT round-trip through the column's native
574
+ * type — all three kinds store as TEXT on every engine, which coerces a bound
575
+ * `42` to the text `42.0` — so {@link sqliteEncode} writes those two in the
576
+ * marked form and this branch reverses them by the marker alone. A number's
577
+ * marked payload is `float64SqlKey`, so its text order is numeric order; the
578
+ * marked JSON an earlier build wrote is still read back here, which is what
579
+ * makes a table correct between the format change and the rewrite pass.
580
+ * `from` belongs to THIS group, not to `object`/`array`/`record`: an external
581
+ * Standard Schema can describe a string just as easily as an object, and
582
+ * {@link sqliteEncode} keys off the runtime JS type — so a `v.from(z.string())`
583
+ * column holding `"123"` is stored verbatim, and unconditional parsing would
584
+ * read it back as the NUMBER 123.
585
+ * A `bigint` member decodes too, by SHAPE: {@link sqliteEncode} keys off the
586
+ * runtime type, so a bigint here is stored as the same order-preserving key a
587
+ * declared `v.bigint()` column gets, and returning that verbatim handed the
588
+ * caller 40 characters of padding instead of the value it wrote. See the
589
+ * ambiguity this buys, and why the wire marker cannot carry it instead, below.
590
+ * CAVEAT: a union/any/from member is stored verbatim by {@link sqliteEncode}, so
591
+ * a legitimate *string* value that itself looks like JSON (`'{"a":1}'`, `'[1,2]'`)
592
+ * is ambiguous on read and decodes back to the parsed object/array, not the
593
+ * original string. The bigint test admits the same class of ambiguity, narrower
594
+ * but real: `decodeBigintSqlKey` accepts EXACTLY 40 characters — `"0"` or `"1"`,
595
+ * then 39 digits — and a stored *string* of that shape (a zero-padded account
596
+ * number, a numeric external id) is byte-identical on disk to a key and reads
597
+ * back as a `bigint`. Pinned by a test in `ctx-db.test.ts` so the trade is
598
+ * visible rather than rediscovered.
599
+ *
600
+ * Preferred anyway, because the alternative is not "no ambiguity" but
601
+ * guaranteed corruption: WITHOUT the test, every bigint any code writes to an
602
+ * untyped column comes back as padding, on every read. The narrow false
603
+ * positive costs a specific 40-character digit string its type; the absent test
604
+ * cost every such column its value.
605
+ *
606
+ * The unambiguous {@link WIRE_PREFIX} marker cannot carry this instead. It is
607
+ * not reached: {@link sqliteEncode} returns at its `bigint` branch first, and it
608
+ * takes no `kind`, so it cannot encode an untyped column differently from a
609
+ * declared one. It is also `serializeColumnValue`, which builds every WHERE
610
+ * binding — a prefixed bigint would never match a row stored as a key, and the
611
+ * padded key is order-preserving on purpose (indexes, range predicates, MIN/MAX
612
+ * all read it). Two storage forms for one runtime type breaks comparison
613
+ * between them. Disambiguating properly means tagging every encoded non-scalar,
614
+ * a breaking storage-format change, so it is documented rather than fixed.
615
+ * - everything else (string/number/date/timestamp/id/literal): verbatim.
616
+ */
173
617
  declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
174
- export { type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, readSqlCdcChanges, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, trimSqlCdcChanges, tryJsonParse };
618
+ export {
619
+ /**
620
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
621
+ * shared by Lunora's `.global()` table backends.
622
+ *
623
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
624
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
625
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
626
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
627
+ * whose `broadcast` hook drives live queries regardless of engine.
628
+ *
629
+ * This package is internal: consumers depend on `@lunora/d1` or
630
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
631
+ */
632
+ type ExportGlobalArgs,
633
+ /**
634
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
635
+ * shared by Lunora's `.global()` table backends.
636
+ *
637
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
638
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
639
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
640
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
641
+ * whose `broadcast` hook drives live queries regardless of engine.
642
+ *
643
+ * This package is internal: consumers depend on `@lunora/d1` or
644
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
645
+ */
646
+ type ExportRow, type FacetGlobalColumnOptions, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type GlobalTableInfo, type GlobalTablePage,
647
+ /**
648
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
649
+ * shared by Lunora's `.global()` table backends.
650
+ *
651
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
652
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
653
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
654
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
655
+ * whose `broadcast` hook drives live queries regardless of engine.
656
+ *
657
+ * This package is internal: consumers depend on `@lunora/d1` or
658
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
659
+ */
660
+ type ImportError,
661
+ /**
662
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
663
+ * shared by Lunora's `.global()` table backends.
664
+ *
665
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
666
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
667
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
668
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
669
+ * whose `broadcast` hook drives live queries regardless of engine.
670
+ *
671
+ * This package is internal: consumers depend on `@lunora/d1` or
672
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
673
+ */
674
+ type ImportGlobalArgs,
675
+ /**
676
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
677
+ * shared by Lunora's `.global()` table backends.
678
+ *
679
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
680
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
681
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
682
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
683
+ * whose `broadcast` hook drives live queries regardless of engine.
684
+ *
685
+ * This package is internal: consumers depend on `@lunora/d1` or
686
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
687
+ */
688
+ type ImportResult, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };