Skip to content

Chapter 2 — Partial Updates & Guardrails#

Act I · Chapter 2 Night 1 · 00:40 7 min readDifficulty 2 of 5

PATCH semantics that never wipe a column by accident, and a DELETE that refuses to delete everything.

pg.UNSETRETURNING OLD/NEWUnsafeDmlErrorUniqueViolationError
▶ Run it yourself · examples/154_patch_and_returning.py
00:40. Pip, a Bornean pygmy elephant, has been at the kiosk for eleven minutes.

00:40. Pip, a Bornean pygmy elephant, has been at the kiosk for eleven minutes.

Pip: I'd like the newsletter, please! Just the newsletter. Don't touch anything else, I like my phone number.

Panda: Easy. Take the whole form, UPDATE every column. Empty fields become NULL. Clean!

Pip: …why did I stop getting text messages?

The mission#

The front desk receives partial changes all night: one guest opts into marketing, another removes a phone number, a third earns loyalty points at two desks at once. Maya needs updates that:

  1. change only the fields that were actually sent,
  2. can deliberately set a field to "nothing" (NULL) when that's the intent,
  3. never lose points when two desks write at the same time,
  4. never let a tired intern delete every room in the building.

The Panda's plan

"Read the guest, change the fields in Python, write the whole row back. For points: read the balance, add 1,250, write it back."

Three bugs in one plan. Omitted form fields overwrite real data with NULL. Two desks crediting points at the same moment both read 0 and both write 1250, so one credit vanishes. And nothing stops DELETE FROM room from running without a WHERE.

1. Updates that only touch what you sent#

pgdorm gives every field three states, which is exactly what an HTTP PATCH needs:

You pass pgdorm does
pg.UNSET (the default) Leaves the column out of the UPDATE entirely.
None Writes SQL NULL on purpose.
A value Overwrites the column.
examples/154_patch_and_returning.py · patch_guest
async def patch_guest(
    pool: pg.Pool,
    guest_id: int,
    *,
    phone: str | pg.UnsetType | None = pg.UNSET,
    country: str | pg.UnsetType | None = pg.UNSET,
    marketing_opt_in: bool | pg.UnsetType = pg.UNSET,
) -> Guest:
    # UNSET skips the column, None writes SQL NULL, and a concrete value overwrites it.
    return await pool.one(
        pg.update(Guest)
        .set(phone=phone, country=country, marketing_opt_in=marketing_opt_in)
        .where(Guest.guest_id == guest_id)
        .returning(Guest)
    )

Here it is in action. Pip opts in, and her phone number survives. Later she asks to remove the phone number, and only that changes:

examples/154_patch_and_returning.py · run
async def run(pool: pg.Pool) -> None:
    dorm, pip = await check_in_pip(pool)

    pip = await patch_guest(pool, pip.guest_id, marketing_opt_in=True)
    print(f"opted in: phone={pip.phone}, country={pip.country}, opt_in={pip.marketing_opt_in}")
    # => orphan room blocked: fk_jwckuaya

    pip = await patch_guest(pool, pip.guest_id, phone=None)
    print(f"cleared phone: phone={pip.phone}, country={pip.country}")
    # => full-table delete refused by UnsafeDmlError

    await credit_points(pool, pip.guest_id)
    await reject_bad_writes(pool, dorm)

What just happened

  • patch_guest(pool, pip.guest_id, marketing_opt_in=True) left phone and country as pg.UNSET, so the generated UPDATE only contains "marketing_opt_in" = $1. Check the SQL at the end of the chapter.
  • phone=None is not the same as "not sent". It produced "phone" = $1 with NULL as the value, exactly as intended.
  • The type hints (str | pg.UnsetType | None) make the three states visible in your editor, and type checkers enforce them.

2. Arithmetic on the server, old and new values in one trip#

Loyalty points are where lost updates hide. Instead of reading the balance into Python, Maya lets PostgreSQL do the addition, and asks for the value before and after in the same statement:

examples/154_patch_and_returning.py · credit_points
async def credit_points(pool: pg.Pool, guest_id: int) -> None:
    # Server-side arithmetic prevents lost updates; RETURNING OLD/NEW reports both in 1 RTT.
    async with pool.trace() as tr:
        before, after = await pool.one(
            pg.update(Guest)
            .set(peanut_points=Guest.peanut_points + 1_250)
            .where(Guest.guest_id == guest_id)
            .returning(pg.old(Guest.peanut_points), pg.new(Guest.peanut_points))
        )
    print(f"peanut points: {before} -> {after} ({tr.rtts} RTT)")
    # => opted in: phone=+60 88 555 019, country=MY, opt_in=True

What just happened

  • Guest.peanut_points + 1_250 is an expression, not a Python number. It compiles to SET "peanut_points" = "peanut_points" + $1, so PostgreSQL applies it atomically under the row lock. Two desks can run this at once and both credits land.
  • pg.old(...) and pg.new(...) use RETURNING OLD/NEW in PostgreSQL. You get the before and after values of the same row, in the same round trip (1 RTT, measured by pool.trace()).

3. Typed errors and a refusal to delete everything#

Constraints are the database's way of saying no. pgdorm turns each "no" into a specific Python exception that carries the constraint's name, so you never parse error strings:

examples/154_patch_and_returning.py · reject_bad_writes
async def reject_bad_writes(pool: pg.Pool, dorm: Dormitory) -> None:
    room_101 = Room(
        dormitory_id=dorm.dormitory_id,
        number="101",
        floor=1,
        category=RoomCategory.BUNK,
        max_guests=2,
    )
    await pool.execute(pg.insert(Room).values(room_101))

    # Constraint violations surface as typed exceptions carrying the exact constraint name.
    try:
        await pool.execute(pg.insert(Room).values(room_101))
    except pg.UniqueViolationError as err:
        print(f"duplicate room blocked: {err.constraint}")
        # => cleared phone: phone=None, country=MY

    try:
        await pool.execute(
            pg.insert(Room).values(
                Room(
                    dormitory_id=dorm.dormitory_id,
                    number="999",
                    floor=9,
                    category=RoomCategory.PENTHOUSE,
                    max_guests=20,
                )
            )
        )
    except pg.CheckViolationError as err:
        print(f"overcrowded room blocked: {err.constraint}")
        # => peanut points: 0 -> 1250 (1 RTT)

    try:
        await pool.execute(
            pg.insert(Room).values(
                Room(
                    dormitory_id=-1, number="404", floor=4, category=RoomCategory.POD, max_guests=2
                )
            )
        )
    except pg.ForeignKeyViolationError as err:
        print(f"orphan room blocked: {err.constraint}")
        # => duplicate room blocked: uq_shlxfdur

    # Bare DELETE / UPDATE without WHERE is refused at compile time unless explicitly justified.
    try:
        pg.compile(pg.delete(Room))
    except pg.UnsafeDmlError:
        print("full-table delete refused by UnsafeDmlError")
        # => overcrowded room blocked: ck_zzdaverq

What just happened

  • Room 101 already exists in Lisbon, so UNIQUE (dormitory_id, number) fires and you catch pg.UniqueViolationError with err.constraint == "room_dormitory_id_number_key".
  • Twenty guests in one room breaks CHECK (max_guests BETWEEN 1 AND 8), raised as pg.CheckViolationError.
  • A room in dormitory -1 has no parent, so the foreign key raises pg.ForeignKeyViolationError.
  • pg.delete(Room) with no .where(...) never reaches the network: pg.compile(...) raises pg.UnsafeDmlError immediately.

When you really do mean every row

Say so, with a reason: pg.delete(Room).allow_full_table(reason="nightly reset of the demo database"). The reason string ends up in code review, where it belongs.

Ferris' basement: why RETURNING OLD/NEW matters

In older PostgreSQL releases, getting the previous value of an updated row meant either a second SELECT … FOR UPDATE round trip before the update, or a self-joining CTE trick. RETURNING old.col, new.col does it natively. pgdorm assumes modern PostgreSQL as its baseline so it can use syntax like this everywhere, while capability-gating newer server features before anything hits the wire.

What PostgreSQL actually received#

🔭 What PostgreSQL received: 9 statements in 9 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 19 statements omitted · full transcript in examples/__wire__/patch_and_returning.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 ──
UPDATE "guest"
SET "marketing_opt_in" = $1
WHERE "guest_id" = $2
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 4 ──
UPDATE "guest"
SET "phone" = $1
WHERE "guest_id" = $2
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 5 ──
UPDATE "guest"
SET "peanut_points" = "peanut_points" + $1
WHERE "guest_id" = $2
RETURNING OLD."peanut_points", NEW."peanut_points";
-- → 1 row

-- ── round trip 6 ──
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);
-- → 1 affected

-- ── round trip 7 ──
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);
-- ✗ PostgreSQL rejected this round trip: SQLSTATE 23505

-- ── round trip 8 ──
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);
-- ✗ PostgreSQL rejected this round trip: SQLSTATE 23514

-- ── round trip 9 ──
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);
-- ✗ PostgreSQL rejected this round trip: SQLSTATE 23503

Shift report

  • Sent partial updates with pg.UNSET, and deliberate NULLs with None
  • Did arithmetic on the server instead of read-modify-write in Python
  • Read before and after values with PostgreSQL RETURNING OLD/NEW
  • Caught constraint violations as typed exceptions
  • Watched pgdorm refuse a DELETE without WHERE

Try it yourself

In reject_bad_writes, swap pg.delete(Room) for pg.update(Room).set(out_of_service=True). Does pgdorm treat a full-table UPDATE like a full-table DELETE?

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

Sticky note from Management

"FERRY DOCKED. Herd of forty walking up the hill. Twelve rooms still not in the system. 01:00 SHARP."