durable-db 0.0.1

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 (46) hide show
  1. package/README.md +1052 -0
  2. package/dist/cli/bin.d.ts +1 -0
  3. package/dist/cli/bin.js +18 -0
  4. package/dist/cli/index.d.ts +330 -0
  5. package/dist/cli/index.js +9 -0
  6. package/dist/cli-Cr9686BF.js +630 -0
  7. package/dist/context/index.d.ts +2 -0
  8. package/dist/context/index.js +5 -0
  9. package/dist/context-BuIiIQ6K.js +103 -0
  10. package/dist/db/index.d.ts +3 -0
  11. package/dist/db/index.js +760 -0
  12. package/dist/debug-BZJbKybf.js +49 -0
  13. package/dist/defineDatabase-CONf4xFC.js +54 -0
  14. package/dist/defineDatabase-jBv90-Pk.d.ts +188 -0
  15. package/dist/generator-BUPP9scJ.js +180 -0
  16. package/dist/index-BFM5d0FP.d.ts +328 -0
  17. package/dist/index-CqVMaMYY.d.ts +65 -0
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.js +8 -0
  20. package/dist/migrations/generator.d.ts +101 -0
  21. package/dist/migrations/generator.js +5 -0
  22. package/dist/migrations/snapshot.d.ts +2 -0
  23. package/dist/migrations/snapshot.js +3 -0
  24. package/dist/parser-CbX54Flt.js +293 -0
  25. package/dist/protocol-g_plhPOY.js +35 -0
  26. package/dist/push-BgQ5cnfH.js +184 -0
  27. package/dist/push-BkkaslPd.js +8 -0
  28. package/dist/registry.d.ts +28 -0
  29. package/dist/registry.js +72 -0
  30. package/dist/schema-BOtrGnzM.js +8 -0
  31. package/dist/schema-CpzTOfZ6.d.ts +6 -0
  32. package/dist/schema.d.ts +2 -0
  33. package/dist/schema.js +3 -0
  34. package/dist/snapshot-C162qYoA.d.ts +125 -0
  35. package/dist/snapshot-D170nL7i.js +93 -0
  36. package/dist/state-BCcvNN-M.js +5 -0
  37. package/dist/state-FOEjpgJ6.js +203 -0
  38. package/dist/transport/protocol.d.ts +27 -0
  39. package/dist/transport/protocol.js +3 -0
  40. package/dist/transport/websocket.d.ts +31 -0
  41. package/dist/transport/websocket.js +3 -0
  42. package/dist/vite/durableDb.d.ts +20 -0
  43. package/dist/vite/durableDb.js +933 -0
  44. package/dist/websocket-Dx1fqwnF.js +104 -0
  45. package/package.json +114 -0
  46. package/virtual.d.ts +15 -0
package/README.md ADDED
@@ -0,0 +1,1052 @@
1
+ # durable-db
2
+
3
+ Zero-configuration database abstraction for Cloudflare Durable Objects with SQLite.
4
+
5
+ Define your schema with [Drizzle](https://orm.drizzle.team/), query with [Kysely](https://kysely.dev/), validate with [ArkType](https://arktype.io/) -- and let the Vite plugin handle the rest: Durable Object class generation, RPC stubs, migration embedding, and wrangler config patching.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Quick Start](#quick-start)
10
+ - [Defining a Database](#defining-a-database)
11
+ - [Writing Actions](#writing-actions)
12
+ - [Calling Actions from Your Worker](#calling-actions-from-your-worker)
13
+ - [CLI](#cli)
14
+ - [push](#db-push)
15
+ - [generate](#db-generate)
16
+ - [status](#db-status)
17
+ - [reset](#db-reset)
18
+ - [validate](#db-validate)
19
+ - [Migration System](#migration-system)
20
+ - [Dev Migrations](#dev-migrations)
21
+ - [Production Migrations](#production-migrations)
22
+ - [Breakpoints](#breakpoints)
23
+ - [Epoch System](#epoch-system)
24
+ - [Typical Workflow](#typical-workflow)
25
+ - [Vite Plugin](#vite-plugin)
26
+ - [Outerbase Studio Integration](#outerbase-studio-integration)
27
+ - [Instance Strategies](#instance-strategies)
28
+ - [Action-to-Action Calls](#action-to-action-calls)
29
+ - [PITR Safety](#pitr-safety)
30
+ - [Recovery Workflows](#recovery-workflows)
31
+ - [Architecture](#architecture)
32
+ - [Development](#development)
33
+
34
+ ---
35
+
36
+ ## Quick Start
37
+
38
+ ### 1. Install
39
+
40
+ ```bash
41
+ pnpm add durable-db
42
+ ```
43
+
44
+ ### 2. Define your schema
45
+
46
+ ```ts
47
+ // src/databases/schema.ts
48
+ import { table, text, integer } from 'durable-db/schema';
49
+
50
+ export const users = table('users', {
51
+ id: text().primaryKey(),
52
+ name: text().notNull(),
53
+ email: text().notNull(),
54
+ createdAt: integer({ mode: 'timestamp' }).notNull(),
55
+ });
56
+ ```
57
+
58
+ Column names are derived from JS property keys and auto-converted to snake_case (e.g. `createdAt` → `created_at`). Table names passed to `table()` are also auto-snake_cased.
59
+
60
+ **Date columns**: use `integer({ mode: 'timestamp' })` and pass `Date` values — they round-trip as `Date` objects automatically. Plain `text()` columns always round-trip verbatim: if you store an ISO string (`new Date().toISOString()`), you get the exact same string back, never a `Date`.
61
+
62
+ > ⚠️ All tables referenced in `defineDatabase({ schema })` must be **exported from the schema module** and imported into the database file. Tables defined inline in the database file (or not exported) cannot be loaded by the migration CLI — `db push`/`db generate` will fail with an explicit error rather than silently generating empty migrations.
63
+
64
+ ### 3. Define your database
65
+
66
+ ```ts
67
+ // src/databases/main.ts
68
+ import { defineDatabase } from 'durable-db';
69
+ import { users } from './schema';
70
+
71
+ export const { action } = defineDatabase({
72
+ schema: { users },
73
+ });
74
+ ```
75
+
76
+ ### 4. Write actions
77
+
78
+ ```ts
79
+ // src/databases/actions/createUser.ts
80
+ import { action } from '../main';
81
+
82
+ export const createUser = action({
83
+ args: {
84
+ name: 'string',
85
+ email: 'string.email',
86
+ },
87
+ handler: async (db, args) => {
88
+ return db
89
+ .insertInto('users')
90
+ .values({
91
+ id: crypto.randomUUID(),
92
+ name: args.name,
93
+ email: args.email,
94
+ createdAt: new Date(),
95
+ })
96
+ .returningAll()
97
+ .executeTakeFirstOrThrow();
98
+ },
99
+ });
100
+ ```
101
+
102
+ ### 5. Add the Vite plugin
103
+
104
+ ```ts
105
+ // vite.config.ts
106
+ import { defineConfig } from 'vite';
107
+ import { cloudflare } from '@cloudflare/vite-plugin';
108
+ import { durableDb } from 'durable-db/vite';
109
+
110
+ export default defineConfig({
111
+ plugins: [
112
+ durableDb(),
113
+ cloudflare(),
114
+ ],
115
+ });
116
+ ```
117
+
118
+ ### 6. Use in your worker
119
+
120
+ ```ts
121
+ // src/worker.ts
122
+ import { setTenantIdResolver } from 'durable-db';
123
+ import { createUser } from './databases/actions/createUser';
124
+
125
+ // In a real app, resolve from authentication/session
126
+ setTenantIdResolver(() => 'my-tenant');
127
+
128
+ // Export the generated Durable Object classes
129
+ export * from 'virtual:durable-db/__durableObjects';
130
+
131
+ export default {
132
+ async fetch(request: Request, env: any) {
133
+ const user = await createUser({ name: 'Alice', email: 'alice@example.com' });
134
+ return Response.json(user);
135
+ },
136
+ };
137
+ ```
138
+
139
+ For TypeScript support, add `durable-db/virtual` to your `tsconfig.json`:
140
+
141
+ ```json
142
+ {
143
+ "compilerOptions": {
144
+ "types": ["durable-db/virtual"]
145
+ }
146
+ }
147
+ ```
148
+
149
+ ### 7. Push schema and run
150
+
151
+ ```bash
152
+ db push # Create dev migrations from your schema
153
+ pnpm dev # Start the dev server
154
+ ```
155
+
156
+ ---
157
+
158
+ ## Defining a Database
159
+
160
+ Call `defineDatabase()` with a config object. The Vite plugin parses this at build time to generate a Durable Object class.
161
+
162
+ ```ts
163
+ import { defineDatabase } from 'durable-db';
164
+ import { users, posts } from './schema';
165
+
166
+ export const { action } = defineDatabase({
167
+ schema: { users, posts },
168
+ instance: 'per-tenant', // or 'global' (default: 'per-tenant')
169
+ transport: 'rpc', // or 'websocket' (default: 'rpc')
170
+ browsable: 'development', // Outerbase Studio integration (default: false)
171
+ });
172
+ ```
173
+
174
+ The destructured `action` function is your factory for creating database actions.
175
+
176
+ ### Config Options
177
+
178
+ | Option | Type | Default | Description |
179
+ |--------|------|---------|-------------|
180
+ | `schema` | `object` | `{}` | Drizzle schema tables |
181
+ | `instance` | `'per-tenant' \| 'global'` | `'per-tenant'` | Instance strategy (see [Instance Strategies](#instance-strategies)) |
182
+ | `transport` | `'rpc' \| 'websocket'` | `'rpc'` | Transport for action stubs. WebSocket uses Cloudflare's 20:1 message billing ratio for cheaper high-volume calls |
183
+ | `browsable` | `boolean \| 'development'` | `false` | Enable Outerbase SQL browsing (see [Outerbase Studio](#outerbase-studio-integration)) |
184
+
185
+ ---
186
+
187
+ ## Writing Actions
188
+
189
+ Actions are type-safe database operations with runtime argument validation.
190
+
191
+ ```ts
192
+ import { action } from '../main';
193
+
194
+ export const getUser = action({
195
+ args: { userId: 'string' },
196
+ handler: async (db, args, ctx) => {
197
+ return db
198
+ .selectFrom('users')
199
+ .selectAll()
200
+ .where('id', '=', args.userId)
201
+ .executeTakeFirst();
202
+ },
203
+ });
204
+ ```
205
+
206
+ ### The `args` object
207
+
208
+ Uses [ArkType](https://arktype.io/) syntax for runtime validation:
209
+
210
+ ```ts
211
+ args: { name: 'string' } // Required string
212
+ args: { email: 'string.email' } // Email validation
213
+ args: { limit: 'number > 0' } // Positive number
214
+ args: { offset: 'number >= 0' } // Non-negative number
215
+ args: { tags: 'string[]' } // Array of strings
216
+ args: { name: 'string', age: 'number?' } // Optional field
217
+ args: { role: "'admin' | 'user'" } // Literal union
218
+ ```
219
+
220
+ ### The `handler` function
221
+
222
+ Receives three arguments:
223
+
224
+ | Argument | Type | Description |
225
+ |----------|------|-------------|
226
+ | `db` | `Kysely<Schema>` | Type-safe Kysely query builder bound to your Drizzle schema |
227
+ | `args` | inferred from `args` | Validated arguments (ArkType ensures correctness at runtime) |
228
+ | `ctx` | `ActionContext` | Context with `env` (Cloudflare bindings) and `instanceKey` |
229
+
230
+ ### File organization
231
+
232
+ Actions can live inline in the database file or in separate files:
233
+
234
+ ```
235
+ src/databases/
236
+ main.ts # defineDatabase() call (may also contain action() definitions)
237
+ schema.ts # Drizzle schema (excluded from action discovery)
238
+ actions/
239
+ createUser.ts # import { action } from '../main'
240
+ getUser.ts
241
+ listUsers.ts
242
+ ```
243
+
244
+ Both styles are fully supported: the Vite plugin transforms `action()` definitions in the database file itself exactly like those in separate files — they're registered with the DO and rewritten into RPC stubs.
245
+
246
+ Files named `schema.ts`, `_*.ts`, and `.d.ts` are excluded from action discovery.
247
+
248
+ ---
249
+
250
+ ## Calling Actions from Your Worker
251
+
252
+ For `per-tenant` databases, actions need a tenant ID to know which Durable Object instance to use. Call `setTenantIdResolver()` once at startup to provide it:
253
+
254
+ ```ts
255
+ import { setTenantIdResolver } from 'durable-db';
256
+ import { createUser } from './databases/actions/createUser';
257
+ import { listUsers } from './databases/actions/listUsers';
258
+
259
+ // In a real app, resolve from authentication/session
260
+ setTenantIdResolver(() => 'example-tenant');
261
+
262
+ export default {
263
+ async fetch(request: Request, env: any) {
264
+ if (request.method === 'POST') {
265
+ const body = await request.json();
266
+ const user = await createUser({ name: body.name, email: body.email });
267
+ return Response.json(user);
268
+ }
269
+
270
+ const users = await listUsers({ limit: 10, offset: 0 });
271
+ return Response.json(users);
272
+ },
273
+ };
274
+ ```
275
+
276
+ ### Framework integration
277
+
278
+ If your framework has request-scoped context (e.g. RWSDK's `getRequestInfo()`), use the resolver to bridge the two:
279
+
280
+ ```ts
281
+ import { setTenantIdResolver } from 'durable-db';
282
+ import { getRequestInfo } from 'rwsdk/worker';
283
+
284
+ setTenantIdResolver(() => getRequestInfo().ctx.session!.shop);
285
+ ```
286
+
287
+ The resolver is called at the moment a database operation needs the tenant ID — by which point request middleware (auth, session, etc.) has already completed.
288
+
289
+ ### How it works
290
+
291
+ Behind the scenes, each action call is an RPC call to the correct Durable Object instance. The Vite plugin generates stubs that handle instance routing, argument validation, and DO communication transparently.
292
+
293
+ ---
294
+
295
+ ## CLI
296
+
297
+ The `db` CLI manages your migration lifecycle. All commands share these options:
298
+
299
+ | Flag | Default | Description |
300
+ |------|---------|-------------|
301
+ | `-d, --databases-dir <dir>` | `src/databases` | Directory containing database definitions |
302
+ | `-v, --verbose` | `false` | Show detailed output |
303
+
304
+ **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:
305
+
306
+ - the tables are defined inline in the database file instead of a schema module
307
+ - the schema import can't be resolved
308
+ - the schema module fails to build
309
+ - any declared table is missing from the schema module's exports
310
+
311
+ A database with no `schema` declared at all is still skipped silently — that's a valid (if unusual) configuration.
312
+
313
+ ### `db push`
314
+
315
+ Push schema changes to dev migrations. This is the command you run most often during development.
316
+
317
+ ```bash
318
+ db push
319
+ db push --verbose
320
+ db push --databases-dir ./src/db
321
+ ```
322
+
323
+ **What it does:**
324
+
325
+ 1. Discovers all database files in your databases directory
326
+ 2. Parses each file for `defineDatabase()` calls
327
+ 3. For each database:
328
+ - Loads the current production snapshot (`_snapshot.json` in the migrations directory)
329
+ - Generates a fresh snapshot from your current Drizzle schema
330
+ - Diffs the two snapshots to produce SQL migration statements
331
+ - 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
+ - If the same content hash already exists, nothing is rewritten — the DO recognizes the migration name and skips it
333
+
334
+ **Output example:**
335
+
336
+ ```
337
+ ✓ main: dev_a1b2c3d4 (3 statements)
338
+ · analytics: no changes
339
+ ```
340
+
341
+ When nothing changed anywhere:
342
+
343
+ ```
344
+ · main: no changes
345
+ · analytics: no changes
346
+
347
+ All databases are up to date.
348
+ ```
349
+
350
+ 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
+
352
+ ### `db generate`
353
+
354
+ Generate a production migration from your current schema changes. Run this when you're ready to commit.
355
+
356
+ ```bash
357
+ db generate
358
+ db generate add_user_bio
359
+ db generate --database main
360
+ db generate --database main add_posts_table
361
+ ```
362
+
363
+ **Arguments:**
364
+
365
+ | Argument | Description |
366
+ |----------|-------------|
367
+ | `[name]` | Optional suffix appended to the timestamp-based migration name |
368
+
369
+ **Extra flags:**
370
+
371
+ | Flag | Description |
372
+ |------|-------------|
373
+ | `--database <db>` | Only generate for this specific database |
374
+
375
+ **What it does:**
376
+
377
+ 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)
382
+
383
+ **Output example:**
384
+
385
+ ```
386
+ ✓ main: 20240315123045_add_user_bio
387
+ → migrations/main/20240315123045_add_user_bio.sql
388
+ 2 statement(s)
389
+ ```
390
+
391
+ **Migration file naming:**
392
+
393
+ - Without name argument: `20240315123045.sql`
394
+ - With name argument: `20240315123045_add_user_bio.sql`
395
+
396
+ ### `db status`
397
+
398
+ Show the current migration status for all databases without making any changes.
399
+
400
+ ```bash
401
+ db status
402
+ db status --verbose
403
+ ```
404
+
405
+ **Output example:**
406
+
407
+ ```
408
+ Dev Epoch: m1a2b3c
409
+
410
+ 📦 main
411
+ Production migrations: 3
412
+ Dev migrations: 1
413
+ 📝 Uncommitted changes: 1 statement(s)
414
+ Pending SQL:
415
+ - ALTER TABLE users ADD COLUMN bio TEXT
416
+ Last push: 2024-03-15T10:30:00.000Z
417
+
418
+ 📦 analytics
419
+ Production migrations: 1
420
+ Dev migrations: 0
421
+ ✓ Schema is up to date
422
+ ```
423
+
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.
425
+
426
+ ### `db reset`
427
+
428
+ Reset dev state and create fresh database instances via an epoch bump.
429
+
430
+ ```bash
431
+ db reset
432
+ db reset --keep-epoch
433
+ db reset --database main
434
+ db reset --database main --keep-epoch
435
+ db reset --purge-local-storage
436
+ ```
437
+
438
+ **Extra flags:**
439
+
440
+ | Flag | Description |
441
+ |------|-------------|
442
+ | `--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) |
445
+
446
+ **Two modes:**
447
+
448
+ | Mode | What happens |
449
+ |------|-------------|
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. |
451
+ | **Keep epoch** (`--keep-epoch`) | Only clears dev migrations and snapshots. Existing DO instances keep running with their current data. |
452
+
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.
454
+
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.
456
+
457
+ **Output example:**
458
+
459
+ ```
460
+ ✓ New epoch: n4d5e6f — databases start fresh on the next request
461
+ ✓ Reset databases: main, analytics
462
+ ```
463
+
464
+ ### `db validate`
465
+
466
+ Dry-run all migrations against a local in-memory SQLite database to catch errors before deployment.
467
+
468
+ ```bash
469
+ db validate
470
+ db validate --database main
471
+ db validate --no-dev
472
+ db validate --verbose
473
+ ```
474
+
475
+ **Extra flags:**
476
+
477
+ | Flag | Description |
478
+ |------|-------------|
479
+ | `--database <db>` | Only validate this specific database |
480
+ | `--no-dev` | Skip dev migrations, only validate production migrations |
481
+
482
+ **What it does:**
483
+
484
+ 1. Creates an in-memory SQLite database using `libsql`
485
+ 2. Applies all migrations sequentially (production + dev, unless `--no-dev`)
486
+ 3. Builds the expected schema separately from the Drizzle definition
487
+ 4. Compares the migrated schema against the expected schema to detect drift
488
+ 5. Reports SQL errors, foreign key violations, or schema mismatches
489
+
490
+ **Output example (success):**
491
+
492
+ ```
493
+ ✓ main: 5 migration(s) (includes dev migrations)
494
+ Schema matches ✓
495
+ ```
496
+
497
+ **Output example (failure):**
498
+
499
+ ```
500
+ ✗ main: 5 migration(s)
501
+ ✗ 20240315123045_bad[0]: near "INVALID": syntax error
502
+ ```
503
+
504
+ Schema drift (migrations ran cleanly but produce a different schema than your Drizzle definition) is reported as:
505
+
506
+ ```
507
+ ⚠ Schema drift detected:
508
+ [missing] table users: column bio
509
+ ```
510
+
511
+ **Exit codes:**
512
+
513
+ | Code | Meaning |
514
+ |------|---------|
515
+ | `0` | All validations passed |
516
+ | `1` | Validation errors found |
517
+
518
+ ### Embedding in your own CLI
519
+
520
+ The commands are composable Commander commands, so a host CLI can re-use them:
521
+
522
+ ```ts
523
+ import { Command } from 'commander';
524
+ import { createDbCommand, registerDbCommands } from 'durable-db/cli';
525
+
526
+ // As a nested `db` group: `mycli db push`
527
+ program.addCommand(createDbCommand());
528
+
529
+ // Or flat on your own command: `mycli push`
530
+ // (this is exactly what the standalone `db` binary does)
531
+ registerDbCommands(program);
532
+ ```
533
+
534
+ ### Programmatic API
535
+
536
+ All CLI functions are also available for integration into other tools:
537
+
538
+ ```ts
539
+ import * as db from 'durable-db/cli';
540
+
541
+ const pushResults = await db.push({ verbose: true });
542
+ const statusResults = await db.status();
543
+ const generateResults = await db.generate({}, { name: 'add_bio' });
544
+ const resetResult = await db.reset({}, { keepEpoch: false, purgeLocalStorage: false });
545
+ const validateResults = await db.validate({ noDev: false });
546
+ ```
547
+
548
+ ---
549
+
550
+ ## Migration System
551
+
552
+ ### Dev Migrations
553
+
554
+ Dev migrations are ephemeral migration files used during development for fast iteration.
555
+
556
+ - **Created by**: `db push`
557
+ - **Location**: `node_modules/.cache/durable-db/databases/<dbName>/migrations/`
558
+ - **Naming**: Content-hash based -- a single squashed `dev_<hash>.sql` that is replaced (not appended to) on every push with changes. The deterministic name lets the DO skip migrations it has already applied
559
+ - **Lifecycle**: Cleared when you run `db generate` (consolidated into production) or `db reset`
560
+ - **Never committed to git**
561
+
562
+ The Vite plugin automatically loads dev migrations in dev mode and appends them after production migrations when generating the DO class.
563
+
564
+ ### Production Migrations
565
+
566
+ Production migrations are the canonical migrations committed to your repository.
567
+
568
+ - **Created by**: `db generate`
569
+ - **Location**: The `migrationsDir` configured in the Vite plugin (e.g. `migrations/main/`)
570
+ - **Naming**: Timestamp-based -- `20240315123045.sql` or `20240315123045_description.sql`
571
+ - **Lifecycle**: Permanent, committed to git, deployed to production
572
+ - **Snapshot**: Each `generate` also updates `_snapshot.json` in the migrations directory (tracks schema state with `id`/`prevId` chain)
573
+
574
+ ### Breakpoints
575
+
576
+ Long migrations can be split into chunks using the `--> breakpoint` marker:
577
+
578
+ ```sql
579
+ CREATE TABLE users (id TEXT PRIMARY KEY, name TEXT NOT NULL);
580
+
581
+ --> breakpoint
582
+
583
+ CREATE INDEX idx_users_name ON users(name);
584
+
585
+ --> breakpoint
586
+
587
+ CREATE TABLE posts (id TEXT PRIMARY KEY, author_id TEXT REFERENCES users(id));
588
+ ```
589
+
590
+ 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
+
592
+ ### Epoch System
593
+
594
+ In development, each database instance key gets an epoch suffix to enable clean resets:
595
+
596
+ | Environment | Instance key |
597
+ |-------------|-------------|
598
+ | Production | `example-tenant` |
599
+ | Development | `example-tenant__dev_m1a2b3c` |
600
+
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.
602
+
603
+ The epoch is a base36-encoded timestamp stored in `node_modules/.cache/durable-db/state.json`.
604
+
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.
606
+
607
+ ### Dev State Structure
608
+
609
+ ```
610
+ node_modules/.cache/durable-db/
611
+ state.json # Global state (epoch, per-db push info)
612
+ databases/
613
+ main/
614
+ _snapshot.json # Dev snapshot (schema state)
615
+ migrations/
616
+ dev_a1b2c3d4.sql # Single squashed dev migration (content-hash name)
617
+ analytics/
618
+ _snapshot.json
619
+ migrations/
620
+ dev_e5f6a7b8.sql
621
+ ```
622
+
623
+ The `state.json` file tracks:
624
+
625
+ ```json
626
+ {
627
+ "epoch": "m1a2b3c",
628
+ "databases": {
629
+ "main": {
630
+ "prodSnapshotHash": "abc123...",
631
+ "lastPush": "2024-03-15T10:30:00.000Z",
632
+ "devMigrationCount": 2
633
+ }
634
+ }
635
+ }
636
+ ```
637
+
638
+ ### Typical Workflow
639
+
640
+ **During development:**
641
+
642
+ ```bash
643
+ # 1. Edit your Drizzle schema
644
+ # 2. Push changes to dev migrations
645
+ db push
646
+
647
+ # 3. Run the dev server -- migrations apply automatically on DO access
648
+ pnpm dev
649
+
650
+ # 4. Iterate: edit schema -> push -> refresh browser
651
+ # 5. If you need a clean slate (works while the dev server is running):
652
+ db reset
653
+ ```
654
+
655
+ **Ready to deploy:**
656
+
657
+ ```bash
658
+ # 1. Generate a production migration
659
+ db generate add_user_profiles
660
+
661
+ # 2. Validate before deploying
662
+ db validate
663
+
664
+ # 3. Commit the migration file and updated snapshot
665
+ git add migrations/
666
+ git commit -m "Add user profiles migration"
667
+
668
+ # 4. Deploy
669
+ ```
670
+
671
+ **Team collaboration:**
672
+
673
+ `db push` always diffs against the *current* production snapshot, so after pulling a teammate's migration your next push rebuilds the squashed dev migration on top of the new baseline automatically. If your local DO instances already applied an outdated dev migration, run `db reset` to rotate to fresh instances — `db status` warns with `⚠️ Production snapshot changed` when this applies.
674
+
675
+ ---
676
+
677
+ ## Vite Plugin
678
+
679
+ ```ts
680
+ import { durableDb } from 'durable-db/vite';
681
+
682
+ durableDb({
683
+ databasesDir: 'src/databases', // Where database files live
684
+ migrationsDir: 'migrations', // Where production migrations live
685
+ });
686
+ ```
687
+
688
+ ### Plugin Options
689
+
690
+ | Option | Type | Default | Description |
691
+ |--------|------|---------|-------------|
692
+ | `databasesDir` | `string` | `'src/databases'` | Directory containing database definition files |
693
+ | `migrationsDir` | `string` | `'migrations'` | Directory for production migrations, relative to project root. Each database gets a subdirectory (e.g. `migrations/main/`) |
694
+ | `contextImport` | `string` | `'durable-db/context'` | Import path for the context module (for framework integrations) |
695
+ | `registryImport` | `string` | `'durable-db/registry'` | Import path for the action registry module (for framework integrations) |
696
+
697
+ ### What the plugin does
698
+
699
+ 1. **Discovery**: Finds all `defineDatabase()` files in your databases directory (excludes `schema.ts`, `_*.ts`, `.d.ts`)
700
+ 2. **AST Parsing**: Uses Babel to extract database config and action definitions (no regexes)
701
+ 3. **Migration Loading**: Loads production migrations from disk; in dev mode also loads dev migrations from cache
702
+ 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)
703
+ 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
704
+ 6. **Wrangler Patching**: Automatically updates `wrangler.jsonc` with Durable Object bindings and SQLite migration entries
705
+ 7. **HMR**: Watches database files and invalidates the virtual module on change
706
+
707
+ ### Generated Class Naming
708
+
709
+ For each `defineDatabase()` call, the plugin generates a class based on the filename:
710
+
711
+ | Filename | Class Name | Binding Name |
712
+ |----------|-----------|-------------|
713
+ | `main.ts` | `MainDatabaseDO` | `MAIN_DATABASE_DO` |
714
+ | `analytics.ts` | `AnalyticsDatabaseDO` | `ANALYTICS_DATABASE_DO` |
715
+ | `user-data.ts` | `UserDataDatabaseDO` | `USER_DATA_DATABASE_DO` |
716
+
717
+ Export the generated classes from your worker entry point:
718
+
719
+ ```ts
720
+ export * from 'virtual:durable-db/__durableObjects';
721
+ ```
722
+
723
+ ### Action Transformation
724
+
725
+ The plugin transforms each `action()` definition into two things:
726
+
727
+ 1. **A registry registration** (handler + ArkType validator) -- runs inside the DO
728
+ 2. **An RPC stub function** (exported under the same name) -- runs in your worker
729
+
730
+ The stub function:
731
+ - Validates args with ArkType
732
+ - Checks if we're already inside the same DO (via AsyncLocalStorage) for a fast direct-call path
733
+ - 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))
734
+ - Otherwise, resolves the DO instance via `env.BINDING.idFromName(instanceKey)` and calls `stub.rpc()`
735
+
736
+ ---
737
+
738
+ ## Outerbase Studio Integration
739
+
740
+ [Outerbase Studio](https://github.com/outerbase/browsable-durable-object) provides a web UI and SQL endpoint for inspecting SQLite tables inside Durable Objects.
741
+
742
+ ### Configuration
743
+
744
+ Add `browsable` to your `defineDatabase()` config:
745
+
746
+ ```ts
747
+ export const { action } = defineDatabase({
748
+ schema: { users, posts },
749
+ browsable: 'development', // Enable in dev mode only
750
+ });
751
+ ```
752
+
753
+ ### Options
754
+
755
+ | Value | Behavior |
756
+ |-------|----------|
757
+ | `false` | Disabled (default) |
758
+ | `true` | Always enabled (dev and production) |
759
+ | `'development'` | Enabled only when running `vite dev` / `vite serve` |
760
+
761
+ ### How it works
762
+
763
+ When `browsable` is enabled, the Vite plugin wraps the generated Durable Object class with Outerbase's `Browsable()` decorator. This adds:
764
+
765
+ - A `fetch()` handler that serves `/query/raw` for direct SQL access
766
+ - A `__studio()` RPC method used by the Outerbase Studio web UI
767
+
768
+ The `'development'` value is resolved at build time: the Vite plugin checks `config.command === 'serve'` and only applies the decorator when running in dev mode.
769
+
770
+ Migrations are guaranteed to run before any browsable request — the generated class overrides both `fetch()` and `__studio()` to call `ensureMigrations()` first.
771
+
772
+ ### Adding the Studio UI
773
+
774
+ To serve the Outerbase Studio web interface, add a route in your worker that calls the `studio()` helper:
775
+
776
+ ```ts
777
+ import { studio } from 'durable-db/db';
778
+
779
+ export default {
780
+ async fetch(request: Request, env: any) {
781
+ const url = new URL(request.url);
782
+
783
+ if (url.pathname === '/studio') {
784
+ return studio(request, env.MAIN_DATABASE_DO);
785
+ }
786
+
787
+ // ... rest of your routes
788
+ },
789
+ };
790
+ ```
791
+
792
+ Then visit `/studio` in your browser. You'll be prompted to enter a DO instance name (e.g. your tenant ID), and Outerbase Studio will open with full SQL access to that instance.
793
+
794
+ ### Querying a Durable Object directly
795
+
796
+ You can also query a DO's SQL endpoint directly without the Studio UI:
797
+
798
+ ```bash
799
+ curl -X POST http://your-do-endpoint/query/raw \
800
+ -H 'Content-Type: application/json' \
801
+ -d '{"sql": "SELECT * FROM users LIMIT 10"}'
802
+ ```
803
+
804
+ ### Security
805
+
806
+ The browsable endpoint has **no built-in authentication**. For production use (`browsable: true`), add your own authentication middleware or restrict access at the network level.
807
+
808
+ Using `browsable: 'development'` is recommended -- it enables the endpoint only during local development and excludes it from production builds entirely.
809
+
810
+ ---
811
+
812
+ ## Instance Strategies
813
+
814
+ ### `per-tenant` (default)
815
+
816
+ Each tenant gets its own Durable Object instance, keyed by the tenant ID provided via `setTenantIdResolver()`.
817
+
818
+ ```ts
819
+ defineDatabase({
820
+ schema: { users },
821
+ instance: 'per-tenant',
822
+ });
823
+ ```
824
+
825
+ ### `global`
826
+
827
+ A single shared Durable Object instance for all requests, keyed by the string `'global'`.
828
+
829
+ ```ts
830
+ defineDatabase({
831
+ schema: { settings },
832
+ instance: 'global',
833
+ });
834
+ ```
835
+
836
+ ---
837
+
838
+ ## Action-to-Action Calls
839
+
840
+ Actions can call other actions. The Vite plugin detects these calls at build time and routes them correctly.
841
+
842
+ ```ts
843
+ // actions/createUser.ts
844
+ import { action } from '../main';
845
+ import { getUserByEmail } from './getUserByEmail';
846
+
847
+ export const createUser = action({
848
+ args: { name: 'string', email: 'string.email' },
849
+ handler: async (db, args) => {
850
+ // This calls another action in the same database
851
+ const existing = await getUserByEmail({ email: args.email });
852
+ if (existing) throw new Error('User already exists');
853
+
854
+ return db.insertInto('users').values({
855
+ id: crypto.randomUUID(),
856
+ name: args.name,
857
+ email: args.email,
858
+ createdAt: new Date(),
859
+ }).returningAll().executeTakeFirstOrThrow();
860
+ },
861
+ });
862
+ ```
863
+
864
+ ### Routing behavior
865
+
866
+ - **Same database**: The call uses a direct fast path via AsyncLocalStorage (no RPC overhead). The registry detects that we're already inside the target DO and calls the handler directly.
867
+ - **Cross database**: The call routes through RPC to the other database's Durable Object, using the appropriate instance key based on the target database's strategy.
868
+
869
+ ---
870
+
871
+ ## PITR Safety
872
+
873
+ On Cloudflare with Point-in-Time Recovery (PITR) enabled, migrations are protected with automatic snapshots.
874
+
875
+ ### How it works
876
+
877
+ 1. Before running migrations, the DO increments a retry counter and takes a PITR bookmark
878
+ 2. Migrations are applied (this is the second write, after the counter increment)
879
+ 3. On success: the retry counter is reset to 0
880
+ 4. On failure: the DO schedules a restore to the pre-migration bookmark and aborts
881
+ 5. On next access, the DO restarts with the counter already incremented (the counter write was before the bookmark)
882
+ 6. After 3 consecutive failures, PITR restore is skipped and the error propagates so the developer can fix the migration and redeploy
883
+
884
+ This prevents broken migrations from permanently corrupting data while giving developers a clear signal to fix the issue.
885
+
886
+ ### Diagnostic methods
887
+
888
+ The `SqliteDurableObject` base class provides methods for inspecting migration state:
889
+
890
+ - `getMigrationAttempts()` -- Returns `{ attemptCount, lastAttemptAt, lastError }`
891
+ - `getMigrationBookmark()` -- Returns the current PITR bookmark string, or `null` if PITR is unavailable
892
+ - `restoreToBookmark(bookmark)` -- Manually trigger a PITR restore
893
+
894
+ ---
895
+
896
+ ## Recovery Workflows
897
+
898
+ This section covers what to do when things go wrong. The goal is to give you a clear playbook for the common failure modes instead of guessing.
899
+
900
+ ### Migration keeps failing past the PITR cap
901
+
902
+ After 3 consecutive failed migration attempts, PITR restore is skipped and the error surfaces on every request. The DO will log:
903
+
904
+ ```
905
+ [database] Migration has failed 3 times. PITR restore disabled -- fix the migration and redeploy.
906
+ ```
907
+
908
+ **Do this:**
909
+
910
+ 1. Inspect current state with `getMigrationStatus()` on the DO -- it returns `{ attempts, pending, applied, pitrAvailable, pitrAttemptsRemaining }`, so you can see exactly which migration is stuck and how many PITR retries are left. (`getMigrationAttempts()` still exists if you only need the attempts counter.)
911
+ 2. Fix the offending `.sql` file in `migrations/<db>/`. Typical culprits: non-nullable column added without a default, a `DROP COLUMN` on a table with data, an index name collision.
912
+ 3. Redeploy. The next request will attempt the (now fixed) migration against the pre-migration state -- no manual reset needed.
913
+ 4. If you're certain the DO is already in a bad state (e.g. a migration was half-applied before the bookmark logic landed), call `restoreToBookmark(bookmark)` manually from a worker route with a known-good bookmark, then redeploy.
914
+
915
+ **Don't** try to delete or rewrite a migration that's already been applied in production -- it'll be skipped on machines that already ran it and break machines that haven't. Always forward-fix with a new migration.
916
+
917
+ ### Local dev: start from scratch
918
+
919
+ In development, migrations run against ephemeral state cached under `node_modules/.cache/durable-db/`. Use whichever matches your situation:
920
+
921
+ - **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.
922
+ - **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/`.
923
+ - **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.
924
+
925
+ ### Snapshot corruption (`_snapshot.json`)
926
+
927
+ 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:
928
+
929
+ 1. `pnpm db validate` -- this will compare your live schema against what the snapshot claims and flag drift.
930
+ 2. If only the snapshot is missing but the `.sql` files are correct, delete `_snapshot.json` and run `pnpm db generate`. It will reconstruct the snapshot by replaying migration history.
931
+ 3. If both `_snapshot.json` and an SQL file are out of sync: check `git log -- migrations/<db>/` for the last known-good revision and restore from there. Never regenerate by hand -- let `db generate` produce the diff.
932
+
933
+ ### "Action not registered" / "Missing binding" at runtime
934
+
935
+ These errors now include the list of available actions/bindings so you can see what _is_ wired up. Typical causes:
936
+
937
+ - **Action not registered**: the action file didn't match the Vite plugin's discovery rules (see the [Vite Plugin](#vite-plugin) section). Files named `schema.ts`, `_*.ts`, or `*.d.ts` are excluded.
938
+ - **Missing binding**: the target database `.ts` file isn't in `databasesDir`, or the wrangler config wasn't patched (check `wrangler.jsonc` for a `durable_objects.bindings` entry). A full Vite restart regenerates bindings.
939
+
940
+ ### WebSocket transport hangs
941
+
942
+ Pending requests time out after 30s by default and reject with `WebSocket request '<action>' timed out after 30000ms`. If you're seeing timeouts:
943
+
944
+ - Confirm the target DO's action handler actually returns (look for unawaited promises or an uncaught exception in logs).
945
+ - If the action is legitimately slow, pass `new WebSocketTransport(stub, { requestTimeoutMs: 60_000 })` when constructing manually, or switch that database to `transport: 'rpc'` which has no intrinsic timeout beyond the platform's request limit.
946
+
947
+ ---
948
+
949
+ ## Architecture
950
+
951
+ ### Module Map
952
+
953
+ | Export path | Source | Purpose |
954
+ |---|---|---|
955
+ | `./db` | `src/db/` | `defineDatabase()`, `SqliteDurableObject`, Kysely plugins |
956
+ | `./vite` | `src/vite/durableDb.ts` | Vite plugin (`durableDb`) |
957
+ | `./vite/modules` | `src/vite/modules/` | Plugin internals: discovery, AST parsing, code generation, wrangler patching |
958
+ | `./context` | `src/context/` | Tenant ID context (`setTenantIdResolver`, `getTenantId`) |
959
+ | `./migrations` | `src/migrations/` | Snapshot-based migration generation via drizzle-kit |
960
+ | `./registry` | `src/registry.ts` | Action registry and RPC dispatch (`registerAction`, `getAction`, `callAction`) |
961
+ | `./schema` | `src/schema.ts` | Schema builders: `table()` (auto-snake_case wrapper around Drizzle's `sqliteTable`), `text`, `integer`, etc. |
962
+ | `./cli` | `src/cli/` | CLI commands (`push`, `generate`, `status`, `reset`, `validate`) and `db` binary |
963
+
964
+ ### Request Flow
965
+
966
+ ```
967
+ setTenantIdResolver(...) // Configure once at startup
968
+
969
+ Worker fetch()
970
+ -> createUser({ name, email }) // Looks like a normal function call
971
+ -> ArkType validates args
972
+ -> getTenantId() // Calls resolver → throw if unset
973
+ -> Check DO context for direct-call short path
974
+ -> If same DO: direct handler call (no RPC)
975
+ -> If cross-DO: env.BINDING.idFromName(instanceKey) -> stub.rpc()
976
+ -> DO.rpc(method, args, rpcContext)
977
+ -> ensureMigrations() // Run pending migrations if any
978
+ -> getAction(dbName, method) // Look up handler in registry
979
+ -> Validate args with ArkType
980
+ -> runWithDoContext(...) // Set up DO-local context
981
+ -> handler(db, validatedArgs, ctx) // Your action code runs here
982
+ ```
983
+
984
+ ### Kysely Plugins
985
+
986
+ The library includes plugins for transparent data mapping between JavaScript and SQLite:
987
+
988
+ - **DrizzleDefaultsPlugin**: Auto-populates columns with Drizzle's `$defaultFn()` on INSERT (e.g. auto-generated IDs, `createdAt` timestamps) and `$onUpdateFn()` on UPDATE (e.g. `updatedAt` timestamps). Columns that are explicitly provided in the query are not overridden.
989
+ - **SchemaPlugin**: Schema-aware extension of Kysely's `CamelCasePlugin`. Maps camelCase JS property names to snake_case SQL names for both tables and columns using Drizzle schema metadata. Falls back to standard CamelCasePlugin behavior for names not in the schema.
990
+ - **DateSerializePlugin**: Converts `Date` objects to `YYYY-MM-DD HH:MM:SS` strings for SQLite storage, and parses them back into `Date` objects on read. The read path is deliberately conservative: only values in exactly the format the write path produces (also what SQLite's `CURRENT_TIMESTAMP` emits) are converted, and — when constructed with a schema — only for columns Drizzle declares as date-typed (e.g. `integer({ mode: 'timestamp' })`). User-stored strings in `text()` columns (ISO strings with a `T` separator, timezone, or milliseconds) round-trip verbatim.
991
+
992
+ All three plugins are automatically configured when using `createDrizzlePlugins(schema)`.
993
+
994
+ ---
995
+
996
+ ## Development
997
+
998
+ ```bash
999
+ pnpm install # Install dependencies
1000
+ pnpm build # Build with tsdown -> dist/
1001
+ pnpm dev # Build in watch mode
1002
+ pnpm test # Run vitest in watch mode
1003
+ pnpm test:run # Run tests once
1004
+ ```
1005
+
1006
+ Run a single test file:
1007
+
1008
+ ```bash
1009
+ npx vitest run tests/db/defineDatabase.test.ts
1010
+ ```
1011
+
1012
+ Run the example apps:
1013
+
1014
+ ```bash
1015
+ cd examples/simple && pnpm dev
1016
+ cd examples/rwsdk && pnpm dev
1017
+ ```
1018
+
1019
+ ### Project Structure
1020
+
1021
+ ```
1022
+ src/
1023
+ cli/ # CLI commands and state management
1024
+ bin.ts # Binary entry point (commander)
1025
+ push.ts # Push command implementation
1026
+ generate.ts # Generate command implementation
1027
+ status.ts # Status command implementation
1028
+ reset.ts # Reset command implementation
1029
+ validate.ts # Validate command implementation
1030
+ state.ts # Dev state persistence (epoch, snapshots, counters)
1031
+ context/ # Tenant ID resolver context
1032
+ db/ # Core database abstractions
1033
+ SqliteDurableObject.ts # Base DO class with migrations + PITR
1034
+ defineDatabase.ts # defineDatabase() API
1035
+ plugins.ts # Kysely plugins (DrizzleDefaults, Schema, DateSerialize)
1036
+ types.ts # TypeScript type definitions
1037
+ migrations/ # Snapshot-based migration generation
1038
+ snapshot.ts # Drizzle schema -> snapshot diffing
1039
+ generator.ts # Migration file reading/writing
1040
+ registry.ts # Action registration and RPC dispatch
1041
+ vite/
1042
+ durableDb.ts # Vite plugin entry
1043
+ modules/
1044
+ discovery.ts # Database file discovery
1045
+ parser.ts # Babel AST parsing
1046
+ generator.ts # DO class and stub code generation
1047
+ wrangler.ts # wrangler.jsonc auto-patching
1048
+ tests/ # Mirrors src/ structure
1049
+ examples/
1050
+ simple/ # Basic Cloudflare Worker example
1051
+ rwsdk/ # Multi-tenant analytics API with RWSDK + WebSocket transport
1052
+ ```