Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions spanner/backups/README.md
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:

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

Update the setup instructions to reflect the updated minimum Python version requirement of '>=3.12'.

Suggested change
1. Create and activate a Python 3.13+ virtual environment:
1. Create and activate a Python 3.12+ virtual environment:
References
  1. When configuring Python test environments, the oldest tested Python version must align with the minimum Python version required by the project's dependencies and samples (requiring >=3.12), rather than assuming older versions like 3.10 are supported.

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! Keeping the README aligned with the Python 3.13+ requirement in pyproject.toml.


```sh
python3 -m venv env
source env/bin/activate
```

2. Install dependencies:

```sh
pip install -r requirements.txt

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.

This is the wrong command for installing project wide dependencies using a toml file, use: pip install -e .

```

## Running Tests

Run unit tests offline:

```sh
pip install -r requirements-test.txt
pytest tests
```
21 changes: 21 additions & 0 deletions spanner/backups/noxfile_config.py
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"],

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

Update the ignored Python versions to align with the updated minimum Python version requirement of '>=3.12' for samples.

Suggested change
"ignored_versions": ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11", "3.12"],
"ignored_versions": ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11"],
References
  1. When configuring Python test environments, the oldest tested Python version must align with the minimum Python version required by the project's dependencies and samples (requiring >=3.12), rather than assuming older versions like 3.10 are supported.

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! Keeping ignored_versions aligned with the >=3.13 baseline for these new Spanner sample packages.

"enforce_type_hints": True,
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
"pip_version_override": None,
"envs": {},
}
30 changes: 30 additions & 0 deletions spanner/backups/pyproject.toml
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"

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

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
requires-python = ">=3.13"
requires-python = ">=3.12"
References
  1. When configuring Python test environments, the oldest tested Python version must align with the minimum Python version required by the project's dependencies and samples (requiring >=3.12), rather than assuming older versions like 3.10 are supported.

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! New Spanner sample packages in this series standardize on Python 3.13+, so we are keeping requires-python = ">=3.13".

dependencies = [
"google-api-core==2.44.0",

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.

Having duplicate pinned versions here and on requirement.txt will probably cause conflicts when updating dependencies and only one file is updated, then when running nox, it will install requirements.txt, then install requirements-test.txt, which has -e . at the beginning, which will make pyproject.toml overwrite the changes on the previous install of requirements.txt. Instead let pyproject.toml reference dynamically requirements.txt, so this file is always the sole source fo truth:

[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"]
2 changes: 2 additions & 0 deletions spanner/backups/requirements-test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-e .
pytest==9.2.0
2 changes: 2 additions & 0 deletions spanner/backups/requirements.txt
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
13 changes: 13 additions & 0 deletions spanner/backups/src/spanner_backups/__init__.py
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.
124 changes: 124 additions & 0 deletions spanner/backups/src/spanner_backups/copy_backup.py
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)

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.

This line breaks the Long-running Operations and Bounded Wait for Long-Running Operations by setting the timeout to 2100 seconds. Also operation.operation.name is never printed before waiting.

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

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

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}")

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 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.



# [END spanner_copy_backup]


if __name__ == "__main__":

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.

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,
)
93 changes: 93 additions & 0 deletions spanner/backups/src/spanner_backups/delete_backup_schedule.py
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,
)
Loading