Skip to content

Chapter 13 — The Nightly Feed#

Act IV · Chapter 13 Month 6 · 00:00 6 min readDifficulty 4 of 5

Stage a whole partner feed and MERGE it with full OLD/NEW reporting in one round trip.

temp=True tablespipe.stage()pg.merge()merge_action()MERGE … RETURNING
▶ Run it yourself · examples/092_staging_and_merge_import.py
Month 6, 00:00. The travel-agency partner just dropped its nightly batch of guest updates and newcomers.

Month 6, 00:00. The travel-agency partner just dropped its nightly batch of guest updates and newcomers.

Panda: Easy! Loop over the file, run a SELECT to see if each email exists, then INSERT or UPDATE — and log the old surname with another SELECT first!

Rocco: If you create a session-scoped temp table behind my transaction pooler, it's going to collide with the next tenant. Use ON COMMIT DROP or stay outside.

Ferris: Stage the whole feed in a pg_temp table with ON COMMIT DROP, index it, analyze it, and run MERGE … RETURNING OLD/NEW — all inside one round trip.

The mission#

Nightly batch syncs are the classic place where for-loops turn into 30-minute lock storms. Maya needs a feed importer that:

  1. declares a typed ephemeral staging table (temp=True, on_commit=pg.enums.OnCommit.DROP) that is safe even behind PgBouncer transaction pooling,
  2. creates, populates (via UNNEST), indexes, and ANALYZEs the staging table inside a pipelined transaction,
  3. reconciles the staged rows into Guest with pg.merge(...), reporting every INSERT / UPDATE action and OLD → NEW change in the same 1 RTT.

The Panda's plan

One SELECT + one INSERT/UPDATE per feed row. Ten thousand partner records become 20,000 round trips, half-applied state if the script crashes at row 4,812, and no clean audit log of which surnames actually changed.

1. Define a typed pg_temp staging table#

Temporary staging tables don't need a permanent <table_name>_id primary key (temp=True is an explicit exemption). Setting on_commit=pg.enums.OnCommit.DROP ensures PostgreSQL drops the table automatically when the transaction finishes — required whenever you sit behind a transaction pooler like PgBouncer:

examples/092_staging_and_merge_import.py · StageGuestFeed
class StageGuestFeed(pg.Table, temp=True, on_commit=pg.enums.OnCommit.DROP):
    email: pg.Col[str] = pg.col()
    first_name: pg.Col[str] = pg.col()
    last_name: pg.Col[str] = pg.col()
    species: pg.Col[Species] = pg.col()
    country: pg.Col[str | None] = pg.col(default=None)
    loyalty_tier: pg.Col[LoyaltyTier] = pg.col(default=LoyaltyTier.CALF)
    peanut_points: pg.Col[int] = pg.col(default=0)
    preferences: pg.Col[pg.Jsonb[StayPreferences]] = pg.col(default_factory=StayPreferences)
    marketing_opt_in: pg.Col[bool] = pg.col(default=False)

2. Stage, index, analyze, and MERGE … RETURNING in 1 RTT#

Now combine pipe.stage(...) with pg.merge(Guest) inside tx.pipeline(commit=True):

examples/092_staging_and_merge_import.py · sync_ota_feed
async def sync_ota_feed(pool: pg.Pool, feed_rows: list[StageGuestFeed]) -> None:
    merge_stmt = (
        pg.merge(Guest)
        .using(StageGuestFeed)
        .on(Guest.email)
        .when_matched_update(last_name=StageGuestFeed.last_name, country=StageGuestFeed.country)
        .when_not_matched_insert(by_name=True)
        .returning(pg.merge_action(), Guest.email, pg.old(Guest.last_name), pg.new(Guest.last_name))
        .tag("examples.merge_ota_guests")
    )

    # BEGIN + CREATE TEMP (ON COMMIT DROP) + UNNEST + INDEX + ANALYZE + MERGE + COMMIT = 1 RTT!
    async with pool.trace() as tr, pool.transaction() as tx, tx.pipeline(commit=True) as pipe:
        pipe.stage(StageGuestFeed, feed_rows, index_on=(StageGuestFeed.email,), analyze=True)
        h_deltas = pipe.add(merge_stmt)

    deltas = sorted(h_deltas.all(), key=lambda r: r[1])
    print(f"merged {len(deltas)} feed rows in {tr.rtts} RTT ({tr.statement_count} stmts):")
    # => merged 2 feed rows in 1 RTT (7 stmts):
    for action, email, old_last, new_last in deltas:
        print(f"  {action} {email}: {old_last} -> {new_last}")
        # =>   UPDATE [email protected]: Kalahari -> Kalahari-Okavango
        # =>   INSERT [email protected]: None -> Serengeti

What just happened

  • pipe.stage(StageGuestFeed, feed_rows, index_on=(StageGuestFeed.email,), analyze=True) queues CREATE TEMP TABLE … ON COMMIT DROP, bulk UNNEST insert, CREATE INDEX, and ANALYZE directly into the pipeline.
  • Immediately after, pipe.add(merge_stmt) runs MERGE INTO "guest" USING "pg_temp"."stage_guest_feed" with WHEN MATCHED THEN UPDATE and WHEN NOT MATCHED THEN INSERT. Passing by_name=True resolves every StageGuestFeed column onto Guest automatically at query-build time — catching typos, incompatible PG types, or missing required columns early while letting new columns added to both tables propagate automatically (with exclude=(...) and explicit keyword overrides when needed).
  • .returning(pg.merge_action(), Guest.email, pg.old(Guest.last_name), pg.new(Guest.last_name)) pairs merge_action() with PostgreSQL's OLD/NEW RETURNING aliases so you know both the exact action (UPDATE vs INSERT) and the before/after surname (Kalahari -> Kalahari-Okavango, None -> Serengeti).
  • Count the network cost: 7 statements (BEGIN, CREATE TEMP TABLE, INSERT, CREATE INDEX, ANALYZE, MERGE, COMMIT) in 1 single round trip (tr.rtts == 1)!

Look at the exact MERGE statement PostgreSQL executed:

-- captured live from PostgreSQL · examples/__wire__/staging_and_merge_import.sql
MERGE INTO "guest" AS t
USING "pg_temp"."stage_guest_feed" AS s
ON t."email" = s."email"
WHEN MATCHED THEN
  UPDATE SET
    "last_name" = s."last_name",
    "country" = s."country"
WHEN NOT MATCHED THEN
  INSERT ("email", "first_name", "last_name", "species", "country", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
  VALUES (s."email", s."first_name", s."last_name", s."species", s."country", s."loyalty_tier", s."peanut_points", s."preferences", s."marketing_opt_in")
RETURNING merge_action(), t."email", OLD."last_name", NEW."last_name"
/* op:examples.merge_ota_guests */;
Ferris' basement: OnCommit.DROP vs OnCommit.DELETE_ROWS

On a direct connection pool, on_commit=pg.enums.OnCommit.DELETE_ROWS lets pgdorm create a temp table once per backend connection and reuse it across transactions. Behind a transaction pooler (Pool.connect(..., pool_mode=pg.enums.PoolMode.TRANSACTION)), every transaction might land on a different PostgreSQL backend — so pgdorm refuses OnCommit.DELETE_ROWS loudly at runtime and steers you to OnCommit.DROP, which leaves every connection spotless at COMMIT.

What PostgreSQL actually received#

🔭 What PostgreSQL received: 13 statements in 6 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 19 statements omitted · full transcript in examples/__wire__/staging_and_merge_import.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 · 7 statements pipelined ──
BEGIN;
CREATE TEMP TABLE IF NOT EXISTS "stage_guest_feed" ("email" TEXT NOT NULL, "first_name" TEXT NOT NULL, "last_name" TEXT NOT NULL, "species" INTEGER NOT NULL, "country" TEXT, "loyalty_tier" INTEGER NOT NULL DEFAULT 1, "peanut_points" BIGINT NOT NULL DEFAULT 0, "preferences" JSONB NOT NULL, "marketing_opt_in" BOOLEAN NOT NULL DEFAULT false) ON COMMIT DROP;
INSERT INTO "pg_temp"."stage_guest_feed" ("email", "first_name", "last_name", "species", "country", "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
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, ord)
ORDER BY u.ord;
-- → 2 affected
CREATE INDEX IF NOT EXISTS "idx_stage_guest_feed_email" ON "pg_temp"."stage_guest_feed" ("email");
ANALYZE "pg_temp"."stage_guest_feed";
MERGE INTO "guest" AS t
USING "pg_temp"."stage_guest_feed" AS s
ON t."email" = s."email"
WHEN MATCHED THEN
  UPDATE SET
    "last_name" = s."last_name",
    "country" = s."country"
WHEN NOT MATCHED THEN
  INSERT ("email", "first_name", "last_name", "species", "country", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
  VALUES (s."email", s."first_name", s."last_name", s."species", s."country", s."loyalty_tier", s."peanut_points", s."preferences", s."marketing_opt_in")
RETURNING merge_action(), t."email", OLD."last_name", NEW."last_name"
/* op:examples.merge_ota_guests */;
-- → 2 rows
COMMIT;

-- ── round trip 6 ──
SELECT COUNT(*)
FROM "guest";
-- → 1 row

Shift report

  • Declared a typed pg_temp staging table with on_commit=pg.enums.OnCommit.DROP
  • Staged, indexed, and analyzed partner rows inside a 1-RTT pipeline with pipe.stage()
  • Reconciled inserts and updates atomically with pg.merge()
  • Audited exact actions (merge_action()) and before/after deltas (OLD/NEW)

Try it yourself

Add a third StageGuestFeed row for Pip ([email protected]) updating her last_name and run the script. Notice tr.rtts stays 1 and tr.statement_count stays 7.

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

Note

Also in pgdorm: When you only need targeted multi-table mutations rather than a full MERGE, use Update.from_(...), Delete.using(...), or Insert.from_select(...) — see the Queries & DML Reference.

Sticky note from Management

"Porto's front desk just saw Lisbon's private desk notes because someone forgot a WHERE dorm_code = 'OPO'. NEVER AGAIN. Enforce tenant isolation inside PostgreSQL itself — and don't break Rocco's pooler!"