Spanner

Google Cloud Spanner adapter using the Spanner client library with session pool management.

Configuration

class sqlspec.adapters.spanner.SpannerSyncConfig[source]

Bases: SyncDatabaseConfig[SpannerConnection, AbstractSessionPool, SpannerSyncDriver]

Spanner configuration and session management.

driver_type

alias of SpannerSyncDriver

connection_type

alias of Any

__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]
create_connection()[source]

Create a database connection.

Return type:

Any

provide_connection(*args, transaction=False, **kwargs)[source]

Yield a Snapshot (default) or Transaction context from the configured pool.

Parameters:
  • *args (Any) – Additional positional arguments (unused, for interface compatibility).

  • transaction (bool) – If True, yields a Transaction context that supports execute_update() for DML statements. If False (default), 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=False, **kwargs)[source]

Provide a Spanner driver session context manager.

Parameters:
  • *args (Any) – Additional arguments.

  • statement_config (StatementConfig | None) – Optional statement configuration override.

  • transaction (bool) – Whether to use a transaction.

  • **kwargs (Any) – Additional keyword arguments.

Return type:

SpannerSessionContext

Returns:

A Spanner driver session context manager.

provide_write_session(*args, statement_config=None, **kwargs)[source]

Provide a Spanner driver write session context manager.

Parameters:
  • *args (Any) – Additional arguments.

  • statement_config (StatementConfig | None) – Optional statement configuration override.

  • **kwargs (Any) – Additional keyword arguments.

Return type:

SpannerSessionContext

Returns:

A Spanner driver write session context manager.

get_signature_namespace()[source]

Get the signature namespace for SpannerSyncConfig types.

Return type:

dict[str, typing.Any]

Returns:

Dictionary mapping type names to types.

get_event_runtime_hints()[source]

Return queue defaults for Spanner JSON handling.

Return type:

EventRuntimeHints

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: SyncDriverAdapterBase

Synchronous 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:
  • connection (Any) – Database connection instance

  • statement_config (StatementConfig | None) – Statement configuration for the driver

  • driver_features (dict[str, typing.Any] | None) – Driver-specific features like extensions, secrets, and connection callbacks

  • observability – Optional runtime handling lifecycle hooks, observers, and spans

dispatch_execute(cursor, statement)[source]

Execute a single SQL statement.

Must be implemented by each driver for database-specific execution logic.

Parameters:
  • cursor (Any) – Database cursor/connection object

  • statement (SQL) – SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with execution data

dispatch_execute_many(cursor, statement)[source]

Execute SQL with multiple parameter sets (executemany).

Must be implemented by each driver for database-specific executemany logic.

Parameters:
  • cursor (Any) – Database cursor/connection object

  • statement (SQL) – SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with execution data for the many operation

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.

Parameters:
  • cursor (Any) – Database cursor/connection object

  • statement (SQL) – SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with script execution data including statement counts

begin()[source]

Begin a database transaction on the current connection.

Return type:

None

commit()[source]

Commit the current transaction on the current connection.

Return type:

None

rollback()[source]

Rollback the current transaction on the current connection.

Return type:

None

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.

select_to_arrow(statement, /, *parameters, **kwargs)[source]

Execute query and return results as Apache Arrow format.

This base implementation uses the conversion path: execute() → dict → Arrow. Adapters with native Arrow support (ADBC, DuckDB, BigQuery) override this method to use zero-copy native paths for 5-10x performance improvement.

Parameters:
  • statement (typing.Any) – SQL query string, Statement, or QueryBuilder

  • *parameters (typing.Any) – Query parameters (same format as execute()/select())

  • statement_config – Optional statement configuration override

  • return_format – “table” for pyarrow.Table (default), “batch” for single RecordBatch, “batches” for iterator of RecordBatches, “reader” for RecordBatchReader

  • native_only – If True, raise error if native Arrow unavailable (default: False)

  • batch_size – Rows per batch for “batch”/”batches” format (default: None = all rows)

  • arrow_schema – Optional pyarrow.Schema for type casting

  • **kwargs (Any) – Additional keyword arguments

Return type:

ArrowResult

Returns:

ArrowResult containing pyarrow.Table, RecordBatchReader, or RecordBatches

Raises:

ImproperConfigurationError – If native_only=True and adapter doesn’t support native Arrow

Examples

>>> result = driver.select_to_arrow(
...     "SELECT * FROM users WHERE age > ?", 18
... )
>>> df = result.to_pandas()
>>> print(df.head())
>>> # Force native Arrow path (raises error if unavailable)
>>> result = driver.select_to_arrow(
...     "SELECT * FROM users", native_only=True
... )
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:

StorageBridgeJob

load_from_arrow(table, source, *, partitioner=None, overwrite=False, telemetry=None)[source]

Load Arrow data into Spanner table via batch mutations.

load_from_storage(table, source, *, file_format, partitioner=None, overwrite=False)[source]

Load artifacts from storage into Spanner table.

Return type:

StorageBridgeJob

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.

Return type:

tuple[list[typing.Any], list[str], int]

resolve_rowcount(cursor)[source]

Resolve rowcount from Spanner cursor for the direct execution path.

Return type:

int