Spanner#
Google Cloud Spanner adapter using the Spanner client library with session pool management.
Request And Session Controls#
Spanner request behavior stays on the existing execution APIs. SQLSpec does not
expose public execute_with_options(), execute_partitioned_dml(),
apply_mutations(), or provide_batch_snapshot() methods.
Default request controls can be configured through
SpannerSyncConfig.driver_features:
request_optionsForwarded to Spanner
execute_sql(),execute_update(), andbatch_update()calls. Use this for request tags, transaction tags, and priority options supported by the Google Cloud Spanner client.directed_read_optionsForwarded only to read calls that use
execute_sql(). Directed reads are not forwarded to DML calls.retryandtimeoutForwarded to Spanner statement execution calls when provided.
Per-call overrides use the existing execute(), execute_many(), and
execute_script() methods:
result = driver.execute(
"SELECT id FROM users WHERE id = @id",
id="u-1",
request_options={"request_tag": "users.lookup"},
directed_read_options=directed_read_options,
timeout=10.0,
)
directed_read_options only applies to read statements. The driver accepts
the argument for a DML statement so call sites can share option plumbing, but it
does not forward directed-read options to execute_update() or
batch_update().
Session-Scoped Controls#
SpannerSyncConfig.provide_session() also accepts explicit Spanner controls
for the returned session context:
with config.provide_session(
request_options={"transaction_tag": "orders.write"},
retry=retry,
timeout=20.0,
) as driver:
driver.execute("UPDATE orders SET status = @status WHERE id = @id", status="paid", id="o-1")
The explicit provide_session() arguments are copied into the returned
driver's feature set and do not mutate config.driver_features. They also do
not hide a database_provider feature for unrelated database-level methods.
provide_read_session() is the read-only helper for single-use snapshot
reads. For DDL, DML, and write-capable transactions, use provide_session()
or provide_write_session().
Configuration#
- class sqlspec.adapters.spanner.SpannerSyncConfig[source]#
Bases:
SyncDatabaseConfig[SpannerConnection,AbstractSessionPool,SpannerSyncDriver]Spanner configuration and session management.
- driver_type#
alias of
SpannerSyncDriver
- __init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]#
- provide_connection(*args, transaction=True, **kwargs)[source]#
Yield a Transaction (default) or Snapshot context from the configured pool.
- Parameters:
*args¶ (
Any) -- Additional positional arguments (unused, for interface compatibility).transaction¶ (
bool) -- If True (default), yields a Transaction context that supports execute_update() for DML statements. If False, yields a read-only Snapshot context for SELECT queries.**kwargs¶ (
Any) -- Additional keyword arguments (unused, for interface compatibility).
- Return type:
SpannerConnectionContext
- provide_session(*args, statement_config=None, transaction=True, request_options=None, directed_read_options=None, retry=None, timeout=None, **kwargs)[source]#
Provide a Spanner driver session context manager.
Returns a write-capable Transaction session by default, matching every other sqlspec adapter. Pass
transaction=Falseor useprovide_read_session()to obtain a read-only Snapshot session.- Parameters:
statement_config¶ (
StatementConfig|None) -- Optional statement configuration override.transaction¶ (
bool) -- Whether to use a Transaction (True, default) or Snapshot (False).request_options¶ (
RequestOptions|dict[str, typing.Any] |None) -- Session-scoped RequestOptions for Spanner statements.directed_read_options¶ (
DirectedReadOptions|None) -- Session-scoped DirectedReadOptions for reads.retry¶ (
Retry|None) -- Session-scoped retry policy for Spanner statement calls.timeout¶ (
float|None) -- Session-scoped timeout for Spanner statement calls.
- Return type:
SpannerSessionContext- Returns:
A Spanner driver session context manager.
- provide_write_session(*args, statement_config=None, request_options=None, directed_read_options=None, retry=None, timeout=None, **kwargs)[source]#
Provide a write-capable Spanner session (alias for
provide_session()).- Return type:
SpannerSessionContext
- provide_read_session(*args, statement_config=None, request_options=None, directed_read_options=None, retry=None, timeout=None, **kwargs)[source]#
Provide a read-only Snapshot Spanner session.
Use for query workloads that benefit from Spanner's snapshot reads. For DDL/DML, use
provide_session()(write-capable by default).- Return type:
SpannerSessionContext
Custom Dialects#
Spanner uses the Spanner and Spangres dialects for SQL compilation. See the Dialects reference for details.
Driver#
- class sqlspec.adapters.spanner.SpannerSyncDriver[source]#
Bases:
SyncDriverAdapterBaseSynchronous Spanner driver operating on Snapshot or Transaction contexts.
- __init__(connection, statement_config=None, driver_features=None)[source]#
Initialize driver adapter with connection and configuration.
- Parameters:
- dispatch_execute(cursor, statement)[source]#
Execute a single SQL statement.
Must be implemented by each driver for database-specific execution logic.
- dispatch_select_stream(statement, chunk_size)[source]#
Adapter hook returning a native row stream, or None when unsupported.
- dispatch_execute_many(cursor, statement)[source]#
Execute SQL with multiple parameter sets (executemany).
Must be implemented by each driver for database-specific executemany logic.
- dispatch_execute_script(cursor, statement)[source]#
Execute a SQL script containing multiple statements.
Default implementation splits the script and executes statements individually. Drivers can override for database-specific script execution methods.
- with_cursor(connection)[source]#
Create and return a context manager for cursor acquisition and cleanup.
Returns a context manager that yields a cursor for database operations. Concrete implementations handle database-specific cursor creation and cleanup.
- Return type:
SpannerSyncCursor
- handle_database_exceptions()[source]#
Handle database-specific exceptions and wrap them appropriately.
- Return type:
SpannerExceptionHandler- Returns:
Exception handler with deferred exception pattern for mypyc compatibility. The handler stores mapped exceptions in pending_exception rather than raising from __exit__ to avoid ABI boundary violations.
- execute(statement, /, *parameters, statement_config=None, **kwargs)[source]#
Execute a statement with optional Spanner per-call request options.
- execute_many(statement, /, parameters, *filters, statement_config=None, **kwargs)[source]#
Execute a batch statement with optional Spanner per-call request options.
- execute_script(statement, /, *parameters, statement_config=None, **kwargs)[source]#
Execute a multi-statement script with optional Spanner per-call request options.
- select_stream(statement, /, *parameters, schema_type=None, statement_config=None, chunk_size=1000, native_only=False, **kwargs)[source]#
Execute a query and stream rows with optional Spanner per-call options.
- Overloads:
self, statement (SQL | Statement | QueryBuilder), parameters (StatementParameters | StatementFilter), schema_type (type[SchemaT]), statement_config (StatementConfig | None), chunk_size (int), native_only (bool), kwargs (Any) → SyncRowStream[SchemaT]
self, statement (SQL | Statement | QueryBuilder), parameters (StatementParameters | StatementFilter), schema_type (None), statement_config (StatementConfig | None), chunk_size (int), native_only (bool), kwargs (Any) → SyncRowStream[dict[str, Any]]
- select_to_storage(statement, destination, /, *parameters, statement_config=None, partitioner=None, format_hint=None, telemetry=None, **kwargs)[source]#
Execute query and stream Arrow results to storage.
- Return type:
- load_from_arrow(table, source, *, partitioner=None, overwrite=False, telemetry=None)[source]#
Load Arrow data into Spanner table via batch mutations.
- Return type:
- load_from_storage(table, source, *, file_format, partitioner=None, overwrite=False)[source]#
Load artifacts from storage into Spanner table.
- Return type:
- property data_dictionary: SpannerDataDictionary#
Get the data dictionary for this driver.
- Returns:
Data dictionary instance for metadata queries
- collect_rows(cursor, fetched)[source]#
Collect Spanner rows for the direct execution path.
Note: Spanner's collect_rows requires result set fields and a type converter. The direct execution path may not always have this metadata available, so this falls back to basic collection.
For the direct path, if result set fields metadata is not available, it returns raw data with no column names. If rows are dicts, it attempts to extract column names from dict keys. For tuple rows without metadata, it returns them as-is.
Data Dictionary#
- class sqlspec.adapters.spanner.data_dictionary.SpannerDataDictionary[source]#
Bases:
SyncDataDictionaryBaseFetch table, column, and index metadata from Spanner.
- dialect: ClassVar[str] = 'spanner'#
Dialect identifier. Must be defined by subclasses as a class attribute.
- get_version(driver)[source]#
Get Spanner version information.
- Parameters:
driver¶ (
SpannerSyncDriver) -- Spanner driver instance.- Return type:
VersionInfo|None- Returns:
None since Spanner does not expose version information.
- get_feature_flag(driver, feature)[source]#
Check if Spanner supports a specific feature.
- Parameters:
driver¶ (
SpannerSyncDriver) -- Spanner driver instance.
- Return type:
- Returns:
True if feature is supported, False otherwise.
- get_optimal_type(driver, type_category)[source]#
Get optimal Spanner type for a category.
- Parameters:
driver¶ (
SpannerSyncDriver) -- Spanner driver instance.
- Return type:
- Returns:
Spanner-specific type name.
- get_tables(driver, schema=None)[source]#
Get tables using INFORMATION_SCHEMA.
- Return type:
list[TableMetadata]
- get_columns(driver, table=None, schema=None)[source]#
Get column information for a table or schema.
- Return type:
list[ColumnMetadata]
- get_indexes(driver, table=None, schema=None)[source]#
Get index metadata for a table or schema.
- Return type:
list[IndexMetadata]
- get_foreign_keys(driver, table=None, schema=None)[source]#
Get foreign key metadata.
- Return type:
list[ForeignKeyMetadata]