Skip to content

PostgreSQL — pg8000

sqlspec.adapters.pg8000 wraps pg8000 (>= 1.31.5), providing a pure-Python, libpq-free synchronous PostgreSQL adapter with task-keyed connection pooling, first-party Google Cloud SQL and AlloyDB Python Connector support, COPY streaming, Arrow export, and PostgreSQL RLS tenancy.

Overview & Capabilities

Choose pg8000 when your runtime cannot ship native libpq binaries, such as restricted containers, WebAssembly/Pyodide environments, or pure-Python serverless functions. It also supports synchronous connections through the official Google Cloud SQL or AlloyDB Python Connectors.

Adapter Config Execution Pool Class Best For
Pg8000Config Sync Pg8000ConnectionPool Pure-Python runtimes without libpq, Cloud SQL Python Connector, and AlloyDB Python Connector.

Installation & Quickstart

uv add "sqlspec[pg8000]"
pip install "sqlspec[pg8000]"
pdm add "sqlspec[pg8000]"
poetry add "sqlspec[pg8000]"

For Google Cloud Managed Databases, combine with cloud-sql or alloydb:

uv add "sqlspec[pg8000,cloud-sql]"
uv add "sqlspec[pg8000,alloydb]"
pip install "sqlspec[pg8000,cloud-sql]"
pip install "sqlspec[pg8000,alloydb]"
pdm add "sqlspec[pg8000,cloud-sql]"
pdm add "sqlspec[pg8000,alloydb]"
poetry add "sqlspec[pg8000,cloud-sql]"
poetry add "sqlspec[pg8000,alloydb]"
from sqlspec import SQLSpec
from sqlspec.adapters.pg8000 import Pg8000Config

spec = SQLSpec()
config = spec.add_config(
    Pg8000Config(
        connection_config={
            "dsn": "postgresql://app:secret@localhost:5432/prod",
            "max_size": 10,
        }
    )
)
from sqlspec import SQLSpec
from sqlspec.adapters.pg8000 import Pg8000Config

spec = SQLSpec()
config = spec.add_config(
    Pg8000Config(
        connection_config={
            "user": "[email protected]",
            "database": "prod",
        },
        driver_features={
            "enable_cloud_sql": True,
            "cloud_sql_instance": "my-project:us-central1:prod-pg",
            "cloud_sql_enable_iam_auth": True,
        },
    )
)
from sqlspec import SQLSpec
from sqlspec.adapters.pg8000 import Pg8000Config

instance_uri = (
    "projects/my-project/locations/us-central1"
    "/clusters/prod-cluster/instances/primary"
)
spec = SQLSpec()
config = spec.add_config(
    Pg8000Config(
        connection_config={
            "user": "[email protected]",
            "database": "prod",
        },
        driver_features={
            "enable_alloydb": True,
            "alloydb_instance_uri": instance_uri,
            "enable_alloydb_iam_auth": True,
            "enable_alloydb_columnar": True,
        },
    )
)

Connection & Pool Configuration

Connection and Pool Parameters

Pass Pg8000ConnectionParams and Pg8000PoolParams keys inside connection_config={...} on Pg8000Config:

Key Type Default Description
dsn str - PostgreSQL connection URI (postgresql://, postgres://, or postgresql+pg8000://).
url str - Connection URL alias parsed identically to dsn.
connection_string str - Connection string alias parsed identically to dsn.
user str - PostgreSQL role name used for authentication.
username str - Alias normalized to user when user is omitted.
password str - Password or token for user.
host str 'localhost' Database server hostname for direct TCP connections (defaults to 'localhost').
port int 5432 Database server TCP port for direct TCP connections (defaults to 5432).
database str - Target PostgreSQL database name.
dbname str - Alias normalized to database when database is omitted.
db str - Short alias normalized to database when database is omitted.
unix_sock str - Filesystem path to a local PostgreSQL Unix domain socket.
ssl_context ssl.SSLContext or None - Optional ssl.SSLContext used to negotiate TLS with PostgreSQL.
timeout float or None - Socket timeout in seconds for network operations.
tcp_keepalive bool True Enable OS-level TCP keepalive probes on the socket (defaults to True).
application_name str - Application identifier reported in pg_stat_activity.
replication str - PostgreSQL replication protocol mode passed in startup parameters.
startup_params dict[str, str] - Additional PostgreSQL startup GUC key/value parameters sent during handshake.
sock Any - Pre-connected socket object supplied directly to pg8000.dbapi.connect.
source_address tuple[str, int] or None - Optional (host, port) tuple bound as the client socket source address.
autocommit bool False Enable pg8000 autocommit mode on newly opened connections (defaults to False).
auth_token_provider Callable[[], str] - Synchronous callable returning a fresh password or IAM token for each new connection.
connection_creator Callable[[], Pg8000Connection] - Custom callable returning an opened pg8000.dbapi.Connection instance.
extra dict[str, Any] - Additional keyword arguments forwarded to pg8000.dbapi.connect.
pool_recycle_seconds int 86400 Maximum connection age in seconds before recycling pooled connections (defaults to 86400).
health_check_interval float 30.0 Minimum idle seconds before running a SELECT 1 liveness check (defaults to 30.0).
max_size int - Optional maximum number of concurrent connection checkouts across threads and tasks.
acquire_timeout float 30.0 Maximum seconds to wait for a checkout permit when max_size is set (defaults to 30.0).

Driver Features

Pass Pg8000DriverFeatures keys inside driver_features={...} on Pg8000Config:

Key Type Default Description
enable_pgvector bool - Register pgvector codecs and promote the dialect when pgvector is installed.
enable_paradedb bool True Detect pg_search and promote the SQL dialect to paradedb (defaults to True).
enable_pg_textsearch bool True Detect pg_textsearch and promote the SQL dialect for BM25 <@> ranking (defaults to True).
tenant_strategy SyncTenantStrategy or TenantStrategyShorthand or None - Opt-in tenant strategy, or the 'rls' shorthand, applied to every session and connection lease.
json_serializer Callable[[Any], str] to_json Custom JSON serializer registered on connection output codecs (defaults to to_json).
json_deserializer Callable[[str], Any] from_json Custom JSON deserializer registered on json/jsonb input codecs (defaults to from_json).
on_connection_create Callable[[Pg8000Connection], None] - Synchronous hook invoked with each raw pg8000.dbapi.Connection after internal setup.
reset_session_on_release bool False Execute DISCARD ALL and re-initialize each connection on outermost release (defaults to False).
pooler_mode Literal['session', 'transaction', 'statement', 'auto'] 'session' External pooler compatibility mode (session, transaction, statement, or auto; defaults to 'session').
direct_dsn str or Mapping[str, Any] or None - Direct PostgreSQL DSN or connection mapping bypassing the pooler for session-mode operations.
enable_events bool - Enable durable table-backed SQLSpec event queue support.
events_backend Literal['poll_queue'] - Event channel backend (poll_queue is the sole backend for pg8000).
enable_cloud_sql bool False Route connections through cloud-sql-python-connector (mutually exclusive with enable_alloydb; defaults to False).
cloud_sql_instance str - Cloud SQL instance connection string in project:region:instance format.
cloud_sql_enable_iam_auth bool False Use IAM database authentication with the Cloud SQL Python Connector (defaults to False).
cloud_sql_ip_type str 'PRIVATE' Cloud SQL network path (PUBLIC, PRIVATE, or PSC; defaults to 'PRIVATE').
enable_alloydb bool False Route connections through google-cloud-alloydb-connector (mutually exclusive with enable_cloud_sql; defaults to False).
alloydb_instance_uri str - AlloyDB instance resource URI (projects/PROJECT/locations/REGION/clusters/CLUSTER/instances/INSTANCE).
alloydb_ip_type str 'PRIVATE' AlloyDB network path (PUBLIC, PRIVATE, or PSC; defaults to 'PRIVATE').
enable_alloydb_iam_auth bool False Use IAM database authentication with the AlloyDB Python Connector (defaults to False).
enable_alloydb_columnar 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 int 3 Maximum retry attempts on transient Cloud SQL or AlloyDB connector errors (defaults to 3; 0 disables retries).
connector_retry_delay float 0.5 Initial delay in seconds before jittered exponential connector retries (defaults to 0.5).
connector_retry_max_delay float 5.0 Upper bound in seconds on the delay between connector retry attempts (defaults to 5.0).

COPY Streaming, Arrow Export & Tenancy

  • COPY Streaming: pg8000.dbapi.Cursor.execute(sql, args, stream=...) streams COPY ... FROM STDIN and COPY ... TO STDOUT directly through file-like buffers (io.BytesIO or io.StringIO) without materializing entire payloads into SQL literals.
  • Arrow Export with OID Fallback: session.select_to_arrow(...) converts query results to Apache Arrow tables and falls back to PostgreSQL OID schema synthesis from cursor.description when a query returns zero rows.
  • Events Queue Backend: Pg8000EventQueueStore supports events_backend="poll_queue" using FOR UPDATE SKIP LOCKED. Native PostgreSQL LISTEN/NOTIFY hubs are out of scope for pg8000.
  • RLS Tenant Isolation: Enable driver_features={"tenant_strategy": "rls"} to enforce Pg8000RLSStrategy across provide_session() and provide_connection(), with pooler_mode="session", GUC read-back verification, and automatic discard of poisoned connections on cleanup failure.
  • SQLSTATE Exception Mapping: pg8000 exposes PostgreSQL ErrorResponse dictionaries on DatabaseError.args[0], mapping SQLSTATE codes (23505, 23503, 23502, 23514, 40P01, 40001, 42501, 57014) to the same SQLSpec exception hierarchy as asyncpg, psycopg, and psqlpy.

Type Mappings & Dialect Notes

Database Type Python Type Notes / Feature Flag
JSON / JSONB dict / list Serialized via json_serializer / json_deserializer (msgspec by default); text parameters cast cleanly with ::jsonb.
UUID uuid.UUID / str Native pg8000 UUID adaptation.
VECTOR (pgvector) list[float] / numpy.ndarray Registered when enable_pgvector=True and pgvector is installed.
ARRAY list[T] Native PostgreSQL array binding.
BYTEA bytes / bytearray / memoryview Binary wire transport.
NUMERIC / DECIMAL decimal.Decimal Exact decimal arithmetic.

See Also