Skip to content

Database Drivers, Analytics & Cloud Dialers

vertebra.db provides database configs, sync and async drivers, capability protocols, DB-API 2.0 adapters, Apache Arrow cursors, DataFusion SQL federation, change data capture, tenant scoping, and direct Cloud SQL and AlloyDB dialers. See the Databases & Native Drivers Usage Guide for patterns and examples.

Category Coverage
SQLSpec Adapters Litestar adapter configs under vertebra.extensions.sqlspec backed by Vertebra drivers and connection leasing.
PEP 249 DB-API Sync and async DB-API 2.0 interfaces under vertebra.db.dbapi with no SQLAlchemy dependency.
Registry & Driver Contracts URL-based driver resolution, shared pool keys, uniform sync and async contracts, query pipelining, and zero-copy Arrow cursors.
Capability Protocols Runtime-checkable protocols for pipelining, pub/sub notifications, CDC streams, SKIP LOCKED queues, and in-database embedding pushdown.
Relational & Analytical Drivers Configs for PostgreSQL, MySQL, SQLite, Oracle 26ai, SQL Server, DuckDB, BigQuery, and Spanner.
Key-Value & Federated SQL RESP3 Redis and Valkey clients with client-side caching, Sentinel, and Cluster routing, plus cross-engine DataFusion analytics.
Cloud Dialers, CDC & RLS Direct IAM token auth, :5433 AlloyDB and :3307 Cloud SQL mTLS connectors, logical replication and change streams, and tenant isolation.

Registry, Driver Contracts & Pipelines

DatabaseRegistry and provide_driver resolve configs and shared drivers from URL schemes. SyncDatabaseDriver and AsyncDatabaseDriver define the execution contract, while SyncPipelineCapable and AsyncPipelineCapable add batched driver.pipeline() execution.

DatabaseRegistry

Named registry of configured database, cache, analytics, and cloud dialer instances.

register

register(name, config_or_url)

Register a database alias from a typed config or URL.

parse_url

parse_url(url, **overrides)

Parse a database, cache, analytics, or dialer URL into its typed configuration struct.

get_driver

get_driver(name='default')

Lazily instantiate and return the asynchronous driver for the given alias.

get_sync_driver

get_sync_driver(name='default')

Lazily instantiate and return the synchronous driver for the given alias.

get_dialer

get_dialer(config, *, sync=False)

Return a cached Cloud SQL or AlloyDB dialer for config and sync mode.

provide_driver

provide_driver(name_or_config='default', *, sync=False, registry=None)

Resolve a database, cache, or analytics driver from DatabaseRegistry for framework DI.

BaseDatabaseConfig

Bases: FrozenBaseStruct

Base configuration struct for built-in Vertebra database and cache drivers.

SyncDatabaseDriver

Bases: CommonDriverMixin[ConfigT]

Base execution contract for synchronous SQL and analytical database drivers.

AsyncDatabaseDriver

Bases: CommonDriverMixin[ConfigT]

Base execution contract for asynchronous SQL and analytical database drivers.

DatabaseError

Bases: VertebraError

Base error raised for database driver, wire-protocol, or query execution failures.

SyncPipelineCapable

Bases: Protocol

Capability protocol for synchronous drivers supporting wire-level query pipelining.

pipeline

pipeline()

Create a new synchronous query pipeline bound to this driver.

AsyncPipelineCapable

Bases: Protocol

Capability protocol for asynchronous drivers supporting wire-level query pipelining.

pipeline

pipeline()

Create a new asynchronous query pipeline bound to this driver.

ArrowCursor

Zero-copy shared-memory Arrow IPC cursor for bulk analytical result sets.

_shm_anchor pins the source region and memoryviews backing _buffer so Arrow buffers decoded over the payload never outlive the mapping, _ipc_table_cache memoizes the pyarrow.Table when pyarrow is installed, and _native_ipc_cursor lazily memoizes vertebra._vertebra.ArrowCursor.from_ipc_bytes only when pyarrow is absent.

PEP 249 DB-API

SyncDBAPIConnection

Bases: _BaseDBAPIConnection

Standalone synchronous PEP 249 connection backed by Vertebra native drivers.

AsyncDBAPIConnection

Bases: _BaseDBAPIConnection

Standalone asynchronous PEP 249 connection backed by Vertebra async drivers.

SyncDBAPIModule

Bases: _BaseDBAPIModule

Standalone synchronous PEP 249 DBAPI 2.0 module descriptor.

AsyncDBAPIModule

Bases: _BaseDBAPIModule

Standalone asynchronous DBAPI module adapter returning AsyncDBAPIConnection instances.

Relational, Cloud & Analytical Drivers

PostgreSQLConfig

Bases: BaseDatabaseConfig

PostgreSQL configuration supporting Cloud SQL, AlloyDB, and PgBouncer/PgCat/pgdog poolers.

Attributes:

Name Type Description
dialectstr
Default: 'postgres'
dialect_tagint
Default: POSTGRES_DIALECT_TAG
url_schemestuple[str, ...]
Default: ('postgresql', 'postgres')
driver_modulestr
Default: 'vertebra.db.adapters.postgres.driver'
sync_driver_namestr
Default: 'SyncPostgreSQLDriver'
async_driver_namestr
Default: 'AsyncPostgreSQLDriver'
dsnstr

Primary PostgreSQL connection URI (may point to a PgBouncer, PgCat, or pgdog pooler).

direct_dsnstr | None

Optional unpooled direct PostgreSQL URI used for LISTEN/NOTIFY, migrations, and DDL.

pooler_modePoolerMode

Connection pooler multiplexing mode ("direct", "transaction", "session", "statement", or "auto").

pgbouncerbool

When True, configure transaction-mode PgBouncer settings (statement_cache_size = 0).

pgbouncer_modebool

Alias for pgbouncer matching sqlspec driver features.

protocol_level_pooler_cachebool

When True, retain prepared statements in transaction-mode poolers supporting protocol-level statement caching.

max_prepared_statementsint | None

Maximum per-connection prepared statement LRU capacity (None defaults to 256 when safe).

min_sizeint

Minimum number of pooled connections maintained per worker.

max_sizeint

Maximum number of pooled connections permitted per worker.

enable_cloud_sqlbool

When True, enable zero-sidecar Google Cloud SQL (:3307) mTLS connection dialing.

cloud_sql_instancestr | None

Optional Google Cloud SQL instance connection name (project:region:instance) for zero-sidecar port 3307 mTLS.

cloud_sql_ip_typeLiteral['PUBLIC', 'PRIVATE', 'PSC']

Preferred Google Cloud SQL IP connectivity mode.

enable_alloydbbool

When True, enable zero-sidecar Google Cloud AlloyDB (:5433) mTLS and MetadataExchange dialing.

alloydb_instance_uristr | None

Optional Google Cloud AlloyDB instance URI (projects/.../instances/...) for zero-sidecar port 5433 mTLS.

alloydb_ip_typeLiteral['PUBLIC', 'PRIVATE', 'PSC']

Preferred Google Cloud AlloyDB IP connectivity mode.

connector_retry_countint

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

connector_retry_delayfloat

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

connector_retry_max_delayfloat

Upper bound in seconds on exponential backoff between dialer retry attempts (defaults to 5.0).

enable_iam_authbool

When True, authenticate using short-lived Google Cloud IAM OAuth2 tokens (on direct :5432 TCP/TLS or :3307/:5433 dialers).

iam_auth_optionsMapping[str, str]

Optional GcpTokenCache options (service_account_key, application_credentials_path, scopes) for direct :5432 or dialer IAM token resolution.

token_providerAny

Optional cloud database token provider (DatabaseTokenProvider) supplying dynamic IAM passwords.

ca_pemstr | None

Optional inline Root CA PEM bundle used for PostgreSQL TLS verification.

enable_alloydb_columnar_enginebool

When True, enable google_columnar_engine.enabled = on in session startup GUCs.

cockroach_clusterstr | None

Optional CockroachDB cluster routing identifier forwarded as --cluster=<id> in startup options.

application_namestr

PostgreSQL application_name GUC reported in pg_stat_activity.

statement_timeout_msint | None

Optional per-statement execution timeout in milliseconds (statement_timeout GUC).

idle_in_transaction_session_timeout_msint | None

Optional timeout in milliseconds before aborting idle open transactions.

session_gucsMapping[str, str]

Additional PostgreSQL session GUC key-value pairs applied on connection startup.

brokerAny

Optional shared-memory DatabaseBroker, SyncSHMBrokerTransport, or AsyncSHMBrokerTransport for cross-worker connection leasing.

effective_statement_cache_sizeint

Return the prepared statement cache capacity safe for the configured pooler mode.

effective_direct_dsnstr

Return the direct primary DSN for LISTEN/NOTIFY, logical replication, and migrations.

MySQLConfig

Bases: BaseDatabaseConfig

Configuration for SyncMySQLDriver and AsyncMySQLDriver.

ssl_mode holds only what the caller set; None means unset. canonical_ssl_mode resolves the effective mode: an explicit DSN ssl parameter, then the ssl_mode field, then a default. The default is verify-full for AwsRdsIamTokenProvider or AzureEntraTokenProvider on a remote host, require for any other token provider or for loopback, unix-socket, and Cloud SQL targets, and prefer without a token provider. Remote cloud IAM targets reject explicit disable and prefer.

SQLiteConfig

Bases: BaseDatabaseConfig

Configuration for SQLite 3.45+ with WAL mode, memory-mapped I/O, and SHM broker leasing.

Attributes:

Name Type Description
dialectstr
Default: 'sqlite'
dialect_tagint
Default: SQLITE_DIALECT_TAG
url_schemestuple[str, ...]
Default: ('sqlite',)
driver_modulestr
Default: 'vertebra.db.adapters.sqlite.driver'
sync_driver_namestr
Default: 'SyncSQLiteDriver'
async_driver_namestr
Default: 'AsyncSQLiteDriver'
pathstr

Filesystem path to the SQLite database file or ":memory:".

wal_modebool

When True, enable PRAGMA journal_mode = WAL for concurrent readers alongside a single writer.

synchronousstr

SQLite PRAGMA synchronous durability level ("OFF", "NORMAL", "FULL", or "EXTRA").

mmap_sizeint

Maximum memory-mapped I/O window in bytes (PRAGMA mmap_size, default 256 MiB).

busy_timeout_msint

Lock contention wait timeout in milliseconds (PRAGMA busy_timeout).

max_readersint

Maximum number of concurrent read connections leased across workers.

foreign_keysbool

When True, enforce referential integrity via PRAGMA foreign_keys = ON.

brokerAny

Optional shared-memory DatabaseBroker coordinating single-writer/multi-reader leases.

databasestr | Path | None

Optional alias for path accepting a pathlib.Path or string.

enable_jsonbbool

When True, use SQLite 3.45+ binary JSONB functions when available.

is_in_memorybool

Return True if the target database is in-memory.

OracleConfig

Bases: BaseDatabaseConfig

Configuration for the Oracle driver backed by the native vertebra._oracle module.

MSSQLConfig

Bases: BaseDatabaseConfig

Configuration for the native SQL Server (TDS 7.4) driver.

DuckDBConfig

Bases: BaseDatabaseConfig

Configuration for the embedded DuckDB analytical engine.

Attributes:

Name Type Description
dialectstr
Default: 'duckdb'
dialect_tagint
Default: DUCKDB_DIALECT_TAG
url_schemestuple[str, ...]
Default: ('duckdb',)
driver_modulestr
Default: 'vertebra.db.adapters.duckdb.driver'
sync_driver_namestr
Default: 'SyncDuckDBDriver'
async_driver_namestr
Default: 'AsyncDuckDBDriver'
pathstr

Filesystem path to the DuckDB database file or ":memory:".

databasestr

Fallback database path alias used when path is left at ":memory:".

memory_limit_mbint

Maximum buffer manager memory allowance in MiB (SET memory_limit).

threadsint

Number of DuckDB execution threads (SET threads).

temp_directorystr | None

Optional spill directory configured via SET temp_directory.

parquet_metadata_cachebool

When True, enable SET parquet_metadata_cache = true after connection bootstrap.

httpfs_connection_cachingbool

When True, keep remote HTTP/object-storage connections warm (SET http_keep_alive = true).

enable_http_metadata_cachebool

When True, cache remote HTTP/Parquet HEAD metadata (SET enable_http_metadata_cache = true).

read_onlybool

When True, open the DuckDB file in read-only mode allowing multi-process readers.

secretstuple[DuckDBSecretConfig | Mapping[str, Any], ...]

Optional DuckDB secrets (DuckDBSecretConfig or sqlspec-compatible secret mappings) provisioned on sessions.

extensionstuple[str, ...]

Optional DuckDB extensions ("<ext>" or "<ext> FROM <repo>") loaded on every pooled session.

init_statementstuple[str, ...]

Optional SQL statements executed after bootstrap on every pooled session.

configdict[str, str]

Optional DuckDB session SET key/value overrides.

pool_min_sizeint

Minimum number of pooled DuckDB cursors per worker.

pool_max_sizeint

Maximum number of pooled DuckDB cursors per worker.

statement_cache_sizeint

Maximum number of prepared analytical statements cached per worker.

brokerAny

Optional shared-memory DatabaseBroker coordinating single-writer/multi-reader leases.

BigQueryConfig

Bases: BaseDatabaseConfig

Configuration for SyncBigQueryDriver and AsyncBigQueryDriver.

Attributes:

Name Type Description
dialectstr
Default: 'bigquery'
dialect_tagint
Default: BIGQUERY_DIALECT_TAG
url_schemestuple[str, ...]
Default: ('bigquery', 'bq')
driver_modulestr
Default: 'vertebra.db.adapters.bigquery.driver'
sync_driver_namestr
Default: 'SyncBigQueryDriver'
async_driver_namestr
Default: 'AsyncBigQueryDriver'
requires_statement_autocommitbool
Default: True
project_idstr

Google Cloud project identifier owning BigQuery jobs and default datasets.

dataset_idstr | None

Default BigQuery dataset identifier for unqualified table references.

locationstr

BigQuery dataset and job processing location (such as US or EU).

dsnstr | None

Optional bigquery://project_id[/dataset_id]?location=... connection URI.

rest_endpointstr

Base URL for the BigQuery REST v2 API.

storage_endpointstr

Endpoint URL for the BigQuery Storage Read/Write v1 gRPC API.

maximum_bytes_billedint | None

Optional FinOps byte billing cap applied to executed query jobs.

job_timeout_msint | None

Optional server-side query execution timeout in milliseconds.

priorityLiteral['INTERACTIVE', 'BATCH']

BigQuery query scheduling priority (INTERACTIVE or BATCH).

labelsdict[str, str]

Static key-value labels attached to BigQuery jobs after label sanitization.

credentials_pathstr | None

Optional filesystem path to a Google Cloud service-account or ADC JSON file.

service_account_keystr | dict[str, Any] | None

Optional inline service-account JSON string or mapping.

quota_project_idstr | None

Optional x-goog-user-project quota project override.

impersonate_service_accountstr | None

Optional target service-account email for keyless IAM Credentials generateAccessToken impersonation.

access_tokenstr | None

Optional static OAuth2 bearer access token override.

use_gcloud_clibool

Whether to force token minting via the local gcloud CLI subprocess.

scopestuple[str, ...]

OAuth2 scopes requested when minting bearer tokens.

pool_sizeint

Maximum pooled HTTP/1.1 and HTTP/2 h2 channels maintained by the Rust client.

statement_cache_capacityint

Maximum entries retained in the shared-memory SQL statement plan cache.

use_shm_cachebool

Whether to enable the cross-worker POSIX shared-memory statement cache.

arrow_compressionLiteral['LZ4_FRAME', 'ZSTD', 'UNSPECIFIED']

Arrow IPC stream compression codec negotiated with BigQuery Storage Read API v1.

max_read_streamsint

Maximum parallel ReadRows streams requested in CreateReadSession.

ca_pembytes | None

PEM root certificates added to the REST API client. The Storage Read/Write API clients use the system trust store and ignore this value.

brokerAny

Optional shared-memory LeaseBroker instance.

SpannerConfig

Bases: BaseDatabaseConfig

Configuration for SyncSpannerDriver and AsyncSpannerDriver.

Attributes:

Name Type Description
dialect_tagint
Default: SPANNER_GOOGLESQL_DIALECT_TAG
url_schemestuple[str, ...]
Default: ('spanner', 'spangres', 'spanner+googlesql', 'spanner+spangres')
driver_modulestr
Default: 'vertebra.db.adapters.spanner.driver'
sync_driver_namestr
Default: 'SyncSpannerDriver'
async_driver_namestr
Default: 'AsyncSpannerDriver'
requires_statement_autocommitbool
Default: True
project_idstr

Google Cloud project identifier owning the Spanner instance.

instance_idstr

Cloud Spanner instance identifier.

database_idstr

Cloud Spanner database identifier.

dsnstr | None

Optional spanner:// or spangres:// connection URI.

database_rolestr | None

Optional fine-grained access control (FGAC) creator_role attached to the multiplexed session.

dialectLiteral['googlesql', 'spangres']

SQL dialect configured on the Spanner database (googlesql or spangres).

endpointstr

Cloud Spanner v1 gRPC endpoint URI.

admin_endpointstr | None

REST endpoint for DDL (UpdateDatabaseDdl). Defaults to https://spanner.googleapis.com for Google endpoints and to port 9020 of an http://…:9010 emulator endpoint; required for any other endpoint.

pool_sizeint

Number of pooled HTTP/2 h2 channels maintained by GrpcChannelPool.

route_to_leader_enabledbool

Whether x-goog-spanner-route-to-leader: true is sent on ReadWrite and PartitionedDml RPCs.

max_commit_delay_msint | None

Optional CommitRequest.max_commit_delay batching window in milliseconds.

data_boost_enabledbool

Whether ExecuteSqlRequest.data_boost_enabled is set on partitioned Arrow reads.

max_partitionsint

Maximum parallel PartitionQuery partitions requested for fetch_arrow.

credentials_pathstr | None

Optional filesystem path to a Google Cloud service-account or ADC JSON file.

service_account_keystr | dict[str, Any] | None

Optional inline service-account JSON string or mapping.

quota_project_idstr | None

Optional x-goog-user-project quota project header override.

impersonate_service_accountstr | None

Optional target service-account email for keyless IAM Credentials generateAccessToken impersonation.

use_gcloud_clibool

Whether to force token minting via the local gcloud CLI subprocess.

scopestuple[str, ...]

OAuth2 scopes requested when minting bearer tokens.

access_tokenstr | None

Optional static bearer token override for testing or workload federation.

use_shm_cachebool

Whether to enable the cross-worker POSIX shared-memory statement cache.

statement_cache_capacityint

Maximum entries retained in the shared-memory SQL statement plan cache.

ca_pembytes | None

PEM root certificates for a non-googleapis https:// endpoint (Spanner Omni or a private test server). Rejected for *.googleapis.com endpoints, which use the system trust store, and for http:// endpoints.

brokerAny

Optional shared-memory LeaseBroker instance.

database_uristr

Return the canonical projects/{p}/instances/{i}/databases/{d} resource path.

database_pathstr

Return the canonical projects/{p}/instances/{i}/databases/{d} resource path.

Key-Value Stores & DataFusion

RedisConfig

Bases: BaseRESPConfig

Configuration for Redis 7.2+ / 8.0+ standalone, Sentinel, and Cluster connections.

ValkeyConfig

Bases: BaseRESPConfig

Configuration for Valkey 8.0+ / 9.0+ standalone, Sentinel, Cluster, and GCP Memorystore.

DataFusionConfig

Bases: BaseDatabaseConfig

Configuration for embedded in-process Apache DataFusion analytics execution.

DataFusionEngine

Federated query engine joining ObjectStore datasets with live database Arrow tables.

register_table

register_table(registration)

Register an ObjectStore dataset, file source, or registered Arrow table.

register_arrow_table

register_arrow_table(name, table)

Normalize and register an in-memory PyArrow table or ArrowCursor on the session context.

register_parquet_from_store

register_parquet_from_store(name, store, key)

Register a Parquet dataset located in an ObjectStore.

execute_arrow

execute_arrow(sql)

Execute sql on the DataFusion SessionContext and return a PyArrow Table.

execute_sql

execute_sql(sql)

Execute sql and return results as a list of dictionaries.

Cloud Dialers, CDC & Row-Level Security

AlloyDBConfig

Bases: FrozenBaseStruct

Configuration for zero-sidecar AlloyDB connections on port 5433.

CloudSQLConfig

Bases: FrozenBaseStruct

Configuration for zero-sidecar Cloud SQL connections on port 3307.

ChangeFeed

Publish change-feed envelopes with bounded history and spill storage.

publish_event

publish_event(operation, payload)

Encode an event, spilling payloads that exceed the inline byte threshold.

replay_since

replay_since(last_event_id)

Return all buffered ChangeEvent items with event_id > last_event_id.

flush_to_parquet

flush_to_parquet(path)

Flush in-memory history events to a PyArrow Parquet object in the attached ObjectStore.

TenantPredicate

Bases: FrozenBaseStruct

Render a tenant predicate with a bound value and an optional ANSI cast.

TenantScopeConfig.setting_name is adapter-neutral. TenantPredicate renders ANSI placeholders with an optional CAST, while the PostgreSQL and Oracle adapters own session SQL. SQLSpec accepts the declared PostgreSQL and Oracle setters and rejects other engines. BigQuery and Spanner constructors reject a non-None tenant_predicate before initialization. Oracle VPD scopes support trusted context package procedures alongside DBMS_SESSION.SET_IDENTIFIER and reset or evict connections on pool release.

See Database Capabilities for notification, change-stream, tenant-scope, and tool-provider APIs.