psycopg Adapter¶
from sqlspec.adapters.psycopg import (
PsycopgAsyncConfig,
PsycopgAsyncDriver,
PsycopgAsyncExceptionHandler,
PsycopgConnectionParams,
PsycopgDriverFeatures,
PsycopgPoolParams,
PsycopgSyncConfig,
PsycopgSyncDriver,
PsycopgSyncExceptionHandler,
)
Synchronous and asynchronous PostgreSQL adapters built on psycopg v3 and psycopg_pool. Inherited execution methods are documented on SyncDriverAdapterBase and AsyncDriverAdapterBase. See the PostgreSQL (psycopg) Setup Guide for setup and COPY streaming examples.
Configuration & Parameters¶
PsycopgSyncConfig
¶
Bases: SyncDatabaseConfig[PsycopgSyncConnection, PsycopgConnectionPool, PsycopgSyncDriver]
Configuration for Psycopg synchronous database connections with direct field-based configuration.
PsycopgAsyncConfig
¶
Bases: AsyncDatabaseConfig[PsycopgAsyncConnection, PsycopgAsyncConnectionPool, PsycopgAsyncDriver]
Configuration for Psycopg asynchronous database connections with direct field-based configuration.
PsycopgConnectionParams
¶
Bases: TypedDict
Psycopg connection parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
conninfo |
NotRequired[str]
|
PostgreSQL libpq connection URI or keyword/value conninfo string. |
host |
NotRequired[str]
|
Database server hostname or Unix socket directory. |
port |
NotRequired[int]
|
Database server TCP port (defaults to |
user |
NotRequired[str]
|
PostgreSQL role name used for authentication. |
password |
NotRequired[str]
|
Password or token for |
dbname |
NotRequired[str]
|
Target PostgreSQL database name. |
connect_timeout |
NotRequired[int]
|
Connection establishment timeout in seconds. |
options |
NotRequired[str]
|
Command-line startup GUC options sent to the PostgreSQL backend. |
application_name |
NotRequired[str]
|
Application identifier reported in |
sslmode |
NotRequired[PsycopgSSLMode]
|
libpq TLS verification mode ( |
sslcert |
NotRequired[str]
|
Path to the client TLS certificate file. |
sslkey |
NotRequired[str]
|
Path to the client TLS private key file. |
sslrootcert |
NotRequired[str]
|
Path to the trusted root CA certificate file. |
autocommit |
NotRequired[bool]
|
Enable Psycopg autocommit mode outside explicit transactions. |
prepare_threshold |
NotRequired[int | None]
|
Executions before server-side statement preparation, or |
context |
NotRequired[PsycopgAdaptContext | None]
|
Custom Psycopg |
row_factory |
NotRequired[PsycopgRowFactory[Any] | PsycopgAsyncRowFactory[Any] | None]
|
Row factory applied to raw Psycopg connections or cursors. |
cursor_factory |
NotRequired[type[PsycopgCursor[Any] | PsycopgNativeAsyncCursor[Any]] | None]
|
Custom Psycopg |
extra |
NotRequired[dict[str, Any]]
|
Additional libpq keyword parameters forwarded to |
PsycopgPoolParams
¶
Bases: PsycopgConnectionParams
Psycopg pool parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
min_size |
NotRequired[int]
|
Minimum number of connections kept open in |
max_size |
NotRequired[int]
|
Maximum number of connections allowed in the pool. |
connection_class |
NotRequired[type[PsycopgConnection[Any] | PsycopgNativeAsyncConnection[Any]]]
|
Custom Psycopg |
name |
NotRequired[str]
|
Pool identifier used in logs and worker thread names. |
timeout |
NotRequired[float]
|
Maximum wait time in seconds when acquiring a connection from the pool. |
max_waiting |
NotRequired[int]
|
Maximum number of queued callers waiting for a connection ( |
max_lifetime |
NotRequired[float]
|
Maximum connection age in seconds before recycling. |
max_idle |
NotRequired[float]
|
Maximum idle duration in seconds before shrinking connections above |
reconnect_timeout |
NotRequired[float]
|
Seconds to retry failed connection attempts before invoking |
num_workers |
NotRequired[int]
|
Number of background maintenance workers run by |
open |
NotRequired[bool | None]
|
Whether to open the pool immediately upon instantiation. |
configure |
NotRequired[PsycopgConnectionCB[PsycopgSyncConnection] | PsycopgAsyncConnectionCB[PsycopgAsyncConnection] | None]
|
Callback run once on each new physical connection before entering the pool. |
check |
NotRequired[PsycopgConnectionCB[PsycopgSyncConnection] | PsycopgAsyncConnectionCB[PsycopgAsyncConnection] | None]
|
Health-check callback run before lending out a pooled connection. |
reset |
NotRequired[PsycopgConnectionCB[PsycopgSyncConnection] | PsycopgAsyncConnectionCB[PsycopgAsyncConnection] | None]
|
Reset callback run when returning a connection to the pool. |
close_returns |
NotRequired[bool]
|
Make |
reconnect_failed |
NotRequired[PsycopgConnectFailedCB | PsycopgAsyncConnectFailedCB | None]
|
Callback invoked when pool reconnection attempts exceed |
kwargs |
NotRequired[dict[str, Any]]
|
Explicit connection keyword mapping passed to |
null_pool |
NotRequired[bool]
|
Use |
PsycopgDriverFeatures
¶
Bases: TypedDict
Optional Psycopg driver feature flags, extension codecs, AlloyDB settings, and pooler modes.
Attributes:
| Name | Type | Description |
|---|---|---|
enable_pgvector |
NotRequired[bool]
|
Register |
enable_paradedb |
NotRequired[bool]
|
Detect |
enable_pg_textsearch |
NotRequired[bool]
|
Detect |
json_serializer |
NotRequired[Callable[[Any], str]]
|
Custom JSON serializer applied to statement parameters and Psycopg JSON dumpers. |
json_deserializer |
NotRequired[Callable[[str], Any]]
|
Custom JSON deserializer applied to Psycopg JSON/JSONB loaders. |
on_connection_create |
NotRequired[Callable[..., Any]]
|
Sync or async callback invoked with each raw Psycopg connection after internal setup. |
enable_events |
NotRequired[bool]
|
Enable SQLSpec event channel pub/sub support (defaults to |
events_backend |
NotRequired[Literal['notify', 'notify_queue', 'poll_queue']]
|
Event transport backend ( |
enable_alloydb |
NotRequired[bool]
|
Route sync connections through |
alloydb_instance_uri |
NotRequired[str]
|
AlloyDB instance resource URI ( |
enable_alloydb_iam_auth |
NotRequired[bool]
|
Use IAM database authentication with the AlloyDB Python Connector. |
alloydb_ip_type |
NotRequired[str]
|
AlloyDB network path ( |
enable_alloydb_columnar |
NotRequired[bool]
|
Enable |
pooler_mode |
NotRequired[Literal['session', 'transaction', 'statement', 'auto']]
|
External pooler compatibility mode; sets |
pgbouncer |
NotRequired[bool]
|
Alias for |
pgbouncer_mode |
NotRequired[bool]
|
Alias for |
direct_dsn |
NotRequired[str | Mapping[str, Any] | None]
|
Direct PostgreSQL DSN or connection mapping bypassing the pooler for migrations and |
null_pool |
NotRequired[bool]
|
Enable |
Driver & Pool¶
PsycopgSyncDriver
¶
Bases: PsycopgPipelineMixin, SyncDriverAdapterBase
PostgreSQL psycopg synchronous driver.
Provides synchronous database operations for PostgreSQL using psycopg3. Supports SQL statement execution with parameter binding, transaction management, result processing with column metadata, parameter style conversion, PostgreSQL arrays and JSON handling, COPY operations for bulk data transfer, and PostgreSQL-specific error handling.
PsycopgAsyncDriver
¶
Bases: PsycopgPipelineMixin, AsyncDriverAdapterBase
PostgreSQL psycopg asynchronous driver.
Provides asynchronous database operations for PostgreSQL using psycopg3. Supports async SQL statement execution with parameter binding, async transaction management, async result processing with column metadata, parameter style conversion, PostgreSQL arrays and JSON handling, COPY operations for bulk data transfer, PostgreSQL-specific error handling, and async pub/sub support.
PsycopgSyncExceptionHandler
¶
Bases: BaseSyncExceptionHandler
Context manager for handling PostgreSQL psycopg database exceptions.
Maps PostgreSQL SQLSTATE error codes to SQLSpec exceptions stored on
pending_exception.
PsycopgAsyncExceptionHandler
¶
Bases: BaseAsyncExceptionHandler
Async context manager for handling PostgreSQL psycopg database exceptions.
Maps PostgreSQL SQLSTATE error codes to SQLSpec exceptions stored on
pending_exception.
Extension Stores¶
PsycopgSyncStore
¶
Bases: BaseSQLSpecStore['PsycopgSyncConfig']
PostgreSQL session store using Psycopg sync driver.
Implements server-side session storage for Litestar using PostgreSQL via the synchronous Psycopg (psycopg3) driver. Uses Litestar's sync_to_thread utility to provide an async interface compatible with the Store protocol.
Provides efficient session management with
- Sync operations wrapped for async compatibility
- UPSERT support using ON CONFLICT
- Automatic expiration handling
- Efficient cleanup of expired sessions
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PsycopgSyncConfig
|
PsycopgSyncConfig instance. |
required |
PsycopgAsyncStore
¶
Bases: BaseSQLSpecStore['PsycopgAsyncConfig']
PostgreSQL session store using Psycopg async driver.
Implements server-side session storage for Litestar using PostgreSQL via the Psycopg (psycopg3) async driver. Provides efficient session management with: - Native async PostgreSQL operations - UPSERT support using ON CONFLICT - Automatic expiration handling - Efficient cleanup of expired sessions
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PsycopgAsyncConfig
|
PsycopgAsyncConfig instance. |
required |
PsycopgSyncADKStore
¶
Bases: BaseSyncADKStore['PsycopgSyncConfig']
PostgreSQL synchronous ADK store using Psycopg3 driver.
PsycopgAsyncADKStore
¶
Bases: BaseAsyncADKStore['PsycopgAsyncConfig']
PostgreSQL ADK store using Psycopg3 async driver.
Implements session and event storage for Google Agent Development Kit
using PostgreSQL via psycopg3 with native async/await support.
Events are stored as a single JSONB blob (event_data) alongside
indexed scalar columns for efficient querying.
Provides
- Session state management with JSONB storage
- Full-fidelity event storage via
event_dataJSONB column - Atomic
append_event_and_update_statefor durable session mutations - Microsecond-precision timestamps with TIMESTAMPTZ
- Foreign key constraints with cascade delete
- GIN indexes for JSONB queries
- HOT updates with FILLFACTOR 80
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PsycopgAsyncConfig
|
PsycopgAsyncConfig with extension_config["adk"] settings. |
required |
PsycopgSyncADKMemoryStore
¶
PsycopgAsyncADKMemoryStore
¶
Bases: BaseAsyncADKMemoryStore['PsycopgAsyncConfig']
PostgreSQL ADK memory store using Psycopg3 async driver.
PsycopgSyncEventQueueStore
¶
Bases: BaseEventQueueStore[PsycopgSyncConfig]
Queue DDL for psycopg synchronous configs.
PostgreSQL uses JSONB for efficient binary JSON storage with indexing support, and TIMESTAMPTZ for timezone-aware timestamps.
PsycopgAsyncEventQueueStore
¶
Bases: BaseEventQueueStore[PsycopgAsyncConfig]
Queue DDL for psycopg async configs.
PostgreSQL uses JSONB for efficient binary JSON storage with indexing support, and TIMESTAMPTZ for timezone-aware timestamps.