Skip to content

cockroach-psycopg Adapter

from sqlspec.adapters.cockroach_psycopg import (
    CockroachPsycopgAsyncConfig,
    CockroachPsycopgAsyncDriver,
    CockroachPsycopgAsyncExceptionHandler,
    CockroachPsycopgConnectionConfig,
    CockroachPsycopgDriverFeatures,
    CockroachPsycopgPoolConfig,
    CockroachPsycopgRetryConfig,
    CockroachPsycopgSyncConfig,
    CockroachPsycopgSyncDriver,
    CockroachPsycopgSyncExceptionHandler,
    CockroachPsycopgSyncRLSStrategy,
    CockroachPsycopgAsyncRLSStrategy,
)

Synchronous and asynchronous CockroachDB adapters built on psycopg v3 with SQLSTATE 40001 retry policies and follower-read support. Inherited execution methods are documented on SyncDriverAdapterBase and AsyncDriverAdapterBase. See the CockroachDB Setup Guide for usage examples and the CockroachDB Data Dictionary & SQL Catalog.

Configuration & Parameters

CockroachPsycopgSyncConfig

Bases: SyncDatabaseConfig[CockroachSyncConnection, CockroachPsycopgConnectionPool, CockroachPsycopgSyncDriver]

Configuration for CockroachDB synchronous connections using psycopg.

CockroachPsycopgAsyncConfig

Bases: AsyncDatabaseConfig[CockroachAsyncConnection, CockroachPsycopgAsyncConnectionPool, CockroachPsycopgAsyncDriver]

Configuration for CockroachDB async connections using psycopg.

CockroachPsycopgConnectionConfig

Bases: TypedDict

CockroachDB connection parameters.

Attributes:

Name Type Description
conninfo NotRequired[str]

CockroachDB libpq connection URI or keyword/value conninfo string.

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.

dbname NotRequired[str]

Target CockroachDB database name.

connect_timeout NotRequired[int]

Connection establishment timeout in seconds.

options NotRequired[str]

Command-line startup session options sent to CockroachDB.

default_transaction_use_follower_reads NotRequired[bool]

Enable bounded-staleness follower reads for read-only transactions.

results_buffer_size NotRequired[int]

CockroachDB server result streaming buffer size in bytes.

statement_timeout NotRequired[int]

Per-statement execution timeout in milliseconds.

idle_in_transaction_session_timeout NotRequired[int]

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

application_name NotRequired[str]

Application identifier visible in CockroachDB session diagnostics.

sslmode NotRequired[str]

libpq TLS verification mode (such as require or verify-full).

sslcert NotRequired[str]

Path to the client TLS certificate file.

sslkey NotRequired[str]

Path to the client TLS private key file.

sslrootcert NotRequired[str]

Path to the root CA certificate bundle.

autocommit NotRequired[bool]

Enable Psycopg autocommit mode outside explicit transactions.

prepare_threshold NotRequired[int | None]

Executions before Psycopg prepares a statement server-side, or None to disable.

row_factory NotRequired[Callable[..., Any]]

Custom Psycopg row factory applied to raw connections.

cursor_factory NotRequired[type[Any]]

Custom Psycopg cursor class used by raw connections.

context NotRequired[Any]

Psycopg AdaptContext providing custom type adapters.

cluster NotRequired[str]

CockroachDB Serverless / Cloud routing cluster identifier.

extra NotRequired[dict[str, Any]]

Additional libpq keyword parameters merged into connect.

CockroachPsycopgPoolConfig

Bases: CockroachPsycopgConnectionConfig

CockroachDB pool parameters.

Attributes:

Name Type Description
min_size NotRequired[int]

Minimum number of connections maintained in ConnectionPool / AsyncConnectionPool.

max_size NotRequired[int]

Maximum number of connections allowed in the pool.

name NotRequired[str]

Diagnostic pool name used in logs and worker threads.

timeout NotRequired[float]

Maximum wait time in seconds when acquiring a connection from the pool.

max_waiting NotRequired[int]

Maximum queued callers waiting for an available connection (0 means unlimited).

max_lifetime NotRequired[float]

Maximum lifetime in seconds before a pooled connection is recycled.

max_idle NotRequired[float]

Maximum idle time in seconds before shrinking connections above min_size.

reconnect_timeout NotRequired[float]

Duration in seconds the pool retries failed connection attempts before invoking reconnect_failed.

reconnect_failed NotRequired[Callable[..., Any]]

Callback invoked when pool reconnection attempts exceed reconnect_timeout.

num_workers NotRequired[int]

Number of background maintenance worker threads/tasks managed by the pool.

configure NotRequired[Callable[..., Any]]

Callback invoked once on each newly created connection before entering the pool.

check NotRequired[Callable[..., Any]]

Health-check callback invoked before handing out a pooled connection.

reset NotRequired[Callable[..., Any]]

Callback invoked to clean connection state when returned to the pool.

open NotRequired[bool | None]

Whether to open the pool immediately during construction.

close_returns NotRequired[bool]

Make conn.close() return the connection to the pool instead of closing the socket.

kwargs NotRequired[dict[str, Any]]

Explicit connection keyword dictionary passed to psycopg.connect.

CockroachPsycopgDriverFeatures

Bases: TypedDict

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

Attributes:

Name Type Description
tenant_strategy NotRequired[SyncTenantStrategy | AsyncTenantStrategy | TenantStrategyShorthand | None]

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

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 applied to statement parameters (defaults to to_json).

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

Custom JSON deserializer retained alongside json_serializer (defaults to from_json).

on_connection_create NotRequired[Callable[..., Any]]

Sync or async callback invoked with each raw Psycopg connection after internal setup.

reset_session_on_release NotRequired[bool]

Run DISCARD ALL on each connection before it returns to the pool (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).

CockroachPsycopgRetryConfig

CockroachDB psycopg transaction retry configuration.

Tenant Strategies

Set driver_features={"tenant_strategy": "rls"}; "default" and True select the mode-specific CockroachDB strategy. Omitted or None pooler mode becomes "session"; transaction, statement, and auto modes are rejected. close_returns=True is rejected because invalidation must physically close a connection.

Both providers run tenant leases. Capture/apply and restore/verify each use one management query, with transaction completion as a separate operation. Unset owned keys restore to an empty string; NULL does not reset them. Existing retry and follower-read behavior remains available. Cleanup failure physically closes the connection. Tenant leases keep the native commit behavior: a clean exit commits and an exception rolls back.

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.

CockroachPsycopgSyncRLSStrategy

Bases: PostgresTenantSettings

Apply and restore synchronous CockroachDB session settings.

__init__

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

checkout

checkout(connection, payload)

Apply identity and finish only the management transaction.

checkin

checkin(connection, state)

Restore owned settings after the lease has finished application work.

CockroachPsycopgAsyncRLSStrategy

Bases: PostgresTenantSettings

Apply and restore asynchronous CockroachDB session settings.

__init__

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

checkout

checkout(connection, payload)

Apply identity and finish only the management transaction.

checkin

checkin(connection, state)

Restore owned settings after the lease has finished application work.

Driver, Pool & Data Dictionary

CockroachPsycopgSyncDriver

Bases: PsycopgSyncDriver

CockroachDB sync driver using psycopg.crdb.

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.

CockroachPsycopgAsyncDriver

Bases: PsycopgAsyncDriver

CockroachDB async driver using psycopg.crdb.

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.

CockroachPsycopgSyncExceptionHandler

Bases: PsycopgSyncExceptionHandler

Context manager for handling CockroachDB psycopg exceptions.

CockroachPsycopgAsyncExceptionHandler

Bases: PsycopgAsyncExceptionHandler

Async context manager for handling CockroachDB psycopg exceptions.

CockroachPsycopgSyncDataDictionary

Bases: SyncDataDictionaryBase

CockroachDB sync data dictionary.

CockroachPsycopgAsyncDataDictionary

Bases: AsyncDataDictionaryBase

CockroachDB async data dictionary.

Extension Stores & Configs

CockroachPsycopgLitestarConfig

Bases: LitestarConfig

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

CockroachPsycopgSyncStore

Bases: BaseSQLSpecStore['CockroachPsycopgSyncConfig']

CockroachDB session store using psycopg sync driver.

CockroachPsycopgAsyncStore

Bases: BaseSQLSpecStore['CockroachPsycopgAsyncConfig']

CockroachDB session store using psycopg async driver.

CockroachPsycopgADKConfig

Bases: ADKConfig

CockroachDB psycopg ADK extension settings.

Use these keys inside extension_config["adk"] with the CockroachDB psycopg 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.

CockroachPsycopgSyncADKStore

Bases: BaseSyncADKStore['CockroachPsycopgSyncConfig']

CockroachDB ADK store using psycopg sync driver.

CockroachPsycopgAsyncADKStore

Bases: BaseAsyncADKStore['CockroachPsycopgAsyncConfig']

CockroachDB ADK store using psycopg async driver.

CockroachPsycopgSyncADKMemoryStore

Bases: BaseSyncADKMemoryStore['CockroachPsycopgSyncConfig']

CockroachDB ADK memory store using psycopg sync driver.

CockroachPsycopgAsyncADKMemoryStore

Bases: BaseAsyncADKMemoryStore['CockroachPsycopgAsyncConfig']

CockroachDB ADK memory store using psycopg async driver.

CockroachPsycopgSyncEventQueueStore

Bases: BaseEventQueueStore[CockroachPsycopgSyncConfig]

Queue DDL for CockroachDB psycopg synchronous configs.

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

CockroachPsycopgAsyncEventQueueStore

Bases: BaseEventQueueStore[CockroachPsycopgAsyncConfig]

Queue DDL for CockroachDB psycopg async configs.

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