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 ( |
username |
NotRequired[str]
|
PostgreSQL role name used for authentication. |
password |
NotRequired[str]
|
Password for |
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 |
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 ( |
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 |
options |
NotRequired[str]
|
Command-line startup GUC options sent to the PostgreSQL backend. |
application_name |
NotRequired[str]
|
Application identifier reported in |
client_encoding |
NotRequired[str]
|
Client character set encoding (defaults to |
gssencmode |
NotRequired[str]
|
GSSAPI transport encryption mode ( |
sslnegotiation |
NotRequired[str]
|
PostgreSQL 17+ TLS handshake mode ( |
sslcompression |
NotRequired[str]
|
TLS compression setting forwarded to |
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 |
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 ( |
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 |
load_balance_hosts |
NotRequired[Literal['disable', 'random'] | LoadBalanceHosts]
|
Host ordering policy across multi-host configurations ( |
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 |
conn_recycling_method |
NotRequired[str]
|
Pool connection reset strategy (such as |
max_db_pool_size |
NotRequired[int]
|
Maximum number of concurrent connections held by |
configure |
NotRequired[Callable[..., Any]]
|
Optional pool connection configuration callback. |
extra |
NotRequired[dict[str, Any]]
|
Additional keyword options passed directly to |
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 |
enable_cast_detection |
NotRequired[bool]
|
Use SQL type casts in statements to coerce JSON, UUID, and temporal bind values (defaults to |
enable_pgvector |
NotRequired[bool]
|
Detect the PostgreSQL |
enable_paradedb |
NotRequired[bool]
|
Detect |
enable_pg_textsearch |
NotRequired[bool]
|
Detect |
enable_alloydb_columnar |
NotRequired[bool]
|
Enable |
pooler_mode |
NotRequired[Literal['session', 'transaction', 'statement', 'auto'] | None]
|
External pooler compatibility mode; executes queries with |
direct_dsn |
NotRequired[str | Mapping[str, Any] | None]
|
Direct PostgreSQL DSN or connection mapping bypassing the pooler for migrations and |
json_serializer |
NotRequired[Callable[[Any], str]]
|
Custom JSON serializer applied to statement parameter conversion (defaults to |
json_deserializer |
NotRequired[Callable[[str], Any]]
|
Custom JSON deserializer retained alongside |
on_connection_create |
NotRequired[Callable[[PsqlpyConnection], Awaitable[None]]]
|
Async callback invoked once per physical |
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 |
enable_events |
NotRequired[bool]
|
Enable SQLSpec event channel pub/sub support (defaults to |
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 ( |
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
¶
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
¶
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_dataJSONB column - Atomic
append_event_and_update_statefor 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
¶
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.