Connections¶
Connection and Pool accept standard libpq option names; the Connection reference lists every parameter and default.
Configuration and precedence¶
# Partial: configuration forms; host names and credentials are placeholders.
from gres import Connection, Pool
db = Connection() # PGHOST, PGDATABASE, PGUSER, ... from the environment
db = Connection(
'postgresql://app@db.example.com:5432/inventory?application_name=api'
)
db = Connection('host=db.example.com dbname=inventory user=app')
db = Connection(
host='db.example.com', dbname='inventory', user='app', password=secret
)
pool = Pool('service=inventory', max_size=20)
Each setting resolves from the first source that provides it:
- Keyword argument
- Connection string (PostgreSQL URI or keyword format)
- Selected service file section (
service/PGSERVICE; per-user.pg_service.conf,servicefile/PGSERVICEFILE, orPGSYSCONFDIR/pg_service.conf) - libpq environment variables (
PGHOST,PGPORT,PGDATABASE,PGUSER,PGPASSWORD,PGSSLMODE, etc.) - Default
Common deployment setups:
- Local development: leave
hostunset or point it at a Unix socket directory (local sockets do not use TLS). A local TCP container without TLS needssslmode='disable'on loopback or a private network only. - Managed PostgreSQL with a public CA: defaults apply (
sslmode='verify-full'against system trust). - Managed PostgreSQL with a private CA (such as Amazon RDS): pass the provider's CA bundle as
sslrootcertand keepsslmode='verify-full'. - Transaction poolers (such as PgBouncer): set
pool_mode='transaction'; see PgBouncer transaction pooling.
Keep passwords out of connection strings that may reach logs; use PGPASSWORD, a password file, or a credential provider. Unsupported libpq parameters in a connection string, service section, or environment variable raise ConfigurationError rather than being ignored. Gres does not implement GSSAPI encryption or delegation and accepts gssencmode=disable/prefer, gssdelegation=0, and either sslcompression value (gssencmode=require is an error).
An open pool freezes its resolved settings for new physical connections; after a failed open(), retrying resolves configuration again. Containers without a user home directory can use a system service definition with explicit paths for sslrootcert, sslcert, sslkey, or passfile.
Lifecycle and timeouts¶
Constructing a Connection or Pool performs no I/O. Open with async with or await db.open(), and close terminally with await db.aclose().
# Partial: run inside a coroutine; settings come from the libpq environment.
from gres import Connection, scalar
db = Connection(operation_timeout=5)
await db.open()
try:
user = await db.fetch_one('SELECT current_user', row=scalar(str))
finally:
await db.aclose()
- Use a connection on the event loop that opened it, one operation at a time.
open_timeout,operation_timeout, andcleanup_timeoutare in seconds. Per-calltimeoutdefaults tooperation_timeout(INHERIT);Nonedisables the deadline, and0expires before dispatch.- On timeout or task cancellation during execution, Gres cancels the running statement on the server and waits up to
cleanup_timeoutto keep the session usable (any open transaction is aborted). See Retry safety for dispatch guarantees and why Gres never replays statements. - Protocol negotiation: Gres requests PostgreSQL protocol
3.2by default (max_protocol_version='latest'), enabling 256-bit cancel keys on PostgreSQL 18+ while older servers negotiate down to3.0. Setmax_protocol_version='3.0'(PGMAXPROTOCOLVERSION) behind a pooler or proxy that drops connections on a3.2startup packet; setmin_protocol_version='3.2'to refuse downgrade.
TLS and authentication¶
TCP connections default to sslmode='verify-full', requiring TLS and verifying both the certificate chain and host name (the only mode protecting against server impersonation on an untrusted network). Gres supports all standard libpq sslmode values (verify-full, verify-ca, require, prefer, allow, disable).
sslnegotiation='direct'starts TLS immediately with PostgreSQL ALPN and never falls back to plaintext.hostaddrselects the IP address to connect to whilehostremains the TLS certificate identity.sslsni=Falseomits SNI from the TLS ClientHello without disabling host-name verification.ssl_min_protocol_versionandssl_max_protocol_versionselectTLSv1.2orTLSv1.3.
Certificate authorities¶
- Pass
sslrootcertfor a private CA, optionally paired with a PEMsslcrl(system trust does not accept a separate CRL file). - Without
sslrootcert, Gres uses~/.postgresql/root.crt(%APPDATA%\postgresql\root.crton Windows) in place of system trust when present; passsslrootcert='system'to select system trust explicitly. Unreadable conventional files fail opening rather than falling back silently. - The same directory supplies
postgresql.crtandpostgresql.keyfor client certificates unlesssslcertmode='disable'.
Passwords and channel binding¶
- Pass
passwordas a string or an asyncPasswordProvideraccepting aPasswordRequest(called only when the server requests a password mechanism). Providers run on the opening event loop in a copy of its context; cancelling opening cancels the provider, and a pool holds the opening slot until it finishes. - Without
passwordorPGPASSWORD, Gres reads the first matching entry inpassfile,PGPASSFILE, or the per-user.pgpass(which must deny group/other access on Unix). New physical connections re-read the file; a rejected explicit credential never falls back to it. channel_binding='prefer'(default) selectsSCRAM-SHA-256-PLUSwhen available;'require'refuses any authentication not bound to the TLS endpoint;'disable'omits channel binding.require_auth(PGREQUIREAUTH) restricts allowed server methods as in libpq: e.g.require_auth='scram-sha-256'orrequire_auth='!password,!md5'. Any disallowed method fails withConfigurationErrorbefore credentials are sent.
OAuth bearer tokens¶
PostgreSQL 18+ supports OAuth bearer tokens. Pass a token string or an async OAuthProvider accepting an OAuthRequest:
- Return a cached token to authenticate immediately, or
Noneto request the server's discovery URL and scope. - On the second call, validate
request.discoveryagainst your trusted identity provider, obtain a token, and return it.
Gres makes no HTTP requests (libpq's oauth_issuer/oauth_ca_file device-flow options do not apply); your provider owns HTTP and trust configuration. A rejected token does not trigger a refresh. On TCP, OAuth requires hostname-verified TLS; channel_binding='require' precludes OAuth because it requires SCRAM-SHA-256-PLUS. Discovery reconnects to the same address within the remaining opening budget.
Kerberos and SSPI¶
Install the kerberos extra for GSSAPI authentication.
- The service principal uses
host(even withhostaddr) andkrbsrvname(default'postgres'). - Gres requests mutual authentication without delegation; pair with verified TLS for transport encryption.
- On Windows, SSPI uses the current logon and refuses NTLM (which cannot prove server identity).
TLS client certificates¶
Set sslcert (PEM chain, leaf first) and sslkey.
- For an encrypted PKCS#8 key, set
sslpasswordto a string, bytes, or an asyncKeyPasswordProvideraccepting aKeyPasswordRequest(called only for encrypted keys, never prompted). - Server verification (
sslrootcert) is independent. Each new physical connection re-reads the files so rotated certificates take effect without restarting a pool. sslcertmode='allow'sends the certificate if requested,'require'fails if the server does not request one, and'disable'withholds it.
Multi-host and standbys¶
Pass host as a comma-separated string or a sequence, with a single port or a matching sequence.
- Hosts are tried in order;
load_balance_hosts='random'shuffles hosts and resolved addresses per physical connection (never mid-transaction). - Connection refusal advances to the next host; an authentication failure ends the attempt immediately.
target_session_attrs=requires a writable primary ('read-write' primaryalone does not imply writable);prefer-standbyprefers a standby before falling back.connect_timeoutbounds each host attempt;open_timeoutbounds the entire open.- TCP keepalives: enabled by default with OS timings. Configure
keepalives,keepalives_idle,keepalives_interval,keepalives_count, and Linuxtcp_user_timeout(ms). These apply to TCP connections (including cancel sockets), not Unix sockets or query deadlines.
Read your own writes from a standby¶
On PostgreSQL 19, WAIT FOR LSN holds a standby session until it has replayed a WAL position from the primary:
# Partial: primary and standby are open connections to PostgreSQL 19.
from gres import Literal, scalar
await primary.execute('INSERT INTO orders (id) VALUES ($1)', (42,))
lsn = await primary.fetch_one(
'SELECT pg_current_wal_insert_lsn()::text', row=scalar(str)
)
await standby.execute("WAIT FOR LSN $lsn WITH (TIMEOUT '5s')", {'lsn': Literal(lsn)})
order = await standby.fetch_optional('SELECT id FROM orders WHERE id = $1', (42,))
Pass the LSN as a Literal. Timeout raises ServerError unless you add NO_THROW (which returns 'timeout' as a row). Run WAIT outside a transaction or as its first statement before a snapshot or lock is acquired.
Session defaults and limits¶
- Session parameters: pass
server_settings={'TimeZone': 'UTC'}toConnectionorPool. They overrideoptions/PGOPTIONSand are restored on pooled session reset. Native decoding requiresUTF8client encoding,ISODateStyle,IntervalStyle=postgres, and positiveextra_float_digits; Gres checks these on open and application SQL must preserve them. - Field size limit: set
max_value_bytes(default unlimited) to bound any single encoded parameter, result field (including arrays/records with framing), or typed COPY field.0still allows empty payloads andNULL; raw COPY chunks and inline SQL literals are excluded. Oversized parameters raiseEncodingErrorbefore dispatch; oversized results raiseDecodingError(wrap writes in a transaction if decoding failure must roll them back). - Event-loop scheduling (
sequential=True): aConnection-only keyword option (not valid onPoolor DSNs) that runs short individual lookups on the calling event loop instead of the background I/O thread over a direct Unix socket. Any managed transaction, bulk operation, or large transfer permanently moves the connection to the background thread without reconnecting; TCP and transaction pooling always use the background thread. Keep the default (False) for services sharing an event loop across multiple connections.