@lunora/d1 1.0.0-alpha.4 → 1.0.0-alpha.40

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.ts CHANGED
@@ -42,32 +42,42 @@ interface ImportResult {
42
42
  inserted: Record<string, number>;
43
43
  }
44
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
- */
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
49
  declare const selectGlobalTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
50
50
  interface ExportGlobalArgs {
51
51
  batchSize?: number;
52
52
  tables?: ReadonlyArray<string>;
53
53
  }
54
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
- */
55
+ * Yield rows from every requested `.global()` table in batches.
56
+ *
57
+ * Keyset-paginates on the physical primary key (`id` — every `.global()` table
58
+ * carries it, see `frameworkColumnDdl`): `WHERE "id" > ? ORDER BY "id" LIMIT ?`,
59
+ * carrying the last id forward. A plain `LIMIT/OFFSET` scan would be wrong here —
60
+ * SQLite gives no ordering guarantee for an unordered SELECT and each page is a
61
+ * separate query, so pages could overlap or skip rows (and any concurrent
62
+ * insert/delete would shift offsets and silently drop/duplicate rows in the
63
+ * snapshot). Keyset paging is deterministic under concurrent writes and avoids
64
+ * O(n^2) OFFSET scans on large tables.
65
+ *
66
+ * Tables are provisioned first (idempotent `CREATE … IF NOT EXISTS`): `.global()`
67
+ * tables are created lazily on first write, so a fresh deployment — or any table
68
+ * never written — would otherwise abort the stream with a raw `no such table`
69
+ * instead of exporting it as empty.
70
+ */
61
71
  declare const exportGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, args: ExportGlobalArgs) => AsyncGenerator<ExportRow, void, undefined>;
62
72
  interface ImportGlobalArgs {
63
73
  /**
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 &lt;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
- */
74
+ * Optional direct exec handle to the same D1 database the writer targets.
75
+ * When supplied, the conflict pre-probe issues a single
76
+ * `SELECT 1 FROM &lt;table> WHERE id = ? LIMIT 1` against the row's declared
77
+ * table instead of falling back to `writer.get(id)`, which scans every
78
+ * global table looking for the id. Strongly recommended for large schemas
79
+ * — the writer-fallback is O(N tables) per row.
80
+ */
71
81
  exec?: D1ExecLike;
72
82
  rows: ReadonlyArray<ExportRow>;
73
83
  startLine?: number;
@@ -77,20 +87,19 @@ interface D1ExecLike {
77
87
  all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
78
88
  }
79
89
  /**
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
- */
90
+ * Import rows into `.global()` tables via the schema-aware D1 writer. The
91
+ * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
92
+ * absent); we pre-probe each row's `_id` so a collision is reported as a
93
+ * conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
94
+ * `errors`; the rest land.
95
+ */
86
96
  declare const importGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportGlobalArgs) => Promise<ImportResult>;
87
97
  /**
88
- * Minimal structural projection of `D1Database` to keep the adapter
89
- * compatible with the real workers-types value as well as unit-test doubles.
90
- */
98
+ * Minimal structural projection of `D1Database` to keep the adapter
99
+ * compatible with the real workers-types value as well as unit-test doubles.
100
+ */
91
101
  interface D1DatabaseLike {
92
102
  batch?: (statements: D1PreparedStatementLike[]) => Promise<unknown[]>;
93
- exec?: (sql: string) => Promise<unknown>;
94
103
  prepare: (sql: string) => D1PreparedStatementLike;
95
104
  withSession: (bookmark?: string) => D1SessionLike;
96
105
  }
@@ -131,67 +140,67 @@ declare class D1Session {
131
140
  }>;
132
141
  first<T = unknown>(sql: string, ...binds: unknown[]): Promise<T | null>;
133
142
  /**
134
- * Returns the most recent bookmark known to the session, or `undefined`
135
- * when D1 has not issued one yet.
136
- */
143
+ * Returns the most recent bookmark known to the session, or `undefined`
144
+ * when D1 has not issued one yet.
145
+ */
137
146
  getBookmark(): string | undefined;
138
147
  }
139
148
  declare class D1Client {
140
149
  private readonly db;
141
150
  /**
142
- * SQL string -> prepared statement. Prepared statements are reusable in
143
- * D1; preparing the same SQL twice forces the worker to round-trip the
144
- * statement plan. Caching is per-instance so unit-test isolation holds.
145
- * Bounded to {@link STMT_CACHE_CAPACITY} via LRU eviction.
146
- */
151
+ * SQL string -> prepared statement. Prepared statements are reusable in
152
+ * D1; preparing the same SQL twice forces the worker to round-trip the
153
+ * statement plan. Caching is per-instance so unit-test isolation holds.
154
+ * Bounded to {@link STMT_CACHE_CAPACITY} via LRU eviction.
155
+ */
147
156
  private readonly stmtCache;
148
157
  /**
149
- * Lazily-built drizzle handle over the bare binding. Memoised so a single
150
- * `D1Client` reuses the same dialect/session machinery across calls.
151
- */
158
+ * Lazily-built drizzle handle over the bare binding. Memoised so a single
159
+ * `D1Client` reuses the same dialect/session machinery across calls.
160
+ */
152
161
  private drizzleHandle;
153
162
  constructor(database: D1DatabaseLike);
154
163
  /**
155
- * Open a Sessions-API scoped session. Pass the bookmark forwarded by
156
- * the client to opt into read-your-writes consistency.
157
- *
158
- * With no bookmark this is the first request of a session — there is no
159
- * prior write to read, so we open with the explicit `"first-unconstrained"`
160
- * constraint (Cloudflare's lowest-latency default: the first read may serve
161
- * from any replica). Read-your-writes for sequenced requests still flows
162
- * through the forwarded bookmark; a caller needing a strongly-consistent
163
- * very-first read should pass `"first-primary"` as the bookmark instead.
164
- */
164
+ * Open a Sessions-API scoped session. Pass the bookmark forwarded by
165
+ * the client to opt into read-your-writes consistency.
166
+ *
167
+ * With no bookmark this is the first request of a session — there is no
168
+ * prior write to read, so we open with the explicit `"first-unconstrained"`
169
+ * constraint (Cloudflare's lowest-latency default: the first read may serve
170
+ * from any replica). Read-your-writes for sequenced requests still flows
171
+ * through the forwarded bookmark; a caller needing a strongly-consistent
172
+ * very-first read should pass `"first-primary"` as the bookmark instead.
173
+ */
165
174
  withSession(bookmark?: string): D1Session;
166
175
  /**
167
- * Prepare a statement, reusing a cached one when the SQL text matches.
168
- * `bind()` on a prepared statement returns a new bound statement and
169
- * leaves the underlying prepared plan reusable, so cache hits are safe
170
- * even when the previous caller already called `.bind(...).run()`.
171
- */
176
+ * Prepare a statement, reusing a cached one when the SQL text matches.
177
+ * `bind()` on a prepared statement returns a new bound statement and
178
+ * leaves the underlying prepared plan reusable, so cache hits are safe
179
+ * even when the previous caller already called `.bind(...).run()`.
180
+ */
172
181
  prepare(sql: string): D1PreparedStatementLike;
173
182
  /**
174
- * Drizzle handle over the bare `env.DB` binding. Used for typed queries
175
- * against generated `sqliteTable` schemas; does **not** participate in the
176
- * D1 Sessions API (no bookmark pinning). For bookmark-scoped reads, use
177
- * {@link drizzleSession} instead.
178
- */
183
+ * Drizzle handle over the bare `env.DB` binding. Used for typed queries
184
+ * against generated `sqliteTable` schemas; does **not** participate in the
185
+ * D1 Sessions API (no bookmark pinning). For bookmark-scoped reads, use
186
+ * {@link drizzleSession} instead.
187
+ */
179
188
  get drizzle(): DrizzleD1Database<Record<string, unknown>>;
180
189
  /**
181
- * Drizzle handle scoped to a D1 Sessions-API session. The bookmark, when
182
- * supplied, opts into read-your-writes consistency for follow-up reads on
183
- * the same session.
184
- *
185
- * A `D1DatabaseSession` exposes the same `prepare` / `batch` surface
186
- * drizzle calls into, so a single `unknown` cast lets us treat the session
187
- * as a `D1Database` for driver-construction purposes.
188
- */
190
+ * Drizzle handle scoped to a D1 Sessions-API session. The bookmark, when
191
+ * supplied, opts into read-your-writes consistency for follow-up reads on
192
+ * the same session.
193
+ *
194
+ * A `D1DatabaseSession` exposes the same `prepare` / `batch` surface
195
+ * drizzle calls into, so a single `unknown` cast lets us treat the session
196
+ * as a `D1Database` for driver-construction purposes.
197
+ */
189
198
  drizzleSession(bookmark?: string): DrizzleD1Database<Record<string, unknown>>;
190
199
  /**
191
- * Atomic batch over the drizzle d1 driver. Mirrors `db.batch([...])`
192
- * exactly; exposed on the client so callers don't need to hold a drizzle
193
- * handle just to run a typed batch.
194
- */
200
+ * Atomic batch over the drizzle d1 driver. Mirrors `db.batch([...])`
201
+ * exactly; exposed on the client so callers don't need to hold a drizzle
202
+ * handle just to run a typed batch.
203
+ */
195
204
  batch<U extends BatchItem<"sqlite">, T extends Readonly<[U, ...U[]]>>(items: T): Promise<BatchResponse<T>>;
196
205
  /** Direct access to the underlying binding (advanced use only). */
197
206
  get raw(): D1DatabaseLike;
@@ -205,24 +214,24 @@ interface GlobalTableInfo {
205
214
  interface GlobalTablePage {
206
215
  columns: string[];
207
216
  /**
208
- * Foreign-key columns (local column → referenced table) for tables that carry
209
- * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
210
- * Schema `.global()` tables omit this (their refs come from `describeTables`);
211
- * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
212
- * schema diagram can draw their global→global FK edges.
213
- */
217
+ * Foreign-key columns (local column → referenced table) for tables that carry
218
+ * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
219
+ * Schema `.global()` tables omit this (their refs come from `describeTables`);
220
+ * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
221
+ * schema diagram can draw their global→global FK edges.
222
+ */
214
223
  refs?: Record<string, string>;
215
224
  rows: Record<string, unknown>[];
216
225
  total: number;
217
226
  }
218
227
  /**
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
- */
228
+ * One equality constraint a facet-value click adds to the global browser's view:
229
+ * `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
230
+ * displayed column name, validated against the table's columns and mapped to its
231
+ * physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
232
+ * value** the facet returned (a SQLite scalar), bound as a parameter and never
233
+ * interpolated. AND-combined with the other clauses.
234
+ */
226
235
  interface GlobalFilterClause {
227
236
  column: string;
228
237
  value: unknown;
@@ -234,13 +243,13 @@ interface ReadGlobalTablePageOptions {
234
243
  table: string;
235
244
  }
236
245
  /**
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
- */
246
+ * Options for {@link facetGlobalColumn} — the read-only "what values does this
247
+ * column hold?" summary for the global (D1) browser. `column` is the displayed
248
+ * column to group by (validated and mapped to its physical column, never
249
+ * interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
250
+ * constraints so the facet reflects the **active view** (the same rows the
251
+ * browser is previewing); `limit` caps the distinct values returned (clamped).
252
+ */
244
253
  interface FacetGlobalColumnOptions {
245
254
  column: string;
246
255
  filters?: GlobalFilterClause[];
@@ -253,43 +262,43 @@ interface GlobalFacetValue {
253
262
  value: unknown;
254
263
  }
255
264
  /**
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
- */
265
+ * Payload of a {@link facetGlobalColumn} call: the top-N distinct `values` (each
266
+ * with a `count`) ordered by frequency, plus `truncated` — `true` when more
267
+ * distinct values existed beyond the cap, so the UI can say so rather than imply
268
+ * the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
269
+ */
261
270
  interface GlobalFacetResult {
262
271
  truncated: boolean;
263
272
  values: GlobalFacetValue[];
264
273
  }
265
274
  /**
266
- * List every browsable D1 table with its row count, ordered by name. Surfaces
267
- * both the schema's `.global()` tables (provisioned first) and external tables
268
- * (auth, etc.); internal/companion tables are excluded.
269
- */
275
+ * List every browsable D1 table with its row count, ordered by name. Surfaces
276
+ * both the schema's `.global()` tables (provisioned first) and external tables
277
+ * (auth, etc.); internal/companion tables are excluded.
278
+ */
270
279
  declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promise<GlobalTableInfo[]>;
271
280
  /**
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
- */
281
+ * Read a page of rows from one D1 table. The table is validated against the live
282
+ * browsable-table list before its name is interpolated, so this can't be coerced
283
+ * into reading an internal table or injecting SQL. `limit` is clamped to
284
+ * `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
285
+ * matching each `column = value` eq constraint (a facet-value drill-down), bound
286
+ * through {@link buildEqPredicate} so they never inject SQL.
287
+ */
279
288
  declare const readGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
280
289
  /**
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
- */
290
+ * Summarise the distinct values of one displayed column over the **active view**
291
+ * (the same eq `filters` the global browser is previewing) — the D1 twin of the
292
+ * shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
293
+ * count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
294
+ * against the table's displayed columns (typed 404 if unknown), mapped to its
295
+ * physical column, and quoted — never interpolated from caller input. The extra
296
+ * over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
297
+ * an external (non-schema) table is never grouped — it collapses to a single
298
+ * redacted `•••` bucket — mirroring the page browser's value redaction so the
299
+ * facet can't leak credentials. The returned `value` is the raw stored scalar, so
300
+ * a click feeds it straight back as an eq filter.
301
+ */
293
302
  declare const facetGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
294
303
  interface Migration {
295
304
  /** Human-readable name, e.g. `001_init` (used in logs). */
@@ -310,20 +319,20 @@ interface MigrationRunnerResult {
310
319
  }[];
311
320
  }
312
321
  /**
313
- * Sequentially applies pending migrations against a D1 database via the
314
- * drizzle-orm/d1 driver. Each migration is hashed (SHA-256 over its SQL
315
- * text); the hash is stored in `__drizzle_migrations`, so re-applying the
316
- * same SQL under a different `version` is rejected and identical migrations
317
- * are skipped idempotently.
318
- */
322
+ * Sequentially applies pending migrations against a D1 database via the
323
+ * drizzle-orm/d1 driver. Each migration is hashed (SHA-256 over its SQL
324
+ * text); the hash is stored in `__drizzle_migrations`, so re-applying the
325
+ * same SQL under a different `version` is rejected and identical migrations
326
+ * are skipped idempotently.
327
+ */
319
328
  declare class MigrationRunner {
320
329
  private readonly client;
321
330
  private readonly migrations;
322
331
  /**
323
- * Accepts either a {@link D1Client} (preferred — gets typed batches +
324
- * drizzle handle for free) or a raw `D1DatabaseLike` binding (wrapped on
325
- * the caller's behalf so existing `@lunora/cli` callers keep working).
326
- */
332
+ * Accepts either a {@link D1Client} (preferred — gets typed batches +
333
+ * drizzle handle for free) or a raw `D1DatabaseLike` binding (wrapped on
334
+ * the caller's behalf so existing `@lunora/cli` callers keep working).
335
+ */
327
336
  constructor(database: D1Client | D1DatabaseLike, migrations: Migration[]);
328
337
  run(): Promise<MigrationRunnerResult>;
329
338
  private applyOne;
@@ -331,9 +340,9 @@ declare class MigrationRunner {
331
340
  private assertUniqueSql;
332
341
  }
333
342
  /**
334
- * The canonical SQLite dialect: column affinities, the shared SQLite value
335
- * codec, `RETURNING` support (both D1 and `node:sqlite`), and `sqlite_master`
336
- * table probing. The rest of the per-statement shaping is drizzle's.
337
- */
343
+ * The canonical SQLite dialect: column affinities, the shared SQLite value
344
+ * codec, `RETURNING` support (both D1 and `node:sqlite`), and `sqlite_master`
345
+ * table probing. The rest of the per-statement shaping is drizzle's.
346
+ */
338
347
  declare const sqliteDialect: SqlDialect;
339
348
  export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1DatabaseLike, type D1PreparedStatementLike, D1Session, type D1SessionLike, 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 Migration, MigrationRunner, type MigrationRunnerResult, type ReadGlobalTablePageOptions, createD1ContextDatabase as createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, selectGlobalTables, sqliteDialect, trimD1CdcChanges };
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- export { exportGlobalRows, importGlobalRows, selectGlobalTables } from './packem_shared/exportGlobalRows-BGCPm_nA.mjs';
2
- export { D1Client, D1Session } from './packem_shared/D1Client-DA3flo1o.mjs';
1
+ export { exportGlobalRows, importGlobalRows, selectGlobalTables } from './packem_shared/exportGlobalRows-q0RgCLPM.mjs';
2
+ export { D1Client, D1Session } from './packem_shared/D1Client-DSj8p7c4.mjs';
3
3
  export { createD1CtxDb, readD1CdcChanges, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, trimD1CdcChanges } from './packem_shared/createD1CtxDb-BMR8J0dT.mjs';
4
- export { facetGlobalColumn, listGlobalTables, readGlobalTablePage } from './packem_shared/facetGlobalColumn-C6u_WMIY.mjs';
5
- export { MigrationRunner } from './packem_shared/MigrationRunner-BkEwQ-Ya.mjs';
4
+ export { facetGlobalColumn, listGlobalTables, readGlobalTablePage } from './packem_shared/facetGlobalColumn-DnglIe4P.mjs';
5
+ export { MigrationRunner } from './packem_shared/MigrationRunner-A-o1LTKj.mjs';
6
6
  export { default as sqliteDialect } from './packem_shared/sqliteDialect-DqYnHPuu.mjs';
7
7
  export { createSqlCtxDb } from '@lunora/sql-store';
@@ -1,6 +1,28 @@
1
1
  import { drizzle } from 'drizzle-orm/d1';
2
2
 
3
+ const evictOldestEntry = (map, capacity) => {
4
+ if (map.size < capacity) {
5
+ return;
6
+ }
7
+ const oldest = map.keys().next().value;
8
+ if (oldest !== void 0) {
9
+ map.delete(oldest);
10
+ }
11
+ };
12
+
3
13
  const STMT_CACHE_CAPACITY = 256;
14
+ const prepareCached = (cache, prepare, sql) => {
15
+ const cached = cache.get(sql);
16
+ if (cached) {
17
+ cache.delete(sql);
18
+ cache.set(sql, cached);
19
+ return cached;
20
+ }
21
+ const stmt = prepare(sql);
22
+ evictOldestEntry(cache, STMT_CACHE_CAPACITY);
23
+ cache.set(sql, stmt);
24
+ return stmt;
25
+ };
4
26
  const D1_FIRST_UNCONSTRAINED = "first-unconstrained";
5
27
  class D1Session {
6
28
  session;
@@ -10,21 +32,7 @@ class D1Session {
10
32
  this.session = session;
11
33
  }
12
34
  prepare(sql) {
13
- const cached = this.stmtCache.get(sql);
14
- if (cached) {
15
- this.stmtCache.delete(sql);
16
- this.stmtCache.set(sql, cached);
17
- return cached;
18
- }
19
- const stmt = this.session.prepare(sql);
20
- if (this.stmtCache.size >= STMT_CACHE_CAPACITY) {
21
- const oldest = this.stmtCache.keys().next().value;
22
- if (oldest !== void 0) {
23
- this.stmtCache.delete(oldest);
24
- }
25
- }
26
- this.stmtCache.set(sql, stmt);
27
- return stmt;
35
+ return prepareCached(this.stmtCache, (text) => this.session.prepare(text), sql);
28
36
  }
29
37
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T types the result rows for the caller and is forwarded to the prepared statement.
30
38
  async run(sql, ...binds) {
@@ -84,21 +92,7 @@ class D1Client {
84
92
  * even when the previous caller already called `.bind(...).run()`.
85
93
  */
86
94
  prepare(sql) {
87
- const cached = this.stmtCache.get(sql);
88
- if (cached) {
89
- this.stmtCache.delete(sql);
90
- this.stmtCache.set(sql, cached);
91
- return cached;
92
- }
93
- const stmt = this.db.prepare(sql);
94
- if (this.stmtCache.size >= STMT_CACHE_CAPACITY) {
95
- const oldest = this.stmtCache.keys().next().value;
96
- if (oldest !== void 0) {
97
- this.stmtCache.delete(oldest);
98
- }
99
- }
100
- this.stmtCache.set(sql, stmt);
101
- return stmt;
95
+ return prepareCached(this.stmtCache, (text) => this.db.prepare(text), sql);
102
96
  }
103
97
  /**
104
98
  * Drizzle handle over the bare `env.DB` binding. Used for typed queries
@@ -1,18 +1,19 @@
1
+ import { LunoraError } from '@lunora/errors';
1
2
  import { sql } from 'drizzle-orm';
2
- import { D1Client } from './D1Client-DA3flo1o.mjs';
3
+ import { D1Client } from './D1Client-DSj8p7c4.mjs';
3
4
 
4
5
  const TRACKING_TABLE_NAME = "__drizzle_migrations";
5
- const TRACKING_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${TRACKING_TABLE_NAME} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL, created_at NUMERIC)`;
6
+ const TRACKING_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${TRACKING_TABLE_NAME} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC)`;
6
7
  const WHITESPACE_RE = /\s/u;
7
- const TRAILING_SEMICOLON_RE = /;\s*$/u;
8
8
  const SHA256_HEX_RE = /^[0-9a-f]{64}$/u;
9
+ const TRACKING_HASH_UNIQUE_RE = new RegExp(String.raw`UNIQUE constraint failed:\s*${TRACKING_TABLE_NAME}\.hash`, "iu");
9
10
  const assertSingleStatement = (migration) => {
10
11
  const text = migration.sql;
11
12
  let inSingle = false;
12
13
  let inDouble = false;
13
14
  let inLineComment = false;
14
15
  let inBlockComment = false;
15
- let seenStatement = false;
16
+ let terminatorIndex;
16
17
  for (let index = 0; index < text.length; index += 1) {
17
18
  const character = text[index];
18
19
  const next = text[index + 1];
@@ -49,14 +50,6 @@ const assertSingleStatement = (migration) => {
49
50
  }
50
51
  continue;
51
52
  }
52
- if (character === "'") {
53
- inSingle = true;
54
- continue;
55
- }
56
- if (character === '"') {
57
- inDouble = true;
58
- continue;
59
- }
60
53
  if (character === "-" && next === "-") {
61
54
  inLineComment = true;
62
55
  index += 1;
@@ -67,16 +60,28 @@ const assertSingleStatement = (migration) => {
67
60
  index += 1;
68
61
  continue;
69
62
  }
70
- if (character === ";") {
71
- seenStatement = true;
63
+ if (terminatorIndex !== void 0) {
64
+ if (character !== void 0 && !WHITESPACE_RE.test(character)) {
65
+ throw new LunoraError(
66
+ "INTERNAL",
67
+ `Migration "${migration.name}" (v${String(migration.version)}) contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`
68
+ );
69
+ }
72
70
  continue;
73
71
  }
74
- if (seenStatement && character !== void 0 && !WHITESPACE_RE.test(character)) {
75
- throw new Error(
76
- `Migration "${migration.name}" (v${String(migration.version)}) contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`
77
- );
72
+ if (character === "'") {
73
+ inSingle = true;
74
+ continue;
75
+ }
76
+ if (character === '"') {
77
+ inDouble = true;
78
+ continue;
79
+ }
80
+ if (character === ";") {
81
+ terminatorIndex = index;
78
82
  }
79
83
  }
84
+ return terminatorIndex;
80
85
  };
81
86
  const hashMigration = async (text) => {
82
87
  const bytes = new TextEncoder().encode(text);
@@ -110,26 +115,38 @@ class MigrationRunner {
110
115
  skipped.push({ name: migration.name, version: migration.version });
111
116
  continue;
112
117
  }
113
- await this.applyOne(migration, hash);
114
- applied.push({ name: migration.name, version: migration.version });
118
+ const didApply = await this.applyOne(migration, hash);
119
+ if (didApply) {
120
+ applied.push({ name: migration.name, version: migration.version });
121
+ } else {
122
+ skipped.push({ name: migration.name, version: migration.version });
123
+ }
115
124
  }
116
125
  return { applied, skipped };
117
126
  }
118
127
  async applyOne(migration, hash) {
119
- assertSingleStatement(migration);
120
- const statementText = migration.sql.replace(TRAILING_SEMICOLON_RE, "").trim();
128
+ const terminatorIndex = assertSingleStatement(migration);
129
+ const statementText = (terminatorIndex === void 0 ? migration.sql : migration.sql.slice(0, terminatorIndex)).trim();
121
130
  if (!SHA256_HEX_RE.test(hash)) {
122
- throw new Error(`migration "${migration.name}" produced a non-hex hash; refusing to inline into SQL`);
131
+ throw new LunoraError("INTERNAL", `migration "${migration.name}" produced a non-hex hash; refusing to inline into SQL`);
123
132
  }
124
133
  const trackingInsertSql = `INSERT INTO ${TRACKING_TABLE_NAME} (hash, created_at) VALUES ('${hash}', ${String(Date.now())})`;
125
134
  const items = [this.client.drizzle.run(sql.raw(statementText)), this.client.drizzle.run(sql.raw(trackingInsertSql))];
126
- await this.client.batch(items);
135
+ try {
136
+ await this.client.batch(items);
137
+ } catch (error) {
138
+ if (TRACKING_HASH_UNIQUE_RE.test(error instanceof Error ? error.message : String(error))) {
139
+ return false;
140
+ }
141
+ throw error;
142
+ }
143
+ return true;
127
144
  }
128
145
  assertUniqueVersions() {
129
146
  const seen = /* @__PURE__ */ new Set();
130
147
  for (const m of this.migrations) {
131
148
  if (seen.has(m.version)) {
132
- throw new Error(`Duplicate migration version ${String(m.version)}`);
149
+ throw new LunoraError("INTERNAL", `Duplicate migration version ${String(m.version)}`);
133
150
  }
134
151
  seen.add(m.version);
135
152
  }
@@ -139,7 +156,10 @@ class MigrationRunner {
139
156
  for (const m of this.migrations) {
140
157
  const previousVersion = seen.get(m.sql);
141
158
  if (previousVersion !== void 0) {
142
- throw new Error(`Migrations ${String(previousVersion)} and ${String(m.version)} have identical SQL — bump the content, not just the version.`);
159
+ throw new LunoraError(
160
+ "INTERNAL",
161
+ `Migrations ${String(previousVersion)} and ${String(m.version)} have identical SQL — bump the content, not just the version.`
162
+ );
143
163
  }
144
164
  seen.set(m.sql, m.version);
145
165
  }
@@ -1,7 +1,9 @@
1
+ import { toErrorBody } from '@lunora/errors';
2
+ import { runD1GlobalTableMigrations } from './createD1CtxDb-BMR8J0dT.mjs';
3
+ import { quoteIdentifier } from './quoteIdentifier-B-ZeSe1V.mjs';
1
4
  import { decodeGlobalRow } from '@lunora/sql-store';
2
5
 
3
6
  const DEFAULT_BATCH_SIZE = 200;
4
- const quoteIdentifier = (name) => `"${name.replaceAll('"', '""')}"`;
5
7
  const selectGlobalTables = (schema, requested) => {
6
8
  const isGlobal = (table) => schema.tables[table]?.shardMode?.kind === "global";
7
9
  if (requested && requested.length > 0) {
@@ -19,16 +21,21 @@ const decodeRow = (schema, table, row) => {
19
21
  const exportGlobalRows = async function* (exec, schema, args) {
20
22
  const tables = selectGlobalTables(schema, args.tables);
21
23
  const batchSize = args.batchSize ?? DEFAULT_BATCH_SIZE;
24
+ await runD1GlobalTableMigrations(exec, schema);
22
25
  for (const table of tables) {
23
- let offset = 0;
26
+ const quoted = quoteIdentifier(table);
27
+ let lastId;
24
28
  let hasMore = true;
25
29
  while (hasMore) {
26
- const rows = await exec.all(`SELECT * FROM ${quoteIdentifier(table)} LIMIT ? OFFSET ?`, [batchSize, offset]);
30
+ const rows = lastId === void 0 ? await exec.all(`SELECT * FROM ${quoted} ORDER BY "id" LIMIT ?`, [batchSize]) : await exec.all(`SELECT * FROM ${quoted} WHERE "id" > ? ORDER BY "id" LIMIT ?`, [lastId, batchSize]);
27
31
  for (const row of rows) {
28
32
  yield { doc: decodeRow(schema, table, row), table };
29
33
  }
34
+ const last = rows.at(-1);
35
+ if (last !== void 0) {
36
+ lastId = String(last["id"]);
37
+ }
30
38
  hasMore = rows.length === batchSize;
31
- offset += rows.length;
32
39
  }
33
40
  }
34
41
  };
@@ -88,9 +95,8 @@ const importOneRow = async (writer, schema, args, row, line) => {
88
95
  await writer.insert(table, doc, { allowExplicitId: true });
89
96
  return { inserted: table, kind: "inserted" };
90
97
  } catch (error) {
91
- const code = error.code ?? "INSERT_FAILED";
92
- const message = error instanceof Error ? error.message : String(error);
93
- return { error: { code, line, message, table }, kind: "error" };
98
+ const { body } = toErrorBody(error, { fallbackCode: "INSERT_FAILED" });
99
+ return { error: { code: body.code, line, message: body.message, table }, kind: "error" };
94
100
  }
95
101
  };
96
102
  const importGlobalRows = async (writer, schema, args) => {