Polars to and from PostgreSQL, Citus and CedarDB with ADBC drivers
We write a Polars DataFrame of 6,001,215 rows (TPC-H lineitem) to PostgreSQL, Citus and CedarDB and read it back, with ArpePGSQL and with the Apache ADBC PostgreSQL driver. Both use the binary COPY protocol. ArpePGSQL is 1.3 to 4.4 times faster in the six cases: on PostgreSQL, the write takes 5.4 s against 10.8 s and the read 4.5 s against 8.4 s, within 0.3 s of what psql gets from the server. On PostgreSQL and Citus, most of the gap seems to come from two places: the Apache driver is slower with the Arrow stream that Polars hands over, and it reads NUMERIC columns as strings, where ArpePGSQL returns decimals.
Polars works on columns, while the PostgreSQL protocol sends and receives rows: the driver in between converts one into the other, and this can take longer than the query itself. We write a Polars DataFrame of 6,001,215 rows into a database table and read it back. We compare two ADBC drivers: ArpePGSQL, our driver, which implements the PostgreSQL wire protocol itself, and the Apache ADBC PostgreSQL driver, built on libpq. The round trip runs against three databases that speak this protocol: PostgreSQL, Citus, an extension that distributes PostgreSQL tables, and CedarDB, a separate database system that accepts PostgreSQL clients.
Outline
- Setup
- System and package versions
- Data types
- Code
- Results
- Where the gap comes from
- In practice
- Scripts
Setup
The three databases run in Docker containers, without resource limits, on the machine that runs Python: a laptop with an Intel Core i9-12900H (20 threads) and 32 GB of RAM, under Linux. Nothing else runs on the machine during the measurements.
- 18.6
- official image
- 14.1.0, on PostgreSQL 18.4
- single node
- distributed on l_orderkey, 32 shards
- v2026-11-18
The three databases keep the default configuration of their images. For PostgreSQL and Citus, this means shared_buffers at 128 MB and max_wal_size at 1 GB.
The three servers accept TLS, and both drivers use it by default (sslmode=prefer). On PostgreSQL and Citus, pg_stat_ssl shows TLS 1.3 on the connections of both drivers; CedarDB does not provide this view. TLS is off in the official PostgreSQL image: we enabled it on this container with a self-signed certificate.
The client and the servers are on the same machine, so the data goes through the loopback interface, not through a network. The binary COPY stream of the table is about 1.09 GB: on a 1 Gb/s link, carrying it would take about 9 s by itself, which would hide much of the difference between the drivers. The timings below correspond to a client next to the database, or to a fast network.
ArpePGSQL is installed and registered with the ADBC driver manager by a one-line script, as described in the documentation. The script takes the path of a licence file. You can get a free 30-day trial licence for ArpePGSQL from the trial page, which also gives the install command. The Apache driver is a Python package:
curl -fsSL https://raw.githubusercontent.com/arpe-io/adbc-drivers/main/install.sh \
| sh -s -- arpepgsql --license /path/to/your.lic
pip install adbc-driver-manager adbc-driver-postgresql polars pyarrow
System and package versions
- polars 2.1.0
- pyarrow 26.0.1
- adbc_driver_manager 1.13.0
- connectorx 0.4.6
- ArpePGSQL 0.5.5
- adbc_driver_postgresql 1.13.0
- psql 15.20
- PostgreSQL 18.6
- Citus 14.1.0 (PostgreSQL 18.4)
- CedarDB v2026-11-18
Data types
The data is the lineitem table of the TPC-H benchmark at scale factor 1, 6,001,215 rows and 16 columns, loaded from a Parquet file into a Polars DataFrame. It has four kinds of columns: 4 integers, 4 decimals, 5 strings and 3 dates. The file stores the integers on 64 bits, so they are cast to Int32 after loading, to match the INTEGER columns of the table.
The target table is created before each write, with the same statement on the three databases, so that the column types do not depend on the driver. The column types are those of the TPC-H schema. The table has no primary key and no index: with them, the server would spend more time on each write, for both drivers.
DDL = """
CREATE TABLE lineitem (
l_orderkey INTEGER,
l_partkey INTEGER,
l_suppkey INTEGER,
l_linenumber INTEGER,
l_quantity NUMERIC(15, 2),
l_extendedprice NUMERIC(15, 2),
l_discount NUMERIC(15, 2),
l_tax NUMERIC(15, 2),
l_returnflag CHAR(1),
l_linestatus CHAR(1),
l_shipdate DATE,
l_commitdate DATE,
l_receiptdate DATE,
l_shipinstruct VARCHAR(25),
l_shipmode VARCHAR(10),
l_comment VARCHAR(44)
)"""
On Citus, the table is then distributed with SELECT create_distributed_table('lineitem', 'l_orderkey').
Write: Polars to the database
Polars hands the DataFrame to the driver as Apache Arrow data, without going through pyarrow. Source and target types are the same for both drivers and the three databases:
| Polars dtype | Arrow type received by the driver | Column type |
|---|---|---|
Int32 | int32 | INTEGER |
Decimal(15, 2) | decimal128(15, 2) | NUMERIC(15, 2) |
String | string_view | CHAR(1), VARCHAR(n) |
Date | date32 | DATE |
Without the CREATE TABLE statement, each driver creates the table itself. On PostgreSQL and Citus, both then create INTEGER, TEXT and DATE columns, with one difference for the decimals: ArpePGSQL creates NUMERIC(15, 2) columns, and the Apache driver NUMERIC columns without precision and scale.
Read: the database to Polars
| Column type | ArpePGSQL: Arrow type, Polars dtype | Apache driver: Arrow type, Polars dtype |
|---|---|---|
INTEGER | int32, Int32 | int32, Int32 |
NUMERIC(15, 2) | decimal128(15, 2), Decimal(15, 2) | arrow.opaque over string, Extension('arrow.opaque', String) |
CHAR(1), VARCHAR(n) | string, String | string, String |
DATE | date32, Date | date32, Date |
These types are the same on the three databases. The two drivers return the same rows, with different types for the four NUMERIC columns: decimals with ArpePGSQL, and the text representation of the numbers with the Apache driver. Its documentation explains that NUMERIC values are read as strings because they cannot always be converted to an Arrow decimal type without loss.
ArpePGSQL returns decimals when the column declares a precision and a scale, as here. For a NUMERIC value without them, such as sum(l_extendedprice) or avg(l_discount), it returns a string column. A cast in the query, for example sum(l_extendedprice)::numeric(18, 2), gives a decimal column.
With Polars 2.1.0, such a column can be converted afterwards with pl.col("l_quantity").ext.storage().cast(pl.Decimal(15, 2)). This conversion is not part of the timings below: the read times of the Apache driver stop before this step, which a computation on these columns needs.
Code
Both drivers get the same URI. ArpePGSQL is loaded by name by the driver manager, and the Apache driver through its own Python module:
import adbc_driver_manager.dbapi as dbapi
import adbc_driver_postgresql.dbapi as pg_dbapi
def connect(driver, uri):
"""Open an autocommit ADBC connection with ArpePGSQL or the Apache driver.
uri: postgresql://user:password@host:port/database"""
if driver == "arpepgsql":
return dbapi.connect(
driver="arpepgsql", db_kwargs={"uri": uri}, autocommit=True
)
return pg_dbapi.connect(uri, autocommit=True)
The write and the read are one Polars call each, with the connection as argument:
import polars as pl
QUERY = "SELECT * FROM lineitem"
def write_polars(df, conn):
df.write_database("lineitem", conn, engine="adbc", if_table_exists="append")
def read_polars(conn):
return pl.read_database(QUERY, conn)
For each database, the sequence is repeated 5 times, the two drivers alternating within each repetition: the table is dropped and created, the write is timed, the number of rows in the table is checked, and the read of the whole table is timed. The drivers are used with their default options. The full scripts are given at the end of the post.
With these calls, both drivers transfer the data with the binary COPY protocol: COPY lineitem (...) FROM STDIN (FORMAT binary) for the write, and COPY (SELECT * FROM lineitem) TO STDOUT (FORMAT binary) for the read. We checked the statements in pg_stat_activity on PostgreSQL and Citus; CedarDB's pg_stat_activity does not show them.
Results

To separate the server's share of these timings from the driver's, we also ran the same binary COPY statements with psql, the PostgreSQL command-line client. Unlike the drivers, psql does not convert the data to Arrow or to any other format: it passes the bytes of the COPY stream through unchanged. For the read, these bytes are written to /dev/null and discarded, so the time is what the server needs to produce and send the table. For the write, they come from a file prepared beforehand in the binary COPY format, so the time is what the server needs to receive and store the rows. The gap between a driver and psql is then roughly the work done by the driver on the client side. The psql runs were done after the benchmark, 5 per case.
Medians of the 5 runs, in seconds, and ArpePGSQL throughput:
| Database | Operation | ArpePGSQL | Apache ADBC PostgreSQL | psql | ArpePGSQL, million rows/s |
|---|---|---|---|---|---|
| PostgreSQL | write | 5.4 | 10.8 | 5.4 | 1.11 |
| PostgreSQL | read | 4.5 | 8.4 | 4.2 | 1.34 |
| Citus | write | 8.5 | 13.8 | 8.5 | 0.70 |
| Citus | read | 11.5 | 15.1 | 11.2 | 0.52 |
| CedarDB | write | 9.1 | 13.7 | 8.3 | 0.66 |
| CedarDB | read | 2.1 | 9.0 | 0.7 | 2.90 |
All 30 writes and 30 reads transferred the 6,001,215 rows. The 5 timings of a given case stay within 0.55 s of each other, except the writes to PostgreSQL (5.3 to 6.3 s with ArpePGSQL, 10.6 to 12.4 s with the Apache driver) and the ArpePGSQL writes to Citus (8.1 to 9.0 s).
On PostgreSQL and Citus, ArpePGSQL writes in the same time as psql and reads within 0.3 s of it: the server seems to set the pace. On CedarDB, it is 0.8 s slower than psql for the write and 1.4 s for the read. The read with the Apache driver takes 8.4 s on PostgreSQL and 9.0 s on CedarDB, although CedarDB sends the table in 0.7 s, so most of that time appears to be spent on the client side. CedarDB, derived from the Umbra research system of TU Munich, is a different engine from PostgreSQL, which probably explains why its server times differ so much.
The writes to PostgreSQL vary more than the other cases, with psql too (5.1 to 8.1 s). With max_wal_size at 1 GB, a load of the 6,001,215 rows, 771 MB of table data, triggers about two checkpoints, and the PostgreSQL log reports checkpoints are occurring too frequently during the runs.
These numbers compare the two drivers on each database. They say little about the databases themselves: these are three different systems, none of them tuned for this test, and the Citus table is split into 32 shards on a single node.
CedarDB supports COPY ... TO STDOUT (FORMAT binary) since v2026-10-08 according to its release notes. On v2026-09-16, this statement returned rows in text format, and the read with the Apache driver failed with Invalid PGCOPY signature at beginning of stream.
Where the gap comes from
The measurements in this section use the same tables and the same alternating order, 5 runs per case. Here, several reads follow each load. On PostgreSQL, the first read of a freshly loaded table is slower than the next ones: it also records, in every row, that the transaction that inserted it has committed (the hint bits). As in the benchmark, where the row count after each write plays this role, an untimed full scan runs before the timed reads, so that this work does not fall on whichever read comes first. The reads of this section fetch the Arrow table from the cursor and convert it with pl.from_arrow, where the benchmark calls pl.read_database, which probably explains why they are 0.1 to 0.4 s shorter than in the benchmark above.
Writing from a pyarrow Table
df.write_database hands the DataFrame to the driver as an Arrow stream, with string_view columns. We also wrote the same data from a pyarrow Table, with string columns, through the adbc_ingest method of the cursor. Medians in seconds:
| Database | ArpePGSQL, Polars | ArpePGSQL, pyarrow | Apache, Polars | Apache, pyarrow |
|---|---|---|---|---|
| PostgreSQL | 5.4 | 5.1 | 10.8 | 5.9 |
| Citus | 8.5 | 8.2 | 13.8 | 8.4 |
| CedarDB | 9.1 | 9.2 | 13.7 | 13.5 |
From a pyarrow Table, the Apache driver writes to PostgreSQL and Citus almost as fast as ArpePGSQL (5.9 s against 5.1 s, 8.4 s against 8.2 s). On these two databases, most of its write gap seems tied to the stream that Polars hands over rather than to the COPY itself. On CedarDB, it stays 1.5 times slower. ArpePGSQL takes about the same time on both paths.
Reading the NUMERIC columns as float8
The Apache driver turns the four NUMERIC columns into strings, and ArpePGSQL into decimal128 columns, so the two reads do not build the same DataFrame. With the four columns cast to float8 in the query (l_quantity::float8 AS l_quantity, and so on), both drivers build the same Arrow types. Medians in seconds:
| Database | ArpePGSQL, NUMERIC | ArpePGSQL, float8 | Apache, NUMERIC | Apache, float8 | psql, float8 |
|---|---|---|---|---|---|
| PostgreSQL | 4.3 | 5.9 | 8.0 | 5.8 | 5.8 |
| Citus | 11.4 | 10.0 | 14.9 | 10.3 | 10.1 |
| CedarDB | 1.9 | 1.5 | 8.7 | 4.4 | 0.6 |
With float8, both drivers take the time of psql on PostgreSQL and Citus: on these two databases, the Apache driver's longer read seems to come from the NUMERIC columns read as strings. The casts are computed by the server, which likely explains why ArpePGSQL's float8 read is slower than its NUMERIC one on PostgreSQL. On CedarDB, ArpePGSQL stays 3 times faster.
Driver options and ConnectorX
The Apache driver's adbc.postgresql.batch_size_hint_bytes option, 16 MB by default, sets the size of the record batches it returns. At 64 MB and 256 MB, the read on PostgreSQL takes 8.0 s and 8.2 s, the same as with the default (8.0 s).
ConnectorX, which pl.read_database_uri uses by default, reads the table with one connection in 7.2 s on PostgreSQL, 14.1 s on Citus and 7.9 s on CedarDB, against 4.3 s, 11.4 s and 1.9 s with ArpePGSQL. ConnectorX can also split a query over several connections, and so can tools such as FastBCP. Parallel transfers are beyond the scope of this post, which compares single-connection transfers.
Memory
Peak memory of a full read into Polars, measured in a fresh Python process as the increase of the resident set high-water mark (VmHWM) during the read, median of 3 runs on PostgreSQL:
| Client | DataFrame size | Peak memory increase |
|---|---|---|
| ArpePGSQL | 783 MB | 1,562 MB |
| Apache ADBC PostgreSQL | 535 MB | 1,677 MB |
| ConnectorX | 783 MB | 1,403 MB |
The DataFrame built from the Apache driver is smaller because its four NUMERIC columns hold text instead of 16-byte decimals. ArpePGSQL peaks at about twice the size of the DataFrame, and the Apache driver at about three times. On Citus and CedarDB, the values are within 60 MB of these.
In practice
Where the gap between the two drivers seems to come from, from the measurements above (times of the Apache driver against ArpePGSQL):
| Database | Write | Read |
|---|---|---|
| PostgreSQL | mostly the Arrow stream handed over by Polars: from a pyarrow Table, 5.9 s against 5.1 s | mostly the NUMERIC columns read as strings: with float8, 5.8 s against 5.9 s |
| Citus | the same: from a pyarrow Table, 8.4 s against 8.2 s | the same: with float8, 10.3 s against 10.0 s |
| CedarDB | still there from a pyarrow Table: 13.5 s against 9.2 s | still there with float8: 4.4 s against 1.5 s |
On PostgreSQL and Citus, it seems that much of the gap can be avoided with the Apache driver, by writing a pyarrow Table through adbc_ingest rather than calling df.write_database, and by casting the NUMERIC columns in the query, at the cost of the decimal type. With ArpePGSQL, the plain df.write_database and pl.read_database calls appear to run at the pace of the server, and the NUMERIC(15, 2) columns come back as decimals. On CedarDB, ArpePGSQL appears faster whatever the path.
Scripts
The full scripts, with the timing loops. The Parquet file holds the TPC-H lineitem table at scale factor 1, as generated by DuckDB.
common.py: connections, table definition and Parquet loading
"""Connections and table DDL shared by the scripts of this post.
URIs can be overridden with the POSTGRES_URI, CITUS_URI and CEDARDB_URI environment
variables.
"""
import os
import adbc_driver_manager.dbapi as dbapi
import adbc_driver_postgresql.dbapi as pg_dbapi
import pyarrow as pa
import pyarrow.parquet as pq
PARQUET = os.environ.get(
"LINEITEM_PARQUET", "lineitem_sf1.parquet"
)
URIS = {
"postgres": os.environ.get(
"POSTGRES_URI", "postgresql://postgres:mypass@localhost:5434/postgres"
),
"citus": os.environ.get(
"CITUS_URI", "postgresql://postgres:mypass@localhost:5433/postgres"
),
"cedardb": os.environ.get(
"CEDARDB_URI", "postgresql://postgres:CedarDb_2026@localhost:35432/postgres"
),
}
DRIVERS = ["arpepgsql", "postgresql"]
# PG_SSLMODE=disable turns TLS off for both drivers (default: each driver's own
# default, sslmode=prefer for both)
SSLMODE = os.environ.get("PG_SSLMODE")
DDL = """
CREATE TABLE lineitem (
l_orderkey INTEGER,
l_partkey INTEGER,
l_suppkey INTEGER,
l_linenumber INTEGER,
l_quantity NUMERIC(15, 2),
l_extendedprice NUMERIC(15, 2),
l_discount NUMERIC(15, 2),
l_tax NUMERIC(15, 2),
l_returnflag CHAR(1),
l_linestatus CHAR(1),
l_shipdate DATE,
l_commitdate DATE,
l_receiptdate DATE,
l_shipinstruct VARCHAR(25),
l_shipmode VARCHAR(10),
l_comment VARCHAR(44)
)"""
KEYS = ["l_orderkey", "l_partkey", "l_suppkey", "l_linenumber"]
def load_lineitem(rows=None):
"""Read the Parquet file as an Arrow table. The four key columns are int64 in
the file and are cast to int32, the type of the INTEGER columns of the table."""
table = pq.read_table(PARQUET)
if rows:
table = table.slice(0, rows)
for name in KEYS:
i = table.schema.get_field_index(name)
table = table.set_column(i, name, table[name].cast(pa.int32()))
return table
def connect(driver, db):
"""Open an autocommit ADBC connection with ArpePGSQL or the Apache driver."""
uri = URIS[db] + (f"?sslmode={SSLMODE}" if SSLMODE else "")
if driver == "arpepgsql":
return dbapi.connect(
driver="arpepgsql", db_kwargs={"uri": uri}, autocommit=True
)
return pg_dbapi.connect(uri, autocommit=True)
def recreate_table(conn, db, table="lineitem"):
"""Drop and create the target table, distributed on l_orderkey in Citus."""
with conn.cursor() as cur:
cur.execute(f"DROP TABLE IF EXISTS {table}")
cur.execute(DDL.replace("lineitem", table, 1))
if db == "citus":
cur.execute(f"SELECT create_distributed_table('{table}', 'l_orderkey')")
bench.py: the benchmark
"""Round trips of TPC-H lineitem (SF1, 6,001,215 rows) between Polars and
PostgreSQL/Citus/CedarDB, with ArpePGSQL and the Apache ADBC PostgreSQL driver.
For every (database, driver) the script writes the DataFrame into an empty
`lineitem` table, checks the row count, then reads the table back into a
DataFrame. Each case is repeated REPS times, the drivers alternating; one CSV line
per run goes to results/bench.csv. A failing case is recorded with its error and
skipped.
python bench.py [--reps 5] [--rows N]
"""
import argparse
import csv
import gc
import os
import platform
import time
from importlib.metadata import version
import polars as pl
from common import DRIVERS, SSLMODE, URIS, connect, load_lineitem, recreate_table
QUERY = "SELECT * FROM lineitem"
def write_polars(df, conn):
df.write_database("lineitem", conn, engine="adbc", if_table_exists="append")
def read_polars(conn):
return pl.read_database(QUERY, conn)
def count_rows(db):
# through ArpePGSQL: the Apache driver cannot run a SELECT on CedarDB before
# v2026-10-08 (no binary COPY TO STDOUT). On PostgreSQL, this full scan also
# sets the hint bits of the freshly loaded table before the timed read.
with connect("arpepgsql", db) as conn, conn.cursor() as cur:
cur.execute("SELECT count(*) FROM lineitem")
return cur.fetch_arrow_table().column(0)[0].as_py()
def timed(fn, *args):
gc.collect()
t0 = time.perf_counter()
out = fn(*args)
return time.perf_counter() - t0, out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--reps", type=int, default=5)
ap.add_argument("--rows", type=int, default=None)
ap.add_argument("--out", default="results/bench.csv")
ap.add_argument("--dbs", nargs="+", default=list(URIS), choices=list(URIS))
args = ap.parse_args()
df = pl.from_arrow(load_lineitem(args.rows))
n = len(df)
print(f"rows={n:,} python={platform.python_version()} polars={pl.__version__} "
f"adbc_driver_postgresql={version('adbc-driver-postgresql')} "
f"sslmode={SSLMODE or 'driver default'}")
os.makedirs(os.path.dirname(args.out), exist_ok=True)
with open(args.out, "w", newline="") as f:
w = csv.writer(f)
w.writerow(["db", "driver", "op", "rep", "seconds", "rows", "error"])
# the drivers alternate within each repetition, so that a slow period of the
# server (a checkpoint, for instance) does not fall on one driver only
for db in args.dbs:
for rep in range(args.reps):
for driver in DRIVERS:
with connect(driver, db) as conn:
recreate_table(conn, db)
try:
s, _ = timed(write_polars, df, conn)
rows, err = count_rows(db), ""
except Exception as e: # noqa: BLE001
s, rows, err = None, None, str(e).splitlines()[0][:200]
w.writerow([db, driver, "write", rep, s, rows, err])
print(f"{db:8} {driver:10} write #{rep}: "
f"{f'{s:6.2f}s' if s else 'FAIL ' + err}")
if err:
# reload with the ArpePGSQL bulk ingest so the read can run
with connect("arpepgsql", db) as c2, c2.cursor() as cur:
cur.adbc_ingest("lineitem", df.to_arrow(), mode="append")
try:
s, out = timed(read_polars, conn)
rows, err = len(out), ""
del out
except Exception as e: # noqa: BLE001
s, rows, err = None, None, str(e).splitlines()[0][:200]
w.writerow([db, driver, "read", rep, s, rows, err])
print(f"{db:8} {driver:10} read #{rep}: "
f"{f'{s:6.2f}s' if s else 'FAIL ' + err}")
f.flush()
if __name__ == "__main__":
main()
extras.py: the measurements of the section above
"""Side measurements for the post, on PostgreSQL, Citus and CedarDB.
For each database, REPS repetitions, the cases alternating within a repetition:
- write from a pyarrow Table (adbc_ingest) instead of the Polars DataFrame;
- read of the whole table with each driver, with cur.fetch_arrow_table() and
pl.from_arrow where bench.py calls pl.read_database;
- read with the four NUMERIC columns cast to float8, so that both drivers build
the same Arrow types;
- read with ConnectorX, one connection;
- on PostgreSQL only, the Apache driver's read with batch_size_hint_bytes at
64 MB and 256 MB (default: 16 MB).
Before the timed reads, an untimed full scan. Then the peak memory of a full read
into Polars, each in a fresh process.
python extras.py [--reps 5] [--dbs postgres citus cedardb]
"""
import argparse
import csv
import gc
import json
import os
import subprocess
import sys
import time
import connectorx as cx
import polars as pl
from common import DRIVERS, URIS, connect, load_lineitem, recreate_table
QUERY = "SELECT * FROM lineitem"
NUMERIC = ["l_quantity", "l_extendedprice", "l_discount", "l_tax"]
def float_query(names):
cols = [f"{c}::float8 AS {c}" if c in NUMERIC else c for c in names]
return f"SELECT {', '.join(cols)} FROM lineitem"
def timed(fn):
gc.collect()
t0 = time.perf_counter()
out = fn()
return time.perf_counter() - t0, out
def adbc_read(driver, db, query, options=None):
def run():
with connect(driver, db) as conn, conn.cursor() as cur:
if options:
cur.adbc_statement.set_options(**options)
cur.execute(query)
return pl.from_arrow(cur.fetch_arrow_table())
return run
def cx_read(db):
return lambda: cx.read_sql(URIS[db] + "?sslmode=prefer", QUERY, return_type="polars")
# peak memory of one read, in a fresh process: the high-water mark of the resident
# set (VmHWM) after the read minus the same once the modules are imported and the
# connection is open. VmHWM starts again at exec, unlike ru_maxrss, which a child
# inherits from its parent.
MEM_SCRIPT = r"""
import json, sys
import polars as pl
from common import URIS, connect
case, db = sys.argv[1], sys.argv[2]
def kb():
with open("/proc/self/status") as f:
return int(next(l for l in f if l.startswith("VmHWM:")).split()[1])
if case == "connectorx":
import connectorx as cx
base = kb()
df = cx.read_sql(URIS[db] + "?sslmode=prefer", "SELECT * FROM lineitem", return_type="polars")
else:
conn = connect(case, db)
base = kb()
df = pl.read_database("SELECT * FROM lineitem", conn)
print(json.dumps({"rows": len(df), "peak_mb": (kb() - base) / 1024,
"frame_mb": df.estimated_size() / 2**20}))
"""
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--reps", type=int, default=5)
ap.add_argument("--dbs", nargs="+", default=list(URIS), choices=list(URIS))
ap.add_argument("--out", default="results/extras.csv")
ap.add_argument("--memory-only", action="store_true")
args = ap.parse_args()
table = load_lineitem()
n = table.num_rows
fq = float_query(table.column_names)
os.makedirs("results", exist_ok=True)
with open(args.out, "w", newline="") as f:
w = csv.writer(f)
w.writerow(["db", "case", "rep", "seconds", "rows", "peak_mb", "frame_mb", "error"])
def record(db, case, rep, s=None, rows=None, peak=None, frame=None, err=""):
w.writerow([db, case, rep, s, rows, peak, frame, err])
f.flush()
val = f"{s:6.2f}s" if s is not None else (f"{peak:7.0f} MB" if peak else "")
print(f"{db:8} {case:45} #{rep} {val} {err}", flush=True)
for db in args.dbs:
reads = {f"read, {d}": adbc_read(d, db, QUERY) for d in DRIVERS}
reads.update({f"read float8, {d}": adbc_read(d, db, fq) for d in DRIVERS})
reads["read, connectorx"] = cx_read(db)
if db == "postgres":
for mb in (64, 256):
reads[f"read, postgresql, batch_size_hint_bytes {mb} MB"] = adbc_read(
"postgresql", db, QUERY,
{"adbc.postgresql.batch_size_hint_bytes": str(mb << 20)})
for rep in range(0 if args.memory_only else args.reps):
for driver in DRIVERS:
with connect(driver, db) as conn:
recreate_table(conn, db)
with conn.cursor() as cur:
s, _ = timed(lambda: cur.adbc_ingest("lineitem", table, mode="append"))
record(db, f"write pyarrow Table, {driver}", rep, s)
# untimed full scan: on PostgreSQL, the first scan of a freshly loaded
# table also writes the hint bits of every page, which would slow down
# whichever read comes first
with connect("arpepgsql", db) as conn, conn.cursor() as cur:
cur.execute("SELECT count(*) FROM lineitem")
cur.fetchall()
for case, fn in reads.items():
try:
s, out = timed(fn)
rows = len(out)
del out
record(db, case, rep, s, rows)
except Exception as e: # noqa: BLE001
record(db, case, rep, err=str(e).splitlines()[0][:200])
for rep in range(3):
for case in DRIVERS + ["connectorx"]:
r = subprocess.run([sys.executable, "-c", MEM_SCRIPT, case, db],
capture_output=True, text=True)
if r.returncode:
record(db, f"memory, {case}", rep, err=r.stderr.strip().splitlines()[-1][:200])
continue
m = json.loads(r.stdout.strip().splitlines()[-1])
assert m["rows"] == n, m
record(db, f"memory, {case}", rep, rows=m["rows"],
peak=m["peak_mb"], frame=m["frame_mb"])
if __name__ == "__main__":
main()
psql_baseline.sh: the psql baseline
#!/bin/bash
# Binary COPY with psql, which converts nothing: the server's share of the timings.
# For each database, REPS repetitions: recreate the table, load lineitem.bin (binary
# COPY format) with COPY FROM STDIN, then COPY TO STDOUT into /dev/null.
# ./psql_baseline.sh lineitem.bin [reps] > results/psql_baseline.csv
set -e
BIN=$1; REPS=${2:-5}
COLS="l_orderkey,l_partkey,l_suppkey,l_linenumber,l_quantity,l_extendedprice,l_discount,l_tax,l_returnflag,l_linestatus,l_shipdate,l_commitdate,l_receiptdate,l_shipinstruct,l_shipmode,l_comment"
DDL="DROP TABLE IF EXISTS lineitem; CREATE TABLE lineitem (l_orderkey INTEGER, l_partkey INTEGER, l_suppkey INTEGER, l_linenumber INTEGER, l_quantity NUMERIC(15,2), l_extendedprice NUMERIC(15,2), l_discount NUMERIC(15,2), l_tax NUMERIC(15,2), l_returnflag CHAR(1), l_linestatus CHAR(1), l_shipdate DATE, l_commitdate DATE, l_receiptdate DATE, l_shipinstruct VARCHAR(25), l_shipmode VARCHAR(10), l_comment VARCHAR(44));"
declare -A URI=(
[postgres]=${POSTGRES_URI:-postgresql://postgres:mypass@localhost:5434/postgres}
[citus]=${CITUS_URI:-postgresql://postgres:mypass@localhost:5433/postgres}
[cedardb]=${CEDARDB_URI:-postgresql://postgres:CedarDb_2026@localhost:35432/postgres}
)
now() { date +%s.%N; }
echo "db,op,rep,seconds,rows"
for db in postgres citus cedardb; do
u=${URI[$db]}
ddl=$DDL; [ $db = citus ] && ddl="$DDL SELECT create_distributed_table('lineitem','l_orderkey');"
for ((i=0; i<REPS; i++)); do
psql "$u" -q -c "$ddl" > /dev/null
t0=$(now); psql "$u" -q -c "COPY lineitem ($COLS) FROM STDIN (FORMAT binary)" < "$BIN"; t1=$(now)
n=$(psql "$u" -Atc "SELECT count(*) FROM lineitem")
echo "$db,write,$i,$(echo "$t1-$t0" | bc),$n"
t0=$(now); psql "$u" -q -c "COPY (SELECT * FROM lineitem) TO STDOUT (FORMAT binary)" > /dev/null; t1=$(now)
echo "$db,read,$i,$(echo "$t1-$t0" | bc),$n"
done
done
Driver downloads are at github.com/arpe-io/adbc-drivers. The binaries download freely and run once a licence is present. A 30-day trial licence can be downloaded for free for ArpePGSQL; for a full licence, contact us at sales@arpe.io or see arpe.io.
Free 30-day trial
