Repository navigation
Conversation
Bounding individual SQL or DML RPC latency inside a transaction passes timeout to transaction.execute_update(). Add a standalone spanner_set_statement_timeout sample and test suite.
|
Here is the summary of changes. You are about to add 1 region tag.
This comment is generated by snippet-bot.
|
There was a problem hiding this comment.
Code Review
This pull request introduces a new sample script and corresponding tests demonstrating how to execute a Spanner DML statement with an explicit per-statement RPC timeout. The feedback suggests several improvements to make the code more robust and idiomatic: allowing project_id to be optional to leverage Application Default Credentials (ADC) both in the function signature and the CLI argument parser, returning the row count directly from the transaction callback instead of using a nonlocal variable, and replacing the deprecated err.message with str(err) to prevent potential AttributeError exceptions in Python 3.
| def execute_statement_with_timeout( | ||
| project_id: str, instance_id: str, database_id: str | ||
| ) -> None: |
There was a problem hiding this comment.
Allow project_id to be optional (str | None) so that the Spanner client can automatically infer the project ID from Application Default Credentials (ADC) when it is not explicitly provided.
| def execute_statement_with_timeout( | |
| project_id: str, instance_id: str, database_id: str | |
| ) -> None: | |
| def execute_statement_with_timeout( | |
| project_id: str | None, instance_id: str, database_id: str | |
| ) -> None: |
There was a problem hiding this comment.
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.
| inserted_rows = 0 | ||
|
|
||
| def write_with_timeout(transaction: spanner_v1.transaction.Transaction) -> None: | ||
| nonlocal inserted_rows | ||
| inserted_rows = transaction.execute_update( | ||
| "INSERT INTO Singers (SingerId, FirstName, LastName) " | ||
| "VALUES (112, 'George', 'Washington')", | ||
| timeout=60.0, | ||
| ) | ||
|
|
||
| try: | ||
| database.run_in_transaction(write_with_timeout) |
There was a problem hiding this comment.
Instead of using a nonlocal variable to capture the number of inserted rows from within the transaction callback, you can return the value directly from the callback. database.run_in_transaction automatically returns the value returned by the callback function. This is more idiomatic and avoids mutable nonlocal state.
| inserted_rows = 0 | |
| def write_with_timeout(transaction: spanner_v1.transaction.Transaction) -> None: | |
| nonlocal inserted_rows | |
| inserted_rows = transaction.execute_update( | |
| "INSERT INTO Singers (SingerId, FirstName, LastName) " | |
| "VALUES (112, 'George', 'Washington')", | |
| timeout=60.0, | |
| ) | |
| try: | |
| database.run_in_transaction(write_with_timeout) | |
| def write_with_timeout(transaction: spanner_v1.transaction.Transaction) -> int: | |
| return transaction.execute_update( | |
| "INSERT INTO Singers (SingerId, FirstName, LastName) " | |
| "VALUES (112, 'George', 'Washington')", | |
| timeout=60.0, | |
| ) | |
| try: | |
| inserted_rows = database.run_in_transaction(write_with_timeout) |
There was a problem hiding this comment.
Thanks for the suggestion! Keeping this as is for consistency with the rest of this sample set: transaction callbacks record their result in an enclosing variable and the sample prints it after the transaction commits, rather than passing a return value back through run_in_transaction.
| except exceptions.DeadlineExceeded as err: | ||
| print( | ||
| f"error: DML statement exceeded 60s timeout on database " | ||
| f"'{database_id}' in instance '{instance_id}': {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| except exceptions.GoogleAPICallError as err: | ||
| print( | ||
| f"error: statement-timeout transaction failed on database " | ||
| f"'{database_id}' in instance '{instance_id}': {err.message}", | ||
| file=sys.stderr, | ||
| ) |
There was a problem hiding this comment.
In Python 3, accessing err.message is deprecated and can raise an AttributeError on standard exceptions. It is more idiomatic and robust to use str(err) or interpolate the exception object directly in the f-string.
| except exceptions.DeadlineExceeded as err: | |
| print( | |
| f"error: DML statement exceeded 60s timeout on database " | |
| f"'{database_id}' in instance '{instance_id}': {err.message}", | |
| file=sys.stderr, | |
| ) | |
| except exceptions.GoogleAPICallError as err: | |
| print( | |
| f"error: statement-timeout transaction failed on database " | |
| f"'{database_id}' in instance '{instance_id}': {err.message}", | |
| file=sys.stderr, | |
| ) | |
| except exceptions.DeadlineExceeded as err: | |
| print( | |
| f"error: DML statement exceeded 60s timeout on database " | |
| f"'{database_id}' in instance '{instance_id}': {err}", | |
| file=sys.stderr, | |
| ) | |
| except exceptions.GoogleAPICallError as err: | |
| print( | |
| f"error: statement-timeout transaction failed on database " | |
| f"'{database_id}' in instance '{instance_id}': {err}", | |
| file=sys.stderr, | |
| ) |
There was a problem hiding this comment.
Done: the handlers interpolate the exception directly (2ce5eab).
| parser.add_argument( | ||
| "--project-id", | ||
| default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), | ||
| help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)", | ||
| ) |
There was a problem hiding this comment.
Change the default value of --project-id to None (by omitting the fallback string) so that the project ID can be inferred from Application Default Credentials (ADC) if the environment variable GOOGLE_CLOUD_PROJECT is not set, rather than falling back to a placeholder string.
| parser.add_argument( | |
| "--project-id", | |
| default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), | |
| help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)", | |
| ) | |
| parser.add_argument( | |
| "--project-id", | |
| default=os.environ.get("GOOGLE_CLOUD_PROJECT"), | |
| help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)", | |
| ) |
References
- 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.
There was a problem hiding this comment.
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/set_statement_timeout.py
Problem: multi-line SQL and DDL statements were written as adjacent string fragments. That style is easy to get wrong (a missing trailing space joins two SQL tokens) and is harder to read than the statement itself, and the samples in this set mixed it with triple-quoted SQL. Solution: write each multi-line statement as a single triple-quoted string, matching the layout already used by the other samples. Only whitespace between SQL tokens changes; the statements are otherwise identical. Files updated: - spanner/transactions/src/spanner_transactions/set_statement_timeout.py
Description
Adds
spanner_set_statement_timeoutconfiguring an explicit RPCtimeoutontransaction.execute_update().Checklist
Testing
Compliance & Style
spanner/, which the default repository owners cover.Post-Approval Actions