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 |
user |
NotRequired[str]
|
CockroachDB SQL username. |
password |
NotRequired[str]
|
Password or JWT token for |
service |
NotRequired[str]
|
Service profile name in |
servicefile |
NotRequired[str]
|
Path to an alternate |
database |
NotRequired[str]
|
Target CockroachDB database name. |
ssl |
NotRequired[Any]
|
TLS mode string, boolean flag, or |
passfile |
NotRequired[str]
|
Path to a |
direct_tls |
NotRequired[bool]
|
Initiate TLS handshake directly without |
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 |
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 ( |
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 |
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 ( |
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 |
connect |
NotRequired[Callable[..., Awaitable[CockroachAsyncpgConnection]]]
|
Custom async connection factory passed to |
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 |
connection_class |
NotRequired[type[CockroachAsyncpgConnection]]
|
Custom |
record_class |
NotRequired[type[CockroachAsyncpgRecord]]
|
Custom |
extra |
NotRequired[dict[str, Any]]
|
Additional keyword arguments forwarded to |
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 |
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 |
native_storage_csv_options |
NotRequired[_NativeStorageCSVOptions]
|
Explicit CSV markers mapping supporting |
enable_auto_retry |
NotRequired[bool]
|
Automatically retry CockroachDB |
max_retries |
NotRequired[int]
|
Maximum retry attempts on |
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 |
default_staleness |
NotRequired[str]
|
Default |
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]
|
Register automatic |
enable_pgvector |
NotRequired[bool]
|
Register |
on_connection_create |
NotRequired[Callable[[CockroachAsyncpgConnection], Awaitable[None]]]
|
Async callback invoked with each raw |
reset_session_on_release |
NotRequired[bool]
|
Clear cursors, session authorization, and session settings when a connection is released (defaults to |
enable_events |
NotRequired[bool]
|
Enable durable queue-backed SQLSpec event channel support. |
events_backend |
NotRequired[Literal['poll_queue']]
|
Event channel backend ( |
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
¶
Driver, Pool & Data Dictionary¶
CockroachAsyncpgDriver
¶
Bases: AsyncpgDriver
CockroachDB AsyncPG driver with retry support.
run_transaction_with_retry
¶
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
¶
CockroachAsyncpgDataDictionary
¶
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
¶
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
¶
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.