asyncpg Adapter¶
from sqlspec.adapters.asyncpg import (
AsyncpgConfig,
AsyncpgConnectionConfig,
AsyncpgDriver,
AsyncpgDriverFeatures,
AsyncpgExceptionHandler,
AsyncpgPool,
AsyncpgPoolConfig,
)
Asynchronous PostgreSQL adapter built on asyncpg. Inherited execution methods are documented on AsyncDriverAdapterBase. See the PostgreSQL (asyncpg) Setup Guide for connection pooling, JSON codecs, and pgvector configuration.
Configuration & Parameters¶
AsyncpgConfig
¶
Bases: AsyncDatabaseConfig[AsyncpgConnection, 'Pool[Record]', AsyncpgDriver]
Configuration for AsyncPG database connections using TypedDict.
AsyncpgConnectionConfig
¶
Bases: TypedDict
TypedDict for AsyncPG connection parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
dsn |
NotRequired[str]
|
PostgreSQL connection URI ( |
host |
NotRequired[str]
|
Database server hostname or Unix domain 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 dynamic token for |
database |
NotRequired[str]
|
Target PostgreSQL database name. |
ssl |
NotRequired[Any]
|
TLS mode string, boolean flag, or |
passfile |
NotRequired[str]
|
Path to a |
service |
NotRequired[str]
|
Service section name in |
servicefile |
NotRequired[str]
|
Path to an alternate |
direct_tls |
NotRequired[bool]
|
Initiate TLS negotiation directly without PostgreSQL |
timeout |
NotRequired[float]
|
Connection establishment timeout in seconds (alias supported by |
connect_timeout |
NotRequired[float]
|
Pool connection establishment timeout in seconds. |
command_timeout |
NotRequired[float]
|
Default per-command execution timeout in seconds. |
statement_cache_size |
NotRequired[int]
|
Maximum number of server-side prepared statements cached per connection ( |
pgbouncer |
NotRequired[bool]
|
Disable prepared statement caching for transaction-pooling proxies such as PgBouncer. |
max_cached_statement_lifetime |
NotRequired[int]
|
Maximum age in seconds before cached prepared statements are evicted. |
max_cacheable_statement_size |
NotRequired[int]
|
Maximum SQL byte length eligible for prepared statement caching. |
server_settings |
NotRequired[dict[str, str]]
|
Startup PostgreSQL run-time GUC settings (such as |
target_session_attrs |
NotRequired[AsyncpgTargetSessionAttrs]
|
Required server session role when connecting to multi-host targets (such as |
krbsrvname |
NotRequired[str]
|
Kerberos service principal name used for GSSAPI authentication. |
gsslib |
NotRequired[AsyncpgGSSLib]
|
GSSAPI library backend ( |
AsyncpgPoolConfig
¶
Bases: AsyncpgConnectionConfig
TypedDict for AsyncPG pool parameters, inheriting connection parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
min_size |
NotRequired[int]
|
Minimum number of connections maintained in the pool. |
max_size |
NotRequired[int]
|
Maximum number of concurrent connections allowed in the pool. |
max_queries |
NotRequired[int]
|
Number of executed queries after which a pooled connection is closed and replaced. |
max_inactive_connection_lifetime |
NotRequired[float]
|
Idle duration in seconds before unused connections above |
connect |
NotRequired[Callable[..., Awaitable[AsyncpgConnection]]]
|
Custom async callable invoked to establish raw |
setup |
NotRequired[Callable[[AsyncpgConnection], Awaitable[None]]]
|
Async callback invoked before each connection acquisition from the pool. |
init |
NotRequired[Callable[[AsyncpgConnection], Awaitable[None]]]
|
Async callback invoked once when a new physical connection is created. |
reset |
NotRequired[Callable[[AsyncpgConnection], Awaitable[None]]]
|
Async callback invoked when a connection is released back to the pool. |
loop |
NotRequired[AbstractEventLoop]
|
Explicit |
connection_class |
NotRequired[type[AsyncpgConnection]]
|
Custom |
record_class |
NotRequired[type[AsyncpgRecord]]
|
Custom |
extra |
NotRequired[dict[str, Any]]
|
Additional keyword arguments forwarded directly to |
AsyncpgDriverFeatures
¶
Bases: TypedDict
Optional driver feature flags, codecs, cloud connectors, and pooler settings for AsyncPG.
Attributes:
| Name | Type | Description |
|---|---|---|
json_serializer |
NotRequired[Callable[[Any], str]]
|
Custom JSON serializer registered on |
json_deserializer |
NotRequired[Callable[[str], Any]]
|
Custom JSON deserializer registered on |
enable_json_codecs |
NotRequired[bool]
|
Automatically register |
enable_pgvector |
NotRequired[bool]
|
Register |
enable_paradedb |
NotRequired[bool]
|
Detect |
enable_pg_textsearch |
NotRequired[bool]
|
Detect |
enable_cloud_sql |
NotRequired[bool]
|
Route connections through |
cloud_sql_instance |
NotRequired[str]
|
Cloud SQL instance connection string in |
cloud_sql_enable_iam_auth |
NotRequired[bool]
|
Use IAM database authentication with the Cloud SQL Python Connector. |
cloud_sql_ip_type |
NotRequired[str]
|
Cloud SQL network path ( |
enable_alloydb |
NotRequired[bool]
|
Route 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 |
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 ( |
on_connection_create |
NotRequired[Callable[[AsyncpgConnection], Awaitable[None]]]
|
Async hook invoked with each raw |
pooler_mode |
NotRequired[Literal['session', 'transaction', 'statement', 'auto'] | None]
|
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 |
type_codecs |
NotRequired[list[dict[str, Any]]]
|
Custom |
Driver & Pool¶
AsyncpgDriver
¶
Bases: AsyncDriverAdapterBase
AsyncPG PostgreSQL driver for async database operations.
Supports COPY operations, numeric parameter style handling, PostgreSQL exception handling, transaction management, SQL statement compilation and caching, and parameter processing with type coercion.
AsyncpgExceptionHandler
¶
Bases: BaseAsyncExceptionHandler
Async context manager for handling AsyncPG database exceptions.
Maps PostgreSQL SQLSTATE error codes to SQLSpec exceptions stored on
pending_exception.
Extension Stores¶
AsyncpgStore
¶
Bases: BaseSQLSpecStore['AsyncpgConfig']
PostgreSQL session store using AsyncPG driver.
Implements server-side session storage for Litestar using PostgreSQL via the AsyncPG 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
|
AsyncpgConfig
|
AsyncpgConfig instance with extension_config["litestar"] settings. |
required |
AsyncpgADKStore
¶
Bases: BaseAsyncADKStore[AsyncConfigT]
PostgreSQL ADK store using asyncpg driver.
Implements session and event storage for Google Agent Development Kit
using PostgreSQL via asyncpg. 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
- Optional owner ID column for multi-tenancy
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AsyncConfigT
|
PostgreSQL database config with extension_config["adk"] settings. |
required |
AsyncpgADKMemoryStore
¶
Bases: BaseAsyncADKMemoryStore['AsyncpgConfig']
PostgreSQL ADK memory store using asyncpg driver.
Implements memory entry storage for Google Agent Development Kit using PostgreSQL via the asyncpg driver. Provides: - Session memory storage with JSONB for content and metadata - Full-text search using to_tsvector/to_tsquery (postgres_fts strategy) - Simple ILIKE search fallback (simple strategy) - TIMESTAMPTZ for precise timestamp storage - Deduplication via event_id unique constraint - Efficient upserts using ON CONFLICT DO NOTHING
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AsyncpgConfig
|
AsyncpgConfig with extension_config["adk"] settings. |
required |
AsyncpgEventQueueStore
¶
Bases: BaseEventQueueStore[AsyncpgConfig]
PostgreSQL event queue store with JSONB columns.
Uses PostgreSQL-native JSONB for efficient JSON storage and querying. TIMESTAMPTZ ensures proper timezone handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigT
|
AsyncpgConfig with extension_config["events"] settings. |
required |
AsyncpgEventsBackend
¶
Native LISTEN/NOTIFY backend backed by a persistent listener hub.