Chapter 3 — Signed Work Orders#
Ship code-reviewed Python migrations with explicit renames, SHA-256 checksums, and history-divergence guards.
MigrationMigrationAppupgrade_schema()render_python_migration()ChecksumMismatchErrorexamples/127_mig_versioned_migrations.pyYear 2 · Summer, 09:00. The hostel now runs staging, Lisbon production, and Porto production. Management pins a red folder to the check-in desk.
Management: "NO MORE AD-HOC SYNCS IN PRODUCTION! EVERY SCHEMA CHANGE MUST BE A SIGNED, REVIEWED WORK ORDER IN GIT — AND DON'T LOSE PIP'S NAME WHEN YOU RENAME nick_name TO display_name!"
Panda: Easy! I'll just edit 0002 in place after we deploy it to staging if I notice a typo!
Ferris: Touch an applied migration and _pgdorm's SHA-256 checksum check halts immediately with ChecksumMismatchError. Work orders are append-only!
The mission#
Declarative sync_schema() (Mode A) is unbeatable for local development and simple services, but multi-environment production teams want immutable, code-reviewed releases committed to version control. Mode B gives you plain typed Python pgm.Migration dataclasses bundled in a pgm.MigrationApp — no magic folder scanner, no template files, no raw SQL:
- render a Python
pgm.Migrationconstant straight from a live plan withpgm.render_python_migration(), - apply versioned releases with
pgm.upgrade_schema()(mode=VERSIONED), - catch an accidental drop+recreate rename with
pgm.detect_potential_renames()and author an explicitpgm.rename_column()insideMigrationAppso live data survives untouched, - verify tamper-proof history via
pgm.ChecksumMismatchErrorandpgm.HistoryDivergenceError.
The Panda's plan
Let an auto-differ blindly emit DROP COLUMN nick_name + ADD COLUMN display_name, wiping every guest's name — or silently rewrite an already-deployed migration file so staging and production diverge forever.
1. V1 and V2 models (a column rename)#
class V1:
class ConciergeGuest(pg.Table):
concierge_guest_id: pg.Col[int] = pg.pk(default=pg.identity())
email: pg.Col[str] = pg.col(unique=True)
nick_name: pg.Col[str] = pg.col()
class V2:
class ConciergeGuest(pg.Table):
concierge_guest_id: pg.Col[int] = pg.pk(default=pg.identity())
email: pg.Col[str] = pg.col(unique=True)
display_name: pg.Col[str] = pg.col()
2. Rendering & applying a code-defined Migration#
pgm.render_python_migration(plan, var_name="M_0001_INIT") formats any MigrationPlan into a clean, self-contained Python pgm.Migration(...) value you can paste into migrations.py and review in a pull request:
async def render_and_apply_versioned(pool: pg.Pool) -> list[pgm.Migration]:
# 1. Dry-run V1 and render a reviewable Python Migration constant to commit into Git.
plan1 = await pgm.plan_migration(
pool, (V1.ConciergeGuest,), version="0001", name="init_concierge"
)
rendered = pgm.render_python_migration(plan1, var_name="M_0001_INIT")
first_line = next(ln for ln in rendered.splitlines() if ln.startswith("M_0001_INIT"))
print(f"rendered: {first_line}")
# => rendered: M_0001_INIT = pgm.Migration(
m0001 = pgm.Migration(version="0001", name="init_concierge", ops=plan1.ops)
applied = await pgm.upgrade_schema(pool, (m0001,))
print(f"applied v1: {[(r.version, r.migration_mode_id.name) for r in applied]}")
# => applied v1: [('0001', 'VERSIONED')]
# Seed a live row before renaming `nick_name` -> `display_name`.
await pool.execute(
pg.insert(V1.ConciergeGuest).values(
V1.ConciergeGuest(email="[email protected]", nick_name="Pip Kinabatangan")
)
)
return [m0001]
3. Detecting renames & bundling a MigrationApp#
A pure structural diff cannot know whether removing nick_name and adding display_name is a drop+add or a rename. pgm.detect_potential_renames() flags same-table drop/add pairs of compatible types so you can write an explicit pgm.rename_column() (or pgm.rename_table()) inside Migration and bundle it into your pgm.MigrationApp:
async def detect_and_apply_explicit_rename(
pool: pg.Pool, migrations: list[pgm.Migration]
) -> list[pgm.Migration]:
# Pure diff sees DropColumn + AddColumn; detect_potential_renames spots the rename!
(schema_name,) = await pool.one(pg.select_expr(pg.func("current_schema")))
assert isinstance(schema_name, str)
live = await pgm.introspect_schema(pool, schema_name)
desired = pgm.snapshot_from_tables(V2.ConciergeGuest, schema=schema_name)
candidates = pgm.detect_potential_renames(live, desired)
print(f"rename hints: {candidates}")
# => rename hints: (('concierge_guest', 'nick_name', 'display_name'),)
# Author an explicit RenameColumn migration so zero rows are lost!
m0002 = pgm.Migration(
version="0002",
name="rename_nick_to_display",
ops=(pgm.rename_column(V1.ConciergeGuest, old="nick_name", new="display_name"),),
)
app = pgm.MigrationApp(
tables=(V2.ConciergeGuest,),
migrations=(*migrations, m0002),
)
applied = await pgm.upgrade_schema(pool, app.migrations, tables=app.tables, allow_breaking=True)
guest = await pool.one(
pg.select(V2.ConciergeGuest).where(V2.ConciergeGuest.email == "[email protected]")
)
print(f"upgraded={[r.version for r in applied]} preserved={guest.display_name!r}")
# => upgraded=['0002'] preserved='Pip Kinabatangan'
return list(app.migrations)
4. Checksum & history-divergence guards#
Every applied Migration stores a deterministic SHA-256 checksum of its ops in _pgdorm.migration. upgrade_schema() verifies every previously applied migration before running new ones:
async def checksum_and_divergence_guards(pool: pg.Pool, migrations: list[pgm.Migration]) -> None:
m0001, _ = migrations
# Editing an already-applied migration trips ChecksumMismatchError.
tampered = pgm.Migration(
version="0002",
name="rename_nick_to_display",
ops=(pgm.rename_column(V1.ConciergeGuest, old="nick_name", new="full_label"),),
)
try:
await pgm.upgrade_schema(pool, (m0001, tampered), allow_breaking=True)
except pgm.ChecksumMismatchError as exc:
print(f"checksum guard: {type(exc).__name__}")
# => checksum guard: ChecksumMismatchError
# Dropping an applied migration from the list trips HistoryDivergenceError.
try:
await pgm.upgrade_schema(pool, (m0001,))
except pgm.HistoryDivergenceError as exc:
print(f"divergence guard: {type(exc).__name__}")
# => divergence guard: HistoryDivergenceError
# Re-running the authentic list is a clean 0-op no-op.
noop = await pgm.upgrade_schema(pool, migrations)
print(f"re-run applied={len(noop)}")
# => re-run applied=0
Ferris' basement: pre-baseline skips
When an existing database was adopted with pgm.baseline_schema(..., version="0002_baseline"), pgm.upgrade_schema() automatically skips every migration whose version sorts at or before the baseline version — only applying revisions newer than the baseline!
What PostgreSQL actually received#
🔭 What PostgreSQL received: 104 statements in 56 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" ASC;
-- ── round trip 4 ──
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 5 ──
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 6 · 2 statements pipelined ──
BEGIN;
SELECT pg_advisory_xact_lock(hashtext($1));
-- → 1 row
-- ── round trip 7 ──
SELECT "oid", "nspname"
FROM "pg_catalog"."pg_namespace"
WHERE "nspname" = $1;
-- → 1 row
-- ── round trip 8 ──
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 9 · 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 10 ──
COMMIT;
-- ── round trip 11 ──
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 12 ──
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 13 ──
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 14 · 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 15 ──
CREATE TABLE IF NOT EXISTS "concierge_guest" ("concierge_guest_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "email" TEXT NOT NULL, "nick_name" TEXT NOT NULL, CONSTRAINT "pk_tpqxbble" PRIMARY KEY ("concierge_guest_id"), CONSTRAINT "uq_ugbibxrt" UNIQUE ("email"));
-- ── round trip 16 ──
COMMIT;
-- ── round trip 17 ──
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 18 ──
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 19 ──
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 20 · 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
-- … 63 more statements in examples/__wire__/mig_versioned_migrations.sql
Shift report
- Generated reviewable Python migration code via
pgm.render_python_migration() - Applied versioned releases with
pgm.Migration,pgm.MigrationApp, andpgm.upgrade_schema() - Preserved live guest data through a rename using
pgm.detect_potential_renames()andpgm.rename_column() - Verified tamper and missing-revision guards (
ChecksumMismatchErrorandHistoryDivergenceError)
Try it yourself
Print the full string returned by pgm.render_python_migration(plan1, var_name="M_0001_INIT") — notice it emits typed pgm.CreateTable / pgm.ColumnSnapshot dataclasses with zero raw SQL strings and passes a strict type check.
Go deeper: tests/integration/migrations/test_versioned_and_evolution.py (live PostgreSQL test suites & snapshots)
Sticky note from Management
"Love the signed work orders! Next renovation: split full_name into given_name + family_name and backfill every existing guest without downtime or raw SQL!"
← PreviousAct II · Planned RenovationsAct II · Versioned Apps, Backfills & Locks
Next →Chapter 4 · Moving Elephants Mid-RenovationChapter 4 · RunPython & Expand-Contract