Skip to content

spanner Adapter

from sqlspec.adapters.spanner import (
    SpannerAsyncConfig,
    SpannerAsyncDriver,
    SpannerAsyncExceptionHandler,
    SpannerConnectionParams,
    SpannerDriverFeatures,
    SpannerPoolParams,
    SpannerSyncConfig,
    SpannerSyncDriver,
    SpannerSyncExceptionHandler,
)

Synchronous and asynchronous Google Cloud Spanner adapters supporting both GoogleSQL (spanner) and PostgreSQL (spangres) dialects, multiplexed sessions, read-only timestamp snapshots, and CommitResponse mutation tracking. Inherited execution methods are documented on SyncDriverAdapterBase and AsyncDriverAdapterBase. See the Cloud Spanner Setup Guide for usage examples.

Configuration & Parameters

SpannerSyncConfig

Bases: SyncDatabaseConfig['SpannerSyncConnection', 'AbstractSessionPool', SpannerSyncDriver]

Spanner configuration and session management.

SpannerAsyncConfig

Bases: AsyncDatabaseConfig['SpannerAsyncConnection', 'AsyncAbstractSessionPool', SpannerAsyncDriver]

Async Spanner configuration and session management.

SpannerConnectionParams

Bases: TypedDict

Google Cloud Spanner client, instance, and database connection parameters.

Attributes:

Name Type Description
project NotRequired[str]

Google Cloud project ID owning the Spanner instance.

project_id NotRequired[str]

Alias normalized to project when project is unset.

credentials NotRequired[SpannerCredentials]

Explicit google.auth.credentials.Credentials instance overriding ADC.

client_info NotRequired[SpannerClientInfo]

Custom google.api_core.gapic_v1.client_info.ClientInfo user-agent metadata.

client_options NotRequired[SpannerClientOptions | dict[str, Any]]

GAPIC ClientOptions or mapping configuring API endpoint, universe domain, or quota project.

query_options NotRequired[QueryOptions]

Client-wide default ExecuteSqlRequest.QueryOptions (such as optimizer_version).

route_to_leader_enabled NotRequired[bool]

Route read-write transactions and Partitioned DML directly to Paxos leader replicas.

directed_read_options NotRequired[SpannerDirectedReadOptions]

Client-wide replica routing rules for read-only snapshot requests.

observability_options NotRequired[Any]

Google Cloud Spanner client-side OpenTelemetry tracing configuration.

default_transaction_options NotRequired[SpannerDefaultTransactionOptions]

Default isolation level or read-lock mode applied to read-write transactions.

experimental_host NotRequired[str]

Direct single-endpoint Spanner or emulator host address.

disable_builtin_metrics NotRequired[bool]

Disable built-in Cloud Monitoring client-side metric export.

client_context NotRequired[dict[str, str]]

Key-value client context attributes attached to Spanner RPC metadata.

use_plain_text NotRequired[bool]

Connect over unencrypted plaintext gRPC when targeting local emulators.

ca_certificate NotRequired[str]

PEM root CA certificate bundle path for custom TLS verification.

client_certificate NotRequired[str]

PEM client certificate path for mTLS authentication.

client_key NotRequired[str]

PEM client private key path paired with client_certificate.

instance_type NotRequired[str]

Spanner instance edition or provisioning type forwarded to the client.

instance_id NotRequired[str]

Target Spanner instance identifier.

instance NotRequired[str]

Alias normalized to instance_id when instance_id is unset.

configuration_name NotRequired[str]

Regional or multi-region Spanner instance configuration resource name.

display_name NotRequired[str]

Human-readable display name used when referencing or provisioning an instance.

node_count NotRequired[int]

Allocated node count for the Spanner instance descriptor.

processing_units NotRequired[int]

Allocated processing units for sub-node or granular Spanner instances.

instance_labels NotRequired[dict[str, str]]

Resource labels associated with the Spanner instance.

database_id NotRequired[str]

Target Spanner database identifier within instance_id.

database NotRequired[str]

Alias normalized to database_id when database_id is unset.

db NotRequired[str]

Short alias normalized to database_id when database_id is unset.

ddl_statements NotRequired[tuple[str, ...] | list[str]]

Initial DDL statements associated with the Database handle.

logger NotRequired[Logger]

Custom Python logging.Logger attached to the Spanner Database object.

encryption_config NotRequired[SpannerEncryptionConfig | dict[str, Any]]

Customer-managed Cloud KMS encryption configuration for the database.

database_dialect NotRequired[SpannerDatabaseDialect]

Spanner SQL dialect enum (GOOGLE_STANDARD_SQL or POSTGRESQL).

database_role NotRequired[str]

Fine-grained access control database role assumed by sessions.

enable_drop_protection NotRequired[bool]

Flag indicating whether database drop protection is enabled on the handle.

enable_interceptors_in_tests NotRequired[bool]

Enable gRPC client interceptors when running under test harnesses.

proto_descriptors NotRequired[bytes]

Serialized protobuf FileDescriptorSet bytes associated with the database.

extra NotRequired[dict[str, Any]]

Additional keyword arguments retained in normalized connection configuration.

SpannerPoolParams

Bases: SpannerConnectionParams

Session pool configuration.

pool_type must be a sync pool class for :class:SpannerSyncConfig (default FixedSizePool) and an async pool class for :class:SpannerAsyncConfig (default async FixedSizePool).

Attributes:

Name Type Description
pool_type NotRequired[type[SpannerAbstractSessionPool | SpannerAsyncAbstractSessionPool]]

Session pool class (FixedSizePool, BurstyPool, PingingPool, or async equivalents).

size NotRequired[int]

Fixed session count pre-allocated by FixedSizePool or PingingPool.

target_size NotRequired[int]

Target warm session count maintained by BurstyPool.

max_sessions NotRequired[int]

Upper cap on sessions opened concurrently by custom or bursty pools.

default_timeout NotRequired[int | float]

Seconds to wait when borrowing a session from the pool before timing out.

session_labels NotRequired[dict[str, str]]

Key-value labels attached to sessions created by the pool.

labels NotRequired[dict[str, str]]

Alias for session_labels forwarded to pool session creation.

ping_interval NotRequired[int]

Background keepalive ping interval in seconds for PingingPool.

max_age_minutes NotRequired[int]

Maximum session age in minutes before pool rotation.

SpannerDriverFeatures

Bases: TypedDict

Driver feature flags configuring Spanner codecs, RPC options, and Batch Write ingestion.

Attributes:

Name Type Description
enable_uuid_conversion NotRequired[bool]

Automatically coerce UUID parameters to strings (defaults to True).

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

Custom JSON serializer for JSON parameter payloads.

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

Custom JSON deserializer for JSON column values.

retry NotRequired[SpannerRetry | None]

Default google.api_core.retry.Retry policy passed to execute_sql, execute_update, and batch_update.

timeout NotRequired[float | None]

Default per-RPC timeout in seconds passed to execute_sql, execute_update, and batch_update.

query_options NotRequired[QueryOptions | dict[str, Any] | None]

Default ExecuteSqlRequest.QueryOptions forwarded to SQL execution calls.

request_options NotRequired[SpannerRequestOptions | dict[str, Any] | None]

Default RequestOptions (priority, request tag, transaction tag) forwarded to statement RPCs.

directed_read_options NotRequired[SpannerDirectedReadOptions | None]

Default DirectedReadOptions forwarded to snapshot execute_sql reads.

session_labels NotRequired[dict[str, str]]

Deprecated compatibility alias for connection_config['session_labels'].

enable_events NotRequired[bool]

Enable SQLSpec table-backed event channel support.

events_backend NotRequired[Literal['poll_queue']]

Event queue backend name ('poll_queue').

enable_batch_write_api NotRequired[bool]

Route load_from_arrow through Spanner batch_write mutation groups instead of single-transaction mutations (defaults to False).

Driver & Pool

SpannerSyncDriver

Bases: SyncDriverAdapterBase

Synchronous Spanner driver operating on Snapshot or Transaction contexts.

SpannerAsyncDriver

Bases: AsyncDriverAdapterBase

Asynchronous Spanner driver operating on AsyncSnapshot or AsyncTransaction contexts.

SpannerSyncExceptionHandler

Bases: BaseSyncExceptionHandler

Map Spanner client exceptions to SQLSpec exceptions stored on pending_exception.

SpannerAsyncExceptionHandler

Bases: BaseAsyncExceptionHandler

Map async Spanner client exceptions to SQLSpec exceptions stored on pending_exception.

Extension Stores

SpannerSyncStore

Bases: _SpannerLitestarStoreCommonMixin, BaseSQLSpecStore['SpannerSyncConfig']

Spanner-backed Litestar session store using sync driver wrapped as async.

SpannerAsyncStore

Bases: _SpannerLitestarStoreCommonMixin, BaseSQLSpecStore['SpannerAsyncConfig']

Spanner-backed Litestar session store using native async Spanner client.

SpannerSyncADKStore

Bases: _SpannerADKStoreMixin, BaseSyncADKStore[SpannerSyncConfig]

Spanner ADK store backed by synchronous Spanner client.

SpannerAsyncADKStore

Bases: _SpannerADKStoreMixin, BaseAsyncADKStore[SpannerAsyncConfig]

Spanner ADK store backed by asynchronous Spanner client.

SpannerSyncADKMemoryStore

Bases: _SpannerADKMemoryStoreMixin, BaseSyncADKMemoryStore[SpannerSyncConfig]

Spanner ADK memory store backed by synchronous Spanner client.

SpannerAsyncADKMemoryStore

Bases: _SpannerADKMemoryStoreMixin, BaseAsyncADKMemoryStore[SpannerAsyncConfig]

Spanner ADK memory store backed by asynchronous Spanner client.

SpannerSyncADKArtifactStore

Bases: BaseSyncADKArtifactStore[SpannerSyncConfig], _SpannerADKArtifactStoreMixin

Spanner ADK artifact store backed by synchronous Spanner client.

SpannerAsyncADKArtifactStore

Bases: BaseAsyncADKArtifactStore[SpannerAsyncConfig], _SpannerADKArtifactStoreMixin

Spanner ADK artifact store backed by asynchronous Spanner client.

SpannerSyncEventQueueStore

Bases: _SpannerEventStoreMixin, BaseEventQueueStore[SpannerSyncConfig]

Spanner event queue store for synchronous configs.

Spanner does not support IF NOT EXISTS, so statements must be executed with proper error handling for existing objects.

Parameters:

Name Type Description Default
config ConfigT

SpannerSyncConfig with extension_config["events"] settings.

required

SpannerAsyncEventQueueStore

Bases: _SpannerEventStoreMixin, BaseEventQueueStore[SpannerAsyncConfig]

Spanner event queue store for asynchronous configs.

Spanner does not support IF NOT EXISTS, so statements must be executed with proper error handling for existing objects.

Parameters:

Name Type Description Default
config ConfigT

SpannerAsyncConfig with extension_config["events"] settings.

required