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 and the Spanner (GoogleSQL) and Spangres (PostgreSQL) Data Dictionary SQL Catalogs.

Configuration & Parameters

See the full connection and pool parameter table for pool settings, types, and defaults.

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

SpannerDriverFeatures

Bases: TypedDict

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

Attributes:

Name Type Description
default_staleness NotRequired[Mapping[str, Any]]

Default timestamp bound for read-only snapshot providers.

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

on_connection_create NotRequired[Callable[[Any], Any | None] | None]

Callback invoked after a new Spanner connection (Snapshot or Transaction) is created.

Driver, Pool & Data Dictionary

SpannerSyncDriver

Synchronous Spanner driver operating on Snapshot or Transaction contexts.

run_in_transaction

run_in_transaction(fn, *args, **kwargs)

Execute a callable inside Spanner's retryable transaction runner.

fn is called as fn(driver, *args, **kwargs) with a driver bound to the runner's transaction. A DeadlockError caused by google.api_core.exceptions.Aborted is unwrapped so the runner retries, and a terminal Aborted is raised as DeadlockError.

execute_partitioned_dml

execute_partitioned_dml(sql, params=None, param_types=None, **kwargs)

Execute a Partitioned DML statement against the Spanner database.

write_insert

write_insert(table, columns, values)

Buffer Spanner INSERT mutations on the active transaction or batch.

write_upsert

write_upsert(table, columns, values)

Buffer Spanner INSERT_OR_UPDATE mutations on the active transaction or batch.

write_update

write_update(table, columns, values)

Buffer Spanner UPDATE mutations on the active transaction or batch.

write_delete

write_delete(table, keyset)

Buffer a Spanner DELETE mutation on the active transaction or batch.

bind_external_transaction

bind_external_transaction()

Mark the driver as bound to an externally managed transaction runner.

SpannerAsyncDriver

Asynchronous Spanner driver operating on AsyncSnapshot or AsyncTransaction contexts.

run_in_transaction(fn, *args, **kwargs)

Execute a coroutine function inside Spanner's async retryable transaction runner.

fn is awaited as fn(driver, *args, **kwargs) with a driver bound to the runner's transaction. A DeadlockError caused by google.api_core.exceptions.Aborted is unwrapped so the runner retries, and a terminal Aborted is raised as DeadlockError.

execute_partitioned_dml(sql, params=None, param_types=None, **kwargs)

Execute a Partitioned DML statement against the async Spanner database.

write_insert(table, columns, values)

Buffer Spanner INSERT mutations on the active async transaction or batch.

write_upsert(table, columns, values)

Buffer Spanner INSERT_OR_UPDATE mutations on the active async transaction or batch.

write_update(table, columns, values)

Buffer Spanner UPDATE mutations on the active async transaction or batch.

write_delete(table, keyset)

Buffer a Spanner DELETE mutation on the active async transaction or batch.

bind_external_transaction()

Mark the driver as bound to an externally managed transaction runner.

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.

SpannerSyncDataDictionary

Bases: SyncDataDictionaryBase

Fetch table, column, and index metadata from Spanner.

SpannerAsyncDataDictionary

Bases: AsyncDataDictionaryBase

Fetch table, column, and index metadata from Spanner.

Extension Stores & Configs

SpannerLitestarConfig

Bases: LitestarConfig

Spanner-specific Litestar settings.

Use inside extension_config["litestar"] with this adapter's session store. Note: Cloud Spanner Litestar store currently requires GoogleSQL dialect.

Attributes:

Name Type Description
shard_count NotRequired[int]

Number of session key shards.

table_options NotRequired[str]

Table DDL options.

index_options NotRequired[str]

Index DDL options.

enable_row_deletion_policy NotRequired[bool]

Whether to enable Spanner native ROW DELETION POLICY for session expiration.

SpannerSyncStore

Bases: _SpannerLitestarStoreCommonMixin, BaseSQLSpecStore['SpannerSyncConfig']

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

Note: Cloud Spanner Litestar store currently requires GoogleSQL dialect.

SpannerAsyncStore

Bases: _SpannerLitestarStoreCommonMixin, BaseSQLSpecStore['SpannerAsyncConfig']

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

SpannerADKConfig

Bases: ADKConfig

Spanner-specific ADK extension settings.

Attributes:

Name Type Description
shard_count NotRequired[int]

Generated shard count for hot key mitigation.

session_table_options NotRequired[str]

Raw Spanner OPTIONS clause content for the ADK session table.

events_table_options NotRequired[str]

Raw Spanner OPTIONS clause content for the ADK events table.

memory_table_options NotRequired[str]

Raw Spanner OPTIONS clause content for the ADK memory table.

expires_index_options NotRequired[str]

Raw Spanner OPTIONS clause content for expiration indexes.

retention NotRequired[SpannerADKRetentionConfig]

Spanner row-deletion retention policy settings.

vector_dimensions NotRequired[int | None]

Optional fixed dimensionality for the memory embedding column.

vector_distance_type NotRequired[str]

Distance metric for the memory vector index ('COSINE', 'EUCLIDEAN', 'DOT_PRODUCT').

vector_index_enabled NotRequired[bool]

Whether to emit CREATE VECTOR INDEX for the memory table.

scann_tree_depth NotRequired[int]

ScaNN tree depth for the memory vector index (2 or 3).

scann_num_leaves NotRequired[int]

ScaNN leaf count for the memory vector index.

enable_hybrid_search NotRequired[bool]

Enable Reciprocal Rank Fusion when both embedding and FTS query are supplied.

enable_memory_graph NotRequired[bool]

Emit CREATE OR REPLACE PROPERTY GRAPH over the ADK memory table.

memory_graph_name NotRequired[str]

Name of the Spanner Property Graph created over the ADK memory table.

SpannerADKRetentionConfig

Bases: TypedDict

Spanner-specific ADK row-deletion policy settings.

Attributes:

Name Type Description
session_ttl_seconds NotRequired[int]

Session row retention in seconds.

event_ttl_seconds NotRequired[int]

Event row retention in seconds.

memory_ttl_seconds NotRequired[int]

Memory row retention in seconds.

artifact_ttl_seconds NotRequired[int]

Artifact row retention in seconds.

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