Skip to content

Commit 3b2da5c

Browse files
authored
Fixes from a standalone Lagerverk monorepo: migration race, required columns, dev migrations, wrangler reconciliation (#22)
* CLI and Vite plugin: early wrangler patch, unsafe-migration checks, per-database reset, rename answers, transform prefilter - The plugin patches wrangler.jsonc in its `config` hook (patchWranglerConfig: true), ahead of @cloudflare/vite-plugin's, which builds the emitted wrangler.json from the config it reads there and restarts a dev server on a later write. One build now ships the bindings it patched; the first dev start no longer restarts mid-start. The change is logged (`durable-db updated wrangler.jsonc (…)`); nothing is written while a database file does not parse. syncWranglerConfig() is exported from durable-db/vite. - transform skips modules that neither mention defineDatabase/destroyDatabase nor import an `action` factory, so a syntax error elsewhere is not reported as [plugin:durable-db]. - Dev epochs are per database: `db reset --database x` sets state.json databases[x].epoch and rotates x alone; stubs call applyDevEpoch(key, dbName). getTenantId() inside a global database's DO no longer yields 'global' in dev. - --database on push/generate/status/reset/validate; an unknown name throws UnknownDatabaseError listing the valid ones (exit 1). - Rename questions: --rename <table>.<old>=<new> / <old>=<new> and --no-renames answer drizzle-kit's "created or renamed?" before it diffs (renames applied to the previous snapshot, create + drop as two diffs); without a TTY an unanswered one throws SchemaRenameRequiredError naming the command and both answers. status reports "needs rename resolution". - generate refuses a column added NOT NULL without a default (UnsafeMigrationError, --force overrides) and warns about drops and columns made NOT NULL; push/status show the warnings, validate reports them for the not-yet-generated change. Every diff runs before any file is written. - The plugin records the running dev server (dev-server.json, pid + token); `reset --purge-local-storage` refuses while it is alive (--force). * docs: wrangler sync timing and reconciliation, per-database reset, renames, unsafe migrations, dev/prod migration hand-off, testing actions * Migrations: one run for concurrent first calls; dev migrations hand off to the generated production migration ensureMigrations() memoises the run in flight instead of guarding it with a boolean. runMigrations() reads the pending list and then awaits the PITR probe and bookmark, so concurrent first calls on a fresh Durable Object (a new tenant's first page, StrictMode's double effect) applied the same CREATE TABLEs twice and one failed with MigrationSchemaConflictError. A failed run is retried by the next call; resetMigrationState() drops a run in flight. In dev, the statements applied by dev migrations (_dev_…) are journaled in __dev_migration_statements. A pending production migration whose statements those dev migrations already ran (db push, then db generate) is recorded as applied without being executed, instead of failing with "duplicate column name" on every request until db reset. Production storage never has the journal. "duplicate column name" now maps to MigrationSchemaConflictError like "already exists", naming the dev migrations involved and the `db reset --database <name>` to run. * Quote identifiers with backticks so a missing column fails instead of reading as a string SQLite (workerd's build included) reads a double-quoted identifier that names no column as a string literal: a column not yet migrated selected its own name and a WHERE on it compared two constants. createKyselyFromSql compiles with a SqliteQueryCompiler that quotes identifiers in backticks, so such a query fails with "no such column". The parameter inliner skips backtick-quoted identifiers too. * Actions: optional args accept undefined; direct calls run against the test database in tests An optional key (`'photoKey?': 'string'`) type-checks with `photoKey: undefined` but validation rejected it. Action args are compiled with a `type` whose validators drop undefined-valued keys of a plain-object args value first; it is the `type` durable-db/registry exports to the action transform, so the RPC stub and the Durable Object both use it, whether args is an object or a type(...). The untransformed action() and the test harness use it too. An action called directly outside the build (code under test) now runs against the newest live test database createTestDatabase() created with its database's tables; destroyDatabase() empties it. Without one, the error says how to set it up and no longer points at a Vite config or lists ArkType internals as the action's args. * Admit Vite 8 in the vite peer range The plugin is built and tested with Vite 8; installs on it reported an unmet peer dependency. * Wrangler config: reconcile durable-db's Durable Objects and edit wrangler.jsonc in place patchWranglerConfig() was add-only. It now also removes durable-db's own bindings (<X>_DATABASE_DO -> <X>DatabaseDO) whose class is no longer a discovered database (workerd refuses to start with a binding to a class the worker does not export), writes a renamed_classes migration when a database's class name changed unambiguously (an extension's mount changed), and never deletes a removed database's class: it warns with the exact deleted_classes migration to add. Bindings of other names or to other workers' classes are left alone. checkWranglerConfig() reports stale bindings and classes. PatchResult keeps its fields and adds addedBindings, removedBindings, newClasses, renamedClasses and deletedClasses. Edits are made in place on the JSONC text (parsed with jsonc-parser, a new dependency): comments, layout, line endings and the trailing newline are kept, one-line arrays stay on one line, and no wrangler.jsonc.backup is written. * Changeset: runtime and wrangler config fixes * Vite plugin: the transform pre-check admits every import the parser takes an action factory from - ACTION_IMPORT required `{` right after `import`, so an action file that also took the database module's default export (`import main, { action } from '../databases/main'`) was never parsed: its actions stayed unregistered and the worker ran the untransformed action(), which throws. The gap between `import` and `{` now admits any clause text (a default binding, `type`, comments, line breaks) and excludes only what cannot occur in it (a quote, `;`, `{`, `}`). Tests: the default-binding, no-space, multi-line, comment and string specifier forms reach the parser; the default-binding action file is transformed into stubs. - syncWranglerConfig's unit tests move to tests/vite/modules/syncWrangler.test.ts (tests mirror src/), plus prefixed sources and discoverDatabaseInfos; durableDb.test.ts keeps the config-hook tests and checks the re-export. - The hot-channel watcher test rewrites state.json until a reload is seen: macOS starts fs.watch's FSEvents stream on another thread, so a write right after configureServer could precede it under a loaded test run. * Wrangler config: a renamed database's migrations move with its data; renames are no longer guessed A renamed_classes migration hands the new class the old storage, with its __migrations journal, while the build embedded the migrations of the new name's directory: after a mount change, `db generate` wrote a fresh init there and the deploy failed every request with "table already exists". The rename now moves the old database's migrations directory (the sibling whose name gives the stale class, exactly) to the new name. When it cannot - the new directory already has migrations, or several directories belong to the old class - neither a rename nor a new class is written, PatchResult.conflicts lists it, a warning gives the two ways out (rm -r + mv to keep the data, or the deleted_classes migration), and the plugin throws until one is done. Migrations are loaded after the config is reconciled, so the moved ones are embedded. The log no longer claims dev data is kept: miniflare keys local storage by class name. Pairing is limited to a database of a mounted source whose file stem the stale class ends with (a mount change, or a database moved into a mount). catalog.ts -> product-catalog.ts, and a database moved out of a mount (which reads the same as an app replacing product-catalog.ts with catalog.ts), are never paired. checkWranglerConfig() no longer reports a rename target as a missing class too, suggests one migration with the next free tag, gives the mv for a rename's migrations, and reports renamedClasses, migrationsMoves and conflicts. A failed production build names what is missing and what is stale (describeWranglerCheck()). * Action args: optional keys accept undefined through ArkType's own option Replace the pipe that dropped undefined-valued keys before validation with an ArkType scope that sets exactOptionalPropertyTypes: false (jitless, like the shared one). A required key whose type admits undefined ('string | undefined') stays valid when passed as undefined, as it was in 0.3.0; optional keys of nested objects accept undefined too; and the args validator is a plain object Type again, so .props and .toJsonSchema() work (undefined becomes { not: {} } in JSON Schema). The type exported from durable-db is unchanged. * Migrations: a second db push no longer breaks the dev database; hints name the database db push diffs from the production snapshot, so after add a column, restart, add another, the new squashed dev migration repeats the first one's ALTERs and failed with "duplicate column name" until db reset. A pending dev migration now skips the statements of an earlier dev migration (from the dev statement journal) that it contains whole. One that redoes an earlier change in another form still runs, and its MigrationSchemaConflictError says so. The generated Durable Object sets databaseName, so the db reset hint names the database the db commands know (orderItems, not order-items). * Docs and changeset: migrations move with a rename, args scope, repeated dev pushes
1 parent 7f8b595 commit 3b2da5c

55 files changed

Lines changed: 6451 additions & 430 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.changeset/dev-loop-and-cli.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
'durable-db': minor
3+
---
4+
5+
The plugin's `transform` only Babel-parses modules that can define a database or actions (they mention
6+
`defineDatabase`, or import an `action` factory): a syntax error in a page is reported by the compiler that owns
7+
it, not as `[plugin:durable-db]`.
8+
9+
Dev epochs are per database. `db reset --database <name>` gives that database its own epoch
10+
(`state.json` → `databases[name].epoch`), so only its instances start fresh — a tenant directory and every other
11+
database keep their data; a full reset sets a new project epoch for all. `applyDevEpoch(key, dbName)`: generated
12+
stubs pass their database's name. Inside a global database's Durable Object, `getTenantId()` no longer returns
13+
`'global'` in dev.
14+
15+
`--database` is on every command (`push`, `generate`, `status`, `reset`, `validate`), and an unknown name exits
16+
with code 1 listing the valid ones (`UnknownDatabaseError`) instead of "No databases found." or resetting
17+
everything.
18+
19+
Renames without a terminal: drizzle-kit's "created or renamed?" questions can be answered on the command line —
20+
`push`/`generate --rename <table>.<old>=<new>` (a column; `<old>=<new>` a table; repeatable) and `--no-renames`
21+
(create + drop) — or programmatically (`renames`, `noRenames`, `interactive: false`). Without a TTY and without
22+
answers, the commands fail with `SchemaRenameRequiredError`, naming the command and both answers, instead of
23+
drizzle-kit's bare "Interactive prompts require a TTY terminal". `db status` never prompts and reports such a
24+
change as "Changes pending — needs rename resolution" instead of "Schema is up to date".
25+
26+
`db generate` refuses a column added `NOT NULL` without a default (exit 1, nothing written): the migration fails
27+
on every table that has rows, so every tenant with data would break after the deploy — add `.default(...)`, or
28+
add it nullable and backfill. `--force` writes it anyway. It warns about dropped columns and tables and columns
29+
made NOT NULL; `push` and `status` show the same warnings, and `db validate` reports them for the change not yet
30+
generated (its replay runs on an empty database).
31+
32+
`db reset --purge-local-storage` refuses while the project's dev server runs (the plugin records it in
33+
`node_modules/.cache/durable-db/dev-server.json`; `--force` overrides): deleting workerd's storage under it broke
34+
every database request until a restart.

‎.changeset/runtime-and-wrangler.md‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
---
2+
'durable-db': minor
3+
---
4+
5+
Runtime and wrangler config fixes found by building an app on durable-db through a framework.
6+
7+
- **Concurrent first calls share one migration run.** `ensureMigrations()` memoises the run in flight
8+
instead of guarding it with a boolean. A new tenant's first calls arriving together (server
9+
components, a client component's RPC call on mount, React StrictMode's double effect) used to apply
10+
the same `CREATE TABLE`s twice, and one of them failed with `MigrationSchemaConflictError`.
11+
- **`db push` then `db generate` no longer breaks the dev database.** In dev, a Durable Object journals
12+
the statements its dev migrations (`_dev_…`) apply. A pending production migration whose statements
13+
those dev migrations already ran is recorded as applied without being executed. Before, it ran again
14+
and failed with "duplicate column name" on every request until `db reset` wiped every dev database.
15+
Production storage never holds the journal, so production behaviour is unchanged. A "duplicate column
16+
name" failure now raises `MigrationSchemaConflictError` as "already exists" does. Its message names
17+
the dev migrations involved and the `db reset --database <name>` to run; the generated Durable Object
18+
sets `databaseName`, so the name is the one `db` commands know (`orderItems`, not `order-items`).
19+
- **A second `db push` no longer breaks the dev database either.** `db push` diffs from the production
20+
snapshot, so after add a column → restart → add another, the new dev migration repeats the first
21+
one's `ALTER`s. A pending dev migration now skips the statements of an earlier dev migration it
22+
contains whole. One that redoes an earlier change in another form (a column whose type changed again)
23+
still runs and raises `MigrationSchemaConflictError`, now saying so.
24+
- **Queries quote identifiers with backticks.** SQLite, workerd's build included, reads a double-quoted
25+
identifier that names no column as a string literal. A column missing from the database (a schema
26+
change not yet migrated) used to select its own name, and a `WHERE` on it compared two constants. It
27+
now fails with "no such column". Raw `sql` you write yourself is unchanged.
28+
- **The wrangler config is reconciled, not only appended to.** With `patchWranglerConfig: true`:
29+
- durable-db's own bindings (`<X>_DATABASE_DO` → `<X>DatabaseDO`) whose class is no longer a
30+
discovered database are removed. workerd refuses to start with a binding to a class the worker does
31+
not export.
32+
- A database of a mounted source whose class name changed unambiguously (the source's mount changed,
33+
or the database moved into a mounted source; its file name unchanged) gets a `renamed_classes`
34+
migration, so its deployed data moves with it. Before, it got a new class and the data was orphaned.
35+
The renamed Durable Object keeps the old storage and its `__migrations` journal, so the old
36+
database's migrations directory moves with it (`migrations/reviews-feedback/` →
37+
`migrations/feedback-feedback/`). When it cannot — the new directory already has migrations, or more
38+
than one directory belongs to the old class — nothing is written for that database: a warning gives
39+
the commands to keep the data or the `deleted_classes` migration to drop it, and the plugin stops
40+
until one is done. A database moved out of a mount, or two databases of the app, are never paired:
41+
`ProductCatalogDatabaseDO` → `CatalogDatabaseDO` reads the same as replacing product-catalog.ts with
42+
catalog.ts. Local dev storage is kept per class name, so in dev a renamed database starts empty.
43+
- A removed database's class is never deleted for you, because that deletes its data. A warning gives
44+
the exact `deleted_classes` migration to add, or says to drop the class from its
45+
`new_sqlite_classes` entry if it was never deployed.
46+
- Bindings of other names, and bindings to other workers' classes (`script_name`), are never touched.
47+
48+
`checkWranglerConfig()` reports such stale bindings and classes (`staleBindings`, `staleClasses`,
49+
`renamedClasses` with the `mv` for their `migrationsMoves`, `conflicts`), so a production build fails on
50+
them when patching is off, with an error that names what is missing and what is stale
51+
(`describeWranglerCheck()`). A rename target is no longer reported as a missing class too, and the
52+
suggested migration takes the next free tag. `PatchResult` gains `addedBindings`, `removedBindings`,
53+
`newClasses`, `migrationTag`, `renamedClasses`, `movedMigrations`, `conflicts` and `deletedClasses`.
54+
- **wrangler.jsonc is patched before anything reads it.** With `patchWranglerConfig: true` the plugin
55+
reconciles the file in its `config` hook, before `@cloudflare/vite-plugin` reads it. Patched lazily, a
56+
build emitted the `wrangler.json` it had read before the patch — a database added since the last build
57+
shipped unbound, without its migration — and the first dev start restarted mid-start (no URLs printed, an
58+
unhandled rejection logged). A refused rename stops the plugin right there. A change is logged in one line
59+
(`durable-db updated wrangler.jsonc (Durable Objects: +AUDIT_DATABASE_DO → AuditDatabaseDO; migration v2:
60+
…)`, removals and renames included); nothing is written while a database file does not parse. Later, the
61+
plugin reconciles again only when the set of databases changes (one added or remounted while the dev
62+
server runs). `syncWranglerConfig({ projectRoot, databasesDir, migrationsDir })` from `durable-db/vite`
63+
runs the same step for CLIs that want the file settled before Vite starts; it returns the `PatchResult`
64+
(`conflicts` included) with the databases, the files that did not parse and the summary's `changes`.
65+
- **wrangler.jsonc edits keep the file as you wrote it.** Comments, formatting, the indentation style,
66+
line endings and the trailing newline all survive. Only the entries added or removed change, and one-line
67+
arrays stay on one line. No `wrangler.jsonc.backup` is written any more. The config is parsed as
68+
JSONC, so trailing commas are fine. This adds `jsonc-parser` as a dependency.
69+
- **Optional action args accept `undefined`.** `'photoKey?': 'string'` infers `{ photoKey?: string }`,
70+
which accepts `photoKey: undefined`, but validation used to reject it ("photoKey must be a string (was
71+
undefined)"). Action args now compile in an ArkType scope with `exactOptionalPropertyTypes: false`, in
72+
the RPC stub and the Durable Object alike: an optional key at any depth admits `undefined`, a required
73+
key stays required (also `'note': 'string | undefined'`, as in TypeScript), and the args Type stays a
74+
plain object Type (`.props`, `.toJsonSchema()`). `durable-db/registry`'s `type` is that scope's; the
75+
`type` exported from `durable-db` is unchanged. An `args` given as a ready `type(…)` keeps the rules of
76+
the scope that made it.
77+
- **Code that calls actions can be tested in Node.** An action called directly outside the build (a page,
78+
procedure or job under test) now runs against the test database `createTestDatabase()` created for
79+
its database's tables (the newest live one). `destroyDatabase()` empties that database. Without a test
80+
database, the error says how to set one up and no longer points at a Vite config or dumps ArkType
81+
internals.
82+
- The `vite` peer range includes Vite 8.

0 commit comments

Comments
 (0)