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 |
credentials |
NotRequired[SpannerCredentials]
|
Explicit |
client_info |
NotRequired[SpannerClientInfo]
|
Custom |
client_options |
NotRequired[SpannerClientOptions | dict[str, Any]]
|
GAPIC |
query_options |
NotRequired[QueryOptions]
|
Client-wide default |
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 |
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 |
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 |
database |
NotRequired[str]
|
Alias normalized to |
db |
NotRequired[str]
|
Short alias normalized to |
ddl_statements |
NotRequired[tuple[str, ...] | list[str]]
|
Initial DDL statements associated with the |
logger |
NotRequired[Logger]
|
Custom Python |
encryption_config |
NotRequired[SpannerEncryptionConfig | dict[str, Any]]
|
Customer-managed Cloud KMS encryption configuration for the database. |
database_dialect |
NotRequired[SpannerDatabaseDialect]
|
Spanner SQL dialect enum ( |
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 |
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 |
json_serializer |
NotRequired[Callable[[Any], str]]
|
Custom JSON serializer for |
json_deserializer |
NotRequired[Callable[[str], Any]]
|
Custom JSON deserializer for |
retry |
NotRequired[SpannerRetry | None]
|
Default |
timeout |
NotRequired[float | None]
|
Default per-RPC timeout in seconds passed to |
query_options |
NotRequired[QueryOptions | dict[str, Any] | None]
|
Default |
request_options |
NotRequired[SpannerRequestOptions | dict[str, Any] | None]
|
Default |
directed_read_options |
NotRequired[SpannerDirectedReadOptions | None]
|
Default |
session_labels |
NotRequired[dict[str, str]]
|
Deprecated compatibility alias for |
enable_events |
NotRequired[bool]
|
Enable SQLSpec table-backed event channel support. |
events_backend |
NotRequired[Literal['poll_queue']]
|
Event queue backend name ( |
enable_batch_write_api |
NotRequired[bool]
|
Route |
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
¶
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 a Partitioned DML statement against the Spanner database.
write_insert
¶
Buffer Spanner INSERT mutations on the active transaction or batch.
write_upsert
¶
Buffer Spanner INSERT_OR_UPDATE mutations on the active transaction or batch.
write_update
¶
Buffer Spanner UPDATE mutations on the active transaction or batch.
write_delete
¶
Buffer a Spanner DELETE mutation on the active transaction or batch.
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
¶
SpannerAsyncDataDictionary
¶
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 |