-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(spanner): add asynchronous code snippets and minor cleanup changes #17337
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
117 changes: 117 additions & 0 deletions
117
packages/google-cloud-spanner/samples/samples/async_snippets.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| #!/usr/bin/env python | ||
|
|
||
| # Copyright 2026 Google LLC All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """This application demonstrates how to do basic asynchronous operations using | ||
| Cloud Spanner. | ||
| """ | ||
|
|
||
| import asyncio | ||
| from google.cloud.spanner_v1 import AsyncClient | ||
| from google.cloud.spanner_v1 import KeySet | ||
|
|
||
| # [START spanner_async_create_client] | ||
| async def async_create_client(instance_id, database_id): | ||
| """Instantiates an asynchronous Spanner client.""" | ||
| spanner_client = AsyncClient() | ||
| instance = spanner_client.instance(instance_id) | ||
| database = instance.database(database_id) | ||
|
|
||
| print("Async Spanner client instantiated successfully.") | ||
| return database | ||
| # [END spanner_async_create_client] | ||
|
|
||
|
|
||
| # [START spanner_async_query_data] | ||
| async def async_query_data(instance_id, database_id): | ||
| """Queries sample data from the database using asynchronous SQL.""" | ||
| spanner_client = AsyncClient() | ||
| instance = spanner_client.instance(instance_id) | ||
| database = instance.database(database_id) | ||
|
|
||
| async with database.snapshot() as snapshot: | ||
| results = await snapshot.execute_sql( | ||
| "SELECT SingerId, AlbumId, AlbumTitle FROM Albums" | ||
| ) | ||
|
|
||
| async for row in results: | ||
| print("SingerId: {}, AlbumId: {}, AlbumTitle: {}".format(*row)) | ||
| # [END spanner_async_query_data] | ||
|
|
||
|
|
||
| # [START spanner_async_insert_data] | ||
| async def async_insert_data(instance_id, database_id): | ||
| """Inserts sample data into the database using DML asynchronously.""" | ||
| spanner_client = AsyncClient() | ||
| instance = spanner_client.instance(instance_id) | ||
| database = instance.database(database_id) | ||
|
|
||
| async def insert_singers(transaction): | ||
| dml = ( | ||
| "INSERT INTO Singers (SingerId, FirstName, LastName) VALUES " | ||
| "(12, 'Melissa', 'Garcia'), " | ||
| "(13, 'Russell', 'Morales')" | ||
| ) | ||
| await transaction.execute_update(dml) | ||
|
|
||
| await database.run_in_transaction(insert_singers) | ||
| print("Async DML Insert transaction complete.") | ||
| # [END spanner_async_insert_data] | ||
|
|
||
|
|
||
| # [START spanner_async_read_write_transaction] | ||
| async def async_read_write_transaction(instance_id, database_id): | ||
| """Performs an asynchronous read-write transaction.""" | ||
| spanner_client = AsyncClient() | ||
| instance = spanner_client.instance(instance_id) | ||
| database = instance.database(database_id) | ||
|
|
||
| async def update_singer_lastname(transaction): | ||
| # Retrieve current name | ||
| results = await transaction.execute_sql( | ||
| "SELECT SingerId, FirstName, LastName FROM Singers WHERE SingerId = 12" | ||
| ) | ||
| async for row in results: | ||
| print("Before Update - SingerId: {}, FirstName: {}, LastName: {}".format(*row)) | ||
|
|
||
| # Update LastName | ||
| await transaction.execute_update( | ||
| "UPDATE Singers SET LastName = 'Jackson' WHERE SingerId = 12" | ||
| ) | ||
|
|
||
| await database.run_in_transaction(update_singer_lastname) | ||
| print("Async read-write transaction complete.") | ||
| # [END spanner_async_read_write_transaction] | ||
|
|
||
|
|
||
| # [START spanner_async_read_only_transaction] | ||
| async def async_read_only_transaction(instance_id, database_id): | ||
| """Performs an asynchronous read-only transaction.""" | ||
| spanner_client = AsyncClient() | ||
| instance = spanner_client.instance(instance_id) | ||
| database = instance.database(database_id) | ||
|
|
||
| async with database.snapshot() as snapshot: | ||
| # Execute a read using standard KeySet | ||
| keyset = KeySet(all_=True) | ||
| results = await snapshot.read( | ||
| table="Singers", | ||
| columns=("SingerId", "FirstName", "LastName"), | ||
| keyset=keyset, | ||
| ) | ||
|
|
||
| async for row in results: | ||
| print("Read Row - SingerId: {}, FirstName: {}, LastName: {}".format(*row)) | ||
| # [END spanner_async_read_only_transaction] |
77 changes: 77 additions & 0 deletions
77
packages/google-cloud-spanner/samples/samples/async_snippets_test.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| # Copyright 2026 Google LLC All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import pytest | ||
| import async_snippets | ||
|
|
||
| @pytest.fixture(scope="module") | ||
| def database_ddl(): | ||
| """DDL statements to set up the database for testing async snippets.""" | ||
| return [ | ||
| """CREATE TABLE Singers ( | ||
| SingerId INT64 NOT NULL, | ||
| FirstName STRING(1024), | ||
| LastName STRING(1024), | ||
| SingerInfo BYTES(MAX) | ||
| ) PRIMARY KEY (SingerId)""", | ||
| """CREATE TABLE Albums ( | ||
| SingerId INT64 NOT NULL, | ||
| AlbumId INT64 NOT NULL, | ||
| AlbumTitle STRING(MAX) | ||
| ) PRIMARY KEY (SingerId, AlbumId), | ||
| INTERLEAVE IN PARENT Singers ON DELETE CASCADE""" | ||
| ] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_async_snippets_flow(capsys, instance_id, sample_database): | ||
| # 1. Test Async Spanner Client Creation | ||
| db = await async_snippets.async_create_client(instance_id, sample_database.database_id) | ||
| assert db is not None | ||
| out, _ = capsys.readouterr() | ||
| assert "Async Spanner client instantiated successfully." in out | ||
|
|
||
| # 2. Test Async DML Insert | ||
| await async_snippets.async_insert_data(instance_id, sample_database.database_id) | ||
| out, _ = capsys.readouterr() | ||
| assert "Async DML Insert transaction complete." in out | ||
|
|
||
| # 3. Seed additional albums data via sync batch write for query testing | ||
| with sample_database.batch() as batch: | ||
| batch.insert( | ||
| table="Albums", | ||
| columns=("SingerId", "AlbumId", "AlbumTitle"), | ||
| values=[ | ||
| (12, 1, "Total Junk"), | ||
| (13, 2, "Go, Go, Go"), | ||
| ], | ||
| ) | ||
|
|
||
| # 4. Test Async Query Data | ||
| await async_snippets.async_query_data(instance_id, sample_database.database_id) | ||
| out, _ = capsys.readouterr() | ||
| assert "SingerId: 12, AlbumId: 1, AlbumTitle: Total Junk" in out | ||
| assert "SingerId: 13, AlbumId: 2, AlbumTitle: Go, Go, Go" in out | ||
|
|
||
| # 5. Test Async Read-Write Transaction | ||
| await async_snippets.async_read_write_transaction(instance_id, sample_database.database_id) | ||
| out, _ = capsys.readouterr() | ||
| assert "Before Update - SingerId: 12, FirstName: Melissa, LastName: Garcia" in out | ||
| assert "Async read-write transaction complete." in out | ||
|
|
||
| # 6. Test Async Read-Only Transaction | ||
| await async_snippets.async_read_only_transaction(instance_id, sample_database.database_id) | ||
| out, _ = capsys.readouterr() | ||
| assert "Read Row - SingerId: 12, FirstName: Melissa, LastName: Jackson" in out | ||
| assert "Read Row - SingerId: 13, FirstName: Russell, LastName: Morales" in out |
3 changes: 1 addition & 2 deletions
3
packages/google-cloud-spanner/tests/mockserver_tests/test_dbapi_partition_query.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 1 addition & 2 deletions
3
packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_partition_helper.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.