Skip to content

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 (postgresql://, postgres://, or postgresql+pg8000://).

url NotRequired[str]

Connection URL alias parsed identically to dsn.

connection_string NotRequired[str]

Connection string alias parsed identically to dsn.

user NotRequired[str]

PostgreSQL role name used for authentication.

username NotRequired[str]

Alias normalized to user when user is omitted.

password NotRequired[str]

Password or token for user.

host NotRequired[str]

Database server hostname for direct TCP connections (defaults to 'localhost').

port NotRequired[int]

Database server TCP port for direct TCP connections (defaults to 5432).

database NotRequired[str]

Target PostgreSQL database name.

dbname NotRequired[str]

Alias normalized to database when database is omitted.

db NotRequired[str]

Short alias normalized to database when database is omitted.

unix_sock NotRequired[str]

Filesystem path to a local PostgreSQL Unix domain socket.

ssl_context NotRequired[SSLContext | None]

Optional ssl.SSLContext used to negotiate TLS with PostgreSQL.

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

application_name NotRequired[str]

Application identifier reported in pg_stat_activity.

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 pg8000.dbapi.connect.

source_address NotRequired[tuple[str, int] | None]

Optional (host, port) tuple bound as the client socket source address.

autocommit NotRequired[bool]

Enable pg8000 autocommit mode on newly opened connections (defaults to False).

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 pg8000.dbapi.Connection instance.

extra NotRequired[dict[str, Any]]

Additional keyword arguments forwarded to pg8000.dbapi.connect.

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

health_check_interval NotRequired[float]

Minimum idle seconds before running a SELECT 1 liveness check (defaults to 30.0).

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 max_size is set (defaults to 30.0).

Pg8000DriverFeatures

Bases: TypedDict

Optional pg8000 driver feature flags, codecs, cloud connectors, and pooler settings.

Attributes:

Name Type Description
enable_pgvector NotRequired[bool]

Register pgvector codecs and promote the dialect when pgvector is installed.

enable_paradedb NotRequired[bool]

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

enable_pg_textsearch NotRequired[bool]

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

tenant_strategy NotRequired[SyncTenantStrategy | TenantStrategyShorthand | None]

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

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

Custom JSON serializer registered on connection output codecs (defaults to to_json).

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

Custom JSON deserializer registered on json/jsonb input codecs (defaults to from_json).

on_connection_create NotRequired[Callable[[Pg8000Connection], None]]

Synchronous hook invoked with each raw pg8000.dbapi.Connection after internal setup.

reset_session_on_release NotRequired[bool]

Execute DISCARD ALL and re-initialize each connection on outermost release (defaults to False).

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

External pooler compatibility mode (session, transaction, statement, or auto; defaults to 'session').

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 (poll_queue is the sole backend for pg8000).

enable_cloud_sql NotRequired[bool]

Route connections through cloud-sql-python-connector (mutually exclusive with enable_alloydb; defaults to False).

cloud_sql_instance NotRequired[str]

Cloud SQL instance connection string in project:region:instance format.

cloud_sql_enable_iam_auth NotRequired[bool]

Use IAM database authentication with the Cloud SQL Python Connector (defaults to False).

cloud_sql_ip_type NotRequired[str]

Cloud SQL network path (PUBLIC, PRIVATE, or PSC; defaults to 'PRIVATE').

enable_alloydb NotRequired[bool]

Route connections through google-cloud-alloydb-connector (mutually exclusive with enable_cloud_sql; defaults to False).

alloydb_instance_uri NotRequired[str]

AlloyDB instance resource URI (projects/PROJECT/locations/REGION/clusters/CLUSTER/instances/INSTANCE).

alloydb_ip_type NotRequired[str]

AlloyDB network path (PUBLIC, PRIVATE, or PSC; defaults to 'PRIVATE').

enable_alloydb_iam_auth NotRequired[bool]

Use IAM database authentication with the AlloyDB Python Connector (defaults to False).

enable_alloydb_columnar NotRequired[bool]

Enable google_columnar_engine.enable_columnar_scan = 'on' on new connections outside transaction/statement pooler modes or via per-transaction SET LOCAL.

connector_retry_count NotRequired[int]

Maximum retry attempts on transient Cloud SQL or AlloyDB connector errors (defaults to 3; 0 disables retries).

connector_retry_delay NotRequired[float]

Initial delay in seconds before jittered exponential connector retries (defaults to 0.5).

connector_retry_max_delay NotRequired[float]

Upper bound in seconds on the delay between connector retry attempts (defaults to 5.0).

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

Bases: PostgresTenantSettings

Capture, apply, and verify synchronous PostgreSQL session settings for pg8000.

__init__
__init__(
    *, tenant_key=DEFAULT_TENANT_KEY, variable_keys=None, schema_resolver=None
)
checkout
checkout(connection, payload)

Apply tenant session settings and commit only the management transaction.

checkin
checkin(connection, state)

Restore captured session settings after the lease finishes application work.

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.