Connections and pools¶
Constructor options follow libpq names. Connections and Pools and PgBouncer explain how they interact.
Connection
¶
Connection(
dsn: str | None = None,
*,
service: str | None = None,
servicefile: str | Path | None = None,
host: str | Sequence[str] | None = None,
hostaddr: str | Sequence[str] | None = None,
port: int | str | Sequence[int] | None = None,
target_session_attrs: Literal[
'any', 'read-write', 'read-only', 'primary', 'standby', 'prefer-standby'
]
| None = None,
load_balance_hosts: Literal['disable', 'random'] | None = None,
connect_timeout: float | None = None,
keepalives: bool | None = None,
keepalives_idle: int | None = None,
keepalives_interval: int | None = None,
keepalives_count: int | None = None,
tcp_user_timeout: int | None = None,
user: str | None = None,
dbname: str | None = None,
password: str | PasswordProvider | None = None,
oauth_token: str | OAuthProvider | None = None,
krbsrvname: str | None = None,
gsslib: Literal['gssapi', 'sspi'] | None = None,
passfile: str | Path | None = None,
sslmode: Literal[
'disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full'
]
| None = None,
sslrootcert: str | Path | None = None,
sslcert: str | Path | None = None,
sslkey: str | Path | None = None,
sslpassword: str | bytes | KeyPasswordProvider | None = None,
sslcertmode: Literal['allow', 'disable', 'require'] | None = None,
sslnegotiation: Literal['postgres', 'direct'] | None = None,
sslsni: bool | None = None,
ssl_min_protocol_version: Literal['TLSv1.2', 'TLSv1.3'] | None = None,
ssl_max_protocol_version: Literal['TLSv1.2', 'TLSv1.3'] | None = None,
sslcrl: str | Path | None = None,
channel_binding: Literal['disable', 'prefer', 'require'] | None = None,
require_auth: str | None = None,
min_protocol_version: Literal['3.0', '3.2', 'latest'] | None = None,
max_protocol_version: Literal['3.0', '3.2', 'latest'] | None = None,
application_name: str | None = None,
options: str | None = None,
client_encoding: str | None = None,
server_settings: Mapping[str, str] | None = None,
pool_mode: PoolMode = 'session',
auto_prepare: bool | None = None,
sequential: bool = False,
decoding: Decoding | None = None,
adapters: Sequence[Binding] = (),
open_timeout: float | None = None,
operation_timeout: float | None = None,
max_value_bytes: int | None = None,
cleanup_timeout: float = 5.0,
tracer_provider: TracerProvider | None = None,
meter_provider: MeterProvider | None = None,
)
A dedicated PostgreSQL session. Construction does not open a socket.
Options use libpq names. For each one, an explicit argument overrides the connection string, which overrides the selected service section, then the PostgreSQL environment variable where one exists, then the default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str | None
|
A PostgreSQL URI or keyword connection string. Unsupported parameters are errors. |
None
|
service
|
str | None
|
Service section to read ( |
None
|
servicefile
|
str | Path | None
|
Service definitions file ( |
None
|
host
|
str | Sequence[str] | None
|
Host name, or a Unix socket directory. A comma-separated string
or a sequence lists hosts tried in order ( |
None
|
hostaddr
|
str | Sequence[str] | None
|
Numeric address to connect to, one per host. |
None
|
port
|
int | str | Sequence[int] | None
|
One port for every host, or one per host ( |
None
|
target_session_attrs
|
Literal['any', 'read-write', 'read-only', 'primary', 'standby', 'prefer-standby'] | None
|
Session role required of an accepted host
( |
None
|
load_balance_hosts
|
Literal['disable', 'random'] | None
|
|
None
|
connect_timeout
|
float | None
|
Seconds allowed for each host attempt
( |
None
|
keepalives
|
bool | None
|
Enable TCP keepalives. Enabled by default. |
None
|
keepalives_idle
|
int | None
|
Idle seconds before the first keepalive probe. |
None
|
keepalives_interval
|
int | None
|
Seconds between keepalive probes. |
None
|
keepalives_count
|
int | None
|
Unanswered probes before the connection is dropped. |
None
|
tcp_user_timeout
|
int | None
|
Milliseconds transmitted data may stay unacknowledged. Linux only. |
None
|
user
|
str | None
|
Database role ( |
None
|
dbname
|
str | None
|
Database name ( |
None
|
password
|
str | PasswordProvider | None
|
Password, or an async provider called only when the server
requests a password mechanism ( |
None
|
oauth_token
|
str | OAuthProvider | None
|
Bearer token, or an async provider that may first return
|
None
|
krbsrvname
|
str | None
|
Kerberos service name ( |
None
|
gsslib
|
Literal['gssapi', 'sspi'] | None
|
System authentication provider ( |
None
|
passfile
|
str | Path | None
|
Password file consulted when no password is given
( |
None
|
sslmode
|
Literal['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full'] | None
|
Transport policy ( |
None
|
sslrootcert
|
str | Path | None
|
PEM CA file that verifies the server, or |
None
|
sslcert
|
str | Path | None
|
PEM client certificate chain, leaf first ( |
None
|
sslkey
|
str | Path | None
|
Private key for |
None
|
sslpassword
|
str | bytes | KeyPasswordProvider | None
|
Passphrase for an encrypted PKCS#8 |
None
|
sslcertmode
|
Literal['allow', 'disable', 'require'] | None
|
Whether to send a client certificate ( |
None
|
sslnegotiation
|
Literal['postgres', 'direct'] | None
|
|
None
|
sslsni
|
bool | None
|
Send the host name in the TLS ClientHello ( |
None
|
ssl_min_protocol_version
|
Literal['TLSv1.2', 'TLSv1.3'] | None
|
Lowest TLS version accepted
( |
None
|
ssl_max_protocol_version
|
Literal['TLSv1.2', 'TLSv1.3'] | None
|
Highest TLS version accepted
( |
None
|
sslcrl
|
str | Path | None
|
PEM certificate revocation list for a file CA ( |
None
|
channel_binding
|
Literal['disable', 'prefer', 'require'] | None
|
SCRAM channel binding policy ( |
None
|
require_auth
|
str | None
|
Allowed server authentication methods ( |
None
|
min_protocol_version
|
Literal['3.0', '3.2', 'latest'] | None
|
Lowest accepted PostgreSQL protocol version:
|
None
|
max_protocol_version
|
Literal['3.0', '3.2', 'latest'] | None
|
PostgreSQL protocol version requested at startup:
|
None
|
application_name
|
str | None
|
Name reported in |
None
|
options
|
str | None
|
Server command-line options for the session ( |
None
|
client_encoding
|
str | None
|
Must resolve to |
None
|
server_settings
|
Mapping[str, str] | None
|
Session parameters set at startup. They override
|
None
|
pool_mode
|
PoolMode
|
|
'session'
|
auto_prepare
|
bool | None
|
Prepare repeated statements and reuse their inferred
types. |
None
|
sequential
|
bool
|
Run short individual lookups on the calling event loop instead
of Gres's background I/O thread, over a Unix socket without a
transaction pooler. Defaults to |
False
|
decoding
|
Decoding | None
|
Default result representations, overridable per call. |
None
|
adapters
|
Sequence[Binding]
|
Type bindings applied to every operation on this resource. |
()
|
open_timeout
|
float | None
|
Seconds allowed for opening, across all hosts. |
None
|
operation_timeout
|
float | None
|
Default budget in seconds for each operation. A
call's |
None
|
max_value_bytes
|
int | None
|
Largest encoded parameter, result field or typed COPY
field accepted, in bytes. |
None
|
cleanup_timeout
|
float
|
Seconds to wait for cancellation and close to finish before reporting them as still pending. |
5.0
|
tracer_provider
|
TracerProvider | None
|
OpenTelemetry tracer provider for operation spans. |
None
|
meter_provider
|
MeterProvider | None
|
OpenTelemetry meter provider for operation and pool metrics. |
None
|
listen
¶
listen(
channel: str,
*channels: str,
buffer_bytes: int = 1024 * 1024,
timeout: float | None = None,
) -> AbstractAsyncContextManager[AsyncIterator[Notification]]
Reserve a session for committed notifications on one or more channels.
Queue overflow (buffer_bytes exceeded) raises NotificationOverflowError;
overflow or connection loss ends delivery without reconnecting. timeout
limits the subscription lifetime in seconds; None (default) sets no
deadline and does not inherit operation_timeout.
prepare
¶
prepare(
sql: Source | Query,
*,
decoding: Decoding | None = None,
adapters: Sequence[Binding] | None = None,
column_adapters: ColumnBindings | None = None,
timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[dict[str, object]]]
prepare(
sql: Source | Query,
*,
row: type[_N],
decoding: Decoding | None = None,
adapters: Sequence[Binding] | None = None,
column_adapters: ColumnBindings | None = None,
timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[_N]]
prepare(
sql: Source | Query,
*,
row: type[tuple[*_Ts,]],
decoding: Decoding | None = None,
adapters: Sequence[Binding] | None = None,
column_adapters: ColumnBindings | None = None,
timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[tuple[*_Ts,]]]
prepare(
sql: Source | Query,
*,
row: type[dict[str, _T]],
decoding: Decoding | None = None,
adapters: Sequence[Binding] | None = None,
column_adapters: ColumnBindings | None = None,
timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[dict[str, _T]]]
prepare(
sql: Source | Query,
*,
row: _Scalar[_T] | Callable[..., _T],
decoding: Decoding | None = None,
adapters: Sequence[Binding] | None = None,
column_adapters: ColumnBindings | None = None,
timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[_T]]
prepare(
sql: Source | Query,
*,
row: Any = dict,
decoding: Decoding | None = None,
adapters: Sequence[Binding] | None = None,
column_adapters: ColumnBindings | None = None,
timeout: float | InheritType | None = INHERIT,
) -> AbstractAsyncContextManager[PreparedStatement[Any]]
Prepare one fixed-signature query on this held session. The context closes its server statement.
Pool
¶
Pool(
dsn: str | None = None,
*,
min_size: int = 0,
max_size: int = 10,
max_idle: float | None = 300.0,
max_waiters: int = 100,
**settings: Unpack[_ConnectionSettings],
)
A bounded pool of PostgreSQL sessions. Construction does not open a socket; use connection() to hold one session across several operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str | None
|
A PostgreSQL URI or keyword connection string, as for
|
None
|
min_size
|
int
|
Sessions the pool keeps open while idle. |
0
|
max_size
|
int
|
Physical capacity, including sessions being opened, reset, or closed. |
10
|
max_idle
|
float | None
|
Seconds an idle session above |
300.0
|
max_waiters
|
int
|
Callers allowed to queue for a session. Further demand
raises |
100
|
**settings
|
Unpack[_ConnectionSettings]
|
Every keyword option of |
{}
|
stats
property
¶
stats: PoolStats
Snapshot occupancy without checking out a session; physical states are mutually exclusive.
listen
¶
listen(
channel: str,
*channels: str,
buffer_bytes: int = 1024 * 1024,
timeout: float | None = None,
) -> AbstractAsyncContextManager[AsyncIterator[Notification]]
Reserve a session for committed notifications on one or more channels.
Queue overflow (buffer_bytes exceeded) raises NotificationOverflowError;
overflow or connection loss ends delivery without reconnecting. timeout
limits the subscription lifetime in seconds; None (default) sets no
deadline and does not inherit operation_timeout.
invalidate_types
¶
invalidate_types() -> None
Refresh client type metadata for subsequent operations on this pool.
Call on the pool's event loop after the migration commits. The call sends no SQL, does not disconnect borrowers, and does not change results already in flight. Other pools and processes must be notified separately.
connection
async
¶
connection(
*, timeout: float | InheritType | None = INHERIT
) -> AsyncGenerator[Connection, None]
Check out one session until the block exits. The checkout timeout does not limit the block.
aclose
async
¶
aclose() -> None
Close the pool and its sessions; closing is terminal.
New checkouts fail at once. Connections still checked out stop working, idle
sessions close, and Gres waits up to cleanup_timeout for their cleanup.
PoolStats
dataclass
¶
PoolStats(
idle: int,
in_use: int,
connecting: int,
resetting: int,
closing: int,
waiters: int,
)
A snapshot of the pool's sessions and the callers waiting for one.
Each session is counted in exactly one of idle, in_use, connecting,
resetting and closing; together they hold the capacity, at most max_size.
Attributes:
| Name | Type | Description |
|---|---|---|
idle |
int
|
Open sessions ready to be checked out. |
in_use |
int
|
Sessions checked out by callers. |
connecting |
int
|
Sessions being opened. |
resetting |
int
|
Returned sessions whose reset has not finished. |
closing |
int
|
Sessions being closed that still hold capacity. |
waiters |
int
|
Callers waiting for a session. |
pending_cleanup
property
¶
pending_cleanup: int
Sessions whose reset or close has not finished: resetting + closing.
ConnectionTarget
dataclass
¶
ConnectionTarget(
host: str, hostaddr: str | None, port: int, dbname: str, user: str
)
PasswordProvider
module-attribute
¶
PasswordProvider: TypeAlias = Callable[[PasswordRequest], Awaitable[str]]
Async callback returning a password when the server challenges with a password mechanism.
PasswordRequest
dataclass
¶
PasswordRequest(target: ConnectionTarget, mechanism: Mechanism)
An admitted server password challenge, before any response is sent.
KeyPasswordProvider
module-attribute
¶
KeyPasswordProvider: TypeAlias = Callable[
[KeyPasswordRequest], Awaitable[str | bytes]
]
Async callback returning the passphrase for an encrypted sslkey.
KeyPasswordRequest
dataclass
¶
KeyPasswordRequest(keyfile: Path)
The selected encrypted local private key, before TLS negotiation.
OAuthProvider
module-attribute
¶
OAuthProvider: TypeAlias = Callable[[OAuthRequest], Awaitable[str | None]]
Async callback returning an OAuth bearer token, or None to request server discovery metadata.
OAuthRequest
dataclass
¶
OAuthRequest(target: ConnectionTarget, discovery: OAuthDiscovery | None)
Bearer token request for one endpoint, with metadata only after deliberate discovery.