Chapter 4 — Moving Elephants Mid-Renovation#
Split columns zero-downtime via Expand -> RunPython Backfill -> Enforce -> Contract and replay ops in memory.
RunPythonadd_column() / set_not_null()Expand-Contractapply_ddl()apply_ops()examples/154_mig_backfills_expand_contract.pyYear 2 · Summer, 11:30. Pip and Bram are sorting room cards in the linen closet when Management drops off a breaking data redesign.
Management: "SPLIT full_name INTO given_name AND family_name — MAKE BOTH NOT NULL — AND KEEP OLD APP SERVERS WORKING DURING THE ROLLOUT!"
Panda: Easy! Drop full_name, add given_name NOT NULL, and apologize to everyone who tries to check in during the deploy!
Maya: No way — we run Expand → Backfill → Enforce → Contract with RunPython using 100% typed pgdorm queries!
The mission#
Zero-downtime data restructures cannot happen in one giant ALTER TABLE. Instead, production PostgreSQL teams ship four small, backward-compatible stages — and pgdorm.migrate expresses every single stage with typed Python ops and zero raw SQL:
- Expand (
0002_expand): add nullablegiven_nameandfamily_namewithpgm.add_column(), - Backfill (
0003_backfill): split existing rows insidepgm.RunPythonusing typedpg.select/pg.update(idempotent viaWHERE given_name IS NULL), - Enforce (
0004_enforce): lock downpgm.set_not_null()(NOT VALID+VALIDATE),pgm.add_check(),pgm.create_index()(CONCURRENTLY), andpgm.analyze_table(), - Contract (
0005_contract): dropfull_namewithpgm.drop_column(..., allow_destructive=True)once every app instance reads the new columns, - Test in 0 ms: replay ops purely in memory with
pgm.apply_ops()(no database required!) and run targeted untracked ops likeANALYZEwithpgm.apply_ddl().
The Panda's plan
Add a NOT NULL column with a dummy default, drop the old column in the same deploy, and crash every running app pod still reading full_name during rolling restarts.
1. Three schema milestones (V1 → V2Expanded → V3Final)#
class V1:
class GuestCard(pg.Table):
guest_card_id: pg.Col[int] = pg.pk(default=pg.identity())
full_name: pg.Col[str]
class V2Expanded:
class GuestCard(pg.Table):
guest_card_id: pg.Col[int] = pg.pk(default=pg.identity())
full_name: pg.Col[str]
given_name: pg.Col[str | None] = pg.col(default=None)
family_name: pg.Col[str | None] = pg.col(default=None)
class V3Final:
class GuestCard(pg.Table):
guest_card_id: pg.Col[int] = pg.pk(default=pg.identity())
given_name: pg.Col[str]
family_name: pg.Col[str] = pg.col(index=True)
@classmethod
def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
return (pg.Check(pg.func("length", cls.given_name, returns=int) > 0),)
2. Zero-raw-SQL data backfills with RunPython#
A pgm.RunPython step receives a live pg.Transaction (tx), so your backfill uses the exact same typed pg.select, pg.update, pg.insert_many, and pg.merge builders as the rest of your app:
async def backfill_split_names(tx: pg.Transaction) -> None:
# 100% typed pgdorm queries inside RunPython — zero raw SQL strings, idempotent on re-run!
pending = await tx.all(
pg.select(V2Expanded.GuestCard)
.where(V2Expanded.GuestCard.given_name.is_null())
.order_by(V2Expanded.GuestCard.guest_card_id.asc())
)
for row in pending:
given, _, family = row.full_name.partition(" ")
await tx.execute(
pg.update(V2Expanded.GuestCard)
.set(given_name=given, family_name=family or given)
.where(V2Expanded.GuestCard.guest_card_id == row.guest_card_id)
)
3. Running all four stages, apply_ddl(), and apply_ops()#
Notice how Stages 1–3 require neither allow_breaking nor allow_destructive — every DDL step expands cleanly into online-safe PostgreSQL statements. Only Stage 4 (drop_column) requires allow_destructive=True:
async def expand_backfill_enforce_contract(pool: pg.Pool) -> None:
# Seed V1 live data before starting the 4-stage rollout.
await pgm.sync_schema(pool, (V1.GuestCard,), version="0001_init", name="init_cards")
await pool.execute(
pg.insert_many(
V1.GuestCard,
[
V1.GuestCard(full_name="Jumbo Kalahari"),
V1.GuestCard(full_name="Bram Pleistocene"),
V1.GuestCard(full_name="Pip Kinabatangan"),
],
)
)
# Stage 1 (Expand) + Stage 2 (Backfill) + Stage 3 (Enforce) — zero breaking/destructive ops!
m_expand = pgm.Migration(
version="0002_expand",
name="add_split_name_cols",
ops=(
pgm.add_column(V2Expanded.GuestCard.given_name),
pgm.add_column(V2Expanded.GuestCard.family_name),
),
)
m_backfill = pgm.Migration(
version="0003_backfill",
name="backfill_split_names",
ops=(pgm.RunPython(name="split_full_name", fn=backfill_split_names),),
)
m_enforce = pgm.Migration(
version="0004_enforce",
name="enforce_split_names",
ops=(
pgm.set_not_null(V2Expanded.GuestCard.given_name),
pgm.set_not_null(V2Expanded.GuestCard.family_name),
pgm.add_check(
V2Expanded.GuestCard,
pg.func("length", V2Expanded.GuestCard.given_name, returns=int) > 0,
name="guest_card_given_nonempty",
),
pgm.create_index(
V2Expanded.GuestCard,
V2Expanded.GuestCard.family_name,
name="idx_guest_card_family",
),
pgm.analyze_table(V2Expanded.GuestCard),
),
)
applied = await pgm.upgrade_schema(pool, (m_expand, m_backfill, m_enforce))
print(f"stages 1-3 applied: {[r.version for r in applied]}")
# => stages 1-3 applied: ['0002_expand', '0003_backfill', '0004_enforce']
# Stage 4 (Contract): drop legacy column after all app pods read given_name/family_name.
m_contract = pgm.Migration(
version="0005_contract",
name="drop_full_name",
ops=(pgm.drop_column(V1.GuestCard, V1.GuestCard.full_name),),
)
contracted = await pgm.upgrade_schema(
pool,
(m_expand, m_backfill, m_enforce, m_contract),
tables=(V3Final.GuestCard,),
allow_destructive=True,
)
rows = await pool.all(
pg.select(V3Final.GuestCard)
.columns(V3Final.GuestCard.given_name, V3Final.GuestCard.family_name)
.order_by(V3Final.GuestCard.guest_card_id.asc())
)
print(f"stage 4={[r.version for r in contracted]}")
# => stage 4=['0005_contract']
print(f"rows={rows}")
# => rows=[('Jumbo', 'Kalahari'), ('Bram', 'Pleistocene'), ('Pip', 'Kinabatangan')]
# Untracked targeted DDL helper (does not write a ledger revision) + 0-ms snapshot replay!
await pgm.apply_ddl(pool, pgm.analyze_table(V3Final.GuestCard))
replayed = pgm.apply_ops(
pgm.snapshot_from_tables(V1.GuestCard, schema="public"),
(*m_expand.ops, *m_enforce.ops, *m_contract.ops),
)
final_cols = [c.name for c in replayed.tables["guest_card"].columns]
drift = await pgm.check_drift(pool, tables=(V3Final.GuestCard,))
print(f"replay cols={final_cols} live in_sync={drift.in_sync}")
# => replay cols=['guest_card_id', 'given_name', 'family_name'] live in_sync=True
Ferris' basement: 0-ms migration unit tests with apply_ops()
pgm.apply_ops(snapshot, ops) applies your MigrationOp sequence directly to an in-memory SchemaSnapshot in microseconds — letting you unit-test that your V1 snapshot + versioned migrations converge to V3Final before Docker even starts!
What PostgreSQL actually received#
🔭 What PostgreSQL received: 257 statements in 137 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 "guest_card" ("guest_card_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "full_name" TEXT NOT NULL, CONSTRAINT "pk_ysqxpumj" PRIMARY KEY ("guest_card_id"));
-- ── 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;
-- → 2 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;
-- → 3 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;
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
-- … 215 more statements in examples/__wire__/mig_backfills_expand_contract.sql
Shift report
- Executed a 4-stage Expand → Backfill → Enforce → Contract rollout with zero downtime
- Backfilled live production rows inside
pgm.RunPythonusing 100% typedpgdormqueries - Authored explicit op helpers (
add_column,set_not_null,add_check,create_index,analyze_table,drop_column) - Verified
pgm.apply_ddl()for targeted untracked DDL andpgm.apply_ops()for 0-ms in-memory snapshot replay
Try it yourself
Run pgm.diff_snapshots(replayed, pgm.snapshot_from_tables(V3Final.GuestCard, schema="public")) at the end of the script — verify that your pure in-memory replay converges to zero diff against V3Final.GuestCard!
Go deeper: tests/integration/migrations/test_data_preservation.py · tests/integration/migrations/test_versioned_and_evolution.py (live PostgreSQL test suites & snapshots)
Sticky note from Management
"02:15 ALERT! A slow analytics query is holding a table lock, Rocco's PgBouncer is pooling Porto, and someone tripped over the power cable mid-CONCURRENTLY index! Make migrations survive!"
← PreviousChapter 3 · Signed Work OrdersChapter 3 · Versioned Apps & Checksums
Next →Chapter 5 · Hard Hats, Locks & Power CutsChapter 5 · Lock Retries, Leases & Recovery