@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.
- package/dist/index.d.mts +274 -6
- package/dist/index.d.ts +274 -6
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/OCC_VERSION_COLUMN-ByC64Jgx.mjs +1 -0
- package/dist/packem_shared/{SEARCH_STATE_TABLE-B6lyHKeq.mjs → SEARCH_STATE_TABLE-noI80gFQ.mjs} +1 -1
- package/dist/packem_shared/backfillSqlSearchIndexes-BYfsAIee.mjs +1 -0
- package/dist/packem_shared/createSqlCtxDb-Cy7Dvrk9.mjs +7 -0
- package/dist/packem_shared/ctx-db-search-B4wC-Jrm.mjs +1 -0
- package/dist/packem_shared/ctx-db-search-state-Dt0iNPGb.mjs +1 -0
- package/dist/packem_shared/{decodeBigint-prUTsk6p.mjs → decodeBigint-BZku9YxY.mjs} +1 -1
- package/dist/packem_shared/decodeGlobalRow-kOyx0SBl.mjs +1 -0
- package/dist/packem_shared/exportSqlGlobalRows-BI_ZxPQU.mjs +1 -0
- package/dist/packem_shared/facetSqlGlobalColumn-Col-9Hcc.mjs +1 -0
- package/dist/packem_shared/{runSqlAggregateMigrations-BqfzHcG8.mjs → runSqlAggregateMigrations-lP0mwd-W.mjs} +1 -1
- package/dist/packem_shared/runSqlGlobalTableMigrations-DMC5hXJo.mjs +1 -0
- package/dist/packem_shared/sql-exec-BKz380dy.mjs +1 -0
- package/dist/packem_shared/{value-codec-CiS1h_97.mjs → value-codec-C52YW-Do.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/backfillSqlSearchIndexes-7INfXpdK.mjs +0 -1
- package/dist/packem_shared/createSqlCtxDb-BVFomXio.mjs +0 -7
- package/dist/packem_shared/ctx-db-search-DB_ejfgj.mjs +0 -1
- package/dist/packem_shared/ctx-db-search-state-DRiojLLm.mjs +0 -1
- package/dist/packem_shared/decodeGlobalRow-DfK8mSDo.mjs +0 -1
- package/dist/packem_shared/runSqlGlobalTableMigrations-qVa5Q8BM.mjs +0 -1
- package/dist/packem_shared/sql-exec-UH-aJj2C.mjs +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TableDefinitionLike,
|
|
1
|
+
import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
|
|
2
2
|
import { SqlRunResult, SqlDialect } from "./dialect.js";
|
|
3
3
|
export type { SqlExec } from "./dialect.js";
|
|
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
|
|
193
|
-
*
|
|
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 {
|
|
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
|
|
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 };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSqlCtxDb as
|
|
1
|
+
import{exportSqlGlobalRows as l,importSqlGlobalRows as o,selectGlobalTables as r}from"./packem_shared/exportSqlGlobalRows-BI_ZxPQU.mjs";import{createSqlCtxDb as s,readSqlCdcChangedTables as S,readSqlCdcChanges as n,readSqlCdcFloor as i,runSqlCdcMigration as d,sweepSqlCdcRetention as q}from"./packem_shared/createSqlCtxDb-Cy7Dvrk9.mjs";import{runSqlGlobalTableMigrations as b}from"./packem_shared/runSqlGlobalTableMigrations-DMC5hXJo.mjs";import{runSqlAggregateMigrations as f,runSqlRankMigrations as g}from"./packem_shared/runSqlAggregateMigrations-lP0mwd-W.mjs";import{b as x,r as C}from"./packem_shared/ctx-db-search-B4wC-Jrm.mjs";import{S as T,m as u}from"./packem_shared/ctx-db-search-state-Dt0iNPGb.mjs";import{facetSqlGlobalColumn as h,listSqlGlobalTables as M,readSqlGlobalTablePage as w}from"./packem_shared/facetSqlGlobalColumn-Col-9Hcc.mjs";import{d as E,e as k,s as B,a as D,t as P}from"./packem_shared/value-codec-C52YW-Do.mjs";import{d as v}from"./packem_shared/sql-exec-BKz380dy.mjs";export{T as SEARCH_STATE_TABLE,x as backfillSqlSearchIndexes,s as createSqlCtxDb,E as decodeBigint,v as decodeGlobalRow,k as effectiveColumnKind,l as exportSqlGlobalRows,h as facetSqlGlobalColumn,o as importSqlGlobalRows,M as listSqlGlobalTables,u as migrateSearchState,S as readSqlCdcChangedTables,n as readSqlCdcChanges,i as readSqlCdcFloor,w as readSqlGlobalTablePage,f as runSqlAggregateMigrations,d as runSqlCdcMigration,b as runSqlGlobalTableMigrations,g as runSqlRankMigrations,C as runSqlSearchMigrations,r as selectGlobalTables,B as sqliteDecode,D as sqliteEncode,q as sweepSqlCdcRetention,P as tryJsonParse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="_version";export{o as OCC_VERSION_COLUMN};
|
package/dist/packem_shared/{SEARCH_STATE_TABLE-B6lyHKeq.mjs → SEARCH_STATE_TABLE-noI80gFQ.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-
|
|
1
|
+
import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-Dt0iNPGb.mjs";import"./sql-exec-BKz380dy.mjs";export{t as SEARCH_STATE_TABLE,S as clearSearchBackfillState,c as migrateSearchState,l as readSearchBackfillState,i as readSearchIndexCoverage,s as writeSearchBackfillState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./ctx-db-search-state-Dt0iNPGb.mjs";import{b as S,c as s,a as i,r as l}from"./ctx-db-search-B4wC-Jrm.mjs";import"./sql-exec-BKz380dy.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{m as Rn,q as Sn}from"./ctx-db-search-state-Dt0iNPGb.mjs";import{c as gn,r as mn,A as Tn,C as vn,R as In,u as An,a as Cn,T as Ln,x as bn,d as Nn}from"./ctx-db-search-B4wC-Jrm.mjs";import{throwingScheduler as Mn,describeRelationWrites as On,CDC_LOG_TABLE as D,cdcForkedError as qn,cursorBelowRetainedFloor as kn,cdcTrimmedError as Dn,serverInList as Bn,assertNoExplicitUndefined as Ke,hasTrigger as Wn,runRowValidators as Ge,assertFlatPredicate as Et,mergeWhere as F,rankTableName as _e,sortColumnName as Re,resolveRankPartition as pt,encodePartitionKey as Me,resolveRankSeekTuple as Fn,RANK_TIEBREAK as Se,CountRlsUnsupportedError as yt,compileWhereSql as z,ConflictError as ae,patchDependsOnRow as Un,normalizeIdStructurally as xn,applyInsertDefaults as Pn,assertValidClientId as Hn,assertStorableRowId as jn,aggregateSqlFunction as Ee,softDeleteScope as Oe,resolveWith as Rt,relationHooks as St,applySelect as gt,encodeCursor as Kn,NotFoundError as Gn,applyOnDelete as Vn,normalizeCountArgument as Yn,selectIndexForCount as Xn,encodeAggregateKey as J,aggregateTableName as ie,selectIndexForAggregate as Qn,readAggregateValue as Ve,runTriggers as zn,nullsOrderSuffix as mt,nullsFirstOf as Tt,rankPivotConditionSql as Ht,CURSOR_PREFIX as Jn,resolvePatch as Zn,stripReservedPatchFields as ei,assertPatchAllowed as ti,resolveRelationPredicates as ni,selectIndexForGroupBy as ii,composeReadPredicate as oi,fanOutScalarCounts as ri,whereOfFilter as si,isPushableWhere as ai,matchesRankStaticWhere as vt,tiebreakDirectionFor as ci,matchesStaticWhere as Ye,coerceAggregateNumber as Xe,foldAggregateTally as It,CDC_LOG_TABLE_SEQ_INDEX as di,NotUniqueError as li,WORKERD_SQLITE_LIMITS as ui}from"@lunora/shard-engine";import{decodeWire as jt,needsWireEncoding as Kt,encodeWire as Gt}from"@lunora/wire";import{sql as e,SQL as fi}from"drizzle-orm";import{p as At,h as Ct,q as I,b as x,c as Vt,i as wi,j as $i,k as hi,l as X,s as oe,e as U,m as Lt,t as _i,a as Ei,n as bt,o as Be,u as ot,v as Nt,w as pi,x as Qe,y as Mt,B as ze,z as Ot,g as qt}from"./sql-exec-BKz380dy.mjs";import{d as So}from"./sql-exec-BKz380dy.mjs";import{runSqlGlobalTableMigrations as yi}from"./runSqlGlobalTableMigrations-DMC5hXJo.mjs";import{runSqlAggregateMigrations as Ri,runSqlRankMigrations as Si}from"./runSqlAggregateMigrations-lP0mwd-W.mjs";import{s as Yt,e as Xt}from"./value-codec-C52YW-Do.mjs";import{OCC_VERSION_COLUMN as pe}from"./OCC_VERSION_COLUMN-ByC64Jgx.mjs";const gi=(r,a)=>{if(r.size<a)return;const u=r.keys().next().value;u!==void 0&&r.delete(u)},kt=50,mi=(r,a={})=>{const u=a.maxBatch??kt,c=Number.isInteger(u)&&u>0?u:kt,R=new Map;let f=!1;const d=async(T,A)=>{const v=[...A.keys()];for(let L=0;L<v.length;L+=c){const b=v.slice(L,L+c);try{const q=await r(T,b);for(const K of b){const Q=q.get(K);for(const Z of A.get(K)??[])Z.resolve(Q)}}catch(q){for(const K of b)for(const Q of A.get(K)??[])Q.reject(q)}}},O=()=>{f=!1;const T=[...R.entries()];R.clear();for(const[A,v]of T)d(A,v).catch(()=>{})};return{async load(T,A){return new Promise((v,L)=>{let b=R.get(T);b||(b=new Map,R.set(T,b));const q=b.get(A);q?q.push({reject:L,resolve:v}):b.set(A,[{reject:L,resolve:v}]),f||(f=!0,queueMicrotask(O))})}}},Ti=new Set(["_id","id"]),vi=r=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(r)}"`)},Qt=(r,a)=>{const u=a.direction==="desc"?"DESC":"ASC",c=a.nullable===!0,R=f=>e`${Be(r,a.field)} ${e.raw(`${u}${f}`)}`;switch(r.name){case"mysql":{const f=R("");return!c||a.nulls===void 0?[f]:[e`(${Be(r,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,f]}case"postgres":return[R(c?mt(Tt(a)):"")];case"sqlite":return[R(c&&a.nulls!==void 0?mt(Tt(a)):"")];default:return vi(r.name)}},Ii=(r,a)=>{const u=r.flatMap(c=>Qt(a,c));if(!r.some(c=>Ti.has(c.field))){const c=ci(r);u.push(e`${U("id")} ${e.raw(c==="desc"?"DESC":"ASC")}`)}return e.join(u,e`, `)},Dt=50,Ai=r=>{const a=r.detail??r["QUERY PLAN"];return typeof a=="string"?a:Object.values(r).map(String).join(" | ")},Je=(r,a,u,c)=>{for(const[R,f]of _i(r)){if(f.serverDefault){R in a&&(u[R]=f.serverDefault({auth:c}));continue}f.onUpdateFn&&!(R in a)&&(u[R]=f.onUpdateFn())}},Ci=128,Li=()=>{const r=new Map;return{delete:a=>{r.delete(a)},get:a=>{const u=r.get(a);if(u!==void 0)return r.delete(a),r.set(a,u),u},set:(a,u)=>{r.has(a)?r.delete(a):gi(r,Ci),r.set(a,u)}}},zt=r=>r.shardMode===void 0||r.shardMode.kind==="global",bi=async(r,a,u,c,R)=>{const f=R.get(c);if(f!==void 0)return f;const d=Object.entries(u.tables).filter(([,T])=>zt(T)).map(([T])=>T),O=await Promise.all(d.map(async T=>({found:(await I(r,a,e`SELECT 1 FROM ${e.identifier(T)} WHERE ${e.identifier("id")} = ${c} LIMIT 1`)).length>0,tableName:T})));for(const T of O)if(T.found)return R.set(c,T.tableName),T.tableName},ce=r=>r==null?null:Number(r),Ni=(r,a,u)=>u.map(c=>{const R={};for(const f of a){const d=r.shape[f];R[f]=Yt(c[f]??null,d&&Xt(d))}return{key:R,value:ce(c.value)}}),Mi=(r,a,u)=>[...r.partitionBy??[],...r.sortBy.map(R=>R.field),...r.where?Object.keys(r.where):[]].every(R=>Mt(a,R)===Mt(u,R)),Jt=r=>r.length===1?r[0]:e`(${e.join(r,e` AND `)})`,re=r=>e.join(r.map(a=>e`${e.identifier(a)}`),e`, `),de=r=>e.join(r.map(a=>e`${a}`),e`, `),Ze=(r,a)=>{if(r==="postgres"){for(const[u,c]of Object.entries(a))if(typeof c=="string"&&c.includes("\0"))throw new g("BAD_REQUEST",`"${u}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},We=r=>r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):r,Oi=(r,a,u,c,R)=>{const f=[];for(let d=0;d<u.length+1;d+=1){const O=u[d],T=a.sortBy[d],A=d<u.length&&O!==void 0&&T!==void 0,v=T?.direction==="desc"?"desc":"asc",L=A?Ht(O,We(c[O]),v,!1):e`${e.identifier(Se)} < ${R}`;if(L===void 0)continue;const b=u.slice(0,d).map(q=>ot(r,e`${e.identifier(q)}`,We(c[q])));b.push(L),f.push(Jt(b))}return f.length>0?e.join(f,e` OR `):e`1 = 0`},qi=(r,a,u)=>{if(u.length!==a.length)return;const c=[];for(const[R,f]of a.entries()){const d=Ht(f.column,We(u[R]),f.direction,!0);if(d===void 0)continue;const O=[];for(let T=0;T<R;T+=1){const A=a[T];A!==void 0&&O.push(ot(r,e`${e.identifier(A.column)}`,We(u[T])))}O.push(d),c.push(Jt(O))}return c.length===0?e`(1 = 0)`:e`(${e.join(c,e` OR `)})`},ki=(r,a)=>{if(r.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${r.name}" requires at least one "sortBy" column for stable pagination`);const u=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[c,R]of r.sortBy.entries())u.push({column:a[c]??Re(c),direction:R.direction,nullable:!0});return u.push({column:Se,direction:"asc",nullable:!1}),u},Di=async(r,a,u,c,R)=>{const d=[];for(let v=0;v<R.length;v+=50)d.push(R.slice(v,v+50));const O=await Promise.all(d.map(async v=>I(r,a,e`SELECT * FROM ${e.identifier(c)} WHERE ${e.identifier("id")} IN (${de(v)})`))),T=new Map;for(const v of O)for(const L of v)T.set(L.id,L);const A=[];for(const v of R){const L=X(u,T.get(v));L&&A.push(L)}return A},Bi=r=>{const a=r.map(f=>Yt(f,"bytes")),u=JSON.stringify(Kt(a)?Gt(a):a),c=new TextEncoder().encode(u);let R="";for(const f of c)R+=String.fromCodePoint(f);return Jn+btoa(R)},Zt=r=>{if(r===void 0)return!1;const a=Xt(r);return a==="any"||a==="bigint"||a==="from"||a==="union"},nt=(r,a,u)=>{if(Zt(r.shape[a]))throw new g("BAD_REQUEST",`${u}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Wi=(r,a,u,c)=>{for(const R of u)nt(r,R,`groupBy(${a}, { by: [..."${R}"] })`);c.field!==void 0&&nt(r,c.field,`groupBy(${a}, { agg: { op: "${c.op}", field: "${c.field}" } })`)},it="__cdc_sweep",qe="__cdc_log_ts",en="global",Fi=6e4,Ui=1e4,xi=3e4;let Bt=0;const Pi=async(r,a)=>{const{autoincrementPrimaryKey:u,key:c,real:R,text:f}=a.companionTypes;await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(D)} (${e.identifier("seq")} ${e.raw(u)}, ${e.identifier("ts")} ${e.raw(R)} NOT NULL, ${e.identifier("table")} ${e.raw(c)} NOT NULL, ${e.identifier("id")} ${e.raw(c)} NOT NULL, ${e.identifier("op")} ${e.raw(c)} NOT NULL, ${e.identifier("doc")} ${e.raw(f)})`);const d=a.indexKeyPrefix?.("string");await Vt(r,a,{columns:e`${d===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(d))})`}, ${e.identifier("seq")}`,name:di,table:D,unique:!1}),await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(it)} (${e.identifier("id")} ${e.raw(c)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(R)} NOT NULL)`),await x(r,a,e`INSERT INTO ${e.identifier(it)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${en}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Hi=async(r,a,u)=>{const c=e`UPDATE ${e.identifier(it)} SET ${e.identifier("lease_until")} = ${u+Fi} WHERE ${e.identifier("id")} = ${en} AND ${e.identifier("lease_until")} <= ${u}`;if(a.supportsReturning)return(await I(r,a,e`${c} RETURNING ${e.identifier("id")}`)).length>0;const R=await x(r,a,c);return(a.affectedRows?a.affectedRows(R??{rowsAffected:0}):0)>0},ji=async(r,a,u,c)=>{if(!await Hi(r,a,c))return;const R=c-u;let f=!0;try{const d=await wi(r,a,D,qe);d!=="valid"&&(d==="invalid"&&await $i(r,a,D,qe),await Vt(r,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:qe,table:D,unique:!1}))}catch(d){f=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${qe}"; sweeping without it.`,d)}f&&(await I(r,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(D)} WHERE ${e.identifier("ts")} <= ${R} LIMIT 1`)).length===0||await x(r,a,e`
|
|
2
|
+
DELETE FROM ${e.identifier(D)} WHERE ${e.identifier("seq")} IN (
|
|
3
|
+
SELECT ${e.identifier("seq")} FROM (
|
|
4
|
+
SELECT ${e.identifier("seq")} FROM ${e.identifier(D)} WHERE +${e.identifier("ts")} <= ${R} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Ui))}
|
|
5
|
+
) AS ${e.identifier("expired")}
|
|
6
|
+
)
|
|
7
|
+
`)},tn=async(r,a)=>{const u=await I(r,a,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(D)}`),c=Number(u[0]?.seq??Number.NaN);return Number.isFinite(c)?c:void 0},Ki=async(r,a)=>{if(a.name!=="sqlite")return;const u=await I(r,a,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${D}`),c=Number(u[0]?.seq??Number.NaN);return Number.isFinite(c)?c:0},Gi=r=>JSON.stringify(Kt(r)?Gt(r):r),Vi=(r,a,u,c,R)=>e`INSERT INTO ${e.identifier(D)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${r}, ${a}, ${u}, ${c}, ${R===void 0?null:Gi(R)})`,nn=1e4,Yi=1e3,Xi=(r,a,u)=>{let c=a;for(const[R,f]of r.entries()){const d=Number(f.seq);if(d>c+1&&Number(f.ts)>u)return r.slice(0,R);c=d}return r},Eo=async(r,a,u)=>{const c=a.sinceSeq??0,R=Math.max(1,Math.min(a.limit??1e3,1e4)),f=await tn(r,u),d=await Ki(r,u);if(d!==void 0&&c>d)throw qn(d,c,"global");if(f!==void 0&&kn(f,c))throw Dn(f,c,"global");const O=await I(r,u,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(D)} WHERE seq > ${c} ORDER BY seq ASC LIMIT ${e.raw(String(R))}`),A=(u.name==="sqlite"?O:Xi(O,c,(a.now??Date.now())-nn)).map(v=>{const{doc:L}=v,b={id:String(v.id),op:String(v.op),seq:Number(v.seq),table:String(v.table),ts:Number(v.ts)};return typeof L=="string"?{...b,doc:jt(JSON.parse(L))}:b});return{changes:A,cursor:A.at(-1)?.seq??c}},Wt=(r,a)=>{const u=e.identifier(D),c=e`(SELECT MIN(v.seq) FROM ${u} v WHERE v.seq > ${r} AND v.seq - 1 > ${r} AND v.ts > ${a} AND NOT EXISTS (SELECT 1 FROM ${u} p WHERE p.seq = v.seq - 1))`;return e`${c} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${u} q WHERE q.seq > ${r} AND q.seq < ${c}) AS ${e.identifier("below")}`},Ft=(r,a,u)=>{const c=Number(a?.gap??Number.NaN);if(!Number.isFinite(c))return r;const R=Number(a?.below??Number.NaN);return Math.min(r,Number.isFinite(R)?R:u)},Qi=r=>{const a=e.identifier(D),u=e.identifier("table");return e`SELECT ${u}, seq FROM (WITH RECURSIVE "t"("name") AS (SELECT MIN(${u}) FROM ${a} UNION ALL SELECT (SELECT MIN(${u}) FROM ${a} WHERE ${u} > "t"."name") FROM "t" WHERE "t"."name" IS NOT NULL) SELECT "t"."name" AS ${u}, (SELECT MAX(seq) FROM ${a} WHERE ${u} = "t"."name" AND seq > ${r}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${u}`},zi=async(r,a,u,c={})=>{const R=e.identifier(D),f=u.name!=="sqlite",d=(c.now??Date.now())-nn;if(c.cursorOnly){const L=e`GREATEST((SELECT MAX(seq) FROM ${R}) - ${e.raw(String(Yi))}, ${a})`,b=await I(r,u,e`SELECT MAX(seq) AS seq${f?e`, ${Wt(L,d)}`:e``} FROM ${R}`),q=Number(b[0]?.seq??a);return{cursor:Ft(Number.isFinite(q)?q:a,b[0],a),tables:[]}}const O=await I(r,u,f?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Wt(e`${a}`,d)} FROM ${R} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:Qi(a));let T=a;const A=[];for(const L of O){const b=Number(L.seq);Number.isFinite(b)&&b>T&&(T=b),A.push(String(L.table))}T=Ft(T,O[0],a);const v=c.retained===!0?await tn(r,u):void 0;return{cursor:T,tables:A,...v===void 0?{}:{floor:v}}},Ji=/string or blob too big/iu,Zi=/row is too big/iu,eo=(r,a)=>{const{code:u,errno:c}=a,R=a instanceof Error?a.message:"";switch(r.name){case"mysql":return c===1118||u==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return Zi.test(R)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return Ji.test(R)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},to=(r,a,u)=>{const c=eo(r,a);if(c!==void 0)throw new g("PAYLOAD_TOO_LARGE",`document is too large to store in "${u}": a single row cannot exceed ${c}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},et=16,Ut="__lunora_patch_if_match__",xt=(r,a,u)=>{throw r.isUniqueViolation(a)?new ae(`unique constraint violation on "${u}"`,"unique"):(to(r,a,u),a)},tt=new WeakMap,Pt=new WeakMap,ye="superseded",no=3e4,ke="__lunora_companion_fence",se=(r,a,u)=>JSON.stringify([r,a,u]),De=r=>JSON.stringify(r,(a,u)=>typeof u=="bigint"?`${String(u)}n`:u),io=r=>{const a=Bn(r);return(u,c,R,f)=>c.some(d=>d instanceof fi)?hi(r,u,c,R):a(u,c,R,f)},po=r=>{const{crossShardCounter:a,crossShardReader:u,exec:c,maxRelationKeys:R,schema:f}=r,{dialect:d}=r,O={fieldRef:n=>Be(d,n),rangeTypeGuard:(n,t)=>pi(d,n,t),...d.name==="mysql"?{containsExpr:(n,t)=>{const i=At(n);return i===void 0?e`LOCATE(${t}, ${n}) > 0`:e`LOCATE(${Ct("mysql",t)}, ${i}) > 0`}}:{},...d.name==="postgres"?{containsExpr:(n,t)=>{const i=At(n);return i===void 0?e`strpos(${n}, ${t}) > 0`:e`strpos(${i}, ${Ct("postgres",t)}) > 0`}}:{},...d.name==="sqlite"?{}:{inList:io(d.name)}},T=new WeakMap,A=n=>{const t=T.get(n);if(t!==void 0)return t;const i={...O,serialize:(o,s)=>Nt(d,s,o,l=>oe(n,s,l))};return T.set(n,i),i},v=(n,t)=>ot(d.name,n,t),L=n=>{const t=re(n.columns),i=de(n.values),o=$=>d.name==="mysql"?e`VALUES(${e.identifier($)})`:e`excluded.${e.identifier($)}`,s=$=>d.name==="postgres"?e`${e.identifier(n.table)}.${e.identifier($)}`:e`${e.identifier($)}`,l=e.join(Object.entries(n.set(o,s)).map(([$,h])=>e`${e.identifier($)} = ${h}`),e`, `),p=d.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${l}`:e`ON CONFLICT(${e.identifier(n.conflictKey)}) DO UPDATE SET ${l}`;return e`INSERT INTO ${e.identifier(n.table)} (${t}) VALUES (${i}) ${p}`},b=r.clock??(()=>Date.now()),q=r.idGenerator??(()=>crypto.randomUUID()),K=r.cdc??!1,Q=typeof r.cdcRetentionMs=="number"&&Number.isFinite(r.cdcRetentionMs)&&r.cdcRetentionMs>0?r.cdcRetentionMs:void 0,Z=r.auth??{identity:null,userId:null},le=(n,t,i,o)=>K?[Vi(b(),n,t,i,o)]:[],on=async()=>{if(!K||Q===void 0)return;const n=b();if(!(n-Bt<xi)){Bt=n;try{await ji(c,d,Q,n)}catch{}}},rn=r.scheduler??Mn,Fe=Li();let ge=0;const ue=r.provisionScope??{},B=async()=>{const n=tt.get(ue);if(n)return n;const t=(async()=>{await yi(c,f,d),await Ri(c,f,d),await Si(c,f,d),await Rn(c,d),await mn(c,f,d),K&&await Pi(c,d)})().catch(i=>{throw tt.delete(ue),i});return tt.set(ue,t),t},me=async(n,t)=>{if(t!==void 0&&!Object.hasOwn(f.tables,t))throw new g("BAD_REQUEST",`ctx.db by-id write (table, id): "${t}" is not a table in this schema`);if(await B(),t===void 0)return bi(c,d,f,n,Fe);const i=Object.hasOwn(f.tables,t)?f.tables[t]:void 0;return i!==void 0&&zt(i)?t:void 0};let Te=Pt.get(ue);Te===void 0&&(Te=new Map,Pt.set(ue,Te));const P=Te,rt={},Ue=(n,t,i)=>{const o=(async()=>(await B(),await i(()=>P.get(n)?.run!==o)))(),s={definition:t,owner:rt,run:o,settled:!1};return o.then(()=>{s.settled=!0},()=>{P.get(n)===s&&P.delete(n)}).catch(()=>{}),P.set(n,s),o},st=async(n,t,i)=>{const o=P.get(n);if(o===void 0)return await Ue(n,t,i);const s=o.definition===t;if(s&&(o.settled||o.owner===rt))return await o.run;if(o.settled)return await Ue(n,t,i);let l;const p=new Promise(h=>{l=setTimeout(h,no,"stalled")}),$=await Promise.race([o.run,p]).finally(()=>{clearTimeout(l)});return $!=="stalled"&&s?$:P.get(n)===o?await Ue(n,t,i):await st(n,t,i)},xe=async(n,t,i)=>{const o=await st(n,t,i);return o===ye?await xe(n,t,i):o},at=async(n,t)=>{const i=P.get(n),o=i?.settled===!0&&i.definition===t?await i.run:void 0;if(typeof o=="boolean")return o;P.delete(n)},sn=n=>{const t=f.tables[n];for(const i of t?.aggregateIndexes??[])P.delete(se("aggregate",n,i.name));for(const i of t?.rankIndexes??[])P.delete(se("rank",n,i.name))},an=async(n,t)=>{const i=ie(n,t);return(await I(c,d,d.tableExists(i))).length>0},ct=async n=>{const{key:t}=d.companionTypes,i=q();await x(c,d,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ke)} (${e.identifier("name")} ${e.raw(t)} PRIMARY KEY, ${e.identifier("token")} ${e.raw(t)} NOT NULL)`),await x(c,d,L({columns:["name","token"],conflictKey:"name",set:s=>({token:s("token")}),table:ke,values:[n,i]}));const o=e`${e.identifier("name")} = ${n} AND ${e.identifier("token")} = ${i}`;return{guardedDelete:()=>e`DELETE FROM ${e.identifier(n)} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ke)} WHERE ${o})`,guardedInsert:(s,l)=>e`INSERT INTO ${e.identifier(n)} (${re(s)}) SELECT ${de(l)} FROM ${e.identifier(ke)} WHERE ${o}`}},cn=async(n,t,i)=>{const o=f.tables[n];if(!o||!await an(n,t.name))return!1;const s=t.by??[],l=new Map;await Ot(c,d,o,n,_=>{if(t.where&&!Ye(_,t.where))return;const w=J(s,_);It(l,w,t,_)});const p=ie(n,t.name);if(i())return ye;const $=await ct(p);await x(c,d,$.guardedDelete());const h=[];for(const[_,w]of l)h.push($.guardedInsert(["__key__","__value__","__count__"],[_,w.value,w.count]));return i()||await qt(c,d,h),i()?ye:!0},ve=(n,t)=>xe(se("aggregate",n,t.name),De(t),i=>cn(n,t,i)),dn=async(n,t,i,o)=>{const s=new Map;let l,p=!0;for(;p;){const $=l===void 0?o:[...o,e`${e.identifier("id")} > ${l}`],h=$.length>0?e` WHERE ${e.join($,e` AND `)}`:e``,_=await I(c,d,e`SELECT ${e.identifier("id")}, ${U(i.field??"")} FROM ${e.identifier(t)}${h} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(ze))}`);for(const w of Lt(n,_))It(s,"",i,w);l=_.at(-1)?.id,p=_.length===ze}return s.get("")?.value??null},ln=async(n,t,i)=>{const o=t.field??"",s=[],l=f.tables[n],p=(w,E)=>Nt(d,w,E,S=>l?oe(l,w,S):Qe(S));for(const w of t.by??[]){const E=p(w,i[w]??null);s.push(E===null?e`${U(w)} IS NULL`:e`${U(w)} = ${E}`)}for(const[w,E]of Object.entries(t.where??{})){const S=E!==null&&typeof E=="object"&&!Array.isArray(E)?E.eq:E,y=p(w,S),m=Be(d,w);s.push(y===null?e`${m} IS NULL`:e`${m} = ${y}`)}const $=s.length>0?e` WHERE ${e.join(s,e` AND `)}`:e``;if(l&&Zt(l.shape[o]))return dn(l,n,t,s);const h=Ee(t.op),_=await I(c,d,e`SELECT ${e.raw(h)}(${U(o)}) AS ${e.identifier("value")} FROM ${e.identifier(n)}${$}`);return ce(_[0]?.value)},un=(n,t)=>e`DELETE FROM ${e.identifier(n)} WHERE ${e.identifier("__key__")} = ${t} AND ${e.identifier("__count__")} <= 0`,fn=async(n,t,i,o)=>{const s=ie(n,t.name),{op:l}=t,p=t.field??"",$=i&&(!t.where||Ye(i,t.where))?i:void 0,h=o&&(!t.where||Ye(o,t.where))?o:void 0;if(!$&&!h)return[];if(l==="count"||l==="sum"||l==="avg"){const w=[],E=new Set;for(const[S,y]of[[$,-1],[h,1]]){if(!S)continue;const m=l==="count"?1:Xe(S[p]);if(m===void 0)continue;const N=J(t.by??[],S);E.add(N),w.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(C,M)=>({__count__:e`${M("__count__")} + ${C("__count__")}`,__value__:l==="count"?e`${M("__value__")} + ${C("__value__")}`:e`COALESCE(${M("__value__")}, 0) + ${C("__value__")}`}),table:s,values:[N,y*m,y]}))}for(const S of E)w.push(un(s,S));return w}const _=[];if($){const w=J(t.by??[],$),E=Xe($[p]),y=(await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${w}`))[0],m=ce(y?.value),N=(y?.count??0)-1;if(N<=0)_.push(e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${w}`);else if(y&&E!==void 0&&m!==null&&E===m){const C=await ln(n,t,$);_.push(e`UPDATE ${e.identifier(s)} SET ${e.identifier("__value__")} = ${C}, ${e.identifier("__count__")} = ${N} WHERE ${e.identifier("__key__")} = ${w}`)}else _.push(e`UPDATE ${e.identifier(s)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${w}`)}if(h){const w=J(t.by??[],h),E=Xe(h[p]);if(E===void 0)_.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(S,y)=>({__count__:e`${y("__count__")} + 1`}),table:s,values:[w,null,1]}));else{const S=l==="min"?"MIN":"MAX";_.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(y,m)=>({__count__:e`${m("__count__")} + 1`,__value__:e`${e.raw(S)}(COALESCE(${m("__value__")}, ${y("__value__")}), ${y("__value__")})`}),table:s,values:[w,E,1]}))}}return _},Ie=async n=>{const t=f.tables[n]?.aggregateIndexes;if(!(!t||t.length===0))for(const i of t)await ve(n,i)},fe=async(n,t,i)=>{const o=f.tables[n]?.aggregateIndexes,s=[];if(!o||o.length===0)return s;for(const l of o)await at(se("aggregate",n,l.name),De(l))&&s.push(...await fn(n,l,t,i));return s},wn=async(n,t)=>{const i=_e(n,t);return(await I(c,d,d.tableExists(i))).length>0},$n=async(n,t,i)=>{const o=f.tables[n];if(!o||!await wn(n,t.name))return!1;const s=_e(n,t.name);if(i())return ye;const l=await ct(s);await x(c,d,l.guardedDelete());const $=["__id__","__partition__",...t.sortBy.map((w,E)=>Re(E))];let h=[];const _=async()=>{const w=h;h=[],!(w.length===0||i())&&await qt(c,d,w)};return await Ot(c,d,o,n,async w=>{if(t.where&&!vt(w,t.where))return;const E=Me(t.partitionBy??[],w),S=t.sortBy.map(y=>Qe(w[y.field]??null));h.push(l.guardedInsert($,[w._id,E,...S])),h.length>=ze&&await _()}),await _(),i()?ye:!0},Pe=(n,t)=>xe(se("rank",n,t.name),De(t),i=>$n(n,t,i)),Ae=async n=>{const t=f.tables[n]?.rankIndexes;if(!(!t||t.length===0))for(const i of t)await Pe(n,i)},ee=async(n,t,i,o)=>{const s=f.tables[n],l=s?.rankIndexes,p=[];if(!l||l.length===0)return p;const $=s?.softDeleteMode?.field,h=$===void 0||o===void 0?void 0:o[$],_=h!=null;for(const w of l){if(i!==void 0&&o!==void 0&&Mi(w,i,o)||!await at(se("rank",n,w.name),De(w)))continue;const S=_e(n,w.name);if(i&&p.push(e`DELETE FROM ${e.identifier(S)} WHERE ${e.identifier("__id__")} = ${t}`),o&&!_){if(w.where&&!vt(o,w.where))continue;const y=w.sortBy.map((M,W)=>Re(W)),m=re(["__id__","__partition__",...y]),N=Me(w.partitionBy??[],o),C=w.sortBy.map(M=>Qe(o[M.field]??null));p.push(e`INSERT INTO ${e.identifier(S)} (${m}) VALUES (${de([t,N,...C])})`)}}return p},te=async(n,t)=>{try{const i=await t();i.length>0&&await Ei(c,d,i)}catch(i){throw sn(n),i}await on()},we=gn({dialect:d,exec:c,schema:f}),dt=new Set;for(const[n,t]of Object.entries(f.tables))for(const i of Object.values(t.triggerMap??{}))dt.add(`${n} ${i.timing} ${i.op}`);const G=(n,t,i)=>dt.has(`${n} ${t} ${i}`);let lt;const V=async(n,t,i)=>{if(ge+=1,ge>Dt)throw ge-=1,new ae(`trigger recursion exceeded ${String(Dt)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await zn({ctx:lt,event:i,op:t,schema:f,tableName:i.table,timing:n})}finally{ge-=1}},hn=async(n,t)=>{try{await x(c,d,t)}catch(i){xt(d,i,n)}},Ce=async(n,t)=>(await I(c,d,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} = ${t}`))[0],ut=async(n,t,i,o,s)=>{const l=e`${e.identifier(pe)}`,p=e.join([v(e`${e.identifier("id")}`,o.id),v(l,o[pe]??null),...s===void 0?[]:[e`(${s})`]],e` AND `),$=t==="UPDATE"?e`UPDATE ${e.identifier(n)} SET ${i}, ${l} = ${bt.sql(l)} WHERE ${p}`:e`DELETE FROM ${e.identifier(n)} WHERE ${p}`;try{if(d.supportsReturning)return(await I(c,d,e`${$} RETURNING ${e.identifier("id")}`)).length>0;const h=await x(c,d,$);return(d.affectedRows?d.affectedRows(h??{rowsAffected:0}):0)>0}catch(h){return xt(d,h,n)}},He=async(n,t,i,o)=>{if(o!==void 0&&!await ut(n,t,i,o))throw new ae(`optimistic concurrency conflict on "${n}" — the row changed during this mutation; refetch and retry`,"occ")},je=(n,t=n?._creationTime)=>({_creationTime:t,[pe]:bt.value(n?.[pe])}),ft=async(n,t,i,o,s,l,p)=>{const $=X(t,s);if(!$||s===void 0)throw new g("INTERNAL",`document not found: ${i}`);const h=Zn(t,o,$),_={...$,...ei(h),_id:i};Je(t,h,_,Z);const w=Ge(t,_,{only:new Set(Object.keys(h)),previous:()=>$,tolerateStoredNull:!0});Ze(d.name,Object.fromEntries(Object.keys(h).map(y=>[y,w[y]]))),ti(p,$,w),G(n,"before","update")&&await V("before","update",{doc:{...w},id:i,op:"update",previous:$,table:n}),await Ie(n),await Ae(n);const E=Object.keys(t.shape),S=e.join(E.map(y=>e`${e.identifier(y)} = ${oe(t,y,w[y]??null)}`),e`, `);if(await ut(n,"UPDATE",S,s,l))return await te(n,async()=>[...await fe(n,$,w),...await ee(n,i,$,w),...le(n,i,"update",w)]),await we(n,i,{document:w,previous:$,written:je(s)}),G(n,"after","update")&&await V("after","update",{doc:w,id:i,op:"update",previous:$,table:n}),w},_n=(n,t,i,o)=>{const s=Object.keys(n.shape);return{columns:["id","_creationTime",...s],values:[t,i,...s.map(l=>oe(n,l,o[l]??null))]}},En=async(n,t,i,o)=>{const s=ii(t,i.op,i.field,o.by,o.where);if(!s||!await ve(n,s.index))return;const p=ie(n,s.index.name),$=Object.keys(s.partial);if($.length===(s.index.by??[]).length&&$.length>0){const _=J(s.index.by??[],s.partial),w=await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(p)} WHERE ${e.identifier("__key__")} = ${_}`);if(w.length===0)return[];const E=w[0];return[{key:{...s.partial},value:Ve(i.op,{count:E.count,value:ce(E.value)})}]}return $.length>0?void 0:(await I(c,d,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(p)}`)).map(_=>{const w=_;return{key:jt(JSON.parse(w.key)),value:Ve(i.op,{count:w.count,value:ce(w.value)})}})},wt=n=>{const t=f.tables[n]?.shardMode?.kind;return t==="shardBy"||t==="root"},$t=n=>{throw new g("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${n}' (it spans every shard) — wire a cross-shard reader to support it`)},pn=(n,t)=>{if(t?.relationMask!==void 0&&t.with!==void 0&&Object.keys(t.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${n}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(t?.relationBaseWhere)for(const o of Object.keys(f.tables)){const s=t.relationBaseWhere(o);s!==void 0&&(i[o]=s)}return{orderBy:t?.orderBy,relationPolicies:i,where:F(t?.baseWhere,t?.where),with:t?.with}},Le=(n,t)=>wt(n)?u?u(n,pn(n,t)):$t(n):H.findMany(n,t),be=(n,t,i)=>ni(n,{fetcher:Le,maxRelationKeys:R,relationBaseWhere:i,schema:f,tableName:t}),yn=mi(async(n,t)=>{const i=await I(c,d,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} IN (${de(t)})`),o=new Map;for(const s of i){const{id:l}=s;typeof l=="string"&&o.set(l,s)}return o}),ht=async(n,t,i)=>{const{fetchLimit:o,limit:s,orderKeys:l,predicate:p}=await oi(t,i,{fetcher:Le,maxRelationKeys:R,schema:f,tableName:n}),$=z(p,A(t)),h=Ii(l,d);let _=e`SELECT * FROM ${e.identifier(n)}`;return $&&(_=e`${_} WHERE ${$}`),_=e`${_} ORDER BY ${h}`,o!==void 0&&(_=e`${_} LIMIT ${e.raw(String(o))}`),{limit:s,orderKeys:l,query:_}},H={relationWrites:On(f),async cdcChangedTables(n,t){if(K)try{return await B(),await zi(c,n,d,{...t,now:b(),retained:Q!==void 0})}catch{return}},async aggregate(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);if(await B(),Ee(t.op),t.op==="count")return H.count(n,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new g("INTERNAL",`aggregate(${n}, { op: "${t.op}" }): "field" is required for non-count reducers`);const o=Oe(i.softDeleteMode,void 0),s=F(F(t.baseWhere,t.where),o),l=await be(s,n,t.relationBaseWhere),p=l!==s;if(i.aggregateIndexes&&!t.baseWhere&&!p&&!o){const S=Qn(i.aggregateIndexes,t.op,t.field,t.where);if(S&&await ve(n,S.index)){const m=J(S.index.by??[],S.key),N=ie(n,S.index.name),M=(await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(N)} WHERE ${e.identifier("__key__")} = ${m}`))[0];return Ve(t.op,M===void 0?void 0:{count:M.count,value:ce(M.value)})}}nt(i,t.field,`aggregate(${n}, { op: "${t.op}", field: "${t.field}" })`);const $=z(l,A(i)),h=e.raw(Ee(t.op)),_=e`SELECT ${h}(${U(t.field)}) AS ${e.identifier("value")} FROM ${e.identifier(n)}`,E=(await I(c,d,$?e`${_} WHERE ${$}`:_))[0]?.value;return E==null?null:Number(E)},async count(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=Yn(t);if(o.restrictsCounts)throw new yt(n);const s=Oe(i.softDeleteMode,void 0),l=F(F(o.baseWhere,o.where),s),p=await be(l,n,o.relationBaseWhere),$=p!==l;if(i.aggregateIndexes&&!o.baseWhere&&!$&&!s){const E=Xn(i.aggregateIndexes,o.where);if(E&&await ve(n,E.index)){const y=J(E.index.by??[],E.key),m=ie(n,E.index.name),N=await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(m)} WHERE ${e.identifier("__key__")} = ${y}`);return Number(N[0]?.value??0)}}const h=z(p,A(i)),_=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(n)}`,w=await I(c,d,h?e`${_} WHERE ${h}`:_);return Number(w[0]?.count??0)},async delete(n,t,i){const o=await me(t,n);if(!o)return;const s=f.tables[o];if(!s)return;const l=await Ce(o,t);if(l===void 0)return;const p=X(s,l),$=i?.hard===!0,h=!$&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(h&&(!p||p[h]!==null&&p[h]!==void 0))){if(G(o,"before","delete")&&await V("before","delete",{id:t,op:"delete",previous:p??void 0,table:o}),await Vn({deletedId:t,deletedReference:_=>p?.[_],findHolders:async(_,w,E,S)=>{if(f.tables[_]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${_}' is not supported — would require Query Coordinator fan-out across shards`);return(await H.findMany(_,{...S,includeDeleted:$,where:{[w]:E}})).page},onCascade:(_,w)=>H.delete(_,w,i),onRestrict:_=>{throw new ae(_,"restrict")},onSetNull:(_,w,E)=>H.patch(_,w,{[E]:null}),schema:f,tableName:o}),await Ie(o),await Ae(o),h&&p){const _={[h]:b()},w={...p,..._};Je(s,_,w,Z);const E=e.join(Object.keys(s.shape).map(S=>e`${e.identifier(S)} = ${oe(s,S,w[S]??null)}`),e`, `);await He(o,"UPDATE",E,l),await te(o,async()=>[...await fe(o,p,w),...await ee(o,t,p,void 0),...le(o,t,"update",w)]),await we(o,t,{document:w,previous:p,written:je(l)}),G(o,"after","delete")&&await V("after","delete",{id:t,op:"delete",previous:p,table:o});return}await He(o,"DELETE",void 0,l),Fe.delete(t),await te(o,async()=>[...await fe(o,p??void 0,void 0),...await ee(o,t,p??void 0,void 0),...le(o,t,"delete")]),await we(o,t,void 0),G(o,"after","delete")&&await V("after","delete",{id:t,op:"delete",previous:p??void 0,table:o})}},async findFirst(n,t={}){return(await H.findMany(n,{...t,limit:1})).page[0]??null},async findFirstOrThrow(n,t={}){const i=await H.findFirst(n,t);if(i===null)throw new Gn(`findFirstOrThrow: no "${n}" document matched`);return i},async findMany(n,t={}){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=async(S,y,m,N)=>{if(wt(S))return a?ri(a,S,y,m,N):$t(S);const C=f.tables[S];if(!C)throw new g("INTERNAL",`unknown table: ${S}`);const M=Oe(C.softDeleteMode,void 0),W={[y]:{in:m}},Y=F(F(W,N),M),$e=await be(Y,S,void 0),Ne=z($e,A(C)),he=U(y);let j=e`SELECT ${he} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(S)}`;Ne&&(j=e`${j} WHERE ${Ne}`),j=e`${j} GROUP BY ${he}`;const k=await I(c,d,j),ne=new Map;for(const _t of k)ne.set(_t.__fk__,Number(_t.count??0));return ne},{limit:s,orderKeys:l,query:p}=await ht(n,i,t),$=await I(c,d,p),h=Lt(i,$);if(s===void 0)return t.with&&await Rt({fetcher:Le,groupedCounter:o,parents:h,...St(t),schema:f,tableName:n,with:t.with}),{continueCursor:null,isDone:!0,page:gt(h,t.select,t.with)};const _=h.length>s,w=_?h.slice(0,s):h,E=w.at(-1);return t.with&&await Rt({fetcher:Le,groupedCounter:o,parents:w,...St(t),schema:f,tableName:n,with:t.with}),{continueCursor:_&&E?Kn(E,l):null,isDone:!_,page:gt(w,t.select,t.with)}},async explain(n,t={}){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const{query:o}=await ht(n,i,t),s=d.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",l=await I(c,d,e`${e.raw(s)} ${o}`),{params:p,sql:$}=d.render(o);return{params:p,plan:l.map(h=>Ai(h)),sql:$}},async get(n,t){const i=Object.hasOwn(f.tables,n)?f.tables[n]:void 0;if(!i)throw new g("BAD_REQUEST",`ctx.db.get(table, id): "${n}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await B(),X(i,await yn.load(n,t)))},async groupBy(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=t.agg??{op:"count"};if(Ee(o.op),o.op!=="count"&&!o.field)throw new g("INTERNAL",`groupBy(${n}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const s=Oe(i.softDeleteMode,void 0),l=F(F(t.baseWhere,t.where),s),p=await be(l,n,t.relationBaseWhere),$=p!==l;if(i.aggregateIndexes&&!t.baseWhere&&!$&&!s){const y=await En(n,i.aggregateIndexes,o,t);if(y!==void 0)return y}Wi(i,n,t.by,o);const h=z(p,A(i)),_=t.by.map(y=>e`${U(y)} AS ${e.identifier(y)}`);if(o.op==="count")_.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!o.field)throw new g("INTERNAL",`groupBy(${n}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);_.push(e`${e.raw(Ee(o.op))}(${U(o.field)}) AS ${e.identifier("value")}`)}const w=e.join(t.by.map(y=>U(y)),e`, `);let E=e`SELECT ${e.join(_,e`, `)} FROM ${e.identifier(n)}`;h&&(E=e`${E} WHERE ${h}`),E=e`${E} GROUP BY ${w}`;const S=await I(c,d,E);return Ni(i,t.by,S)},async insert(n,t,i){const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);await B();const s=Ge(o,Pn(o,t,Z),{supplied:t,trusted:i?.allowExplicitId===!0});Ze(d.name,s);let l,p=!0;i?.clientId!==void 0?(Hn(i.clientId),l=i.clientId):i?.allowExplicitId&&typeof s._id=="string"?(jn(s._id),l=s._id):(l=q(),p=!1);const $=i?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:b(),h={...s,_creationTime:$,_id:l};G(n,"before","insert")&&await V("before","insert",{doc:{...h},id:l,op:"insert",table:n}),await Ie(n),await Ae(n);const{columns:_,values:w}=_n(o,l,$,s);return await hn(n,e`INSERT INTO ${e.identifier(n)} (${re(_)}) VALUES (${de(w)})`),p&&Fe.set(l,n),await te(n,async()=>[...await fe(n,void 0,h),...await ee(n,l,void 0,h),...le(n,l,"insert",h)]),await we(n,l,{document:h,written:{_creationTime:$,[pe]:null}}),G(n,"after","insert")&&await V("after","insert",{doc:h,id:l,op:"insert",table:n}),l},normalizeId(n,t){return xn(f,n,t)},async patch(n,t,i,o){Ke("patch",i);const s=await me(t,n);if(!s)throw new g("INTERNAL",`document not found: ${t}`);const l=f.tables[s];if(!l)throw new g("INTERNAL",`document not found: ${t}`);const p=Un(l,i)?et:1;for(let $=0;$<p;$+=1){const h=await Ce(s,t);if(await ft(s,l,t,i,h,void 0,o))return}throw new ae(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(n,t,i){Ke("patchIf",i.patch),await B();const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=z(i.where,A(o))??e`1 = 1`;for(let l=0;l<et;l+=1){const[p]=await I(c,d,e`SELECT *, CASE WHEN (${s}) THEN 1 ELSE 0 END AS ${e.identifier(Ut)} FROM ${e.identifier(n)} WHERE ${e.identifier("id")} = ${t}`);if(p===void 0)return{applied:!1,doc:null};const{[Ut]:$,...h}=p;if(Number($)!==1)return{applied:!1,doc:X(o,h)??null};const _=await ft(n,o,t,i.patch,h,s,{verify:i.verify});if(_)return{applied:!0,doc:_}}throw new ae(`patchIf on "${n}" lost the row to concurrent writes ${String(et)} times in a row; retry the operation`,"occ")},async restore(n,t){const i=await me(t,n),o=i===void 0?void 0:await Ce(i,t);if(!i||o===void 0)throw new g("INTERNAL",`document not found: ${t}`);const s=f.tables[i],l=s?.softDeleteMode?.field;if(!s||!l)throw new g("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const p=o[l]!==null&&o[l]!==void 0;if(await H.patch(n,t,{[l]:null}),p){const $=X(s,o);$!==null&&await te(i,async()=>await ee(i,t,void 0,{...$,[l]:null}))}},query(n){const t=f.tables[n];if(!t)throw new g("INTERNAL",`unknown table: ${n}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=[];let s=0,l;const p=d.name!=="mysql",$={...A(t),fieldRef:E=>e`m.${U(E)}`,rangeTypeGuard:()=>{throw new g("INTERNAL","a path range is never pushed into a search")}},h=E=>o.every(S=>S(E)),_=async(E,S)=>{await B();const y=2*An+E.filters.length,m=l===void 0?void 0:z(l,$,void 0,y),N=m!==void 0&&d.name==="sqlite"&&d.render(m).params.length+y>ui.boundParams,C=N?void 0:m,M=s>0||N,W=await Cn(c,d,t,n,C===void 0?E:{...E,scope:C},Ln(M?void 0:S));!M&&S===void 0&&bn(W);const Y=W.filter($e=>h($e));return S===void 0?Y:Y.slice(0,S)},w=E=>{const S={async*[Symbol.asyncIterator](){if(!E)throw new g("INTERNAL",i);yield*await _(E,void 0)},async collect(){if(!E)throw new g("INTERNAL",i);return _(E,void 0)},async collectWithScores(){throw new g("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${n}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(y){o.push(y);const m=si(y);return m!==void 0&&ai(m,t.shape,p)?l=F(l,m):s+=1,S},async first(){if(!E)throw new g("INTERNAL",i);return(await _(E,1))[0]??null},order(){return S},async paginate(y){if(!E)throw new g("INTERNAL",i);const m=vn(y);return In(await _(E,Nn(m)),m)},async take(y){if(!E)throw new g("INTERNAL",i);return _(E,y)},async unique(){if(!E)throw new g("INTERNAL",i);const y=await _(E,2);if(y.length>1)throw new li(`unique() on table "${n}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${n}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",i)},withSearchIndex(y,m){const N=(t.searchIndexes??[]).find(M=>M.name===y);if(!N)throw new g("INTERNAL",`unknown search index "${y}" on table "${n}"`);const C={definition:N,field:N.field,filters:[],hasQuery:!1,indexName:y,query:""};if(m(Tn(C,n,Sn(N.language))),!C.hasQuery)throw new g("INTERNAL",`search index "${y}" on table "${n}" requires a .search(field, query) call`);return w(C)}};return S};return w(void 0)},async rank(n,t,i){const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=o.rankIndexes?.find(W=>W.name===t);if(!s)throw new g("INTERNAL",`unknown rankIndex "${t}" on table "${n}"`);if(i.restrictsCounts)throw new yt(n);if(await B(),!await Pe(n,s))return null;const p=typeof i.row=="string"?i.row:i.row._id;if(!p)return null;const $=_e(n,s.name),h=s.sortBy.map((W,Y)=>Re(Y)),_=re(["__partition__",...h]),E=(await I(c,d,e`SELECT ${_} FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${p}`))[0];if(!E)return null;const S=E.__partition__,y=F(i.baseWhere,i.where);Et(y,f,n,"rank");const m=pt(s,y);if(m&&Me(s.partitionBy??[],m)!==S)return null;const N=Oi(d.name,s,h,E,p),C=await I(c,d,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${S} AND (${N})`),M=await I(c,d,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${S}`);return{position:Number(C[0]?.c??0)+1,total:Number(M[0]?.c??0)}},async rankPage(n,t,i={}){Et(F(i.baseWhere,i.where),f,n,"rankPage");const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=o.rankIndexes?.find(k=>k.name===t);if(!s)throw new g("INTERNAL",`unknown rankIndex "${t}" on table "${n}"`);if(await B(),!await Pe(n,s))return{continueCursor:null,isDone:!0,page:[]};const p=_e(n,s.name),$=s.sortBy.map((k,ne)=>Re(ne)),h=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),_=F(i.baseWhere,i.where),w=pt(s,_),E=ki(s,$),S=e.join(E.flatMap(k=>Qt(d,{direction:k.direction,field:k.column,nullable:k.nullable})),e`, `),y=[];typeof i.partitionKey=="string"?y.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):w&&y.push(e`${e.identifier("__partition__")} = ${Me(s.partitionBy??[],w)}`);const m=Fn(i);if(m!==void 0){const k=qi(d.name,E,m);k!==void 0&&y.push(k)}const N=re([Se,"__partition__",...$]);let C=e`SELECT ${N} FROM ${e.identifier(p)}`;y.length>0&&(C=e`${C} WHERE ${e.join(y,e` AND `)}`),C=e`${C} ORDER BY ${S} LIMIT ${e.raw(String(h+1))}`;const M=await I(c,d,C),W=M.length>h,Y=W?M.slice(0,h):M,$e=Y.map(k=>k[Se]),Ne=await Di(c,d,o,n,$e);let he=null;const j=Y.at(-1);if(W&&j!==void 0){const k=[j.__partition__,...$.map(ne=>j[ne]),j[Se]];he=Bi(k)}return{continueCursor:he,isDone:!W,page:Ne}},async replace(n,t,i,o){Ke("replace",i);const s=await me(t,n);if(!s)throw new g("INTERNAL",`document not found: ${t}`);const l=f.tables[s];if(!l)throw new g("INTERNAL",`document not found: ${t}`);const p=await Ce(s,t);if(p===void 0)throw new g("INTERNAL",`document not found: ${t}`);const h=Wn(f,s,"update")||(l.aggregateIndexes??[]).length>0||(l.rankIndexes??[]).length>0?X(l,p)??void 0:void 0,_=o?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,w=typeof p._creationTime=="number"?p._creationTime:void 0,E=_??w??b(),S={...i,_creationTime:E,_id:t};Je(l,i,S,Z);const y=Ge(l,S,{previous:()=>h??X(l,p)??void 0,supplied:i,trusted:o?.allowExplicitId===!0});Ze(d.name,y),G(s,"before","update")&&await V("before","update",{doc:{...y},id:t,op:"update",previous:h,table:s}),await Ie(s),await Ae(s);const m=Object.keys(l.shape),N=e.join([e`${e.identifier("_creationTime")} = ${E}`,...m.map(C=>e`${e.identifier(C)} = ${oe(l,C,y[C]??null)}`)],e`, `);await He(s,"UPDATE",N,p),await te(s,async()=>[...await fe(s,h,y),...await ee(s,t,h,y),...le(s,t,"update",y)]),await we(s,t,{document:y,previous:h,written:je(p,E)}),G(s,"after","update")&&await V("after","update",{doc:y,id:t,op:"update",previous:h,table:s})}};return lt={db:H,scheduler:rn},H};export{po as createSqlCtxDb,So as decodeGlobalRow,zi as readSqlCdcChangedTables,Eo as readSqlCdcChanges,tn as readSqlCdcFloor,Pi as runSqlCdcMigration,ji as sweepSqlCdcRetention};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{q,c as vt,m as Dt,r as F,a as qt,l as lt,w as D,b as Ft}from"./ctx-db-search-state-Dt0iNPGb.mjs";import{ftsUnmappedPage as bt,groupUnmappedRows as Ut,ftsWriteDocument as mt,ftsPurgeDocument as pt,ftsCompanionDdl as kt,unionAll as Ht,ftsRowidMapName as Pt}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{q as p,u as Bt,l as Q,a as O,i as C,c as V,j as L,b as T,m as ht,e as rt,x as jt,r as Wt,z as xt}from"./sql-exec-BKz380dy.mjs";import{OCC_VERSION_COLUMN as Kt}from"./OCC_VERSION_COLUMN-ByC64Jgx.mjs";const Gt=n=>{const t=atob(n),e=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(e)},Yt=()=>new h("BAD_REQUEST","invalid cursor"),ot=16,st=8,y=1024,b=(n,t)=>t.query(n),Qt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",r=(e.codePointAt(0)??0)+1;if(r>=55296&&r<=57343||r>1114111)return{exact:!0,lower:n,upper:n};const o=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:o+String.fromCodePoint(r)}},Ln=(n,t,e)=>{const r={eq:(o,s)=>{if(!n.definition.filterFields?.includes(o))throw new h("INTERNAL",`field "${o}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=st)throw new h("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(st)} .eq() filters are supported per search query`);return n.filters.push({field:o,value:s}),r},search:(o,s)=>{const a=n;if(o!==a.definition.field)throw new h("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${o}"`);const f=b(s,e).length;if(f>ot)throw new h("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(ot)} search terms are supported (got ${String(f)})`);return a.field=o,a.query=s,a.hasQuery=!0,r}};return r},Mn=n=>{if(n.length>y)throw new h("BAD_REQUEST",`more than ${String(y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},vn=n=>Math.min(n.offset+n.numItems+1,y),Vt=n=>btoa(`search:${String(n)}`),Xt=n=>{let t;try{t=Gt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},Dn=n=>{if(typeof n.endCursor=="string")throw new h("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new h("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Xt(n.cursor):0;if(e===void 0)throw Yt();if(e+t>=y)throw new h("BAD_REQUEST",`search pagination reaches the ${String(y)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,y-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},qn=(n,t)=>{const e=t.offset+t.numItems,r=t.numItems>0&&n.length>e;return{continueCursor:r?Vt(e):null,isDone:!r,page:n.slice(t.offset,e)}},Fn=n=>{if(n===void 0)return y+1;if(!Number.isFinite(n))return y;const t=Math.max(0,Math.floor(n));if(t>y)throw new h("BAD_REQUEST",`search returns at most ${String(y)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},Jt=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const r of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[r]}return e},U=(n,t)=>`${n}__fts_${t}`,S="__id__",g="__token__",A="__n__",zt=1e3,Zt=(n,t)=>t.document(n),W=(n,t)=>Jt(n,t),tn=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",nn=(n,t,e)=>n!==void 0&&t!==void 0&&W(n,e.field)===W(t,e.field),gt=(n,t)=>Zt(tn(W(n,t.field)),q(t.language)).slice(0,zt),X=(n,t)=>gt(n,t).join(" "),Tt=(n,t)=>{const e=new Map;for(const r of gt(n,t))e.set(r,(e.get(r)??0)+1);return e},yt=[Kt,"_creationTime"],at=50,$=(n,t)=>i`${i.identifier(n)}.${i.identifier(t)}`,M=(n,t,e)=>i`DELETE FROM ${i.identifier(n)} WHERE ${$(n,S)} = ${t}${e===void 0?i``:i` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const r=yt.map(o=>i` AND ${Bt(n.name,$(e,o),t[o]??null)}`);return i`SELECT 1 FROM ${i.identifier(e)} WHERE ${$(e,"id")} = ${t.id}${i.join(r)}${n.name==="postgres"?i` FOR SHARE`:i``}`},v=(n,t)=>i`EXISTS (${Rt(n,t)})`,k=(n,t)=>i`NOT EXISTS (SELECT 1 FROM ${i.identifier(n)} WHERE ${$(n,"id")} = ${t})`,_t=(n,t,e,r)=>r===void 0?k(t,e):v(n,{row:r,table:t}),J=async(n,t,e,r)=>{const o=new Map;for(let s=0;s<r.length;s+=at){const a=r.slice(s,s+at),f=await p(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${$(e,"id")} IN (${i.join(a.map(u=>i`${u}`),i`, `)})`);for(const u of f)o.set(String(u.id),u)}return o},x=(n,t,e)=>n.name==="mysql"?i`${i.identifier(t)}(${i.raw(String(e))})`:n.textPatternOperatorClass===void 0?i`${i.identifier(t)}`:i`${i.identifier(t)} ${i.raw(n.textPatternOperatorClass)}`,z=512,Z=(n,t)=>({columns:i`${x(n,g,256)}, ${x(n,S,z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),B=n=>i`${n} COLLATE utf8mb4_0900_bin`,j=(n,t)=>{const e=JSON.stringify(t.map(([r,o])=>({o,t:r})));switch(n.name){case"mysql":return i`JSON_TABLE(${e}, '$[*]' COLUMNS (${i.identifier("t")} VARCHAR(256) PATH '$.t', ${i.identifier("o")} INT PATH '$.o')) AS ${i.identifier("j")}`;case"postgres":return i`json_to_recordset(${e}::json) AS ${i.identifier("j")}(${i.identifier("t")} text, ${i.identifier("o")} integer)`;default:return i`(SELECT json_extract(${$("e","value")}, '$.t') AS ${i.identifier("t")}, json_extract(${$("e","value")}, '$.o') AS ${i.identifier("o")} FROM json_each(${e}) AS ${i.identifier("e")}) AS ${i.identifier("j")}`}},Nt=(n,t,e,r,o)=>{const s=i.join([g,S,A].map(f=>i.identifier(f)),i`, `),a=f=>i`INSERT INTO ${i.identifier(t)} (${s}) SELECT ${$("j","t")}, ${e}, ${$("j","o")} FROM ${j(n,r)} WHERE ${f}`;switch(n.name){case"mysql":{const f=v(n,o),u=$(t,g),c=i.identifier("held");return[i`${a(i`${f} AND NOT EXISTS (SELECT 1 FROM ${i.identifier(t)} AS ${c} WHERE ${$("held",S)} = ${e} AND ${$("held",g)} = ${B($("j","t"))})`)} ON DUPLICATE KEY UPDATE ${$(t,A)} = ${$(t,A)}`,i`UPDATE ${i.identifier(t)} JOIN ${j(n,r)} ON ${u} = ${B($("j","t"))} SET ${$(t,A)} = ${$("j","o")} WHERE ${$(t,S)} = ${e} AND ${f}`,i`DELETE FROM ${i.identifier(t)} WHERE ${$(t,S)} = ${e} AND ${f} AND ${u} NOT IN (SELECT ${B($("j","t"))} FROM ${j(n,r)})`]}case"postgres":{const f=i.identifier("__source__"),u=i.identifier("__purged__"),c=i`EXISTS (SELECT 1 FROM ${f})`;return[i`WITH ${f} AS (${Rt(n,o)}), ${u} AS (${M(t,e,c)} RETURNING 1) ${a(i`${c} AND (SELECT COUNT(*) FROM ${u}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const f=v(n,o);return[M(t,e,f),i`${a(f)} ON CONFLICT DO NOTHING`]}}},At={uniqueKeyMissing:!1,unmappedSkipped:0},ft=new Set,ut=(n,t)=>{ft.has(n)||(ft.add(n),console.warn(`[@lunora/sql-store] ${t}`))},ct=100,dt=3,K=async(n,t,e,r=0)=>{const{companion:o,definition:s,index:a,tableName:f}=e,u={done:!0,last:r,left:0};if((await p(n,t,t.tableExists(f))).length===0)return u;const d=await p(n,t,bt(o,ct,r));if(d.length===0)return u;const w=Math.max(...d.map(_=>Number(_.rowid))),E=Ut(d),l=await J(n,t,f,[...E.keys()]),m=[];for(const[_,nt]of E){const P=l.get(_),et=P===void 0?void 0:Q(s,P),it=_t(t,f,_,P);m.push(...et?mt(o,_,X(et,a),{guard:it,unmappedRowids:nt}):pt(o,_,{guard:it,unmappedRowids:nt}))}await O(n,t,m);const R=await p(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(o)} WHERE ${$(o,"rowid")} > ${Math.max(0,r)} AND ${$(o,"rowid")} <= ${w}`);return{done:d.length<ct,last:w,left:Number(R[0]?.n??0)}},en=async(n,t,e)=>{let r=0,o=0;for(;;){let s=await K(n,t,e,r);for(let a=1;s.left>0&&a<dt;a+=1)s=await K(n,t,e,r);if(s.left>0&&(o+=s.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(s.left)} row(s) lost every one of ${String(dt)} attempts to a concurrent write and were left for a later pass.`)),s.done)return o;r=s.last}},rn=async(n,t,e,r)=>r==="step"?(await K(n,t,e),At):{uniqueKeyMissing:!1,unmappedSkipped:await en(n,t,e)},G=n=>`${n}__btree`,on=async(n,t,e)=>{const r=Z(t,e),o=await C(n,t,e,r.name);if(o!=="valid"){if(o==="absent"&&(await p(n,t,i`SELECT 1 AS ${i.identifier("present")} FROM ${i.identifier(e)} LIMIT 1`)).length===0)try{await V(n,t,{...r,concurrently:!1}),await L(n,t,e,G(e));return}catch(a){if(await C(n,t,e,r.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},sn=async(n,t,e)=>{const r=$(e,S),o=$(e,g);return(await p(n,t,i`SELECT ${r} AS ${i.identifier("id")}, ${o} AS ${i.identifier("token")}, COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(e)} GROUP BY ${r}, ${o} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},an=(n,t,{count:e,id:r,token:o})=>{const s=i`${$(t,S)} = ${r} AND ${$(t,g)} = ${o}`;switch(n.name){case"mysql":return i`DELETE FROM ${i.identifier(t)} WHERE ${s} LIMIT ${i.raw(String(e-1))}`;case"postgres":return i`DELETE FROM ${i.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${i.identifier(t)} WHERE ${s} OFFSET 1))`;default:return i`DELETE FROM ${i.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${i.identifier(t)} WHERE ${s} LIMIT -1 OFFSET 1)`}},fn=async(n,t,e,r)=>{const{companion:o,definition:s,index:a,tableName:f}=e;for(const d of r)await T(n,t,an(t,o,d));const u=[...new Set(r.map(d=>d.id))],c=await J(n,t,f,u);for(const d of u){const w=c.get(d),E=w===void 0?void 0:Q(s,w);if(w!==void 0&&E){const l=[...Tt(E,a)];await O(n,t,Nt(t,o,d,l,{row:w,table:f}));continue}await T(n,t,M(o,d,_t(t,f,d,w)))}},un=async(n,t,e)=>t.name!=="mysql"?"":(await p(n,t,i`SELECT COLUMN_NAME AS ${i.identifier("name")}, COLLATION_NAME AS ${i.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${S})`)).filter(o=>!String(o.collation).endsWith("_bin")).map(o=>` Its ${String(o.name)} column uses ${String(o.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(o.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),cn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const r=$(e,S),o=await p(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM (SELECT 1 AS ${i.identifier("x")} FROM ${i.identifier(e)} GROUP BY LEFT(${r}, ${i.raw(String(z))}), ${$(e,g)} HAVING COUNT(DISTINCT ${r}) > 1) AS ${i.identifier("shared")}`);return Number(o[0]?.n??0)},dn=async(n,t,e)=>{const r=Z(t,e),o=await C(n,t,e,r.name);if(o==="valid")return"valid";o==="invalid"&&await L(n,t,e,r.name);try{return await V(n,t,r),"built"}catch(s){const a=await C(n,t,e,r.name);if(a==="valid")return"valid";if(a==="invalid"&&await L(n,t,e,r.name),!t.isUniqueViolation(s))throw s;return"refused"}},$t=3,$n=async(n,t,e)=>{const{companion:r}=e,o=await un(n,t,r);let s="";o!==""&&console.warn(`[@lunora/sql-store] search companion "${r}" folds case and accents in its unique key.${o}`);for(let a=0;a<$t;a+=1){const f=await dn(n,t,r);if(f==="valid")return await L(n,t,r,G(r)),!0;if(f==="refused"){const u=await sn(n,t,r);if(u.length>0)await fn(n,t,e,u);else{const c=await cn(n,t,r);s=c>0?` ${String(c)} token(s) are held by document ids that agree on their first ${String(z)} characters, which the key cannot tell apart; shorten those ids.`:o}}}return await C(n,t,r,Z(t,r).name)==="valid"?(await L(n,t,r,G(r)),!0):(console.warn(`[@lunora/sql-store] search companion "${r}" still has no unique key after ${String($t)} attempts: writes keep working, but two backfills racing over one row can index it twice.${s}`),!1)},wn=async(n,t,e,r)=>r==="step"?At:{uniqueKeyMissing:!await $n(n,t,e),unmappedSkipped:0},Sn=(n,t)=>t?i`${i.identifier(g)} LIKE ${`${n}%`}`:i`${i.identifier(g)} = ${n}`,Ot=(n,t)=>{const e=t.filters.map(r=>i`m.${rt(r.field)} = ${jt(r.value)}`);return n.softDeleteMode&&e.push(i`m.${rt(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(i`(${t.scope})`),e},It=async(n,t,e,r,o,s,a)=>{const f=Ot(e,o);let u=i`SELECT m.* FROM (${a}) s JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = s.${i.identifier(S)}`;return f.length>0&&(u=i`${u} WHERE ${i.join(f,i` AND `)}`),u=i`${u} ORDER BY s.${i.identifier("__score__")} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(s))}`,ht(e,await p(n,t,u))},En=async(n,t,e,r,o,s)=>{const a=b(o.query,q(o.definition.language));if(a.length===0)return[];const f=U(r,o.indexName),u=a.length-1,c=a.map((m,R)=>Sn(m,R===u)),d=i.join(c,i` OR `),w=c.map(m=>i`SUM(CASE WHEN ${m} THEN ${i.identifier(A)} ELSE 0 END)`),E=i.join(w.map(m=>i`${m} > 0`),i` AND `),l=i`SELECT ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM ${i.identifier(f)} WHERE ${d} GROUP BY ${i.identifier(S)} HAVING ${E}`;return It(n,t,e,r,o,s,l)},ln=async(n,t,e,r,o,s)=>{const a=b(o.query,q(o.definition.language));if(a.length===0)return[];const f=U(r,o.indexName),u=`${f}__vocab`,c=a.length-1,d=a.map((l,m)=>{const R=Qt(l,m===c),_=R.exact?i`${i.identifier("term")} = ${R.lower}`:i`${i.identifier("term")} >= ${R.lower} AND ${i.identifier("term")} < ${R.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(m))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(u)} WHERE ${_} GROUP BY ${i.identifier("doc")}`}),w=a.map((l,m)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(m))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),E=i`SELECT f.${i.identifier(S)} AS ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM (${Ht(d)}) u JOIN ${i.identifier(f)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(S)} HAVING ${i.join(w.map(l=>i`${l} > 0`),i` AND `)}`;return It(n,t,e,r,o,s,E)},mn=async(n,t,e,r,o,s)=>{const a=t.nativeTextSearch,f=b(o.query,q(o.definition.language));if(!a||f.length===0)return[];const u=U(r,o.indexName),c=[a.matches(u,f),...Ot(e,o)],d=i`SELECT m.* FROM ${i.identifier(u)} JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = ${i.identifier(u)}.${i.identifier(S)} WHERE ${i.join(c,i` AND `)} ORDER BY ${a.rank(u,f)} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(s))}`;return ht(e,await p(n,t,d))},pn={ensureCompanion:async(n,t,e)=>{const{integer:r,key:o}=t.companionTypes;await T(n,t,i`CREATE TABLE IF NOT EXISTS ${i.identifier(e)} (${i.identifier(g)} ${i.raw(o)} NOT NULL, ${i.identifier(S)} ${i.raw(o)} NOT NULL, ${i.identifier(A)} ${i.raw(r)} NOT NULL)`),await V(n,t,{columns:x(t,S,191),name:`${e}__by_id`,table:e,unique:!1}),await on(n,t,e)},indexDocument:async(n,t,e,r,o,s)=>{const a=[...Tt(r,o)];await O(n,t,Nt(t,e,String(s.row.id),a,s))},migrate:wn,name:"inverted",purgeDocument:async(n,t,e,r,o)=>{await T(n,t,M(e,r,k(o,r)))},runSearch:En},hn={ensureCompanion:async(n,t,e)=>{await O(n,t,kt(e))},indexDocument:async(n,t,e,r,o,s)=>{await O(n,t,mt(e,String(s.row.id),X(r,o),{guard:v(t,s)}))},migrate:rn,name:"fts5",purgeDocument:async(n,t,e,r,o)=>{await O(n,t,pt(e,r,{guard:k(o,r)}))},runSearch:ln},gn={ensureCompanion:async(n,t,e)=>{const r=t.nativeTextSearch;if(r){await T(n,t,r.createCompanion(e,t.companionTypes.key));for(const o of r.createIndexes(e))await T(n,t,o)}},indexDocument:async(n,t,e,r,o,s)=>{const a=t.nativeTextSearch;a&&await T(n,t,a.indexDocument(e,String(s.row.id),X(r,o),v(t,s)))},name:"native",purgeDocument:async(n,t,e,r,o)=>{await T(n,t,M(e,r,k(o,r)))},runSearch:mn},I=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?gn:t.supportsFts5?hn:pn,H=(n,t)=>`${vt(n)}/${I(n,t).name}`,tt=function*(n){for(const[t,e]of Object.entries(n.tables)){const r=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!r))for(const o of r)yield[t,e,o]}},N=(n,t)=>U(n,t.name),Tn=async(n,t,e,r)=>{const o=N(e,r);return lt(await F(n,t,o),H(r,t)).finished?!0:Ft(n,t,o)},bn=async(n,t,e,r,o,s)=>{if(!await Tn(n,t,r,o.definition))throw new h("SEARCH_INDEX_BUILDING",`search index "${o.indexName}" on table "${r}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return I(o.definition,t).runSearch(n,t,e,r,o,s)},wt=n=>n.slice(n.lastIndexOf("/")+1),St=200,Et=5,yn=async(n,t,e,r)=>{const o=[...r.keys()],s=await p(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${i.identifier("id")} >= ${o[0]} AND ${i.identifier("id")} <= ${o.at(-1)} ORDER BY ${i.identifier("id")} ASC`),a=new Map;for(const f of s){const u=f.id,c=r.get(u)?.row;c&&yt.some(d=>String(c[d])!==String(f[d]))&&a.set(u,{row:f})}return a},Y=async(n,t,e,r,o,s,a)=>{const f=I(s,t);let u=a;for(let c=0;u.size>0&&c<Et;c+=1){for(const{document:d,row:w}of u.values()){const E=d??Q(e,w);E&&await f.indexDocument(n,t,o,E,s,{row:w,table:r})}u=await yn(n,t,r,u)}u.size>0&&console.warn(`[@lunora/sql-store] search index "${o}": ${String(u.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,r,o)=>{const s=N(r,o),a=H(o,t),f=lt(await F(n,t,s),a);if(f.finished)return!0;if(f.wipe&&await D(n,t,s,void 0,!1,a),(await p(n,t,t.tableExists(r))).length===0)return await D(n,t,s,void 0,!0,a),!0;const c=await Wt(n,t,r,f.cursor,St),d=c.findLast(l=>typeof l.id=="string")?.id,w=new Map;for(const l of c)typeof l.id=="string"&&w.set(l.id,{row:l});await Y(n,t,e,r,s,o,w);const E=c.length<St;return await D(n,t,s,d??f.cursor,E,a),E},Lt=async(n,t,e)=>{await Dt(n,e);for(const[r,,o]of tt(t)){const s=N(r,o),a=H(o,e),f=await F(n,e,s);f.profile!==void 0&&wt(f.profile)!==wt(a)&&(await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(s)}`),await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(Pt(s))}`),await qt(n,e,s)),await I(o,e).ensureCompanion(n,e,s)}},Rn=async(n,t,e,r,o)=>{const s=N(r,o);if((await F(n,t,s)).profile!==void 0)return;let f=0;(await p(n,t,t.tableExists(r))).length>0&&await xt(n,t,e,r,()=>{f+=1},{limit:1}),await D(n,t,s,void 0,f===0,H(o,t))},Mt=async(n,t,e,r,o,s)=>await I(o,t).migrate?.(n,t,{companion:N(r,o),definition:e,index:o,tableName:r},s)??{uniqueKeyMissing:!1,unmappedSkipped:0},Un=async(n,t,e)=>{await Lt(n,t,e);for(const[r,o,s]of tt(t)){if(await Mt(n,e,o,r,s,"step"),s.staged){await Rn(n,e,o,r,s);continue}await Ct(n,e,o,r,s)}},kn=async(n,t,e)=>{const r={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[o,s,a]of tt(t)){const f=await Mt(n,e,s,o,a,"drain");r.unmappedSkipped+=f.unmappedSkipped,f.uniqueKeyMissing&&r.uniqueKeyMissing.push(N(o,a));let u=!1;for(;!u;)u=await Ct(n,e,s,o,a)}return r},Hn=n=>{const{dialect:t,exec:e,schema:r}=n;return async(o,s,a)=>{const f=r.tables[o],u=f?.searchIndexes;if(!(!f||!u||u.length===0))for(const c of u){if(nn(a?.previous,a?.document,c))continue;const d=N(o,c);if(a){await Y(e,t,f,o,d,c,new Map([[s,{document:a.document,row:{...a.written,id:s}}]]));continue}await I(c,t).purgeDocument(e,t,d,s,o);const E=(await J(e,t,o,[s])).get(s);E!==void 0&&await Y(e,t,f,o,d,c,new Map([[s,{row:E}]]))}}};export{Ln as A,Dn as C,qn as R,Fn as T,bn as a,kn as b,Hn as c,vn as d,Un as r,ot as u,Mn as x};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{b as $,q as h}from"./sql-exec-BKz380dy.mjs";const y=["de","en","es","fr","it","nl","none","pt"],L=i=>y.includes(i),R="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",A="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",q="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",F="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",N="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",_="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",b="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",C=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),x=/[\u0080-\u{10FFFF}]/u,H=/[\p{L}\p{N}]+/gu,O=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,g=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,j=i=>{if(!g.test(i))return[i];const n=[];let t=0;for(const r of i.matchAll(O)){const o=r.index,s=[...r[0]];if(o>t&&n.push(i.slice(t,o)),t=o+r[0].length,s.length===1){n.push(r[0]);continue}for(let a=0;a+1<s.length;a+=1)n.push(`${String(s[a])}${String(s[a+1])}`)}return t<i.length&&n.push(i.slice(t)),n},v=i=>x.test(i)?i.normalize("NFD").replaceAll(C,"").normalize("NFC").toLowerCase():i.toLowerCase(),p=i=>new Set(v(i).split(" ")),z={de:p(A),en:p(R),es:p(q),fr:p(F),it:p(N),nl:p(_),none:new Set,pt:p(b)},D=3,U=256,w=new Map,k=i=>{const n=i!==void 0&&L(i)?i:"none",t=w.get(n);if(t)return t;const r=z[n],o=a=>{const u=v(a),f=u.match(H)??[],l=(g.test(u)?f.flatMap(c=>j(c)):f).filter(c=>c.length<=U);return r.size===0?l:l.filter(c=>!r.has(c))},s={document:o,profile:`${n}-v${String(D)}`,query:a=>{const u=o(a),f=new Set,l=[];for(let c=u.length-1;c>=0;c-=1){const m=u[c];f.has(m)||(f.add(m),l.push(m))}return l.toReversed()}};return w.set(n,s),s},W=i=>`${k(i.language).profile}:${i.field}`,S=i=>{const n=i.slice(i.indexOf(":")+1),t=n.lastIndexOf("/");return t===-1?n:n.slice(0,t)},V=(i,n)=>i.profile!==n?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},M=(i,n)=>typeof i=="string"&&S(i)===S(n),d="__lunora_search_state",K=async(i,n)=>{const{integer:t,key:r}=n.companionTypes,o=async(s,a)=>{try{await $(i,n,e`ALTER TABLE ${e.identifier(d)} ADD COLUMN ${e.identifier(s)} ${e.raw(a)}`)}catch{}};await $(i,n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (${e.identifier("companion")} ${e.raw(r)} PRIMARY KEY, ${e.identifier("cursor")} ${e.raw(r)}, ${e.identifier("done")} ${e.raw(t)} NOT NULL DEFAULT 0, ${e.identifier("profile")} ${e.raw(r)}, ${e.identifier("covered")} ${e.raw(t)} NOT NULL DEFAULT 0)`),await o("profile",r),await o("covered",`${t} NOT NULL DEFAULT 0`),await $(i,n,e`UPDATE ${e.identifier(d)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},T=i=>i===1||i===!0||i==="1",P=async(i,n,t)=>{const r=await h(i,n,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`);return T(r[0]?.covered)},Y=async(i,n,t)=>{await $(i,n,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`)},X=async(i,n,t)=>{const o=(await h(i,n,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`))[0];if(!o)return{cursor:void 0,done:!1,profile:void 0};const{cursor:s,profile:a}=o;return{cursor:typeof s=="string"?s:void 0,done:T(o.done),profile:typeof a=="string"?a:void 0}},G=async(i,n,t,r,o,s)=>{const a=r??null,u=await h(i,n,e`SELECT ${e.identifier("profile")} FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`),f=M(u[0]?.profile,s),l=o?1:0,c=o||!f?e`${e.identifier("covered")} = ${l}`:e`${e.identifier("covered")} = ${e.identifier("covered")}`,m=e`UPDATE ${e.identifier(d)} SET ${e.identifier("cursor")} = ${a}, ${e.identifier("done")} = ${l}, ${e.identifier("profile")} = ${s}, ${c} WHERE ${e.identifier("companion")} = ${t}`;if(u.length>0){await $(i,n,m);return}try{await $(i,n,e`INSERT INTO ${e.identifier(d)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${t}, ${a}, ${o?1:0}, ${s}, ${o?1:0})`)}catch(E){if(!n.isUniqueViolation(E))throw E;await $(i,n,m)}};export{d as S,Y as a,P as b,W as c,V as l,K as m,k as q,X as r,G as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{bigintSqlKey as a}from"@lunora/shard-engine";import{B as t,
|
|
1
|
+
import{bigintSqlKey as a}from"@lunora/shard-engine";import{B as t,c as n,U as o,d as r,e as d,i as E,r as c,s as N,a as U,t as _}from"./value-codec-C52YW-Do.mjs";export{t as BIGINT_KEY_LENGTH,n as UNTYPED_NUMBER_PREFIX,o as UNTYPED_WIRE_PREFIX,a as bigintSqlKey,r as decodeBigint,d as effectiveColumnKind,E as isUntypedColumnKind,c as rewriteLegacyUntypedNumber,N as sqliteDecode,U as sqliteEncode,_ as tryJsonParse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{B as l,e as o,c as r,d as t,l as n,m as d,j as i,o as u,z as f,i as R,n as q,u as c,h as m,k as p,p as x,w as C,f as I,q as S,g as h,b as w,r as E,a as y,x as z,s as B,v as L,t as N}from"./sql-exec-BKz380dy.mjs";import"./value-codec-C52YW-Do.mjs";import{OCC_VERSION_COLUMN as V}from"./OCC_VERSION_COLUMN-ByC64Jgx.mjs";export{l as BACKFILL_BATCH_SIZE,V as OCC_VERSION_COLUMN,o as columnRefSql,r as createIndexIfNotExists,t as decodeGlobalRow,n as decodeRow,d as decodeRows,i as dropIndexIfExists,u as fieldRefSql,f as forEachRowPaged,R as indexState,q as nextRowVersion,c as nullSafeEqualsSql,m as pathContainsNeedle,p as pathInList,x as pathTextReference,C as pathTypeGuardSql,I as qualifiedColumnRefSql,S as queryAll,h as queryBatch,w as queryRun,E as readRowsPage,y as runInOrder,z as serializeColumnValue,B as serializeDocumentColumn,L as serializeFieldValue,N as tableColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as y}from"@lunora/errors";import{needsWireEncoding as g,encodeWire as O,decodeWire as R}from"@lunora/wire";import{sql as p}from"drizzle-orm";import{runSqlGlobalTableMigrations as E}from"./runSqlGlobalTableMigrations-DMC5hXJo.mjs";import{r as v,d as _,q as h}from"./sql-exec-BKz380dy.mjs";const A=200,I=(t,e)=>{const o=r=>t.tables[r]?.shardMode?.kind==="global";return e&&e.length>0?e.filter(r=>o(r)):Object.keys(t.tables).filter(r=>o(r))},S=t=>g(t)?O(t):t,z=async function*(t,e,o,r){const c=I(e,r.tables),n=r.batchSize??A;await E(t,e,o);for(const a of c){const i=e.tables[a];let s,d=!0;for(;d;){const f=await v(t,o,a,s,n);for(const u of f)yield{doc:S(_(i,u)),table:a};const l=f.at(-1);l!==void 0&&(s=String(l.id)),d=f.length===n}}},w=t=>t?._meta?.column?.notNull===!1,L=(t,e)=>{const o=new Set;for(const[r,c]of Object.entries(t.shape)){if(e[r]!==null||c.kind!=="optional"||w(c))continue;const n=c._meta?.inner;w(n)||o.add(r)}return o.size===0?e:Object.fromEntries(Object.entries(e).filter(([r])=>!o.has(r)))},T=new Set(["_creationTime","_id"]),D=(t,e)=>Object.keys(e).find(o=>!T.has(o)&&!Object.hasOwn(t.shape,o)),$=t=>{const e=t._id,o=t._creationTime;if(e!==void 0&&(typeof e!="string"||e===""))return'field "_id": must be a non-empty string';if(o!==void 0&&(typeof o!="number"||!Number.isFinite(o)))return'field "_creationTime": must be a finite number'},F=(t,e,o)=>{const r=t.tables[e];if(!r)return`unknown table: ${e}`;const c=D(r,o);if(c!==void 0)return`unexpected field "${c}": not declared in table "${e}"`;const n=$(o);if(n!==void 0)return n;for(const[a,i]of Object.entries(r.shape)){const s=o[a],d=i.kind==="optional";if(s===void 0&&d)continue;const f=i.parse;if(typeof f=="function")try{f(s)}catch(l){const u=l instanceof Error?l.message:String(l);return`field "${a}": ${u}`}}},m=50,j=async(t,e,o,r,c,n)=>{const a=Object.keys(e.tables).filter(s=>s!==c&&e.tables[s]?.shardMode?.kind==="global"),i=[c,...a];for(let s=0;s<i.length;s+=m){const d=i.slice(s,s+m);if(!r){for(const b of d)if(await t.get(b,n)!==null)return b;continue}const f=d.map((b,k)=>p`SELECT ${p.raw(String(k))} AS slot FROM ${p.identifier(b)} WHERE ${p.identifier("id")} = ${n}`),u=(await h(r,o,p`${p.join(f,p` UNION ALL `)} ORDER BY slot LIMIT 1`))[0]?.slot;if(u!==void 0)return d[Number(u)]}},N=async(t,e,o,r,c,n,a)=>{let i;try{i=await j(t,e,o,r,c,n)}catch(s){const{body:d}=y(s,{fallbackCode:"PROBE_FAILED"});return{error:{code:d.code,line:a,message:d.message,table:c}}}return i!==void 0&&i!==c?{error:{code:"ID_COLLISION",line:a,message:`_id "${n}" already belongs to table "${i}"`,table:c}}:{existingId:i===c?n:void 0}},B=async(t,e,o,r,c)=>{try{if(r!==void 0){const n={...o};return delete n._id,await t.replace(e,r,n,{allowExplicitId:!0}),{kind:"replaced"}}return await t.insert(e,o,{allowExplicitId:!0}),{inserted:e,kind:"inserted"}}catch(n){const{body:a}=y(n,{fallbackCode:r===void 0?"INSERT_FAILED":"REPLACE_FAILED"});return{error:{code:a.code,line:c,message:a.message,table:e},kind:"error"}}},W=async(t,e,o,r,c,n)=>{const{doc:a,table:i}=c;if(typeof i!="string"||i.length===0)return{error:{code:"BAD_ROW",line:n,message:"row is missing `table`",table:i},kind:"error"};if(e.tables[i]?.shardMode?.kind!=="global")return{kind:"skip"};if(!a||typeof a!="object"||Array.isArray(a))return{error:{code:"BAD_ROW",line:n,message:"row is missing or malformed `doc`",table:i},kind:"error"};let s;try{s=R(a)}catch(b){return{error:{code:"BAD_ROW",line:n,message:b instanceof Error?b.message:String(b),table:i},kind:"error"}}s=L(e.tables[i],s);const d=F(e,i,s);if(d!==void 0)return{error:{code:"VALIDATION_ERROR",line:n,message:d,table:i},kind:"error"};if(r.dryRun===!0)return{kind:"checked"};const f=typeof s._id=="string"?s._id:void 0,l=f===void 0?{existingId:void 0}:await N(t,e,o,r.exec,i,f,n);if("error"in l)return{error:l.error,kind:"error"};const{existingId:u}=l;return u!==void 0&&r.onConflict!=="replace"?{kind:"conflict"}:B(t,i,s,u,n)},P=async(t,e,o,r)=>{const c=[],n={};let a=0,i=0,s=(r.startLine??1)-1;r.exec&&r.dryRun!==!0&&await E(r.exec,e,o);for(const d of r.rows){s+=1;const f=d.line??s,l=await W(t,e,o,r,d,f);switch(l.kind){case"conflict":{a+=1;break}case"error":{c.push(l.error);break}case"inserted":{n[l.inserted]=(n[l.inserted]??0)+1;break}case"replaced":{i+=1;break}}}return{conflicts:a,errors:c,inserted:n,replaced:i}};export{z as exportSqlGlobalRows,P as importSqlGlobalRows,I as selectGlobalTables};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{isInternalTableName as U}from"@lunora/shard-engine";import{needsWireEncoding as D,encodeWire as v}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{runSqlGlobalTableMigrations as M}from"./runSqlGlobalTableMigrations-DMC5hXJo.mjs";import{q as _,d as G}from"./sql-exec-BKz380dy.mjs";import{s as K,e as W,a as T}from"./value-codec-C52YW-Do.mjs";const P=50,Y=500,H=30,j=200,X=(t,n,e)=>Math.min(Math.max(t,n),e),h=(t,n,e,a)=>X(Math.trunc(t!==void 0&&Number.isFinite(t)?t:n),e,a),J=(t,n)=>U(t)||n.name==="sqlite"&&t.startsWith("d1_"),g=t=>t.name==="postgres"?o`current_schema()`:o`DATABASE()`,p={columns:async(t,n,e)=>(n.name==="sqlite"?await _(t,n,o`PRAGMA table_info(${o.identifier(e)})`):await _(t,n,o`SELECT column_name AS name FROM information_schema.columns WHERE table_schema = ${g(n)} AND table_name = ${e} ORDER BY ordinal_position`)).map(r=>String(r.name)),foreignKeys:async(t,n,e)=>{let a;return n.name==="sqlite"?a=o`PRAGMA foreign_key_list(${o.identifier(e)})`:n.name==="mysql"?a=o`SELECT column_name AS ${o.identifier("from")}, referenced_table_name AS ${o.identifier("table")} FROM information_schema.key_column_usage WHERE table_schema = DATABASE() AND table_name = ${e} AND referenced_table_name IS NOT NULL AND referenced_table_schema = DATABASE()`:a=o`SELECT kcu.column_name AS ${o.identifier("from")}, ccu.table_name AS ${o.identifier("table")} FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.constraint_schema = tc.constraint_schema AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.constraint_schema = tc.constraint_schema WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = ${e} AND ccu.table_schema = current_schema()`,(await _(t,n,a)).map(s=>({from:String(s.from),target:String(s.table)}))},primaryKey:async(t,n,e)=>n.name==="sqlite"?(await _(t,n,o`PRAGMA table_info(${o.identifier(e)})`)).filter(s=>Number(s.pk??0)>0).map(s=>String(s.name)):(await _(t,n,o`SELECT kcu.column_name AS name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ${g(n)} AND tc.table_name = ${e} ORDER BY kcu.ordinal_position`)).map(r=>String(r.name)),tables:async(t,n)=>(n.name==="sqlite"?await _(t,n,o`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`):await _(t,n,o`SELECT table_name AS name FROM information_schema.tables WHERE table_schema = ${g(n)} AND table_type = 'BASE TABLE' ORDER BY table_name`)).map(a=>String(a.name))},Q=/password|secret|token|hash|salt|credential/iu,V=new Map([["apikey",new Set(["key"])],["jwks",new Set(["privatekey"])],["twofactor",new Set(["backupcodes"])],["verification",new Set(["value"])]]),$=t=>t.toLowerCase().replaceAll("_",""),y=(t,n)=>Q.test(n)||V.get($(t))?.has($(n))===!0,E=(t,n)=>{const e=t.tables[n];return e?.shardMode?.kind==="global"?e:void 0},k=async(t,n)=>(await p.tables(t,n)).filter(a=>!J(a,n)),C=async(t,n,e,a)=>{if(await M(t,e,n),!(await k(t,n)).includes(a))throw new w("UNKNOWN_TABLE",`unknown table: ${a}`,{status:404})},R=async(t,n,e,a=o``)=>{const r=await _(t,n,o`SELECT COUNT(*) AS c FROM ${o.identifier(e)}${a}`);return Number(r[0]?.c??0)},L=(t,n,e)=>E(t,n)!==void 0&&e==="_id"?"id":e,I=(t,n,e)=>{const a=E(t,n)?.shape[e];return a===void 0?void 0:W(a)},z=/^-?\d+$/u,O=100,B=(t,n)=>{if(n>O)throw new w("BAD_REQUEST",`the query over ${t} binds ${String(n)} parameters, and a statement takes at most ${String(O)} — remove some filters`)},Z=(t,n,e)=>{if(e)return t instanceof ArrayBuffer?new Uint8Array(t):t;if(n!=="bigint")return T(t);const a=typeof t=="number"||typeof t=="string"?String(t).trim():void 0;return T(a!==void 0&&z.test(a)?BigInt(a):t,n)},x=t=>{if(t.operator!==void 0&&t.operator!=="eq")throw new w("BAD_REQUEST",`operator "${t.operator}" is not supported on the global browser — only eq is`);if(t.path!==void 0&&!(Array.isArray(t.path)&&t.path.length===0))throw new w("BAD_REQUEST",`a nested path is not supported on the global browser, so ${t.column} must be a top-level column`)},q=(t,n,e,a,r)=>{const s=[],i=E(t,e)===void 0&&n.name!=="sqlite";let m=0;for(const c of r??[]){if(x(c),!a.includes(c.column))throw new w("UNKNOWN_COLUMN",`unknown column: ${c.column}`,{status:404});if(E(t,e)===void 0&&y(e,c.column))throw new w("FORBIDDEN",`cannot filter on a redacted column: ${c.column}`,{status:403});const u=o.identifier(L(t,e,c.column));if(c.value===null||c.value===void 0)s.push(o`${u} IS NULL`);else{const l=Z(c.value,I(t,e,c.column),i);s.push(i&&n.name==="postgres"&&l instanceof Date?o`${u}::timestamptz = ${l}::timestamptz`:o`${u} = ${l}`),m+=1}}return{bound:m,where:s.length>0?o` WHERE ${o.join(s,o` AND `)}`:o``}},tt=(t,n,e)=>{const a=E(t,n);if(a)return G(a,e);const r={};for(const[s,i]of Object.entries(e))r[s]=i!=null&&y(n,s)?"•••":i;return r},F=async(t,n,e,a)=>{const r=E(e,a);return r?["_id","_creationTime",...Object.keys(r.shape)]:p.columns(t,n,a)},nt=async(t,n,e,a)=>{if(E(e,a))return;const r=await p.foreignKeys(t,n,a);if(r.length===0)return;const s={};for(const i of r){const{from:m,target:c}=i;s[m]??=c}return s},ut=async(t,n,e)=>{await M(t,n,e);const a=await k(t,e);return Promise.all(a.map(async r=>({name:r,rowCount:await R(t,e,r)})))},et=async(t,n,e,a,r)=>{if(E(e,a)!==void 0)return o`${o.identifier("id")}`;const s=await p.primaryKey(t,n,a);return s.length>0?o.join(s.map(i=>o.identifier(i)),o`, `):r.includes("id")?o`${o.identifier("id")}`:n.name==="sqlite"?o.raw("rowid"):o.join(r.map(i=>n.name==="postgres"?o`${o.identifier(i)}::text`:o.identifier(i)),o`, `)},lt=async(t,n,e,a)=>{const{table:r}=a;await C(t,e,n,r);const s=h(a.limit,P,1,Y),i=h(a.offset,0,0,Number.MAX_SAFE_INTEGER),m=await F(t,e,n,r),{bound:c,where:u}=q(n,e,r,m,a.filters);B(r,c);const l=await R(t,e,r,u),A=await et(t,e,n,r,m),b=(await _(t,e,o`SELECT * FROM ${o.identifier(r)}${u} ORDER BY ${A} LIMIT ${o.raw(String(s))} OFFSET ${o.raw(String(i))}`)).map(d=>{const f=tt(n,r,d);return D(f)?v(f):f}),S=await nt(t,e,n,r);return S===void 0?{columns:m,rows:b,total:l}:{columns:m,refs:S,rows:b,total:l}},ft=async(t,n,e,a)=>{const{column:r,table:s}=a;await C(t,e,n,s);const i=await F(t,e,n,s);if(!i.includes(r))throw new w("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const{bound:m,where:c}=q(n,e,s,i,a.filters);if(B(s,m),E(n,s)===void 0&&y(s,r)){const f=await R(t,e,s,c);return{truncated:!1,values:f===0?[]:[{count:f,value:"•••"}]}}const u=h(a.limit,H,1,j),l=o.identifier(L(n,s,r)),A=await _(t,e,o`SELECT ${l} AS value, COUNT(*) AS count FROM ${o.identifier(s)}${c} GROUP BY ${l} ORDER BY count DESC, ${l} ASC LIMIT ${o.raw(String(u+1))}`),N=A.length>u,b=N?A.slice(0,u):A,S=I(n,s,r)==="bigint",d=b.map(f=>({count:Number(f.count),value:S?K(f.value,"bigint"):f.value}));return{truncated:N,values:D(d)?v(d):d}};export{ft as facetSqlGlobalColumn,ut as listSqlGlobalTables,lt as readSqlGlobalTablePage};
|