@lunora/sql-store 1.0.0-alpha.213 → 1.0.0-alpha.215

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.
Files changed (25) hide show
  1. package/dist/index.d.mts +274 -6
  2. package/dist/index.d.ts +274 -6
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/OCC_VERSION_COLUMN-ByC64Jgx.mjs +1 -0
  5. package/dist/packem_shared/{SEARCH_STATE_TABLE-B6lyHKeq.mjs → SEARCH_STATE_TABLE-noI80gFQ.mjs} +1 -1
  6. package/dist/packem_shared/backfillSqlSearchIndexes-BYfsAIee.mjs +1 -0
  7. package/dist/packem_shared/createSqlCtxDb-Cy7Dvrk9.mjs +7 -0
  8. package/dist/packem_shared/ctx-db-search-B4wC-Jrm.mjs +1 -0
  9. package/dist/packem_shared/ctx-db-search-state-Dt0iNPGb.mjs +1 -0
  10. package/dist/packem_shared/{decodeBigint-prUTsk6p.mjs → decodeBigint-BZku9YxY.mjs} +1 -1
  11. package/dist/packem_shared/decodeGlobalRow-kOyx0SBl.mjs +1 -0
  12. package/dist/packem_shared/exportSqlGlobalRows-BI_ZxPQU.mjs +1 -0
  13. package/dist/packem_shared/facetSqlGlobalColumn-Col-9Hcc.mjs +1 -0
  14. package/dist/packem_shared/{runSqlAggregateMigrations-BqfzHcG8.mjs → runSqlAggregateMigrations-lP0mwd-W.mjs} +1 -1
  15. package/dist/packem_shared/runSqlGlobalTableMigrations-DMC5hXJo.mjs +1 -0
  16. package/dist/packem_shared/sql-exec-BKz380dy.mjs +1 -0
  17. package/dist/packem_shared/{value-codec-CiS1h_97.mjs → value-codec-C52YW-Do.mjs} +1 -1
  18. package/package.json +3 -3
  19. package/dist/packem_shared/backfillSqlSearchIndexes-7INfXpdK.mjs +0 -1
  20. package/dist/packem_shared/createSqlCtxDb-BVFomXio.mjs +0 -7
  21. package/dist/packem_shared/ctx-db-search-DB_ejfgj.mjs +0 -1
  22. package/dist/packem_shared/ctx-db-search-state-DRiojLLm.mjs +0 -1
  23. package/dist/packem_shared/decodeGlobalRow-DfK8mSDo.mjs +0 -1
  24. package/dist/packem_shared/runSqlGlobalTableMigrations-qVa5Q8BM.mjs +0 -1
  25. package/dist/packem_shared/sql-exec-UH-aJj2C.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { TableDefinitionLike, ServerDefaultContextLike, DatabaseWriterLike, CrossShardReadArgs, QueryPage, SchedulerLike, SchemaLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
1
+ import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
2
2
  import { SqlRunResult, SqlDialect } from "./dialect.mjs";
3
3
  export type { SqlExec } from "./dialect.mjs";
4
4
  import 'drizzle-orm';
@@ -28,6 +28,98 @@ interface SqlCtxExec {
28
28
  * correct on SQLite, Postgres and MySQL.
29
29
  */
30
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 pre-probe each row's `_id` 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
+ declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
31
123
  interface SqlCtxDbOptions {
32
124
  /**
33
125
  * Resolved request auth handed to `.serverDefault(fn)` column factories so
@@ -63,6 +155,11 @@ interface SqlCtxDbOptions {
63
155
  * region writes it, so a row count is not a bound any single consumer can
64
156
  * reason about, while "older than N" is exactly what they compare their own
65
157
  * lag against.
158
+ *
159
+ * Setting it costs one index write per `.global()` write: the first sweep
160
+ * builds `__cdc_log_ts` so a pass with nothing expired is one index seek
161
+ * rather than a walk of the log (on D1, a billed row written per append
162
+ * against reads of the whole log per pass).
66
163
  */
67
164
  cdcRetentionMs?: number;
68
165
  clock?: () => number;
@@ -135,6 +232,12 @@ interface SqlCtxDbOptions {
135
232
  * isolate is no longer healed by the next request, since the entry lives as
136
233
  * long as the scope does.
137
234
  *
235
+ * The aggregate-counter and rank-companion rebuilds share the scope too, so
236
+ * a counter skewed by a lost companion write heals on the next isolate
237
+ * rather than the next request. The per-write deltas keep it exact between
238
+ * rebuilds, and a rebuild racing another isolate's write is itself what
239
+ * skews it, so rebuilding less often is the safer direction.
240
+ *
138
241
  * Omit it and the memo stays per ctx-db — slower, never wrong, and what the
139
242
  * tests want (they pair a fresh database with a reused schema object).
140
243
  */
@@ -179,9 +282,19 @@ declare const readSqlCdcFloor: (exec: SqlCtxExec, dialect: SqlDialect) => Promis
179
282
  /**
180
283
  * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
181
284
  * (clamped to [1, 10000]); plus the cursor to resume from.
285
+ *
286
+ * On Postgres and MySQL the page also stops at the first late-commit hole: an
287
+ * allocated `seq` not yet visible, followed by a row younger than
288
+ * {@link CDC_LATE_COMMIT_WINDOW_MS} (see "Late commits" on
289
+ * {@link readSqlCdcChangedTables}). The cursor is a consumer's only record of
290
+ * what it has seen, so handing out rows past an in-flight append would skip that
291
+ * append for good. Stopping the page instead of just the cursor keeps the
292
+ * cursor the `seq` of the last change returned. A permanent hole (a failed
293
+ * append) holds the page back for one window only.
182
294
  */
183
295
  declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
184
296
  limit?: number;
297
+ now?: number;
185
298
  sinceSeq?: number;
186
299
  }, dialect: SqlDialect) => Promise<{
187
300
  changes: CdcChange[];
@@ -189,8 +302,9 @@ declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
189
302
  }>;
190
303
  /**
191
304
  * Which tables the changelog recorded a write to after `sinceSeq`, plus the
192
- * cursor to resume from. Metadata only — it reads no `doc`, so its cost is a
193
- * grouped scan over an index range rather than the size of the documents in it.
305
+ * cursor to resume from. Metadata only — it reads no `doc`, so its cost is
306
+ * index seeks (on SQLite, see {@link sqliteChangedTablesSql}) rather than the
307
+ * size of the documents in it.
194
308
  *
195
309
  * The `.global()` shape poll asks this once per tick for the whole shard, and a
196
310
  * shape whose table is absent from the answer skips its membership read
@@ -300,6 +414,118 @@ declare const backfillSqlSearchIndexes: (exec: SqlCtxExec, schema: SchemaLike, d
300
414
  declare const SEARCH_STATE_TABLE = "__lunora_search_state";
301
415
  /** Create the progress table. Idempotent; runs alongside the companion DDL. */
302
416
  declare const migrateSearchState: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
417
+ /** A table plus its current row count. */
418
+ interface GlobalTableInfo {
419
+ name: string;
420
+ rowCount: number;
421
+ }
422
+ /** A window of rows from one table, plus the column list and total size. */
423
+ interface GlobalTablePage {
424
+ columns: string[];
425
+ /**
426
+ * Foreign-key columns (local column → referenced table) for tables that carry
427
+ * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
428
+ * Schema `.global()` tables omit this (their refs come from `describeTables`);
429
+ * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
430
+ * schema diagram can draw their global→global FK edges.
431
+ */
432
+ refs?: Record<string, string>;
433
+ rows: Record<string, unknown>[];
434
+ total: number;
435
+ }
436
+ /**
437
+ * One equality constraint a facet-value click adds to the global browser's view:
438
+ * `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
439
+ * displayed column name, validated against the table's columns and mapped to its
440
+ * physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
441
+ * value** the facet returned (a SQLite scalar — including a BLOB, which reaches
442
+ * here as bytes because the facet payload is wire-encoded), normalised by
443
+ * {@link sqliteEncode} and bound as a parameter, never interpolated.
444
+ * AND-combined with the other clauses.
445
+ *
446
+ * Only `eq` is compiled on this path. `operator` and `path` exist so that a
447
+ * request asking for anything else is refused by {@link buildEqPredicate} rather
448
+ * than read as an equality: a `has` or `contains` clause matched as `= ?` would
449
+ * return rows the caller did not ask for.
450
+ */
451
+ interface GlobalFilterClause {
452
+ column: string;
453
+ /** Must be absent or `"eq"`; any other operator is refused. */
454
+ operator?: string;
455
+ /** Must be absent or empty; a nested path is refused (D1 columns are physical). */
456
+ path?: string[];
457
+ value: unknown;
458
+ }
459
+ interface ReadGlobalTablePageOptions {
460
+ filters?: GlobalFilterClause[];
461
+ limit?: number;
462
+ offset?: number;
463
+ table: string;
464
+ }
465
+ /**
466
+ * Options for {@link facetSqlGlobalColumn} — the read-only "what values does this
467
+ * column hold?" summary for the global (D1) browser. `column` is the displayed
468
+ * column to group by (validated and mapped to its physical column, never
469
+ * interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
470
+ * constraints so the facet reflects the **active view** (the same rows the
471
+ * browser is previewing); `limit` caps the distinct values returned (clamped).
472
+ */
473
+ interface FacetGlobalColumnOptions {
474
+ column: string;
475
+ filters?: GlobalFilterClause[];
476
+ limit?: number;
477
+ table: string;
478
+ }
479
+ /** One distinct value of a faceted global column with its row count over the active view. */
480
+ interface GlobalFacetValue {
481
+ count: number;
482
+ value: unknown;
483
+ }
484
+ /**
485
+ * Payload of a {@link facetSqlGlobalColumn} call: the top-N distinct `values` (each
486
+ * with a `count`) ordered by frequency, plus `truncated` — `true` when more
487
+ * distinct values existed beyond the cap, so the UI can say so rather than imply
488
+ * the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
489
+ */
490
+ interface GlobalFacetResult {
491
+ truncated: boolean;
492
+ values: GlobalFacetValue[];
493
+ }
494
+ /**
495
+ * List every browsable D1 table with its row count, ordered by name. Surfaces
496
+ * both the schema's `.global()` tables (provisioned first) and external tables
497
+ * (auth, etc.); internal/companion tables are excluded.
498
+ */
499
+ declare const listSqlGlobalTables: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<GlobalTableInfo[]>;
500
+ /**
501
+ * Read a page of rows from one D1 table. The table is validated against the live
502
+ * browsable-table list before its name is interpolated, so this can't be coerced
503
+ * into reading an internal table or injecting SQL. `limit` is clamped to
504
+ * `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
505
+ * matching each `column = value` eq constraint (a facet-value drill-down), bound
506
+ * through {@link buildEqPredicate} so they never inject SQL.
507
+ */
508
+ declare const readSqlGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
509
+ /**
510
+ * Summarise the distinct values of one displayed column over the **active view**
511
+ * (the same eq `filters` the global browser is previewing) — the D1 twin of the
512
+ * shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
513
+ * count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
514
+ * against the table's displayed columns (typed 404 if unknown), mapped to its
515
+ * physical column, and quoted — never interpolated from caller input. The extra
516
+ * over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
517
+ * an external (non-schema) table is never grouped — it collapses to a single
518
+ * redacted `•••` bucket — mirroring the page browser's value redaction so the
519
+ * facet can't leak credentials. The returned `value` is the raw stored scalar, so
520
+ * a click feeds it straight back as an eq filter.
521
+ *
522
+ * The payload is wire-encoded on the way out, like the page read's rows: a BLOB
523
+ * column's stored value is bytes, and `Response.json` flattens those to `{}` —
524
+ * which is not a display glitch but a broken drill-down, since the flattened
525
+ * value is what the click sends back as the filter. `needsWireEncoding` leaves a
526
+ * facet over an ordinary text/numeric column untouched.
527
+ */
528
+ declare const facetSqlGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
303
529
  /** Map a JS value onto its SQLite storage form — SQLite has no boolean, so true/false → 1/0. */
304
530
  declare const sqliteEncode: (value: unknown, kind?: string) => unknown;
305
531
  /** Parse `raw` as JSON, returning `raw` unchanged when it is not valid JSON. */
@@ -385,7 +611,49 @@ declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefi
385
611
  * - everything else (string/number/date/timestamp/id/literal): verbatim.
386
612
  */
387
613
  declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
388
- export { SEARCH_STATE_TABLE,
614
+ export {
615
+ /**
616
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
617
+ * shared by Lunora's `.global()` table backends.
618
+ *
619
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
620
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
621
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
622
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
623
+ * whose `broadcast` hook drives live queries regardless of engine.
624
+ *
625
+ * This package is internal: consumers depend on `@lunora/d1` or
626
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
627
+ */
628
+ type ExportGlobalArgs,
629
+ /**
630
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
631
+ * shared by Lunora's `.global()` table backends.
632
+ *
633
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
634
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
635
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
636
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
637
+ * whose `broadcast` hook drives live queries regardless of engine.
638
+ *
639
+ * This package is internal: consumers depend on `@lunora/d1` or
640
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
641
+ */
642
+ type ExportRow, type FacetGlobalColumnOptions, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type GlobalTableInfo, type GlobalTablePage,
643
+ /**
644
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
645
+ * shared by Lunora's `.global()` table backends.
646
+ *
647
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
648
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
649
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
650
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
651
+ * whose `broadcast` hook drives live queries regardless of engine.
652
+ *
653
+ * This package is internal: consumers depend on `@lunora/d1` or
654
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
655
+ */
656
+ type ImportError,
389
657
  /**
390
658
  * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
391
659
  * shared by Lunora's `.global()` table backends.
@@ -399,7 +667,7 @@ export { SEARCH_STATE_TABLE,
399
667
  * This package is internal: consumers depend on `@lunora/d1` or
400
668
  * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
401
669
  */
402
- type SqlCtxDbOptions,
670
+ type ImportGlobalArgs,
403
671
  /**
404
672
  * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
405
673
  * shared by Lunora's `.global()` table backends.
@@ -413,4 +681,4 @@ type SqlCtxDbOptions,
413
681
  * This package is internal: consumers depend on `@lunora/d1` or
414
682
  * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
415
683
  */
416
- type SqlCtxExec, type SqlDialect, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
684
+ 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 };