Skip to content

Chapter 5 — Group Bookings & Folios#

Act II · Chapter 5 Week 2 · Monday 21:00 10 min readDifficulty 3 of 5

Joins that write themselves, refuse to be ambiguous, and load parents plus children in 2 round trips.

JOIN … USINGJoinLintErrorlink tablessplit_load()
▶ Run it yourself · examples/207_joins_and_folios.py
Week 2, Monday 21:00. Jumbo is back at the desk, and this time he brought his niece Nala. Behind them, Bram is negotiating a mud-spa package for Pip.

Week 2, Monday 21:00. Jumbo is back at the desk, and this time he brought his niece Nala. Behind them, Bram is negotiating a mud-spa package for Pip.

Jumbo: Two suites, four elephants, one shared bill per group, please!

Panda: Easy! Fetch all bookings, then loop over each booking to fetch its guests and its charges. Or join all three tables at once and deduplicate in Python!

Ferris: Both of those hurt. One is N+1 round trips; the other multiplies rows until your folio looks twice as expensive as it is.

The mission#

A single guest checking into a single room was Act I. Now Maya has to model real group stays without falling into either classic ORM trap:

  1. link multiple guests to one booking via a clean junction table (BookingGuest),
  2. record line-item charges whose totals PostgreSQL computes automatically,
  3. join tables cleanly without ambiguous columns or silent bugs,
  4. load bookings together with all their charges and co-travellers in 2 round trips, with zero Cartesian row multiplication.

The Panda's plan

Option A: fetch 50 bookings, then run SELECT * FROM charge WHERE booking_id = $1 and SELECT * FROM booking_guest WHERE booking_id = $1 inside a for loop — 101 round trips.

Option B: SELECT * FROM booking JOIN charge ... JOIN booking_guest ... — a booking with 4 charges and 5 co-travellers comes back as 20 duplicate rows (a Cartesian product), and summing charge.amount over those rows bills the guest 5× too much.

1. Bookings, co-travellers and stored charges#

Notice BookingGuest in examples/schema.py: even a link table keeps its own <table_name>_id primary key (booking_guest_id) plus pg.Unique(booking_id, guest_id). And Charge.amount is a stored generated column (quantity * unit_price), so a line item's subtotal can never drift out of sync with its quantity or unit price.

examples/207_joins_and_folios.py · create_group_bookings
async def create_group_bookings(
    pool: pg.Pool, dorm: Dormitory, guests: list[Guest]
) -> list[Booking]:
    jumbo, pip, bram = guests
    calf = await pool.one(
        pg.insert(Guest)
        .values(
            Guest(
                email="[email protected]",
                first_name="Nala",
                last_name="Kalahari",
                species=Species.SAVANNA,
                country="BW",
            )
        )
        .returning(Guest)
    )

    bookings = await pool.all(
        pg.insert_many(
            Booking,
            [
                Booking(
                    dormitory_id=dorm.dormitory_id,
                    primary_guest_id=jumbo.guest_id,
                    stay=pg.Range(lower=date(2026, 7, 10), upper=date(2026, 7, 13)),
                    reference_code="HERD-101",
                ),
                Booking(
                    dormitory_id=dorm.dormitory_id,
                    primary_guest_id=bram.guest_id,
                    stay=pg.Range(lower=date(2026, 7, 11), upper=date(2026, 7, 14)),
                    reference_code="HERD-102",
                ),
            ],
        ).returning(Booking)
    )
    b_jumbo, b_bram = bookings

    # Link table (`booking_guest`) tracks co-travellers with its own PK + UNIQUE(booking, guest).
    await pool.execute(
        pg.insert_many(
            BookingGuest,
            [
                BookingGuest(booking_id=b_jumbo.booking_id, guest_id=jumbo.guest_id),
                BookingGuest(booking_id=b_jumbo.booking_id, guest_id=calf.guest_id),
                BookingGuest(booking_id=b_bram.booking_id, guest_id=bram.guest_id),
                BookingGuest(booking_id=b_bram.booking_id, guest_id=pip.guest_id),
            ],
        )
    )

    # Stored generated column `Charge.amount = quantity * unit_price` is computed by PostgreSQL.
    await pool.execute(
        pg.insert_many(
            Charge,
            [
                Charge(
                    booking_id=b_jumbo.booking_id,
                    kind=ChargeKind.NIGHTLY_RATE,
                    description="Private suite (3 nights)",
                    quantity=3,
                    unit_price=Decimal("120.00"),
                ),
                Charge(
                    booking_id=b_jumbo.booking_id,
                    kind=ChargeKind.PEANUT_BAR,
                    description="Roasted peanut bucket",
                    quantity=4,
                    unit_price=Decimal("7.50"),
                ),
                Charge(
                    booking_id=b_bram.booking_id,
                    kind=ChargeKind.MUD_SPA,
                    description="Glacier mud soak",
                    quantity=1,
                    unit_price=Decimal("85.00"),
                ),
            ],
        )
    )
    return bookings

What just happened

  • Booking carries primary_guest_id (a role-named foreign key to Guest.guest_id) alongside stay, a PostgreSQL date range (pg.Range).
  • BookingGuest links each booking to every elephant in the party — Jumbo and Nala on HERD-101, Bram and Pip on HERD-102.
  • Charge rows never pass amount: PostgreSQL calculates quantity * unit_price on insert (3 × 120.00 = 360.00, 4 × 7.50 = 30.00, 1 × 85.00 = 85.00).

2. Joins that write themselves, and split_load()#

One big JOIN split_load(): 2 round trips booking × guests × charges HERD-101 · Jumbo · Private suite … HERD-101 · Jumbo · Private suite … HERD-101 · Jumbo · Private suite … HERD-101 · Jumbo · Private suite … HERD-101 · Jumbo · Private suite … HERD-101 · Jumbo · Private suite … HERD-101 · Jumbo · Private suite … HERD-101 · Jumbo · Private suite … 2 guests × 10 charges = 20 duplicated rows Wave 1: SELECT bookings Wave 2: charges = ANY($1) + members = ANY($1), pipelined Wave 2 queries are pipelined together underone REPEATABLE READ snapshot. Zero duplicates.

Because every table uses <table_name>_id, BookingGuest.booking_id and Booking.booking_id share the exact same name. pgdorm sees that symmetry and emits JOIN … USING ("booking_id") automatically — and refuses to guess when a join is ambiguous or violates require_using=True:

examples/207_joins_and_folios.py · demonstrate_joins_and_split_load
async def demonstrate_joins_and_split_load(pool: pg.Pool) -> None:
    # Symmetric FKs auto-emit `JOIN ... USING`; `via=` disambiguates multiple FKs to Guest.
    using_q = (
        pg.select(BookingGuest)
        .join(Booking, require_using=True)
        .join(Guest, via=BookingGuest.guest_id, require_using=True)
        .columns(Booking.reference_code, Guest.full_name)
        .order_by(Booking.reference_code.asc(), Guest.first_name.asc())
    )
    print(f"symmetric join uses USING: {'USING' in pool.compile(using_q).sql}")
    # => symmetric join uses USING: True
    roster = await pool.all(using_q)
    for ref, full_name in roster:
        print(f"  {ref} -> {full_name}")
        # =>   HERD-101 -> Jumbo Kalahari
        # =>   HERD-101 -> Nala Kalahari
        # =>   HERD-102 -> Bram Pleistocene
        # =>   HERD-102 -> Pip Kinabatangan

    # Role-named FK (`primary_guest_id` != `guest_id`) falls back to `ON`; `require_using=True`
    # fails loudly via JoinLintError so asymmetric joins are always deliberate.
    try:
        pg.compile(pg.select(Booking).join(Guest, require_using=True))
    except pg.JoinLintError:
        print("role-named FK rejected by require_using=True (JoinLintError)")
        # => role-named FK rejected by require_using=True (JoinLintError)

    primary_q = (
        pg.select(Booking)
        .join(Guest)
        .columns(Booking.reference_code, Guest.full_name)
        .order_by(Booking.reference_code.asc())
    )
    print("primary guests:", await pool.all(primary_q))
    # => primary guests: [('HERD-101', 'Jumbo Kalahari'), ('HERD-102', 'Bram Pleistocene')]

    # Load bookings + charges + co-travellers under REPEATABLE READ in 2 RTTs, zero Cartesian bloat.
    charges_rel = pg.SplitRelation(
        name="charges",
        child_table=Charge,
        child_fk=Charge.booking_id,
        parent_key=Booking.booking_id,
        order_by=(Charge.charge_id.asc(),),
    )
    members_rel = pg.SplitRelation(
        name="members",
        child_table=BookingGuest,
        child_fk=BookingGuest.booking_id,
        parent_key=Booking.booking_id,
    )
    async with pool.trace() as tr:
        result = await pool.split_load(
            pg.select(Booking).order_by(Booking.reference_code.asc()),
            relations=(charges_rel, members_rel),
        )
    print(f"split_load fetched {len(result.parents)} bookings in {tr.rtts} RTTs")
    # => split_load fetched 2 bookings in 2 RTTs

    # Join Charge -> ChargeKindType to inspect human-readable lookup codes alongside totals.
    for booking in result.parents:
        charges = result.for_parent(charges_rel, booking.booking_id)
        members = result.for_parent(members_rel, booking.booking_id)
        total = sum((c.amount for c in charges), Decimal("0.00"))
        print(
            f"  {booking.reference_code}: {len(members)} guest(s), "
            f"{len(charges)} charge(s), folio EUR {total}"
        )
        # =>   HERD-101: 2 guest(s), 2 charge(s), folio EUR 390.00
        # =>   HERD-102: 2 guest(s), 1 charge(s), folio EUR 85.00

    charge_codes = await pool.all(
        pg.select(Charge)
        .join(ChargeKindType)
        .columns(ChargeKindType.code, Charge.amount)
        .order_by(Charge.charge_id.asc())
    )
    print("charges:", [(code, str(amt)) for code, amt in charge_codes])
    # => charges: [('nightly_rate', '360.00'), ('peanut_bar', '30.00'), ('mud_spa', '85.00')]

What just happened

  • .join(Booking, require_using=True) emits INNER JOIN "booking" USING ("booking_id") with zero manual ON condition.
  • Joining Guest after Booking and BookingGuest has two paths (Booking.primary_guest_id and BookingGuest.guest_id), so via=BookingGuest.guest_id picks the exact foreign key unambiguously.
  • Booking.primary_guest_id does not share a column name with Guest.guest_id, so .join(Guest, require_using=True) fails immediately with pg.JoinLintError. Without require_using=True, pgdorm falls back cleanly to ON "booking"."primary_guest_id" = "guest"."guest_id".
  • pool.split_load(...) fetches all parent bookings in round trip 1, then pipelines all child queries (Charge and BookingGuest) in round trip 2 using = ANY($1) — all inside a single REPEATABLE READ snapshot so parent and child views are always consistent, with zero Cartesian explosion.

Why auto_index_fk matters for joins

Every foreign key in examples/schema.py automatically gets a B-tree index unless it's already covered by the leftmost prefix of a primary key or UNIQUE constraint. If you ever join over an unindexed foreign key, pgdorm raises JoinLintError at compile time unless you explicitly opt in with .allow_seq_scan(reason="...").

Ferris' basement: how split_load() fits N relations into 2 round trips

Round trip 1 opens a REPEATABLE READ read-only transaction and runs the parent query. As soon as the parent IDs arrive, pgdorm packs every SplitRelation query (WHERE booking_id = ANY($1)) plus COMMIT into a single pipelined flush — round trip 2. Whether you load two child tables or six, the network cost stays flat at 2 RTTs, and pg_stat_statements stays O(1) because every child query uses = ANY($1).

What PostgreSQL actually received#

🔭 What PostgreSQL received: 17 statements in 13 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 54 statements omitted · full transcript in examples/__wire__/joins_and_folios.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 "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 6 ──
INSERT INTO "booking" ("dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5
FROM unnest($1, $2, $3, $4, $5, $6) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, ord)
ORDER BY u.ord
RETURNING "booking_id", "dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code", "created_at";
-- → 2 rows

-- ── round trip 7 ──
INSERT INTO "booking_guest" ("booking_id", "guest_id")
SELECT u.c0, u.c1
FROM unnest($1, $2) WITH ORDINALITY AS u(c0, c1, ord)
ORDER BY u.ord;
-- → 4 affected

-- ── round trip 8 ──
INSERT INTO "charge" ("booking_id", "kind", "description", "quantity", "unit_price")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4
FROM unnest($1, $2, $3, $4, $5) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, ord)
ORDER BY u.ord;
-- → 3 affected

-- ── round trip 9 ──
SELECT "booking"."reference_code", "guest"."full_name"
FROM "booking_guest"
INNER JOIN "booking" USING ("booking_id")
INNER JOIN "guest" USING ("guest_id")
ORDER BY "booking"."reference_code" ASC, "guest"."first_name" ASC;
-- → 4 rows

-- ── round trip 10 ──
SELECT "booking"."reference_code", "guest"."full_name"
FROM "booking"
INNER JOIN "guest" ON "booking"."primary_guest_id" = "guest"."guest_id"
ORDER BY "booking"."reference_code" ASC;
-- → 2 rows

-- ── round trip 11 · 2 statements pipelined ──
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT
  "booking_id",
  "dormitory_id",
  "primary_guest_id",
  "status",
  "channel",
  "stay",
  "reference_code",
  "created_at"
FROM "booking"
ORDER BY "reference_code" ASC;
-- → 2 rows

-- ── round trip 12 · 3 statements pipelined ──
SELECT
  "charge_id",
  "booking_id",
  "kind",
  "description",
  "quantity",
  "unit_price",
  "amount"
FROM "charge"
WHERE "booking_id" = ANY($1)
ORDER BY "charge_id" ASC;
-- → 3 rows
SELECT "booking_guest_id", "booking_id", "guest_id"
FROM "booking_guest"
WHERE "booking_id" = ANY($1);
-- → 4 rows
COMMIT;

-- ── round trip 13 ──
SELECT "charge_kind_type"."code", "charge"."amount"
FROM "charge"
INNER JOIN "charge_kind_type" ON "charge"."kind" = "charge_kind_type"."charge_kind_type_id"
ORDER BY "charge"."charge_id" ASC;
-- → 3 rows

Shift report

  • Modeled many-to-many co-travellers with a strict-PK link table (BookingGuest)
  • Let PostgreSQL compute Charge.amount as a stored generated column
  • Used automatic JOIN … USING, via= disambiguation, and JoinLintError guardrails
  • Loaded bookings, charges and members together in 2 round trips with split_load()

Try it yourself

In demonstrate_joins_and_split_load, remove via=BookingGuest.guest_id from using_q and run the script. Notice how pgdorm stops you with JoinLintError before a single byte touches PostgreSQL.

Go deeper: tests/integration/relations/links/test_links.py (live PostgreSQL test suites & snapshots)

Sticky note from Management

"EMERGENCY. Room 304 (the penthouse) is booked by Jumbo AND Bram for Saturday night. Neither of them will fit on the sofa. Make double bookings IMPOSSIBLE."