Skip to content

Field Note 2 — The Retired Room Category#

Field Notes · ORM Design · 🕛 Post-Launch · 15:10 · ⏱ 7 min read · 🥜🥜🥜◌◌

TypeTable · SyncTypeTable · LockMode.NONE · FK 23503 · assimilate_enums

▶ Run it yourself: examples/169_type_table_evolution.py

Post-Launch, 15:10. A neon sticky note from Management is slapped onto the lobby monitor: "Peak check-in! Launch `ICE_GROTTO`, rename `VIP_POOL` to `THERMAL_SUITE`, and retire `HAMMOCK_LOFT` before the 16:00 herd arrives."

Post-Launch, 15:10. A neon sticky note from Management is slapped onto the lobby monitor: "Peak check-in! Launch ICE_GROTTO, rename VIP_POOL to THERMAL_SUITE, and retire HAMMOCK_LOFT before the 16:00 herd arrives."

Maya: Ferris, if suite_tier were a PostgreSQL CREATE TYPE ... AS ENUM, retiring HAMMOCK_LOFT at peak check-in would lock the entire table for a rewrite!

Ferris: Good thing it isn't. In pgdorm, enums live inside PostgreSQL as INT4 TypeTable lookup tables with UNIQUE (code) and a real Foreign Key. Adding, renaming, and retiring are plain transactional DML — zero DDL locks, zero rewrites.

Maya: Let's run the whole evolution live and compare it side-by-side against native pg_enum.

Why pgdorm uses TypeTable instead of CREATE TYPE ... AS ENUM#

PostgreSQL's native CREATE TYPE ... AS ENUM looks tempting at first glance, until a production schema needs to evolve under traffic:

Operation Native CREATE TYPE ... AS ENUM pgdorm pg.TypeTable + IntEnum
Add a value ALTER TYPE ... ADD VALUE — cannot be used in the same transaction (SQLSTATE 55P04: unsafe use of new value) SyncTypeTable / INSERT (LockMode.NONE) — usable immediately in the same transaction
Rename a value ALTER TYPE ... RENAME VALUE (DDL catalog lock) UPDATE suite_tier_type SET code = ... (1 row, 0 rows touched on hostel_suite)
Remove a value No ALTER TYPE ... DROP VALUE exists in PostgreSQL! Requires a 5-step CREATE TYPE __new + ALTER TABLE ... ALTER COLUMN TYPE ... USING ::text (ACCESS EXCLUSIVE full table & index rewrite) Reassign rows + DELETE FROM suite_tier_type in 1 RTT; Foreign Key (23503) blocks orphans automatically
Extra metadata Impossible — pg_enum stores only (oid, label) Add columns right on the TypeTable (e.g. nightly_rate, display_order, is_active)

1. Adding ICE_GROTTO & renaming VIP_POOL with zero DDL locks#

When Management adds ICE_GROTTO and renames VIP_POOL -> THERMAL_SUITE, pgm.plan_migration() emits a single SyncTypeTable step with LockMode.NONE. Because it is plain DML, you can insert ICE_GROTTO and immediately book a room with it inside the exact same transaction — no 55P04 error — while hostel_suite keeps its compact INT4 foreign key (2) untouched:

examples/169_type_table_evolution.py · add_and_rename_lock_free
async def add_and_rename_lock_free(pool: pg.Pool) -> None:
    # 1. Seed V1 categories and three active suites, plus per-category nightly rates.
    await pool.create_all(V1.SuiteTierType, V1Tables.HostelSuite)
    await pool.execute(
        pg.update(V1.SuiteTierType)
        .set(nightly_rate=Decimal("260.00"))
        .where(V1.SuiteTierType.suite_tier_type_id == SuiteTierV1.VIP_POOL)
    )
    await pool.execute(
        pg.insert_many(
            V1Tables.HostelSuite,
            [
                V1Tables.HostelSuite(number="101", suite_tier_type_id=SuiteTierV1.BUNK),
                V1Tables.HostelSuite(number="201", suite_tier_type_id=SuiteTierV1.VIP_POOL),
                V1Tables.HostelSuite(number="301", suite_tier_type_id=SuiteTierV1.HAMMOCK_LOFT),
            ],
        )
    )

    # 2. Plan V1 -> V2: adding ICE_GROTTO and renaming VIP_POOL -> THERMAL_SUITE is pure DML
    #    (SyncTypeTable, LockMode.NONE) — zero ALTER TYPE, zero ACCESS EXCLUSIVE lock.
    plan = await pgm.plan_migration(pool, (V2.SuiteTierType, V2Tables.HostelSuite))
    locks = sorted({step.lock_mode.name for step in plan.steps})
    print(f"evolution plan: steps={len(plan.steps)}, locks={locks}")
    # => evolution plan: steps=1, locks=['NONE']

    # 3. Apply the new category and immediately insert an ICE_GROTTO suite in the SAME tx!
    #    (Native PG ENUMs reject using a newly added value in the same tx with SQLSTATE 55P04.)
    async with pool.trace() as tr, pool.transaction() as tx:
        await tx.execute(
            pg.insert(V2.SuiteTierType).values(
                V2.SuiteTierType(
                    suite_tier_type_id=SuiteTierV2.ICE_GROTTO,
                    code="ice_grotto",
                    nightly_rate=Decimal("340.00"),
                )
            )
        )
        await tx.execute(
            pg.update(V2.SuiteTierType)
            .set(code="thermal_suite")
            .where(V2.SuiteTierType.suite_tier_type_id == SuiteTierV2.THERMAL_SUITE)
        )
        grotto = await tx.one(
            pg.insert(V2Tables.HostelSuite)
            .values(V2Tables.HostelSuite(number="401", suite_tier_type_id=SuiteTierV2.ICE_GROTTO))
            .returning(V2Tables.HostelSuite)
        )
    print(f"same-tx add+use: {grotto.number}={grotto.suite_tier_type_id.name} ({tr.rtts} RTTs)")
    # => same-tx add+use: 401=ICE_GROTTO (4 RTTs)

    # 4. Suite 201 still points to INT4 key 2 — now named THERMAL_SUITE with zero table rewrite.
    rows = await pool.all(
        pg.select(V2Tables.HostelSuite)
        .join(V2.SuiteTierType)
        .columns(V2Tables.HostelSuite.number, V2.SuiteTierType.code, V2.SuiteTierType.nightly_rate)
        .order_by(V2Tables.HostelSuite.number.asc())
    )
    board = ", ".join(f"{num}:{code}({rate or '-'})" for num, code, rate in rows)
    print(f"board: {board}")
    # => board: 101:bunk(-), 201:thermal_suite(260.00), 301:hammock_loft(-), 401:ice_grotto(340.00)

What just happened

  • plan_migration() reported locks=['NONE'] — no ALTER TYPE, no catalog lock, no table rewrite.
  • Suite 401 was inserted with SuiteTierV2.ICE_GROTTO in the very same transaction that created the category.
  • Suite 201 still holds suite_tier_type_id = 2, which now joins to thermal_suite (along with its nightly_rate metadata column).

2. Retiring HAMMOCK_LOFT — Foreign Key safety vs. 5-step ENUM rewrite#

Retiring a category is where native pg_enum hurts most: PostgreSQL has no ALTER TYPE ... DROP VALUE. Dropping a value from a native ENUM forces a 5-step migration:

-- Native pg_enum removal requires an ACCESS EXCLUSIVE full table & index rewrite:
CREATE TYPE suite_tier_new AS ENUM ('bunk', 'thermal_suite', 'ice_grotto');
UPDATE hostel_suite SET tier = 'thermal_suite' WHERE tier = 'hammock_loft';
ALTER TABLE hostel_suite
  ALTER COLUMN tier TYPE suite_tier_new USING tier::text::suite_tier_new; -- ACCESS EXCLUSIVE!
DROP TYPE suite_tier;
ALTER TYPE suite_tier_new RENAME TO suite_tier;

With a pg.TypeTable, PostgreSQL's own Foreign Key protects you from leaving orphaned rows (SQLSTATE 23503), and retiring HAMMOCK_LOFT is a 1-RTT pipelined UPDATE + DELETE:

examples/169_type_table_evolution.py · retire_category_safely
async def retire_category_safely(pool: pg.Pool) -> None:
    # 1. PostgreSQL's Foreign Key blocks retiring HAMMOCK_LOFT while suite 301 still references it.
    try:
        await pool.execute(
            pg.delete(V2.SuiteTierType).where(
                V2.SuiteTierType.suite_tier_type_id == SuiteTierV2.HAMMOCK_LOFT
            )
        )
    except pg.ForeignKeyViolationError as exc:
        print(f"orphan blocked: sqlstate={exc.sqlstate} table={exc.table_name}")
        # => orphan blocked: sqlstate=23503 table=hostel_suite

    # 2. Reassign suite 301 and DELETE HAMMOCK_LOFT atomically in 1 RTT — zero table rewrite.
    async with pool.trace() as tr, pool.transaction() as tx, tx.pipeline(commit=True) as pipe:
        pipe.add(
            pg.update(V2Tables.HostelSuite)
            .set(suite_tier_type_id=SuiteTierV2.THERMAL_SUITE)
            .where(V2Tables.HostelSuite.suite_tier_type_id == SuiteTierV2.HAMMOCK_LOFT)
        )
        pipe.add(
            pg.delete(V2.SuiteTierType).where(
                V2.SuiteTierType.suite_tier_type_id == SuiteTierV2.HAMMOCK_LOFT
            )
        )
    remaining = [
        code
        for (code,) in await pool.all(
            pg.select(V2.SuiteTierType)
            .columns(V2.SuiteTierType.code)
            .order_by(V2.SuiteTierType.suite_tier_type_id.asc())
        )
    ]
    print(f"retired HAMMOCK_LOFT in {tr.rtts} RTT; active={remaining}")
    # => retired HAMMOCK_LOFT in 1 RTT; active=['bunk', 'thermal_suite', 'ice_grotto']
Ferris' basement: Migrating off existing PostgreSQL ENUMs

Inheriting a legacy database that already uses CREATE TYPE ... AS ENUM? Pass assimilate_enums=True to pgm.scaffold_from_db(pool, mode=pgm.enums.ScaffoldMode.ASSIMILATE, assimilate_enums=True) (see Field Note 4) to generate IntEnum + pg.TypeTable definitions automatically.


What PostgreSQL actually received#

🔭 What PostgreSQL received: 23 statements in 12 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 6 statements omitted · full transcript in examples/__wire__/type_table_evolution.sql

-- ── round trip 1 ──
UPDATE "suite_tier_type"
SET "nightly_rate" = $1
WHERE "suite_tier_type_id" = $2;
-- → 1 affected

-- ── round trip 2 ──
INSERT INTO "hostel_suite" ("number", "suite_tier_type_id")
SELECT u.c0, u.c1
FROM unnest($1, $2) WITH ORDINALITY AS u(c0, c1, ord)
ORDER BY u.ord;
-- → 3 affected

-- ── round trip 3 ──
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;
-- → 2 rows

-- ── round trip 4 · 8 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;
-- → 6 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;
-- → 10 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;
-- → 3 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 "suite_tier_type_id", "nightly_rate", "code"
FROM "suite_tier_type"
ORDER BY "suite_tier_type_id" ASC;
-- → 3 rows

-- ── round trip 5 · 2 statements pipelined ──
BEGIN;
INSERT INTO "suite_tier_type" ("suite_tier_type_id", "nightly_rate", "code")
VALUES ($1, $2, $3);
-- → 1 affected

-- ── round trip 6 ──
UPDATE "suite_tier_type"
SET "code" = $1
WHERE "suite_tier_type_id" = $2;
-- → 1 affected

-- ── round trip 7 ──
INSERT INTO "hostel_suite" ("number", "suite_tier_type_id")
VALUES ($1, $2)
RETURNING "hostel_suite_id", "number", "suite_tier_type_id";
-- → 1 row

-- ── round trip 8 ──
COMMIT;

-- ── round trip 9 ──
SELECT "hostel_suite"."number", "suite_tier_type"."code", "suite_tier_type"."nightly_rate"
FROM "hostel_suite"
INNER JOIN "suite_tier_type" USING ("suite_tier_type_id")
ORDER BY "hostel_suite"."number" ASC;
-- → 4 rows

-- ── round trip 10 ──
DELETE FROM "suite_tier_type"
WHERE "suite_tier_type_id" = $1;
-- ✗ PostgreSQL rejected this round trip: SQLSTATE 23503

-- ── round trip 11 · 4 statements pipelined ──
BEGIN;
UPDATE "hostel_suite"
SET "suite_tier_type_id" = $1
WHERE "suite_tier_type_id" = $2;
-- → 1 affected
DELETE FROM "suite_tier_type"
WHERE "suite_tier_type_id" = $1;
-- → 1 affected
COMMIT;

-- ── round trip 12 ──
SELECT "code"
FROM "suite_tier_type"
ORDER BY "suite_tier_type_id" ASC;
-- → 3 rows

Shift report

  • Planned a TypeTable evolution with LockMode.NONE (SyncTypeTable)
  • Added ICE_GROTTO and used it immediately in the same transaction (impossible with ALTER TYPE ... ADD VALUE, 55P04)
  • Renamed VIP_POOL -> THERMAL_SUITE in 1 lookup row without touching hostel_suite
  • Verified Foreign Key orphan protection (23503) and retired HAMMOCK_LOFT in 1 RTT with zero table rewrite

Go deeper: tests/integration/docs/test_field_notes_enums.py (live PostgreSQL test suites & snapshots)