Skip to content

Field Note 3 — One Trip Through Seven Tables#

Field Notes · ORM Design · 🕛 Post-Launch · 15:40 · ⏱ 5 min read · 🥜🥜🥜🥜◌

Select.into() · LEFT JOIN SubDto | None · split_load() · pool.json() · __slots__

▶ Run it yourself: examples/234_nested_hydration_and_graphs.py

Post-Launch, 15:40. The lobby concierge wants a single Stay Board showing every booking's guest, dormitory, region, assigned room, folio charges, and payments.

Post-Launch, 15:40. The lobby concierge wants a single Stay Board showing every booking's guest, dormitory, region, assigned room, folio charges, and payments.

Maya: I can write a five-table JOIN for the scalar chain — Booking -> Guest, Dormitory -> Region, RoomAssignment -> Room — but I don't want to hand-slice a 12-column flat tuple in Python, and I definitely don't want a Cartesian blowup when I add Charge[] and Payment[].

Ferris: Two tools, zero magic. Use explicit nested Select.into(ConciergeStayCard) to hydrate the 1:1 / N:1 chain directly into __slots__ dataclasses in Rust in 1 RTT, and pair it with pool.split_load() for the two independent 1:N lists in 2 RTTs — or pool.json() when the client just wants JSON.

Explicit nested graphs vs. hidden auto-joins#

Many ORMs hide multi-table loading behind selectinload() / joinedload() metadata on the model class. That makes it easy to trigger N+1 queries or accidental 4-table joins far from the call site.

pgdorm keeps every join explicit in the query, and lets you project the result directly into a nested dataclass tree with .into(ConciergeStayCard):

  • Multi-hop JOIN ... USING & via=: Booking -> Guest, Booking -> Dormitory -> Region, and Booking -> RoomAssignment -> Room are written right in the Select pipeline (JoinLintError catches ambiguous FKs at build time).
  • NULL-safe LEFT JOIN sub-DTOs: room: RoomCard | None and region: RegionCard | None automatically become None when the outer-joined side has no matching row.
  • Rust-side __slots__ hydration: ConciergeStayCard and all nested cards are frozen=True, slots=True dataclasses with zero __dict__ overhead, hydrated in 1 RTT.

1. Multi-hop Select.into(NestedDto) in 1 RTT#

examples/234_nested_hydration_and_graphs.py · nested_into_multi_hop_board
async def nested_into_multi_hop_board(pool: pg.Pool) -> None:
    # Explicit multi-hop JOIN + LEFT JOIN hydrated into nested __slots__ dataclasses in 1 RTT.
    # Zero implicit auto-joins, zero global state, and NULL-safe SubDto | None handling.
    async with pool.trace() as tr:
        cards = await pool.all(
            pg.select(Booking)
            .join(Guest, via=Booking.primary_guest_id)
            .join(Dormitory)
            .join(Region, kind=pg.enums.JoinKind.LEFT)
            .join(RoomAssignment, kind=pg.enums.JoinKind.LEFT)
            .join(Room, via=RoomAssignment.room_id, kind=pg.enums.JoinKind.LEFT)
            .order_by(Booking.reference_code.asc())
            .into(ConciergeStayCard)
        )
    has_dict = any(hasattr(c, "__dict__") or hasattr(c.guest, "__dict__") for c in cards)
    summary = ", ".join(
        f"{c.reference_code}({c.guest.full_name.split()[0]}@{c.dormitory.code}/"
        f"rm={c.room.number if c.room else 'none'})"
        for c in cards
    )
    print(f"board ({tr.rtts} RTT, __dict__={has_dict}): {summary}")
    # => board (1 RTT, __dict__=False): FN-NH-001(Jumbo@LIS/rm=304), FN-NH-002(Pip@LIS/rm=none)

What just happened

  • One single SELECT fetched Booking, Guest, Dormitory, Region (LEFT JOIN), RoomAssignment (LEFT JOIN), and Room (LEFT JOIN) in 1 RTT.
  • FN-NH-001 hydrated room=RoomCard(number='304'); FN-NH-002 (not yet assigned a room) cleanly hydrated room=None.
  • Every hydrated card is a bare __slots__ value (__dict__=False) with zero global state or Identity Map tracking.

2. Avoiding the M × N Cartesian trap with split_load() and pool.json()#

The Panda's plan: Joining two 1:N child tables in one SELECT

Joining Booking -> Charge (3 rows) and Booking -> Payment (2 rows) in the same SELECT multiplies them into 3 × 2 = 6 rows for a single booking! At 50 charges and 20 payments, one booking explodes into 1,000 duplicate wire rows.

Instead, pool.split_load() fetches the parent bookings in RTT 1 and pipelines independent = ANY($1) child queries for Charge and Payment in RTT 2 (2 RTTs total, constant SQL shape, zero Cartesian duplication). And when an API endpoint only needs JSON, pool.json() serializes directly inside PostgreSQL in 1 RTT:

examples/234_nested_hydration_and_graphs.py · split_load_vs_cartesian_trap
async def split_load_vs_cartesian_trap(pool: pg.Pool) -> None:
    # 1. Naive multi-1:N JOIN multiplies M charges x N payments (3 x 2 = 6 rows for 1 booking!).
    naive_rows = await pool.all(
        pg.select(Booking)
        .join(Charge)
        .join(Payment)
        .columns(Booking.reference_code, Charge.charge_id, Payment.payment_id)
        .where(Booking.reference_code == "FN-NH-001")
    )
    print(f"naive multi-1:N JOIN rows={len(naive_rows)} (3 charges x 2 payments Cartesian trap)")
    # => naive multi-1:N JOIN rows=6 (3 charges x 2 payments Cartesian trap)

    # 2. pool.split_load() fetches parents, then pipelines child = ANY($1) queries in 2 RTTs.
    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(),),
    )
    payments_rel = pg.SplitRelation(
        name="payments",
        child_table=Payment,
        child_fk=Payment.booking_id,
        parent_key=Booking.booking_id,
        order_by=(Payment.payment_id.asc(),),
    )
    async with pool.trace() as tr:
        bundle = await pool.split_load(
            pg.select(Booking).order_by(Booking.reference_code.asc()),
            relations=(charges_rel, payments_rel),
        )
    counts = ", ".join(
        f"{b.reference_code}(c={len(bundle.for_parent(charges_rel, b.booking_id))},"
        f"p={len(bundle.for_parent(payments_rel, b.booking_id))})"
        for b in bundle.parents
    )
    print(f"split_load ({tr.rtts} RTTs, {tr.statement_count} stmts): {counts}")
    # => split_load (2 RTTs, 5 stmts): FN-NH-001(c=3,p=2), FN-NH-002(c=1,p=0)

    # 3. For API endpoints returning JSON directly, pool.json() serializes in PostgreSQL (1 RTT).
    async with pool.trace() as tr_json:
        payload = await pool.json(
            pg.select(Booking)
            .columns(Booking.reference_code)
            .order_by(Booking.reference_code.asc())
        )
    print(f"pool.json ({tr_json.rtts} RTT): {payload.decode()}")
    # => pool.json (1 RTT): [{"reference_code":"FN-NH-001"},{"reference_code":"FN-NH-002"}]

What PostgreSQL actually received#

🔭 What PostgreSQL received: 19 statements in 15 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 54 statements omitted · full transcript in examples/__wire__/nested_hydration_and_graphs.sql

-- ── round trip 1 ──
INSERT INTO "region" ("code", "name", "parent_region_id")
VALUES ($1, $2, $3)
RETURNING "region_id", "code", "name", "parent_region_id";
-- → 1 row

-- ── round trip 2 · 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 3 ──
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 4 ──
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 5 ──
COMMIT;

-- ── round trip 6 ──
UPDATE "dormitory"
SET "region_id" = $1
WHERE "dormitory_id" = $2;
-- → 1 affected

-- ── round trip 7 ──
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 8 ──
INSERT INTO "room_assignment" ("room_id", "stay", "booking_id")
VALUES ($1, $2, $3);
-- → 1 affected

-- ── round trip 9 ──
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;
-- → 4 affected

-- ── round trip 10 ──
INSERT INTO "payment" ("payment_method_id", "booking_id", "amount", "card_last4")
SELECT u.c0, u.c1, u.c2, u.c3
FROM unnest($1, $2, $3, $4) WITH ORDINALITY AS u(c0, c1, c2, c3, ord)
ORDER BY u.ord;
-- → 2 affected

-- ── round trip 11 ──
SELECT
  "booking"."booking_id",
  "booking"."reference_code",
  "guest"."guest_id",
  "guest"."full_name",
  "dormitory"."dormitory_id",
  "dormitory"."code",
  "dormitory"."city",
  "region"."region_id",
  "region"."name",
  "room"."room_id",
  "room"."number"
FROM "booking"
INNER JOIN "guest" ON "booking"."primary_guest_id" = "guest"."guest_id"
INNER JOIN "dormitory" USING ("dormitory_id")
LEFT JOIN "region" USING ("region_id")
LEFT JOIN "room_assignment" USING ("booking_id")
LEFT JOIN "room" USING ("room_id")
ORDER BY "booking"."reference_code" ASC;
-- → 2 rows

-- ── round trip 12 ──
SELECT "booking"."reference_code", "charge"."charge_id", "payment"."payment_id"
FROM "booking"
INNER JOIN "charge" USING ("booking_id")
INNER JOIN "payment" USING ("booking_id")
WHERE "booking"."reference_code" = $1;
-- → 6 rows

-- ── round trip 13 · 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 14 · 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;
-- → 4 rows
SELECT
  "payment_id",
  "payment_method_id",
  "booking_id",
  "amount",
  "paid_at",
  "card_last4",
  "iban",
  "voucher_code"
FROM "payment"
WHERE "booking_id" = ANY($1)
ORDER BY "payment_id" ASC;
-- → 2 rows
COMMIT;

-- ── round trip 15 ──
SELECT "reference_code"
FROM "booking"
ORDER BY "reference_code" ASC;
-- → 2 rows

Shift report

  • Hydrated a 6-table JOIN + LEFT JOIN chain into nested __slots__ dataclasses via Select.into(ConciergeStayCard) in 1 RTT
  • Handled missing LEFT JOIN rows cleanly as RoomCard | None
  • Demonstrated the 3 × 2 = 6 multi-1:N Cartesian trap and eliminated it with 2-RTT = ANY($1) pool.split_load()
  • Streamed a pre-serialized JSON array directly from PostgreSQL with pool.json() in 1 RTT

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