Last updated:
Lunora has two distinct migration surfaces, because it has two distinct storage backends:
- Sharded / root tables live in each Durable Object's own SQLite. There is
no schema-migration step: editing
lunora/schema.tsand re-running codegen is the migration. The DO provisions tables and indexes on demand. - Global tables (
.global()) live in D1. A relational store needs explicitCREATE TABLE/ADD COLUMNSQL. The runtime writes the additive part itself on first use, andlunora migrate generateemits a timestamped.sqlfile recording the diff — a review artifact and the place to hand-write what the generator cannot express. No command applies that file,lunora deployincluded.
Separately, data migrations (defineMigration) rewrite existing rows in a
sharded table: a backfill or shape change applied to live documents, running
inside each shard's DO in resumable batches.
There is no migrations DSL for sharded-table schema. If all your tables are sharded, the only migration surface you'll touch is defineMigration for data
backfills.
The deploy gate tells you when you need one
You do not have to work out which schema edits need a backfill. lunora deploy
(and prepare / verify) diffs your schema against the committed baseline in
lunora/.lunora-schema.json and classifies every change. Additive edits — a new
optional field, a new table, an added index — are reported and let through. A
change existing rows cannot satisfy blocks the deploy, names the field, and
prints the command that scaffolds the migration it wants:
deploy blocked: 1 unresolved breaking schema change(s) since the last blessed schema baseline:
- added required field users.displayName — existing rows have no value; add a data migration to backfill it
To fix:
• Add a `defineMigration({ id, table, up })` in lunora/ for each affected table, then re-run this command — the baseline is re-blessed on a successful deploy, not by `lunora migrate` itself.
Scaffold the missing migration(s) — the generated `up` is an identity placeholder you must fill in:
lunora migrate create backfill_users --table users
• If the stored rows already fit the new schema, `lunora deploy` goes ahead on its own: it reads the rows of each affected table from the deployed worker (`--migrate-url` or the project link, plus `LUNORA_ADMIN_TOKEN`) and names any row that does not fit.
• For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.
Docs: https://lunora.sh/docs/concepts/migrationsThe scaffolded up is (document) => document, an identity transform. A
migration whose up only returns its document rewrites no row, so it does not
cover anything: the gate names it and keeps blocking until you fill it in, or
until the stored rows show the backfill is not needed.
When the stored rows already fit
A tightening is often already true of the data: every stored row has the new
required field, or every stored value already has the new type. lunora deploy
checks that instead of asking for a migration. For each blocking change that
concerns one field (a new required field, a field made required, a changed type
or shape, a dropped field) it reads the stored rows of that table from the
deployed worker, across every shard and the .global() plane, and runs the new
validator on the changed fields:
- every row fits: the deploy goes ahead, and the baseline advances when it succeeds;
- a row does not fit: the deploy stays blocked and lists the first ten such rows by
table,
_id, field and reason. Stored values, shard keys and record keys are never printed.
The rows are read through the deployed worker's admin export, from the URL
--migrate-url names (or the project link
for this --env), with LUNORA_ADMIN_TOKEN as the bearer. With no URL or no
token the check does not run and the block stands. The URL must be the worker
this deploy ships to: a local or private address (localhost, 127.0.0.1, a
LAN address) is refused, and so is a URL other than the one this checkout is
linked to for the --env (path included) or a URL linked to a different --env.
A *.workers.dev URL is trusted only when the project link for that --env
names it: the Worker name in the host is not enough, because the account
subdomain after it cannot be read from the config and a same-named Worker in
another account would match. Without that link the check is inconclusive and the
block stands; run lunora link --url after the first deploy, or confirm the
drift yourself with --allow-schema-drift. A custom domain must match a route/routes pattern that --env
declares in the Wrangler config, and is refused when it matches another env's
route; only a project that declares no routes at all has nothing to compare it
with, and its URL is taken as given. A refused URL keeps the block and the
message names it. A celld deploy prints no worker URL to link, so record the fleet's URL
once with lunora link --url or pass --migrate-url. The Node target has no
lunora deploy. The scaffolded CI pipelines pass LUNORA_DEPLOY_URL and
LUNORA_ADMIN_TOKEN from the provider's secrets. CI has no project link (the
.lunora/ directory is not committed), so on a *.workers.dev URL the stored
rows are not read there and a tightening still needs a migration or
--allow-schema-drift; a custom domain on a route in the Wrangler config is read.
Some changes cannot be settled by reading rows, and keep their block until a
migration covers them: a field that is no longer nullable or gained a refinement,
and any changed field whose validator codegen could not resolve, that now points
a v.id() or v.storage() somewhere else, or that carries a refinement other than a
literal .max(n). A new .unique() column or unique index is not one of
them: rows settle it (see below). The export route holds each shard's rows in
worker memory before streaming them, so the check is bounded by that.
A migration only clears the drift on the table it iterates, so a backfill on
messages will not wave through a required field added to users. A migration
whose up returns the document unchanged, or whose table is not a string
literal, covers nothing. An up given by name is followed to its declaration (in
the file or imported); one that cannot be resolved to a function is treated as a
real transform, so it is trusted to cover.
Every change is classified by what it can do to the stored data:
| Change | Effect on stored data | How it clears |
|---|---|---|
| New optional field, new table, new index, new relation | none | Does not block |
| Field made optional or nullable, constraint relaxed | none | Does not block |
| TTL lengthened or removed | every row stays (it expires later, or is no longer swept) | Does not block; warns |
| New required field, optional made required, type or shape change, dropped field | rows can become invalid | lunora deploy reads the rows and passes if all fit; otherwise a migration on the table |
New unique index, index made unique, field made .unique() | duplicate values would break the index | lunora deploy reads the rows and passes if no value repeats (naming the repeats otherwise); otherwise a migration that de-duplicates |
No longer nullable, gained a refinement, .commitOrdered() turned on | rows can become invalid or lack a sequence | A migration on the table |
| Dropped index, unique or not | none | Does not block, unless a query still names it through withIndex: the deploy is refused naming the function; point the query elsewhere first |
| Dropped table | rows are left in place, unreachable | Does not block; warns. Export the shard if the data must be kept, or declare the table again |
| Dropped relation | foreign-key values stay; its onDelete stops | Does not block; warns |
| TTL added, moved to another column, or shortened | the next sweep deletes rows now past the cutoff | Blocks until a new migration declares covers: { table, ttl: { field, after } }; the message counts the rows that would go when lunora deploy can read the worker |
.commitOrdered() turned off | none; a _commitSeq changefeed stops advancing | Does not block; warns |
| Shard-mode flip | rows move to other storage | Blocks until a new migration declares covers: { table, shardMode } naming the table and the mode it moves to, after the rows are moved by an export/import round trip |
Table turned .memory() | every row is deleted on the next cold start | Blocks until a new migration declares covers: { table, memory: true }; export the rows first if they must be kept |
| Jurisdiction change | every Durable Object is re-homed | Blocks until a new migration declares covers: { jurisdiction } naming the jurisdiction it moves to (none when removed), after the data is moved |
For the changes that move data, a migration clears the gate only when it names the
change in covers, so an unrelated migration never does. covers is read
statically, so its values must be literals: table, shardMode (root, global,
global:d1, global:hyperdrive or shardBy:<field>; global matches either global
backend), memory: true, ttl ({ field, after } in milliseconds, after 0 when
absent), or jurisdiction (eu, fedramp, us, or none). It must
match the change exactly: the table and the mode the table moves to, or the
jurisdiction the schema moves to. Where a table is involved the migration must also
iterate that table with an up that rewrites rows (one that returns the document
unchanged covers nothing); a jurisdiction change has no table, so covers alone is the
acknowledgement. A missing, different or unreadable covers keeps the block, and the
message names what to declare. For a users table moving to .shardBy("tenantId"):
lunora export --tables users --out users.ndjson # before the deploy
lunora deploy # with the migration below declared
lunora import users.ndjson # rows route to their new homeexport const rehomeUsers = defineMigration({
id: "rehome_users",
table: "users",
covers: { shardMode: "shardBy:tenantId", table: "users" },
// give every row what its new home needs, here its shard key
up: (doc) => ({ ...doc, tenantId: doc.tenantId ?? "default" }),
});A jurisdiction change reads covers: { jurisdiction: "eu" }. The gate cannot see that
the rows were moved: declaring the migration is how you tell it. A dropped index a
query still names is the one drop that blocks, because the shard drops the index and
the next request through that query would throw. The gate reads the
.withIndex("name") calls in your functions; a call whose index name is not a string
literal makes it refuse every dropped index of that table.
A new unique index, an index that becomes unique, or a field that becomes .unique()
is checked against the stored rows: lunora deploy refuses while two rows repeat a
value, naming them by _id (never printing the value), or while the rows cannot be
read. A NULL never counts as a repeat, true and 1 are one value as in SQLite's
index, and on a .shardBy() table only rows of the same shard are compared, because
each shard has its own index.
When every change is verified, or a new migration covers it, the baseline
advances with the deploy. --allow-schema-drift skips the block for one run
without checking anything and leaves the baseline where it was, so the next run
sees the same drift. lunora prepare reads no deployment, so for a change only
stored rows can confirm it refuses and points you at lunora deploy. A baseline
file that is unreadable blocks until it is fixed or deleted; deleting it makes
the next run a first capture.
Schema migrations (global tables)
lunora migrate generate parses lunora/schema.ts, filters to .global()
tables, and diffs the result against lunora/migrations/.snapshot.json. When
the diff is non-empty it writes a timestamped SQL file and updates the snapshot.
lunora migrate generate # name defaults to "auto"
lunora migrate generate add_email_index # name the migrationThis emits lunora/migrations/<timestamp>_<slug>.sql and rewrites
lunora/migrations/.snapshot.json. Commit both: they are deterministic, and the
snapshot is what the next generate diffs against.
Supported diffs: CREATE TABLE (new global table), DROP TABLE (removed
table), ALTER TABLE … ADD COLUMN (added column), and CREATE INDEX (added
index). Unsupported deltas (column rename, column type change, dropping a
column or index) are surfaced as a commented unsupported block in the
generated file with a warning; write that SQL by hand.
A deploy with no migration step
Most deploys need no migration command at all. Each kind of table provisions itself from the schema the worker is running:
- Root and
.shardBy()tables are provisioned by each Durable Object on its next cold start. A field added to the schema is added as a column then (ALTER TABLE … ADD COLUMN), so rows written before the deploy stay readable and read the new field as absent. .global()tables are provisioned on the first request that touches them, with the same additive rules. Several isolates cold-starting at once may all try to add the same column; the ones that lose see it already there and carry on, so no request fails on it.
Adding a required field to a table that has rows
An added column is always created nullable, because SQLite and D1 reject
ADD COLUMN … NOT NULL on a populated table. The validator still treats the
field as required, so rows written before it need a value:
- A required field with a default (
.default(v),.defaultNow(),.$defaultFn(fn)) is backfilled on a.global()table when the column is added, whether the runtime adds it or a generated SQL file does throughlunora migrate apply, which fills it in the same batch. Every row without a value gets the default, evaluated once. That includes theupdatedAtcolumn.timestamps()adds, which starts at the time of the deploy. A column under a unique constraint (.unique(), or part of any unique index) is the exception, whatever its default: one value written to every row would collide when the index is built, so it is treated as having no default. If the backfill statement itself fails, the runtime logs theUPDATEto run and carries on with the column in place. - A required field with no default has no value to invent. Its existing rows
keep reading
NULL, and the runtime logs one warning naming the column. Add a backfillingUPDATE(the generated migration file shows the statement) before you rely on the field. - A field that may hold null (
v.optional,.nullable(), a union withv.null()) needs nothing.
Root and .shardBy() tables store each row as a JSON document, so a field
added later is absent from older rows.
So a deploy that only adds tables, optional fields or non-unique indexes needs nothing beyond the deploy itself. Two things still need a person before it: the hand-written SQL described below, and a data migration that backfills rows.
Applying the generated file
The runtime provisions a global table on the first request that touches one: it
runs CREATE TABLE IF NOT EXISTS for the declared columns and indexes, and
ALTER TABLE … ADD COLUMN for fields the table lacks. That covers every additive
change, which is most of them, with the schema as the single source of truth.
What it never runs is the rest: a DROP TABLE, a DROP INDEX, anything the
generator flags as unsupported, and SQL you add by hand, such as a backfilling
UPDATE or a column rename written as add/copy/drop. Apply those with
lunora migrate apply:
lunora migrate status --sql --url https://your-worker.example.workers.dev # what has run, what is pending
lunora migrate apply --url https://your-worker.example.workers.dev --yes # run the pending filesapply sends each lunora/migrations/*.sql file to the Worker in name order.
The Worker runs a file's statements and records its name and SHA-256 in one
atomic batch, so a file runs once per environment. A second run is a no-op. A
file whose text changed after it ran is refused rather than run again: put the
change in a new file. Renaming an applied file counts as a change, so it is
refused too. A DROP or a replacing write is refused unless you pass
--allow-destructive, and the refusal lists the statements. --yes only
confirms the target, so a remote run needs both flags for such a file. --dry-run prints the statements without
running them. A file cannot contain BEGIN, COMMIT or ROLLBACK, because each
file already runs as one batch. lunora deploy --migrate runs apply before the
data migrations, so a deploy applies its SQL with the rest. Any other deploy tool
can call the same command as a step before its deploy.
Who may run apply is set by the token. The root admin token runs any file. A
named token minted with lunora admin-token create <name> --scope migrations runs
only additive statements: CREATE TABLE, a CREATE INDEX that is not UNIQUE, and
ADD COLUMN with no default, constraint or generated value. A file with any other statement, such as a DROP,
an UPDATE, a trigger or a CREATE UNIQUE INDEX, is refused before anything in the
run executes, and the refusal says which token it needs. A .unique() field or index
generates a CREATE UNIQUE INDEX, so a deploy that adds one needs the root token. A
dry run shows which statements those are.
Upgrading an existing project. Files committed before migrate apply existed were never recorded, so the first run would treat every one of them as pending. A file that drops a table could then run again over rows written since it last ran. Record the files that already ran on each environment, without running them, before its first deploy --migrate:
# Every file in lunora/migrations/ has already run on this environment:
lunora migrate apply --baseline --url https://your-worker.example.workers.dev --yes
# Only the files up to the last one that ran. Later files, such as a DROP that has not run yet, stay pending:
lunora migrate apply --baseline-through <last-file-that-ran>.sql --url https://your-worker.example.workers.dev --yesAfter a --baseline-through, lunora migrate apply --url … --yes runs the files
that are left, including a DROP. Baseline only the files that ran: a recorded
file is never executed.
If the file that drops a table is the first .sql file on a stage, nothing ran
before it there, so there is no earlier file to name. Run that file's statements
by hand on the stage first, then record it. Do not run the whole file as it is: an
ADD COLUMN the runtime already provisioned makes the duplicate column stop the
run before the DROP. Copy the file, delete the ADD COLUMN lines for columns the
stage already has, and run the copy:
cp lunora/migrations/<file>.sql /tmp/<file>.sql
# Remove the ADD COLUMN lines for columns the stage already has from /tmp/<file>.sql
wrangler d1 execute <database-name> --remote --file /tmp/<file>.sql
lunora migrate apply --baseline-through <file>.sql --url https://your-worker.example.workers.dev --yesRecord the file only once every statement in it has run.
Name the file you ran by hand, so --baseline-through records it and nothing
after it. A later file on the same stage stays pending, and a normal
lunora migrate apply --url … --yes runs it, with --allow-destructive too if it drops or replaces data. Plain --baseline would record
every pending file as applied, later ones included, so a later file would never
run.
Run it by hand before the baseline, never after or instead of it: a recorded file
is never executed, so a baseline of a DROP that has not run leaves the table in
place for good. The same applies to a seed INSERT on a database that is new to
tracking.
A database with no recorded file refuses any file that drops, replaces or writes
rows, whatever --allow-destructive says, and the refusal points here. Once a file is
recorded, a later run applies only what is new.
An ADD COLUMN that the runtime already added is skipped, since SQLite has no
IF NOT EXISTS for it. The generator's -- lunora:allow-destructive comment
before each DROP is what @lunora/d1's MigrationRunner reads, and apply
does not need it.
Relaxing NOT NULL on a D1 table
A required field whose validator accepts null — v.any(), v.null(),
v.literal(null), or a v.union(…) with one of those as a member — is
provisioned as a nullable column. Tables created before that rule carry
NOT NULL on such a column, and an insert of null fails there with a raw
constraint error. lunora migrate generate reports it as a
nullability change … NOT NULL → NULL.
On a Hyperdrive (Postgres or MySQL) backend the runtime drops the constraint itself on its next start. SQLite cannot drop a column constraint in place, so a D1 table needs a one-off rebuild. Read the table's current definition, then apply a file like this once per environment:
wrangler d1 execute <DB> --remote --command="SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'notes'"-- The statement printed above, renamed, with NOT NULL removed from the affected column.
CREATE TABLE "notes__rebuild" ("id" TEXT PRIMARY KEY, "_creationTime" REAL NOT NULL, "_version" INTEGER, "note" TEXT, "title" TEXT NOT NULL);
INSERT INTO "notes__rebuild" SELECT * FROM "notes";
DROP TABLE "notes";
ALTER TABLE "notes__rebuild" RENAME TO "notes";Keep the column order exactly as printed, or SELECT * copies values into the
wrong columns. Dropping the old table drops its indexes; the runtime re-creates
every index the schema declares on its next request.
A hand-edited migration file that is only committed and deployed runs nowhere. The runtime will silently add a fresh empty column where your file intended a backfilled one, and the deploy stays green.
Data migrations (sharded tables)
A data migration is a per-document transform over one table. Declare it with
defineMigration from @lunora/server anywhere under lunora/; codegen
discovers it through the type checker and keys a registry on its id.
// lunora/migrations.ts
import { defineMigration } from "lunorash/server";
export const backfillReadBy = defineMigration({
id: "backfill-read-by",
table: "messages",
up: (document) => ({ ...document, readBy: [] }),
});| Field | Required | Description |
|---|---|---|
id | yes | Stable, unique string. The registry key and the per-shard run-state key. |
table | yes | Table whose documents the migration iterates. |
up | yes | Forward transform applied to every row by migrate up. |
down | no | Reverse transform, applied by migrate down. |
batchSize | no | Rows fetched and rewritten per batch (defaults to the runner's batch size). |
The transform receives the stored document (including _id and
_creationTime). Return a new document to rewrite the row, or undefined (or
nothing) to leave it untouched; untouched rows are counted as processed, not
changed. The runner always preserves the original _id and _creationTime, so
a transform should not change row identity.
id and table must be static string literals. Codegen lifts them at build time to key the registry and resolve the target table, and rejects
duplicate ids across the project.
What a data migration cannot do
The runner executes inside one shard's Durable Object, and the only write it
performs is a replace of the row it was handed. Two consequences are worth
knowing before you plan a change around it:
- It cannot delete a row. Returning
undefinedmeans "leave this one alone", not "drop it". Removing rows is a job for an ordinary mutation. - It cannot move a row to another DO. The orchestrator runs the transform once per shard, but each run only ever rewrites its own shard's rows.
That second one rules it out for adopting .shardBy() on a table that already
has rows — re-homing them is an export/import round trip, not a transform. See
Migrating a populated table,
and Migrating a populated table to D1
for the .global() variant. That one runs in a different order: the root DO's
copies must be cleared before the schema edit, because once a table is declared
.global() the shard's writer refuses to touch it.
The admin surface is the exception, and the reason that procedure works: admin reads and writes are addressed to a shard rather than routed by the schema, so the Studio can still reach a root DO's copies of a table the schema has since sharded. A data migration is the one path that always follows the schema.
Scaffolding
lunora migrate create <name> writes a defineMigration stub into
lunora/migrations.ts, appending to the file (and adding the import) when it
already exists. It refuses to clobber a migration with the same id or export
name.
lunora migrate create backfill_read_by --table messagesThe free-text name is slugified into a kebab-case id and a camelCase export.
The table must be a bare identifier. Omit --table and the command prompts for
it interactively (offering the tables declared in lunora/schema.ts); in a
non-interactive context (CI / piped) it fails instead, so pass --table
explicitly there.
Running a data migration
lunora migrate up | down | status <id> drives the cross-shard orchestrator. It
resolves the migration's table locally, then POSTs an admin RPC to the worker's
/_lunora/migrate endpoint, which fans the run out to every live shard of that
table and rolls the per-shard outcomes up.
lunora migrate up backfill-read-by # run forward across shards
lunora migrate up backfill-read-by --dry-run # preview counts, rewrite nothing
lunora migrate down backfill-read-by # apply the down transform
lunora migrate status backfill-read-by # per-shard run-state| Flag | Description |
|---|---|
--dry-run | Scan and count without rewriting rows or persisting run-state. |
--batch-size | Rows per batch, overriding the migration's own batchSize and the default. |
--steps | Cap on batches processed this invocation (the runner's maxBatches). The run stays resumable. |
--url | Worker URL (defaults to http://localhost:8787). |
--token | Admin bearer token. Falls back to LUNORA_ADMIN_TOKEN. |
--prod | Target production. Requires an explicit --url. |
--yes | Required alongside --prod for up/down, and for any apply against a non-local worker; confirms the target. |
--allow-destructive | apply only: confirms a file that drops, renames, truncates or replaces data. Separate from --yes. |
Every run is admin-gated: pass --token or set LUNORA_ADMIN_TOKEN. Against
production, --prod requires an explicit --url, and up/down additionally
require --yes.
You can also apply pending data migrations as part of a deploy:
lunora deploy --migrate --migrate-yes --migrate-url https://app.example.com --migrate-token $LUNORA_ADMIN_TOKENResumable and idempotent
Each shard's runner tracks progress (cursor, processed/changed counts, status)
in a reserved __lunora_migrations table, persisting after every batch. Two
properties follow:
- Resumable. An interrupted run, or one stopped by
--steps, resumes from the stored cursor instead of rescanning. Iteration uses a stable_creationTime ASC, _id ASCkeyset order, and rewrites preserve row identity, so each row is visited exactly once even as the batch ahead is rewritten. - Idempotent on completion. Re-running a migration already
completedin the same direction is a no-op that returns the recorded counts.
The rolled-up status across shards is completed only when every shard finished
cleanly; failed if any shard's runner reported failure; and in_progress if
any shard is incomplete or unreachable (the run stays resumable). The roll-up
also reports summed processed / changed counts and the number of ok vs
failed shards.
The built-in re-projection backfill
One migration id is reserved by the framework rather than declared in your
lunora/: __lunora_reproject__<table>. It rewrites rows whose v.bigint() /
v.bytes() columns are still stored in the pre-projection form. Such a row
reads back correctly, but SQL never matches it, so filter, withIndex,
ORDER BY and SUM silently skip it. Only rows written before the storage
codec was fixed are affected, and any ordinary write heals a row, so what is
left is whatever nobody rewrites.
--dry-run answers whether you need it, per shard, without rewriting anything:
lunora migrate up __lunora_reproject__payment_sessions --dry-run
lunora migrate up __lunora_reproject__payment_sessionsThe transform skips a row already in the current projection, and the runner
counts only the rows it would rewrite, so a dry run's changed is the
legacy-row count for that shard. migrate status reports run-state for a
backfill that has already run; use the dry run before one, since a shard that
never ran it has no run-state to report.
One caveat on reading changed: 0 as "done": the transform also skips a row it
cannot re-project at all (a bigint wider than the projection's 39-digit key,
which is reachable for a uint256-shaped value), and such a row is counted
processed, not changed. It logs a warning naming the row id, and that warning is
the only signal. So changed: 0 means "nothing left that this backfill can fix",
which is the same thing as "fully re-projected" only when the shard's logs are
clean.
The backfill is deliberately not automatic on deploy: every rewritten row pokes its live subscribers, so an all-legacy shard would turn a deploy into a broadcast storm on a path nobody asked for.
Inspecting run-state in the Studio
The Studio's Database → Migrations panel (see
Studio › Database) inspects and drives data
migrations on a single shard. Enter a shard key to read its persisted run-state
table (id, direction, status, processed, changed, last updated, and
any error) over a live channel, so an in-progress migration's counts climb in
place. You can kick off a migration by id with a direction and an optional
dry-run toggle; a real (non-dry-run) run is behind a confirm gate. The panel
issues no credentials of its own; it relies on the worker's LUNORA_ADMIN_TOKEN
gate like the CLI.
One-off data edits without a deploy
A defineMigration is the right tool for a backfill you want reviewed,
versioned and re-runnable. It is the wrong tool for "mark these 800 rows
seen" — that shouldn't need a deploy at all.
The Studio's data browser has Set column on N matching beside Delete N matching. Filter the table to the rows you mean, pick a column, give it a JSON value, and every matching row is patched through the same schema-aware writer a mutation uses: validators run, indexes and full-text search (FTS), aggregate and rank shadow tables stay in sync, and live subscribers are poked.
The Studio is always local: lunora view opens the studio the running dev
server serves, and a deployed worker serves none — so these edits land in
whatever storage that dev server is bound to. lunora dev --remote proxies the
D1/KV/R2 bindings to the deployed worker, which puts the data browser on
production .global() tables. DO shards stay local either way, so a sharded
table's rows are only ever edited against the dev server's own storage.
The value is parsed as JSON, not taken as text, so true, 42 and null
arrive as themselves — a v.boolean() column takes true, not "true". A
v.bigint() or v.bytes() column takes the same tagged form the grid displays.
The SQL console (Database → SQL) is deliberately read-only. A raw UPDATE would bypass the schema-aware writer and desync the FTS, aggregate and rank
shadow tables, so bulk edits go through this path instead.
Things worth knowing before you run one:
- It is scoped to one shard. The data browser is shard-addressed, so on a
.shardBy()table "every matching row" means every matching row in the shard you are viewing. The dialog names the shard. Other shards are untouched — repeat per shard, or write adefineMigration, which runs across all of them. - It is bounded. The shard writes at most one page per round-trip and the browser loops it. A very large set stops with "rows still match"; running it again resumes from where it stopped rather than rescanning from the top.
- A unique column is refused. Setting a single-column
.unique()index to the same value on more than one row cannot succeed, so the dialog blocks it rather than letting the writer fail partway. - A failure mid-run is partial, not rolled back. Each row commits on its own, so the message reports how many rows had already been written.
- Every call is audited — table, the field names set, and the row count. The values themselves are never recorded.
For anything you want to keep, review or run again later, write a
defineMigration instead.
Resetting local state
lunora reset is not a migration command, but it's the companion when a local
schema change leaves stale dev data. It clears the local Miniflare state
directory (.wrangler/state), and with --all also removes .lunora-cache.
lunora reset # clear .wrangler/state (prompts to confirm)
lunora reset --all # also remove .lunora-cache
lunora reset --yes # skip the prompt (required when stdin is not a TTY)This only touches local state; it never reaches a deployed worker or D1.