QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Database structure

How do you test database migrations?

A migration is tested by comparing the state before and after on data close to production. On an empty database NOT NULL, UNIQUE and foreign keys prove nothing. The comparison covers counts by group, values (including NULLs of source columns), how new columns are filled for old rows, rollback, re-run, duration and locking. A migration already applied to production is fixed by a new one, not edited.

SQL · Constraints and indexes

The migration passed on an empty dev database and failed on staging. What should have been checked?

A developer adds a column status NOT NULL. On the empty local database the migration passes and CI is green. On a staging with real data it fails, and had it passed it could have silently damaged the data. A migration changes a schema or data that already exists, so it is tested differently from a new feature: you compare the state before and after. The lesson is about what exactly to compare and where migrations break.

How it works and why. A migration is a versioned script (Flyway, Liquibase, Prisma Migrate, Alembic, Django or Rails migrations) that runs once on every environment and is recorded in a service table. Two consequences follow. First: on the same script, environments differ by data, so the result on an empty database proves nothing. Second: a migration already applied in production is not edited but corrected by a new one. PostgreSQL runs most DDL in a transaction, so a failed migration usually rolls back whole, but long locks and things done outside a transaction (for example CREATE INDEX CONCURRENTLY) do not have that.

The order of testing a migration

1. Snapshot beforecounts, group sums, NULLs2. Migrate upon a copy close to production3. Comparethe same queries: what changed, what did not4. The applicationold records open and save5. Roll back and up againstate without loss, a clean rerun
Figure 1. A snapshot before the migration gives something to compare with: without it "it matches" cannot be proved.

Example 1: NOT NULL on existing data.

ALTER TABLE transactions ADD COLUMN status text NOT NULL;
-- ERROR:  column "status" of relation "transactions"
--         contains null values
-- on an empty dev database the migration passes

The safe sequence splits the change into three steps: add nullable, backfill old rows, only then set the constraint.

-- 1) add nullable, 2) backfill, 3) make mandatory
ALTER TABLE transactions ADD COLUMN status text;

UPDATE transactions
SET status = CASE WHEN is_failed THEN 'failed' ELSE 'completed' END;

ALTER TABLE transactions ALTER COLUMN status SET NOT NULL;

Example 2: a data migration and NULL. The backfill looks right, but there is a trap. The column is_failed is boolean and in ten rows it is: two true, seven false and one NULL.

-- before: 10 rows; is_failed: true = 2, false = 7, NULL = 1
-- after the migration:
SELECT status, COUNT(*) FROM transactions GROUP BY status ORDER BY status;
-- completed | 8
-- failed    | 2

-- the row with is_failed = NULL became completed: ELSE caught the NULL
SELECT COUNT(*) FROM transactions
WHERE status = 'completed' AND is_failed IS NULL;  -- 1

CASE WHEN NULL does not fire (the condition is unknown), so the row goes to ELSE and gets "completed": 7 + 1 gives 8 completed and 2 failed. The group counts agree on the total (10), but in substance a payment with an unknown outcome became successful. That is why besides counts you check values per group and the NULLs of the source columns.

What to check, in short:

  • Counts: rows, and per group, before and after; any difference must be explained.
  • Values: sums and selected rows, especially with NULL, empty, the largest values.
  • New columns: what the old rows hold: NULL, DEFAULT or a computed value.
  • Constraints and indexes: new NOT NULL, UNIQUE, foreign keys did not fail on old data.
  • Application: old records open, edit and save.
  • Rollback: the down migration restores the state without loss; dropping a column loses its data for good.
  • Time and locks: duration on a volume close to production.

Limits and alternatives. Duration and locking depend on the operation. In PostgreSQL 11+ adding a column with a constant DEFAULT is fast and does not rewrite the table, while a volatile default (a random value, for instance) does rewrite it. ALTER COLUMN SET NOT NULL scans the table under a strong lock; on a large table the safer route is CHECK (status IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT under a weaker lock, after which SET NOT NULL skips the full scan. Indexes on a live table are built with CONCURRENTLY. Large data migrations use batched updates to avoid one long transaction. All this can be tested only on a copy with real volume; for personal data it is anonymised. The check "the application works with the old schema" is needed during deployment too, when old and new code versions share one database for a while.

Common mistakes.

  • Testing only on an empty database: NOT NULL, UNIQUE and foreign keys show up only on data.
  • Comparing only the total row count: values may change while the count is kept.
  • Not recording the "before" state: later there is nothing to compare with.
  • Checking "up" and not "down" and the rerun.
  • Treating rollback as safe: a down migration that drops a column loses data.

Check yourself

A migration fills status with CASE WHEN is_failed THEN 'failed' ELSE 'completed' END. In 1 of 10 rows is_failed = NULL. What happens and how to find it?

Answer

NULL gives UNKNOWN, the WHEN condition does not fire and the row gets "completed". It is found by a query for rows where status = 'completed' and the source field IS NULL; total counts will not show it. It is a question for requirements: what to do with an unknown outcome, usually not "completed".

Why does the migration "ADD COLUMN … NOT NULL" without DEFAULT pass on an empty database and fail on staging?

Answer

An empty table has no rows that would lack the new value. On staging the existing rows would get NULL, violating NOT NULL, so the database refuses. So migrations are tested on data close to production and the change is split into "add nullable, backfill, set NOT NULL".

In an interview. Junior: For migrations I compare the state before and after: row counts and group checksums must match. I check how new columns were filled for old records and whether the application works with old data. Middle/Senior: I test on a copy with the volume and shape of production data, because NOT NULL, UNIQUE and NULL traps show only there. I look not only at counts but at values per group and the NULLs of source columns, check the rollback and a rerun, and measure the duration and table locks.

More articles in this chapter