durable-db 0.2.2 → 0.4.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.
Files changed (34) hide show
  1. package/README.md +175 -25
  2. package/dist/{arktypeConfig-DxP0OcV_.js → actionArgs-1hEaDUia.js} +35 -1
  3. package/dist/cli/bin.js +1 -1
  4. package/dist/cli/index.d.ts +204 -62
  5. package/dist/cli/index.js +4 -3
  6. package/dist/{cli-BUSZTS2D.js → cli-CVS0b2im.js} +272 -95
  7. package/dist/context/index.js +14 -8
  8. package/dist/db/index.d.ts +2 -3
  9. package/dist/db/index.js +216 -25
  10. package/dist/defineDatabase-D_RpcKj1.js +109 -0
  11. package/dist/{defineDatabase-IUthY3Ex.d.ts → defineDatabase-zrUJrMd5.d.ts} +10 -3
  12. package/dist/{index-BdrcuAU7.d.ts → index-CJ6Focq4.d.ts} +70 -17
  13. package/dist/index.d.ts +1 -2
  14. package/dist/index.js +2 -2
  15. package/dist/{kysely-Be6KwFZC.js → kysely-CYmmiwDm.js} +25 -5
  16. package/dist/migrations/generator.d.ts +1 -1
  17. package/dist/migrations/generator.js +1 -1
  18. package/dist/migrations/snapshot.d.ts +2 -2
  19. package/dist/migrations/snapshot.js +1 -91
  20. package/dist/{parser-DR57GOjv.js → parser-DyepmXzE.js} +1 -1
  21. package/dist/registry.d.ts +29 -2
  22. package/dist/registry.js +2 -2
  23. package/dist/snapshot-B9Ae2TrS.d.ts +180 -0
  24. package/dist/snapshot-D_z95s6E.js +459 -0
  25. package/dist/{state-OVuoHRC9.js → state-DGYycIoJ.js} +106 -9
  26. package/dist/testing/index.d.ts +8 -1
  27. package/dist/testing/index.js +30 -11
  28. package/dist/vite/durableDb.d.ts +130 -1
  29. package/dist/vite/durableDb.js +733 -180
  30. package/package.json +15 -14
  31. package/virtual.d.ts +4 -2
  32. package/dist/arktypeConfig-AXvobTPL.d.ts +0 -5
  33. package/dist/defineDatabase-CHmzpzFf.js +0 -70
  34. package/dist/snapshot-CaG5xnE2.d.ts +0 -48
package/README.md CHANGED
@@ -16,13 +16,16 @@ Define your schema with [Drizzle](https://orm.drizzle.team/), query with [Kysely
16
16
  - [status](#db-status)
17
17
  - [reset](#db-reset)
18
18
  - [validate](#db-validate)
19
+ - [Renames](#renames)
19
20
  - [Migration System](#migration-system)
20
21
  - [Dev Migrations](#dev-migrations)
21
22
  - [Production Migrations](#production-migrations)
22
23
  - [Breakpoints](#breakpoints)
24
+ - [Adding a required column](#adding-a-required-column)
23
25
  - [Epoch System](#epoch-system)
24
26
  - [Typical Workflow](#typical-workflow)
25
27
  - [Vite Plugin](#vite-plugin)
28
+ - [Testing Actions](#testing-actions)
26
29
  - [Outerbase Studio Integration](#outerbase-studio-integration)
27
30
  - [Instance Strategies](#instance-strategies)
28
31
  - [Action-to-Action Calls](#action-to-action-calls)
@@ -115,6 +118,8 @@ export default defineConfig({
115
118
  });
116
119
  ```
117
120
 
121
+ The plugin supports Vite 5 through 8 (`vite` is a peer dependency).
122
+
118
123
  ### 6. Use in your worker
119
124
 
120
125
  ```ts
@@ -213,10 +218,12 @@ args: { email: 'string.email' } // Email validation
213
218
  args: { limit: 'number > 0' } // Positive number
214
219
  args: { offset: 'number >= 0' } // Non-negative number
215
220
  args: { tags: 'string[]' } // Array of strings
216
- args: { name: 'string', age: 'number?' } // Optional field
221
+ args: { name: 'string', 'age?': 'number' } // Optional key
217
222
  args: { role: "'admin' | 'user'" } // Literal union
218
223
  ```
219
224
 
225
+ An optional key accepts `undefined`, as its inferred TypeScript type (`{ photoKey?: string }`) does: `addReview({ productId, photoKey: maybeKey })` validates whether or not there is a key, at any depth. A required key stays required, also when its type admits `undefined` (`note: 'string | undefined'` must be passed). Args compile with the `type` of `durable-db/registry`, an ArkType scope with `exactOptionalPropertyTypes: false`; the `type` exported from `durable-db` keeps ArkType's default.
226
+
220
227
  ### The `handler` function
221
228
 
222
229
  Receives three arguments:
@@ -299,6 +306,7 @@ The `db` CLI manages your migration lifecycle. All commands share these options:
299
306
  | Flag | Default | Description |
300
307
  |------|---------|-------------|
301
308
  | `-d, --databases-dir <dir>` | `src/databases` | Directory containing database definitions |
309
+ | `--database <db>` | (all) | Only this database. An unknown name exits with code 1 and lists the valid ones |
302
310
  | `-v, --verbose` | `false` | Show detailed output |
303
311
 
304
312
  **Schema loading is strict.** When a database declares tables in `defineDatabase({ schema })`, every command that loads the schema (`push`, `generate`, `status`, `validate`) fails with exit code 1 — instead of reporting "no changes" — if:
@@ -318,8 +326,17 @@ Push schema changes to dev migrations. This is the command you run most often du
318
326
  db push
319
327
  db push --verbose
320
328
  db push --databases-dir ./src/db
329
+ db push --database main
330
+ db push --rename users.bio=about # answer a rename question (see Renames)
321
331
  ```
322
332
 
333
+ **Extra flags:**
334
+
335
+ | Flag | Description |
336
+ |------|-------------|
337
+ | `--rename <table.old=new>` | Answer a rename question without a prompt: `<table>.<old>=<new>` renames a column, `<old>=<new>` a table. Repeatable. See [Renames](#renames) |
338
+ | `--no-renames` | Answer every remaining rename question with "create" (the old column/table is dropped) |
339
+
323
340
  **What it does:**
324
341
 
325
342
  1. Discovers all database files in your databases directory
@@ -331,6 +348,8 @@ db push --databases-dir ./src/db
331
348
  - If there are changes: replaces any previous dev migration with a **single squashed migration** named after a hash of its content (e.g. `dev_a1b2c3d4.sql`). `CREATE TABLE`/`CREATE INDEX` statements get `IF NOT EXISTS` added so the squashed migration can overlay tables a previous dev migration already created
332
349
  - If the same content hash already exists, nothing is rewritten — the DO recognizes the migration name and skips it
333
350
 
351
+ Every push diffs from the production snapshot, so a second push (add a column, restart, add another) repeats the first one's statements. The dev Durable Object journals what each dev migration ran and skips the statements of an earlier dev migration that the new one contains whole; one that redoes an earlier change in another form (the same column with another type) fails with `MigrationSchemaConflictError` and the `db reset --database <name>` to run.
352
+
334
353
  **Output example:**
335
354
 
336
355
  ```
@@ -349,6 +368,8 @@ All databases are up to date.
349
368
 
350
369
  Dev migrations are stored in `node_modules/.cache/durable-db/` and are never committed to git. They are loaded automatically by the Vite plugin in dev mode.
351
370
 
371
+ `push` warns (`⚠`) about what a change risks on a database that has rows — a `NOT NULL` column without a default fails on every table with rows, your dev database's included (see [Adding a required column](#adding-a-required-column)), and a dropped column or table loses its data.
372
+
352
373
  ### `db generate`
353
374
 
354
375
  Generate a production migration from your current schema changes. Run this when you're ready to commit.
@@ -371,14 +392,23 @@ db generate --database main add_posts_table
371
392
  | Flag | Description |
372
393
  |------|-------------|
373
394
  | `--database <db>` | Only generate for this specific database |
395
+ | `--rename <table.old=new>` | Answer a rename question without a prompt (repeatable). See [Renames](#renames) |
396
+ | `--no-renames` | Answer every remaining rename question with "create" (the old column/table is dropped) |
397
+ | `--force` | Write the migration even when a statement fails on every table that has rows |
374
398
 
375
399
  **What it does:**
376
400
 
377
401
  1. Compares your current Drizzle schema against the production snapshot (`_snapshot.json`)
378
- 2. Generates SQL statements for the diff
379
- 3. Writes a timestamped `.sql` file to the configured `migrationsDir`
380
- 4. Updates the production snapshot with a new ID and `prevId` chain
381
- 5. Clears dev state for this database (the dev migrations are now superseded by the production migration)
402
+ 2. Generates SQL statements for the diff (asking about renames — see [Renames](#renames))
403
+ 3. Checks what they do to a database that has rows (below) — before any file is written
404
+ 4. Writes a timestamped `.sql` file to the configured `migrationsDir`
405
+ 5. Updates the production snapshot with a new ID and `prevId` chain
406
+ 6. Clears dev state for this database (the dev migrations are now superseded by the production migration)
407
+
408
+ **Unsafe statements.** Per-tenant databases migrate lazily, on each tenant's first request after a deploy — so a statement that only fails on a table with rows surfaces in production, once per tenant with data, and that tenant's database stays broken until a fixed migration ships. `db validate` cannot catch it: it replays the migrations on an empty database. So `generate`:
409
+
410
+ - **refuses** (exit code 1, nothing written) a column added `NOT NULL` without a default: `products.currency is added NOT NULL without a default — the migration fails on every table that has rows: add .default(...) or add it nullable and backfill`. `--force` writes it anyway (a table known to be empty everywhere). See [Adding a required column](#adding-a-required-column);
411
+ - **warns** (`⚠`) when a column or table is dropped (its data is lost) or a column becomes `NOT NULL` (fails where a row holds `NULL`).
382
412
 
383
413
  **Output example:**
384
414
 
@@ -399,6 +429,7 @@ Show the current migration status for all databases without making any changes.
399
429
 
400
430
  ```bash
401
431
  db status
432
+ db status --database main
402
433
  db status --verbose
403
434
  ```
404
435
 
@@ -421,7 +452,18 @@ Dev Epoch: m1a2b3c
421
452
  ✓ Schema is up to date
422
453
  ```
423
454
 
424
- Shows per-database: production migration count, dev migration count, whether there are uncommitted schema changes (pending SQL statements that haven't been pushed yet), and the last push timestamp. If a teammate committed new production migrations since your last push, a `⚠️ Production snapshot changed - run 'db:reset' to sync` warning appears.
455
+ Shows per-database: production migration count, dev migration count, whether there are uncommitted schema changes (pending SQL statements that haven't been pushed yet), and the last push timestamp. If a teammate committed new production migrations since your last push, a `⚠️ Production snapshot changed - run 'db:reset' to sync` warning appears. A database with its own epoch (after `db reset --database`) shows it.
456
+
457
+ `status` never prompts. A change drizzle-kit can only diff by asking whether a name is a rename is reported as such, never as up to date:
458
+
459
+ ```
460
+ 📦 main
461
+ 📝 Changes pending — needs rename resolution:
462
+ - users: about added, bio removed
463
+ Answer when you push/generate: in a terminal (it asks), or with --rename users.bio=about (a rename) or --no-renames (create + drop)
464
+ ```
465
+
466
+ Pending SQL that would fail on a table with rows, or drop data, is listed with a `⚠️` line.
425
467
 
426
468
  ### `db reset`
427
469
 
@@ -440,19 +482,21 @@ db reset --purge-local-storage
440
482
  | Flag | Description |
441
483
  |------|-------------|
442
484
  | `--keep-epoch` | Only clear dev migrations; keep the same DO instances |
443
- | `--database <db>` | Only reset this specific database |
444
- | `--purge-local-storage` | Also delete workerd's persisted DO storage under `.wrangler/` (requires the dev server to be stopped) |
485
+ | `--database <db>` | Only reset this database: it alone starts fresh, every other keeps its data |
486
+ | `--purge-local-storage` | Also delete workerd's persisted DO storage under `.wrangler/`. Refused while the dev server runs |
487
+ | `--force` | With `--purge-local-storage`: purge even when a dev server appears to be running |
445
488
 
446
- **Two modes:**
489
+ **Three modes:**
447
490
 
448
491
  | Mode | What happens |
449
492
  |------|-------------|
450
- | **Full reset** (default) | Bumps the epoch. All databases rotate to brand-new DO instances on the next request — fresh, empty SQLite with migrations re-applied. Clears all dev migrations and snapshots. Works while the dev server is running. |
493
+ | **Full reset** (default) | Bumps the project epoch. All databases rotate to brand-new DO instances on the next request — fresh, empty SQLite with migrations re-applied. Clears all dev migrations and snapshots. Works while the dev server is running. |
494
+ | **One database** (`--database <db>`) | Gives that database its own new epoch: only its instances rotate (every tenant's), the other databases — a tenant directory, say — keep their data. Clears its dev migrations and snapshot. |
451
495
  | **Keep epoch** (`--keep-epoch`) | Only clears dev migrations and snapshots. Existing DO instances keep running with their current data. |
452
496
 
453
- **How fresh instances work**: in dev, every DO instance key is suffixed with the current epoch (`<key>__dev_<epoch>`) by the generated stubs. Bumping the epoch makes `idFromName()` resolve to entirely new DO instances, so the old tables can never collide with the new schema. The Vite dev server watches the dev-state file and reloads automatically when the epoch changes — no restart needed.
497
+ **How fresh instances work**: in dev, every DO instance key is suffixed with its database's epoch (`<key>__dev_<epoch>`) by the generated stubs. Bumping an epoch makes `idFromName()` resolve to entirely new DO instances, so the old tables can never collide with the new schema. The Vite dev server watches the dev-state file and reloads automatically when an epoch changes — no restart needed.
454
498
 
455
- **Disk space**: the previous instances' SQLite files stay orphaned under `.wrangler/state/v3/do` until you purge them. Run `db reset --purge-local-storage` (with the dev server **stopped** — workerd keeps deleted storage open and breaks with `internal error; reference = …` until restart) or simply `rm -rf .wrangler` whenever you want the disk back. With `--database <db>`, only the storage directories matching that database's DO class are purged.
499
+ **Disk space**: the previous instances' SQLite files stay orphaned under `.wrangler/state/v3/do` until you purge them. Run `db reset --purge-local-storage` with the dev server **stopped** — workerd keeps deleted storage open and every database request fails with `internal error; reference = …` until it restarts, so the command refuses while the dev server runs (the Vite plugin records the running server in `node_modules/.cache/durable-db/dev-server.json`; a server that was killed leaves a stale record, which is ignored once its process is gone). Or simply `rm -rf .wrangler` whenever you want the disk back. With `--database <db>`, only the storage directories matching that database's DO class are purged.
456
500
 
457
501
  **Output example:**
458
502
 
@@ -486,6 +530,9 @@ db validate --verbose
486
530
  3. Builds the expected schema separately from the Drizzle definition
487
531
  4. Compares the migrated schema against the expected schema to detect drift
488
532
  5. Reports SQL errors, foreign key violations, or schema mismatches
533
+ 6. Warns (`⚠ not yet generated: …`) about what the schema change `db generate` has not written yet would do to a database that has rows — the checks `generate` applies (a `NOT NULL` column without a default, dropped columns and tables, names that may be renames)
534
+
535
+ The replay runs on an **empty** database, so it proves a migration is valid SQL, not that it succeeds on a table with rows. Committed migrations are not re-checked for that: validate cannot know which of them already ran where.
489
536
 
490
537
  **Output example (success):**
491
538
 
@@ -515,6 +562,26 @@ Schema drift (migrations ran cleanly but produce a different schema than your Dr
515
562
  | `0` | All validations passed |
516
563
  | `1` | Validation errors found |
517
564
 
565
+ ### Renames
566
+
567
+ drizzle-kit cannot tell a renamed column (or table) from a dropped one plus a new one. When a table has both a new and a vanished column — or the schema both a new and a vanished table — its diff asks:
568
+
569
+ ```
570
+ Is about column in users table created or renamed from another column?
571
+ ❯ + about create column
572
+ ~ bio › about rename column
573
+ ```
574
+
575
+ `push` and `generate` show that prompt in a terminal. Without one (CI, a piped shell, a host CLI that runs `push` in the background) they answer from the command line instead, or fail with a message naming the command and both answers:
576
+
577
+ ```bash
578
+ db generate rename_bio --rename users.bio=about # a rename: the data is kept
579
+ db generate --rename items=products # a table rename
580
+ db generate --no-renames # create + drop: bio's data is lost
581
+ ```
582
+
583
+ Names are the SQL names (snake_case, as in the migration files); a camelCase property name works too. An answer applies to the database(s) where it matches; one that matches no pending change is an error. The rename is written as drizzle-kit writes it (`` ALTER TABLE `users` RENAME COLUMN "bio" TO "about"; ``), so `push` and `generate` produce the same statement. Programmatically: `push({ renames, noRenames, interactive })`, `generate(ctx, { renames, noRenames, interactive, force })` — `interactive: false` never prompts (a host CLI starting a dev server wants that), and an unanswered question throws `SchemaRenameRequiredError` (its `describe(command)` is the message with your command's name).
584
+
518
585
  ### Embedding in your own CLI
519
586
 
520
587
  The commands are composable Commander commands, so a host CLI can re-use them:
@@ -531,6 +598,8 @@ program.addCommand(createDbCommand());
531
598
  registerDbCommands(program);
532
599
  ```
533
600
 
601
+ Messages that suggest a command (a rename answer, for one) name it as the user typed it: `mycli db generate --rename …`.
602
+
534
603
  ### Programmatic API
535
604
 
536
605
  All CLI functions are also available for integration into other tools:
@@ -589,6 +658,17 @@ CREATE TABLE posts (id TEXT PRIMARY KEY, author_id TEXT REFERENCES users(id));
589
658
 
590
659
  Each chunk is tracked independently in the `__migrations` table. If a Durable Object restarts mid-migration, it resumes from the last completed chunk rather than re-running from the start.
591
660
 
661
+ Concurrent first calls to a Durable Object share one migration run: requests that arrive while it migrates wait for it instead of applying the same statements again.
662
+
663
+ ### Adding a required column
664
+
665
+ SQLite rejects `ALTER TABLE … ADD … NOT NULL` without a default on a table that has rows (`Cannot add a NOT NULL column with default value NULL`), and every tenant's database migrates on its own, after the deploy. So `db generate` refuses such a column (see [Unsafe statements](#db-generate)). Either:
666
+
667
+ - give it a default: `currency: text().notNull().default('SEK')` — the existing rows get it; or
668
+ - add it nullable (`currency: text()`), deploy, backfill every tenant (a job over your tenants, say), then make it `.notNull()` in a later migration.
669
+
670
+ The same holds for renames: answering a rename question with "create" (or `--no-renames`) adds the new column — `NOT NULL` without a default fails the same way — and drops the old one with its data.
671
+
592
672
  ### Epoch System
593
673
 
594
674
  In development, each database instance key gets an epoch suffix to enable clean resets:
@@ -598,17 +678,18 @@ In development, each database instance key gets an epoch suffix to enable clean
598
678
  | Production | `example-tenant` |
599
679
  | Development | `example-tenant__dev_m1a2b3c` |
600
680
 
601
- When you run `db reset` (without `--keep-epoch`), a new epoch is generated. This causes all subsequent DO accesses to create fresh instances, effectively giving you a clean database without data from previous iterations.
681
+ When you run `db reset` (without `--keep-epoch`), a new project epoch is generated. This causes all subsequent DO accesses to create fresh instances, effectively giving you a clean database without data from previous iterations. `db reset --database <db>` gives that database an epoch of its own instead, so only its instances rotate; the next full reset moves every database back to the (new) project epoch.
602
682
 
603
- The epoch is a base36-encoded timestamp stored in `node_modules/.cache/durable-db/state.json`.
683
+ Epochs are base36-encoded timestamps stored in `node_modules/.cache/durable-db/state.json` — the project's as `epoch`, a database's own as `databases.<name>.epoch`.
604
684
 
605
- **How the epoch reaches the worker**: the Vite plugin serves a virtual module (`virtual:durable-db/__devEpoch`) exporting `applyDevEpoch(key)`, and every generated stub routes its instance key through it. In dev the plugin embeds the current epoch from `state.json`; in production builds the epoch is `null` and `applyDevEpoch` is the identity function, so production keys are never suffixed. The dev server watches durable-db's dev cache directory and reloads on change, so both `db reset` (new epoch → fresh instances) and `db push` (new dev migration → re-embedded into the DO module) take effect on the next request without restarting.
685
+ **How the epoch reaches the worker**: the Vite plugin serves a virtual module (`virtual:durable-db/__devEpoch`) exporting `applyDevEpoch(key, dbName)`, and every generated stub routes its instance key through it with its database's name. In dev the plugin embeds the epochs from `state.json`; in production builds the epoch is `null` and `applyDevEpoch` is the identity function, so production keys are never suffixed. The dev server watches durable-db's dev cache directory and reloads on change, so both `db reset` (new epoch → fresh instances) and `db push` (new dev migration → re-embedded into the DO module) take effect on the next request without restarting.
606
686
 
607
687
  ### Dev State Structure
608
688
 
609
689
  ```
610
690
  node_modules/.cache/durable-db/
611
- state.json # Global state (epoch, per-db push info)
691
+ state.json # Global state (epoch, per-db epochs and push info)
692
+ dev-server.json # The running dev server (pid), while one runs
612
693
  databases/
613
694
  main/
614
695
  _snapshot.json # Dev snapshot (schema state)
@@ -628,13 +709,17 @@ The `state.json` file tracks:
628
709
  "databases": {
629
710
  "main": {
630
711
  "prodSnapshotHash": "abc123...",
631
- "lastPush": "2024-03-15T10:30:00.000Z",
632
- "devMigrationCount": 2
712
+ "lastPush": "2024-03-15T10:30:00.000Z"
713
+ },
714
+ "analytics": {
715
+ "epoch": "m1a9x2k"
633
716
  }
634
717
  }
635
718
  }
636
719
  ```
637
720
 
721
+ A database's `epoch` is set by `db reset --database <name>`; without it the project `epoch` applies.
722
+
638
723
  ### Typical Workflow
639
724
 
640
725
  **During development:**
@@ -654,6 +739,8 @@ db reset
654
739
 
655
740
  **Ready to deploy:**
656
741
 
742
+ `db generate` writes the statements your dev database already applied through `db push` as a production migration. A dev database that applied them records that migration as applied instead of running it again (which would fail with `duplicate column name` / `already exists`), so the dev data survives the hand-off — no reset needed.
743
+
657
744
  ```bash
658
745
  # 1. Generate a production migration
659
746
  db generate add_user_profiles
@@ -693,16 +780,16 @@ durableDb({
693
780
  | `migrationsDir` | `string` | `'migrations'` | Directory for production migrations, relative to project root. Each database gets a subdirectory (e.g. `migrations/main/`) |
694
781
  | `contextImport` | `string` | `'durable-db/context'` | Import path for the context module (for framework integrations) |
695
782
  | `registryImport` | `string` | `'durable-db/registry'` | Import path for the action registry module (for framework integrations) |
696
- | `patchWranglerConfig` | `boolean` | `false` | Write missing DO bindings and sqlite migration entries to `wrangler.jsonc` automatically. Off by default — the plugin only verifies the config and logs the exact JSON to add. Only `wrangler.jsonc`/`wrangler.json` are supported (not `wrangler.toml`) |
783
+ | `patchWranglerConfig` | `boolean` | `false` | Reconcile `wrangler.jsonc` with the discovered databases automatically, in the plugin's `config` hook: add bindings and `new_sqlite_classes` migrations, remove durable-db's own stale bindings, write `renamed_classes` for a mount change. Off by default — the plugin only verifies the config and logs the exact JSON to add. Only `wrangler.jsonc`/`wrangler.json` are supported (not `wrangler.toml`) |
697
784
 
698
785
  ### What the plugin does
699
786
 
700
787
  1. **Discovery**: Finds all `defineDatabase()` files in your databases directory (excludes `schema.ts`, `_*.ts`, `.d.ts`)
701
- 2. **AST Parsing**: Uses Babel to extract database config and action definitions (no regexes)
788
+ 2. **AST Parsing**: Uses Babel to extract database config and action definitions (no regexes). Only modules that can define a database or actions (they mention `defineDatabase`, or import an `action` factory) are parsed — a syntax error in any other module is reported by the compiler that owns it, not by durable-db
702
789
  3. **Migration Loading**: Loads production migrations from disk; in dev mode also loads dev migrations from cache
703
790
  4. **Code Generation**: Produces a virtual module (`virtual:durable-db/__durableObjects`) containing Durable Object classes with embedded migrations and RPC dispatch methods, plus a `virtual:durable-db/__devEpoch` module that suffixes DO instance keys with the dev epoch (identity in production builds)
704
791
  5. **Action Transform**: Replaces `action()` call-sites with RPC stubs + `registerAction()` calls so actions can be called like regular functions from your worker. This applies to actions in separate files *and* actions defined in the database file itself
705
- 6. **Wrangler Verification**: Checks that `wrangler.jsonc` contains the required Durable Object bindings and SQLite migration entries, and logs the exact JSON to add when something is missing. With `patchWranglerConfig: true`, writes them for you instead
792
+ 6. **Wrangler Verification**: Checks that `wrangler.jsonc` contains the required Durable Object bindings and SQLite migration entries and no binding or class of a database that is gone, and logs the exact JSON to add (or remove) when something is off. With `patchWranglerConfig: true`, reconciles it for you instead
706
793
  7. **HMR**: Watches database files and invalidates the virtual module on change
707
794
 
708
795
  ### Wrangler config: verify vs. patch
@@ -720,7 +807,36 @@ The plugin needs each database's Durable Object binding and a `new_sqlite_classe
720
807
  Or let the plugin write it for you: durableDb({ patchWranglerConfig: true })
721
808
  ```
722
809
 
723
- **Opt-in (auto-patch)**: pass `durableDb({ patchWranglerConfig: true })` and the plugin writes the missing entries for you. If your `wrangler.jsonc` contains comments, the original is backed up to `wrangler.jsonc.backup` first (re-serializing strips comments).
810
+ A production build fails when the config does not match, with an error naming what is missing and what is stale.
811
+
812
+ **Opt-in (auto-patch)**: pass `durableDb({ patchWranglerConfig: true })` and the plugin reconciles the config with the discovered databases, editing the file in place: comments, formatting and line endings stay as you wrote them, only the entries it adds or removes change.
813
+
814
+ - A new database gets its binding and a `new_sqlite_classes` migration.
815
+ - durable-db's own bindings (`<X>_DATABASE_DO` → `<X>DatabaseDO`) whose class is no longer a discovered database are removed: workerd refuses to start with a binding to a class the worker does not export. Other bindings, and bindings with a `script_name`, are never touched.
816
+ - A database of a mounted source (a `databasesDir` entry with a `prefix`) whose class name changed — its mount changed, or it moved into a mounted source, its file name unchanged — gets a `renamed_classes` migration, so Cloudflare moves its deployed data to the new class on deploy. That data carries its `__migrations` journal, so the old migrations directory moves with it (`migrations/reviews-feedback/` → `migrations/feedback-feedback/`). If the new directory already has migrations (say `db generate` ran under the new mount first), or several directories belong to the old class, nothing is written for that database and the plugin stops with the two ways out: `rm -r` the new directory and `mv` the old one to keep the data, or add the `deleted_classes` migration to drop it. A database moved out of a mount, or two databases of the app (`product-catalog.ts` replacing `catalog.ts`), are never paired. Local dev storage is kept per class name, so in dev a renamed database starts empty.
817
+ - A removed database's class is never deleted for you (that deletes its data): a warning gives the exact `deleted_classes` migration to add, or says to drop the class from its `new_sqlite_classes` entry if it was never deployed.
818
+
819
+ It does this in its `config` hook, before `@cloudflare/vite-plugin` reads the file (durable-db is `enforce: 'pre'`): the Cloudflare plugin builds `dist/<worker>/wrangler.json` from the config it read and restarts a dev server when the file changes later, so a later patch would ship a build without the new binding and restart the first dev start. A change is logged:
820
+
821
+ ```
822
+ durable-db updated wrangler.jsonc (Durable Objects: +AUDIT_DATABASE_DO → AuditDatabaseDO; migration v2: AuditDatabaseDO)
823
+ ```
824
+
825
+ A CLI that wants the file settled before it starts Vite (to deploy it, say) can run the same step itself:
826
+
827
+ ```ts
828
+ import { syncWranglerConfig } from 'durable-db/vite';
829
+
830
+ const { modified, changes, conflicts } = syncWranglerConfig({
831
+ projectRoot: process.cwd(),
832
+ databasesDir: 'src/databases', // the plugin's defaults
833
+ migrationsDir: 'migrations',
834
+ });
835
+ ```
836
+
837
+ It returns what changed (`addedBindings`, `removedBindings`, `newClasses`, `renamedClasses`, `movedMigrations`), the classes left for a hand-written `deleted_classes` (`deletedClasses`) and the renames it refused (`conflicts` — the plugin stops on them).
838
+
839
+ While a database file does not parse, nothing is written (a partial set of databases would read as databases removed).
724
840
 
725
841
  > ⚠️ Only `wrangler.jsonc` / `wrangler.json` are supported. If your project uses `wrangler.toml`, the plugin can't verify or patch it — it will print the required config and you add the TOML equivalent yourself.
726
842
 
@@ -750,11 +866,34 @@ The plugin transforms each `action()` definition into two things:
750
866
  The stub function:
751
867
  - Validates args with ArkType
752
868
  - Checks if we're already inside the same DO (via AsyncLocalStorage) for a fast direct-call path
753
- - Computes the instance key (`getTenantId()` or `"global"`) and routes it through `applyDevEpoch()` (dev-epoch suffix in dev, identity in production — see [Epoch System](#epoch-system))
869
+ - Computes the instance key (`getTenantId()` or `"global"`) and routes it through `applyDevEpoch(key, dbName)` (its database's dev-epoch suffix in dev, identity in production — see [Epoch System](#epoch-system))
754
870
  - Otherwise, resolves the DO instance via `env.BINDING.idFromName(instanceKey)` and calls `stub.rpc()`
755
871
 
756
872
  ---
757
873
 
874
+ ## Testing Actions
875
+
876
+ `durable-db/testing` runs actions against a real in-memory SQLite (Node's `node:sqlite`) in plain vitest — no worker pool, no Vite plugin:
877
+
878
+ ```ts
879
+ import { createTestDatabase } from 'durable-db/testing';
880
+ import { users } from '../src/databases/schema';
881
+ import { createUser } from '../src/databases/actions/createUser';
882
+ import { signUp } from '../src/routes/signUp';
883
+
884
+ const t = await createTestDatabase({ schema: { users }, tenantId: 'acme' });
885
+
886
+ await t.run(createUser, { name: 'Ann', email: 'ann@example.com' }); // validates args like production
887
+ await createUser({ name: 'Bo', email: 'bo@example.com' }); // a direct call runs here too
888
+ await signUp(request); // so does code that calls actions
889
+
890
+ t.destroy();
891
+ ```
892
+
893
+ While a test database is live, an action called directly — from a page, a procedure, a job under test — runs against the newest live test database created with every table of the action's database.
894
+
895
+ ---
896
+
758
897
  ## Outerbase Studio Integration
759
898
 
760
899
  [Outerbase Studio](https://github.com/outerbase/browsable-durable-object) provides a web UI and SQL endpoint for inspecting SQLite tables inside Durable Objects.
@@ -939,9 +1078,18 @@ After 3 consecutive failed migration attempts, PITR restore is skipped and the e
939
1078
  In development, migrations run against ephemeral state cached under `node_modules/.cache/durable-db/`. Use whichever matches your situation:
940
1079
 
941
1080
  - **Reset one tenant's data while keeping schema**: call `destroyDatabase()` from a route. This runs `ctx.storage.deleteAll()` on the current tenant's DO and re-runs migrations on the next call.
942
- - **Reset _every_ tenant's data for a database**: run `pnpm db reset` (or `pnpm db reset --database main`) — the dev server can keep running. Instance keys get a new `__dev_<epoch>` suffix, so every tenant rotates to a brand-new DO with empty SQLite on the next request. Add `--purge-local-storage` (dev server stopped) when you also want the orphaned instances' files deleted from `.wrangler/`.
1081
+ - **Reset _every_ tenant's data for one database**: run `pnpm db reset --database main` — the dev server can keep running. That database's instance keys get a new `__dev_<epoch>` suffix, so every tenant rotates to a brand-new DO with empty SQLite on the next request; the other databases keep their data.
1082
+ - **Reset every database**: `pnpm db reset`. Add `--purge-local-storage` (dev server stopped — the command refuses otherwise) when you also want the orphaned instances' files deleted from `.wrangler/`.
943
1083
  - **Drop everything and re-derive migrations from the schema**: `rm -rf node_modules/.cache/durable-db` and restart `pnpm dev`. The plugin regenerates dev migrations from the current schema.
944
1084
 
1085
+ ### "already exists" / "duplicate column name" in dev
1086
+
1087
+ A pending migration fails with `MigrationSchemaConflictError` when the storage already holds what it creates and the `__migrations` journal doesn't know it: migration files renamed or regenerated after the storage was created, or storage written by an older version. (The usual dev loop — `db push`, then `db generate` — is handled: see [Typical Workflow](#typical-workflow).) The error names the database; `db reset --database <name>` gives it fresh instances.
1088
+
1089
+ ### A column reads back as its own name
1090
+
1091
+ Queries quote identifiers with backticks. SQLite reads a double-quoted identifier that names no column as a string literal — a column missing from the database (a schema change not yet migrated) would select its own name and filter on a constant — while a backticked one fails with `no such column`.
1092
+
945
1093
  ### Snapshot corruption (`_snapshot.json`)
946
1094
 
947
1095
  The `_snapshot.json` file in each `migrations/<db>/` directory is the source of truth for what schema the migration history represents. If it's been hand-edited, merged badly, or lost:
@@ -1055,7 +1203,9 @@ src/
1055
1203
  plugins.ts # Kysely plugins (DrizzleDefaults, Schema, DateSerialize)
1056
1204
  types.ts # TypeScript type definitions
1057
1205
  migrations/ # Snapshot-based migration generation
1058
- snapshot.ts # Drizzle schema -> snapshot diffing
1206
+ snapshot.ts # Drizzle schema -> snapshot diffing (rename answers applied first)
1207
+ renames.ts # Rename questions: detection, --rename answers, create + drop
1208
+ risks.ts # What a change does to a table with rows (NOT NULL adds, drops)
1059
1209
  generator.ts # Migration file reading/writing
1060
1210
  registry.ts # Action registration and RPC dispatch
1061
1211
  vite/
@@ -7428,4 +7428,38 @@ ark.declare;
7428
7428
  //#region src/arktypeConfig.ts
7429
7429
  const type = scope({}, { jitless: true }).type;
7430
7430
  //#endregion
7431
- export { type as t };
7431
+ //#region src/db/actionArgs.ts
7432
+ /**
7433
+ * ArkType's `type`, for an action's `args` schema: jitless like
7434
+ * `../arktypeConfig` (eval-free for Workers), and with an optional key
7435
+ * accepting `undefined`.
7436
+ *
7437
+ * ArkType checks an optional key as TypeScript's `exactOptionalPropertyTypes`
7438
+ * would by default: `'photoKey?': 'string'` rejects `{ photoKey: undefined }`,
7439
+ * while the inferred `{ photoKey?: string }` accepts it under TypeScript's
7440
+ * default settings — so `addReview({ …, photoKey: maybeKey })` type-checks and
7441
+ * then fails at runtime. This scope turns ArkType's
7442
+ * `exactOptionalPropertyTypes` off: an optional key, at any depth, admits
7443
+ * `undefined`, and a required key stays required (`'note': 'string |
7444
+ * undefined'` must be present, as TypeScript says). The validator is a plain
7445
+ * object Type — `.props`, `.toJsonSchema()` and `.assert()` work as usual; in
7446
+ * JSON Schema the `undefined` an optional key admits is `{ not: {} }` (a JSON
7447
+ * document never holds it), so `'photoKey?': 'string'` is still a string.
7448
+ *
7449
+ * An `args` given as a ready `type(…)` keeps the rules of the scope that made
7450
+ * it.
7451
+ *
7452
+ * The action transform compiles `args` with this (it is the `type` that
7453
+ * `durable-db/registry` exports), for the RPC stub and the Durable Object
7454
+ * alike; the untransformed `action()` and the test harness use it too.
7455
+ */
7456
+ const actionArgsType = scope({}, {
7457
+ jitless: true,
7458
+ exactOptionalPropertyTypes: false,
7459
+ toJsonSchema: { fallback: { unit: (ctx) => {
7460
+ if (ctx.unit === void 0) return { not: {} };
7461
+ throw new Error(`${String(ctx.unit)} is not convertible to JSON Schema`);
7462
+ } } }
7463
+ }).type;
7464
+ //#endregion
7465
+ export { type as n, actionArgsType as t };
package/dist/cli/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as registerDbCommands } from "../cli-BUSZTS2D.js";
2
+ import { n as registerDbCommands } from "../cli-CVS0b2im.js";
3
3
  import { Command } from "commander";
4
4
  //#region src/cli/bin.ts
5
5
  const program = new Command();