asyncpg Adapter¶
from sqlspec.adapters.asyncpg import (
AsyncpgConfig,
AsyncpgConnectionConfig,
AsyncpgDriver,
AsyncpgDriverFeatures,
AsyncpgExceptionHandler,
AsyncpgPool,
AsyncpgPoolConfig,
AsyncpgRLSStrategy,
)
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, and the PostgreSQL Data Dictionary & SQL Catalog.
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 | Sequence[str]]
|
Database hostname, socket directory, or sequence of failover hosts. |
port |
NotRequired[int | Sequence[int]]
|
Server port or sequence of ports matching the hosts (defaults to |
user |
NotRequired[str]
|
PostgreSQL role name used for authentication. |
password |
NotRequired[str]
|
Password or dynamic token for |
auth_token_provider |
NotRequired[Callable[[], str] | Callable[[], Awaitable[str]]]
|
Callable or async callable returning a fresh password or IAM token for each new connection. |
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 ( |
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_pgcopy_binary |
NotRequired[bool]
|
Enable binary COPY format for Arrow table ingestion. |
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 |
reset_session_on_release |
NotRequired[bool]
|
Clear cursors, session authorization, settings, listeners, session-level locks, plans, temp objects, and sequences when a connection is released (defaults to |
pooler_mode |
NotRequired[Literal['session', 'transaction', 'statement', 'auto'] | None]
|
External pooler compatibility mode; sets |
direct_dsn |
NotRequired[str | Mapping[str, Any] | None]
|
Direct PostgreSQL DSN or connection mapping bypassing the pooler for migrations and |
tenant_strategy |
NotRequired[AsyncTenantStrategy | TenantStrategyShorthand | None]
|
Opt-in tenant strategy, or the |
tenant_session_baseline |
NotRequired[Mapping[str, str]]
|
Declared session settings replayed before each tenant checkout. |
type_codecs |
NotRequired[list[dict[str, Any]]]
|
Custom |
Tenant Strategies¶
Set driver_features={"tenant_strategy": "rls"} to protect both provide_session() and provide_connection(). "default" and True select the same strategy. Missing scope raises TenantContextError before acquisition; failed cleanup invalidates the connection and raises TenantCleanupError when no body exception is pending.
Tenant mode defaults pooler_mode to "session" and rejects transaction, statement, and auto modes. Prefer passing static session parameters via connection_config={"server_settings": ...} so PostgreSQL sets them once on startup and preserves them across RESET ALL. Reserve tenant_session_baseline for settings altered inside raw asyncpg init or setup pool hooks (on_connection_create defaults tenant_session_baseline to {} automatically when omitted, whereas raw init and setup hooks require an explicit tenant_session_baseline declaration). Capturing and applying tenant settings uses one query; restoring and verifying them uses one query. Baseline replay and pool reset are separate operations.
See Multi-Tenancy for database policy setup and Tenant Operations for workers and cleanup.
AsyncpgRLSStrategy
¶
Driver, Pool & Data Dictionary¶
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.
AsyncpgDataDictionary
¶
Extension Stores & Configs¶
AsyncpgLitestarConfig
¶
Bases: LitestarConfig
Asyncpg-specific Litestar settings.
Use inside extension_config["litestar"] with this adapter's session store.
Attributes:
| Name | Type | Description |
|---|---|---|
fillfactor |
NotRequired[int]
|
Table fillfactor. Default: 80. |
autovacuum_vacuum_scale_factor |
NotRequired[float]
|
Table autovacuum vacuum scale factor. |
autovacuum_analyze_scale_factor |
NotRequired[float]
|
Table autovacuum analyze scale factor. |
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 |
AsyncpgADKConfig
¶
Bases: ADKConfig
Asyncpg-specific ADK extension settings.
Use these keys inside extension_config["adk"] with the asyncpg ADK store.
Attributes:
| Name | Type | Description |
|---|---|---|
enable_event_generated_columns |
NotRequired[bool]
|
Create PostgreSQL generated columns and indexes for common ADK event JSON paths. |
enable_covering_indexes |
NotRequired[bool]
|
Add PostgreSQL INCLUDE columns to ADK event replay indexes. |
fillfactor |
NotRequired[int]
|
Table fillfactor. Defaults to 80. |
autovacuum_vacuum_scale_factor |
NotRequired[float]
|
Optional event-table autovacuum vacuum scale factor. |
autovacuum_analyze_scale_factor |
NotRequired[float]
|
Optional event-table autovacuum analyze scale factor. |
vector_index_type |
NotRequired[Literal['hnsw', 'ivfflat', 'scann']]
|
Vector index algorithm for memory embeddings ('hnsw', 'ivfflat', 'scann'). Default: 'hnsw'. |
vector_dimensions |
NotRequired[int]
|
Dimensionality of embedding vectors (e.g. 768 for gemini-embedding-001 with MRL). Default: 768. |
enable_bm25 |
NotRequired[bool]
|
Enable native BM25 full-text indexing. Requires the pg_textsearch extension. Default: False. |
scann_num_leaves |
NotRequired[int]
|
Number of partition leaves (clusters) for ScaNN tree quantization. Default: 100. |
scann_quantizer |
NotRequired[str]
|
Quantization method for ScaNN index ('SQ8', 'FP32'). Default: 'SQ8'. |
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 (app_name, user_id, 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 |
AsyncpgEventsConfig
¶
Bases: EventsConfig
Asyncpg events settings for queue storage and supported native transports.
Attributes:
| Name | Type | Description |
|---|---|---|
fillfactor |
NotRequired[int]
|
PostgreSQL queue-table fillfactor; omitted to use the server default. |
autovacuum_vacuum_scale_factor |
NotRequired[float]
|
PostgreSQL queue vacuum threshold fraction; omitted to use the server default. |
autovacuum_analyze_scale_factor |
NotRequired[float]
|
PostgreSQL queue analyze threshold fraction; omitted to use the server default. |
listener_queue_capacity |
NotRequired[int]
|
Maximum buffered notifications per native listener; omitted for an unbounded queue. |
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.