Repository navigation
feat(spanner): Add Spanner backup copy sample #14854
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
base: main
Are you sure you want to change the base?
Changes from all commits
8f7b974
7b2ad1b
8964f92
e52292b
544d52d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| # Cloud Spanner Backup & Restore Samples | ||
|
|
||
| Python samples demonstrating Cloud Spanner backup creation, cross-instance backup copying, and listing copy-backup long-running operations. | ||
|
|
||
| ## Setup | ||
|
|
||
| 1. Create and activate a Python 3.13+ virtual environment: | ||
|
|
||
| ```sh | ||
| python3 -m venv env | ||
| source env/bin/activate | ||
| ``` | ||
|
|
||
| 2. Install dependencies: | ||
|
|
||
| ```sh | ||
| pip install -r requirements.txt | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is the wrong command for installing project wide dependencies using a toml file, use: |
||
| ``` | ||
|
|
||
| ## Running Tests | ||
|
|
||
| Run unit tests offline: | ||
|
|
||
| ```sh | ||
| pip install -r requirements-test.txt | ||
| pytest tests | ||
| ``` | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,21 @@ | ||||||
| # Copyright 2026 Google LLC | ||||||
| # | ||||||
| # 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. | ||||||
|
|
||||||
| TEST_CONFIG_OVERRIDE = { | ||||||
| "ignored_versions": ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11", "3.12"], | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Update the ignored Python versions to align with the updated minimum Python version requirement of '>=3.12' for samples.
Suggested change
References
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks! Keeping |
||||||
| "enforce_type_hints": True, | ||||||
| "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", | ||||||
| "pip_version_override": None, | ||||||
| "envs": {}, | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,30 @@ | ||||||
| # Copyright 2026 Google LLC | ||||||
| # | ||||||
| # 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. | ||||||
|
|
||||||
| # Local samples only. This package isn't published: install it from this | ||||||
| # directory with `pip install -e .`, never by name from PyPI. | ||||||
| [build-system] | ||||||
| requires = ["setuptools>=64"] | ||||||
| build-backend = "setuptools.build_meta" | ||||||
|
|
||||||
| [project] | ||||||
| name = "spanner-backups-samples" | ||||||
| version = "0.0.0" | ||||||
| requires-python = ">=3.13" | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Requiring Python >=3.13 is unnecessarily restrictive for this sample, as it does not use any Python 3.13-specific features. Lowering the minimum supported version to '>=3.12' makes the sample accessible to a wider audience, aligning with the repository's minimum Python version requirement for samples.
Suggested change
References
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for the suggestion! New Spanner sample packages in this series standardize on Python 3.13+, so we are keeping |
||||||
| dependencies = [ | ||||||
| "google-api-core==2.44.0", | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Having duplicate pinned versions here and on [project]
name = "spanner-backups-samples"
version = "0.0.0"
requires-python = ">=3.12"
dynamic = ["dependencies"]
classifiers = ["Private :: Do Not Upload"]
[tool.setuptools.dynamic]
dependencies = {file = ["requirements.txt"]} |
||||||
| "google-cloud-spanner==3.72.0", | ||||||
| ] | ||||||
| # PyPI rejects uploads with this classifier. | ||||||
| classifiers = ["Private :: Do Not Upload"] | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| -e . | ||
| pytest==9.2.0 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| google-api-core==2.44.0 | ||
| google-cloud-spanner==3.72.0 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # 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. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # 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. | ||
|
|
||
| # [START spanner_copy_backup] | ||
| from datetime import datetime, timedelta, timezone | ||
| import sys | ||
|
|
||
| from google.api_core import exceptions | ||
| from google.cloud import spanner_admin_database_v1 | ||
|
|
||
|
|
||
| def copy_backup( | ||
| project_id: str, | ||
| instance_id: str, | ||
| backup_id: str, | ||
| source_backup_path: str, | ||
| ) -> None: | ||
| """Copies an existing Spanner backup to a destination instance. | ||
|
|
||
| Args: | ||
| project_id: The destination Google Cloud project ID. | ||
| instance_id: The destination Spanner instance ID. | ||
| backup_id: The ID for the newly copied backup. | ||
| source_backup_path: Full resource path of the source backup | ||
| (projects/<proj>/instances/<inst>/backups/<backup>). | ||
| """ | ||
| client = spanner_admin_database_v1.DatabaseAdminClient() | ||
| parent = client.instance_path(project_id, instance_id) | ||
| expire_time = datetime.now(timezone.utc) + timedelta(days=14) | ||
|
|
||
| source_backup_id = source_backup_path.split("/")[-1] | ||
| request = spanner_admin_database_v1.CopyBackupRequest( | ||
| parent=parent, | ||
| backup_id=backup_id, | ||
| source_backup=source_backup_path, | ||
| expire_time=expire_time, | ||
| ) | ||
|
|
||
| try: | ||
| operation = client.copy_backup(request=request) | ||
| print(f"Waiting for backup copy '{backup_id}' to complete...") | ||
| copied = operation.result(timeout=2100) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This line breaks the Long-running Operations and Bounded Wait for Long-Running Operations by setting the timeout to 2100 seconds. Also |
||
| except exceptions.AlreadyExists as err: | ||
| print( | ||
| f"error: backup '{backup_id}' already exists on instance " | ||
| f"'{instance_id}': {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| except exceptions.NotFound as err: | ||
| print( | ||
| f"error: source backup '{source_backup_id}' or destination " | ||
| f"instance '{instance_id}' was not found: {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| except TimeoutError as err: | ||
| print( | ||
| f"error: timed out waiting for the operation on backup '{backup_id}' " | ||
| f"to complete; the operation may still be running: {err}", | ||
| file=sys.stderr, | ||
| ) | ||
| except exceptions.GoogleAPICallError as err: | ||
| print( | ||
| f"error: failed to copy backup '{source_backup_id}' to " | ||
| f"'{backup_id}' on instance '{instance_id}': {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| else: | ||
| print(f"Resource ID: {backup_id}") | ||
| print(f"Backup State: {copied.state.name}") | ||
| print(f"Size Bytes: {copied.size_bytes}") | ||
|
Comment on lines
+50
to
+81
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Swallowing API exceptions inside the sample function makes it harder for programmatic callers (and tests) to detect failures, and causes the CLI entry point to exit with a success status (0) even when the operation fails. It is more idiomatic for Google Cloud Python samples to let exceptions propagate naturally to the caller, allowing them to handle errors or see the traceback. operation = client.copy_backup(request=request)
print(f"Waiting for backup copy '{backup_id}' to complete...")
copied = operation.result(timeout=2100)
print(f"Resource ID: {copied.name}")
print(f"Backup State: {copied.state.name}")
print(f"Size Bytes: {copied.size_bytes}")
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for the feedback! Standalone documentation snippets here intentionally catch |
||
|
|
||
|
|
||
| # [END spanner_copy_backup] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This breaks the rule of No-CLIs |
||
| import argparse | ||
| import os | ||
|
|
||
| parser = argparse.ArgumentParser( | ||
| description="Copy an existing Cloud Spanner backup." | ||
| ) | ||
| parser.add_argument( | ||
| "--project-id", | ||
| default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), | ||
| help="Destination Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)", | ||
| ) | ||
| parser.add_argument( | ||
| "--instance-id", | ||
| default=os.environ.get("SPANNER_INSTANCE_ID", "example-instance"), | ||
| help="Destination Spanner instance ID (default: $SPANNER_INSTANCE_ID)", | ||
| ) | ||
| parser.add_argument( | ||
| "--backup-id", | ||
| default=os.environ.get("SPANNER_BACKUP_ID", "example-copied-backup"), | ||
| help="New copied backup ID (default: $SPANNER_BACKUP_ID)", | ||
| ) | ||
| parser.add_argument( | ||
| "--source-backup-path", | ||
| default=os.environ.get( | ||
| "SPANNER_SOURCE_BACKUP_PATH", | ||
| "projects/example-project-id/instances/example-instance/backups/example-source-backup", | ||
| ), | ||
| help="Full resource path of the source backup", | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| copy_backup( | ||
| project_id=args.project_id, | ||
| instance_id=args.instance_id, | ||
| backup_id=args.backup_id, | ||
| source_backup_path=args.source_backup_path, | ||
| ) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # 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. | ||
|
|
||
| # [START spanner_delete_backup_schedule] | ||
| import sys | ||
|
|
||
| from google.api_core import exceptions | ||
| from google.cloud import spanner_admin_database_v1 | ||
|
|
||
|
|
||
| def delete_backup_schedule( | ||
| project_id: str, | ||
| instance_id: str, | ||
| database_id: str, | ||
| schedule_id: str, | ||
| ) -> None: | ||
| """Deletes a backup schedule from a Cloud Spanner database. | ||
|
|
||
| Args: | ||
| project_id: The Google Cloud project ID. | ||
| instance_id: The Spanner instance ID. | ||
| database_id: The Spanner database ID. | ||
| schedule_id: The backup schedule ID to delete. | ||
| """ | ||
| client = spanner_admin_database_v1.DatabaseAdminClient() | ||
| schedule_path = client.backup_schedule_path( | ||
| project_id, instance_id, database_id, schedule_id | ||
| ) | ||
| request = spanner_admin_database_v1.DeleteBackupScheduleRequest(name=schedule_path) | ||
|
|
||
| try: | ||
| client.delete_backup_schedule(request=request) | ||
| except exceptions.NotFound as err: | ||
| print( | ||
| f"error: backup schedule '{schedule_id}' on database " | ||
| f"'{database_id}' in instance '{instance_id}' was not found: " | ||
| f"{err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| except exceptions.GoogleAPICallError as err: | ||
| print( | ||
| f"error: failed to delete backup schedule '{schedule_id}' on " | ||
| f"database '{database_id}': {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| else: | ||
| print(f"Resource ID: {schedule_id}") | ||
| print(f"Deleted Schedule: {schedule_id}") | ||
|
|
||
|
|
||
| # [END spanner_delete_backup_schedule] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import argparse | ||
| import os | ||
|
|
||
| parser = argparse.ArgumentParser(description="Delete a Spanner backup schedule.") | ||
| parser.add_argument( | ||
| "--project-id", | ||
| default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), | ||
| ) | ||
| parser.add_argument( | ||
| "--instance-id", | ||
| default=os.environ.get("SPANNER_INSTANCE_ID", "example-instance"), | ||
| ) | ||
| parser.add_argument( | ||
| "--database-id", | ||
| default=os.environ.get("SPANNER_DATABASE_ID", "example-db"), | ||
| ) | ||
| parser.add_argument( | ||
| "--schedule-id", | ||
| default="example-backup-schedule", | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| delete_backup_schedule( | ||
| project_id=args.project_id, | ||
| instance_id=args.instance_id, | ||
| database_id=args.database_id, | ||
| schedule_id=args.schedule_id, | ||
| ) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Update the setup instructions to reflect the updated minimum Python version requirement of '>=3.12'.
References
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks! Keeping the README aligned with the Python 3.13+ requirement in
pyproject.toml.