Skip to content

cockroach-asyncpg Adapter

from sqlspec.adapters.cockroach_asyncpg import (
    CockroachAsyncpgConfig,
    CockroachAsyncpgConnectionConfig,
    CockroachAsyncpgDriver,
    CockroachAsyncpgDriverFeatures,
    CockroachAsyncpgExceptionHandler,
    CockroachAsyncpgPool,
    CockroachAsyncpgPoolConfig,
    CockroachAsyncpgRetryConfig,
    CockroachAsyncpgRLSStrategy,
)

Asynchronous CockroachDB adapter built on asyncpg with SQLSTATE 40001 serialization retry handling and follower-read support. Inherited execution methods are documented on AsyncDriverAdapterBase. See the CockroachDB Setup Guide for cluster topology and retry configuration, and the CockroachDB Data Dictionary & SQL Catalog.

Configuration & Parameters

CockroachAsyncpgConfig

Bases: AsyncDatabaseConfig[CockroachAsyncpgConnection, CockroachAsyncpgPool, CockroachAsyncpgDriver]

Configuration for CockroachDB using AsyncPG.

CockroachAsyncpgConnectionConfig

Bases: TypedDict

AsyncPG connection parameters for CockroachDB.

Attributes:

Name Type Description
dsn NotRequired[str]

CockroachDB PostgreSQL-compatible connection URI.

host NotRequired[str]

CockroachDB node or load-balancer hostname.

port NotRequired[int]

CockroachDB SQL TCP port (defaults to 26257).

user NotRequired[str]

CockroachDB SQL username.

password NotRequired[str]

Password or JWT token for user.

service NotRequired[str]

Service profile name in pg_service.conf.

servicefile NotRequired[str]

Path to an alternate pg_service.conf file.

database NotRequired[str]

Target CockroachDB database name.

ssl NotRequired[Any]

TLS mode string, boolean flag, or ssl.SSLContext instance.

passfile NotRequired[str]

Path to a pgpass password file.

direct_tls NotRequired[bool]

Initiate TLS handshake directly without SSLRequest negotiation.

timeout NotRequired[float]

Connection establishment timeout in seconds.

connect_timeout NotRequired[float]

Pool connection establishment timeout in seconds.

command_timeout NotRequired[float]

Default per-command timeout in seconds.

application_name NotRequired[str]

Application identifier forwarded via server_settings.

cluster NotRequired[str]

CockroachDB Serverless / Cloud routing cluster identifier.

default_transaction_use_follower_reads NotRequired[bool]

Session setting enabling bounded-staleness follower reads on read-only transactions.

results_buffer_size NotRequired[int]

CockroachDB server result streaming buffer size in bytes.

statement_cache_size NotRequired[int]

Maximum 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 CockroachDB session variables passed at connection time.

target_session_attrs NotRequired[CockroachAsyncpgTargetSessionAttrs]

Required node session attribute when connecting across multiple hosts.

statement_timeout NotRequired[int]

Per-statement execution timeout in milliseconds forwarded via server_settings.

idle_in_transaction_session_timeout NotRequired[int]

Idle-in-transaction timeout in milliseconds before aborting open transactions.

krbsrvname NotRequired[str]

Kerberos service principal name for GSSAPI authentication.

gsslib NotRequired[CockroachAsyncpgGSSLib]

GSSAPI library implementation (gssapi or sspi).

CockroachAsyncpgPoolConfig

Bases: CockroachAsyncpgConnectionConfig

AsyncPG pool parameters for CockroachDB.

Attributes:

Name Type Description
min_size NotRequired[int]

Minimum number of open connections maintained in the pool.

max_size NotRequired[int]

Maximum number of concurrent connections allowed in the pool.

max_queries NotRequired[int]

Number of queries after which a pooled connection is recycled.

max_inactive_connection_lifetime NotRequired[float]

Idle timeout in seconds before closing unused connections above min_size.

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

Custom async connection factory passed to asyncpg.create_pool.

setup NotRequired[Callable[[CockroachAsyncpgConnection], Awaitable[None]]]

Async hook run before each connection checkout from the pool.

init NotRequired[Callable[[CockroachAsyncpgConnection], Awaitable[None]]]

Async hook run once when a new physical connection is opened.

reset NotRequired[Callable[[CockroachAsyncpgConnection], Awaitable[None]]]

Async hook run when returning a connection to the pool.

loop NotRequired[AbstractEventLoop]

Explicit asyncio event loop for pool tasks.

connection_class NotRequired[type[CockroachAsyncpgConnection]]

Custom asyncpg.Connection subclass used by the pool.

record_class NotRequired[type[CockroachAsyncpgRecord]]

Custom asyncpg.Record subclass returned by raw queries.

extra NotRequired[dict[str, Any]]

Additional keyword arguments forwarded to asyncpg.create_pool.

CockroachAsyncpgDriverFeatures

Bases: TypedDict

Driver feature flags for CockroachDB retries, follower reads, codecs, and native storage.

Attributes:

Name Type Description
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.

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

Tenant connections require session affinity.

enable_native_storage NotRequired[bool]

Opt in to server-side CockroachDB EXPORT and IMPORT INTO storage operations.

native_storage_csv_options NotRequired[_NativeStorageCSVOptions]

Explicit CSV markers mapping supporting nullas (export NULL string), nullif (import NULL string), and skip (header line count to skip on import).

enable_auto_retry NotRequired[bool]

Automatically retry CockroachDB 40001 serialization failure transactions with backoff.

max_retries NotRequired[int]

Maximum retry attempts on 40001 transaction serialization conflicts.

retry_delay_base_ms NotRequired[float]

Initial exponential backoff delay in milliseconds between serialization retries.

retry_delay_max_ms NotRequired[float]

Upper bound in milliseconds on exponential backoff delay between retries.

enable_retry_logging NotRequired[bool]

Emit structured debug/warning logs when serialization retries occur.

enable_follower_reads NotRequired[bool]

Allow AS OF SYSTEM TIME follower-read clauses on read queries.

default_staleness NotRequired[str]

Default AS OF SYSTEM TIME staleness expression (such as '-5s' or follower_read_timestamp()).

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]

Register automatic json and jsonb codecs on new connections (defaults to True).

enable_pgvector NotRequired[bool]

Register pgvector codecs for CockroachDB VECTOR columns when pgvector is installed.

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

Async callback invoked with each raw asyncpg connection after codec initialization.

reset_session_on_release NotRequired[bool]

Clear cursors, session authorization, and session settings when a connection is released (defaults to False).

enable_events NotRequired[bool]

Enable durable queue-backed SQLSpec event channel support.

events_backend NotRequired[Literal['poll_queue']]

Event channel backend (poll_queue for CockroachDB table-backed polling).

CockroachAsyncpgRetryConfig

CockroachDB asyncpg transaction retry configuration.

Tenant Strategies

Set driver_features={"tenant_strategy": "rls"}; "default" and True select the CockroachDB strategy. Omitted or None pooler mode becomes "session"; transaction, statement, and auto modes are rejected. Both providers acquire through the tenant lease. Dirty connections are terminated and released to native pool bookkeeping only after physical disposal.

Declare settings that raw asyncpg init or setup pool hooks change in tenant_session_baseline; the lease replays them after the native pool reset. Those hooks require an explicit declaration ({} when they leave no lasting settings), and a baseline value must agree with server_settings.

One management query captures/applies owned GUCs; another restores/verifies them. Unset owned keys restore to an empty string because NULL does not reset a CockroachDB setting. Cleanup uses no blanket RESET ALL. Existing retry and follower-read behavior remains available; database policies must enforce tenant access.

Missing tenant identity raises TenantContextError before acquisition. Failed cleanup raises TenantCleanupError when no body exception is pending; otherwise the body error keeps its identity and receives a cleanup note. See Multi-Tenancy and Tenant Operations.

CockroachAsyncpgRLSStrategy

Bases: PostgresTenantSettings

Apply and restore tenant session settings on CockroachDB asyncpg connections.

__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

CockroachAsyncpgDriver

Bases: AsyncpgDriver

CockroachDB AsyncPG driver with retry support.

run_transaction_with_retry

run_transaction_with_retry(operation)

Execute a full CockroachDB transaction callback with serialization retries.

A rollback that itself fails leaves the transaction aborted, and every statement on it would then fail with a non-retryable error that hides the real conflict. The original exception is raised instead of retrying, so the rollback failure never replaces the transaction's outcome.

CockroachAsyncpgExceptionHandler

Bases: AsyncpgExceptionHandler

Async context manager for CockroachDB AsyncPG exceptions.

CockroachAsyncpgPool

CockroachAsyncpgPool = Pool[Record]

CockroachAsyncpgDataDictionary

Bases: AsyncpgDataDictionary

CockroachDB async data dictionary (AsyncPG).

Extension Stores & Configs

CockroachAsyncpgLitestarConfig

Bases: LitestarConfig

CockroachAsyncpg-specific Litestar settings.

Use inside extension_config["litestar"] with this adapter's session store.

Attributes:

Name Type Description
enable_hash_sharded_indexes NotRequired[bool]

Enable hash-sharded session indexes.

hash_shard_bucket_count NotRequired[int]

Number of hash index buckets.

ttl_expiration_expression NotRequired[Literal[False, 'expires_at']]

Enable row-level TTL using expires_at, or disable it with False.

CockroachAsyncpgStore

Bases: BaseSQLSpecStore['CockroachAsyncpgConfig']

CockroachDB session store using asyncpg driver.

CockroachAsyncpgADKConfig

Bases: ADKConfig

CockroachDB asyncpg ADK extension settings.

Use these keys inside extension_config["adk"] with the CockroachDB asyncpg ADK stores.

Attributes:

Name Type Description
table_locality NotRequired[str]

Default raw CockroachDB LOCALITY clause for ADK tables.

session_table_locality NotRequired[str]

Raw CockroachDB LOCALITY clause for the ADK session table.

events_table_locality NotRequired[str]

Raw CockroachDB LOCALITY clause for the ADK events table.

app_state_table_locality NotRequired[str]

Raw CockroachDB LOCALITY clause for the ADK app state table.

user_state_table_locality NotRequired[str]

Raw CockroachDB LOCALITY clause for the ADK user state table.

metadata_table_locality NotRequired[str]

Raw CockroachDB LOCALITY clause for the ADK metadata table.

memory_table_locality NotRequired[str]

Raw CockroachDB LOCALITY clause for the ADK memory table.

enable_hash_sharded_indexes NotRequired[bool]

Create CockroachDB hash-sharded secondary indexes on hot timestamp access paths.

hash_shard_bucket_count NotRequired[int]

Optional bucket count for CockroachDB hash-sharded secondary indexes.

enable_storing_indexes NotRequired[bool]

Add CockroachDB STORING columns to common ADK replay/session indexes.

enable_memory_trigram_index NotRequired[bool]

Create a CockroachDB trigram GIN index for simple ILIKE memory search.

CockroachAsyncpgADKStore

Bases: BaseAsyncADKStore['CockroachAsyncpgConfig']

CockroachDB ADK store using asyncpg driver.

CockroachAsyncpgADKMemoryStore

Bases: BaseAsyncADKMemoryStore['CockroachAsyncpgConfig']

CockroachDB ADK memory store using asyncpg driver.

CockroachAsyncpgEventQueueStore

Bases: BaseEventQueueStore[CockroachAsyncpgConfig]

Queue DDL for CockroachDB asyncpg configs.

CockroachDB uses JSONB for efficient JSON storage and TIMESTAMPTZ for timezone-aware timestamps.