Writing a migration
Defining a migration with defineMigration, what happens automatically, and what migration code may use.
A migration is defined with defineMigration from
@voidhash/mimic-server/migrate. This page shows how to write one, what the
framework does for you before your code runs, and the rules the code must
follow.
A first migration
Suppose a collection was created with this schema, and you want every note to
have a slug:
// schema/note-v0.ts
import { Primitive } from "@voidhash/mimic-core";
export const NoteV0 = Primitive.Struct({
title: Primitive.String().required(),
});Keep the old schema, add the new one next to it, and define the step between them:
// migrations/0001_add_slug.ts
import { Primitive } from "@voidhash/mimic-core";
import { defineMigration } from "@voidhash/mimic-server/migrate";
import { NoteV0 } from "../schema/note-v0";
export const NoteV1 = Primitive.Struct({
title: Primitive.String().required(),
slug: Primitive.String().required(),
});
export const addSlug = defineMigration({
version: 1,
name: "add-slug",
from: NoteV0,
to: NoteV1,
migrate: ({ oldRoot, root }) => {
const title = oldRoot.title.get();
root.slug.set(title.toLowerCase().replaceAll(" ", "-"));
},
});| Name | Type | Description |
|---|---|---|
version * | number | The migration's number in its collection's registry, from 1 after the baseline; mimic-kit applies it as the collection version it produces. Built and pushed by hand, it is that collection version: one past the active one. |
name * | string | A name for diagnostics. |
from * | Primitive | The schema documents have before the migration. |
to * | Primitive | The schema documents have after it. |
migrate | ({ oldRoot, root }) => void | Rewrites the document. Optional; must be synchronous. |
Your application's current schema is always the to of its latest migration.
Export it from there, or alias it, so that clients and the SDK use the same
primitive.
What happens before migrate runs
For each document, the framework:
- Checks the stored value against
from. A value that does not match fails the migration for that document with the codeinvalid_source. - Reconciles the value toward
to: fields that exist in both schemas keep their values, fields thattono longer declares are dropped, and fields thattoadds take their defaults. - Calls
migratewith two proxies:oldRootreads the document as it was, typed byfrom. It is read-only; writing through it fails withread_only_write.rootis the reconciled document, typed byto. Write your changes through it, exactly as in a client transaction.
- Checks the result against
to. A result that does not match fails withinvalid_target.
Because of step 2, migrate only has to do what reconciliation cannot.
When reconciliation cannot produce a valid document on its own, for example
because to adds a required field without a default, root starts from the
old value instead and migrate is expected to fill the gaps; fields that
to does not declare are still dropped at the end.
Migrations without code
When reconciliation alone produces a valid document, leave migrate out:
export const addPinned = defineMigration({
version: 2,
name: "add-pinned",
from: NoteV1,
to: NoteV1.extend({ pinned: Primitive.Boolean().default(false) }),
});This covers adding an optional field, adding a field with a default, and removing a field. It does not cover adding a required field without a default: nothing can fill it, so every document would fail.
Common changes
Renaming a field. Reconciliation drops the old field and cannot fill the new one. Copy it:
migrate: ({ oldRoot, root }) => {
root.owner.set(oldRoot.author.get() ?? "unknown");
},Changing a field's type. Read the old value and write the converted one:
migrate: ({ oldRoot, root }) => {
root.status.set(oldRoot.done.get() ? "done" : "open");
},Restructuring a list. Read the old entries and set the new array:
migrate: ({ oldRoot, root }) => {
const tags = oldRoot.tags.get() ?? [];
root.tags.set(tags.map((tag) => ({ id: crypto.randomUUID(), label: tag.value })));
},Replacing an array gives its items new ids.
What a migration can use
The server runs your migration in a sandbox, possibly long after you activated it. Its result must depend only on the document.
- It must be synchronous. A
migratethat returns a promise, or writes after it returned, fails withasync_migration. The TypeScript type rejectsasyncfunctions. - No I/O. There is no network, no file system, no
fetchand no timers. A migration cannot look anything up; everything it needs must be in the document or in the code. - Randomness is seeded.
Math.random,crypto.randomUUIDandcrypto.getRandomValueswork, and return the same values every time the migration runs on the same document. Ids you generate are therefore stable. - The clock is fixed.
Date.now()andnew Date()return the time the migration was staged on the server, not the time it runs. - No locale support. There is no
Intl, andlocaleCompareandtoLocaleStringare not locale-aware. - It is bundled. The build bundles the migration, its schemas and everything they import into one script of at most 8 MiB. Import only what the migration needs, and nothing that expects Node or a browser.
Other JavaScript behaviour (strings, JSON, numbers, sorting, regular expressions, dates) matches Node.
Limits
A whole-document migration handles documents up to 8 MiB, and a run is bounded in memory (256 MiB) and in the number of instructions it may execute. For collections whose documents can be larger, write a record migration instead.
Keeping old schemas
Each migration refers to the schema before and after it, so the code of every schema version stays in your repository for as long as its migration does. A convenient layout keeps one file per version or defines each new schema in the migration that introduces it, as above. Never edit a schema that a pushed migration refers to: write a new migration instead.