Chapter 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()update().set()delete()examples/097_hello_dorm.py00:05. The lobby door creaks open. Something very large is breathing very politely.
Jumbo: Good evening! Jumbo Kalahari, from Botswana. I believe I have a reservation. Somewhere.
Maya: You absolutely do. Give me ninety seconds to… invent the guest database.
Ferris: Ninety seconds? Fine. But every question you ask PostgreSQL costs one round trip, so don't ask twice.
The mission#
Every database app starts with four verbs: create, read, update and delete (CRUD for short). Before Jumbo's brass suitcase touches the floor, Maya needs all four:
- open the Lisbon dormitory,
- check Jumbo in,
- look him up (and confirm a ghost is not staying here),
- upgrade his loyalty tier and, eventually, check him out.
The whole chapter is one runnable script. You'll walk through it step by step.
The Panda's plan
"Easy! INSERT the guest, then SELECT him right back, so we learn which ID the database gave him. Oh, and his badge number. And his default tier. That's just two trips to the database per guest. What could go wrong at 01:00 when the herd arrives?"
Two round trips per check-in, and a window in which another receptionist can change the row between your INSERT and your SELECT.
1. Open the dormitory#
Tables first. pgdorm describes tables as Python classes (Dormitory, Room, Guest, … in the shared examples/schema.py), and create_all() turns them into real PostgreSQL tables:
async def open_dormitory(pool: pg.Pool) -> Dormitory:
# create_all() creates tables in dependency order and seeds every TypeTable.
await pool.create_all(*ACT1_TABLES)
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.00"),
opened_on=date(2024, 5, 1),
)
)
.returning(Dormitory)
)
print(f"opened {dorm.name} (check-in {dorm.check_in:%H:%M})")
# => opened The Elephant Dormitory — Lisbon (check-in 15:00)
return dorm
What just happened
create_all(*ACT1_TABLES)created every Act I table in dependency order (dormitories before rooms, rooms before guests) and seeded the lookup tables such asspecies_typewith their fixed values. Running it twice is harmless.pg.insert(Dormitory).values(Dormitory(...))builds theINSERTfrom a typed object. Misspell a column and your editor complains before PostgreSQL ever sees it.- We never set
check_in, yet the output says15:00. That's the column default from the schema, handed back by.returning(Dormitory).
2. Check Jumbo in#
async def check_in(pool: pg.Pool) -> Guest:
jumbo = await pool.one(
pg.insert(Guest)
.values(
Guest(
email="[email protected]",
first_name="Jumbo",
last_name="Kalahari",
species=Species.SAVANNA,
country="BW",
)
)
.returning(Guest)
)
print(f"checked in {jumbo.full_name} [{jumbo.species.name}] tier={jumbo.loyalty_tier.name}")
# => checked in Jumbo Kalahari [SAVANNA] tier=CALF
return jumbo
What just happened
.returning(Guest)asks PostgreSQL to send back the whole row it just stored, including everything it generated: the identityguest_id, a time-ordered UUIDv7public_idbadge, the defaultloyalty_tier(CALF) andfull_name, a PostgreSQL virtual generated column that is computed on read and never stored.- All of that arrives in the same round trip as the insert. The Panda's second trip simply doesn't exist.
pool.one(...)means "exactly one row, please", and you get a realGuestobject back, not a dictionary.
3. Look him up, and look up a ghost#
async def look_up(pool: pg.Pool, guest_id: int) -> None:
found = await pool.one(pg.select(Guest).where(Guest.guest_id == guest_id))
missing = await pool.one_or_none(pg.select(Guest).where(Guest.email == "[email protected]"))
print(f"lookup: found={found.first_name}, missing={missing}")
# => lookup: found=Jumbo, missing=None
What just happened
.where(Guest.guest_id == guest_id)is ordinary Python comparison syntax that compiles into a parameterisedWHERE "guest_id" = $1. Values travel separately from the SQL text, so there's no string concatenation and no SQL injection.pool.one(...)raisespg.NoResultErrorif nothing matches. Use it when "not found" is a bug.pool.one_or_none(...)returnsGuest | None. Use it when "not found" is a perfectly normal answer, like a ghost who never checked in.
4. Upgrade, then check out#
async def upgrade_and_check_out(pool: pg.Pool, guest_id: int) -> None:
upgraded = await pool.one(
pg.update(Guest)
.set(loyalty_tier=LoyaltyTier.SILVER, peanut_points=500)
.where(Guest.guest_id == guest_id)
.returning(Guest)
)
print(
f"upgraded {upgraded.full_name}: {upgraded.loyalty_tier.name}, {upgraded.peanut_points} pts"
)
# => upgraded Jumbo Kalahari: SILVER, 500 pts
deleted = await pool.execute(pg.delete(Guest).where(Guest.guest_id == guest_id))
print(f"checked out {deleted} guest")
# => checked out 1 guest
What just happened
pg.update(Guest).set(...)names exactly the columns to change; everything else stays untouched.pool.execute(...)returns how many rows were affected, which is handy for "did that actually delete anything?" checks.- Both statements carry a
.where(...). Try leaving it out in the next chapter and watchpgdormrefuse to run it.
Ferris' basement: why one question costs one round trip
Each pool.one(...) above is a single exchange in PostgreSQL's extended query protocol: Parse (only the first time; after that the prepared statement is reused), Bind with the parameters, Execute, then Sync, and PostgreSQL answers. That's one network round trip (RTT). INSERT … RETURNING is what lets the ID, the badge and the computed name ride back on the same trip, instead of costing a second SELECT.
What PostgreSQL actually received#
Every statement this chapter sent was captured from a live PostgreSQL while the test suite ran. Open it up. This is the real SQL, not a hand-written approximation:
🔭 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__/hello_dorm.sql
-- ── round trip 1 ──
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 "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 "guest_id" = $1;
-- → 1 row
-- ── round trip 4 ──
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;
-- ── round trip 5 ──
UPDATE "guest"
SET
"loyalty_tier" = $1,
"peanut_points" = $2
WHERE "guest_id" = $3
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 6 ──
DELETE FROM "guest"
WHERE "guest_id" = $1;
-- → 1 affected
Shift report
- Created tables and seeded lookup values with
create_all() - Inserted a typed row and received server-generated values with
.returning() - Told "exactly one" (
one) apart from "maybe none" (one_or_none) - Updated and deleted one row by primary key
Try it yourself
Run the script linked at the top of this page. Then change Jumbo's country="BW" to country="BWA" and run it again. Which error do you get, and which layer raised it? (Hint: look up Country in examples/schema.py.)
Go deeper: tests/integration/crud/test_quickstart.py (live PostgreSQL test suites & snapshots)
Sticky note from Management
"Guest in room 2B wants to change ONE thing on her profile. Do NOT erase the rest of it this time."
← PreviousAct I · The First NightAct I · Typed CRUD, Bulk & DDL
Next →Chapter 2 · Partial Updates & GuardrailsChapter 2 · Partial PATCH & Guardrails