Chapter 0 — The Internship#
Build the Dormitory schema from its first table, one reviewed migration per step, with a diagram of where you are after each one.
plan_migration()sync_schema()migration_history()to_svg_erd(focus=…)examples/083_mig_internship.pyYear 2 · Spring, 07:45. Maya's first morning as the Dormitory's database intern. The production schema already has 22 tables, and nobody remembers the order they were built in.
Panda: Easy! Read the whole schema.py top to bottom and memorise it before lunch!
Ferris: Nobody learns a building from its full blueprint. Start with one room, add a floor at a time, and look at the plan after every step.
Maya: So each step is a migration, and the diagram shows me where I am?
The mission#
Before the later chapters change live tables, Maya builds the Elephant Dormitory's schema from an empty database, one migration per step. Every step:
- adds a few tables to the ones that already exist, dependencies first,
- asks
pgm.plan_migration()what would change, and applies it withpgm.sync_schema(), - ends with a diagram of where we are now: the new tables highlighted, their neighbours faded.
The steps reuse the real models from examples/schema.py, the same ones the Story uses, so nothing here is a throwaway example.
1. The first table#
Every schema starts somewhere. The Dormitory starts with Region, which points at itself so regions can nest (Lisbon inside Portugal):
class Region(pg.Table):
region_id: Col[int] = pg.pk(default=pg.identity())
code: Col[Code] = pg.col(unique=True)
name: Col[str]
parent_region_id: Col[int | None] = pg.self_fk(
on_delete=pg.enums.OnDelete.SET_NULL, default=None
)
Plan it, read the plan, then apply it:
async def first_table(pool: pg.Pool) -> None:
# Step 1: one table. Ask for a plan first, read it, then apply it.
name, tables = INTERNSHIP_STEPS[0]
plan = await pgm.plan_migration(pool, tables, version="0001_first_table", name=name)
print(f"plan: {[op.op_kind for op in plan.ops]}")
# => plan: ['create_table']
for step in plan.steps:
print(f" {(step.sql or step.description).split(' (')[0].split(' ON ')[0]}")
# => CREATE TABLE IF NOT EXISTS "region"
# => CREATE INDEX IF NOT EXISTS "ix_knrqdjrl"
rec = await pgm.sync_schema(pool, tables, version="0001_first_table", name=name)
assert rec is not None
replan = await pgm.plan_migration(pool, tables)
print(f"applied {rec.version}; re-plan empty: {replan.is_empty}")
# => applied 0001_first_table; re-plan empty: True
The plan is the exact SQL that will run, nothing hidden. Applying it records the step as version 0001_first_table, and planning again afterwards finds nothing left to do.
Where we are now#
2. One step at a time#
The rest of the schema arrives in six more steps. The order is written down once, in examples/schema.py, so the code, the diagrams and this page can't disagree:
INTERNSHIP_STEPS: tuple[tuple[str, tuple[type[pg.Table], ...]], ...] = (
("first_table", (Region,)),
("lookups", (SpeciesType, RoomCategoryType, LoyaltyTierType)),
("buildings", (Dormitory, Room)),
("guests", (Guest,)),
(
"bookings",
(BookingStatusType, BookingChannelType, Booking, BookingGuest, RoomAssignment, Rate),
),
("money", (ChargeKindType, PaymentMethodType, Charge, Payment)),
("operations", (TaskKindType, Task, CleaningTask, MaintenanceTask, DoorEvent)),
)
Each migration describes all the tables so far. pgdorm compares that with the live database and plans only the difference:
async def grow_step_by_step(pool: pg.Pool) -> None:
# Steps 2-7: every migration targets *all* tables so far; pgdorm plans only the difference.
so_far: tuple[type[pg.Table], ...] = INTERNSHIP_STEPS[0][1]
for n, (name, new_tables) in enumerate(INTERNSHIP_STEPS[1:], start=2):
so_far = (*so_far, *new_tables)
version = f"{n:04d}_{name}"
plan = await pgm.plan_migration(pool, so_far, version=version, name=name)
kinds = Counter(op.op_kind for op in plan.ops if op.op_kind != "create_extension")
print(f"step {n} {name}: +{len(new_tables)} tables {dict(sorted(kinds.items()))}")
# Extensions the schema needs from here on; pgdorm installs any that are missing.
if needs := pgm.snapshot_from_tables(*so_far, schema=SCHEMA).extensions:
print(f" needs extensions: {list(needs)}")
await pgm.sync_schema(pool, so_far, version=version, name=name)
# => step 2 lookups: +3 tables {'create_table': 3, 'sync_type_table': 3}
# => step 3 buildings: +2 tables {'create_table': 2}
# => step 4 guests: +1 tables {'create_table': 1}
# => step 5 bookings: +6 tables {'create_table': 6, 'sync_type_table': 2}
# => needs extensions: ['btree_gist']
# => step 6 money: +4 tables {'create_table': 4, 'sync_type_table': 2}
# => needs extensions: ['btree_gist']
# => step 7 operations: +5 tables {'create_table': 5, 'sync_type_table': 1}
# => needs extensions: ['btree_gist']
sync_type_table steps fill lookup tables such as species_type with their enum values, so lookups never drift from the Python enums.
From step 5 on, the schema needs an extension. Rate keeps seasonal prices whose date ranges may never overlap, and its key mixes a plain dormitory_id with a date range. PostgreSQL needs the btree_gist extension for that, so pgdorm records it in the schema and, if the database doesn't have it yet, plans a create_extension step ahead of the tables. Nobody has to install it by hand.
Step 2 · Lookups#
Species, room categories and loyalty tiers become small lookup tables that other tables point at. Nothing references them yet.
Step 3 · Buildings#
Dormitory belongs to a Region; Room belongs to a Dormitory and has a room category.
Step 4 · Guests#
Guest carries a species and a loyalty tier, both through the lookups from step 2.
Step 5 · Bookings#
The busiest step: bookings, the guests on each booking, room assignments, and seasonal rates whose date ranges may never overlap.
Step 6 · Money#
Charges and payments hang off bookings. All payment methods share one payment table, told apart by their method.
Step 7 · Operations#
The task board (each kind of task with its own detail table) and the partitioned keycard log, door_event.
3. The ledger remembers every step#
pgdorm records each applied migration in its own _pgdorm schema, so the build history can be queried, and drift detection can confirm the database matches the models:
async def read_the_ledger(pool: pg.Pool) -> None:
# Every step is recorded in pgdorm's own ledger, so the history is queryable.
history = await pgm.migration_history(pool)
print(f"ledger: {len(history)} migrations, {history[0].version} … {history[-1].version}")
# => ledger: 7 migrations, 0001_first_table … 0007_operations
everything = tuple(t for _, step in INTERNSHIP_STEPS for t in step)
report = await pgm.check_drift(pool, tables=everything)
print(f"in sync: {report.in_sync}")
# => in sync: True
🔭 What PostgreSQL received: 797 statements in 420 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"."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 3 ──
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 4 ──
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 5 ──
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 6 ──
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 7 ──
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 8 · 2 statements pipelined ──
BEGIN;
SELECT pg_advisory_xact_lock(hashtext($1));
-- → 1 row
-- ── round trip 9 ──
SELECT "oid", "nspname"
FROM "pg_catalog"."pg_namespace"
WHERE "nspname" = $1;
-- → 1 row
-- ── round trip 10 ──
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 11 · 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 12 ──
COMMIT;
-- ── round trip 13 ──
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 14 ──
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 15 ──
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 16 · 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 17 ──
CREATE TABLE IF NOT EXISTS "region" ("region_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "code" CHARACTER VARYING(8) NOT NULL, "name" TEXT NOT NULL, "parent_region_id" BIGINT, CONSTRAINT "pk_rjsydubt" PRIMARY KEY ("region_id"), CONSTRAINT "uq_mkyshoqo" UNIQUE ("code"), CONSTRAINT "fk_czwvplpn" FOREIGN KEY ("parent_region_id") REFERENCES "region" ("region_id") ON DELETE SET NULL);
-- ── round trip 18 ──
CREATE INDEX IF NOT EXISTS "ix_knrqdjrl" ON "region" ("parent_region_id") WHERE parent_region_id IS NOT NULL;
-- ── round trip 19 ──
COMMIT;
-- ── round trip 20 ──
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 21 ──
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 22 ──
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 23 ──
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 24 ──
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 25 · 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;
-- → 4 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;
-- → 6 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;
-- → 2 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
-- … 751 more statements in examples/__wire__/mig_internship.sql
Shift report
- Built the Dormitory schema from an empty database in seven reviewed migrations
- Read each plan before applying it, and proved every re-plan is empty
- Drew each step with
pg.to_svg_erd(..., focus=...): new tables highlighted, neighbours faded - Read the build history back from the
_pgdormledger and confirmed zero drift
Try it yourself
Move Guest to step 3 and run the script again. The plan for step 3 now creates three tables, and the ledger still tells the full story.
Go deeper: tests/integration/migrations/test_sync_lifecycle.py (live PostgreSQL test suites & snapshots)
Sticky note from Management
"Lovely build, intern. The blueprints are in the drawer now. Tomorrow you'll learn how to change a schema that guests are already living in."
← PreviousAct I · Blueprints & GuardrailsAct I · Catalog Diff, Sync & Online DDL
Next →Chapter 1 · Opening the BlueprintsChapter 1 · Catalog Diff, Sync & Drift