Skip to main content

ArpePGSQL — Examples & recipes

Copy-paste snippets for the common tasks. All assume the driver is installed and loadable by name (driver="arpepgsql") — see the install guide. For the full option reference behind each db_kwargs, see Connection.


Connect and query to Arrow​

The same recipe in every ADBC client — the driver is loaded by name (arpepgsql) from the installed ADBC manifest, so only the language changes:

import adbc_driver_manager.dbapi as dbapi

with dbapi.connect(
driver="arpepgsql",
db_kwargs={"uri": "postgresql://alice:<password>@localhost:5432/tpch?sslmode=require"},
autocommit=True,
) as conn, conn.cursor() as cur:
cur.execute("SELECT * FROM lineitem LIMIT 10")
table = cur.fetch_arrow_table() # pyarrow.Table
print(table.schema)

Connect with discrete options​

Discrete options keep secrets out of a single string and override any uri. Set them where the uri went — the rest of each program is identical to the recipe above:

conn = dbapi.connect(driver="arpepgsql", db_kwargs={
"adbc.arpepgsql.server": "localhost",
"adbc.arpepgsql.port": "5432",
"adbc.arpepgsql.database": "tpch",
"adbc.arpepgsql.username": "alice",
"adbc.arpepgsql.password": "<password>",
"adbc.arpepgsql.sslmode": "require",
}, autocommit=True)

Straight to pandas / Polars​

The result is already Arrow, so these handoffs stay zero-copy — no row-by-row marshalling. pandas and Polars read straight from the ADBC connection:

Python
import adbc_driver_manager.dbapi as dbapi
import pandas as pd
import polars as pl

uri = "postgresql://alice:<password>@localhost:5432/tpch?sslmode=require"

with dbapi.connect(driver="arpepgsql", db_kwargs={"uri": uri}) as conn:
# pandas — Arrow-backed dtypes, no Python-object columns
df = pd.read_sql(
"SELECT * FROM orders WHERE o_orderdate >= '1996-01-01'",
conn, dtype_backend="pyarrow",
)

# Polars — reads the same ADBC result directly
pf = pl.read_database(
"SELECT * FROM orders WHERE o_orderdate >= '1996-01-01'", conn
)

Connect and query from DuckDB​

DuckDB itself can be the ADBC client, via the third-party adbc_scanner community extension — it loads the arpepgsql driver and scans the result straight into DuckDB, in pure SQL:

-- DuckDB itself as the ADBC client, via the adbc_scanner community extension:
-- https://query.farm/products/extensions/adbc_scanner/
INSTALL adbc_scanner FROM community;
LOAD adbc_scanner;

-- Load the driver by name from the installed ADBC manifest.
SET VARIABLE conn = adbc_connect({
'driver': 'arpepgsql',
'uri': 'postgresql://alice:<password>@localhost:5432/tpch?sslmode=require'
});

SELECT * FROM adbc_scan(getvariable('conn'), 'SELECT * FROM lineitem LIMIT 10');

Prepared statements & parameter binding​

Bind a parameter to a $1 placeholder. In the compiled clients you bind an Arrow batch of parameters to the statement before executing:

with conn.cursor() as cur:
cur.execute("SELECT * FROM orders WHERE o_orderkey = $1", parameters=[42])
row = cur.fetch_arrow_table()

PostgreSQL uses $1, $2, … placeholders in the extended-query protocol. Array binding — bind a whole Arrow batch of parameters in one call (Python's executemany):

Python
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO t(a, b) VALUES ($1, $2)",
seq_of_parameters=[(1, "x"), (2, "y"), (3, "z")],
)
conn.commit()

executemany (and execute_update with a bound batch or stream) runs the statement once per parameter row. The rows are pipelined: up to 1024 rows go out per network round trip (fewer when the server's replies are large), so a high-latency link costs one round trip per window of rows, not per row. The outcome is the same as running the rows one at a time:

  • With autocommit off, the first failing row aborts the transaction; later rows are not run, and the error names the failing row (counted from 0 across all bound batches). Roll back to continue.
  • With autocommit on, the result is as if each row committed on its own: when row k fails, rows 0 to k-1 stay committed and later rows are not run. Each window of rows runs as one transaction, so when a row fails the driver re-runs the rows of its window before it one at a time; volatile side effects outside the transaction (a nextval() default, for example) then happen twice for those rows, as in any retried transaction.

Bulk ingest an Arrow table​

Native PostgreSQL COPY — pipe an Arrow table straight in. The ingest runs inside the connection's transaction: with autocommit=True it is committed when it completes; with autocommit off, call commit() to keep it:

import pyarrow as pa

conn = dbapi.connect(driver="arpepgsql", db_kwargs={...}, autocommit=True)

table = pa.table({
"id": pa.array([1, 2, 3], pa.int32()),
"name": pa.array(["a", "b", "c"], pa.string()),
})

with conn.cursor() as cur:
cur.adbc_ingest("my_table", table, mode="create") # create | append | replace | create_append
note

Rust & C++ have no one-call adbc_ingest helper: set the standard statement options adbc.ingest.target_table / adbc.ingest.mode, Bind the Arrow batch, then execute_update (Rust) / AdbcStatementExecuteQuery (C++). A single batch (Bind) or a stream (BindStream) can be bound. An unset adbc.ingest.mode means create; set it to append to add to an existing table.

Ingest into a specific schema or a temp table via the statement options adbc.ingest.target_db_schema and adbc.ingest.temporary (see Connection → Statement & ingest options). adbc.ingest.target_catalog is accepted only when it names the connected database: PostgreSQL cannot write to another one. Ingest reads the target table's column types, so an Arrow utf8 column loads into any column type (jsonb, uuid, integer, date, a range, …), and numbers are converted into an existing column of another type (a decimal into bigint, a float64 into numeric, …). A value the column's type would change fails the ingest, naming the column and row; see Data types → Write path. A dictionary-encoded column (a pandas Categorical) is written as its values.

To copy a table whose dates or timestamps hold infinity, read and ingest it with adbc.arpepgsql.temporal_infinity=extreme on both connections:

Python
opts = {"adbc.arpepgsql.temporal_infinity": "extreme"}
src = dbapi.connect(driver="arpepgsql", db_kwargs={"uri": SRC_URI, **opts})
dst = dbapi.connect(driver="arpepgsql", db_kwargs={"uri": DST_URI, **opts}, autocommit=True)

with src.cursor() as cur:
cur.execute("SELECT * FROM history")
table = cur.fetch_arrow_table() # infinity -> largest Arrow value
with dst.cursor() as cur:
cur.adbc_ingest("history", table, mode="append") # written back as infinity

Export a query to Parquet​

Python
import pyarrow.parquet as pq

with conn.cursor() as cur:
cur.execute("SELECT * FROM lineitem")
reader = cur.fetch_record_batch() # streaming RecordBatchReader
with pq.ParquetWriter("lineitem.parquet", reader.schema) as w:
for batch in reader:
w.write_batch(batch)

Streaming keeps memory flat regardless of result size: the driver hands over one batch of buffer_size rows (default 32,000) at a time.

TLS with certificate verification​

Verify the server certificate chain and hostname, and pin a custom root CA:

Python
conn = dbapi.connect(driver="arpepgsql", db_kwargs={
"adbc.arpepgsql.server": "db.example.com",
"adbc.arpepgsql.database": "mydb",
"adbc.arpepgsql.username": "alice",
"adbc.arpepgsql.password": "<password>",
"adbc.arpepgsql.sslmode": "verify-full",
"adbc.arpepgsql.ssl_root_cert": "/etc/ssl/certs/pg-root.pem",
# bind SCRAM to the TLS channel, refusing a PLUS-stripping downgrade:
"adbc.arpepgsql.channel_binding": "require",
}, autocommit=True)

See Connection → TLS & sslmode for the sslmode matrix.

Kerberos authentication (Linux)​

Log in with a Kerberos ticket, with no password. The host needs MIT Kerberos installed (krb5-libs or libgssapi-krb5-2).

Python
# kinit alice@EXAMPLE.COM   (or use a keytab, below)
conn = dbapi.connect(driver="arpepgsql", db_kwargs={
"adbc.arpepgsql.server": "db.example.com",
"adbc.arpepgsql.database": "mydb",
"adbc.arpepgsql.username": "alice", # PostgreSQL role mapped to your principal
"adbc.arpepgsql.auth_type": "integrated",
# optional explicit Kerberos credentials:
# "adbc.arpepgsql.krb5.ccache": "/tmp/krb5cc_1000",
# "adbc.arpepgsql.krb5.keytab": "/path/to/alice.keytab",
# encrypt with GSSAPI instead of TLS:
# "adbc.arpepgsql.gssencmode": "require",
})

See Authentication for the credential modes and the SPN.

Integrated authentication (Windows)​

On Windows: log in as the current Windows user through SSPI, with no password.

Python
conn = dbapi.connect(driver="arpepgsql", db_kwargs={
"adbc.arpepgsql.server": "db.example.com", # FQDN the SPN is registered for
"adbc.arpepgsql.database": "mydb",
"adbc.arpepgsql.username": "alice", # PostgreSQL role mapped to your Windows login
"adbc.arpepgsql.auth_type": "integrated",
# optional, when the SPN is not POSTGRES/db.example.com:
# "adbc.arpepgsql.krb5.spn": "POSTGRES/pg-cluster.example.com",
})

See Authentication for SPN and role mapping details.

Loading by explicit path​

Load-by-name (above) uses the ADBC manifest the installer registers. When the driver is not installed system-wide, point the driver manager at the shared library instead (libarpepgsql_adbc_driver-linux-x64.so on Linux, arpepgsql_adbc_driver-win-x64.dll on Windows) — e.g. pass the full path as driver= in Python, or in C# use CAdbcDriverImporter.Load("arpepgsql_adbc_driver-win-x64.dll", "AdbcDriverInit"). To keep loading by name with a manifest in a non-standard directory, point the driver manager's ADBC_DRIVER_PATH environment variable at that directory. Everything after loading is identical.

See also​