Nov 23, 20268 min read

How to Test Database Migrations Before They Reach Production

The ways a database migration fails in production, and how to catch each one before deploy: replaying the full migration chain from an empty database, running migrations against realistic data, checking locks, and testing the code against the migrated schema, with a Go example.

Illustration for How to Test Database Migrations Before They Reach Production

A migration that worked on your laptop can still take down production. Locally the table has a dozen rows, so a new UNIQUE constraint finishes instantly, while in production it fails on duplicates or holds a lock that queues every write.

This guide covers the checks that test a migration against production conditions, and which of them are worth automating.

How do you test database migrations?

Test a migration in four ways: replay the whole chain from an empty database, run the new migration against realistic data, check the locks it takes, and run the application's tests against the migrated schema. Each check catches a different failure, and the first and last are cheap enough to run on every pull request.

CheckWhat it catchesWhere it runsCost
Replay from emptyBroken SQL, out-of-order files, migrations that only worked on someone's drifted databaseCI on every pull requestSeconds
Tests against the migrated schemaCode that reads a column the migration renamed or droppedCI on every pull requestYour test suite
Apply to realistic dataConstraints that existing rows violate, slow backfillsA staging copy or a preview environmentMinutes, plus keeping the copy fresh
Lock reviewStatements that block reads or writes on large tablesCode review, a migration linter, lock_timeoutLow

Why replay every migration from an empty database?

A developer's local database has been migrated one step at a time, edited by hand during debugging, and sometimes migrated from a branch that was later abandoned, so a migration that applies cleanly there may depend on state that exists nowhere else. Creating an empty database and applying every migration in order is the only way to prove that the files in the repository produce the schema the code expects.

The replay also catches the dull mistakes, such as two pull requests that both add a migration numbered 7 or a file that references a table created in a later migration. Run it in CI against the same major version of Postgres that production runs.

How do you test a migration against existing data?

Most production failures depend on data that an empty database does not have, such as duplicate emails that block a new UNIQUE index, NULL values in a column you are about to mark NOT NULL, or a backfill UPDATE that touches every row. To catch them, apply the new migration to a copy of a database with realistic data and time it.

A staging database that mirrors production's shape works if it is refreshed often, and a scrubbed copy of production gives the most accurate timing. Postgres runs most DDL inside a transaction, as the Postgres wiki's page on transactional DDL describes, so a migration wrapped in one transaction that fails halfway rolls back completely instead of leaving the schema half changed.

How do you check whether a migration will lock a table?

Read each statement against the lock it takes, using the ALTER TABLE reference, which lists the lock level for each subcommand and shows that most of them take an ACCESS EXCLUSIVE lock that blocks reads and writes on the table until the transaction ends. Adding a nullable column without a volatile default is quick, while adding a CHECK constraint scans the whole table unless you add it as NOT VALID and validate it in a later step.

Setting lock_timeout at the top of a migration makes it fail fast instead of waiting behind a long-running query and blocking everything queued behind it. Migration linters such as Squawk flag risky statements in pull request review, and the expand and contract pattern splits a breaking change into steps that are each safe to deploy.

Do you need to test down migrations?

Down migrations are useful while you iterate locally, and they rarely help in production, since a down migration that drops a column also drops every value written to it since the deploy. Most teams roll forward with a new migration that fixes the problem, which only works if each migration is small and the team can ship a fix quickly.

If you do keep down migrations, test them the same way as up migrations, by applying up, then down, then up again on a database with data, since a down migration that has never run is unlikely to work the first time someone needs it.

How does Encore test migrations?

Encore

Encore brings infrastructure from code, so a service's database and its migrations directory are declared next to the code that queries them, and every place that database exists gets the same migrations applied in order. encore run starts Postgres locally and applies pending migrations, encore test applies the full chain to a separate test cluster before your tests run, and a failed migration in a cloud deployment is rolled back and aborts the deploy, as the database docs describe.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

The first migration creates the table, and the second adds a status column in three steps, so existing rows get a value before the column becomes required:

-- accounts/migrations/1_create_accounts.up.sql CREATE TABLE accounts ( id BIGSERIAL PRIMARY KEY, email TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT now() );

The second migration sets a short lock timeout, backfills, and only then adds the constraints:

-- accounts/migrations/2_add_status.up.sql SET lock_timeout = '5s'; ALTER TABLE accounts ADD COLUMN status TEXT; UPDATE accounts SET status = 'active' WHERE status IS NULL; ALTER TABLE accounts ALTER COLUMN status SET DEFAULT 'active'; ALTER TABLE accounts ALTER COLUMN status SET NOT NULL; ALTER TABLE accounts ADD CONSTRAINT accounts_status_check CHECK (status IN ('active', 'suspended', 'closed'));

This runs in one step on a small table, while on a table with millions of rows you would split the backfill into batches and add the constraint as NOT VALID with a separate VALIDATE CONSTRAINT migration, so no single statement holds the table for long. The service reads and writes the new column:

// accounts/accounts.go package accounts import ( "context" "encore.dev/storage/sqldb" ) // Migrations in ./migrations are applied in order wherever this database exists. var db = sqldb.NewDatabase("accounts", sqldb.DatabaseConfig{ Migrations: "./migrations", }) type CreateParams struct { Email string `json:"email"` } type Account struct { ID int64 `json:"id"` Email string `json:"email"` Status string `json:"status"` } //encore:api public method=POST path=/accounts func Create(ctx context.Context, p *CreateParams) (*Account, error) { a := &Account{Email: p.Email} err := db.QueryRow(ctx, ` INSERT INTO accounts (email) VALUES ($1) RETURNING id, status`, p.Email).Scan(&a.ID, &a.Status) if err != nil { return nil, err } return a, nil } type StatusParams struct { Status string `json:"status"` } //encore:api public method=PUT path=/accounts/:id/status func SetStatus(ctx context.Context, id int64, p *StatusParams) error { _, err := db.Exec(ctx, `UPDATE accounts SET status = $1 WHERE id = $2`, p.Status, id) return err }

The test calls the endpoints against the migrated schema and checks that the constraint from the second migration is in place, which fails if the migration and the code disagree:

// accounts/accounts_test.go package accounts import ( "context" "testing" ) func TestMigratedSchema(t *testing.T) { ctx := context.Background() acct, err := Create(ctx, &CreateParams{Email: "migration-test@example.com"}) if err != nil { t.Fatalf("create: %v", err) } if acct.Status != "active" { t.Fatalf("new accounts should default to active, got %q", acct.Status) } if err := SetStatus(ctx, acct.ID, &StatusParams{Status: "suspended"}); err != nil { t.Fatalf("suspend: %v", err) } // The CHECK constraint added in 2_add_status.up.sql must reject unknown values. if err := SetStatus(ctx, acct.ID, &StatusParams{Status: "deleted"}); err == nil { t.Fatal("expected the status check constraint to reject an unknown status") } }

encore test ./... sets up the test databases in a separate cluster, applies every migration and runs the tests against them, with fsync skipped and an in-memory filesystem so the run stays fast, and et.NewTestDatabase gives a single test its own database, cloned from a fully migrated template, when it needs isolation. Running it in CI covers the replay from empty and the code check on every pull request.

For the data-dependent failures, preview environments, available once the app is linked to GitHub, can give each pull request's database a copy of another environment's database, such as staging, chosen in the Platform Dashboard, so the preview starts from existing rows instead of an empty database. The copy uses Neon's database branching, so it requires Neon as the database provider, and a migration that fails during a cloud deployment is rolled back and the deploy is aborted. Encore records the applied version in the schema_migrations table, and applies only up migrations, so a fix after a bad migration is a new migration.

The database and its migrations are declared in the code a coding agent is already editing, so an agent that writes a migration can run encore test in the same session and see the migrated schema pass or fail against the code it changed, without access to a shared database.

Best fit: Teams that want every pull request to prove its migrations apply cleanly and match the code before deploy, on AWS or GCP.

Frequently asked questions

How do you test a database migration?

Apply the full migration chain to an empty database in CI and run your integration tests against the result, then apply the new migration to a copy of realistic data, such as a staging copy, to catch failures that depend on existing rows. Check that each migration takes only short locks before it runs against a busy table.

Why does a migration pass locally and fail in production?

The local database is usually empty or small, while production is not. A migration that adds a UNIQUE constraint or sets a column NOT NULL succeeds on a fresh database and fails on production rows that violate it, and an ALTER TABLE that finishes instantly on ten rows can hold a lock for minutes on ten million.

Should migrations have down migrations?

No. Down migrations help in development, but they rarely save a production deploy, since a down migration that drops a column also drops the data written to it. Most teams roll forward with a new migration instead, and keep each migration small enough that rolling forward is quick.

How do I test migrations with Encore?

Run encore test, which creates the test databases and applies every migration in the service's migrations directory before the tests run, so your tests call the endpoints against that schema. If a migration fails during a cloud deployment, Encore rolls it back and aborts the deploy.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders