@lunora/d1 1.0.0-alpha.23 → 1.0.0-alpha.231
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 +6 -0
- package/dist/dialect.d.mts +69 -30
- package/dist/dialect.d.ts +69 -30
- package/dist/dialect.mjs +1 -36
- package/dist/index.d.mts +281 -261
- package/dist/index.d.ts +281 -261
- package/dist/index.mjs +1 -7
- package/dist/packem_shared/D1Client-CzS0Qfa6.mjs +1 -0
- package/dist/packem_shared/D1TimeoutError-D4YUqZPk.mjs +1 -0
- package/dist/packem_shared/MigrationRunner-DADTo9Q8.mjs +5 -0
- package/dist/packem_shared/OCC_VERSION_COLUMN-ByC64Jgx.mjs +1 -0
- package/dist/packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs +1 -0
- package/dist/packem_shared/d1QueryTag-BcEGW4q1.mjs +1 -0
- package/dist/packem_shared/exportGlobalRows-IncHgv-p.mjs +1 -0
- package/dist/packem_shared/facetGlobalColumn-BqK1_P3S.mjs +1 -0
- package/dist/packem_shared/quoteIdentifier-CObIFRhb.mjs +1 -0
- package/dist/packem_shared/sqliteDialect-B_3JNtdq.mjs +1 -0
- package/package.json +6 -5
- package/dist/packem_shared/D1Client-DA3flo1o.mjs +0 -143
- package/dist/packem_shared/MigrationRunner-BQx8HAGh.mjs +0 -154
- package/dist/packem_shared/createD1CtxDb-BMR8J0dT.mjs +0 -14
- package/dist/packem_shared/exportGlobalRows-DR6UiAZ8.mjs +0 -122
- package/dist/packem_shared/facetGlobalColumn-C6u_WMIY.mjs +0 -142
- package/dist/packem_shared/quoteIdentifier-B-ZeSe1V.mjs +0 -3
- package/dist/packem_shared/sqliteDialect-DqYnHPuu.mjs +0 -27
package/dist/index.d.mts
CHANGED
|
@@ -1,295 +1,174 @@
|
|
|
1
|
-
import { SchemaLike, DatabaseWriterLike } from '@lunora/
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { SchemaLike, DatabaseWriterLike } from '@lunora/shard-engine';
|
|
2
|
+
export { applyCdcChanges } from '@lunora/shard-engine';
|
|
3
|
+
import { SqlCtxExec, ExportGlobalArgs, ExportRow, ImportGlobalArgs, ImportResult, SqlCtxDbOptions, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, FacetGlobalColumnOptions, GlobalFacetResult, GlobalTableInfo, ReadGlobalTablePageOptions, GlobalTablePage, SqlDialect } from '@lunora/sql-store';
|
|
4
|
+
export { type SqlCtxExec as D1Exec, type ExportGlobalArgs, type FacetGlobalColumnOptions, type ExportRow as GlobalExportRow, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type ImportError as GlobalImportError, type ImportResult as GlobalImportResult, type GlobalTableInfo, type GlobalTablePage, type ImportGlobalArgs, type ReadGlobalTablePageOptions, type SqlCtxDbOptions, type SqlCtxExec, createSqlCtxDb, selectGlobalTables } from '@lunora/sql-store';
|
|
5
|
+
import { D1DatabaseLike, D1SessionLike, D1PreparedStatementLike } from '@lunora/platform';
|
|
6
|
+
export type { D1DatabaseLike, D1PreparedStatementLike, D1SessionLike } from '@lunora/platform';
|
|
4
7
|
import { BatchItem, BatchResponse } from 'drizzle-orm/batch';
|
|
5
8
|
import { DrizzleD1Database } from 'drizzle-orm/d1';
|
|
6
|
-
/**
|
|
7
|
-
type D1ContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect">;
|
|
8
|
-
/** Build a D1-backed `.global()` writer (the shared store core bound to the SQLite dialect). */
|
|
9
|
-
declare const createD1ContextDatabase: (options: D1ContextDatabaseOptions) => ReturnType<typeof createSqlCtxDb>;
|
|
10
|
-
/** Auto-provision the schema's `.global()` tables in D1 (idempotent `CREATE TABLE IF NOT EXISTS`). */
|
|
11
|
-
declare const runD1GlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
|
|
12
|
-
/** Materialize the `__agg_<index>` companion tables for the schema's aggregate indexes. */
|
|
13
|
-
declare const runD1AggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
|
|
14
|
-
/** Materialize the `__rank_<index>` companion tables for the schema's rank indexes. */
|
|
15
|
-
declare const runD1RankMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
|
|
16
|
-
/** Materialize the `__fts_<index>` fts5 shadow tables for the schema's search indexes (no-op without fts5). */
|
|
17
|
-
declare const runD1SearchMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
|
|
18
|
-
/** Create the `__cdc_log` table in D1 (idempotent; only run when CDC is enabled). */
|
|
19
|
-
declare const runD1CdcMigration: (exec: SqlCtxExec) => Promise<void>;
|
|
20
|
-
/** Read changelog entries newer than `sinceSeq` in commit order. */
|
|
21
|
-
declare const readD1CdcChanges: (exec: SqlCtxExec, options?: {
|
|
22
|
-
limit?: number;
|
|
23
|
-
sinceSeq?: number;
|
|
24
|
-
}) => ReturnType<typeof readSqlCdcChanges>;
|
|
25
|
-
/** Drop changelog entries at or below a checkpointed `throughSeq`. */
|
|
26
|
-
declare const trimD1CdcChanges: (exec: SqlCtxExec, throughSeq: number) => Promise<void>;
|
|
27
|
-
/** One exported row: `doc` is reconstructed from the column tuple. */
|
|
28
|
-
interface ExportRow {
|
|
29
|
-
doc: Record<string, unknown>;
|
|
30
|
-
table: string;
|
|
31
|
-
}
|
|
32
|
-
interface ImportError {
|
|
33
|
-
code: string;
|
|
34
|
-
line: number;
|
|
35
|
-
message: string;
|
|
36
|
-
table: string;
|
|
37
|
-
}
|
|
38
|
-
interface ImportResult {
|
|
39
|
-
/** Skipped rows whose `_id` already exists. */
|
|
40
|
-
conflicts: number;
|
|
41
|
-
errors: ImportError[];
|
|
42
|
-
inserted: Record<string, number>;
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Return every `.global()` table in the schema, optionally narrowed by an
|
|
46
|
-
* allowlist. Shard-local tables are skipped here — they're handled by the DO
|
|
47
|
-
* helpers — so callers get a clean separation between the two storage planes.
|
|
48
|
-
*/
|
|
49
|
-
declare const selectGlobalTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
|
|
50
|
-
interface ExportGlobalArgs {
|
|
51
|
-
batchSize?: number;
|
|
52
|
-
tables?: ReadonlyArray<string>;
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Yield rows from every requested `.global()` table in batches. Uses
|
|
56
|
-
* `LIMIT ?/OFFSET ?` because D1 globals don't have a stable keyset abstraction
|
|
57
|
-
* here (the writer's `findMany` does, but at the cost of routing through the
|
|
58
|
-
* full validator pipeline; for a snapshot stream a plain offset scan is
|
|
59
|
-
* sufficient and predictable).
|
|
60
|
-
*/
|
|
9
|
+
/** Yield every requested D1 `.global()` table's rows, keyset-paged; never-written tables export empty. */
|
|
61
10
|
declare const exportGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, args: ExportGlobalArgs) => AsyncGenerator<ExportRow, void, undefined>;
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Optional direct exec handle to the same D1 database the writer targets.
|
|
65
|
-
* When supplied, the conflict pre-probe issues a single
|
|
66
|
-
* `SELECT 1 FROM <table> WHERE id = ? LIMIT 1` against the row's declared
|
|
67
|
-
* table instead of falling back to `writer.get(id)`, which scans every
|
|
68
|
-
* global table looking for the id. Strongly recommended for large schemas
|
|
69
|
-
* — the writer-fallback is O(N tables) per row.
|
|
70
|
-
*/
|
|
71
|
-
exec?: D1ExecLike;
|
|
72
|
-
rows: ReadonlyArray<ExportRow>;
|
|
73
|
-
startLine?: number;
|
|
74
|
-
}
|
|
75
|
-
/** Minimal slice of `D1Exec` (declared locally to avoid a circular import). */
|
|
76
|
-
interface D1ExecLike {
|
|
77
|
-
all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Import rows into `.global()` tables via the schema-aware D1 writer. The
|
|
81
|
-
* writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
|
|
82
|
-
* absent); we pre-probe each row's `_id` so a collision is reported as a
|
|
83
|
-
* conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
|
|
84
|
-
* `errors`; the rest land.
|
|
85
|
-
*/
|
|
11
|
+
/** Insert snapshot rows into D1 `.global()` tables; an existing `_id` is a conflict left unchanged unless `args.onConflict` is `"replace"`, which overwrites it. */
|
|
86
12
|
declare const importGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportGlobalArgs) => Promise<ImportResult>;
|
|
87
13
|
/**
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
results: T[];
|
|
105
|
-
success: boolean;
|
|
106
|
-
}>;
|
|
107
|
-
bind: (...values: unknown[]) => D1PreparedStatementLike;
|
|
108
|
-
first: <T = unknown>(column?: string) => Promise<T | null>;
|
|
109
|
-
raw: <T = unknown>() => Promise<T[][]>;
|
|
110
|
-
run: <T = unknown>() => Promise<{
|
|
111
|
-
meta?: Record<string, unknown>;
|
|
112
|
-
results?: T[];
|
|
113
|
-
success: boolean;
|
|
114
|
-
}>;
|
|
115
|
-
}
|
|
116
|
-
/** Thin wrapper over a `D1DatabaseSession` exposing bookmark plumbing. */
|
|
14
|
+
* Thin wrapper over a `D1DatabaseSession` exposing bookmark plumbing.
|
|
15
|
+
*
|
|
16
|
+
* `all` and `first` retry D1's expected transient failures — but only for a
|
|
17
|
+
* statement that is provably read-only. D1 produces a documented
|
|
18
|
+
* baseline of infrastructural errors even when healthy (Cloudflare's team calls
|
|
19
|
+
* a handful every few hours "not unexpected") and their guidance is to retry;
|
|
20
|
+
* a client that does not has adopted that error rate as the application's own.
|
|
21
|
+
*
|
|
22
|
+
* Nothing else on this class or on {@link D1Client} retries. `run` is the write
|
|
23
|
+
* path, and every transient D1 error is ambiguous about whether the statement
|
|
24
|
+
* applied — re-running a non-idempotent write after a lost response
|
|
25
|
+
* double-applies it. `all` is not a read path either: D1 runs
|
|
26
|
+
* `UPDATE … RETURNING` through it, so the retry is gated on the statement's
|
|
27
|
+
* leading keyword rather than on the method name. Wrap a genuinely idempotent
|
|
28
|
+
* write in {@link withD1Retry} yourself, per call.
|
|
29
|
+
*/
|
|
117
30
|
declare class D1Session {
|
|
118
31
|
private readonly session;
|
|
119
32
|
/** See {@link D1Client.stmtCache}. Scoped per session. */
|
|
120
33
|
private readonly stmtCache;
|
|
121
34
|
constructor(session: D1SessionLike);
|
|
122
35
|
prepare(sql: string): D1PreparedStatementLike;
|
|
36
|
+
/**
|
|
37
|
+
* Execute a statement. **Not retried** — `run` is the write path, and a
|
|
38
|
+
* transient D1 error does not say whether the write applied.
|
|
39
|
+
*/
|
|
123
40
|
run<T = unknown>(sql: string, ...binds: unknown[]): Promise<{
|
|
124
41
|
meta?: Record<string, unknown>;
|
|
125
42
|
results?: T[];
|
|
126
43
|
success: boolean;
|
|
127
44
|
}>;
|
|
45
|
+
/**
|
|
46
|
+
* Read all rows, retrying D1's transient failures when `sql` is a
|
|
47
|
+
* read-only statement. An `UPDATE … RETURNING` runs through here too and is
|
|
48
|
+
* left unretried.
|
|
49
|
+
*/
|
|
128
50
|
all<T = unknown>(sql: string, ...binds: unknown[]): Promise<{
|
|
51
|
+
meta?: Record<string, unknown>;
|
|
129
52
|
results: T[];
|
|
130
53
|
success: boolean;
|
|
131
54
|
}>;
|
|
55
|
+
/** Read the first row, retrying under the same read-only rule as {@link all}. */
|
|
132
56
|
first<T = unknown>(sql: string, ...binds: unknown[]): Promise<T | null>;
|
|
133
57
|
/**
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
58
|
+
* Returns the most recent bookmark known to the session, or `undefined`
|
|
59
|
+
* when D1 has not issued one yet.
|
|
60
|
+
*/
|
|
137
61
|
getBookmark(): string | undefined;
|
|
138
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* A D1 handle: prepared-statement caching, Sessions-API sessions, and the
|
|
65
|
+
* drizzle-typed accessors.
|
|
66
|
+
*
|
|
67
|
+
* **Nothing on this class retries.** `prepare`, `drizzle`, `drizzleSession`,
|
|
68
|
+
* `batch` and `raw` all hand back the underlying D1 surface untouched. The
|
|
69
|
+
* automatic retry lives on {@link D1Session.all} / {@link D1Session.first} and
|
|
70
|
+
* on `retryingExec` (the seam `.global()` tables read through); wrap anything
|
|
71
|
+
* else in {@link withD1Retry} yourself, and only when it is safe to run twice.
|
|
72
|
+
*/
|
|
139
73
|
declare class D1Client {
|
|
140
74
|
private readonly db;
|
|
141
75
|
/**
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
76
|
+
* SQL string -> prepared statement. D1 caches compiled statements
|
|
77
|
+
* server-side keyed by the SQL text — the JS `D1PreparedStatement` is
|
|
78
|
+
* inert and every execution carries the text + params over RPC anyway —
|
|
79
|
+
* so this cache buys no round trips: it only avoids re-allocating a
|
|
80
|
+
* statement object per call and hands repeated binds one object to start
|
|
81
|
+
* from. Caching is per-instance so unit-test isolation holds. Bounded to
|
|
82
|
+
* {@link STMT_CACHE_CAPACITY} via LRU eviction.
|
|
83
|
+
*/
|
|
147
84
|
private readonly stmtCache;
|
|
148
85
|
/**
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
86
|
+
* Lazily-built drizzle handle over the bare binding. Memoised so a single
|
|
87
|
+
* `D1Client` reuses the same dialect/session machinery across calls.
|
|
88
|
+
*/
|
|
152
89
|
private drizzleHandle;
|
|
153
90
|
constructor(database: D1DatabaseLike);
|
|
154
91
|
/**
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
92
|
+
* Open a Sessions-API scoped session. Pass the bookmark forwarded by
|
|
93
|
+
* the client to opt into read-your-writes consistency.
|
|
94
|
+
*
|
|
95
|
+
* With no bookmark this is the first request of a session — there is no
|
|
96
|
+
* prior write to read, so we open with the explicit `"first-unconstrained"`
|
|
97
|
+
* constraint (Cloudflare's lowest-latency default: the first read may serve
|
|
98
|
+
* from any replica). Read-your-writes for sequenced requests still flows
|
|
99
|
+
* through the forwarded bookmark; a caller needing a strongly-consistent
|
|
100
|
+
* very-first read should pass `"first-primary"` as the bookmark instead.
|
|
101
|
+
*/
|
|
165
102
|
withSession(bookmark?: string): D1Session;
|
|
166
103
|
/**
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
104
|
+
* Prepare a statement, reusing a cached one when the SQL text matches.
|
|
105
|
+
* `bind()` on a prepared statement returns a new bound statement and
|
|
106
|
+
* leaves the cached one untouched, so cache hits are safe even when the
|
|
107
|
+
* previous caller already called `.bind(...).run()`.
|
|
108
|
+
*/
|
|
172
109
|
prepare(sql: string): D1PreparedStatementLike;
|
|
173
110
|
/**
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
get drizzle(): DrizzleD1Database
|
|
111
|
+
* Drizzle handle over the bare `env.DB` binding. Used for typed queries
|
|
112
|
+
* against generated `sqliteTable` schemas; does **not** participate in the
|
|
113
|
+
* D1 Sessions API (no bookmark pinning). For bookmark-scoped reads, use
|
|
114
|
+
* {@link drizzleSession} instead.
|
|
115
|
+
*/
|
|
116
|
+
get drizzle(): DrizzleD1Database;
|
|
180
117
|
/**
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
drizzleSession(bookmark?: string): DrizzleD1Database
|
|
118
|
+
* Drizzle handle scoped to a D1 Sessions-API session. The bookmark, when
|
|
119
|
+
* supplied, opts into read-your-writes consistency for follow-up reads on
|
|
120
|
+
* the same session.
|
|
121
|
+
*
|
|
122
|
+
* A `D1DatabaseSession` exposes the same `prepare` / `batch` surface
|
|
123
|
+
* drizzle calls into, so a single `unknown` cast lets us hand the session to
|
|
124
|
+
* the driver.
|
|
125
|
+
*/
|
|
126
|
+
drizzleSession(bookmark?: string): DrizzleD1Database;
|
|
190
127
|
/**
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
128
|
+
* Atomic batch over the drizzle d1 driver. Mirrors `db.batch([...])`
|
|
129
|
+
* exactly; exposed on the client so callers don't need to hold a drizzle
|
|
130
|
+
* handle just to run a typed batch.
|
|
131
|
+
*/
|
|
195
132
|
batch<U extends BatchItem<"sqlite">, T extends Readonly<[U, ...U[]]>>(items: T): Promise<BatchResponse<T>>;
|
|
196
133
|
/** Direct access to the underlying binding (advanced use only). */
|
|
197
134
|
get raw(): D1DatabaseLike;
|
|
198
135
|
}
|
|
199
|
-
/**
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
}
|
|
218
|
-
/**
|
|
219
|
-
* One equality constraint a facet-value click adds to the global browser's view:
|
|
220
|
-
* `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
|
|
221
|
-
* displayed column name, validated against the table's columns and mapped to its
|
|
222
|
-
* physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
|
|
223
|
-
* value** the facet returned (a SQLite scalar), bound as a parameter and never
|
|
224
|
-
* interpolated. AND-combined with the other clauses.
|
|
225
|
-
*/
|
|
226
|
-
interface GlobalFilterClause {
|
|
227
|
-
column: string;
|
|
228
|
-
value: unknown;
|
|
229
|
-
}
|
|
230
|
-
interface ReadGlobalTablePageOptions {
|
|
231
|
-
filters?: GlobalFilterClause[];
|
|
232
|
-
limit?: number;
|
|
233
|
-
offset?: number;
|
|
234
|
-
table: string;
|
|
235
|
-
}
|
|
236
|
-
/**
|
|
237
|
-
* Options for {@link facetGlobalColumn} — the read-only "what values does this
|
|
238
|
-
* column hold?" summary for the global (D1) browser. `column` is the displayed
|
|
239
|
-
* column to group by (validated and mapped to its physical column, never
|
|
240
|
-
* interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
|
|
241
|
-
* constraints so the facet reflects the **active view** (the same rows the
|
|
242
|
-
* browser is previewing); `limit` caps the distinct values returned (clamped).
|
|
243
|
-
*/
|
|
244
|
-
interface FacetGlobalColumnOptions {
|
|
245
|
-
column: string;
|
|
246
|
-
filters?: GlobalFilterClause[];
|
|
136
|
+
/** The D1 store options — the shared store options minus `dialect` (the SQLite dialect is injected for you). */
|
|
137
|
+
type D1ContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect">;
|
|
138
|
+
/** Build a D1-backed `.global()` writer (the shared store core bound to the SQLite dialect). */
|
|
139
|
+
declare const createD1ContextDatabase: (options: D1ContextDatabaseOptions) => ReturnType<typeof createSqlCtxDb>;
|
|
140
|
+
/** Auto-provision the schema's `.global()` tables in D1 (idempotent `CREATE TABLE IF NOT EXISTS`). */
|
|
141
|
+
declare const runD1GlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
|
|
142
|
+
/** Materialize the `__agg_<index>` companion tables for the schema's aggregate indexes. */
|
|
143
|
+
declare const runD1AggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
|
|
144
|
+
/** Materialize the `__rank_<index>` companion tables for the schema's rank indexes. */
|
|
145
|
+
declare const runD1RankMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
|
|
146
|
+
/** Materialize (and backfill) the `__fts_<index>` fts5 shadow tables for the schema's search indexes. */
|
|
147
|
+
declare const runD1SearchMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
|
|
148
|
+
/** Index existing rows into every search companion, including the `staged: true` ones migrations leave empty. */
|
|
149
|
+
declare const backfillD1SearchIndexes: (exec: SqlCtxExec, schema: SchemaLike) => Promise<SqlSearchBackfillResult>;
|
|
150
|
+
/** Create the `__cdc_log` table in D1 (idempotent; only run when CDC is enabled). */
|
|
151
|
+
declare const runD1CdcMigration: (exec: SqlCtxExec) => Promise<void>;
|
|
152
|
+
/** Read changelog entries newer than `sinceSeq` in commit order. */
|
|
153
|
+
declare const readD1CdcChanges: (exec: SqlCtxExec, options?: {
|
|
247
154
|
limit?: number;
|
|
248
|
-
|
|
249
|
-
}
|
|
250
|
-
/** One distinct value of a faceted global column with its row count over the active view. */
|
|
251
|
-
interface GlobalFacetValue {
|
|
252
|
-
count: number;
|
|
253
|
-
value: unknown;
|
|
254
|
-
}
|
|
255
|
-
/**
|
|
256
|
-
* Payload of a {@link facetGlobalColumn} call: the top-N distinct `values` (each
|
|
257
|
-
* with a `count`) ordered by frequency, plus `truncated` — `true` when more
|
|
258
|
-
* distinct values existed beyond the cap, so the UI can say so rather than imply
|
|
259
|
-
* the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
|
|
260
|
-
*/
|
|
261
|
-
interface GlobalFacetResult {
|
|
262
|
-
truncated: boolean;
|
|
263
|
-
values: GlobalFacetValue[];
|
|
264
|
-
}
|
|
155
|
+
sinceSeq?: number;
|
|
156
|
+
}) => ReturnType<typeof readSqlCdcChanges>;
|
|
265
157
|
/**
|
|
266
|
-
*
|
|
267
|
-
*
|
|
268
|
-
*
|
|
269
|
-
|
|
158
|
+
* Delete `.global()` changelog entries older than `retentionMs`, if this writer
|
|
159
|
+
* wins the fleet's sweep lease. See `sweepSqlCdcRetention`.
|
|
160
|
+
*
|
|
161
|
+
* Replaces the seq-based `trimD1CdcChanges`, which took a checkpoint no caller
|
|
162
|
+
* could compute: the log is shared across every shard and region, so no single
|
|
163
|
+
* caller knows a `seq` that is safe for all of them. A time window is a bound
|
|
164
|
+
* they can all reason about, and the lease is what stops them racing.
|
|
165
|
+
*/
|
|
166
|
+
declare const sweepD1CdcRetention: (exec: SqlCtxExec, retentionMs: number, now: number) => Promise<void>;
|
|
167
|
+
/** Every browsable D1 table with its row count (schema `.global()` tables provisioned first). */
|
|
270
168
|
declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promise<GlobalTableInfo[]>;
|
|
271
|
-
/**
|
|
272
|
-
* Read a page of rows from one D1 table. The table is validated against the live
|
|
273
|
-
* browsable-table list before its name is interpolated, so this can't be coerced
|
|
274
|
-
* into reading an internal table or injecting SQL. `limit` is clamped to
|
|
275
|
-
* `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
|
|
276
|
-
* matching each `column = value` eq constraint (a facet-value drill-down), bound
|
|
277
|
-
* through {@link buildEqPredicate} so they never inject SQL.
|
|
278
|
-
*/
|
|
169
|
+
/** One page of a D1 table's rows, eq-filtered. */
|
|
279
170
|
declare const readGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
|
|
280
|
-
/**
|
|
281
|
-
* Summarise the distinct values of one displayed column over the **active view**
|
|
282
|
-
* (the same eq `filters` the global browser is previewing) — the D1 twin of the
|
|
283
|
-
* shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
|
|
284
|
-
* count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
|
|
285
|
-
* against the table's displayed columns (typed 404 if unknown), mapped to its
|
|
286
|
-
* physical column, and quoted — never interpolated from caller input. The extra
|
|
287
|
-
* over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
|
|
288
|
-
* an external (non-schema) table is never grouped — it collapses to a single
|
|
289
|
-
* redacted `•••` bucket — mirroring the page browser's value redaction so the
|
|
290
|
-
* facet can't leak credentials. The returned `value` is the raw stored scalar, so
|
|
291
|
-
* a click feeds it straight back as an eq filter.
|
|
292
|
-
*/
|
|
171
|
+
/** The distinct values of one D1 column over the active view. */
|
|
293
172
|
declare const facetGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
|
|
294
173
|
interface Migration {
|
|
295
174
|
/** Human-readable name, e.g. `001_init` (used in logs). */
|
|
@@ -310,30 +189,171 @@ interface MigrationRunnerResult {
|
|
|
310
189
|
}[];
|
|
311
190
|
}
|
|
312
191
|
/**
|
|
313
|
-
* Sequentially applies pending migrations against a D1 database via the
|
|
314
|
-
* drizzle-orm/d1 driver
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
|
|
192
|
+
* Sequentially applies pending migrations against a D1 database via the
|
|
193
|
+
* drizzle-orm/d1 driver, recording each one's `version` and SHA-256 in
|
|
194
|
+
* `__drizzle_migrations`.
|
|
195
|
+
*
|
|
196
|
+
* A migration is skipped when its VERSION is recorded, never by its text alone.
|
|
197
|
+
* Deduplicating by hash re-applied any migration whose text changed after it
|
|
198
|
+
* ran — a comment, a whitespace fix, a CRLF checkout — so a non-idempotent one
|
|
199
|
+
* (`SET balance = balance * 100`) ran twice. A recorded version whose hash no
|
|
200
|
+
* longer matches is refused as `MIGRATION_DRIFT` instead: the runner cannot
|
|
201
|
+
* tell a harmless edit from a changed migration, and running either again is
|
|
202
|
+
* the one outcome that is never right.
|
|
203
|
+
*/
|
|
319
204
|
declare class MigrationRunner {
|
|
320
205
|
private readonly client;
|
|
321
206
|
private readonly migrations;
|
|
322
207
|
/**
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
208
|
+
* Accepts either a {@link D1Client} (preferred — gets typed batches +
|
|
209
|
+
* drizzle handle for free) or a raw `D1DatabaseLike` binding (wrapped on
|
|
210
|
+
* the caller's behalf so existing `@lunora/cli` callers keep working).
|
|
211
|
+
*/
|
|
327
212
|
constructor(database: D1Client | D1DatabaseLike, migrations: Migration[]);
|
|
328
213
|
run(): Promise<MigrationRunnerResult>;
|
|
214
|
+
/** Does the tracking table carry the `version` column yet? One catalog read. */
|
|
215
|
+
private hasVersionColumn;
|
|
216
|
+
/**
|
|
217
|
+
* Create the tracking table, or bring one written before `version` existed
|
|
218
|
+
* up to the current shape.
|
|
219
|
+
*
|
|
220
|
+
* Two runners can upgrade the same table at once (parallel deploys): both
|
|
221
|
+
* see no column, and the second `ADD COLUMN` fails with "duplicate column
|
|
222
|
+
* name". That failure is only accepted once a re-read shows the column
|
|
223
|
+
* really is there — any other failure of the `ALTER` still surfaces.
|
|
224
|
+
*/
|
|
225
|
+
private ensureTrackingTable;
|
|
226
|
+
/**
|
|
227
|
+
* Read the tracking rows, first giving every row recorded before versions
|
|
228
|
+
* were tracked the version whose SQL it hashed — the only link to a version
|
|
229
|
+
* such a row has. A row whose hash matches no current migration stays
|
|
230
|
+
* unversioned, and {@link run} refuses to guess around it.
|
|
231
|
+
*/
|
|
232
|
+
private readTrackingRows;
|
|
329
233
|
private applyOne;
|
|
330
234
|
private assertUniqueVersions;
|
|
331
235
|
private assertUniqueSql;
|
|
332
236
|
}
|
|
333
237
|
/**
|
|
334
|
-
*
|
|
335
|
-
*
|
|
336
|
-
*
|
|
337
|
-
|
|
238
|
+
* Derive a low-cardinality tag for a rendered statement — `select:users`,
|
|
239
|
+
* `insert:orders`, `select:unknown` when no table token is recognisable.
|
|
240
|
+
*
|
|
241
|
+
* Cardinality is the whole design constraint. The rendered SQL is unique per
|
|
242
|
+
* shape and near-unique per call site, so grouping on it produces a tag space
|
|
243
|
+
* that grows without bound and answers nothing; verb + table is the coarsest
|
|
244
|
+
* label that still points at a specific culprit.
|
|
245
|
+
*/
|
|
246
|
+
declare const d1QueryTag: (sql: string) => string;
|
|
247
|
+
/** One statement's cost, read off D1's `meta`. */
|
|
248
|
+
interface D1QueryCost {
|
|
249
|
+
/** D1's own server-side duration in ms, when reported. */
|
|
250
|
+
durationMs?: number;
|
|
251
|
+
/** Rows D1 SCANNED — the billed number, and the one a missing index inflates. */
|
|
252
|
+
rowsRead: number;
|
|
253
|
+
/** Rows written by a DML statement; `0` for reads. */
|
|
254
|
+
rowsWritten: number;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Project D1's `meta` onto {@link D1QueryCost}, or `undefined` when the result
|
|
258
|
+
* carried no usable accounting — a test double, or a `batch()` leg that reports
|
|
259
|
+
* none. Callers skip the emit entirely in that case rather than logging zeroes,
|
|
260
|
+
* which would read as "this query was free".
|
|
261
|
+
*/
|
|
262
|
+
declare const readD1QueryCost: (meta: Record<string, unknown> | undefined) => D1QueryCost | undefined;
|
|
263
|
+
/**
|
|
264
|
+
* Emit one structured cost event per D1 statement into Workers Logs, so
|
|
265
|
+
* "D1 reads spiked" resolves to a tag by group-by.
|
|
266
|
+
*
|
|
267
|
+
* Best-effort by contract, exactly like the request-log emit: a serialization
|
|
268
|
+
* hiccup must never turn a served query into a failed one, so the caller wraps
|
|
269
|
+
* this and swallows. Emitting one line per D1 statement is proportionate —
|
|
270
|
+
* every one of them is already a network round trip, so the line is noise-free
|
|
271
|
+
* next to the work it describes.
|
|
272
|
+
*
|
|
273
|
+
* The SQL text itself is NEVER emitted: it carries inlined literals on some
|
|
274
|
+
* render paths, and the tag is the groupable thing anyway.
|
|
275
|
+
*/
|
|
276
|
+
declare const emitD1QueryCost: (sql: string, meta: Record<string, unknown> | undefined) => void;
|
|
277
|
+
/** Tuning for {@link withD1Retry}. */
|
|
278
|
+
interface D1RetryOptions {
|
|
279
|
+
/** Total attempts including the first. Default 3. Must be >= 1. */
|
|
280
|
+
attempts?: number;
|
|
281
|
+
/**
|
|
282
|
+
* Total budget across every attempt and backoff, in ms. An attempt still
|
|
283
|
+
* running when the budget expires is abandoned, and a backoff never sleeps
|
|
284
|
+
* past it.
|
|
285
|
+
*
|
|
286
|
+
* `timeoutMs` bounds one attempt; this bounds the operation.
|
|
287
|
+
*/
|
|
288
|
+
deadlineMs?: number;
|
|
289
|
+
/** Sleep implementation. Injected so tests need no timers. */
|
|
290
|
+
sleep?: (ms: number) => Promise<void>;
|
|
291
|
+
/**
|
|
292
|
+
* Abandon a single attempt that has not settled within this many ms, and
|
|
293
|
+
* treat it as a transient failure.
|
|
294
|
+
*
|
|
295
|
+
* There is no default — a legitimate analytical query and a stalled one
|
|
296
|
+
* look identical from outside, so the value has to come from what your
|
|
297
|
+
* workload actually needs. Unset, {@link SLOW_FAILURE_MS} stops a slow
|
|
298
|
+
* failure from being retried rather than guessing a bound for you.
|
|
299
|
+
*
|
|
300
|
+
* Only ever applied to operations that are safe to abandon. It does not
|
|
301
|
+
* cancel the underlying D1 call.
|
|
302
|
+
*/
|
|
303
|
+
timeoutMs?: number;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* True when `error` looks like one of D1's expected transient failures.
|
|
307
|
+
*
|
|
308
|
+
* Deliberately conservative: an unrecognised error is treated as **permanent**
|
|
309
|
+
* and surfaces immediately. Retrying a genuine bug — a syntax error, a
|
|
310
|
+
* constraint violation — turns one fast failure into three slow ones and
|
|
311
|
+
* hides the cause.
|
|
312
|
+
*/
|
|
313
|
+
declare const isTransientD1Error: (error: unknown) => boolean;
|
|
314
|
+
/**
|
|
315
|
+
* Thrown when an attempt is abandoned for exceeding
|
|
316
|
+
* {@link D1RetryOptions.timeoutMs}.
|
|
317
|
+
*
|
|
318
|
+
* Its own class so a caller can tell "D1 hung" apart from "D1 returned an
|
|
319
|
+
* error" — they have different remedies, and collapsing them hides which one
|
|
320
|
+
* is happening.
|
|
321
|
+
*/
|
|
322
|
+
declare class D1TimeoutError extends Error {
|
|
323
|
+
/** Milliseconds waited before the attempt was abandoned. */
|
|
324
|
+
readonly timeoutMs: number;
|
|
325
|
+
constructor(timeoutMs: number);
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Run `operation`, retrying D1's transient failures with exponential backoff
|
|
329
|
+
* and jitter.
|
|
330
|
+
*
|
|
331
|
+
* **Only wrap operations that are safe to run more than once.** Reads always
|
|
332
|
+
* are. A write is only if it is idempotent — an upsert keyed on a primary key,
|
|
333
|
+
* a delete by id, an `INSERT OR IGNORE`. A bare `INSERT` or a relative
|
|
334
|
+
* `UPDATE` is not, and re-running one after a lost response double-applies it.
|
|
335
|
+
*/
|
|
336
|
+
declare const withD1Retry: <T>(operation: () => Promise<T>, options?: D1RetryOptions) => Promise<T>;
|
|
337
|
+
/**
|
|
338
|
+
* Wrap a `.global()` exec so its **read-only** statements retry D1's transient
|
|
339
|
+
* failures.
|
|
340
|
+
*
|
|
341
|
+
* This is where the retry has to live to reach an application: `.global()`
|
|
342
|
+
* tables run every read through the exec codegen builds over the raw D1
|
|
343
|
+
* binding, not through a `D1Client`. `run` and `batch` are passed straight
|
|
344
|
+
* through — they are the write path, and a transient D1 error does not say
|
|
345
|
+
* whether the write applied.
|
|
346
|
+
*
|
|
347
|
+
* `all` is not the read path either. It only retries when
|
|
348
|
+
* {@link isReadOnlyD1Sql} proves the statement is one, because `UPDATE …
|
|
349
|
+
* RETURNING` runs through `all` too.
|
|
350
|
+
*/
|
|
351
|
+
declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlCtxExec;
|
|
352
|
+
/**
|
|
353
|
+
* The canonical SQLite dialect: column affinities, `RETURNING` support (both D1
|
|
354
|
+
* and `node:sqlite`), and `sqlite_master` table probing. The rest of the
|
|
355
|
+
* per-statement shaping is drizzle's. The value codec is NOT a dialect member —
|
|
356
|
+
* the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
|
|
357
|
+
*/
|
|
338
358
|
declare const sqliteDialect: SqlDialect;
|
|
339
|
-
export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type
|
|
359
|
+
export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
|