Skip to content

psqlpy Adapter

from sqlspec.adapters.psqlpy import (
    PsqlpyConfig,
    PsqlpyConnectionParams,
    PsqlpyDriver,
    PsqlpyDriverFeatures,
    PsqlpyExceptionHandler,
    PsqlpyPoolParams,
    PsqlpyRLSStrategy,
)

Rust-backed asynchronous PostgreSQL adapter built on psqlpy. Inherited execution methods are documented on AsyncDriverAdapterBase. See the PostgreSQL (psqlpy) Setup Guide for usage examples and the PostgreSQL Data Dictionary & SQL Catalog.

Configuration & Parameters

PsqlpyConfig

Bases: AsyncDatabaseConfig[PsqlpyConnection, 'ConnectionPool', PsqlpyDriver]

Configuration for Psqlpy asynchronous database connections.

PsqlpyConnectionParams

Bases: TypedDict

Psqlpy connection parameters.

Attributes:

Name Type Description
dsn NotRequired[str]

PostgreSQL connection URI (postgresql://user:pass@host:port/db).

username NotRequired[str]

PostgreSQL role name used for authentication.

password NotRequired[str]

Password for username.

auth_token_provider NotRequired[Callable[[], str] | Callable[[], Awaitable[str]]]

Callable or async callable returning a fresh password or IAM token when creating connections.

db_name NotRequired[str]

Target PostgreSQL database name.

host NotRequired[str]

Database server hostname or IP address.

port NotRequired[int]

Database server TCP port (defaults to 5432).

connect_timeout_sec NotRequired[int]

Whole-second component of the TCP connection establishment timeout.

connect_timeout_nanosec NotRequired[int]

Sub-second nanosecond component of the connection establishment timeout.

tcp_user_timeout_sec NotRequired[int]

Whole-second TCP unacknowledged transmission timeout.

tcp_user_timeout_nanosec NotRequired[int]

Sub-second nanosecond component of the TCP user timeout.

keepalives NotRequired[bool]

Enable TCP keepalive probes on client sockets.

keepalives_idle_sec NotRequired[int]

Idle duration in seconds before sending the first TCP keepalive probe.

keepalives_idle_nanosec NotRequired[int]

Nanosecond component of the TCP keepalive idle interval.

keepalives_interval_sec NotRequired[int]

Interval in seconds between consecutive unacknowledged TCP keepalive probes.

keepalives_interval_nanosec NotRequired[int]

Nanosecond component of the TCP keepalive probe interval.

keepalives_retries NotRequired[int]

Maximum unacknowledged TCP keepalive probes before dropping the connection.

ssl_mode NotRequired[str]

TLS negotiation policy (disable, prefer, require, verify-ca, or verify-full).

ca_file NotRequired[str]

Path to a PEM root CA bundle used to verify server certificates.

target_session_attrs NotRequired[Literal['any', 'read-write', 'read-only', 'primary', 'standby', 'prefer-standby'] | TargetSessionAttrs]

Required server session state for multi-host routing (such as read-write).

options NotRequired[str]

Command-line startup GUC options sent to the PostgreSQL backend.

application_name NotRequired[str]

Application identifier reported in pg_stat_activity.

client_encoding NotRequired[str]

Client character set encoding (defaults to UTF8).

gssencmode NotRequired[str]

GSSAPI transport encryption mode (disable, prefer, or require).

sslnegotiation NotRequired[str]

PostgreSQL 17+ TLS handshake mode (postgres or direct).

sslcompression NotRequired[str]

TLS compression setting forwarded to libpq/Rust TLS configuration.

sslcert NotRequired[str]

Path to the client TLS certificate file.

sslkey NotRequired[str]

Path to the client TLS private key file.

sslpassword NotRequired[str]

Passphrase unlocking an encrypted sslkey.

sslrootcert NotRequired[str]

Path to the trusted root certificate authority file.

sslcrl NotRequired[str]

Path to the certificate revocation list file.

require_auth NotRequired[str]

Comma-separated list of acceptable server authentication methods.

channel_binding NotRequired[str]

SCRAM channel binding requirement (disable, prefer, or require).

krbsrvname NotRequired[str]

Kerberos service principal name for GSSAPI authentication.

gsslib NotRequired[str]

GSSAPI library implementation selector.

gssdelegation NotRequired[str]

Whether to delegate GSSAPI credentials to the PostgreSQL server.

service NotRequired[str]

Service profile name defined in pg_service.conf.

load_balance_hosts NotRequired[Literal['disable', 'random'] | LoadBalanceHosts]

Host ordering policy across multi-host configurations (disable or random).

PsqlpyPoolParams

Bases: PsqlpyConnectionParams

Psqlpy pool parameters.

Attributes:

Name Type Description
hosts NotRequired[list[str]]

Ordered list of PostgreSQL hostnames for multi-host failover or load balancing.

ports NotRequired[list[int]]

Port numbers corresponding to hosts.

conn_recycling_method NotRequired[str]

Pool connection reset strategy (such as fast or verified).

max_db_pool_size NotRequired[int]

Maximum number of concurrent connections held by psqlpy.ConnectionPool.

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

Optional pool connection configuration callback.

extra NotRequired[dict[str, Any]]

Additional keyword options passed directly to psqlpy.ConnectionPool.

PsqlpyDriverFeatures

Bases: TypedDict

Optional driver feature flags, extension detection, and pooler settings for Psqlpy.

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.

enable_cast_detection NotRequired[bool]

Use SQL type casts in statements to coerce JSON, UUID, and temporal bind values (defaults to True).

enable_pgvector NotRequired[bool]

Detect the PostgreSQL vector extension and promote the dialect to pgvector.

enable_paradedb NotRequired[bool]

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

enable_pg_textsearch NotRequired[bool]

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

enable_alloydb_columnar NotRequired[bool]

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

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

External pooler compatibility mode; executes queries with prepared=False when not session.

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

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

json_serializer NotRequired[Callable[[Any], str]]

Custom JSON serializer applied to statement parameter conversion (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[[PsqlpyConnection], Awaitable[None]]]

Async callback invoked once per physical psqlpy connection acquired from the pool.

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

enable_events NotRequired[bool]

Enable SQLSpec event channel pub/sub support (defaults to True when events is configured).

enable_pgcopy_binary NotRequired[bool]

Enable binary wire format for PostgreSQL COPY operations.

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

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

Tenant Strategies

Set driver_features={"tenant_strategy": "rls"}; "default" and True select the same strategy. Omitted or None pooler mode becomes "session"; transaction, statement, and auto modes are rejected. Both session and connection providers require a tenant or explicit bypass; standalone create_connection() is rejected.

The strategy captures/applies and restores/verifies owned GUCs with one management query per boundary. It never uses blanket RESET ALL. Unfinished transactions roll back before cleanup. Dirty connections require confirmed backend termination; an unconfirmed or timed-out disposal closes and resets the pool so it cannot reuse a dirty session.

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.

PsqlpyRLSStrategy

Bases: PostgresTenantSettings

Apply and restore only owned settings through one bound query each.

__init__

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

checkout

checkout(connection, payload)

Capture the previous session state before applying tenant identity.

checkin

checkin(connection, state)

Restore and verify the captured session state before pool release.

Driver, Pool & Data Dictionary

PsqlpyDriver

Bases: AsyncDriverAdapterBase

PostgreSQL driver implementation using psqlpy.

Provides parameter style conversion, type coercion, error handling, and transaction management.

PsqlpyExceptionHandler

Bases: BaseAsyncExceptionHandler

Async context manager for handling psqlpy database exceptions.

Maps PostgreSQL SQLSTATE error codes to SQLSpec exceptions stored on pending_exception.

PsqlpyDataDictionary

Bases: AsyncDataDictionaryBase

PostgreSQL-specific async data dictionary via psqlpy.

Extension Stores & Configs

PsqlpyLitestarConfig

Bases: LitestarConfig

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

PsqlpyStore

Bases: BaseSQLSpecStore['PsqlpyConfig']

PostgreSQL session store using Psqlpy driver.

Implements server-side session storage for Litestar using PostgreSQL via the Psqlpy driver (Rust-based async driver). Provides efficient session management with: - Native async PostgreSQL operations via Rust - UPSERT support using ON CONFLICT - Automatic expiration handling - Efficient cleanup of expired sessions

Parameters:

Name Type Description Default
config PsqlpyConfig

PsqlpyConfig instance.

required

PsqlpyADKConfig

Bases: ADKConfig

Psqlpy-specific ADK extension settings.

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

enable_bm25 NotRequired[bool]

Create BM25 index on content_text using pg_textsearch extension.

vector_dimensions NotRequired[int]

Vector embedding dimension size. Defaults to 1536.

vector_index_type NotRequired[Literal['hnsw', 'ivfflat', 'scann', 'none']]

Type of vector index to create. Defaults to 'hnsw'.

scann_num_leaves NotRequired[int]

Number of leaves for AlloyDB ScaNN index. Defaults to 500.

scann_quantizer NotRequired[Literal['SQ8', 'FP32']]

Quantizer for AlloyDB ScaNN index. Defaults to 'SQ8'.

PsqlpyADKStore

Bases: BaseAsyncADKStore['PsqlpyConfig']

PostgreSQL ADK store using Psqlpy driver.

Implements session and event storage for Google Agent Development Kit using PostgreSQL via the high-performance Rust-based psqlpy driver. 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

Parameters:

Name Type Description Default
config PsqlpyConfig

PsqlpyConfig with extension_config["adk"] settings.

required

PsqlpyADKMemoryStore

Bases: BaseAsyncADKMemoryStore['PsqlpyConfig']

PostgreSQL ADK memory store using Psqlpy driver.

PsqlpyEventsConfig

Bases: EventsConfig

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

PsqlpyEventQueueStore

Bases: BaseEventQueueStore[PsqlpyConfig]

Provide PostgreSQL column mappings for the queue table.

PostgreSQL uses JSONB for efficient binary JSON storage with indexing support, and TIMESTAMPTZ for timezone-aware timestamps.

PsqlpyEventsBackend

Native LISTEN/NOTIFY backend for psqlpy adapters.

PsqlpyHybridEventsBackend

Durable hybrid backend combining queue storage with LISTEN/NOTIFY wakeups.