pg8000 Adapter¶
from sqlspec.adapters.pg8000 import (
Pg8000Config,
Pg8000ConnectionParams,
Pg8000ConnectionPool,
Pg8000DataDictionary,
Pg8000Driver,
Pg8000DriverFeatures,
Pg8000ExceptionHandler,
Pg8000PoolParams,
Pg8000RLSStrategy,
Pg8000TenantLease,
)
Synchronous pure-Python PostgreSQL adapter built on pg8000 (>= 1.31.5) with zero libpq native dependency. Supports direct TCP connections, Google Cloud SQL Python Connector, Google Cloud AlloyDB Python Connector, COPY streaming, Arrow export, and PostgreSQL RLS tenancy. Inherited execution methods are documented on SyncDriverAdapterBase. See the PostgreSQL (pg8000) Setup Guide for setup, Cloud SQL, AlloyDB, and COPY streaming examples, and the PostgreSQL Data Dictionary & SQL Catalog.
Configuration & Parameters¶
Pg8000Config
¶
Bases: SyncDatabaseConfig[Pg8000Connection, Pg8000ConnectionPool, Pg8000Driver]
Configuration for pure-Python pg8000 synchronous PostgreSQL connections.
Pg8000ConnectionParams
¶
Bases: TypedDict
TypedDict for pg8000 connection parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
dsn |
NotRequired[str]
|
PostgreSQL connection URI ( |
url |
NotRequired[str]
|
Connection URL alias parsed identically to |
connection_string |
NotRequired[str]
|
Connection string alias parsed identically to |
user |
NotRequired[str]
|
PostgreSQL role name used for authentication. |
username |
NotRequired[str]
|
Alias normalized to |
password |
NotRequired[str]
|
Password or token for |
host |
NotRequired[str]
|
Database server hostname for direct TCP connections (defaults to |
port |
NotRequired[int]
|
Database server TCP port for direct TCP connections (defaults to |
database |
NotRequired[str]
|
Target PostgreSQL database name. |
dbname |
NotRequired[str]
|
Alias normalized to |
db |
NotRequired[str]
|
Short alias normalized to |
unix_sock |
NotRequired[str]
|
Filesystem path to a local PostgreSQL Unix domain socket. |
ssl_context |
NotRequired[SSLContext | None]
|
Optional |
timeout |
NotRequired[float | None]
|
Socket timeout in seconds for network operations. |
tcp_keepalive |
NotRequired[bool]
|
Enable OS-level TCP keepalive probes on the socket (defaults to |
application_name |
NotRequired[str]
|
Application identifier reported in |
replication |
NotRequired[str]
|
PostgreSQL replication protocol mode passed in startup parameters. |
startup_params |
NotRequired[dict[str, str]]
|
Additional PostgreSQL startup GUC key/value parameters sent during handshake. |
sock |
NotRequired[Any]
|
Pre-connected socket object supplied directly to |
source_address |
NotRequired[tuple[str, int] | None]
|
Optional |
autocommit |
NotRequired[bool]
|
Enable pg8000 autocommit mode on newly opened connections (defaults to |
auth_token_provider |
NotRequired[Callable[[], str]]
|
Synchronous callable returning a fresh password or IAM token for each new connection. |
connection_creator |
NotRequired[Callable[[], Pg8000Connection]]
|
Custom callable returning an opened |
extra |
NotRequired[dict[str, Any]]
|
Additional keyword arguments forwarded to |
Pg8000PoolParams
¶
Bases: Pg8000ConnectionParams
TypedDict for pg8000 pool parameters, inheriting connection parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
pool_recycle_seconds |
NotRequired[int]
|
Maximum connection age in seconds before recycling pooled connections (defaults to |
health_check_interval |
NotRequired[float]
|
Minimum idle seconds before running a |
max_size |
NotRequired[int]
|
Optional maximum number of concurrent connection checkouts across threads and tasks. |
acquire_timeout |
NotRequired[float]
|
Maximum seconds to wait for a checkout permit when |
Pg8000DriverFeatures
¶
Bases: TypedDict
Optional pg8000 driver feature flags, codecs, cloud connectors, and pooler settings.
Attributes:
| Name | Type | Description |
|---|---|---|
enable_pgvector |
NotRequired[bool]
|
Register |
enable_paradedb |
NotRequired[bool]
|
Detect |
enable_pg_textsearch |
NotRequired[bool]
|
Detect |
tenant_strategy |
NotRequired[SyncTenantStrategy | TenantStrategyShorthand | None]
|
Opt-in tenant strategy, or the |
json_serializer |
NotRequired[Callable[[Any], str]]
|
Custom JSON serializer registered on connection output codecs (defaults to |
json_deserializer |
NotRequired[Callable[[str], Any]]
|
Custom JSON deserializer registered on |
on_connection_create |
NotRequired[Callable[[Pg8000Connection], None]]
|
Synchronous hook invoked with each raw |
reset_session_on_release |
NotRequired[bool]
|
Execute |
pooler_mode |
NotRequired[Literal['session', 'transaction', 'statement', 'auto']]
|
External pooler compatibility mode ( |
direct_dsn |
NotRequired[str | Mapping[str, Any] | None]
|
Direct PostgreSQL DSN or connection mapping bypassing the pooler for session-mode operations. |
enable_events |
NotRequired[bool]
|
Enable durable table-backed SQLSpec event queue support. |
events_backend |
NotRequired[Literal['poll_queue']]
|
Event channel backend ( |
enable_cloud_sql |
NotRequired[bool]
|
Route connections through |
cloud_sql_instance |
NotRequired[str]
|
Cloud SQL instance connection string in |
cloud_sql_enable_iam_auth |
NotRequired[bool]
|
Use IAM database authentication with the Cloud SQL Python Connector (defaults to |
cloud_sql_ip_type |
NotRequired[str]
|
Cloud SQL network path ( |
enable_alloydb |
NotRequired[bool]
|
Route connections through |
alloydb_instance_uri |
NotRequired[str]
|
AlloyDB instance resource URI ( |
alloydb_ip_type |
NotRequired[str]
|
AlloyDB network path ( |
enable_alloydb_iam_auth |
NotRequired[bool]
|
Use IAM database authentication with the AlloyDB Python Connector (defaults to |
enable_alloydb_columnar |
NotRequired[bool]
|
Enable |
connector_retry_count |
NotRequired[int]
|
Maximum retry attempts on transient Cloud SQL or AlloyDB connector errors (defaults to |
connector_retry_delay |
NotRequired[float]
|
Initial delay in seconds before jittered exponential connector retries (defaults to |
connector_retry_max_delay |
NotRequired[float]
|
Upper bound in seconds on the delay between connector retry attempts (defaults to |
Tenant Strategies¶
Set driver_features={"tenant_strategy": "rls"} to protect both provide_session() and provide_connection(). "default" and True select Pg8000RLSStrategy. Pg8000Config also accepts structural strategy instances, including unhashable ones. Missing scope raises TenantContextError; failed cleanup physically closes the connection and raises TenantCleanupError when no body exception is pending.
Tenant mode defaults pooler_mode to "session" and rejects transaction, statement, and auto modes. Standalone create_connection() is rejected when tenant isolation is configured. Checkouts verify idle connection state, capture and apply session GUCs with read-back verification, and discard poisoned connections on TenantCleanupError.
See Multi-Tenancy for database policy setup and Tenant Operations for workers and cleanup.
Pg8000RLSStrategy
¶
Pg8000TenantLease
¶
Bases: SyncTenantLease
Fail-closed synchronous tenant lease backed by a pg8000 connection pool.
Driver, Pool & Data Dictionary¶
Pg8000Driver
¶
Bases: SyncDriverAdapterBase
Pure-Python PostgreSQL synchronous driver using pg8000.
Provides synchronous database operations for PostgreSQL via pg8000.dbapi
supporting single, batch, and script execution, lazy-begin transactions and
savepoints, COPY streaming, chunked row streaming, Arrow export, and
PostgreSQL migration schema hooks.
Pg8000ConnectionPool
¶
Thread-local and asyncio-task-keyed connection manager for pg8000.
Inside a running event loop each asyncio task owns its own connection, and connections from finished tasks are parked for reuse. Optional concurrency bounds cap active checkouts via a bounded semaphore without blocking nested acquires on the same thread or task.
Pg8000ExceptionHandler
¶
Bases: BaseSyncExceptionHandler
Context manager for handling PostgreSQL pg8000 database exceptions.
Maps PostgreSQL SQLSTATE error codes and transport errors to SQLSpec
exceptions stored on pending_exception.
Pg8000DataDictionary
¶
Bases: PostgresSyncDataDictionary
PostgreSQL-specific sync data dictionary for pg8000.
Extension Stores & Configs¶
Pg8000LitestarConfig
¶
Bases: LitestarConfig
Pg8000-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. |
Pg8000Store
¶
Bases: BaseSQLSpecStore['Pg8000Config']
PostgreSQL session store using the synchronous pg8000 driver.
Implements server-side session storage for Litestar using PostgreSQL via the
pure-Python pg8000 DB-API driver, offloading blocking operations through
the base store sync runner to satisfy Litestar's asynchronous Store
protocol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Pg8000Config
|
Pg8000Config instance. |
required |
Pg8000ADKConfig
¶
Bases: ADKConfig
Pg8000-specific ADK extension settings.
Use these keys inside extension_config["adk"] with the pg8000 ADK stores.
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. |
vector_index_type |
NotRequired[Literal['hnsw', 'ivfflat', 'scann']]
|
Vector index algorithm for memory embeddings ('hnsw', 'ivfflat', 'scann'). Default: 'hnsw'. |
vector_dimensions |
NotRequired[int]
|
Dimensionality of embedding vectors (e.g. 768 for gemini-embedding-001 with MRL). Default: 768. |
enable_bm25 |
NotRequired[bool]
|
Enable native BM25 full-text indexing. Requires the pg_textsearch extension. Default: False. |
scann_num_leaves |
NotRequired[int]
|
Number of partition leaves (clusters) for ScaNN tree quantization. Default: 100. |
scann_quantizer |
NotRequired[str]
|
Quantization method for ScaNN index ('SQ8', 'FP32'). Default: 'SQ8'. |
Pg8000ADKStore
¶
Bases: BaseSyncADKStore['Pg8000Config']
PostgreSQL synchronous ADK session and event store backed by pg8000.
Implements session state persistence, full-fidelity JSONB event storage,
atomic scoped-state merges, retention deletes, and schema reconciliation
for PostgreSQL via the synchronous pg8000 driver.
Pg8000ADKMemoryStore
¶
Bases: BaseSyncADKMemoryStore['Pg8000Config']
PostgreSQL ADK memory store backed by the synchronous pg8000 driver.
Supports pgvector similarity search, pg_textsearch BM25 hybrid reciprocal rank fusion, PostgreSQL full-text search, and simple substring fallback.
Pg8000EventsConfig
¶
Bases: EventsConfig
Pg8000 events settings for queue table storage.
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. |
Pg8000EventQueueStore
¶
Bases: BaseEventQueueStore[Pg8000Config]
Queue DDL for pg8000 synchronous configs.
PostgreSQL uses JSONB for efficient binary JSON storage with indexing support, and TIMESTAMPTZ for timezone-aware timestamps.