Skip to content

feat(spanner): Add Spanner backup copy sample - #14854

Open
iennae wants to merge 5 commits into
mainfrom
feat/spanner-copy-backup
Open

iennae wants to merge 5 commits into
mainfrom
feat/spanner-copy-backup

Conversation

@iennae

@iennae iennae commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Description

Copying a Cloud Spanner backup across instances or regions requires constructing a CopyBackupRequest on DatabaseAdminClient with a valid expire_time and awaiting the long-running operation.

Establishes the spanner/backups package and adds spanner_copy_backup.

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

Copying an existing Spanner backup with an explicit retention timestamp via DatabaseAdminClient replaces the archived python-spanner sample.
@iennae
iennae requested review from a team as code owners November 17, 2026 23:47
@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 17, 2026
@snippet-bot

snippet-bot Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 3 region tags.

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 Python sample and associated tests for copying Cloud Spanner backups. The feedback suggests letting API exceptions propagate naturally in copy_backup.py instead of swallowing them, which will also allow simplifying the error tests in copy_backup_test.py using pytest.raises. Additionally, it is recommended to lower the minimum supported Python version from 3.13 to 3.12 across pyproject.toml, noxfile_config.py, and README.md to align with repository standards and make the sample more accessible.

Comment on lines +49 to +76
try:
operation = client.copy_backup(request=request)
print(f"Waiting for backup copy '{backup_id}' to complete...")
copied = operation.result(timeout=2100)
except exceptions.AlreadyExists as err:
print(
f"error: backup '{backup_id}' already exists on instance "
f"'{instance_id}' in project '{project_id}': {err.message}",
file=sys.stderr,
)
except exceptions.NotFound as err:
print(
f"error: source backup '{source_backup_path}' or destination "
f"instance '{instance_id}' in project '{project_id}' was not found: "
f"{err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: failed to copy backup '{source_backup_path}' to "
f"'{backup_id}' on instance '{instance_id}' in project "
f"'{project_id}': {err.message}",
file=sys.stderr,
)
else:
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

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.

Comment on lines +63 to +94
@pytest.mark.parametrize(
"error, expected_prefix",
[
(
exceptions.AlreadyExists("exists"),
"error: backup 'example-copied-backup' already exists",
),
(
exceptions.NotFound("missing"),
"error: source backup",
),
(
exceptions.PermissionDenied("denied"),
"error: failed to copy backup",
),
],
)
@mock.patch(ADMIN_CLIENT)
def test_copy_backup_errors(
mock_client_class: mock.MagicMock,
capsys: pytest.CaptureFixture[str],
error: Exception,
expected_prefix: str,
) -> None:
client = mock_client_class.return_value
client.instance_path.return_value = f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}"
client.copy_backup.side_effect = error

copy_backup.copy_backup(PROJECT_ID, INSTANCE_ID, BACKUP_ID, SOURCE_BACKUP)

_out, err = capsys.readouterr()
assert err.startswith(expected_prefix)

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

Since we are propagating exceptions from the copy_backup function rather than swallowing them, we can simplify the error unit tests to assert that the expected exceptions are raised using pytest.raises.

@pytest.mark.parametrize(
    "error",
    [
        exceptions.AlreadyExists("exists"),
        exceptions.NotFound("missing"),
        exceptions.PermissionDenied("denied"),
    ],
)
@mock.patch(ADMIN_CLIENT)
def test_copy_backup_errors(
    mock_client_class: mock.MagicMock,
    error: Exception,
) -> None:
    client = mock_client_class.return_value
    client.instance_path.return_value = f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}"
    client.copy_backup.side_effect = error

    with pytest.raises(type(error)):
        copy_backup.copy_backup(PROJECT_ID, INSTANCE_ID, BACKUP_ID, SOURCE_BACKUP)

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! Since we are keeping explicit google.api_core.exceptions handling and stderr reporting in copy_backup, we are retaining the capsys stderr assertions in this unit test.

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

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

Comment thread spanner/backups/README.md

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

Prints short resource identifiers instead of full project-prefixed resource paths and omits project_id from diagnostic messages.
Problem: the sample waits on a long-running operation with a client-side
timeout. When that wait expires the client raises TimeoutError, which is
not an API call error, so the sample ended with an unhandled traceback.

Solution: catch TimeoutError and print a clear message to stderr noting
that only the wait timed out and the operation may still be running (the
timeout does not cancel it). Add a unit test covering the new handler.
Removing an automated backup schedule from a Spanner database calls DatabaseAdminClient.delete_backup_schedule. Add a standalone spanner_delete_backup_schedule sample.
…4986)

Adjusting backup schedule frequency or retention window uses DatabaseAdminClient.update_backup_schedule with an update_mask. Add a standalone spanner_update_backup_schedule sample.
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.

2 participants