Repository navigation
Conversation
Enumerating databases and their leader options on an instance uses DatabaseAdminClient.list_databases. Add a standalone spanner_list_databases sample with unit and live tests.
|
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 script and associated tests to list Google Cloud Spanner databases and their default leader options on a given instance. The feedback suggests improving the code by letting API exceptions propagate naturally instead of catching and printing them, which enhances reusability. Additionally, it recommends using the client's built-in parse_database_path method for more robust resource name parsing instead of manual string splitting.
| try: | ||
| databases = list(client.list_databases(request=request)) | ||
| except exceptions.NotFound as err: | ||
| print( | ||
| f"error: instance '{instance_id}' was not found: {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| except exceptions.GoogleAPICallError as err: | ||
| print( | ||
| f"error: failed to list databases on instance '{instance_id}': " | ||
| f"{err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| else: | ||
| print(f"Resource ID: {instance_id}") | ||
| print(f"Database Count: {len(databases)}") | ||
| for db in databases: | ||
| db_id = db.name.split("/")[-1] | ||
| leader = db.default_leader or "regional-default" | ||
| print(f"Database ID: {db_id}, Default Leader: {leader}") |
There was a problem hiding this comment.
Improvement: Simplify Exception Handling and Use Robust Path Parsing
- Exception Propagation: Swallowing exceptions and printing to
sys.stderrmakes this function less reusable. In Python, helper/library functions should let exceptions propagate so that calling applications can handle them programmatically (e.g., for retries or custom error handling). Removing thetry-exceptblock also significantly reduces boilerplate, keeping the sample focused on the Spanner API. - Robust Path Parsing: Instead of manually splitting the database resource name with
db.name.split("/")[-1], use the client's built-inparse_database_pathhelper, which is more robust and idiomatic.
Note: If you apply this change, remember to update test_list_databases_errors in tests/list_databases_test.py to use pytest.raises to assert that the expected exceptions are raised.
databases = list(client.list_databases(request=request))
print(f"Resource ID: {instance_id}")
print(f"Database Count: {len(databases)}")
for db in databases:
db_id = client.parse_database_path(db.name)["database"]
leader = db.default_leader or "regional-default"
print(f"Database ID: {db_id}, Default Leader: {leader}")There was a problem hiding this comment.
Thanks for the feedback! Standalone documentation snippets here intentionally catch google.api_core.exceptions inside the sample function and print actionable diagnostic messages to stderr so readers can see concrete error handling directly in context, so we are keeping the try/except block. The resource ID is taken from the last path segment, as in the other samples in this set.
Problem: reviewers of this sample set asked for stricter and clearer tests and for a single source of truth for dependencies. Mocks were created without a spec, so a renamed client argument would pass silently; the mocked wait timeout was raised from the API call instead of from the operation's result; live tests did not say which environment variables they need; and some tests carried leftover or repeated lines. Package dependencies were pinned in both pyproject.toml and requirements.txt. Solution: where applicable to the files below, patch client classes with autospec=True, raise the mocked TimeoutError from operation.result(), document the required environment variables above each live test and skip when one is missing, remove unused or duplicated test lines, and join string literals that the formatter had left split on one line. For package scaffolding, read dependencies from requirements.txt and update the README install command to match. Files updated: - spanner/database_admin/tests/list_databases_test.py
Description
Adds
spanner_list_databaseslisting databases and leader options on a Spanner instance.Checklist
Testing
Compliance & Style
spanner/, which the default repository owners cover.Post-Approval Actions