Chapter 19 — Renovating While Open#
Schema changes planned into lock-friendly steps, applied while the lobby stays open.
plan_migration()sync_schema()check_drift()CONCURRENTLYNOT VALIDexamples/108_online_migrations.pyLaunch Day, 12:00. The lobby is packed with arriving elephants, and hardware engineering just delivered the new RFID badge scanners.
Management: "Add a unique rfid_tag and a positive tusk_span_cm check to dorm_badge right now — WITHOUT blocking live check-ins!"
Panda: Easy! Run ALTER TABLE dorm_badge ADD COLUMN ... UNIQUE CHECK (...) right in production! Wait… why did every checkout request just hang?
Ferris: Because a plain CREATE UNIQUE INDEX or ADD CONSTRAINT CHECK takes an ACCESS EXCLUSIVE or SHARE lock across the entire table scan! Plan it into online-safe steps instead.
The mission#
Schema changes under live traffic are where careless DDL causes outages. pgdorm.migrate (pgm) inspects the live PostgreSQL catalog, diffs it against your Python tables, flags destructive hazards, and expands changes into lock-friendly online steps:
- create the initial
dorm_badgetable and record migration0001_initin_pgdorm, - prove idempotency (
replan.is_empty == True) and zero catalog drift (check_drift().in_sync == True), - evolve
V1.DormBadge→V2.DormBadgeusingCREATE UNIQUE INDEX CONCURRENTLY,ADD CONSTRAINT … NOT VALID, andVALIDATE CONSTRAINT— keeping every live row and every lobby request moving.
The Panda's plan
Run naive blocking ALTER TABLE statements at noon: ADD CONSTRAINT ... CHECK (...) holds an ACCESS EXCLUSIVE lock while scanning every row on disk, queuing every incoming SELECT, INSERT, and UPDATE behind it until connection pools time out.
1. Two versions of the same table#
Here is V1.DormBadge alongside V2.DormBadge (adding rfid_tag with a unique index and tusk_span_cm with a CHECK constraint):
class V1:
class DormBadge(pg.Table):
dorm_badge_id: pg.Col[int] = pg.pk(default=pg.identity())
code: pg.Col[str] = pg.col(unique=True)
holder_name: pg.Col[str] = pg.col()
class V2:
class DormBadge(pg.Table):
dorm_badge_id: pg.Col[int] = pg.pk(default=pg.identity())
code: pg.Col[str] = pg.col(unique=True)
holder_name: pg.Col[str] = pg.col()
rfid_tag: pg.Col[str | None] = pg.col(default=None, unique=True)
tusk_span_cm: pg.Col[int | None] = pg.col(default=None)
@classmethod
def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
return (pg.Check(cls.tusk_span_cm.is_null() | (cls.tusk_span_cm > 0)),)
2. Plan, inspect hazards, apply online, and verify zero drift#
All migration primitives live in pgdorm.migrate (intentionally separated from the runtime query surface on root pgdorm):
async def evolve_schema_online(pool: pg.Pool) -> None:
# 1. Initial schema sync creates `dorm_badge` and records the migration in `_pgdorm`.
rec1 = await pgm.sync_schema(pool, (V1.DormBadge,), name="init_badges", version="0001_init")
assert rec1 is not None
print(f"applied {rec1.version}: status={rec1.migration_status_id.name}")
# => applied 0001_init: status=APPLIED
# Golden rule of schema diffing: immediate re-plan produces zero ops and zero drift.
replan = await pgm.plan_migration(pool, (V1.DormBadge,))
drift1 = await pgm.check_drift(pool, tables=(V1.DormBadge,))
print(f"v1 idempotent={replan.is_empty} in_sync={drift1.in_sync}")
# => v1 idempotent=True in_sync=True
# Seed live production data before evolving v1 -> v2.
await pool.execute(
pg.insert(V1.DormBadge).values(V1.DormBadge(code="BADGE-01", holder_name="Jumbo Kalahari"))
)
# 2. Plan v1 -> v2 online: inspects hazards and expands into online-safe steps
# (CREATE UNIQUE INDEX CONCURRENTLY + ADD CHECK NOT VALID + VALIDATE CONSTRAINT).
plan_v2 = await pgm.plan_migration(
pool,
(V2.DormBadge,),
name="add_rfid_and_tusk",
version="0002_v2_online",
)
sqls = [step.sql for step in plan_v2.steps if step.sql]
has_concurrent_idx = any("CREATE UNIQUE INDEX CONCURRENTLY" in s for s in sqls)
has_not_valid = any("NOT VALID" in s for s in sqls)
has_validate = any("VALIDATE CONSTRAINT" in s for s in sqls)
print(
f"v2 plan: destructive={plan_v2.has_destructive}, "
f"concurrent_idx={has_concurrent_idx}, not_valid={has_not_valid}, validate={has_validate}"
)
# => v2 plan: destructive=False, concurrent_idx=True, not_valid=True, validate=True
rec2 = await pgm.sync_schema(
pool,
(V2.DormBadge,),
name="add_rfid_and_tusk",
version="0002_v2_online",
)
assert rec2 is not None
drift2 = await pgm.check_drift(pool, tables=(V2.DormBadge,))
print(f"applied {rec2.version}: in_sync={drift2.in_sync}")
# => applied 0002_v2_online: in_sync=True
# Existing row survived the online migration intact and accepts the new columns.
upgraded = await pool.one(
pg.update(V2.DormBadge)
.set(rfid_tag="RFID-JUMBO", tusk_span_cm=185)
.where(V2.DormBadge.code == "BADGE-01")
.returning(V2.DormBadge)
)
print(
f"live row preserved: {upgraded.holder_name} "
f"({upgraded.rfid_tag}, {upgraded.tusk_span_cm}cm)"
)
# => live row preserved: Jumbo Kalahari (RFID-JUMBO, 185cm)
What just happened
pgm.sync_schema(pool, (V1.DormBadge,), ...)createsdorm_badgeand tracks0001_initin pgdorm's internal migration ledger (status=APPLIED).- Immediately re-planning against
V1.DormBadgereturnsis_empty=True, andpgm.check_drift(...)confirmsin_sync=True— the golden rule of trustworthy schema diffing. - When planning
V1.DormBadge→V2.DormBadge,pgm.plan_migration(...)automatically breaks the changes into PostgreSQL's zero-downtime choreography: ADD COLUMNfor nullable columns (metadata-only, though it still acquires a briefACCESS EXCLUSIVElock),CREATE UNIQUE INDEX CONCURRENTLY(builds the index without blocking reads or writes),ADD CONSTRAINT "badge_tusk_positive" CHECK (...) NOT VALID(metadata-only briefACCESS EXCLUSIVElock; enforces for all new writes immediately without scanning existing rows),VALIDATE CONSTRAINT "badge_tusk_positive"(scans existing rows under a lighterSHARE UPDATE EXCLUSIVElock so live traffic keeps flowing!).- Because even brief
ACCESS EXCLUSIVElocks queue behind long-running queries,pgdorm.migrateguards DDL execution with built-inlock_timeout="2s",statement_timeout="30s", and automatic lock-timeout retries (lock_retries=3onMigrationApp) so a migration never stalls your lobby. - Jumbo's live
BADGE-01row survives intact and immediately acceptsrfid_tag="RFID-JUMBO"andtusk_span_cm=185.
Ferris' basement: why CONCURRENTLY steps run outside transactions
PostgreSQL forbids CREATE INDEX CONCURRENTLY inside a BEGIN … COMMIT block. pgm.sync_schema() understands which migration steps are transactional and which must execute autocommit, orchestrating each step in order while keeping the _pgdorm migration ledger accurate.
What PostgreSQL actually received#
🔭 What PostgreSQL received: 176 statements in 90 round trips (captured live on PostgreSQL)
-- ── round trip 1 ──
SELECT
"pg_class"."oid",
"pg_class"."relname",
"pg_class"."relnamespace",
"pg_class"."relkind",
"pg_class"."relispartition",
"pg_class"."relam",
"pg_class"."relrowsecurity"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relkind" = ANY($2) AND "pg_class"."relispartition" = $3
ORDER BY "pg_class"."relname" ASC;
-- ── round trip 2 ──
SELECT "pg_class"."relname"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relname" = $2;
-- → 1 row
-- ── round trip 3 ──
SELECT
"migration_id",
"target_schema",
"version",
"parent_version",
"name",
"migration_mode_id",
"migration_status_id",
"checksum",
"ops_json",
"schema_snapshot",
"locked_by",
"lease_expires_at",
"started_at",
"finished_at",
"duration_ms",
"error_detail"
FROM "_pgdorm"."migration"
WHERE "target_schema" = $1 AND "migration_status_id" = $2
ORDER BY "migration_id" DESC
LIMIT $3;
-- ── round trip 4 ──
SELECT
"pg_class"."oid",
"pg_class"."relname",
"pg_class"."relnamespace",
"pg_class"."relkind",
"pg_class"."relispartition",
"pg_class"."relam",
"pg_class"."relrowsecurity"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relkind" = ANY($2) AND "pg_class"."relispartition" = $3
ORDER BY "pg_class"."relname" ASC;
-- ── round trip 5 ──
SELECT "pg_class"."relname"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relname" = $2;
-- → 1 row
-- ── round trip 6 ──
SELECT
"migration_id",
"target_schema",
"version",
"parent_version",
"name",
"migration_mode_id",
"migration_status_id",
"checksum",
"ops_json",
"schema_snapshot",
"locked_by",
"lease_expires_at",
"started_at",
"finished_at",
"duration_ms",
"error_detail"
FROM "_pgdorm"."migration"
WHERE "target_schema" = $1 AND "migration_status_id" = $2
ORDER BY "migration_id" DESC
LIMIT $3;
-- ── round trip 7 · 2 statements pipelined ──
BEGIN;
SELECT pg_advisory_xact_lock(hashtext($1));
-- → 1 row
-- ── round trip 8 ──
SELECT "oid", "nspname"
FROM "pg_catalog"."pg_namespace"
WHERE "nspname" = $1;
-- → 1 row
-- ── round trip 9 ──
SELECT
"pg_class"."oid",
"pg_class"."relname",
"pg_class"."relnamespace",
"pg_class"."relkind",
"pg_class"."relispartition",
"pg_class"."relam",
"pg_class"."relrowsecurity"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relkind" = ANY($2) AND "pg_class"."relispartition" = $3
ORDER BY "pg_class"."relname" ASC;
-- → 8 rows
-- ── round trip 10 · 12 statements pipelined ──
SELECT
"attrelid",
"attnum",
"attname",
pg_catalog.format_type("atttypid", "atttypmod"),
"attnotnull",
"attidentity",
"attgenerated"
FROM "pg_catalog"."pg_attribute"
WHERE "attrelid" = ANY($1) AND "attnum" > $2 AND "attisdropped" = $3
ORDER BY "attrelid" ASC, "attnum" ASC;
-- → 46 rows
SELECT "adrelid", "adnum", pg_catalog.pg_get_expr("adbin", "adrelid")
FROM "pg_catalog"."pg_attrdef"
WHERE "adrelid" = ANY($1);
-- → 3 rows
SELECT
"conrelid",
"conname",
"contype",
"convalidated",
"conkey",
"confrelid",
"confkey",
"confdeltype",
"confdelsetcols",
"conindid",
pg_catalog.pg_get_constraintdef("oid"),
"condeferrable",
"condeferred"
FROM "pg_catalog"."pg_constraint"
WHERE "conrelid" = ANY($1) AND "conparentid" = $2 AND "contype" = ANY($3)
ORDER BY "conname" ASC;
-- → 54 rows
SELECT
"pg_index"."indrelid",
"pg_index"."indexrelid",
"idx_cls"."relname",
"pg_index"."indkey",
"pg_index"."indnatts",
"pg_index"."indnkeyatts",
"pg_index"."indisunique",
"pg_index"."indisprimary",
"pg_index"."indisvalid",
pg_catalog.pg_get_expr("pg_index"."indpred", "pg_index"."indrelid"),
"pg_am"."amname",
pg_catalog.pg_get_indexdef("pg_index"."indexrelid"),
"pg_index"."indoption"
FROM "pg_catalog"."pg_index"
INNER JOIN "pg_catalog"."pg_class" AS "idx_cls" ON "pg_index"."indexrelid" = "idx_cls"."oid"
INNER JOIN "pg_catalog"."pg_am" ON "idx_cls"."relam" = "pg_am"."oid"
WHERE "pg_index"."indrelid" = ANY($1) AND "pg_index"."indisprimary" = $2
ORDER BY "idx_cls"."relname" ASC;
-- → 17 rows
SELECT "partrelid", "partstrat", "partattrs"
FROM "pg_catalog"."pg_partitioned_table"
WHERE "partrelid" = ANY($1);
SELECT
"view_nsp"."nspname",
"view_cls"."relname",
"view_cls"."relkind",
"pg_depend"."refobjid",
"pg_depend"."refobjsubid"
FROM "pg_catalog"."pg_depend"
INNER JOIN "pg_catalog"."pg_rewrite" ON "pg_depend"."objid" = "pg_rewrite"."oid"
INNER JOIN "pg_catalog"."pg_class" AS "view_cls" ON "pg_rewrite"."ev_class" = "view_cls"."oid"
INNER JOIN "pg_catalog"."pg_namespace" AS "view_nsp" ON "view_cls"."relnamespace" = "view_nsp"."oid"
WHERE "pg_depend"."refobjid" = ANY($1) AND "pg_depend"."deptype" = $2 AND "view_cls"."relkind" = ANY($3) AND NOT ("view_nsp"."nspname" = ANY($4));
SELECT "oid", "extname", "extnamespace"
FROM "pg_catalog"."pg_extension"
ORDER BY "extname" ASC;
-- → 3 rows
SELECT "migration_mode_type_id", "code"
FROM "_pgdorm"."migration_mode_type"
ORDER BY "migration_mode_type_id" ASC;
-- → 3 rows
SELECT "migration_status_type_id", "code"
FROM "_pgdorm"."migration_status_type"
ORDER BY "migration_status_type_id" ASC;
-- → 4 rows
SELECT "migration_event_type_id", "code"
FROM "_pgdorm"."migration_event_type"
ORDER BY "migration_event_type_id" ASC;
-- → 7 rows
SELECT "hazard_level_type_id", "code"
FROM "_pgdorm"."hazard_level_type"
ORDER BY "hazard_level_type_id" ASC;
-- → 4 rows
SELECT "lock_mode_type_id", "code"
FROM "_pgdorm"."lock_mode_type"
ORDER BY "lock_mode_type_id" ASC;
-- → 5 rows
-- ── round trip 11 ──
COMMIT;
-- ── round trip 12 ──
UPDATE "_pgdorm"."migration"
SET
"migration_status_id" = $1,
"finished_at" = $2,
"error_detail" = $3
WHERE "target_schema" = $4 AND "migration_status_id" = $5 AND "lease_expires_at" < $6;
-- ── round trip 13 ──
INSERT INTO "_pgdorm"."migration" ("target_schema", "version", "parent_version", "name", "migration_mode_id", "migration_status_id", "checksum", "ops_json", "schema_snapshot", "locked_by", "lease_expires_at", "finished_at", "duration_ms", "error_detail")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
RETURNING "migration_id", "target_schema", "version", "parent_version", "name", "migration_mode_id", "migration_status_id", "checksum", "ops_json", "schema_snapshot", "locked_by", "lease_expires_at", "started_at", "finished_at", "duration_ms", "error_detail";
-- → 1 row
-- ── round trip 14 ──
INSERT INTO "_pgdorm"."migration_event" ("migration_id", "migration_event_type_id", "step_index", "duration_ms", "detail")
VALUES ($1, $2, $3, $4, $5);
-- → 1 affected
-- ── round trip 15 · 4 statements pipelined ──
BEGIN;
SELECT set_config($1, $2, true);
-- → 1 row
SELECT set_config($1, $2, true);
-- → 1 row
SELECT pg_advisory_xact_lock(hashtext($1));
-- → 1 row
-- ── round trip 16 ──
CREATE TABLE IF NOT EXISTS "dorm_badge" ("dorm_badge_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "code" TEXT NOT NULL, "holder_name" TEXT NOT NULL, CONSTRAINT "pk_xuvszepe" PRIMARY KEY ("dorm_badge_id"), CONSTRAINT "uq_ewnpzena" UNIQUE ("code"));
-- ── round trip 17 ──
COMMIT;
-- ── round trip 18 ──
INSERT INTO "_pgdorm"."migration_step" ("migration_id", "step_index", "op_kind", "target_table", "sql_text", "lock_mode_id", "hazard_level_id", "transactional", "migration_status_id", "duration_ms", "error_detail")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);
-- → 1 affected
-- ── round trip 19 ──
INSERT INTO "_pgdorm"."migration_event" ("migration_id", "migration_event_type_id", "step_index", "duration_ms", "detail")
VALUES ($1, $2, $3, $4, $5);
-- → 1 affected
-- ── round trip 20 ──
SELECT
"pg_class"."oid",
"pg_class"."relname",
"pg_class"."relnamespace",
"pg_class"."relkind",
"pg_class"."relispartition",
"pg_class"."relam",
"pg_class"."relrowsecurity"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relkind" = ANY($2) AND "pg_class"."relispartition" = $3
ORDER BY "pg_class"."relname" ASC;
-- → 1 row
-- ── round trip 21 · 7 statements pipelined ──
SELECT
"attrelid",
"attnum",
"attname",
pg_catalog.format_type("atttypid", "atttypmod"),
"attnotnull",
"attidentity",
"attgenerated"
FROM "pg_catalog"."pg_attribute"
WHERE "attrelid" = ANY($1) AND "attnum" > $2 AND "attisdropped" = $3
ORDER BY "attrelid" ASC, "attnum" ASC;
-- → 3 rows
SELECT "adrelid", "adnum", pg_catalog.pg_get_expr("adbin", "adrelid")
FROM "pg_catalog"."pg_attrdef"
WHERE "adrelid" = ANY($1);
SELECT
"conrelid",
"conname",
"contype",
"convalidated",
"conkey",
"confrelid",
"confkey",
"confdeltype",
"confdelsetcols",
"conindid",
pg_catalog.pg_get_constraintdef("oid"),
"condeferrable",
"condeferred"
FROM "pg_catalog"."pg_constraint"
WHERE "conrelid" = ANY($1) AND "conparentid" = $2 AND "contype" = ANY($3)
ORDER BY "conname" ASC;
-- → 5 rows
SELECT
"pg_index"."indrelid",
"pg_index"."indexrelid",
"idx_cls"."relname",
"pg_index"."indkey",
"pg_index"."indnatts",
"pg_index"."indnkeyatts",
"pg_index"."indisunique",
"pg_index"."indisprimary",
"pg_index"."indisvalid",
pg_catalog.pg_get_expr("pg_index"."indpred", "pg_index"."indrelid"),
"pg_am"."amname",
pg_catalog.pg_get_indexdef("pg_index"."indexrelid"),
"pg_index"."indoption"
FROM "pg_catalog"."pg_index"
INNER JOIN "pg_catalog"."pg_class" AS "idx_cls" ON "pg_index"."indexrelid" = "idx_cls"."oid"
INNER JOIN "pg_catalog"."pg_am" ON "idx_cls"."relam" = "pg_am"."oid"
WHERE "pg_index"."indrelid" = ANY($1) AND "pg_index"."indisprimary" = $2
ORDER BY "idx_cls"."relname" ASC;
-- → 1 row
SELECT "partrelid", "partstrat", "partattrs"
FROM "pg_catalog"."pg_partitioned_table"
WHERE "partrelid" = ANY($1);
SELECT
"view_nsp"."nspname",
"view_cls"."relname",
"view_cls"."relkind",
"pg_depend"."refobjid",
"pg_depend"."refobjsubid"
FROM "pg_catalog"."pg_depend"
INNER JOIN "pg_catalog"."pg_rewrite" ON "pg_depend"."objid" = "pg_rewrite"."oid"
INNER JOIN "pg_catalog"."pg_class" AS "view_cls" ON "pg_rewrite"."ev_class" = "view_cls"."oid"
INNER JOIN "pg_catalog"."pg_namespace" AS "view_nsp" ON "view_cls"."relnamespace" = "view_nsp"."oid"
WHERE "pg_depend"."refobjid" = ANY($1) AND "pg_depend"."deptype" = $2 AND "view_cls"."relkind" = ANY($3) AND NOT ("view_nsp"."nspname" = ANY($4));
SELECT "oid", "extname", "extnamespace"
FROM "pg_catalog"."pg_extension"
ORDER BY "extname" ASC;
-- → 3 rows
-- … 134 more statements in examples/__wire__/online_migrations.sql
Shift report
- Synced and tracked versioned migrations with
pgm.sync_schema() - Verified idempotency and zero catalog drift with
pgm.plan_migration()andpgm.check_drift() - Expanded schema evolution into
CREATE UNIQUE INDEX CONCURRENTLY+NOT VALID+VALIDATE CONSTRAINT - Evolved a live table with zero downtime and preserved existing production rows
Try it yourself
After evolve_schema_online finishes, try updating Jumbo's badge with tusk_span_cm=-5. Watch PostgreSQL's newly validated badge_tusk_positive constraint reject it with pg.CheckViolationError.
🏗️ Want the full 8-chapter migration story?
This chapter is the Launch Day introduction to pgdorm.migrate. For the complete Year 2 journey — pg_catalog introspection, baseline_schema(), three-way check_drift(), Mode B versioned MigrationApp & checksums, RunPython Expand-Contract backfills, lock-timeout retries, PgBouncer leases, self-healing crash recovery, SyncTypeTable / RLS, the pgdorm CLI in CI, and legacy schema adoption — continue into The Renovations (Migrations Story)!
Go deeper: tests/integration/migrations/test_sync_lifecycle.py · tests/integration/migrations/test_online_ddl_and_hazards.py (live PostgreSQL test suites & snapshots)
Sticky note from Management
"18:00. Launch survived! Before you clock off, hand Moby a test suite that locks in our 1-RTT budgets, our index choices, our SQL tags, and our schema diagram so nothing ever regresses!"
← PreviousChapter 18 · The Booking Desk APIChapter 18 · FastAPI, Wire JSON & Stats
Next →Chapter 20 · Moby's Test LabChapter 20 · 1-RTT & Schema Test Lab