Appearance
Testing TailorDB Migrations (Beta)
Beta: The
tailordb migrationcommand and the migration runtime are beta features. They may introduce breaking changes in future releases. The CLI emits a beta warning on every invocation.
This page covers testing the migrations that TailorDB Migrations describes how to write. For deploying them, see Operating TailorDB Migrations.
Testing Pending Migrations
tailor tailordb migration test runs every migration pending in the source workspace against an isolated workspace. The source workspace is selected by --workspace-id or the active profile and is never modified.
The command performs the following sequence:
- Reads each migration-enabled namespace's
sdk-migrationcheckpoint from the source workspace and reconstructs that exact snapshot from local migration history. A deployed namespace that has no checkpoint is treated as migration 0 when its schema matches the0000snapshot, astailor deploydoes; otherwise the command fails and lists the differences. A namespace that was never deployed, or has no tables yet, also fails. - Creates a temporary workspace in the same region as the source, unless
--target-workspace-idnames an existing throwaway workspace. By default it is created in the source's organization and folder.--organization-idplaces it at the root of that organization, and--folder-idplaces it in that folder (together with--organization-idwhen the folder is in another organization or the source is not in an organization). With--target-workspace-id, the given values must match where that workspace already is. - Deploys the checkpoint snapshots and writes their checkpoint labels.
- Loads fixture data or clones source records.
- Runs the normal deployment pipeline, including every pending pre-migration,
migrate.ts, and post-migration phase. - Optionally runs an assertion script against the migrated data.
- Deletes an automatically-created workspace after success or failure.
Right after creating an automatically-created workspace (step 2), the command records a 24-hour expiry on it. If the run is interrupted before step 7 — for example, a CI job is cancelled or reaches its time limit — the command cannot delete the workspace, so it stays. Once the 24 hours have passed, tailor workspace prune --expired (with a location option such as --organization-root or --folder-id) deletes it. A workspace given with --target-workspace-id is not given an expiry. If recording the expiry fails, the command warns and continues the test.
Both the pre-migration and final TailorDB schemas come from committed migration snapshots. Ungenerated changes in the current table definitions are not included in the rehearsal.
Executors are omitted from the baseline deployment so loading fixture or cloned records cannot trigger current event handlers against the older schema. Auth user profiles are also deferred until the pending migrations finish, while configured machine users remain available to run seed and migration scripts. The final deployment restores the configured executors and user profiles. Static websites are deployed so configuration references to their URLs resolve, but their workspace-bound custom domains are omitted from migration-test deployments.
Seed mode
Seed mode is the default and uses the JSONL files produced by the configured seedPlugin. Run tailor generate after adding the plugin or changing seed tables, then populate its data/*.jsonl files:
bash
tailor tailordb migration test --data seedRows are loaded only for tables present in the deployed pre-migration snapshots (and current schemas without migrations), in foreign-key dependency order. Fields introduced by pending migrations, including timestamp and nested fields, are removed before insertion so current fixtures can be loaded into the baseline schema. Missing table files are treated as empty. IdP _User fixtures are not loaded by this command.
Use --machine-user to run the seed, the pending migration scripts, and the assertion as that machine user, in place of db.<namespace>.migration.machineUser and the first entry in auth.machineUsers (and, for the seed, the seed plugin's machineUserName). An empty override is rejected. Every machine user needed for these scripts must be defined in auth.machineUsers; the command checks this before creating a temporary workspace or deploying to a designated target. No machine user is required when there are no seed rows, pending migration scripts, or assertions to execute.
Clone mode
Clone mode copies TailorDB records from the source workspace after the identical application, namespace names, and pre-migration schemas exist in the target. For namespaces without migration history, the command reproduces the deployed source schema rather than uncommitted local table changes:
bash
tailor tailordb migration test --data cloneCloning requires editor access to both workspaces, which must be in the same region. Clone mode copies TailorDB records only: IdP users, file blobs, and metadata labels are not copied, and unlike tailor data clone it has no --copy-files or --copy-idp-users option. File fields therefore retain references whose blobs are absent. The command polls the asynchronous operation and reports platform failures.
Clone mode copies the data of one application. With a defineWorkspace() config (Beta), the config must deploy a single application that lists every namespace with pending migrations; otherwise the command stops with MIGRATION_TEST_CLONE_UNSUPPORTED. Use --data seed for such a config.
With --target-workspace-id, the designated target must be in the same region as the source; the command checks this before deploying anything to it.
The source schema is re-verified immediately before cloning; if the source workspace was deployed or otherwise changed after the test started, the command aborts instead of cloning data that no longer matches the deployed baseline.
Assertions and retained targets
Pass a TypeScript file with --assert. Its exported main function uses the same Kysely transaction signature as migrate.ts, runs after all pending migrations, and must throw when an invariant fails:
bash
tailor tailordb migration test \
--data seed \
--assert ./tests/assert-customer-email.ts \
--assert-namespace tailordb--assert-namespace is inferred when only one namespace has pending migrations and is required otherwise.
To inspect the result after a run, pass --keep so the automatically created workspace survives instead of being deleted, on success and on failure:
bash
tailor tailordb migration test --keepA kept workspace records no expiry unless you also pass --keep-ttl <age> (for example --keep-ttl 7d), so tailor workspace prune --expired does not delete it.
Alternatively, provide an empty designated throwaway workspace. This mode never deletes the target and requires explicit acknowledgment:
bash
tailor tailordb migration test \
--target-workspace-id 00000000-0000-4000-8000-000000000000 \
--yesDo not target a shared development or production workspace: baseline deployment reconciles its managed resources and schemas before the migration test runs.
Testing Migrations Locally
Unit-testing migrate.ts
main is a plain function, so you can unit-test it with Vitest before the first deploy ever runs it. createKyselyMock from @tailor-platform/sdk/vitest compiles queries to the same SQL as the deployed migration, so a test verifies the exact statements the script issues — SQL, parameters, and order. Type the mock with the Database interface exported from the generated db.ts.
Scaffold a ready-to-fill test next to the script with:
bash
tailor tailordb migration script 0005 --with-testWhen migrate.ts already exists (the usual case for breaking changes, where migration generate creates it), the command adds only the tests that do not exist yet, plus a missing db.pglite.ts. Or write the test by hand:
typescript
// migrations/0005/migrate.test.ts
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, test } from "vitest";
import { main } from "./migrate";
import type { Database } from "./db";
describe("0005 add required email", () => {
test("backfills null emails", async () => {
const mock = createKyselyMock<Database>();
await mock.withTx((trx) => main(trx));
expect(mock.updates).toHaveLength(1);
expect(mock.updates[0]?.updateValues()).toEqual({ email: "unknown@example.com" });
expect(mock.updates[0]?.sql).toContain('where "email" is null');
});
});Stage the rows each query returns with mock.enqueueResult(...) or mock.setQueryResolver(...) when the script reads before writing; call main(trx, { env: { ... } }) when the script takes a MigrationContext. See Kysely-layer mock for the full mock API.
These tests need no platform connection and no tailor-runtime environment — they run in a plain Vitest setup. Vitest's default include pattern already picks up migrations/**/migrate.test.ts; if your config narrows include, add the migrations directory. The test file is ignored by tailor deploy and never ships to the platform.
A migration generated under defaultDateRepresentation "temporal" or "date" records that in its diff.json, and deploy runs the script with Temporal or Date values for t.date(), t.datetime(), and t.time() fields that omit as. The scaffold calls applyDateRepresentation from @tailor-platform/sdk/vitest with the recorded value, or with "string" for a migration that records none, and imports migrate.ts after that call, so the test runs the script the same way deploy does even after the setting changes in tailor.config.ts. Keep that call when editing the test. The record pins the values at run time only: the types of t fields declared inside migrate.ts follow the current tailor.d.ts like everywhere else, so give such fields an explicit as to keep their types and values aligned after the setting changes. The helper selects the representation but does not provide Temporal itself, so run such a test in the tailor-runtime Vitest environment, which installs it on Node.js versions without native Temporal; this is the one case where a migration unit test needs that environment (a migration recorded under "date", or without a record, needs no Temporal and runs in a plain Vitest setup).
Executing migrate.ts against a local Postgres (PGlite)
A statement-level test verifies what the script issues, not what it does to data (e.g., whether a where clause matches the rows you intended). To run main against real rows locally, back Kysely with @electric-sql/pglite — an in-memory PostgreSQL — via createKyselyPGlite from @tailor-platform/sdk/vitest:
bash
npm install -D @electric-sql/pgliteThe generated db.pglite.ts exports the CREATE TABLE script for the same schema db.ts types — the tables as the pre-migration phase leaves them while migrate.ts runs, including relaxed constraints, renamed fields under both names, and retained removed fields. Run it once on the PGlite instance, stage rows, then run the script in a transaction. tailor tailordb migration script <N> --with-test scaffolds this test too when @electric-sql/pglite is installed. Type the instance with Unmigrated<Database> rather than Database: db.ts types a column the migration makes required as T | null on read but T on write (and an enum it narrows as the old values on read but the new ones on write), so that migrate.ts cannot write what the migration is removing — which would also stop the test from staging the rows the script has to convert. Unmigrated lets every column be written with whatever it can still be read as; main still receives a Transaction<Database>.
Relations are enforced as on the platform: a row that points at a parent that does not exist is rejected. Write the records the test starts from inside prepareFixtures, which leaves relations unchecked while it runs, so you can stage rows that predate a relation, such as rows whose parent does not exist that the script repairs. Relations are checked again when it returns, so the script itself still cannot write a missing parent. The same holds in reverse: the script cannot delete a parent that a row still points at, or change the key a row points at, so delete rows in the opposite order of staging them. NOT NULL, UNIQUE, and CHECK constraints stay enforced. A relation is left unenforced while the pre-migration schema cannot satisfy it: when a pending type change leaves the field a different type from its target, when the migration adds the relation to an existing top-level field or moves it to another table or key, or when the target field's unique constraint is still withheld. How relations on array fields and inside nested objects behave is described under Real SQL execution with PGlite.
typescript
// migrations/0005/migrate.pglite.test.ts
import { PGlite } from "@electric-sql/pglite";
import { createKyselyPGlite, prepareFixtures, type Unmigrated } from "@tailor-platform/sdk/vitest";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { pgliteSchema } from "./db.pglite";
import { main } from "./migrate";
import type { Database } from "./db";
const pglite = new PGlite();
const db = createKyselyPGlite<Unmigrated<Database>>(pglite);
// PGlite loads Postgres on first use, which can take longer than the default hook timeout.
beforeAll(async () => {
await pglite.exec(pgliteSchema.tailordb);
}, 60_000);
afterAll(async () => {
await db.destroy();
});
describe("0005 add required email", () => {
test("backfills null emails and keeps existing ones", async () => {
const now = new Date();
await prepareFixtures(pglite, async () => {
await db
.insertInto("User")
.values([
{ name: "a", email: null, createdAt: now, updatedAt: now },
{ name: "b", email: "b@example.com", createdAt: now, updatedAt: now },
])
.execute();
});
await db.transaction().execute((trx) => main(trx));
const rows = await db.selectFrom("User").select(["name", "email"]).orderBy("name").execute();
expect(rows).toEqual([
{ name: "a", email: "unknown@example.com" },
{ name: "b", email: "b@example.com" },
]);
});
});Queries on db wait while the transaction is open, so check the results after transaction().execute() returns, or query through trx inside it — a query on db from inside the transaction waits on itself and never finishes.
Pass nested field values as JavaScript objects or arrays of objects, without JSON.stringify.
When the migration was generated with kyselyTypePlugin({ temporal: true }), its db.ts types date and datetime fields as Temporal.PlainDate and Temporal.Instant, and top-level time fields as Temporal.PlainTime; nested time fields remain strings. Deploy runs the script with those values. Create the instance with createKyselyPGlite<Unmigrated<Database>>(pglite, { temporal: true }) so PGlite reads top-level temporal columns back the same way; the scaffold adds the option for such migrations. Run the test in the tailor-runtime Vitest environment, which provides Temporal. A migration generated before temporal was enabled still runs with Date values on deploy, so its test leaves the option out. A migration generated with kyselyTypePlugin({ decimal: true }) types its decimal columns as Decimal and runs with Decimal values on deploy; its test creates the instance with createKyselyPGlite<Unmigrated<Database>>(pglite, { decimal: Decimal }), where Decimal comes from @tailor-platform/sdk/runtime, and the scaffold adds the option and the import. As in the Kysely mock scaffold, the test calls applyDateRepresentation with the migration's recorded defaultDateRepresentation (or "string") so t date fields parse the way they do on deploy; a migration recorded under "temporal" likewise needs the tailor-runtime environment for Temporal. Generated migration types use Record<string, unknown> for each nested object so scripts can work with both old and new members during a migration; narrow member values before using them.
Two caveats keep this from replacing a scratch workspace:
- PGlite runs full PostgreSQL, while TailorDB supports a subset of it — a statement that passes here can still be rejected on deploy.
db.pglite.tsmirrors the column shape, not the platform: hooks, validations, and permissions do not run, and the limits listed under Real SQL execution with PGlite apply.
Testing a multi-step script
runMigrationSteps from @tailor-platform/sdk/vitest runs a script's steps in the order tailor deploy runs them, each through the transaction callback you pass, so a test can check what a failing step leaves behind. When a step throws, it rejects with a MigrationStepError naming the failed step and the steps that completed before it. With pglite and Database set up as in the PGlite test above:
typescript
import {
createKyselyPGlite,
runMigrationSteps,
type Unmigrated,
} from "@tailor-platform/sdk/vitest";
import { steps } from "./migrate";
const db = createKyselyPGlite<Unmigrated<Database>>(pglite);
test("backfills every table", async () => {
await runMigrationSteps(steps, {
transaction: (run) => db.transaction().execute(run),
env: { STAGE: "test" },
});
// assert the rows
});tailor tailordb migration script <N> --with-test writes both test scaffolds against steps when migrate.ts exports steps, calling runMigrationSteps instead of main.
To test one step on its own, call its run with a transaction — and a { env } context when the step takes one: await db.transaction().execute((trx) => steps.backfillInvoice.run(trx)). With createKyselyMock, pass transaction: (run) => mock.withTx(run).
Beyond unit tests
A unit test verifies which statements the script issues; a PGlite test verifies what they do to the rows you staged. Neither runs against your actual data. To cover that:
- Run
migration generateon a clean working copy first, reviewdiff.json, then run again after editing tables to ensure the diff matches what you intended. - For non-trivial migrations, apply against a scratch workspace before promoting to staging or production.