Skip to content

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 (postgresql://user:pass@host:port/dbname).

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 5432).

user NotRequired[str]

PostgreSQL role name used for authentication.

password NotRequired[str]

Password or dynamic token for user.

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 ssl.SSLContext instance.

passfile NotRequired[str]

Path to a pgpass password file.

service NotRequired[str]

Service section name in pg_service.conf.

servicefile NotRequired[str]

Path to an alternate pg_service.conf file.

direct_tls NotRequired[bool]

Initiate TLS negotiation directly without PostgreSQL SSLRequest startup.

timeout NotRequired[float]

Connection establishment timeout in seconds (alias supported by asyncpg.connect).

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 (0 disables caching).

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 application_name or search_path).

target_session_attrs NotRequired[AsyncpgTargetSessionAttrs]

Required server session role when connecting to multi-host targets (such as read-write).

krbsrvname NotRequired[str]

Kerberos service principal name used for GSSAPI authentication.

gsslib NotRequired[AsyncpgGSSLib]

GSSAPI library backend (gssapi or sspi on Windows).

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 min_size are closed.

connect NotRequired[Callable[..., Awaitable[AsyncpgConnection]]]

Custom async callable invoked to establish raw asyncpg connections.

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 asyncio event loop passed to asyncpg.create_pool.

connection_class NotRequired[type[AsyncpgConnection]]

Custom asyncpg.Connection subclass instantiated by the pool.

record_class NotRequired[type[AsyncpgRecord]]

Custom asyncpg.Record subclass returned by raw queries.

extra NotRequired[dict[str, Any]]

Additional keyword arguments forwarded directly to asyncpg.create_pool.

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/jsonb codecs (defaults to to_json).

json_deserializer NotRequired[Callable[[str], Any]]

Custom JSON deserializer registered on json/jsonb codecs (defaults to from_json).

enable_json_codecs NotRequired[bool]

Automatically register json and jsonb codecs on new connections (defaults to True).

enable_pgvector NotRequired[bool]

Register pgvector binary codecs and promote the dialect when pgvector is installed.

enable_paradedb NotRequired[bool]

Detect pg_search and promote the SQL dialect to paradedb (defaults to True).

enable_pg_textsearch NotRequired[bool]

Detect pg_textsearch and promote the SQL dialect for BM25 <@> ranking (defaults to True).

enable_cloud_sql NotRequired[bool]

Route connections through cloud-sql-python-connector (mutually exclusive with enable_alloydb).

cloud_sql_instance NotRequired[str]

Cloud SQL instance connection string in project:region:instance format.

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 (PUBLIC, PRIVATE, or PSC; defaults to PRIVATE).

enable_alloydb NotRequired[bool]

Route connections through google-cloud-alloydb-connector (mutually exclusive with enable_cloud_sql).

alloydb_instance_uri NotRequired[str]

AlloyDB instance resource URI (projects/.../locations/.../clusters/.../instances/...).

enable_alloydb_iam_auth NotRequired[bool]

Use IAM database authentication with the AlloyDB Python Connector.

alloydb_ip_type NotRequired[str]

AlloyDB network path (PUBLIC, PRIVATE, or PSC; defaults to PRIVATE).

enable_alloydb_columnar NotRequired[bool]

Enable google_columnar_engine.enable_columnar_scan=on at session startup or per transaction.

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 True when events is configured).

events_backend NotRequired[Literal['notify', 'notify_queue', 'poll_queue']]

Event transport backend (notify for LISTEN/NOTIFY, notify_queue, or poll_queue).

on_connection_create NotRequired[Callable[[AsyncpgConnection], Awaitable[None]]]

Async hook invoked with each raw asyncpg connection after internal codec setup.

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 False).

pooler_mode NotRequired[Literal['session', 'transaction', 'statement', 'auto'] | None]

External pooler compatibility mode; sets statement_cache_size=0 in transaction or statement mode.

direct_dsn NotRequired[str | Mapping[str, Any] | None]

Direct PostgreSQL DSN or connection mapping bypassing the pooler for migrations and LISTEN/NOTIFY.

tenant_strategy NotRequired[AsyncTenantStrategy | TenantStrategyShorthand | None]

Opt-in tenant strategy, or the "rls" shorthand, applied to every session and connection lease.

tenant_session_baseline NotRequired[Mapping[str, str]]

Declared session settings replayed before each tenant checkout.

type_codecs NotRequired[list[dict[str, Any]]]

Custom asyncpg type codec specifications registered on connection initialization.

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

Bases: PostgresTenantSettings

Bind tenant identity and restore owned session settings in one query each.

__init__

__init__(
    *, tenant_key=DEFAULT_TENANT_KEY, variable_keys=None, schema_resolver=None
)

checkout

checkout(connection, payload)

Capture and apply identity before any application transaction.

checkin

checkin(connection, state)

Restore the baseline and verify it before the pool sees the connection.

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.

AsyncpgPool

AsyncpgPool = Pool[Record]

AsyncpgDataDictionary

Bases: AsyncDataDictionaryBase

PostgreSQL-specific async data dictionary.

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_data JSONB column
  • Atomic append_event_and_update_state for 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.