Skip to content

Chapter 16 — The Polar Bears Arrive#

Act IV · Chapter 16 Month 6 · 07:00 8 min readDifficulty 3 of 5

PostgreSQL to Polars and back over Arrow and binary COPY, with zero Python row objects.

copy_from_arrow()on_error="ignore"pool.arrow()copy_to_arrow()
▶ Run it yourself · examples/156_arrow_polars_analytics.py
Month 6, 07:00. A blast of cold air sweeps into the lobby. The Polar Bears from the Arctic analytics office step off the elevator carrying laptops.

Month 6, 07:00. A blast of cold air sweeps into the lobby. The Polar Bears from the Arctic analytics office step off the elevator carrying laptops.

Polar Bear: Good morning! We have keycard scans in a Polars DataFrame to load into DoorEvent, and we need June's scans back in Polars for species weight analytics.

Panda: Easy! Call .to_dicts(), loop over every row in Python, run INSERT, then fetch rows back as Python objects and call pl.DataFrame(...)!

Ferris: Why wake up the Python interpreter for every single cell? Rust speaks PostgreSQL binary COPY on one side and Apache Arrow C Stream on the other. Zero Python row objects.

The mission#

Moving analytical datasets between PostgreSQL and Polars through Python dicts or CSVs burns client CPU and Python heap on per-row serialization (see our PG ↔ Polars benchmark for measured numbers). Maya connects PostgreSQL and Polars directly through Apache Arrow:

  1. Columnar ingest (pool.copy_from_arrow()): feed a Polars DataFrame into Rust and ship it via PostgreSQL COPY FROM STDIN (FORMAT binary) without Python row objects, routing across monthly partitions automatically,
  2. Fault-tolerant ingest (on_error="ignore"): keep valid sensor rows even when a flaky door scanner sends "not-a-timestamp" (using PostgreSQL COPY … ON_ERROR ignore, where pgdorm switches from binary to text COPY automatically because PostgreSQL restricts ON_ERROR to text/CSV),
  3. Zero-Python-row analytical reads (pool.arrow() & pool.copy_to_arrow()): decode parameterized queries and bulk COPY TO STDOUT (FORMAT binary) payloads inside Rust into Arrow RecordBatches and hand them off zero-copy to Polars via __arrow_c_stream__.

The Panda's plan

Export PostgreSQL rows to a temporary .csv file (or build 500,000 Python dicts in memory), parse strings back into floats, dates, and Decimals in Python, then hand them to Polars. Slow, memory-hungry, and breaks the moment a string contains an unescaped comma or timezone offset.

1. Create the monthly partitions#

First, prepare May and June partitions on DoorEvent:

examples/156_arrow_polars_analytics.py · create_monthly_partitions
async def create_monthly_partitions(pool: pg.Pool) -> None:
    await pool.create_partition(
        DoorEvent,
        name="door_event_2026_05",
        for_values="FROM ('2026-05-01 00:00:00+00') TO ('2026-06-01 00:00:00+00')",
    )
    await pool.create_partition(
        DoorEvent,
        name="door_event_2026_06",
        for_values="FROM ('2026-06-01 00:00:00+00') TO ('2026-07-01 00:00:00+00')",
    )

2. Bulk ingest from Polars — including noisy sensors#

pool.copy_from_arrow(DoorEvent, scans_df) consumes any Arrow-compatible producer (polars.DataFrame, pyarrow.Table, DuckDB relation) over the Arrow C Data Interface and streams PostgreSQL binary COPY directly from Rust:

examples/156_arrow_polars_analytics.py · ingest_door_scans
async def ingest_door_scans(pool: pg.Pool, dormitory_id: int) -> None:
    # Columnar ingest directly from Polars via PostgreSQL COPY FROM STDIN (FORMAT binary).
    scans_df = pl.DataFrame(
        {
            "scanned_at": pl.Series(
                [
                    datetime(2026, 5, 14, 22, 10, tzinfo=UTC),
                    datetime(2026, 5, 14, 22, 12, tzinfo=UTC),
                    datetime(2026, 5, 14, 22, 15, tzinfo=UTC),
                    datetime(2026, 6, 2, 7, 30, tzinfo=UTC),
                    datetime(2026, 6, 2, 7, 35, tzinfo=UTC),
                ],
                dtype=pl.Datetime("us", "UTC"),
            ),
            "dormitory_id": pl.Series([dormitory_id] * 5, dtype=pl.Int64),
            "room_number": ["304", "101", "304", "203", "304"],
            "badge_code": ["TRUNK-01", "TRUNK-02", "TRUNK-03", "TRUNK-01", "TRUNK-02"],
            "species_code": ["savanna", "pygmy", "mammoth", "savanna", "pygmy"],
            "granted": [True, True, False, True, True],
            "weight_kg": [5400.5, 1850.0, 8200.0, 5410.0, 1860.5],
            "tariff_eur": pl.Series(
                [
                    Decimal("120.00"),
                    Decimal("45.00"),
                    Decimal("250.00"),
                    Decimal("120.00"),
                    Decimal("45.00"),
                ],
                dtype=pl.Decimal(10, 2),
            ),
            "tags": [
                ["night_shift", "mud_spa"],
                ["peanut_bar"],
                ["overweight_alert"],
                ["breakfast"],
                ["peanut_bar", "early_bird"],
            ],
        }
    )
    copied = await pool.copy_from_arrow(DoorEvent, scans_df)
    print(f"ingested {copied} keycard scans across 2 monthly partitions")
    # => ingested 5 keycard scans across 2 monthly partitions

    # on_error=CopyOnError.IGNORE silently drops corrupted sensor rows instead of aborting COPY.
    # (Servers that support it also accept CopyOnError.SET_NULL for nullable columns.)
    noisy_feed: Any = pl.DataFrame(
        {
            "scanned_at": ["2026-06-03T08:00:00Z", "not-a-timestamp"],
            "dormitory_id": [dormitory_id, dormitory_id],
            "room_number": ["101", "101"],
            "badge_code": ["TRUNK-09", "TRUNK-BAD"],
            "species_code": ["forest", "forest"],
            "granted": [True, True],
            "weight_kg": [3200.0, 3100.0],
            "tariff_eur": ["75.00", "75.00"],
            "tags": ["{sensor_ok}", "{sensor_bad}"],
        }
    )
    loaded = await pool.copy_from_arrow(DoorEvent, noisy_feed, on_error=pg.enums.CopyOnError.IGNORE)
    print(f"noisy sensor feed kept {loaded}/2 valid rows")
    # => noisy sensor feed kept 1/2 valid rows

What just happened

  • scans_df carries Datetime("us", "UTC"), Int64, Decimal(10, 2), booleans, floats, and list[str] tags — all encoded directly to PostgreSQL binary wire format in Rust without creating a single Python row object.
  • When a noisy sensor sends "not-a-timestamp" alongside a good row, on_error="ignore" uses PostgreSQL's native COPY … (FORMAT text, ON_ERROR ignore) — pgdorm switches from binary to text COPY automatically when on_error is set, dropping only the malformed row and loading the valid one (kept 1/2 valid rows) instead of aborting the whole batch!

3. Arrow queries and binary COPY export into Polars#

Reading back into Polars works two ways: pool.arrow(query) for parameterized queries (1 RTT over the extended query protocol), and pool.copy_to_arrow(query, batch_size=...) for bulk exports over COPY TO STDOUT (FORMAT binary) (decoded in Rust into fixed-size Arrow batches with zero Python row objects):

examples/156_arrow_polars_analytics.py · analyze_with_polars
async def analyze_with_polars(pool: pg.Pool, dormitory_id: int) -> None:
    # Parameterized Extended Query -> zero-copy Arrow C Stream (__arrow_c_stream__) -> Polars.
    june_granted = (
        pg.select(DoorEvent)
        .where(
            (DoorEvent.dormitory_id == dormitory_id)
            & (DoorEvent.scanned_at >= datetime(2026, 6, 1, tzinfo=UTC))
            & DoorEvent.granted.is_true()
        )
        .order_by(DoorEvent.scanned_at.asc())
        .tag("examples.arrow_june_scans")
    )
    async with pool.trace() as tr:
        stream = await pool.arrow(june_granted)
    june_df = pl.DataFrame(stream)
    by_species = (
        june_df.group_by("species_code")
        .agg(pl.len().alias("scans"), pl.col("weight_kg").mean().alias("avg_kg"))
        .sort("species_code")
    )
    print(f"June granted scans: {june_df.height} rows in {tr.rtts} RTT")
    # => June granted scans: 3 rows in 1 RTT
    for row in by_species.iter_rows(named=True):
        print(f"  {row['species_code']}: {row['scans']} scan(s), avg {row['avg_kg']:.1f} kg")
        # =>   forest: 1 scan(s), avg 3200.0 kg
        # =>   pygmy: 1 scan(s), avg 1860.5 kg
        # =>   savanna: 1 scan(s), avg 5410.0 kg

    # Bulk export over COPY TO STDOUT (FORMAT binary) in fixed-size RecordBatches.
    export_stream = await pool.copy_to_arrow(
        pg.select(DoorEvent).order_by(DoorEvent.scanned_at.asc()),
        batch_size=3,
    )
    print(
        f"COPY BINARY export: {export_stream.num_rows} rows across "
        f"{export_stream.num_batches} Arrow batches"
    )
    # => COPY BINARY export: 6 rows across 2 Arrow batches
    full_df = pl.DataFrame(export_stream)
    denied = full_df.filter(~pl.col("granted"))["badge_code"].to_list()
    print(f"denied badges: {denied}")
    # => denied badges: ['TRUNK-03']

What just happened

  • stream = await pool.arrow(june_granted) runs the parameterized query in 1 RTT, decodes the binary rows directly into Arrow columnar buffers in Rust (zero Python row objects), and returns an ArrowStream implementing __arrow_c_stream__. Passing stream to pl.DataFrame(stream) hands those Arrow buffers to Polars zero-copy.
  • pool.copy_to_arrow(..., batch_size=3) decodes 6 rows from PostgreSQL binary COPY into 2 Arrow RecordBatches in Rust and hands them off zero-copy into Polars, preserving exact types (Decimal, timestamps, booleans, lists).
Ferris' basement: when to use pool.arrow() vs pool.copy_to_arrow()

Use pool.arrow(q) when your query has bind parameters ($1, $2), runs inside a pipeline, or returns up to tens of thousands of rows — it speaks the standard extended query protocol in 1 RTT. Use pool.copy_to_arrow(q, batch_size=...) for large analytical exports where PostgreSQL's COPY (SELECT …) TO STDOUT (FORMAT binary) gives the highest sustained throughput in fixed-size Arrow batches.

What PostgreSQL actually received#

🔭 What PostgreSQL received: 6 statements in 5 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 21 statements omitted · full transcript in examples/__wire__/arrow_polars_analytics.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 ──
SELECT
  "door_event_id",
  "scanned_at",
  "dormitory_id",
  "room_number",
  "badge_code",
  "species_code",
  "granted",
  "weight_kg",
  "tariff_eur",
  "tags"
FROM "door_event"
WHERE "dormitory_id" = $1 AND "scanned_at" >= $2 AND "granted" IS TRUE
ORDER BY "scanned_at" ASC
/* op:examples.arrow_june_scans */;
-- → 3 rows

Shift report

  • Loaded a Polars DataFrame directly into partitioned DoorEvent via copy_from_arrow()
  • Survived corrupted IoT rows using on_error="ignore" (text COPY)
  • Queried parameterized results straight into Polars in 1 RTT via pool.arrow()
  • Exported bulk RecordBatches over binary COPY via pool.copy_to_arrow()

Try it yourself

Change batch_size=3 to batch_size=2 in analyze_with_polars and watch export_stream.num_batches become 3 while export_stream.num_rows stays 6.

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

Sticky note from Management

"Tuesday 10:00: the Duck auditors just arrived! They want to run embedded DuckDB SQL over July's door scans, archive them to Parquet for the Polar Bears, and stream a verified audit row straight back into PostgreSQL."