Source: https://gres.monicz.dev/guide/connections/

# Connections

`Connection` and `Pool` accept standard libpq option names; the [`Connection` reference](https://gres.monicz.dev/api/connections/#gres.Connection) lists every parameter and default.

## Configuration and precedence

```python
# 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:

1. Keyword argument
2. Connection string ([PostgreSQL URI or keyword format](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING))
3. Selected [service file](https://www.postgresql.org/docs/current/libpq-pgservice.html) section (`service` / `PGSERVICE`; per-user `.pg_service.conf`, `servicefile` / `PGSERVICEFILE`, or `PGSYSCONFDIR/pg_service.conf`)
4. [libpq environment variables](https://www.postgresql.org/docs/current/libpq-envars.html) (`PGHOST`, `PGPORT`, `PGDATABASE`, `PGUSER`, `PGPASSWORD`, `PGSSLMODE`, etc.)
5. Default

Common deployment setups:

- **Local development:** leave `host` unset or point it at a Unix socket directory (local sockets do not use TLS). A local TCP container without TLS needs `sslmode='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 `sslrootcert` and keep `sslmode='verify-full'`.
- **Transaction poolers** (such as PgBouncer): set `pool_mode='transaction'`; see [PgBouncer transaction pooling](https://gres.monicz.dev/guide/pools/#pgbouncer-transaction-pooling).

Keep passwords out of connection strings that may reach logs; use `PGPASSWORD`, a [password file](https://gres.monicz.dev/guide/connections/#passwords-and-channel-binding), 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()`.

```python
# 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`, and `cleanup_timeout` are in seconds. Per-call `timeout` defaults to `operation_timeout` (`INHERIT`); `None` disables the deadline, and `0` expires before dispatch.
- On timeout or task cancellation during execution, Gres cancels the running statement on the server and waits up to `cleanup_timeout` to keep the session usable (any open transaction is aborted). See [Retry safety](https://gres.monicz.dev/guide/errors/#retry-safety) for dispatch guarantees and why Gres never replays statements.
- **Protocol negotiation:** Gres requests PostgreSQL protocol `3.2` by default (`max_protocol_version='latest'`), enabling 256-bit cancel keys on PostgreSQL 18+ while older servers negotiate down to `3.0`. Set `max_protocol_version='3.0'` (`PGMAXPROTOCOLVERSION`) behind a pooler or proxy that drops connections on a `3.2` startup packet; set `min_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](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-PROTECTION) (`verify-full`, `verify-ca`, `require`, `prefer`, `allow`, `disable`).

- `sslnegotiation='direct'` starts TLS immediately with PostgreSQL ALPN and never falls back to plaintext.
- `hostaddr` selects the IP address to connect to while `host` remains the TLS certificate identity. `sslsni=False` omits SNI from the TLS ClientHello without disabling host-name verification.
- `ssl_min_protocol_version` and `ssl_max_protocol_version` select `TLSv1.2` or `TLSv1.3`.

### Certificate authorities

- Pass `sslrootcert` for a private CA, optionally paired with a PEM `sslcrl` (system trust does not accept a separate CRL file).
- Without `sslrootcert`, Gres uses `~/.postgresql/root.crt` (`%APPDATA%\postgresql\root.crt` on Windows) in place of system trust when present; pass `sslrootcert='system'` to select system trust explicitly. Unreadable conventional files fail opening rather than falling back silently.
- The same directory supplies `postgresql.crt` and `postgresql.key` for client certificates unless `sslcertmode='disable'`.

### Passwords and channel binding

- Pass `password` as a string or an async `PasswordProvider` accepting a `PasswordRequest` (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 `password` or `PGPASSWORD`, Gres reads the first matching entry in `passfile`, `PGPASSFILE`, or the per-user [`.pgpass`](https://www.postgresql.org/docs/current/libpq-pgpass.html) (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) selects `SCRAM-SHA-256-PLUS` when 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](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-REQUIRE-AUTH): e.g. `require_auth='scram-sha-256'` or `require_auth='!password,!md5'`. Any disallowed method fails with `ConfigurationError` before credentials are sent.

### OAuth bearer tokens

PostgreSQL 18+ supports [OAuth bearer tokens](https://www.postgresql.org/docs/current/auth-oauth.html). Pass a token string or an async `OAuthProvider` accepting an `OAuthRequest`:

1. Return a cached token to authenticate immediately, or `None` to request the server's discovery URL and scope.
2. On the second call, validate `request.discovery` against 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](https://www.postgresql.org/docs/current/gssapi-auth.html).

- The service principal uses `host` (even with `hostaddr`) and `krbsrvname` (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 `sslpassword` to a string, bytes, or an async `KeyPasswordProvider` accepting a `KeyPasswordRequest` (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='read-write'` requires a writable primary (`primary` alone does not imply writable); `prefer-standby` prefers a standby before falling back.
- `connect_timeout` bounds each host attempt; `open_timeout` bounds the entire open.
- **TCP keepalives:** enabled by default with OS timings. Configure `keepalives`, `keepalives_idle`, `keepalives_interval`, `keepalives_count`, and Linux `tcp_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`](https://www.postgresql.org/docs/19/sql-wait.html) holds a standby session until it has replayed a WAL position from the primary:

```python
# 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'}` to `Connection` or `Pool`. They override `options`/`PGOPTIONS` and are restored on pooled session reset. Native decoding requires `UTF8` client encoding, `ISO` `DateStyle`, `IntervalStyle=postgres`, and positive `extra_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. `0` still allows empty payloads and `NULL`; raw COPY chunks and inline SQL literals are excluded. Oversized parameters raise `EncodingError` before dispatch; oversized results raise `DecodingError` (wrap writes in a transaction if decoding failure must roll them back).
- **Event-loop scheduling (`sequential=True`):** a `Connection`-only keyword option (not valid on `Pool` or 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.
