Skip to content

feat(spanner): Add multi-use read-only snapshot transaction sample - #14918

Open
iennae wants to merge 2 commits into
feat/spanner-select-for-updatefrom
feat/spanner-read-only-transaction
Open

iennae wants to merge 2 commits into
feat/spanner-select-for-updatefrom
feat/spanner-read-only-transaction

Conversation

@iennae

@iennae iennae commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Description

Adds spanner_read_only_transaction demonstrating consistent multi-statement execute_sql() and read() calls inside database.snapshot(multi_use=True).

Note: Stacked on #14839 (feat/spanner-select-for-update) so this PR shows only this sample's diff. It will merge into main after #14839.

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended. Unit and live integration tests pass on Python 3.13.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

Consistent multi-statement reads share a single snapshot timestamp via database.snapshot(multi_use=True). Add a standalone spanner_read_only_transaction sample combining SQL and KeySet reads.
@iennae
iennae requested review from a team as code owners November 18, 2026 04:53
@product-auto-label product-auto-label Bot added api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples. labels Nov 18, 2026
@snippet-bot

snippet-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new script and corresponding tests to demonstrate executing consistent multi-statement reads inside a multi-use read-only transaction in Cloud Spanner. The review feedback suggests allowing the project_id parameter to accept None and adjusting the CLI argument defaults to enable seamless Application Default Credentials (ADC) inference. Additionally, it recommends making the NotFound exception error message more generic, as the exception can be raised if the table is missing, not just the database.

from google.cloud import spanner


def read_only_transaction(project_id: str, instance_id: str, database_id: str) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To allow the project ID to be inferred from Application Default Credentials (ADC) when it is not explicitly provided, update the project_id parameter type to accept None.

Suggested change
def read_only_transaction(project_id: str, instance_id: str, database_id: str) -> None:
def read_only_transaction(project_id: str | None, instance_id: str, database_id: str) -> None:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Comment on lines +43 to +48
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' on instance '{instance_id}' "
f"was not found: {err.message}",
file=sys.stderr,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The exceptions.NotFound exception can be raised if the Albums table does not exist, not just if the database itself is missing. Printing that the database was not found can be misleading. Consider using a more generic error message that includes the actual exception message.

    except exceptions.NotFound as err:
        print(
            f"error: resource not found: {err.message}",
            file=sys.stderr,
        )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: the message now says a resource was not found in the database and includes the server message (dd48243).

Comment on lines +74 to +77
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

By defaulting --project-id to 'example-project-id', the script prevents the Spanner client from automatically inferring the project ID from Application Default Credentials (ADC) when the argument is omitted and GOOGLE_CLOUD_PROJECT is not set. Defaulting to None (or omitting the default value) allows ADC inference to work seamlessly.

    parser.add_argument(
        "--project-id",
        default=os.environ.get("GOOGLE_CLOUD_PROJECT"),
        help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
    )
References
  1. When using argparse for a command-line script, the --project_id argument can be optional, as the project can be inferred from Application Default Credentials (ADC) if not provided.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Problem: review of this sample identified correctness and robustness
improvements in the sample and its tests.

Solution: apply the accepted review suggestions and extend the tests to
cover the updated behavior. Details are in the review thread replies.

Files updated:
  - spanner/transactions/src/spanner_transactions/read_only_transaction.py
  - spanner/transactions/tests/read_only_transaction_test.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant