The Zero-SQL Hall of Shame#
After hours in Ferris' humming server room. The night shift is over, the lobby is quiet, and one last dare is taped to the rack.
Panda: Sure, typed ORM queries work for cute check-ins. Now try timezone business-hour buckets, gap-and-island streaks, recursive CUBE rollups, hybrid full-text + JSONPath, SKIP LOCKED write CTEs, and LATERAL percentiles — without raw SQL!
Ferris: Hold my coffee. Six production monsters, zero SQL strings, 1 round trip each, and every line strictly type-checked.
Maya: Wait — you actually built a Hall of Shame of the wildest things you can force through pgdorm?
What's the wildest thing you might expect to write in
pgdormunder a strict zero-raw-SQL & O(1)-SQL-shape policy — and proof that it still compiles to 1-RTT canonical PostgreSQL.
pgdorm intentionally has no text(), raw(), execute_raw(), or query_raw() escape hatch. Every query in this page is a live-verified, 1-RTT PostgreSQL statement from the hall_of_shame example, strictly type-checked.
Exhibit 1 (🌶️🌶️) — The Timezone Business-Hours Classifier#
Classify UTC timestamps in Lisbon local time into "weekend", "business", or "after_hours" in 1 RTT:
pg.extract("ISODOW", ...)andpg.extract("HOUR", ...)returnExpr[Decimal]because PostgreSQL'sEXTRACTreturnsnumeric. Strict type checkers therefore require explicitDecimal(6)/Decimal(9)bounds instead of silently mixingintandnumeric..in_any([Decimal(6), Decimal(7)])emits= ANY($2)with a single typed array parameter instead of variable-lengthIN ($2, $3), preserving O(1) prepared-statement shapes.
Equivalent Raw SQL:
SELECT guest_name,
CASE
WHEN EXTRACT(ISODOW FROM occurred_at AT TIME ZONE 'Europe/Lisbon') = ANY(ARRAY[6, 7]) THEN 'weekend'
WHEN EXTRACT(HOUR FROM occurred_at AT TIME ZONE 'Europe/Lisbon') BETWEEN 9 AND 17 THEN 'business'
ELSE 'after_hours'
END AS bucket
FROM dorm_event
ORDER BY dorm_event_id ASC;
The zero-SQL pgdorm AST (1 RTT, statically typed):
async def exhibit_business_hours(pool: pg.Pool) -> None:
local_ts = DormEvent.occurred_at.at_time_zone("Europe/Lisbon")
isodow = pg.extract(pg.enums.ExtractField.ISODOW, local_ts)
hour = pg.extract(pg.enums.ExtractField.HOUR, local_ts)
bucket = (
pg.case(
(isodow.in_any([Decimal(6), Decimal(7)]), "weekend"),
(hour.between(Decimal(9), Decimal(17)), "business"),
else_="after_hours",
)
).alias("bucket")
async with pool.trace() as tr:
rows = await pool.all(
pg.select(DormEvent)
.columns(DormEvent.guest_name, bucket)
.order_by(DormEvent.dorm_event_id.asc())
)
assert tr.rtts == 1
print(f"exhibit 1 ({tr.rtts} RTT): {rows}")
# => exhibit 1 (1 RTT): [('Jumbo', 'business'), ('Pip', 'after_hours'), ('Tusk', 'weekend')]
Exact SQL PostgreSQL received on the wire (1 RTT):
-- captured live from PostgreSQL · examples/__wire__/hall_of_shame.sql
SELECT "guest_name", CASE WHEN EXTRACT(ISODOW FROM "occurred_at" AT TIME ZONE $1) = ANY($2) THEN $3 WHEN EXTRACT(HOUR FROM "occurred_at" AT TIME ZONE $4) BETWEEN $5 AND $6 THEN $7 ELSE $8 END AS "bucket"
FROM "dorm_event"
ORDER BY "dorm_event_id" ASC;
Exhibit 2 (🌶️🌶️🌶️) — The 2-CTE Gap-and-Island Streak Detector#
Find every guest's consecutive-night stay streaks of at least 2 nights using LAG, a CASE boundary flag, a running SUM(...) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), and a HAVING COUNT(*) >= 2 aggregation.
Equivalent Raw SQL:
WITH ordered AS (
SELECT guest_name, stay_day,
CASE WHEN (stay_day - LAG(stay_day) OVER (PARTITION BY guest_name ORDER BY stay_day)) = 1
THEN 0 ELSE 1 END AS is_new
FROM stay_checkin
),
islands AS (
SELECT guest_name, stay_day,
SUM(is_new) OVER (
PARTITION BY guest_name ORDER BY stay_day
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS island_id
FROM ordered
)
SELECT guest_name, MIN(stay_day) AS start_day, MAX(stay_day) AS end_day, COUNT(*) AS nights
FROM islands
GROUP BY guest_name, island_id
HAVING COUNT(*) >= 2
ORDER BY guest_name ASC, MIN(stay_day) ASC;
The zero-SQL pgdorm AST (1 RTT, statically typed):
async def exhibit_gap_and_island(pool: pg.Pool) -> None:
prev_day = pg.lag(StayCheckin.stay_day).over(
partition_by=[StayCheckin.guest_name],
order_by=[StayCheckin.stay_day.asc()],
)
ordered = pg.cte(
"ordered",
pg.select(StayCheckin).columns(
StayCheckin.guest_name,
StayCheckin.stay_day,
pg.case(
(pg.cast(StayCheckin.stay_day - prev_day, "int4") == 1, 0),
else_=1,
).alias("is_new"),
),
)
frame = pg.rows_between(
pg.enums.FrameBoundKind.UNBOUNDED_PRECEDING, pg.enums.FrameBoundKind.CURRENT_ROW
)
islands = pg.cte(
"islands",
pg.select(ordered).columns(
ordered.col("guest_name"),
ordered.col("stay_day"),
pg.sum(ordered.col("is_new"))
.over(
partition_by=[ordered.col("guest_name")],
order_by=[ordered.col("stay_day").asc()],
frame=frame,
)
.alias("island_id"),
),
)
async with pool.trace() as tr:
streaks = await pool.all(
pg.with_(
ordered,
islands,
query=pg.select(islands)
.columns(
islands.col("guest_name"),
pg.min(islands.col("stay_day")).alias("start_day"),
pg.max(islands.col("stay_day")).alias("end_day"),
pg.count().alias("nights"),
)
.group_by(islands.col("guest_name"), islands.col("island_id"))
.having(pg.count() >= 2)
.order_by(islands.col("guest_name").asc(), pg.min(islands.col("stay_day")).asc()),
)
)
assert tr.rtts == 1
print(f"exhibit 2 ({tr.rtts} RTT): {[(g, n) for g, _s, _e, n in streaks]}")
# => exhibit 2 (1 RTT): [('Jumbo', 3), ('Pip', 2)]
Exact SQL PostgreSQL received on the wire (1 RTT):
-- captured live from PostgreSQL · examples/__wire__/hall_of_shame.sql
WITH "ordered" AS (
SELECT "guest_name", "stay_day", CASE WHEN CAST("stay_day" - LAG("stay_day") OVER (PARTITION BY "guest_name" ORDER BY "stay_day" ASC) AS INTEGER) = $1 THEN $2 ELSE $3 END AS "is_new"
FROM "stay_checkin"
),
"islands" AS (
SELECT "guest_name", "stay_day", SUM("is_new") OVER (PARTITION BY "guest_name" ORDER BY "stay_day" ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS "island_id"
FROM "ordered"
)
SELECT
"guest_name",
MIN("stay_day") AS "start_day",
MAX("stay_day") AS "end_day",
COUNT(*) AS "nights"
FROM "islands"
GROUP BY "guest_name", "island_id"
HAVING COUNT(*) >= $4
ORDER BY "guest_name" ASC, MIN("stay_day") ASC;
Exhibit 3 (🌶️🌶️🌶️🌶️) — The Recursive Hierarchy Cube Rollup#
Walk a self-referencing wing tree with PostgreSQL's WITH RECURSIVE ... SEARCH DEPTH FIRST ... CYCLE ... SET is_cycle USING path, filter out cycles, and aggregate across GROUP BY ROLLUP(...) with GROUPING(...) bitmasks and conditional SUM(...) FILTER (WHERE ...):
Equivalent Raw SQL:
WITH RECURSIVE wing_tree AS (
SELECT wing_node_id, region_code, tier, beds
FROM wing_node
WHERE parent_wing_id IS NULL
UNION ALL
SELECT w.wing_node_id, w.region_code, w.tier, w.beds
FROM wing_node w
INNER JOIN wing_tree t ON w.parent_wing_id = t.wing_node_id
)
SEARCH DEPTH FIRST BY wing_node_id SET depth_ord
CYCLE wing_node_id SET is_cycle USING path
SELECT region_code, tier,
GROUPING(region_code, tier) AS grp_mask,
SUM(beds) FILTER (WHERE tier = 'vip') AS vip_beds,
SUM(beds) AS total_beds
FROM wing_tree
WHERE is_cycle = FALSE
GROUP BY ROLLUP (region_code, tier)
ORDER BY GROUPING(region_code, tier) ASC, region_code ASC, tier ASC;
The zero-SQL pgdorm AST (1 RTT, statically typed):
async def exhibit_recursive_cube(pool: pg.Pool) -> None:
tree = pg.recursive_cte(
"wing_tree",
base=pg.select(WingNode)
.columns(
WingNode.wing_node_id,
WingNode.region_code,
WingNode.tier,
WingNode.beds,
)
.where(WingNode.parent_wing_id.is_null()),
step=lambda ref: (
pg.select(WingNode)
.join_cte(ref, WingNode.parent_wing_id, ref.col("wing_node_id"))
.columns(
WingNode.wing_node_id,
WingNode.region_code,
WingNode.tier,
WingNode.beds,
)
),
search=(pg.enums.SearchOrder.DEPTH, ["wing_node_id"], "depth_ord"),
cycle=(["wing_node_id"], "is_cycle", "path"),
)
async with pool.trace() as tr:
rollup_rows = await pool.all(
pg.with_(
tree,
query=pg.select(tree)
.columns(
tree.col("region_code"),
tree.col("tier"),
pg.grouping(tree.col("region_code"), tree.col("tier")).alias("grp_mask"),
pg.sum(tree.col("beds")).filter(tree.col("tier") == "vip").alias("vip_beds"),
pg.sum(tree.col("beds")).alias("total_beds"),
)
.where(tree.col("is_cycle") == False) # noqa: E712
.group_by(pg.rollup(tree.col("region_code"), tree.col("tier")))
.order_by(
pg.grouping(tree.col("region_code"), tree.col("tier")).asc(),
tree.col("region_code").asc(),
tree.col("tier").asc(),
),
)
)
assert tr.rtts == 1
summary = [(t, m, str(tot)) for _r, t, m, _v, tot in rollup_rows]
print(f"exhibit 3 ({tr.rtts} RTT): {summary}")
# => exhibit 3 (1 RTT): [('std', 0, '12'), ('vip', 0, '12'), (None, 1, '24'), (None, 3, '24')]
Exact SQL PostgreSQL received on the wire (1 RTT):
-- captured live from PostgreSQL · examples/__wire__/hall_of_shame.sql
WITH RECURSIVE "wing_tree" AS (
SELECT
"wing_node_id",
"region_code",
"tier",
"beds"
FROM "wing_node"
WHERE "parent_wing_id" IS NULL
UNION ALL
SELECT
"wing_node"."wing_node_id",
"wing_node"."region_code",
"wing_node"."tier",
"wing_node"."beds"
FROM "wing_node"
INNER JOIN "wing_tree" ON "wing_node"."parent_wing_id" = "wing_tree"."wing_node_id"
)
SEARCH DEPTH FIRST BY "wing_node_id" SET "depth_ord"
CYCLE "wing_node_id" SET "is_cycle" USING "path"
SELECT
"region_code",
"tier",
GROUPING("region_code", "tier") AS "grp_mask",
SUM("beds") FILTER (WHERE "tier" = $1) AS "vip_beds",
SUM("beds") AS "total_beds"
FROM "wing_tree"
WHERE "is_cycle" = $2
GROUP BY ROLLUP ("region_code", "tier")
ORDER BY GROUPING("region_code", "tier") ASC, "region_code" ASC, "tier" ASC;
Exhibit 4 (🌶️🌶️🌶️🌶️) — The Hybrid Full-Text + SQL/JSON Path Concierge Ranker#
Blend cover-density full-text ranking (pg.ts_rank_cd) with a CASE-based jsonb_path_exists VIP multiplier and pg.coalesce / pg.greatest floor clamping — all in a single 1-RTT statement:
Equivalent Raw SQL:
SELECT title,
GREATEST(
COALESCE(ts_rank_cd(to_tsvector('english', body), websearch_to_tsquery('english', 'mud spa OR peanuts')), 0.0)
* CASE WHEN jsonb_path_exists(meta, '$.vip ? (@ == true)') THEN 2.0 ELSE 1.0 END,
0.01
) AS score
FROM concierge_item
WHERE to_tsvector('english', body) @@ websearch_to_tsquery('english', 'mud spa OR peanuts')
AND jsonb_path_exists(meta, '$.wing.floor')
ORDER BY score DESC, concierge_item_id ASC;
The zero-SQL pgdorm AST (1 RTT, statically typed):
async def exhibit_hybrid_fts_jsonpath(pool: pg.Pool) -> None:
vec = pg.to_tsvector(ConciergeItem.body, config="english")
q_ts = pg.websearch_to_tsquery("mud spa OR peanuts", config="english")
vip_boost = pg.case(
(pg.jsonb_path_exists(ConciergeItem.meta, "$.vip ? (@ == true)"), 2.0),
else_=1.0,
)
blended = pg.greatest(pg.coalesce(pg.ts_rank_cd(vec, q_ts), 0.0) * vip_boost, 0.01)
async with pool.trace() as tr:
ranked = await pool.all(
pg.select(ConciergeItem)
.columns(ConciergeItem.title, blended.alias("score"))
.where(
pg.and_(
vec.ts_match(q_ts),
pg.jsonb_path_exists(ConciergeItem.meta, "$.wing.floor"),
)
)
.order_by(blended.desc(), ConciergeItem.concierge_item_id.asc())
)
assert tr.rtts == 1
print(f"exhibit 4 ({tr.rtts} RTT): {[t for t, _s in ranked]}")
# => exhibit 4 (1 RTT): ['VIP Mud Spa', 'Garden Mud Bath', 'Peanut Platter']
Exact SQL PostgreSQL received on the wire (1 RTT):
-- captured live from PostgreSQL · examples/__wire__/hall_of_shame.sql
SELECT "title", GREATEST(COALESCE(ts_rank_cd(to_tsvector(CAST($1 AS REGCONFIG), "body"), websearch_to_tsquery(CAST($2 AS REGCONFIG), $3)), $4) * CASE WHEN jsonb_path_exists("meta", $5) THEN $6 ELSE $7 END, $8) AS "score"
FROM "concierge_item"
WHERE to_tsvector(CAST($9 AS REGCONFIG), "body") @@ websearch_to_tsquery(CAST($10 AS REGCONFIG), $11) AND jsonb_path_exists("meta", $12)
ORDER BY GREATEST(COALESCE(ts_rank_cd(to_tsvector(CAST($13 AS REGCONFIG), "body"), websearch_to_tsquery(CAST($14 AS REGCONFIG), $15)), $16) * CASE WHEN jsonb_path_exists("meta", $17) THEN $18 ELSE $19 END, $20) DESC, "concierge_item_id" ASC;
Exhibit 5 (🌶️🌶️🌶️🌶️) — Single-Statement Lock-Free Queue Claim & Atomic Archive#
Two classic concurrency patterns that usually force developers out of an ORM:
- Lock-free job claim:
WITH candidate AS (SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1) UPDATE ... FROM candidate ... RETURNING ... - Atomic archive:
WITH purged AS (DELETE ... USING ... RETURNING ...) INSERT INTO ... SELECT ... RETURNING ...
Equivalent Raw SQL:
-- 1. Lock-free queue claim
WITH candidate AS (
SELECT dispatch_job_id
FROM dispatch_job
WHERE state = 'queued'
ORDER BY priority DESC, dispatch_job_id ASC
LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE dispatch_job
SET state = 'claimed'
FROM candidate
WHERE dispatch_job.dispatch_job_id = candidate.dispatch_job_id
RETURNING wing_code, state, priority;
-- 2. Atomic archive
WITH purged AS (
DELETE FROM dispatch_job
USING wing_node
WHERE dispatch_job.wing_code = wing_node.code AND dispatch_job.state = 'done'
RETURNING wing_code, priority
)
INSERT INTO dispatch_archive (wing_code, priority)
SELECT wing_code, priority
FROM purged
RETURNING wing_code, priority;
The zero-SQL pgdorm AST (1+1 RTTs, statically typed):
async def exhibit_queue_claim_and_archive(pool: pg.Pool) -> None:
# 1. Single-statement lock-free queue claim: FOR UPDATE SKIP LOCKED + UPDATE ... FROM.
candidate = pg.cte(
"candidate",
pg.select(DispatchJob)
.columns(DispatchJob.dispatch_job_id)
.where(DispatchJob.state == "queued")
.order_by(DispatchJob.priority.desc(), DispatchJob.dispatch_job_id.asc())
.for_update(skip_locked=True)
.limit(1),
)
async with pool.trace() as tr_claim:
claimed = await pool.all(
pg.with_(
candidate,
query=pg.update(DispatchJob)
.from_(candidate)
.set(state="claimed")
.where(DispatchJob.dispatch_job_id == candidate.col("dispatch_job_id"))
.returning(DispatchJob.wing_code, DispatchJob.state, DispatchJob.priority),
)
)
assert tr_claim.rtts == 1
# 2. Writable CTE atomic archive: DELETE ... USING ... RETURNING -> INSERT ... SELECT.
purged = pg.cte(
"purged",
pg.delete(DispatchJob)
.using(WingNode)
.where(
pg.and_(
DispatchJob.wing_code == WingNode.code,
DispatchJob.state == "done",
)
)
.returning(DispatchJob.wing_code, DispatchJob.priority),
)
async with pool.trace() as tr_arch:
archived = await pool.all(
pg.with_(
purged,
query=pg.insert(DispatchArchive)
.from_select(
pg.select(purged).columns(purged.col("wing_code"), purged.col("priority"))
)
.returning(DispatchArchive.wing_code, DispatchArchive.priority),
)
)
assert tr_arch.rtts == 1
print(f"exhibit 5 ({tr_claim.rtts}+{tr_arch.rtts} RTTs): claimed={claimed} archived={archived}")
# => exhibit 5 (1+1 RTTs): claimed=[('EAST', 'claimed', 10)] archived=[('EAST', 3)]
Exact SQL PostgreSQL received on the wire (1 RTT each):
-- captured live from PostgreSQL · examples/__wire__/hall_of_shame.sql
WITH "candidate" AS (
SELECT "dispatch_job_id"
FROM "dispatch_job"
WHERE "state" = $1
ORDER BY "priority" DESC, "dispatch_job_id" ASC
LIMIT $2
FOR UPDATE SKIP LOCKED
)
UPDATE "dispatch_job"
SET "state" = $3
FROM "candidate"
WHERE "dispatch_job"."dispatch_job_id" = "candidate"."dispatch_job_id"
RETURNING "wing_code", "state", "priority";
-- captured live from PostgreSQL · examples/__wire__/hall_of_shame.sql
WITH "purged" AS (
DELETE FROM "dispatch_job"
USING "wing_node"
WHERE "dispatch_job"."wing_code" = "wing_node"."code" AND "dispatch_job"."state" = $1
RETURNING "wing_code", "priority"
)
INSERT INTO "dispatch_archive" ("wing_code", "priority")
SELECT "wing_code", "priority"
FROM "purged"
RETURNING "wing_code", "priority";
Exhibit 6 (🌶️🌶️🌶️🌶️🌶️) — Correlated LATERAL Top-K + WITHIN GROUP Percentiles + Deep JSONB Surgery#
Join each wing to its top-2 concierge items via LEFT JOIN LATERAL, filter JSONB payloads with .json_has_all_keys(...) (?&), extract nested strings with .json_path_text(...) (#>>), and aggregate with pg.percentile_cont(0.95, order_by=...) and ordered pg.string_agg(...):
Equivalent Raw SQL:
SELECT w.code,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY top_two.fee ASC) AS p95_fee,
STRING_AGG(top_two.floor, ',' ORDER BY top_two.fee DESC) AS floors
FROM wing_node w
LEFT JOIN LATERAL (
SELECT title, fee, meta #>> ARRAY['wing', 'floor'] AS floor
FROM concierge_item
WHERE wing_code = w.code AND meta ?& ARRAY['vip', 'wing']
ORDER BY fee DESC
LIMIT 2
) AS top_two ON TRUE
WHERE w.parent_wing_id IS NOT NULL
GROUP BY w.code
ORDER BY w.code ASC;
The zero-SQL pgdorm AST (1 RTT, statically typed):
async def exhibit_lateral_percentiles_jsonb(pool: pg.Pool) -> None:
top_two = pg.lateral(
pg.select(ConciergeItem)
.columns(
ConciergeItem.title,
ConciergeItem.fee,
ConciergeItem.meta.json_path_text("wing", "floor").alias("floor"),
)
.where(
pg.and_(
ConciergeItem.wing_code == WingNode.code,
ConciergeItem.meta.json_has_all_keys(["vip", "wing"]),
)
)
.order_by(ConciergeItem.fee.desc())
.limit(2),
alias="top_two",
)
async with pool.trace() as tr:
rows = await pool.all(
pg.select(WingNode)
.join_lateral(top_two, kind=pg.enums.LateralJoinKind.LEFT)
.columns(
WingNode.code,
pg.percentile_cont(0.95, order_by=top_two.col("fee", Decimal).asc()).alias(
"p95_fee"
),
pg.string_agg(
top_two.col("floor", str),
",",
order_by=[top_two.col("fee", Decimal).desc()],
).alias("floors"),
)
.where(WingNode.parent_wing_id.is_not_null())
.group_by(WingNode.code)
.order_by(WingNode.code.asc())
)
assert tr.rtts == 1
print(f"exhibit 6 ({tr.rtts} RTT): {[(c, p95, fl) for c, p95, fl in rows]}")
# => exhibit 6 (1 RTT): [('EAST', 174.0, 'penthouse,terrace'), ('WEST', 90.0, 'garden')]
Exact SQL PostgreSQL received on the wire (1 RTT):
-- captured live from PostgreSQL · examples/__wire__/hall_of_shame.sql
SELECT "wing_node"."code", PERCENTILE_CONT($1) WITHIN GROUP (ORDER BY "top_two"."fee" ASC) AS "p95_fee", STRING_AGG("top_two"."floor", $2 ORDER BY "top_two"."fee" DESC) AS "floors"
FROM "wing_node"
LEFT JOIN LATERAL (
SELECT "title", "fee", "meta" #>> $3 AS "floor"
FROM "concierge_item"
WHERE "wing_code" = "code" AND "meta" ?& $4
ORDER BY "fee" DESC
LIMIT $5
) AS "top_two" ON $6
WHERE "wing_node"."parent_wing_id" IS NOT NULL
GROUP BY "wing_node"."code"
ORDER BY "wing_node"."code" ASC;
Where Zero-SQL Draws the Hard Line#
Zero-SQL is a deliberate architectural boundary, not a claim that Python should replace every PostgreSQL feature. pgdorm intentionally never expresses the following in Python AST:
- Server-side procedural code:
CREATE FUNCTION ... LANGUAGE plpgsql, stored procedures, and anonymousDO $$ ... $$blocks. - Trigger definitions & event triggers:
CREATE TRIGGER ... EXECUTE FUNCTION .... - Unmodeled C-extension DDL: custom operator classes, foreign data wrappers, or extension-specific storage DDL outside
pgdorm's schema IR.
When your database owns views, triggers, or PL/pgSQL functions alongside pgdorm-managed tables, declare them as UnmanagedObject in pgdorm.migrate so the migration planner respects their dependency graph without attempting to drop or overwrite them.