Chapter 12 — Mapping the Empire#
Walk a whole tree in one typed recursive query, with cycle protection built in.
Table.alias()recursive_cte()SEARCH DEPTH FIRSTCYCLEexcept_() / union_all()examples/157_hierarchy_regions_cte.pyMonth 3, 14:00. A giant wall map of Europe is pinned above Management's desk, covered in coloured push-pins and yarn.
Management: "Europe contains Iberia, Iberia contains Portugal and Spain, Portugal contains Lisbon Coast, Spain contains Madrid. Print the whole tree in depth-first order — and tell me which regions still need a dormitory!"
Panda: Easy! Query Europe, then in a recursive Python function query each child's children one level at a time. Hope nobody accidentally points a parent at its own child!
Ferris: One WITH RECURSIVE query walks the whole tree in 1 RTT, sorts it depth-first, and catches cycles before they become infinite loops.
The mission#
Trees and hierarchies (Region.parent_region_id → Region.region_id) show up everywhere: geographies, org charts, nested categories. Maya solves three classic graph questions in pure typed Python:
- Direct parents: join
Regionto itself with a typedRegion.alias("parent"), - Full depth-first tree walk: use
pg.recursive_cte(...)with PostgreSQL's nativeSEARCH DEPTH FIRSTandCYCLEguard, - Set algebra: find unhosted regions with
pg.except_(...)and combine flagship hubs withpg.union_all(...).
The Panda's plan
Recursive async def fetch_children(region_id) in Python: 1 round trip per node (or per level). Six regions = 7 round trips; a 500-region tree = 501 round trips — and one bad parent_region_id creates an infinite recursion that crashes the server with RecursionError.
1. Seed the European region hierarchy#
Look at the self-referencing foreign key on Region in examples/schema.py:
class Region(pg.Table):
region_id: Col[int] = pg.pk(default=pg.identity())
code: Col[Code] = pg.col(unique=True)
name: Col[str]
parent_region_id: Col[int | None] = pg.self_fk(
on_delete=pg.enums.OnDelete.SET_NULL, default=None
)
First, seed the 6-node European tree and assign Lisbon and Madrid dormitories to their leaf regions:
async def seed_european_regions(pool: pg.Pool) -> dict[str, Region]:
europe = await pool.one(
pg.insert(Region).values(Region(code="EU", name="Europe")).returning(Region)
)
iberia = await pool.one(
pg.insert(Region)
.values(Region(code="IBER", name="Iberia", parent_region_id=europe.region_id))
.returning(Region)
)
portugal = await pool.one(
pg.insert(Region)
.values(Region(code="PT", name="Portugal", parent_region_id=iberia.region_id))
.returning(Region)
)
spain = await pool.one(
pg.insert(Region)
.values(Region(code="ES", name="Spain", parent_region_id=iberia.region_id))
.returning(Region)
)
lisbon = await pool.one(
pg.insert(Region)
.values(Region(code="PT-LIS", name="Lisbon Coast", parent_region_id=portugal.region_id))
.returning(Region)
)
madrid = await pool.one(
pg.insert(Region)
.values(Region(code="ES-MAD", name="Madrid", parent_region_id=spain.region_id))
.returning(Region)
)
await pool.execute(
pg.insert_many(
Dormitory,
[
Dormitory(
region_id=lisbon.region_id,
code="LIS",
name="The Elephant Dormitory — Lisbon",
city="Lisbon",
country="PT",
timezone="Europe/Lisbon",
opened_on=date(2024, 5, 1),
),
Dormitory(
region_id=madrid.region_id,
code="MAD",
name="The Elephant Dormitory — Madrid",
city="Madrid",
country="ES",
timezone="Europe/Madrid",
opened_on=date(2025, 9, 1),
),
],
)
)
return {
"EU": europe,
"IBER": iberia,
"PT": portugal,
"ES": spain,
"PT-LIS": lisbon,
"ES-MAD": madrid,
}
2. Self-joins, WITH RECURSIVE (SEARCH / CYCLE), and set ops#
Now traverse the entire empire without a single recursive Python call or raw SQL string:
async def traverse_regions_and_set_ops(pool: pg.Pool, regions: dict[str, Region]) -> None:
# 1. Typed self-join via `Region.alias("parent")` lists each region with its direct parent.
parent = Region.alias("parent")
direct_parents = await pool.all(
pg.select(Region)
.join(parent, kind=pg.enums.JoinKind.LEFT, via=Region.parent_region_id)
.columns(Region.code, parent.code)
.order_by(Region.region_id.asc())
)
pairs = [f"{code}<-{pcode or 'ROOT'}" for code, pcode in direct_parents]
print("direct parents:", ", ".join(pairs))
# => direct parents: EU<-ROOT, IBER<-EU, PT<-IBER, ES<-IBER, PT-LIS<-PT, ES-MAD<-ES
# 2. WITH RECURSIVE + SEARCH DEPTH FIRST + CYCLE protection (100% typed ORM).
region_tree = pg.recursive_cte(
"region_tree",
base=pg.select(Region)
.columns(Region.region_id, Region.code, Region.name, Region.parent_region_id)
.where(Region.parent_region_id.is_null()),
step=lambda self_ref: (
pg.select(Region)
.columns(Region.region_id, Region.code, Region.name, Region.parent_region_id)
.join_cte(self_ref, Region.parent_region_id, self_ref.col("region_id"))
),
columns=("region_id", "code", "name", "parent_region_id"),
search=(pg.enums.SearchOrder.DEPTH, ("region_id",), "order_col"),
cycle=(("region_id",), "is_cycle", "path"),
)
tree_rows = await pool.all(
pg.with_(
region_tree,
query=(
pg.select(region_tree)
.columns(region_tree.col("code"), region_tree.col("is_cycle"))
.order_by(region_tree.col("order_col").asc())
),
)
)
print("depth-first hierarchy:", [code for code, _ in tree_rows])
# => depth-first hierarchy: ['EU', 'IBER', 'PT', 'PT-LIS', 'ES', 'ES-MAD']
# 3. Set operations (EXCEPT & UNION ALL) with automatic parameter renumbering.
all_regions = pg.select(Region).columns(Region.code)
hosted_regions = pg.select(Dormitory).join(Region, require_using=True).columns(Region.code)
empty_regions = await pool.all(
pg.except_(all_regions, hosted_regions).order_by(pg.col_ref("code").asc())
)
print("regions without a dormitory yet:", [code for (code,) in empty_regions])
# => regions without a dormitory yet: ['ES', 'EU', 'IBER', 'PT']
both_capitals = await pool.all(
pg.union_all(
pg.select(Region)
.columns(Region.name)
.where(Region.region_id == regions["PT-LIS"].region_id),
pg.select(Region)
.columns(Region.name)
.where(Region.region_id == regions["ES-MAD"].region_id),
).order_by(pg.col_ref("name").asc())
)
print("flagship hubs:", [name for (name,) in both_capitals])
# => flagship hubs: ['Lisbon Coast', 'Madrid']
What just happened
parent = Region.alias("parent")creates a typed table alias so.join(parent, kind="left", via=Region.parent_region_id)joinsRegionto itself cleanly (EU<-ROOT,IBER<-EU,PT<-IBER, …).pg.recursive_cte("region_tree", base=..., step=...)emits a realWITH RECURSIVEquery. Passingsearch=("depth", ("region_id",), "order_col")adds SQL-standardSEARCH DEPTH FIRST BY "region_id" SET "order_col", so sorting byorder_colyields['EU', 'IBER', 'PT', 'PT-LIS', 'ES', 'ES-MAD']automatically!- Passing
cycle=(("region_id",), "is_cycle", "path")adds PostgreSQL'sCYCLE "region_id" SET "is_cycle" USING "path", stopping any accidental loop in the data dead in its tracks. pg.except_(all_regions, hosted_regions)subtracts regions that already have a dormitory from all regions, returning['ES', 'EU', 'IBER', 'PT'].pg.union_all(...)combines two parameterized queries while pgdorm's compiler automatically renumbers$1and$2across arms so parameters never collide.
Look at the recursive CTE PostgreSQL actually ran:
-- captured live from PostgreSQL · examples/__wire__/hierarchy_regions_cte.sql
WITH RECURSIVE "region_tree" ("region_id", "code", "name", "parent_region_id") AS (
SELECT
"region_id",
"code",
"name",
"parent_region_id"
FROM "region"
WHERE "parent_region_id" IS NULL
UNION ALL
SELECT
"region"."region_id",
"region"."code",
"region"."name",
"region"."parent_region_id"
FROM "region"
INNER JOIN "region_tree" ON "region"."parent_region_id" = "region_tree"."region_id"
)
SEARCH DEPTH FIRST BY "region_id" SET "order_col"
CYCLE "region_id" SET "is_cycle" USING "path"
SELECT "code", "is_cycle"
FROM "region_tree"
ORDER BY "order_col" ASC;
Ferris' basement: automatic parameter renumbering across CTEs and set operations
When you compose subqueries with pg.with_(), pg.union_all(), pg.intersect(), or pg.except_(), each branch might carry its own $1, $2 parameters. pgdorm's Rust compiler merges every branch into one unified bind list and renumbers placeholders deterministically ($1, $2, $3, …) before the query ever reaches PostgreSQL.
What PostgreSQL actually received#
🔭 What PostgreSQL received: 11 statements in 11 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 19 statements omitted · full transcript in examples/__wire__/hierarchy_regions_cte.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 ──
INSERT INTO "region" ("code", "name", "parent_region_id")
VALUES ($1, $2, $3)
RETURNING "region_id", "code", "name", "parent_region_id";
-- → 1 row
-- ── round trip 3 ──
INSERT INTO "region" ("code", "name", "parent_region_id")
VALUES ($1, $2, $3)
RETURNING "region_id", "code", "name", "parent_region_id";
-- → 1 row
-- ── round trip 4 ──
INSERT INTO "region" ("code", "name", "parent_region_id")
VALUES ($1, $2, $3)
RETURNING "region_id", "code", "name", "parent_region_id";
-- → 1 row
-- ── round trip 5 ──
INSERT INTO "region" ("code", "name", "parent_region_id")
VALUES ($1, $2, $3)
RETURNING "region_id", "code", "name", "parent_region_id";
-- → 1 row
-- ── round trip 6 ──
INSERT INTO "region" ("code", "name", "parent_region_id")
VALUES ($1, $2, $3)
RETURNING "region_id", "code", "name", "parent_region_id";
-- → 1 row
-- ── round trip 7 ──
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ord)
ORDER BY u.ord;
-- → 2 affected
-- ── round trip 8 ──
SELECT "region"."code", "parent"."code"
FROM "region"
LEFT JOIN "region" AS "parent" ON "region"."parent_region_id" = "parent"."region_id"
ORDER BY "region"."region_id" ASC;
-- → 6 rows
-- ── round trip 9 ──
WITH RECURSIVE "region_tree" ("region_id", "code", "name", "parent_region_id") AS (
SELECT
"region_id",
"code",
"name",
"parent_region_id"
FROM "region"
WHERE "parent_region_id" IS NULL
UNION ALL
SELECT
"region"."region_id",
"region"."code",
"region"."name",
"region"."parent_region_id"
FROM "region"
INNER JOIN "region_tree" ON "region"."parent_region_id" = "region_tree"."region_id"
)
SEARCH DEPTH FIRST BY "region_id" SET "order_col"
CYCLE "region_id" SET "is_cycle" USING "path"
SELECT "code", "is_cycle"
FROM "region_tree"
ORDER BY "order_col" ASC;
-- → 6 rows
-- ── round trip 10 ──
(SELECT "code"
FROM "region")
EXCEPT
(SELECT "region"."code"
FROM "dormitory"
INNER JOIN "region" USING ("region_id"))
ORDER BY "code" ASC;
-- → 4 rows
-- ── round trip 11 ──
(SELECT "name"
FROM "region"
WHERE "region_id" = $1)
UNION ALL
(SELECT "name"
FROM "region"
WHERE "region_id" = $2)
ORDER BY "name" ASC;
-- → 2 rows
Shift report
- Built a typed self-join using
Region.alias("parent") - Walked a full hierarchy in 1 RTT with
pg.recursive_cte() - Used PostgreSQL
SEARCH DEPTH FIRSTandCYCLEprotection natively - Combined and subtracted queries with
pg.except_()andpg.union_all()
Try it yourself
Change search=("depth", ("region_id",), "order_col") to search=("breadth", ("region_id",), "order_col") in traverse_regions_and_set_ops. How does the traversal order of PT-LIS and ES change?
Go deeper: tests/integration/graph/test_recursive_cte.py · tests/integration/graph/test_set_ops.py (live PostgreSQL test suites & snapshots)
Sticky note from Management
"Month 6! Partner OTAs are dumping nightly feeds at midnight, Porto must NEVER see Lisbon's notes, door scanners are firing a million times a month, and the Arctic analytics team just booked a flight."
← PreviousChapter 11 · The Morning Revenue DigestChapter 11 · ROLLUP, Windows & QUALIFY