How to Test Database Migrations
Test migrations on the real engine: fresh installs, upgrades, backfills, lock behavior, rollback, and CI matrices that catch production surprises.
On this page
Introduction
A database migration is production code that changes state. It can lock a table or rewrite millions of rows. Yet teams often test them only once on an empty development database, exercising none of the risks. A migration that applies instantly to ten rows can take the table offline for ten minutes at scale.
Testing migrations means testing the transition: from the previous release with real data, under concurrent writes, with the same engine and privileges, and with a plan for failure. This article covers what to test, how to test on the real database, and what to automate.
What Migration Tests Must Cover
Start with the risks the specific migration creates. A new nullable column is usually low risk; adding a NOT NULL constraint to a large table is not. A backfill that updates every row needs a different test from an index addition. A rename that breaks old app instances needs expand-and-contract, not one happy-path test.
A useful baseline covers applying all migrations to an empty database, upgrading a fixture that represents the previous release, re-running the tool without changes, verifying constraints reject invalid data, checking backfill correctness and idempotence, testing old and new application versions during a rolling deploy, and measuring lock behavior under production-like load. Also test permissions: the production role may not be a superuser and may lack CREATE EXTENSION.
Test Against the Real Database Engine
SQLite and the production database are not interchangeable. They differ in ALTER TABLE, constraint validation, locking, transaction isolation, and index creation. Use a disposable instance of the same engine and major version as production, with the same extensions and a role matching production privileges.
Apply migrations through the real tool when its behavior matters. Flyway, Liquibase, Prisma Migrate, Alembic, and Rails migrations differ in transaction handling, checksums, and repair commands. Replaying SQL by hand does not test the tool that runs in production. The test below applies SQL directly; adapt it if your tool owns the history table.
import { readdir, readFile } from "node:fs/promises";
import { Client } from "pg";
import { afterAll, beforeAll, expect, test } from "vitest";
const db = new Client({ connectionString: process.env.TEST_DATABASE_URL });
beforeAll(async () => {
await db.connect();
await db.query("DROP SCHEMA public CASCADE; CREATE SCHEMA public;");
const files = (await readdir("migrations"))
.filter((file) => file.endsWith(".sql"))
.sort();
for (const file of files) {
await db.query(await readFile(`migrations/${file}`, "utf8"));
}
});
afterAll(() => db.end());
test("currency is required after the upgrade", async () => {
const { rows } = await db.query(
`SELECT is_nullable FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'orders' AND column_name = 'currency'`,
);
expect(rows).toEqual([{ is_nullable: "NO" }]);
});
Seed realistic data, not one row. Include nulls, boundary values, orphaned references, and the largest rows the schema permits. Those rows break backfills and constraints. Isolate each test database or schema so parallel workers cannot interfere with migration history.
Upgrades, Rollbacks, and Rehearsals
An empty-database test proves that migrations compose; an upgrade test proves they work on the state production is in. Keep a fixture of the previous release schema and representative data, apply the new migrations, and assert schema and data. A schema-only dump is not enough, because backfills depend on rows.
Rollback deserves honesty. Many tools generate a down script, but dropping a column also drops its data. Test rollback where it is supported and data-preserving; for destructive migrations, test restore from backup and a roll-forward plan. A down migration that runs but leaves data missing is false confidence.
Rehearse on a sanitized production clone when the change is risky. Measure how long the migration holds locks and whether the application stays healthy. Set lock_timeout and statement_timeout so a migration fails fast rather than queueing behind a long transaction and blocking every query that needs the same lock.
Backfills, Constraints, and Lock Behavior
Large changes should be split into expand and contract phases: add a nullable column, deploy code that writes both, backfill in batches, validate the constraint, switch reads, then remove the old column. Test each phase with the application version that runs during it. Testing only the final schema misses the rolling-deploy window.
Backfills must be keyset-paginated, idempotent, and safe to restart. Update only rows that still need it, commit small batches, and throttle so replication and traffic survive. Test that two runs produce the same result, that a restart does not skip rows, and that concurrent writes are not overwritten with stale values.
-- Validate existing rows without holding an exclusive lock for the full scan.
ALTER TABLE orders ADD CONSTRAINT orders_total_positive
CHECK (total_cents > 0) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_total_positive;
-- Create indexes without blocking writes; this cannot run inside a transaction.
CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);
Lock behavior varies by engine and version. Adding a column with a non-volatile default is metadata-only in PostgreSQL 11 and later, but older versions rewrite the table. CREATE INDEX CONCURRENTLY cannot run inside a transaction and can leave an invalid index after failure, so test failure and re-run. A validated CHECK lets PostgreSQL skip a full scan when setting NOT NULL, but that optimization is version-dependent. Test the version you deploy.
CI and Failure Modes
Run migrations in CI against an ephemeral database: fresh install, upgrade fixture, integration tests, and a second no-op run. Use the least-privilege production role, not the container superuser. Run the matrix if multiple versions are supported; otherwise pin production’s. Keep logs from failures so CI reproduces the 2 a.m. error.
Common failures are predictable. Empty-database tests miss backfill and constraint problems. SQLite tests miss engine-specific locking. Non-deterministic functions such as now() make assertions flaky unless you inject a clock or assert ranges. A backfill that times out halfway may duplicate work. Tools that wrap everything in a transaction break CREATE INDEX CONCURRENTLY. A restore can bring back data without matching migration history. Branch merges can produce duplicate versions, and manual hotfixes create drift no test database knows about.
CI is also where slow tests get skipped. Keep fast install and upgrade checks on every pull request, and run production-scale rehearsals on a schedule. A skipped test provides no signal, and a laptop-only test is not a gate.
A Practical Matrix and Its Limits
A workable matrix is: apply from scratch; upgrade the previous release fixture; re-run for a no-op; verify constraints reject invalid rows; run the backfill twice and check counts and checksums; run old and new app versions against the intermediate schema; assert failure within lock_timeout under a conflicting lock; and restore a backup, then verify schema, data, and migration history. Add timing for migrations that touch large tables.
No test suite can prove zero downtime. Lock duration depends on hardware, load, vacuum state, and data distribution, so measure on a production-like environment and leave margin. Treat the migration suite as part of the release contract: when a migration changes, its tests change with it, and a failure blocks the deploy rather than becoming an incident.
Sources: PostgreSQL: ALTER TABLE, PostgreSQL: CREATE INDEX, Prisma: Migrate.
FAQ
- Why not test migrations against SQLite?
- SQLite does not reproduce PostgreSQL or MySQL locking, ALTER TABLE behavior, constraint validation, or transaction semantics. A migration that passes on SQLite can still take a table lock for minutes in production.
- Should every migration have a rollback test?
- Test rollback when the down migration is genuinely supported and preserves data. Many production changes are irreversible, such as dropping a column; for those, test backup and restore and a roll-forward plan instead of pretending a down script is safe.
- How much production data should the test use?
- Use enough rows to expose full-table scans, lock duration, and backfill batching problems. A sanitized snapshot or a generated data set at production scale is more useful than ten rows, but keep it small enough to run on every pull request.
Report a problem with this articleOpens a pre-filled issue on GitHub.