durable-db 0.3.0 → 0.5.0
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/README.md +177 -25
- package/dist/{arktypeConfig-DxP0OcV_.js → actionArgs-1hEaDUia.js} +35 -1
- package/dist/cli/bin.js +1 -1
- package/dist/cli/index.d.ts +204 -62
- package/dist/cli/index.js +4 -3
- package/dist/{cli-BUSZTS2D.js → cli-CVS0b2im.js} +272 -95
- package/dist/context/index.js +14 -8
- package/dist/db/index.d.ts +3 -4
- package/dist/db/index.js +259 -26
- package/dist/defineDatabase-D_RpcKj1.js +109 -0
- package/dist/{defineDatabase-IUthY3Ex.d.ts → defineDatabase-zrUJrMd5.d.ts} +10 -3
- package/dist/{index-BdrcuAU7.d.ts → index-BvSFkwM9.d.ts} +106 -18
- package/dist/index.d.ts +1 -2
- package/dist/index.js +2 -2
- package/dist/{kysely-Be6KwFZC.js → kysely-CYmmiwDm.js} +25 -5
- package/dist/migrations/generator.d.ts +1 -1
- package/dist/migrations/generator.js +1 -1
- package/dist/migrations/snapshot.d.ts +2 -2
- package/dist/migrations/snapshot.js +1 -91
- package/dist/{parser-DR57GOjv.js → parser-DyepmXzE.js} +1 -1
- package/dist/registry.d.ts +29 -2
- package/dist/registry.js +2 -2
- package/dist/snapshot-B9Ae2TrS.d.ts +180 -0
- package/dist/snapshot-D_z95s6E.js +459 -0
- package/dist/{state-OVuoHRC9.js → state-DGYycIoJ.js} +106 -9
- package/dist/testing/index.d.ts +8 -1
- package/dist/testing/index.js +30 -11
- package/dist/vite/durableDb.d.ts +131 -1
- package/dist/vite/durableDb.js +782 -180
- package/package.json +3 -2
- package/virtual.d.ts +4 -2
- package/dist/arktypeConfig-AXvobTPL.d.ts +0 -5
- package/dist/defineDatabase-CHmzpzFf.js +0 -70
- package/dist/snapshot-CaG5xnE2.d.ts +0 -48
package/dist/context/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { s as __toCommonJS } from "../debug-Cz8KzMft.js";
|
|
2
|
-
import {
|
|
2
|
+
import { d as init_state, v as state_exports } from "../state-DGYycIoJ.js";
|
|
3
3
|
//#region src/context/index.ts
|
|
4
4
|
/**
|
|
5
5
|
* Tenant ID resolver for framework integration.
|
|
@@ -40,17 +40,23 @@ function setTenantIdResolver(resolver) {
|
|
|
40
40
|
/**
|
|
41
41
|
* Inside a Durable Object the instance key IS the tenant (per-tenant DBs key
|
|
42
42
|
* their instances by tenant id, plus an optional `__dev_<epoch>` suffix in
|
|
43
|
-
* dev
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
43
|
+
* dev — the database's own epoch after `db reset --database`, else the
|
|
44
|
+
* project's). The registry publishes its DoContext store getter on globalThis
|
|
45
|
+
* — see the note there for why this is not a module import — so getTenantId()
|
|
46
|
+
* works in action handlers without the worker-side resolver, which the DO
|
|
47
|
+
* execution context never registers.
|
|
47
48
|
*/
|
|
48
49
|
function tenantIdFromDoContext() {
|
|
49
50
|
const getStore = globalThis[Symbol.for("durable-db.doContext")];
|
|
50
51
|
const key = getStore?.()?.instanceKey;
|
|
51
|
-
if (!key
|
|
52
|
-
const
|
|
53
|
-
return
|
|
52
|
+
if (!key) return null;
|
|
53
|
+
const tenant = stripDevEpoch(key);
|
|
54
|
+
return tenant === "global" ? null : tenant;
|
|
55
|
+
}
|
|
56
|
+
/** An instance key without its dev-epoch suffix (`<key>__dev_<epoch>` → `<key>`). */
|
|
57
|
+
function stripDevEpoch(instanceKey) {
|
|
58
|
+
const suffixAt = instanceKey.lastIndexOf("__dev_");
|
|
59
|
+
return suffixAt === -1 ? instanceKey : instanceKey.slice(0, suffixAt);
|
|
54
60
|
}
|
|
55
61
|
function getTenantId() {
|
|
56
62
|
if (tenantIdResolver) return tenantIdResolver();
|
package/dist/db/index.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as
|
|
3
|
-
|
|
4
|
-
export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type ParsedDatabaseFile, type QueryResult, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
|
|
1
|
+
import { a as ActionInfo, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, i as ActionContext, l as DatabaseInfo, n as Action, o as ArgsSchema, p as type, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "../defineDatabase-zrUJrMd5.js";
|
|
2
|
+
import { C as createKyselyFromSql, S as SqlExecutor, _ as MigrationAttemptInfo, a as QueryResult, b as SqliteDurableObject, c as DrizzleDefaultsPlugin, d as dateSerializers, f as DeleteClassMigration, g as Migration, h as removedDatabaseMessage, i as KyselyPlugin, l as SchemaPlugin, m as RemovedDatabaseError, n as CompiledQuery, o as studio, p as RemovedDatabaseDurableObject, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as MigrationSchemaConflictError, x as CreateKyselyOptions, y as Migrations } from "../index-BvSFkwM9.js";
|
|
3
|
+
export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type ParsedDatabaseFile, type QueryResult, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, removedDatabaseMessage, studio, type };
|
package/dist/db/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as init_debug, n as debugMigrations } from "../debug-Cz8KzMft.js";
|
|
2
|
-
import {
|
|
3
|
-
import { n as defineDatabase } from "../defineDatabase-
|
|
4
|
-
import { a as createDrizzlePlugins, i as SchemaPlugin, n as DateSerializePlugin, o as dateSerializers, r as DrizzleDefaultsPlugin, t as createKyselyFromSql } from "../kysely-
|
|
2
|
+
import { n as type } from "../actionArgs-1hEaDUia.js";
|
|
3
|
+
import { n as defineDatabase } from "../defineDatabase-D_RpcKj1.js";
|
|
4
|
+
import { a as createDrizzlePlugins, i as SchemaPlugin, n as DateSerializePlugin, o as dateSerializers, r as DrizzleDefaultsPlugin, t as createKyselyFromSql } from "../kysely-CYmmiwDm.js";
|
|
5
5
|
import { DurableObject } from "cloudflare:workers";
|
|
6
6
|
import { CamelCasePlugin } from "kysely";
|
|
7
7
|
import { studio } from "@outerbase/browsable-durable-object";
|
|
@@ -12,13 +12,52 @@ init_debug();
|
|
|
12
12
|
*/
|
|
13
13
|
const MAX_PITR_ATTEMPTS = 3;
|
|
14
14
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
15
|
+
* Name prefix of dev migrations. The Vite plugin embeds the squashed dev
|
|
16
|
+
* migrations (`db push`) next to the production ones in dev only, as
|
|
17
|
+
* `_dev_<name>` — production builds never contain them, so a `_dev_` row in
|
|
18
|
+
* the `__migrations` journal marks a storage that has run in dev.
|
|
19
|
+
*/
|
|
20
|
+
const DEV_MIGRATION_PREFIX = "_dev_";
|
|
21
|
+
/**
|
|
22
|
+
* Journal of the statements applied by dev migrations, written in dev only
|
|
23
|
+
* (production builds embed no dev migrations), each under the dev migration
|
|
24
|
+
* that ran it. It serves the two ways a dev storage meets statements it
|
|
25
|
+
* already ran (they would fail with "duplicate column name" or "already
|
|
26
|
+
* exists" against the schema the dev migrations built):
|
|
27
|
+
* - `db push` squashes from the production snapshot every time, so the next
|
|
28
|
+
* dev migration repeats the previous one's statements: those are skipped;
|
|
29
|
+
* - `db generate` squashes the dev migrations into a production migration
|
|
30
|
+
* with the same statements: it is recorded as applied instead of executed.
|
|
31
|
+
*/
|
|
32
|
+
const DEV_STATEMENTS_TABLE = "__dev_migration_statements";
|
|
33
|
+
/**
|
|
34
|
+
* The comparable form of a migration statement: whitespace collapsed,
|
|
35
|
+
* trailing semicolons dropped, and the `IF NOT EXISTS` that `db push` adds to
|
|
36
|
+
* a dev migration's `CREATE TABLE`/`CREATE [UNIQUE] INDEX` removed — the
|
|
37
|
+
* production migration `db generate` writes for the same change has none.
|
|
38
|
+
*/
|
|
39
|
+
function normalizeStatement(statement) {
|
|
40
|
+
return statement.replace(/\s+/g, " ").trim().replace(/;+$/, "").trim().replace(/^CREATE (TABLE|INDEX|UNIQUE INDEX) IF NOT EXISTS /i, "CREATE $1 ");
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A best-effort database name for recovery hints, from the generated class
|
|
44
|
+
* name (`<PascalCase(name)>DatabaseDO`): `ReviewsFeedbackDatabaseDO` →
|
|
45
|
+
* `reviews-feedback`.
|
|
46
|
+
*/
|
|
47
|
+
function databaseNameFromClass(className) {
|
|
48
|
+
const match = /^(.+?)DatabaseDO\d*$/.exec(className);
|
|
49
|
+
if (!match) return null;
|
|
50
|
+
return match[1].replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Raised when a pending migration fails with "already exists" or "duplicate
|
|
54
|
+
* column name": the storage holds schema objects the `__migrations` journal
|
|
55
|
+
* doesn't track. Common causes: dev migrations (`db push`) that `db generate`
|
|
56
|
+
* squashed into a production migration the dev storage cannot replay,
|
|
57
|
+
* migration files renamed or regenerated after the storage was created, the
|
|
58
|
+
* storage written by an older version of the database, or a previous attempt
|
|
59
|
+
* that crashed partway through a chunk without PITR. Re-running can never
|
|
60
|
+
* succeed, so this carries recovery guidance instead of the raw SQLITE_ERROR.
|
|
22
61
|
*/
|
|
23
62
|
var MigrationSchemaConflictError = class extends Error {
|
|
24
63
|
constructor(message, options) {
|
|
@@ -92,10 +131,24 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
92
131
|
*/
|
|
93
132
|
sql;
|
|
94
133
|
/**
|
|
134
|
+
* The name `db` commands know this database by (its file name, prefixed by
|
|
135
|
+
* its mount for a mounted source), used in recovery hints. The generated
|
|
136
|
+
* Durable Object sets it; a hand-written subclass that does not gets a
|
|
137
|
+
* best-effort name derived from its class name (`<PascalCase(name)>DatabaseDO`).
|
|
138
|
+
*/
|
|
139
|
+
databaseName;
|
|
140
|
+
/**
|
|
95
141
|
* Whether migrations have been run for this instance
|
|
96
142
|
*/
|
|
97
143
|
migrationsApplied = false;
|
|
98
144
|
/**
|
|
145
|
+
* The migration run in flight, shared by every caller that arrives while it
|
|
146
|
+
* runs. `runMigrations()` reads the pending list and then awaits (the PITR
|
|
147
|
+
* probe and bookmark) before it applies anything, so two first calls racing
|
|
148
|
+
* on a boolean flag would both apply the same `CREATE TABLE`s.
|
|
149
|
+
*/
|
|
150
|
+
migrating;
|
|
151
|
+
/**
|
|
99
152
|
* Cached result of PITR availability check (null = not yet checked)
|
|
100
153
|
*/
|
|
101
154
|
pitrAvailable = null;
|
|
@@ -134,15 +187,24 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
134
187
|
*/
|
|
135
188
|
resetMigrationState() {
|
|
136
189
|
this.migrationsApplied = false;
|
|
190
|
+
this.migrating = void 0;
|
|
137
191
|
debugMigrations("Migration state reset; migrations will re-run on next access");
|
|
138
192
|
}
|
|
139
193
|
/**
|
|
140
|
-
* Ensure migrations are applied before any operation
|
|
194
|
+
* Ensure migrations are applied before any operation. Concurrent first
|
|
195
|
+
* calls share one migration run (a failed run is retried by the next call).
|
|
141
196
|
*/
|
|
142
197
|
async ensureMigrations() {
|
|
143
198
|
if (this.migrationsApplied) return;
|
|
144
|
-
|
|
145
|
-
|
|
199
|
+
if (!this.migrating) {
|
|
200
|
+
const run = this.runMigrations().then(() => {
|
|
201
|
+
if (this.migrating === run) this.migrationsApplied = true;
|
|
202
|
+
}).finally(() => {
|
|
203
|
+
if (this.migrating === run) this.migrating = void 0;
|
|
204
|
+
});
|
|
205
|
+
this.migrating = run;
|
|
206
|
+
}
|
|
207
|
+
await this.migrating;
|
|
146
208
|
}
|
|
147
209
|
/**
|
|
148
210
|
* Execute raw SQL statement
|
|
@@ -181,8 +243,17 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
181
243
|
this.sql.exec(`
|
|
182
244
|
INSERT OR IGNORE INTO __migration_attempts (id, attempt_count) VALUES ('current', 0)
|
|
183
245
|
`);
|
|
184
|
-
|
|
246
|
+
let pending = this.collectPendingMigrations();
|
|
185
247
|
if (pending.length === 0) return;
|
|
248
|
+
pending = this.settleMigrationsAppliedInDev(pending);
|
|
249
|
+
if (pending.length === 0) return;
|
|
250
|
+
const repeated = this.statementsRepeatedFromEarlierPushes(pending);
|
|
251
|
+
if (pending.some((p) => p.name.startsWith("_dev_"))) this.sql.exec(`
|
|
252
|
+
CREATE TABLE IF NOT EXISTS ${DEV_STATEMENTS_TABLE} (
|
|
253
|
+
statement TEXT PRIMARY KEY,
|
|
254
|
+
migration TEXT NOT NULL
|
|
255
|
+
)
|
|
256
|
+
`);
|
|
186
257
|
const hasPitr = await this.checkPitrAvailable();
|
|
187
258
|
let bookmark;
|
|
188
259
|
if (hasPitr) {
|
|
@@ -205,7 +276,7 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
205
276
|
}
|
|
206
277
|
const startedAt = Date.now();
|
|
207
278
|
try {
|
|
208
|
-
this.applyMigrations(pending);
|
|
279
|
+
this.applyMigrations(pending, repeated);
|
|
209
280
|
this.sql.exec(`
|
|
210
281
|
UPDATE __migration_attempts
|
|
211
282
|
SET attempt_count = 0, last_error = NULL
|
|
@@ -244,6 +315,104 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
244
315
|
}
|
|
245
316
|
}
|
|
246
317
|
/**
|
|
318
|
+
* Record pending production migrations whose every statement was already
|
|
319
|
+
* applied by this storage's dev migrations, without executing them.
|
|
320
|
+
*
|
|
321
|
+
* The dev loop is `db push` (a squashed dev migration `_dev_<hash>`, applied
|
|
322
|
+
* by the running dev server) and then `db generate`, which writes the same
|
|
323
|
+
* statements as a production migration and drops the dev one. The dev
|
|
324
|
+
* storage has the schema but its journal only knows the dev name, so the
|
|
325
|
+
* production migration would run again and fail ("duplicate column name",
|
|
326
|
+
* "already exists") on every request. Only a storage that applied dev
|
|
327
|
+
* migrations has the statements table, so this never runs in production.
|
|
328
|
+
*
|
|
329
|
+
* A migration with any chunk already applied, or with a statement no dev
|
|
330
|
+
* migration ran, is left pending. Returns the chunks still to execute.
|
|
331
|
+
*/
|
|
332
|
+
settleMigrationsAppliedInDev(pending) {
|
|
333
|
+
const devStatements = this.readDevStatements();
|
|
334
|
+
if (!devStatements || devStatements.size === 0) return pending;
|
|
335
|
+
const byName = /* @__PURE__ */ new Map();
|
|
336
|
+
for (const chunk of pending) {
|
|
337
|
+
if (chunk.name.startsWith("_dev_")) continue;
|
|
338
|
+
const chunks = byName.get(chunk.name) ?? [];
|
|
339
|
+
chunks.push(chunk);
|
|
340
|
+
byName.set(chunk.name, chunks);
|
|
341
|
+
}
|
|
342
|
+
const settled = /* @__PURE__ */ new Set();
|
|
343
|
+
for (const [name, chunks] of byName) {
|
|
344
|
+
if (chunks.length !== this.migrations[name].chunks.length) continue;
|
|
345
|
+
const statements = chunks.flatMap((chunk) => chunk.statements).map(normalizeStatement).filter((statement) => statement.length > 0);
|
|
346
|
+
if (statements.length === 0) continue;
|
|
347
|
+
if (!statements.every((statement) => devStatements.has(statement))) continue;
|
|
348
|
+
const devMigrations = Array.from(new Set(statements.map((statement) => devStatements.get(statement))));
|
|
349
|
+
const record = () => {
|
|
350
|
+
const appliedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
351
|
+
for (const chunk of chunks) this.sql.exec("INSERT INTO __migrations (name, chunk_index, applied_at) VALUES (?, ?, ?)", name, chunk.chunkIndex, appliedAt);
|
|
352
|
+
for (const statement of statements) this.sql.exec(`DELETE FROM ${DEV_STATEMENTS_TABLE} WHERE statement = ?`, statement);
|
|
353
|
+
};
|
|
354
|
+
const storage = this.ctx.storage;
|
|
355
|
+
if (typeof storage.transactionSync === "function") storage.transactionSync(record);
|
|
356
|
+
else record();
|
|
357
|
+
for (const statement of statements) devStatements.delete(statement);
|
|
358
|
+
settled.add(name);
|
|
359
|
+
console.log(`[database] Recorded migration ${name} as applied without running it: dev migration(s) ${devMigrations.join(", ")} already applied its statements to this storage.`);
|
|
360
|
+
}
|
|
361
|
+
return settled.size === 0 ? pending : pending.filter((chunk) => !settled.has(chunk.name));
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* The statements of pending dev migrations that an earlier dev migration of
|
|
365
|
+
* this storage already ran (normalized), by pending dev migration.
|
|
366
|
+
*
|
|
367
|
+
* `db push` always diffs from the production snapshot, so after a second
|
|
368
|
+
* schema change the new squashed dev migration holds the previous one's
|
|
369
|
+
* statements again — `ADD weight_grams` next to the new `ADD color_code` —
|
|
370
|
+
* and this storage applied them with the previous one. An earlier dev
|
|
371
|
+
* migration's statements are skipped only when the pending one contains
|
|
372
|
+
* every statement that migration ran: then it is the same change, squashed
|
|
373
|
+
* again. A statement the pending migration shares with an earlier one only
|
|
374
|
+
* in part (a table rebuilt differently) still runs, and a conflict is
|
|
375
|
+
* reported as one.
|
|
376
|
+
*/
|
|
377
|
+
statementsRepeatedFromEarlierPushes(pending) {
|
|
378
|
+
const repeated = /* @__PURE__ */ new Map();
|
|
379
|
+
const devChunks = pending.filter((chunk) => chunk.name.startsWith(DEV_MIGRATION_PREFIX));
|
|
380
|
+
if (devChunks.length === 0) return repeated;
|
|
381
|
+
const devStatements = this.readDevStatements();
|
|
382
|
+
if (!devStatements || devStatements.size === 0) return repeated;
|
|
383
|
+
const ranBy = /* @__PURE__ */ new Map();
|
|
384
|
+
for (const [statement, migration] of devStatements) {
|
|
385
|
+
const statements = ranBy.get(migration) ?? /* @__PURE__ */ new Set();
|
|
386
|
+
statements.add(statement);
|
|
387
|
+
ranBy.set(migration, statements);
|
|
388
|
+
}
|
|
389
|
+
for (const name of new Set(devChunks.map((chunk) => chunk.name))) {
|
|
390
|
+
const own = new Set(devChunks.filter((chunk) => chunk.name === name).flatMap((chunk) => chunk.statements).map(normalizeStatement).filter((statement) => statement.length > 0));
|
|
391
|
+
const statements = /* @__PURE__ */ new Set();
|
|
392
|
+
const from = [];
|
|
393
|
+
for (const [earlier, ran] of ranBy) {
|
|
394
|
+
if (earlier === name) continue;
|
|
395
|
+
if (![...ran].every((statement) => own.has(statement))) continue;
|
|
396
|
+
for (const statement of ran) statements.add(statement);
|
|
397
|
+
from.push(earlier);
|
|
398
|
+
}
|
|
399
|
+
if (statements.size > 0) repeated.set(name, {
|
|
400
|
+
statements,
|
|
401
|
+
from
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
return repeated;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* The statements this storage's dev migrations applied (normalized →
|
|
408
|
+
* the dev migration that ran it), or null when it never ran one.
|
|
409
|
+
*/
|
|
410
|
+
readDevStatements() {
|
|
411
|
+
if (this.sql.exec(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`, DEV_STATEMENTS_TABLE).toArray().length === 0) return null;
|
|
412
|
+
const rows = this.sql.exec(`SELECT statement, migration FROM ${DEV_STATEMENTS_TABLE}`).toArray();
|
|
413
|
+
return new Map(rows.map((row) => [row.statement, row.migration]));
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
247
416
|
* Collect pending migration chunks that haven't been applied yet.
|
|
248
417
|
*/
|
|
249
418
|
collectPendingMigrations() {
|
|
@@ -267,16 +436,27 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
267
436
|
return pending;
|
|
268
437
|
}
|
|
269
438
|
/**
|
|
270
|
-
* Apply a list of pending migration chunks
|
|
439
|
+
* Apply a list of pending migration chunks, skipping the statements of a
|
|
440
|
+
* dev migration that earlier dev migrations already ran (`repeated`, see
|
|
441
|
+
* {@link statementsRepeatedFromEarlierPushes}).
|
|
271
442
|
*/
|
|
272
|
-
applyMigrations(pending) {
|
|
443
|
+
applyMigrations(pending, repeated = /* @__PURE__ */ new Map()) {
|
|
444
|
+
const reported = /* @__PURE__ */ new Set();
|
|
273
445
|
for (const { name, chunkIndex, statements } of pending) {
|
|
274
446
|
let currentIndex = -1;
|
|
275
447
|
let currentStatement = null;
|
|
448
|
+
const isDevMigration = name.startsWith(DEV_MIGRATION_PREFIX);
|
|
449
|
+
const skip = repeated.get(name);
|
|
450
|
+
let skipped = 0;
|
|
276
451
|
const applyChunk = () => {
|
|
452
|
+
skipped = 0;
|
|
277
453
|
for (let i = 0; i < statements.length; i++) {
|
|
278
454
|
const statement = statements[i];
|
|
279
455
|
if (!statement.trim()) continue;
|
|
456
|
+
if (skip?.statements.has(normalizeStatement(statement))) {
|
|
457
|
+
skipped++;
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
280
460
|
currentIndex = i;
|
|
281
461
|
currentStatement = statement;
|
|
282
462
|
this.sql.exec(statement);
|
|
@@ -284,12 +464,21 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
284
464
|
currentIndex = -1;
|
|
285
465
|
currentStatement = null;
|
|
286
466
|
this.sql.exec("INSERT INTO __migrations (name, chunk_index, applied_at) VALUES (?, ?, ?)", name, chunkIndex, (/* @__PURE__ */ new Date()).toISOString());
|
|
467
|
+
if (isDevMigration) for (const statement of statements) {
|
|
468
|
+
const normalized = normalizeStatement(statement);
|
|
469
|
+
if (!normalized) continue;
|
|
470
|
+
this.sql.exec(`INSERT OR IGNORE INTO ${DEV_STATEMENTS_TABLE} (statement, migration) VALUES (?, ?)`, normalized, name);
|
|
471
|
+
}
|
|
287
472
|
};
|
|
288
473
|
try {
|
|
289
474
|
const storage = this.ctx.storage;
|
|
290
475
|
if (typeof storage.transactionSync === "function") storage.transactionSync(applyChunk);
|
|
291
476
|
else applyChunk();
|
|
292
477
|
debugMigrations("Migration chunk applied: %s[%d]", name, chunkIndex);
|
|
478
|
+
if (skip && skipped > 0 && !reported.has(name)) {
|
|
479
|
+
reported.add(name);
|
|
480
|
+
console.log(`[database] Dev migration ${name}: skipped the statement(s) dev migration(s) ${skip.from.join(", ")} already applied to this storage (\`db push\` squashes every change since the last \`db generate\` again).`);
|
|
481
|
+
}
|
|
293
482
|
} catch (error) {
|
|
294
483
|
const location = currentStatement !== null ? ` stmt ${currentIndex}: ${formatStatementForLog(currentStatement)}` : " (while recording chunk as applied)";
|
|
295
484
|
console.error(`[database] Migration chunk failed: ${name}[${chunkIndex}]${location}`, error);
|
|
@@ -298,23 +487,25 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
298
487
|
}
|
|
299
488
|
}
|
|
300
489
|
/**
|
|
301
|
-
* Translate an "already exists"
|
|
302
|
-
* {@link MigrationSchemaConflictError}. A chunk is
|
|
303
|
-
* journal has no row for it, so
|
|
304
|
-
* disagree about what has been applied — retrying can
|
|
305
|
-
* the raw SQLITE_ERROR doesn't tell the user how to get
|
|
306
|
-
* Returns null when the error isn't this case.
|
|
490
|
+
* Translate an "already exists" or "duplicate column name" failure on a
|
|
491
|
+
* pending migration into a {@link MigrationSchemaConflictError}. A chunk is
|
|
492
|
+
* only executed when the journal has no row for it, so either error means
|
|
493
|
+
* storage and journal disagree about what has been applied — retrying can
|
|
494
|
+
* never succeed, and the raw SQLITE_ERROR doesn't tell the user how to get
|
|
495
|
+
* unstuck. Returns null when the error isn't this case.
|
|
307
496
|
*/
|
|
308
497
|
toSchemaConflictError(error, name, chunkIndex) {
|
|
309
498
|
const message = error instanceof Error ? error.message : String(error);
|
|
310
|
-
if (!/already exists/i.test(message)) return null;
|
|
499
|
+
if (!/already exists|duplicate column name/i.test(message)) return null;
|
|
311
500
|
let journalNames = [];
|
|
312
501
|
try {
|
|
313
502
|
journalNames = this.sql.exec("SELECT DISTINCT name FROM __migrations").toArray().map((row) => row.name);
|
|
314
503
|
} catch {}
|
|
315
504
|
const known = new Set(Object.keys(this.migrations));
|
|
316
505
|
const untracked = journalNames.filter((n) => !known.has(n));
|
|
317
|
-
|
|
506
|
+
const untrackedDev = untracked.filter((n) => n.startsWith(DEV_MIGRATION_PREFIX));
|
|
507
|
+
const reset = `db reset --database ${this.databaseName ?? databaseNameFromClass(this.constructor.name) ?? "<database>"}`;
|
|
508
|
+
return new MigrationSchemaConflictError(`Migration "${name}" (chunk ${chunkIndex}) tried to create a table, index or column that already exists in storage, but the __migrations journal has no record of this migration being applied. ${untrackedDev.length > 0 && name.startsWith("_dev_") ? `This storage applied an earlier dev migration (${untrackedDev.join(", ")}) whose change "${name}" makes again in another form — a column or table changed once more since that \`db push\` (or it was applied before durable-db journaled dev migration statements).` : untrackedDev.length > 0 ? `This storage applied dev migrations (${untrackedDev.join(", ")}) that \`db generate\` has since turned into production migrations, and their statements differ from "${name}" (or were applied before durable-db journaled dev migration statements).` : untracked.length > 0 ? `The journal records migrations this build doesn't know about (${untracked.join(", ")}), which usually means the migration files were renamed or regenerated after this database's storage was created.` : "This usually means the storage was created by migrations under different names (renamed or regenerated migration files), by an older version of this database, or that a previous attempt crashed partway through a chunk."} To recover in local dev, run \`${reset}\` to rotate to a fresh database (add --purge-local-storage to also delete the orphaned instance data, or wipe .wrangler/state yourself). In production, restore the original migration names, or baseline the journal by inserting rows into __migrations for the migrations whose schema is already present. Original error: ${message}`, { cause: error });
|
|
318
509
|
}
|
|
319
510
|
/**
|
|
320
511
|
* Manually restore the DO to a specific PITR bookmark.
|
|
@@ -434,4 +625,46 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
434
625
|
}
|
|
435
626
|
};
|
|
436
627
|
//#endregion
|
|
437
|
-
|
|
628
|
+
//#region src/db/RemovedDatabaseDurableObject.ts
|
|
629
|
+
/** What a call to a removed database's Durable Object answers. */
|
|
630
|
+
function removedDatabaseMessage(className, deleteMigration) {
|
|
631
|
+
return `${className} is the Durable Object of a removed database: no database defines it any more, but the wrangler migrations still declare it, so durable-db exports it as a tombstone that keeps its data untouched and answers no calls. Re-adding the database brings the data back. To delete the class — and ALL its data — for good, add this migration to wrangler.jsonc: ` + JSON.stringify(deleteMigration);
|
|
632
|
+
}
|
|
633
|
+
/** The error every RPC call to a removed database's Durable Object rejects with. */
|
|
634
|
+
var RemovedDatabaseError = class extends Error {
|
|
635
|
+
className;
|
|
636
|
+
deleteMigration;
|
|
637
|
+
constructor(className, deleteMigration) {
|
|
638
|
+
super(removedDatabaseMessage(className, deleteMigration));
|
|
639
|
+
this.className = className;
|
|
640
|
+
this.deleteMigration = deleteMigration;
|
|
641
|
+
this.name = "RemovedDatabaseError";
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
/**
|
|
645
|
+
* A tombstone for the class of a removed database. The worker must keep
|
|
646
|
+
* exporting every class its wrangler migrations declare (@cloudflare/vite-plugin
|
|
647
|
+
* wraps each one, and a deploy that drops a class with data fails), but only
|
|
648
|
+
* a `deleted_classes` migration drops one — and with it all its data, which
|
|
649
|
+
* durable-db never decides for the user. So the generated module exports this
|
|
650
|
+
* subclass under the old name until the database comes back or the user
|
|
651
|
+
* deletes the class: it never touches the storage, `fetch` answers 410 Gone
|
|
652
|
+
* and the RPC entry points of durable-db's stubs (`rpc`, `sys`) reject with a
|
|
653
|
+
* {@link RemovedDatabaseError} naming the migration that deletes it.
|
|
654
|
+
*/
|
|
655
|
+
var RemovedDatabaseDurableObject = class extends DurableObject {
|
|
656
|
+
fetch(_request) {
|
|
657
|
+
return new Response(removedDatabaseMessage(this.removedClassName, this.deleteMigration), {
|
|
658
|
+
status: 410,
|
|
659
|
+
headers: { "content-type": "text/plain; charset=utf-8" }
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
async rpc(..._args) {
|
|
663
|
+
throw new RemovedDatabaseError(this.removedClassName, this.deleteMigration);
|
|
664
|
+
}
|
|
665
|
+
async sys(..._args) {
|
|
666
|
+
throw new RemovedDatabaseError(this.removedClassName, this.deleteMigration);
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
//#endregion
|
|
670
|
+
export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, removedDatabaseMessage, studio, type };
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { n as type, t as actionArgsType } from "./actionArgs-1hEaDUia.js";
|
|
2
|
+
//#region src/db/defineDatabase.ts
|
|
3
|
+
/**
|
|
4
|
+
* Non-enumerable property the source `action()` stashes on the function it
|
|
5
|
+
* returns, carrying the original `{ args, handler }` config plus the compiled
|
|
6
|
+
* arktype validator. The production Vite transform replaces `action()`
|
|
7
|
+
* call-sites entirely, so this only ever exists in the UNTRANSFORMED world —
|
|
8
|
+
* i.e. tests. The `durable-db/testing` harness reads it to run a handler
|
|
9
|
+
* against a real in-memory database. See src/testing/index.ts.
|
|
10
|
+
*/
|
|
11
|
+
const ACTION_TEST_META = Symbol.for("durable-db.actionTestMeta");
|
|
12
|
+
/**
|
|
13
|
+
* Where the live test databases are listed, newest last. On `globalThis`, not
|
|
14
|
+
* module state: a test run can load `durable-db` (the app's actions) and
|
|
15
|
+
* `durable-db/testing` as separate module copies.
|
|
16
|
+
*/
|
|
17
|
+
const LIVE_TEST_DATABASES = Symbol.for("durable-db.liveTestDatabases");
|
|
18
|
+
/** The live test databases (created on first use). */
|
|
19
|
+
function liveTestDatabases() {
|
|
20
|
+
const store = globalThis;
|
|
21
|
+
return store[LIVE_TEST_DATABASES] ??= [];
|
|
22
|
+
}
|
|
23
|
+
/** The newest live test database holding every table of `schema`, if any. */
|
|
24
|
+
function testDatabaseFor(schema) {
|
|
25
|
+
const tables = Object.values(schema);
|
|
26
|
+
if (tables.length === 0) return void 0;
|
|
27
|
+
const live = globalThis[LIVE_TEST_DATABASES];
|
|
28
|
+
if (!live) return void 0;
|
|
29
|
+
for (let i = live.length - 1; i >= 0; i--) if (tables.every((table) => live[i].tables.has(table))) return live[i];
|
|
30
|
+
}
|
|
31
|
+
/** `createTestDatabase({ schema: { a, b } })` for this database, for messages. */
|
|
32
|
+
function testDatabaseHint(schema) {
|
|
33
|
+
const names = Object.keys(schema);
|
|
34
|
+
return `createTestDatabase({ schema: { ${names.length > 0 ? names.join(", ") : "…"} } })`;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Define a database with its schema and migrations.
|
|
38
|
+
*
|
|
39
|
+
* This function is transformed at build time by the durable-db Vite plugin.
|
|
40
|
+
* At runtime, the actions returned will be RPC stubs that call into the
|
|
41
|
+
* generated Durable Object.
|
|
42
|
+
*
|
|
43
|
+
* Outside the build — code under test calling an action directly — an action
|
|
44
|
+
* runs against the test database `createTestDatabase()` created for its
|
|
45
|
+
* database's tables (the newest one, when there are several); without one it
|
|
46
|
+
* throws.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* import { defineDatabase } from 'durable-db';
|
|
51
|
+
* import { users, posts } from './schema';
|
|
52
|
+
*
|
|
53
|
+
* export const { action } = defineDatabase({
|
|
54
|
+
* schema: { users, posts },
|
|
55
|
+
* });
|
|
56
|
+
*
|
|
57
|
+
* export const createUser = action({
|
|
58
|
+
* args: { name: 'string', email: 'string.email' },
|
|
59
|
+
* handler: async (db, args) => {
|
|
60
|
+
* return db.insertInto('users').values({
|
|
61
|
+
* id: crypto.randomUUID(),
|
|
62
|
+
* name: args.name,
|
|
63
|
+
* email: args.email
|
|
64
|
+
* }).returningAll().executeTakeFirst();
|
|
65
|
+
* },
|
|
66
|
+
* });
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
function defineDatabase(config) {
|
|
70
|
+
const schema = config?.schema ?? {};
|
|
71
|
+
const action = (actionConfig) => {
|
|
72
|
+
const validator = actionArgsType(actionConfig.args);
|
|
73
|
+
const argsDefinition = actionConfig.args;
|
|
74
|
+
const argKeys = argsDefinition !== null && typeof argsDefinition === "object" ? Object.keys(argsDefinition) : null;
|
|
75
|
+
const argsHint = argKeys ? ` (args: ${argKeys.length > 0 ? `{ ${argKeys.join(", ")} }` : "{}"})` : "";
|
|
76
|
+
const actionFn = async (args) => {
|
|
77
|
+
const testDatabase = testDatabaseFor(schema);
|
|
78
|
+
if (testDatabase) return await testDatabase.run(actionFn, args);
|
|
79
|
+
const result = validator(args);
|
|
80
|
+
if (result instanceof type.errors) throw new Error(`Invalid args for action${argsHint}: ${result.summary}`);
|
|
81
|
+
throw new Error(`Action${argsHint} called without transformation: action() call sites are transformed by the build; in tests, create the database with ${testDatabaseHint(schema)} and call the action, or use db.run(action, args).`);
|
|
82
|
+
};
|
|
83
|
+
Object.defineProperty(actionFn, ACTION_TEST_META, {
|
|
84
|
+
value: {
|
|
85
|
+
args: actionConfig.args,
|
|
86
|
+
handler: actionConfig.handler,
|
|
87
|
+
validator,
|
|
88
|
+
schema
|
|
89
|
+
},
|
|
90
|
+
enumerable: false,
|
|
91
|
+
configurable: true
|
|
92
|
+
});
|
|
93
|
+
return actionFn;
|
|
94
|
+
};
|
|
95
|
+
const destroyDatabase = async () => {
|
|
96
|
+
const testDatabase = testDatabaseFor(schema);
|
|
97
|
+
if (testDatabase) {
|
|
98
|
+
testDatabase.clear();
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
throw new Error(`destroyDatabase() called without transformation: it is transformed by the build; in tests, create the database with ${testDatabaseHint(schema)} first.`);
|
|
102
|
+
};
|
|
103
|
+
return {
|
|
104
|
+
action,
|
|
105
|
+
destroyDatabase
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
109
|
+
export { defineDatabase as n, liveTestDatabases as r, ACTION_TEST_META as t };
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import "./arktypeConfig-AXvobTPL.js";
|
|
2
1
|
import { type } from "arktype";
|
|
3
2
|
import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
|
|
4
3
|
import { Kysely } from "kysely";
|
|
5
4
|
import { Kyselify } from "drizzle-orm/kysely";
|
|
5
|
+
//#region src/arktypeConfig.d.ts
|
|
6
|
+
declare const type$1: typeof type;
|
|
7
|
+
//#endregion
|
|
6
8
|
//#region src/db/types.d.ts
|
|
7
9
|
/**
|
|
8
10
|
* Base type for ArkType schema definitions.
|
|
@@ -161,6 +163,11 @@ interface ParsedDatabaseFile {
|
|
|
161
163
|
* At runtime, the actions returned will be RPC stubs that call into the
|
|
162
164
|
* generated Durable Object.
|
|
163
165
|
*
|
|
166
|
+
* Outside the build — code under test calling an action directly — an action
|
|
167
|
+
* runs against the test database `createTestDatabase()` created for its
|
|
168
|
+
* database's tables (the newest one, when there are several); without one it
|
|
169
|
+
* throws.
|
|
170
|
+
*
|
|
164
171
|
* @example
|
|
165
172
|
* ```ts
|
|
166
173
|
* import { defineDatabase } from 'durable-db';
|
|
@@ -182,6 +189,6 @@ interface ParsedDatabaseFile {
|
|
|
182
189
|
* });
|
|
183
190
|
* ```
|
|
184
191
|
*/
|
|
185
|
-
declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(
|
|
192
|
+
declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(config: DatabaseConfig<TSchema>): DatabaseDefinition<TSchema>;
|
|
186
193
|
//#endregion
|
|
187
|
-
export { ActionInfo as a, DatabaseDefinition as c, InferArgs as d, ParsedDatabaseFile as f, ActionContext as i, DatabaseInfo as l, Action as n, ArgsSchema as o, ActionConfig as r, DatabaseConfig as s, defineDatabase as t, DrizzleToKysely as u };
|
|
194
|
+
export { ActionInfo as a, DatabaseDefinition as c, InferArgs as d, ParsedDatabaseFile as f, ActionContext as i, DatabaseInfo as l, Action as n, ArgsSchema as o, type$1 as p, ActionConfig as r, DatabaseConfig as s, defineDatabase as t, DrizzleToKysely as u };
|