Google Cloud Spanner Client Library
The `google-cloud-spanner` client library for Python enables developers to interact with Google Cloud Spanner, a fully managed, horizontally scalable, relational database service. It provides high-level APIs for creating instances and databases, executing SQL queries, managing transactions, and performing schema updates. The library maintains a rapid release cadence, with updates typically occurring on a monthly basis, introducing new features and bug fixes.
Warnings
- breaking Python 3.7 and 3.8 are no longer supported since version 3.58.0. Users on these Python versions must upgrade to Python 3.9 or higher.
- gotcha Spanner's DML and mutations, especially within read-write transactions, require careful transaction management to ensure strong consistency and handle retries for aborted transactions. It is highly recommended to use `database.run_in_transaction` for operations that modify data to automatically handle retry logic.
- gotcha Cloud Spanner does not offer a fully functional local development instance. Developers typically use the Spanner emulator, which mimics Spanner's behavior but might have subtle differences. Full integration testing should be performed against a live Spanner instance.
- gotcha Poorly optimized SQL queries or schema designs, such as DML statements not conditioned on primary keys, can lead to full table scans, lock contention, and significant performance degradation, even though Spanner supports live schema updates.
- bug A thread leak bug related to singleton initialization was present in versions prior to 3.63.0, potentially leading to resource exhaustion over long-running applications.
Install
-
pip install google-cloud-spanner
Imports
- Client
from google.cloud import spanner
- Connection (DB-API)
from google.cloud.spanner_v1.database import SpannerConnection
Quickstart
import os
from google.cloud import spanner
project_id = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-project-id')
instance_id = os.environ.get('SPANNER_INSTANCE_ID', 'your-instance-id')
database_id = os.environ.get('SPANNER_DATABASE_ID', 'your-database-id')
def query_data(project_id, instance_id, database_id):
spanner_client = spanner.Client(project=project_id)
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)
with database.snapshot() as snapshot:
results = snapshot.execute_sql('SELECT 1').fields
for row in results:
print(row)
print(f'Successfully queried data from {database_id} in {instance_id}.')
# Example usage (uncomment to run, ensure environment variables are set or replace placeholders)
# if __name__ == '__main__':
# query_data(project_id, instance_id, database_id)