Skip to content

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

host NotRequired[str]

Database server hostname or Unix domain socket directory.

port NotRequired[int]

Database server TCP port (defaults to 5432).

user NotRequired[str]

PostgreSQL role name used for authentication.

password NotRequired[str]

Password or dynamic token for user.

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

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 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.enabled=on at session startup or per transaction.

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.

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

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

pgbouncer NotRequired[bool]

Alias for pooler_mode='transaction' disabling server-side prepared statements.

pgbouncer_mode NotRequired[bool]

Alias for pooler_mode='transaction' disabling server-side prepared statements.

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

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

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

Custom asyncpg type codec specifications registered on connection initialization.

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.

AsyncpgPool

AsyncpgPool = Pool[Record]

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_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 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.