async_postgres
Async PostgreSQL client
Summary
| Latest Version | 0.5.0 |
|---|---|
| License | MIT |
| CI Status | Failing |
| Downloads | 0 |
| Last Indexed | 2026-11-21 14:04 |
Tags
Authors
- fox0430
Installation
nimble install async_postgres
choosenim install async_postgres
git clone https://github.com/fox0430/async-postgres
OS Compatibility
| Platform | Linux | macOS | Windows | FreeBSD | OpenBSD | NetBSD | Android | iOS | WASM | Embedded |
|---|---|---|---|---|---|---|---|---|---|---|
| async_postgres | ✓ | ✓ | ✓ | - | - | - | - | - | - | - |
Dependencies
| Package | Version | Optional |
|---|---|---|
| nim >= | 2.2.4 | No |
| nimcrypto >= | 0.7.3 | No |
| checksums >= | 0.2.2 | No |
| unicodedb >= | 0.13.2 | No |
| normalize >= | 0.9.0 | No |
Source
| Repository | https://github.com/fox0430/async-postgres |
|---|---|
| Homepage | https://github.com/fox0430/async-postgres |
| Registry Source | nimble_official |
README
async_postgres
Async PostgreSQL client in Nim.
Features
Protocol & Connection
- PostgreSQL wire protocol v3
- Simple Query and Extended Query Protocol
- Pipeline mode — batch multiple operations in a single network round trip
- Connection pooling with health checks, a session reset on each release, and an
afterConnecthook - Pool cluster with read replica routing
- SSL/TLS support (disable, allow, prefer, require, verify-ca, verify-full) with optional client certificate authentication (mTLS)
sslnegotiationmode (postgres, direct) for Direct SSL connections (PostgreSQL 17+)- MD5, SCRAM-SHA-256 and SCRAM-SHA-256-PLUS authentication
channel_bindingpolicy (disable, prefer, require) to harden SCRAM against downgradecredentialsProviderfor per-connection credentials (expiring tokens such as AWS RDS IAM, rotated secrets)- DSN connection string parsing, filled in like libpq from
PG*environment variables,pg_service.confand.pgpass - Unix socket connection
- Multi-host failover, with
load_balance_hosts=randomto spread connections across hosts - Target session attributes (any, read-write, read-only, primary, standby, prefer-standby)
Queries & Statements
sqlmacro — compile-time{expr}placeholder extraction with automatic parameterization?-style placeholders (sqlParams) for db_connector compatibility- Prepared statements with server-side statement cache (LRU eviction)
- Server-side cursors (streaming row chunks)
- Transactions (
withTransaction) - COPY IN / COPY OUT (buffered and streaming), including typed rows in binary COPY (
copyInRows) - Large Object API (streaming binary data)
- LISTEN/NOTIFY with auto-reconnect
- Advisory locks (session/transaction, exclusive/shared)
- Logical and physical replication (pgoutput decoder for logical streams)
Types
- Typed parameters (
pgParams/toPgParam) and row accessors (getStr,getInt, ...) - Row-to-object mapping by column name (
row.to(User),qr.to(seq[User])) - UUID type (
PgUuid) - Numeric type (
PgNumeric— arbitrary-precision decimal) - JSON/JSONB (
JsonNode) - Array types with binary format support
- Range and multirange types (
int4range,tsrange,daterange, ...) - Composite types (user-defined row types via
pgCompositemacro) - Enum types (user-defined enums via
pgEnummacro) - Domain types (user-defined domains via
pgDomainmacro) - Network types (
inet,cidr,macaddr,macaddr8) - Geometric types (
point,line,lseg,box,path,polygon,circle) - Text search types (
tsvector,tsquery) - Bit string types (
bit,varbit) - Interval type (
PgInterval) - hstore type (
PgHstore— extension; requireslookupTypeOidsfor binary encoding) - XML type (
PgXml)
Performance
- Automatic binary format selection for known-safe types
- Compile-time binary format lookup tables
- Zero-copy binary array decoding
- Optimized protocol encoding with minimized allocations
Observability
- Tracing hooks for connection, query, prepared statement, pipeline, COPY, and pool operations
Platform
- Async backend: asyncdispatch (default) or chronos
Requirements
-
Nim >= 2.2.4
-
chronos >= 4.4.0 (Only chronos backend)
-
nim-bearssl >= 0.2.11 (Only chronos backend; TLS 1.2 only due to BearSSL limitation)
Installation
nimble install async_postgres
Basic Usage
import pkg/async_postgres
proc main() {.async.} =
let conn = await connect("postgresql://myuser:mypass@127.0.0.1:5432/mydb")
defer: await conn.close()
# Insert with typed parameters
let name = "Alice"
let age = 30'i32
let cr = await conn.exec(sql"INSERT INTO users (name, age) VALUES ({name}, {age})")
echo "Inserted: ", cr.affectedRows
# Query multiple rows
let minAge = 25'i32
let row = await conn.query(sql"SELECT id, name, age FROM users WHERE age > {minAge}")
for r in row:
echo r.getStr("name"), " age=", r.getInt("age")
# Query a single value
let count = await conn.queryValueOrDefault("SELECT count(*) FROM users", default = "0")
echo "Total users: ", count
waitFor main()
Reconnection Policy
- Connection pool (
PgPool/PgPoolCluster) — broken connections are discarded onacquireandrelease. - Direct
PgConnection— never reconnects on its own: per-query retry is unsafe for non-idempotent statements and open transactions, so callconnect(...)again or use the pool. - LISTEN/NOTIFY — the one exception. The listen pump reconnects with
backoff and re-subscribes every channel, but a NOTIFY sent while it is down
is lost (catch up in
onReconnect), session state such asSET ROLEdoes not carry over, and it can give up (watchonListenError). - Retry classification —
retryAdvice(err)returnsraRetry,raStoporraUnclearfor any failure. A config fault raisesPgConfigError, not aPgConnectionError, so reconnect loops do not retry it;raRetrystill does not make replaying aCOMMITsafe.
See pg_pool,
pg_errors
and onReconnect in the API docs for the details.
Async Backend
By default, asyncdispatch is used. To use chronos:
# asyncdispatch (default)
nim c your_app.nim
# asyncdispatch with ssl
nim c -d:ssl your_app.nim
# chronos
nim c -d:asyncBackend=chronos your_app.nim
chronos is recommended. chronos supports proper future cancellation, which enables reliable timeout handling and clean connection teardown. asyncdispatch lacks real cancellation — timed-out futures continue running in the background, and cancelAndWait is a no-op.
TLS uses OpenSSL on asyncdispatch and BearSSL (via
nim-bearssl) on chronos. Without
-d:ssl, asyncdispatch connects in plaintext under sslmode=prefer/allow
and raises PgConfigError for settings that need TLS. Differences to weigh
when choosing a backend:
- chronos negotiates TLS 1.2 only; asyncdispatch also uses 1.3 when offered.
- chronos fails the handshake on an expired or not-yet-valid server
certificate even under
allow/prefer, andrequirewithout a CA, where asyncdispatch does not check it. - chronos refuses
verify-fullto an IP-literal host. - chronos sends SNI only under
verify-full(sslsnihas no effect).
As in libpq, require verifies the server against sslrootcert when one is
set, and parseDsn fills unset TLS files from ~/.postgresql (root.crt,
postgresql.crt, postgresql.key).
The API docs
list every TLS difference and the stderr-only downgrade notices, and show how
to catch the sslmode=prefer plaintext fallback with conn.sslEnabled.
ConnConfig.sslCert / sslKey describe client certificates (mTLS).
Examples
The examples directory contains runnable samples:
- basic_query — Connect, insert, and query rows
- query_variants —
queryExists/queryValueOrDefault/queryValueOpt/queryRowOpt/queryColumn/queryEach/simpleExec/simpleQuery - query_direct — Low-allocation
queryDirect/execDirectmacros for hot paths (parameter encoding is allocation-free) - prepared_statement — Server-side prepared statements
- transaction — Transaction control with rollback and isolation levels
- cursor — Server-side cursors for streaming large result sets
- pipeline — Batch multiple operations in a single round trip
- copy — Bulk import/export with COPY protocol
- large_object — Large Object API for binary data
- listen_notify — LISTEN/NOTIFY
- pool — Connection pooling
- pool_cluster — Read/write splitting with pool cluster
- advisory_lock — Application-level distributed locking
- replication — Logical replication with pgoutput
Documentation
https://fox0430.github.io/async-postgres/async_postgres.html
License
MIT