Chapter 7 — Payments & Chores#
Polymorphic models backed by real foreign keys instead of magic strings.
discriminator()single-table inheritanceclass-table inheritancepolymorphic loadsexamples/162_inheritance_payments_tasks.pyWeek 2, Saturday 09:30. The supply closet is overflowing with card receipts, IBAN slips, peanut vouchers, and a bent steel bunk ladder.
Maya: Card payments need card_last4, bank transfers need an iban, vouchers need a voucher_code. Meanwhile cleaning tasks track towels and peanuts, while maintenance tracks welders and parts.
Panda: Easy! Add a kind TEXT column with "card", "Card", or "CARD", make every subtype column nullable, and hope nobody inserts a card row with an iban!
Ferris: Or forbid string discriminators completely and let PostgreSQL enforce which columns belong to which variant.
The mission#
Real domains are full of "one of several kinds" entities. PostgreSQL has two classic patterns, and Maya needs both in the right places:
- Single-Table Inheritance (STI) for
Payment(CardPayment,BankTransfer,VoucherPayment) — one fast table when variants only add one or two columns. - Class-Table Inheritance (CTI,
joined=True) forTask(CleaningTask,MaintenanceTask) — a shared base table plus dedicated subtype tables when each kind has its own rich set of fields.
Both use a TypeTable integer discriminator (pg.discriminator(...)) — never free-text strings.
The Panda's plan
A payment_type VARCHAR discriminator plus twelve nullable columns with no constraints. Six months later, a bug writes payment_type = 'credit_card' with voucher_code = 'FREE' and card_last4 = NULL, and the nightly accounting job crashes at 02:00.
1. Choosing STI vs CTI#
Look at how both hierarchies are declared in examples/schema.py:
class Payment(pg.Table):
payment_id: Col[int] = pg.pk(default=pg.identity())
payment_method_id: Col[PaymentMethod] = pg.discriminator(
PaymentMethodType.payment_method_type_id
)
booking_id: Col[int] = pg.fk(Booking, on_delete=pg.enums.OnDelete.CASCADE)
amount: Col[Money]
paid_at: Col[datetime] = pg.col(default=pg.now(), server_managed=True)
class CardPayment(Payment, variant=PaymentMethod.CARD):
card_last4: Col[str]
class BankTransfer(Payment, variant=PaymentMethod.TRANSFER):
iban: Col[str]
class VoucherPayment(Payment, variant=PaymentMethod.VOUCHER):
voucher_code: Col[str]
class Task(pg.Table):
task_id: Col[int] = pg.pk(default=pg.identity())
task_kind_id: Col[TaskKind] = pg.discriminator(TaskKindType.task_kind_type_id)
room_id: Col[int] = pg.fk(Room, on_delete=pg.enums.OnDelete.CASCADE)
summary: Col[str]
claimed_by: Col[str | None] = pg.col(default=None)
done: Col[bool] = pg.col(default=False)
class CleaningTask(Task, joined=True, variant=TaskKind.CLEANING):
extra_towels: Col[pg.Int2] = pg.col(default=2)
peanut_refill_kg: Col[pg.Int2] = pg.col(default=5)
class MaintenanceTask(Task, joined=True, variant=TaskKind.MAINTENANCE):
requires_welder: Col[bool] = pg.col(default=False)
parts_cost: Col[Money] = pg.col(default=Decimal("0.00"))
Notice that pg.discriminator(PaymentMethodType.payment_method_type_id) references a TypeTable primary key, and each subclass passes variant=PaymentMethod.CARD (an enum member, never a raw string).
2. Single-table payments with polymorphic hydration#
async def polymorphic_payments_sti(pool: pg.Pool, dorm: Dormitory, guest: Guest) -> None:
booking = await pool.one(
pg.insert(Booking)
.values(
Booking(
dormitory_id=dorm.dormitory_id,
primary_guest_id=guest.guest_id,
stay=pg.Range(lower=date(2026, 8, 1), upper=date(2026, 8, 4)),
reference_code="PAY-301",
)
)
.returning(Booking)
)
# All three variants share one `payment` table guarded by an INT4 TypeTable discriminator
# and auto-generated disjoint CHECK constraints (no string discriminators allowed).
await pool.execute(
pg.insert(CardPayment).values(
CardPayment(
booking_id=booking.booking_id,
amount=Decimal("180.00"),
card_last4="4242",
)
)
)
await pool.execute(
pg.insert(BankTransfer).values(
BankTransfer(
booking_id=booking.booking_id,
amount=Decimal("240.00"),
iban="PT50000201231234567890154",
)
)
)
await pool.execute(
pg.insert(VoucherPayment).values(
VoucherPayment(
booking_id=booking.booking_id,
amount=Decimal("50.00"),
voucher_code="PEANUT-VIP",
)
)
)
# Querying the root `Payment` hydrates exact Python subclasses polymorphically!
all_payments = await pool.all(pg.select(Payment).order_by(Payment.payment_id.asc()))
print("polymorphic types:", [type(p).__name__ for p in all_payments])
# => polymorphic types: ['CardPayment', 'BankTransfer', 'VoucherPayment']
# Querying a variant auto-injects `WHERE "payment_method_id" = $1`.
cards = await pool.all(pg.select(CardPayment))
print("card payments:", [(c.card_last4, str(c.amount)) for c in cards])
# => card payments: [('4242', '180.00')]
# Join against PaymentMethodType to expose human-readable lookup codes.
summary = await pool.all(
pg.select(Payment)
.join(PaymentMethodType)
.columns(PaymentMethodType.code, Payment.amount)
.order_by(Payment.payment_id.asc())
)
print("payment ledger:", [(code, str(amt)) for code, amt in summary])
# => payment ledger: [('card', '180.00'), ('transfer', '240.00'), ('voucher', '50.00')]
What just happened
CardPayment,BankTransfer, andVoucherPaymentall live in the singlepaymenttable. pgdorm generatesCHECKconstraints guaranteeing that aCARDrow hascard_last4 IS NOT NULLwhileibanandvoucher_codeareNULL(and likewise for the other variants).pg.select(Payment)returns a heterogeneous Python list containing actualCardPayment,BankTransfer, andVoucherPaymentinstances — hydrated straight from thepayment_method_iddiscriminator!pg.select(CardPayment)automatically injectsWHERE "payment_method_id" = $1, so you never forget the discriminator filter.- Joining
PaymentMethodTypelets reports print human-readable codes (card,transfer,voucher) backed by a real foreign key.
3. Class-table tasks with 1-RTT writable CTE inserts#
When subtypes carry distinct columns and defaults (extra_towels and peanut_refill_kg vs requires_welder and parts_cost), joined=True puts shared columns in task and subtype columns in cleaning_task and maintenance_task sharing the same task_id primary key:
async def joined_tasks_cti(pool: pg.Pool, rooms: list[Room]) -> None:
# Class-table inheritance (`joined=True`) inserts into both `task` and the subtype table
# atomically in 1 RTT via a writable CTE (`WITH _pgdorm_cti_0 AS (...) INSERT INTO ...`).
async with pool.trace() as tr:
clean = await pool.one(
pg.insert(CleaningTask)
.values(
CleaningTask(
room_id=rooms[0].room_id,
summary="Restock bamboo pillows in 101",
extra_towels=4,
peanut_refill_kg=6,
)
)
.returning(CleaningTask)
)
maint = await pool.one(
pg.insert(MaintenanceTask)
.values(
MaintenanceTask(
room_id=rooms[3].room_id,
summary="Weld mammoth bunk ladder in 104",
requires_welder=True,
parts_cost=Decimal("145.50"),
)
)
.returning(MaintenanceTask)
)
print(f"inserted 2 CTI tasks across 3 tables in {tr.rtts} RTTs")
# => inserted 2 CTI tasks across 3 tables in 2 RTTs
print(f"cleaning #{clean.task_id}: {clean.peanut_refill_kg}kg peanuts")
# => cleaning #1: 6kg peanuts
print(f"maintenance #{maint.task_id}: welder={maint.requires_welder} cost={maint.parts_cost}")
# => maintenance #2: welder=True cost=145.50
# Querying `MaintenanceTask` auto-joins `task` + `maintenance_task` and returns full models.
welding = await pool.all(
pg.select(MaintenanceTask).where(MaintenanceTask.requires_welder.is_true())
)
print("welding jobs:", [j.summary for j in welding])
# => welding jobs: ['Weld mammoth bunk ladder in 104']
# Querying base `Task` lists the unified work queue without touching subtype tables.
queue = await pool.all(pg.select(Task).order_by(Task.task_id.asc()))
for task in queue:
print(f"queue [{task.task_kind_id.name}]: {task.summary}")
# => queue [CLEANING]: Restock bamboo pillows in 101
# => queue [MAINTENANCE]: Weld mammoth bunk ladder in 104
What just happened
- Inserting a
CleaningTaskwrites to bothtaskandcleaning_taskin 1 round trip using a single PostgreSQL writable CTE (WITH _pgdorm_cti_0 AS (INSERT INTO "task" ... RETURNING ...) INSERT INTO "cleaning_task" ...). Two tasks across three tables = 2 RTTs total. pg.select(MaintenanceTask)automatically joinstaskandmaintenance_taskviaUSING ("task_id")and returns fully typedMaintenanceTaskobjects.pg.select(Task)reads only the basetasktable — perfect for a unified housekeeping dashboard that doesn't need subtype details yet.
Here is the actual writable CTE that PostgreSQL executed for CleaningTask:
-- captured live from PostgreSQL · examples/__wire__/inheritance_payments_tasks.sql
WITH "_pgdorm_cti_0" AS (
INSERT INTO "task" ("task_kind_id", "room_id", "summary", "claimed_by", "done")
VALUES ($1, $2, $3, $4, $5)
RETURNING "task_id", "task_kind_id", "room_id", "summary", "claimed_by", "done"
), "_pgdorm_cti_1" AS (
INSERT INTO "cleaning_task" ("task_id", "task_kind_id", "extra_towels", "peanut_refill_kg")
SELECT "task_id", "task_kind_id", $6, $7
FROM "_pgdorm_cti_0"
RETURNING "task_id", "task_kind_id", "extra_towels", "peanut_refill_kg"
)
SELECT
"_pgdorm_cti_1"."task_id",
"_pgdorm_cti_1"."task_kind_id",
"_pgdorm_cti_0"."room_id",
"_pgdorm_cti_0"."summary",
"_pgdorm_cti_0"."claimed_by",
"_pgdorm_cti_0"."done",
"_pgdorm_cti_1"."extra_towels",
"_pgdorm_cti_1"."peanut_refill_kg"
FROM "_pgdorm_cti_0"
INNER JOIN "_pgdorm_cti_1" USING ("task_id");
Ferris' basement: why string discriminators are forbidden
In pgdorm, pg.discriminator(...) must point to a TypeTable primary key, and every variant= must be a member of its IntEnum. That gives you three wins at once: 4-byte integer storage instead of repeated strings, a real foreign key to a self-documenting lookup table, and compile-time safety against typos like variant="crad".
What PostgreSQL actually received#
🔭 What PostgreSQL received: 16 statements in 15 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 54 statements omitted · full transcript in examples/__wire__/inheritance_payments_tasks.sql
-- ── round trip 1 · 2 statements pipelined ──
BEGIN;
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING "dormitory_id", "region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on";
-- → 1 row
-- ── round trip 2 ──
INSERT INTO "room" ("dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service")
VALUES
($1, $2, $3, $4, $5, $6, $7, $8),
($9, $10, $11, $12, $13, $14, $15, $16),
($17, $18, $19, $20, $21, $22, $23, $24),
($25, $26, $27, $28, $29, $30, $31, $32),
($33, $34, $35, $36, $37, $38, $39, $40),
($41, $42, $43, $44, $45, $46, $47, $48),
($49, $50, $51, $52, $53, $54, $55, $56),
($57, $58, $59, $60, $61, $62, $63, $64),
($65, $66, $67, $68, $69, $70, $71, $72),
($73, $74, $75, $76, $77, $78, $79, $80),
($81, $82, $83, $84, $85, $86, $87, $88),
($89, $90, $91, $92, $93, $94, $95, $96)
RETURNING "room_id", "dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service";
-- → 12 rows
-- ── round trip 3 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at";
-- → 3 rows
-- ── round trip 4 ──
COMMIT;
-- ── round trip 5 ──
INSERT INTO "booking" ("dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code")
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING "booking_id", "dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code", "created_at";
-- → 1 row
-- ── round trip 6 ──
INSERT INTO "payment" ("payment_method_id", "booking_id", "amount", "card_last4")
VALUES ($1, $2, $3, $4);
-- → 1 affected
-- ── round trip 7 ──
INSERT INTO "payment" ("payment_method_id", "booking_id", "amount", "iban")
VALUES ($1, $2, $3, $4);
-- → 1 affected
-- ── round trip 8 ──
INSERT INTO "payment" ("payment_method_id", "booking_id", "amount", "voucher_code")
VALUES ($1, $2, $3, $4);
-- → 1 affected
-- ── round trip 9 ──
SELECT
"payment_id",
"payment_method_id",
"booking_id",
"amount",
"paid_at",
"card_last4",
"iban",
"voucher_code"
FROM "payment"
ORDER BY "payment_id" ASC;
-- → 3 rows
-- ── round trip 10 ──
SELECT
"payment_id",
"payment_method_id",
"booking_id",
"amount",
"paid_at",
"card_last4"
FROM "payment"
WHERE "payment_method_id" = $1;
-- → 1 row
-- ── round trip 11 ──
SELECT "payment_method_type"."code", "payment"."amount"
FROM "payment"
INNER JOIN "payment_method_type" ON "payment"."payment_method_id" = "payment_method_type"."payment_method_type_id"
ORDER BY "payment"."payment_id" ASC;
-- → 3 rows
-- ── round trip 12 ──
WITH "_pgdorm_cti_0" AS (
INSERT INTO "task" ("task_kind_id", "room_id", "summary", "claimed_by", "done")
VALUES ($1, $2, $3, $4, $5)
RETURNING "task_id", "task_kind_id", "room_id", "summary", "claimed_by", "done"
), "_pgdorm_cti_1" AS (
INSERT INTO "cleaning_task" ("task_id", "task_kind_id", "extra_towels", "peanut_refill_kg")
SELECT "task_id", "task_kind_id", $6, $7
FROM "_pgdorm_cti_0"
RETURNING "task_id", "task_kind_id", "extra_towels", "peanut_refill_kg"
)
SELECT
"_pgdorm_cti_1"."task_id",
"_pgdorm_cti_1"."task_kind_id",
"_pgdorm_cti_0"."room_id",
"_pgdorm_cti_0"."summary",
"_pgdorm_cti_0"."claimed_by",
"_pgdorm_cti_0"."done",
"_pgdorm_cti_1"."extra_towels",
"_pgdorm_cti_1"."peanut_refill_kg"
FROM "_pgdorm_cti_0"
INNER JOIN "_pgdorm_cti_1" USING ("task_id");
-- → 1 row
-- ── round trip 13 ──
WITH "_pgdorm_cti_0" AS (
INSERT INTO "task" ("task_kind_id", "room_id", "summary", "claimed_by", "done")
VALUES ($1, $2, $3, $4, $5)
RETURNING "task_id", "task_kind_id", "room_id", "summary", "claimed_by", "done"
), "_pgdorm_cti_1" AS (
INSERT INTO "maintenance_task" ("task_id", "task_kind_id", "requires_welder", "parts_cost")
SELECT "task_id", "task_kind_id", $6, $7
FROM "_pgdorm_cti_0"
RETURNING "task_id", "task_kind_id", "requires_welder", "parts_cost"
)
SELECT
"_pgdorm_cti_1"."task_id",
"_pgdorm_cti_1"."task_kind_id",
"_pgdorm_cti_0"."room_id",
"_pgdorm_cti_0"."summary",
"_pgdorm_cti_0"."claimed_by",
"_pgdorm_cti_0"."done",
"_pgdorm_cti_1"."requires_welder",
"_pgdorm_cti_1"."parts_cost"
FROM "_pgdorm_cti_0"
INNER JOIN "_pgdorm_cti_1" USING ("task_id");
-- → 1 row
-- ── round trip 14 ──
SELECT
"maintenance_task"."task_id",
"maintenance_task"."task_kind_id",
"task"."room_id",
"task"."summary",
"task"."claimed_by",
"task"."done",
"maintenance_task"."requires_welder",
"maintenance_task"."parts_cost"
FROM "maintenance_task"
INNER JOIN "task" USING ("task_id")
WHERE "maintenance_task"."requires_welder" IS TRUE;
-- → 1 row
-- ── round trip 15 ──
SELECT
"task_id",
"task_kind_id",
"room_id",
"summary",
"claimed_by",
"done"
FROM "task"
ORDER BY "task_id" ASC;
-- → 2 rows
Shift report
- Modeled compact polymorphic rows with STI (
Payment→CardPayment,BankTransfer,VoucherPayment) - Hydrated exact Python subclasses from a base
pg.select(Payment)query - Modeled wide subtype tables with CTI (
joined=True) onTask - Inserted across base + subtype tables atomically in 1 RTT via a writable CTE
- Backed every discriminator with a
TypeTableforeign key instead of magic strings
Try it yourself
Open the wire transcript above and find the CREATE TABLE "payment" setup in examples/__wire__/inheritance_payments_tasks.sql. Look at the disjoint CHECK constraints pgdorm generated automatically for each payment variant.
Go deeper: tests/integration/models/inheritance/test_inheritance.py · tests/integration/models/grid/test_grid.py (live PostgreSQL test suites & snapshots)
Sticky note from Management
"3 AM housekeeping shift starts in ten minutes. Three keepers grabbed the SAME room last night and woke Jumbo up three times. Build a task queue — and NO, we are NOT buying a message broker."
← PreviousChapter 6 · No Double BookingsChapter 6 · WITHOUT OVERLAPS Ranges
Next →Chapter 8 · The 3 AM Task BoardChapter 8 · Locks, SKIP LOCKED & NOTIFY