Act I — The First Night#
Night 1. The spreadsheet is gone. The lobby is not empty.
Maya: Okay. Tables, rows, a guest list. How hard can it be?
Bram: HELLO! Is the top bunk free? It's always free for me!
Friday 23:45 to Saturday 03:00. Four chapters, one night, and by dawn the hostel runs on PostgreSQL. You'll create tables from Python classes, insert and read rows, update them without wiping anything by accident, load a whole herd in one statement, and teach the database which species exist.
Tonight's shifts#
| Ch. | Shift | What you'll get | Superpowers |
|---|---|---|---|
| 1 | First Check-In | Insert a row and get the ID, UUIDv7, defaults and computed columns back in the same round trip. | create_all() insert().returning() one_or_none() |
| 2 | Partial Updates & Guardrails | PATCH semantics that never wipe a column by accident, and a DELETE that refuses to delete everything. | pg.UNSET RETURNING OLD/NEW UnsafeDmlError |
| 3 | The 01:00 Herd | Insert 3 or 3,000 rows with one SQL text, one prepared statement and one round trip. | insert_many() UNNEST WITH ORDINALITY in_any() → = ANY($1) |
| 4 | A Mammoth at the Kiosk | Enums the database can enforce, typed JSONB, UUIDv7 and PostgreSQL virtual columns. | TypeTable TypeDecorator uuidv7() |
The Act I schema#
Rather than dumping a twenty-table enterprise diagram on Maya at midnight, Act I uses just the core tables from the shared examples/schema.py. Every example in the book imports from that one file, so you'll recognise these classes everywhere.
Three house rules make the schema boring in the best way:
- Every table has a
<table_name>_idprimary key.guest_id,room_id,dormitory_id. You never have to guess whichida join refers to, and pgdorm can writeJOIN … USING (guest_id)for you. - Lookup values live in
TypeTables, never in strings.SpeciesType,RoomCategoryTypeandLoyaltyTierTypeare real tables seeded from Python enums, and every reference to them is a foreign key. - No raw SQL. Tables, constraints, defaults and indexes are all typed Python, compiled to SQL by pgdorm's Rust compiler.
class SpeciesType(pg.TypeTable, enum=Species):
species_type_id: Col[Species] = pg.pk()
class Dormitory(pg.Table):
dormitory_id: Col[int] = pg.pk(default=pg.identity())
region_id: Col[int | None] = pg.fk(Region, default=None)
code: Col[Code] = pg.col(unique=True)
name: Col[str]
city: Col[str]
country: Col[Country]
timezone: Col[str]
check_in: Col[time] = pg.col(default=time(15, 0))
check_out: Col[time] = pg.col(default=time(11, 0))
city_tax: Col[Money] = pg.col(default=Decimal("2.50"))
opened_on: Col[date]
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()),
)
class Guest(pg.Table):
guest_id: Col[int] = pg.pk(default=pg.identity())
public_id: Col[UUID] = pg.col(default=pg.uuidv7(), unique=True)
email: Col[Email] = pg.col(unique=True)
first_name: Col[str]
last_name: Col[str]
full_name: Col[str] = pg.generated(mode=pg.enums.GeneratedMode.VIRTUAL)
species: Col[Species] = pg.fk(SpeciesType, default=Species.SAVANNA)
phone: Col[str | None] = pg.col(default=None)
country: Col[Country | None] = pg.col(default=None)
birth_date: Col[date | None] = pg.col(default=None)
loyalty_tier: Col[LoyaltyTier] = pg.fk(LoyaltyTierType, default=LoyaltyTier.CALF)
peanut_points: Col[int] = pg.col(default=0)
preferences: Col[pg.Jsonb[StayPreferences]] = pg.col(default_factory=StayPreferences)
marketing_opt_in: Col[bool] = pg.col(default=False)
created_at: Col[datetime] = pg.col(default=pg.now(), server_managed=True)
@classmethod
def __generated__(cls) -> tuple[pg.Generated, ...]:
return (pg.Generated(cls.full_name, cls.first_name.concat(" ").concat(cls.last_name)),)
@classmethod
def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
return (pg.Index(cls.last_name, cls.guest_id),)
pgdorm draws the same model as an entity-relationship diagram, straight from those classes (pg.to_svg_erd(*ACT1_TABLES), pure Rust, no Graphviz):
Next →Chapter 1 · First Check-InChapter 1 · INSERT RETURNING & CRUD