Registry / gcp / google-cloud-spanner

google-cloud-spanner

JSON →
library3.70.0pypypi✓ verified 24d ago

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.

pip install google-cloud-spanner
INSTALL
IMPORT
SIG · GOOGLE-CLOUD-SPANN
G
google-cloud-spanner
gcppythonv3.70.0
Install
6.9s avg
Import
2525ms
Disk
84MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.70.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 3.162s · 85MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 6.9s · import 1.888s · 83MB
84MB installed
● package 84MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Client
from google.cloud import spanner
This is the primary high-level client for interacting with Spanner.
Connection (DB-API)
from google.cloud.spanner_v1.database import SpannerConnection
from google.cloud import spanner_v1
While `spanner_v1` contains lower-level client components, the DB-API `connect` function or `SpannerConnection` class from `spanner_v1.database` is typically used for a PEP 249-compliant interface. Direct usage of `spanner_v1` without a specific class is not the common pattern for establishing a connection.

This quickstart demonstrates how to initialize a Cloud Spanner client, connect to an existing instance and database, and execute a simple SQL query. Ensure you have authenticated your Google Cloud environment (e.g., via `gcloud auth application-default login`) and set the `GOOGLE_CLOUD_PROJECT`, `SPANNER_INSTANCE_ID`, and `SPANNER_DATABASE_ID` environment variables or replace the placeholders.

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)
Debug
Known issues
breakingPython 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.
fix
Upgrade your Python environment to 3.9 or a newer supported version.
affects: >=3.58.0
gotchaSpanner'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.
fix
Wrap your data modification logic within `database.run_in_transaction` callback functions.
affects: All
gotchaCloud 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.
fix
Develop against the Spanner emulator, but ensure thorough testing on a cloud Spanner instance before deployment. Be aware of potential behavioral discrepancies.
affects: All
gotchaPoorly 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.
fix
Follow Spanner best practices for schema design, including primary key choices and interleaved tables. Use query plans and Spanner monitoring tools to identify and optimize slow queries, leveraging secondary indexes where appropriate (explicitly with `FORCE_INDEX` if needed).
affects: All
bugA 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.
fix
Upgrade `google-cloud-spanner` to version 3.63.0 or higher to benefit from the fix.
affects: <3.63.0
Errors
Common errors & fixes
google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded
The Spanner operation exceeded the configured timeout, often due to heavy load, unoptimized queries, schema issues, or network latency.
fix
Investigate Spanner instance CPU utilization and query statistics, optimize SQL queries and database schema, check for lock contention, and ensure client library default timeouts are not overridden with overly aggressive values.
com.google.cloud.spanner.SpannerException: NOT_FOUND: Session not found
The application attempted to use a Spanner session that no longer exists, typically due to explicit deletion, prolonged inactivity, or an exhausted session pool caused by uncommitted transactions.
fix
Ensure all transactions (read-only and read-write) are explicitly committed or rolled back; if using client libraries, avoid prematurely closing database clients. If the session pool is consistently exhausted, review session pool configurations (e.g., `max_sessions`) and consider adding simple 'keep-alive' queries for idle connections.
google.auth.exceptions.DefaultCredentialsError: Could not find default credentials.
The application failed to locate valid Google Cloud authentication credentials, or the authenticated principal lacks the necessary IAM permissions for Spanner access.
fix
For local development, run `gcloud auth application-default login` or set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to a service account key file path. For deployed applications, ensure the associated service account has the required Spanner IAM roles (e.g., `roles/spanner.databaseUser`).
google.api_core.exceptions.NotFound: 404 Instance not found: projects/<project-id>/instances/<instance-id>
The specified Spanner instance or database ID is incorrect, misspelled, or the authenticated identity does not have permission to view it in the specified Google Cloud project.
fix
Verify that the project ID, instance ID, and database ID are correct and free of typos. Ensure the authenticated Google Cloud identity (user or service account) has appropriate IAM permissions to view and interact with the Spanner instance and database.
Upgrade
Version history
3.70.0latest on PyPI · released Aug 24, 2026
Audit
Dependencies

No dependency data recorded yet.

Agent activity
25 hits · last 30 days
node
20
OpenAI (training)
1
Resources