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