Field Note 5 — Straight From the Wire (Slot Hydration, JSON Modes & Concierge Search)#
Field Notes · ORM Design · 🕛 Post-Launch · 17:00 · ⏱ 5 min read · 🥜🥜🥜🥜◌
Direct Slot Hydration · pool.json(mode="client"|"server") · copy_to_arrow() · ts_match() & jsonb_path_exists() · INSERT ... SELECT
▶ Run it yourself: examples/168_wire_slots_and_json_modes.py
Post-Launch, 17:00. The lobby dashboard needs three different shapes from the same PostgreSQL database: typed Python objects for business rules, raw JSON for the HTTP edge, and columnar tables for nightly analytics — plus full-text concierge search.
Maya: We keep serializing rows into Python objects only to dump them right back to JSON, or loading 50,000 rows into objects just to hand them to DuckDB. And the concierge desk wants full-text note search plus 1-RTT archival.
Ferris: Pick the output path that matches the consumer. Direct Slot Hydration writes PG v3 binary frames straight into CPython __slots__, Wire JSON Transcoding (mode="client") and Server JSON Aggregation (mode="server") skip Python objects altogether, and Arrow COPY stays zero-copy columnar.
1. Direct Slot Hydration vs. Columnar Arrow#
When your Python code needs domain objects, pool.all(Guest) uses Direct Slot Hydration: Rust decodes PostgreSQL v3 binary DataRow frames directly into CPython __slots__ descriptors (tp_alloc + Py_tp_descr_set), with zero __dict__ allocation (~380 B/row, 1 RTT).
When the consumer is Polars, DuckDB, or PyArrow, pool.copy_to_arrow() streams PostgreSQL COPY (...) TO STDOUT directly into Arrow buffers with zero per-row Python object allocation:
async def slot_hydration_vs_columnar_arrow(pool: pg.Pool) -> None:
# 1. Direct Slot Hydration: Rust decodes PG v3 binary DataRow frames directly into
# __slots__ descriptors (zero __dict__, ~380 B/row, 1 RTT).
async with pool.trace() as tr_slots:
guests = await pool.all(pg.select(Guest).order_by(Guest.guest_id.asc()))
has_dict = any(hasattr(g, "__dict__") for g in guests)
print(f"slots ({tr_slots.rtts} RTT, __dict__={has_dict}): {len(guests)} guests")
# => slots (1 RTT, __dict__=False): 5 guests
# 2. Zero-copy Columnar Arrow: COPY (...) TO STDOUT stays columnar for Polars/DuckDB.
table = pa.table(
await pool.copy_to_arrow(
pg.select(Guest).columns(Guest.guest_id, Guest.first_name, Guest.peanut_points)
)
)
print(f"arrow (COPY): {table.num_rows} rows x {table.num_columns} cols")
# => arrow (COPY): 5 rows x 3 cols
2. Wire JSON Transcoding (mode="client") vs. Server JSON Aggregation (mode="server")#
When an API endpoint only needs UTF-8 JSON bytes, hydrating Python objects just to call json.dumps() wastes both CPU and memory. pgdorm offers two 1-RTT JSON output paths:
| Mode | Where JSON is built | Wire format | NUMERIC / Decimal |
Best for |
|---|---|---|---|---|
mode="client" (default) |
Wire JSON Transcoding in Rust | Compact PG binary DataRow |
Exact string-quoted ("250.00") |
Offloading CPU from PostgreSQL; exact financial precision |
mode="server" |
Server JSON Aggregation in PostgreSQL (COALESCE(json_agg(row_to_json(...)), '[]'::json)) |
Single JSON text column | JSON number (250.0) |
Near-zero Python/Rust CPU for shaped/nested API payloads |
async def client_vs_server_json_modes(pool: pg.Pool) -> None:
q = (
pg.select(ConciergeNote)
.columns(ConciergeNote.title, ConciergeNote.credit_limit)
.order_by(ConciergeNote.concierge_note_id.asc())
)
# Wire JSON Transcoding (JsonMode.CLIENT, default): compact binary wire, exact string Decimal.
async with pool.trace() as tr_client:
client_bytes = await pool.json(q, mode=pg.enums.JsonMode.CLIENT)
# Server JSON Aggregation (JsonMode.SERVER): PG emits COALESCE(json_agg(row_to_json(..)), '[]').
async with pool.trace() as tr_server:
server_bytes = await pool.json(q, mode=pg.enums.JsonMode.SERVER)
client_first = json.loads(client_bytes)[0]
server_first = json.loads(server_bytes)[0]
print(
f"client ({tr_client.rtts} RTT, limit={client_first['credit_limit']!r}) vs "
f"server ({tr_server.rtts} RTT, limit={server_first['credit_limit']!r})"
)
# => client (1 RTT, limit='250.00') vs server (1 RTT, limit=250.0)
Choosing between mode="client" and mode="server"
Your database server is usually harder to scale horizontally than stateless app workers. Default to mode="client" (Wire JSON Transcoding) to keep PostgreSQL CPU lean and preserve exact Decimal precision; switch to mode="server" (Server JSON Aggregation) when you want PostgreSQL to assemble a single pre-shaped JSON payload with near-zero client CPU.
3. PostgreSQL Concierge Search & 1-RTT Archival#
The concierge desk needs full-text search across guest notes, jsonpath filtering on structured metadata, and 1-RTT archival of high-credit notes into ConciergeArchive — all without a single line of raw SQL:
- Full-text search:
pg.to_tsvector(...),.ts_match(pg.websearch_to_tsquery(...)), andpg.ts_rank(...). - SQL/JSON path filtering:
pg.jsonb_path_exists(ConciergeNote.meta, "$.vip ? (@ == true)"). - 1-RTT archival:
pg.insert(ConciergeArchive).from_select(src).returning(...).
async def concierge_search_and_archival(pool: pg.Pool) -> None:
# 1. Full-text search + jsonpath metadata filter in 1 RTT.
query_ts = pg.websearch_to_tsquery("mud spa OR peanuts", config="english")
body_vec = pg.to_tsvector(ConciergeNote.body, config="english")
async with pool.trace() as tr_search:
matches = await pool.all(
pg.select(ConciergeNote)
.columns(ConciergeNote.title, pg.ts_rank(body_vec, query_ts).alias("rank"))
.where(
body_vec.ts_match(query_ts)
& pg.jsonb_path_exists(ConciergeNote.meta, "$.vip ? (@ == true)")
)
.order_by(pg.ts_rank(body_vec, query_ts).desc())
)
print(f"search ({tr_search.rtts} RTT): {[title for title, _rank in matches]}")
# => search (1 RTT): ['VIP Mud Spa Request']
# 2. 1-RTT archival via INSERT ... SELECT.
src = (
pg.select(ConciergeNote)
.columns(ConciergeNote.guest_id, ConciergeNote.title, ConciergeNote.credit_limit)
.where(ConciergeNote.credit_limit >= Decimal("100.00"))
)
async with pool.trace() as tr_arch:
archived = await pool.all(
pg.insert(ConciergeArchive).from_select(src).returning(ConciergeArchive.title)
)
print(f"archived ({tr_arch.rtts} RTT): {archived}")
# => archived (1 RTT): [('VIP Mud Spa Request',)]