Chapter 4 — A Mammoth at the Kiosk#
Enums the database can enforce, typed JSONB, UUIDv7 and PostgreSQL virtual columns.
TypeTableTypeDecoratoruuidv7()VIRTUAL columnsJsonb[T]partial indexesexamples/157_column_types_and_ddl.py02:30. The kiosk screen has a trunk print on it.
Bram: Email: [email protected] . Species: mammoth. Pillow: glacier foam. Diet: hay, and apples on Sundays!
Panda: Store it all as text. Species "mamoth", a JSON string for the pillow, and we'll .lower() the email… somewhere.
Maya: "Somewhere" is how we got three spellings of "savanna" last week.
The mission#
Make the schema do the boring work, so no service, script or intern can store nonsense:
- species must be one of four real values, and SQL users should see names, not mystery integers;
- emails are always lowercase, however they're typed;
- every guest gets a public badge ID that's safe to put in URLs;
- preferences (pillow, diet, reinforced floor) are structured, typed data;
- "available penthouses with a mud spa" is a fast query, even with a broken room on the floor.
The Panda's plan
Free-text species, email.strip().lower() sprinkled across twelve files, and json.loads(guest["preferences"]) wherever someone remembers. The first missed .lower() creates a duplicate account. The first "Savannah" breaks every report grouped by species.
1. Lookup tables the database enforces#
A TypeTable is a small lookup table generated from a Python IntEnum. create_all() seeds it with the enum's values, and every column that uses the enum becomes a foreign key to it:
class LowerEmail(pg.TypeDecorator[str, str]):
"""Normalize guest email addresses to lowercase before binding and on hydration."""
impl = "text"
def process_bind_param(self, value: str) -> str:
return value.strip().lower()
def process_result_value(self, value: str) -> str:
return value.lower()
@dataclass(frozen=True, kw_only=True, slots=True)
class StayPreferences:
reinforced_floor: bool = False
extra_peanuts: bool = False
mud_bath_access: bool = False
pillow: str | None = None
dietary: tuple[str, ...] = ()
LowerEmail is a TypeDecorator: a tiny class that transforms values on their way into and out of PostgreSQL. StayPreferences is a frozen dataclass that pgdorm stores as typed JSONB.
2. Check Bram in, messy input and all#
async def inspect_type_table_and_codecs(pool: pg.Pool) -> None:
# create_all seeds every TypeTable idempotently so SQL users see codes, not bare ints.
species_rows = await pool.all(
pg.select(SpeciesType).order_by(SpeciesType.species_type_id.asc())
)
print("seeded species:", [row.code for row in species_rows])
# => seeded species: ['savanna', 'forest', 'pygmy', 'mammoth']
# LowerEmail TypeDecorator normalizes mixed-case addresses on bind & read; PostgreSQL fills
# in UUIDv7 public_id, virtual full_name, and stores typed StayPreferences in JSONB.
bram = await pool.one(
pg.insert(Guest)
.values(
Guest(
email=" [email protected] ",
first_name="Bram",
last_name="Pleistocene",
species=Species.MAMMOTH,
birth_date=date(1998, 12, 1),
preferences=StayPreferences(
reinforced_floor=True,
mud_bath_access=True,
pillow="glacier-foam",
dietary=("hay", "apples"),
),
)
)
.returning(Guest)
)
print(f"guest {bram.full_name}: email={bram.email} badge={bram.public_id}")
# => guest Bram Pleistocene: [email protected] badge=<UUIDv7>
print(
f"prefs: reinforced={bram.preferences.reinforced_floor}, "
f"pillow={bram.preferences.pillow}, dietary={bram.preferences.dietary}"
)
# => prefs: reinforced=True, pillow=glacier-foam, dietary=('hay', 'apples')
# Lookup works with any casing because LowerEmail transforms filter parameters too.
looked_up = await pool.one(pg.select(Guest).where(Guest.email == "[email protected]"))
print(f"case-insensitive email hit: {looked_up.guest_id == bram.guest_id}")
# => case-insensitive email hit: True
What just happened
select(SpeciesType)shows the seeded rows:savanna,forest,pygmy,mammoth. Analysts writing SQL see readable codes, andspecies = 7would be rejected by a real foreign key." [email protected] "was stored as[email protected].LowerEmailran before binding.- The same decorator runs on query parameters too: searching for
"[email protected]"finds him. public_idcame from PostgreSQL's built-inuuidv7(): time-ordered, so it's index-friendly, and safe to show publicly (the test suite masks it as<UUIDv7>because it changes on every run).full_nameis a virtual generated column (native in PostgreSQL): computed on read, zero bytes on disk.bram.preferencesis a realStayPreferencesobject, sobram.preferences.dietaryis a tuple, not a JSON string.
3. Arrays and a partial index for the mud-spa search#
Room 302 is closed for floor reinforcement. The Room table declares a partial index, idx_room_available_by_category, that only covers rooms in service, plus a TEXT[] column of amenities:
class Room(pg.Table):
room_id: Col[int] = pg.pk(default=pg.identity())
dormitory_id: Col[int] = pg.fk(Dormitory, on_delete=pg.enums.OnDelete.CASCADE)
number: Col[Code]
floor: Col[pg.Int2]
category: Col[RoomCategory] = pg.fk(RoomCategoryType)
max_weight_kg: Col[pg.Int4] = pg.col(default=6_000)
max_guests: Col[pg.Int2]
amenities: Col[list[str]] = pg.col(default_factory=list)
out_of_service: Col[bool] = pg.col(default=False)
@classmethod
def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
return (
pg.Check(cls.max_weight_kg >= 500),
pg.Check(cls.max_guests.between(1, 8)),
pg.Unique(cls.dormitory_id, cls.number),
pg.Index(cls.dormitory_id, cls.category, where=cls.out_of_service.is_false()),
)
async def query_arrays_and_partial_index(pool: pg.Pool) -> None:
dorm = await pool.one(
pg.insert(Dormitory)
.values(
Dormitory(
code="LIS",
name="The Elephant Dormitory — Lisbon",
city="Lisbon",
country="PT",
timezone="Europe/Lisbon",
city_tax=Decimal("4.50"),
opened_on=date(2024, 5, 1),
)
)
.returning(Dormitory)
)
await pool.execute(
pg.insert_many(
Room,
[
Room(
dormitory_id=dorm.dormitory_id,
number="301",
floor=3,
category=RoomCategory.PENTHOUSE,
max_weight_kg=9_500,
max_guests=4,
amenities=["reinforced_floor", "mud_spa", "river_view"],
),
Room(
dormitory_id=dorm.dormitory_id,
number="302",
floor=3,
category=RoomCategory.PENTHOUSE,
max_weight_kg=9_500,
max_guests=4,
amenities=["reinforced_floor", "mud_spa"],
out_of_service=True,
),
Room(
dormitory_id=dorm.dormitory_id,
number="101",
floor=1,
category=RoomCategory.BUNK,
max_weight_kg=2_000,
max_guests=2,
amenities=["peanut_bin"],
),
],
)
)
# Filter matches the partial index (`out_of_service IS FALSE`) + array containment (@>).
open_penthouses = (
pg.select(Room)
.where(
(Room.dormitory_id == dorm.dormitory_id)
& (Room.category == RoomCategory.PENTHOUSE)
& Room.out_of_service.is_false()
& Room.amenities.contains(["mud_spa"])
)
.order_by(Room.number.asc())
)
matches = await pool.all(open_penthouses)
print("available mud-spa penthouses:", [r.number for r in matches])
# => available mud-spa penthouses: ['301']
partial_idx = next(i.name for i in Room.__pg_resolved_indexes__ if i.where_sql is not None)
plan = await pool.explain(open_penthouses, disable_seqscan=True)
plan.assert_uses_index(partial_idx)
print(f"planner used partial index: {partial_idx in plan.summary()}")
# => planner used partial index: True
What just happened
Room.amenities.contains(["mud_spa"])compiles to PostgreSQL's array containment operator@>.Room.out_of_service.is_false()matches the partial index'sWHEREclause, so the planner can use the small index that skips broken rooms.pool.explain(..., disable_seqscan=True)asks PostgreSQL for its plan, andplan.assert_uses_index(...)turns "is my index used?" into an assertion your tests can run.
Ferris' basement: why integer lookup keys instead of PostgreSQL enums?
PostgreSQL has native ENUM types, but adding or renaming a value is a schema migration, and other tables can't hold extra columns about each value. A TypeTable is a plain table: it can carry descriptions or sort orders, it's joined like any other table, and pgdorm keeps it in sync with your IntEnum every time create_all() runs. TypeTable keys default to INTEGER; regular entity keys default to BIGINT identities.
What PostgreSQL actually received#
🔭 What PostgreSQL received: 6 statements in 6 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 19 statements omitted · full transcript in examples/__wire__/column_types_and_ddl.sql
-- ── round trip 1 ──
SELECT "species_type_id", "code"
FROM "species_type"
ORDER BY "species_type_id" ASC;
-- → 4 rows
-- ── round trip 2 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
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";
-- → 1 row
-- ── round trip 3 ──
SELECT
"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"
FROM "guest"
WHERE "email" = $1;
-- → 1 row
-- ── round trip 4 ──
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 5 ──
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);
-- → 3 affected
-- ── round trip 6 ──
SELECT
"room_id",
"dormitory_id",
"number",
"floor",
"category",
"max_weight_kg",
"max_guests",
"amenities",
"out_of_service"
FROM "room"
WHERE "dormitory_id" = $1 AND "category" = $2 AND "out_of_service" IS FALSE AND "amenities" @> $3
ORDER BY "number" ASC;
-- → 1 row
Shift report
- Generated and seeded lookup tables from Python enums
- Normalised values on the way in and out with a
TypeDecorator - Let PostgreSQL generate UUIDv7 badges and virtual columns
- Stored typed preferences in
JSONBand read them back as dataclasses - Queried arrays and proved a partial index is used
Try it yourself
Add pillow="cloud" to Bram's StayPreferences and a new boolean field snores: bool = False to the dataclass in examples/schema.py. Does the stored JSON change for guests created before the field existed?
Go deeper: tests/integration/codecs/test_codecs.py · tests/integration/features/pg18/test_pg18.py (live PostgreSQL test suites & snapshots)
Note
Also in pgdorm: Declare ForeignKey(deferrable=True, initially_deferred=True) for cyclic/deferred constraints and typed TsVector / JsonPath columns for full-text and JSONB search — see the Models & Types Reference.
Sticky note from Management
"Good night's work. Next week: GROUP bookings. Some families travel with eleven calves."
← PreviousChapter 3 · The 01:00 HerdChapter 3 · UNNEST Bulk Insert & Upsert
Next →Act II · Full HouseAct II · Joins, Temporal Keys & Locks