Zero-downtime PostgreSQL migrations¶
sqlty breaking --against origin/main
A migration can be compatible with every query and still take the site down: an
ALTER TABLE that waits for a lock queues every query behind it, and one that
rewrites the table holds that lock until each row is copied. With the postgres
dialect, sqlty breaking judges each statement of
your migrations that the --against baseline does not have, before it runs. It
reads the files only: no database, no migration tool.
An example¶
against.sql is the schema the baseline ends with, the statements below are the
new migration:
against.sql:
CREATE TABLE users (id BIGINT PRIMARY KEY, email TEXT NOT NULL);
CREATE TABLE orders (id BIGINT PRIMARY KEY, user_id BIGINT NOT NULL, total NUMERIC NOT NULL);
``sql migration
SET lock_timeout = '2s';
-- error: [add-required-column] "addingplanas NOT NULL without a DEFAULT fails whenusershas rows: add it nullable or with a default"
ALTER TABLE users ADD COLUMN plan TEXT NOT NULL;
-- error: [constraint-scan] "adding the constraint checks every row oforderswhile it blocks writes: add itNOT VALID, thenVALIDATE CONSTRAINTit"
ALTER TABLE orders ADD CONSTRAINT orders_user FOREIGN KEY (user_id) REFERENCES users (id);
-- error: [unbatched-backfill] "changes every matching row ofordersin one statement: it holds their row locks and grows the WAL until it ends; change them in batches by key,WHERE id IN (SELECT id ... LIMIT 5000)`"
UPDATE orders SET total = 0;
The fixes keep each lock short: add the column with a default, add the foreign
key `NOT VALID` and validate it in a second statement, which lets writes through,
and backfill in batches.
```sql migration
SET lock_timeout = '2s';
-- error:
ALTER TABLE users ADD COLUMN plan TEXT NOT NULL DEFAULT 'free';
ALTER TABLE orders ADD CONSTRAINT orders_user FOREIGN KEY (user_id) REFERENCES users (id) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_user;
UPDATE orders SET total = 0 WHERE id BETWEEN 1 AND 10000;
The rules¶
Locks that stop the table. A statement that blocks writes, or reads too, for as long as it runs:
| Rule | Reports |
|---|---|
missing-concurrently |
an index built or dropped without CONCURRENTLY |
table-rewrite |
a statement that rewrites the table: a volatile default, a type change that is not binary coercible, VACUUM FULL |
constraint-scan |
a constraint, SET NOT NULL or a new partition that checks every row while it blocks writes |
missing-lock-timeout |
a lock that blocks writes taken before SET lock_timeout |
multi-table-lock |
a transaction that locks several tables against writes |
locked-backfill |
an UPDATE or DELETE of a table its transaction locked |
unbatched-backfill |
an UPDATE or DELETE whose WHERE does not bound its rows |
Statements that fail. PostgreSQL rejects them on a table with rows, or in a transaction:
| Rule | Reports |
|---|---|
add-required-column |
a NOT NULL column without a default |
concurrently-in-transaction |
CONCURRENTLY or VACUUM between BEGIN and COMMIT |
enum-value-in-transaction |
an enum value used in the transaction that added it |
concurrent-index-if-not-exists |
CREATE INDEX CONCURRENTLY IF NOT EXISTS, which skips an invalid index a failed build left |
Data and replication. Statements that do more than they say:
| Rule | Reports |
|---|---|
truncate-cascade |
TRUNCATE ... CASCADE |
disable-trigger-all |
DISABLE TRIGGER ALL, which turns off foreign key checks |
drop-primary-key |
a dropped primary key or REPLICA IDENTITY NOTHING, leaving a table without a replica identity |
rerun-backfill |
an INSERT ... SELECT without ON CONFLICT, which fails or duplicates rows when run again |
dropped-delete-action |
a dropped foreign key with ON DELETE or ON UPDATE CASCADE, SET NULL or SET DEFAULT |
backfill-without-writer |
a backfill of a column that a query of the new code inserts into the table without, or leaves stale |
A dropped or renamed column is not a rule of its own: sqlty breaking reports it
where a query of the other revision still reads it. See
Breaking schema changes.
What the schema tells it¶
A linter that sees one migration file can't tell an empty table from one with a
billion rows, or a varchar column from an integer one. sqlty breaking knows
the schema each statement changes, from the baseline:
- Only new statements are judged. The migrations that already ran are never
reported again, and need no
ignorecomment. - A table the new statements create is empty: locking it is harmless until rows
are copied into it with
INSERT ... SELECT,COPY ... FROM,MERGEorCREATE TABLE ... ASwithoutWITH NO DATA. - A type change is judged by the column's current type:
varchar(50)totext, ornumeric(5, 2)tonumeric(9, 2), is metadata only;integertobigintrewrites the table. SET NOT NULLis not reported when a validatedCHECK (col IS NOT NULL)already proves it.
add-required-column, concurrently-in-transaction and
enum-value-in-transaction are errors by default, so sqlty breaking fails on
them; the others warn. To fail CI on every one, raise them for your migrations:
[[tool.sqlty.overrides]]
include = ["migrations/**"]
[tool.sqlty.overrides.rules]
missing-concurrently = "error"
table-rewrite = "error"
constraint-scan = "error"
Severities, -- sqlty: ignore[rule] comments and [tool.sqlty.overrides] work as for
every other rule. Migrations that lock tables
covers which files are read and how each database of a configuration is judged.
Where the migrations come from¶
schema names the files sqlty breaking reads. Point it at your SQL
migrations, or at the SQL your migration tool writes for them:
| Tool | Schema files |
|---|---|
| Plain SQL, Flyway | the migration directory |
| Alembic | the output of alembic upgrade head --sql; see the Alembic recipe |
A pg_dump --schema-only dump |
not judged: it describes the result, not the steps |
Schema changes in CI shows how to
run sqlty breaking on every pull request.
Other migration linters¶
SQLTy vs Squawk, SQLTy vs MigrationPilot and SQLTy vs pgdeadbolt compare these rules with dedicated PostgreSQL migration linters.
Sources¶
- PostgreSQL:
ALTER TABLEnotes and explicit locking