From 74c595cfda5e2de44943e7b2ca1a36afafb132ca Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Wed, 18 Nov 2026 22:16:16 +0000 Subject: [PATCH 1/2] feat(spanner): Add CreateBackupSchedule incremental backup sample Enterprise Spanner databases reduce backup storage and cost with IncrementalBackupSpec schedules via create_backup_schedule. Add a standalone spanner_create_incremental_backup_schedule sample. --- .../create_incremental_backup_schedule.py | 113 +++++++++++++ ...create_incremental_backup_schedule_test.py | 159 ++++++++++++++++++ 2 files changed, 272 insertions(+) create mode 100644 spanner/backups/src/spanner_backups/create_incremental_backup_schedule.py create mode 100644 spanner/backups/tests/create_incremental_backup_schedule_test.py diff --git a/spanner/backups/src/spanner_backups/create_incremental_backup_schedule.py b/spanner/backups/src/spanner_backups/create_incremental_backup_schedule.py new file mode 100644 index 0000000000..d8c9c6b664 --- /dev/null +++ b/spanner/backups/src/spanner_backups/create_incremental_backup_schedule.py @@ -0,0 +1,113 @@ +# 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_create_incremental_backup_schedule] +import datetime +import sys + +from google.api_core import exceptions +from google.cloud import spanner_admin_database_v1 + + +def create_incremental_backup_schedule( + project_id: str, + instance_id: str, + database_id: str, + schedule_id: str, +) -> None: + """Creates an incremental backup schedule on an Enterprise Spanner database. + + Args: + project_id: The Google Cloud project ID. + instance_id: The Enterprise Spanner instance ID. + database_id: The Spanner database ID. + schedule_id: The new incremental backup schedule ID. + """ + client = spanner_admin_database_v1.DatabaseAdminClient() + parent = client.database_path(project_id, instance_id, database_id) + cron_spec = spanner_admin_database_v1.CrontabSpec(text="0 */4 * * *") + schedule_spec = spanner_admin_database_v1.BackupScheduleSpec(cron_spec=cron_spec) + enc_type = ( + spanner_admin_database_v1.CreateBackupEncryptionConfig.EncryptionType.GOOGLE_DEFAULT_ENCRYPTION + ) + enc_config = spanner_admin_database_v1.CreateBackupEncryptionConfig( + encryption_type=enc_type + ) + schedule_pb = spanner_admin_database_v1.BackupSchedule( + spec=schedule_spec, + retention_duration=datetime.timedelta(hours=24), + encryption_config=enc_config, + incremental_backup_spec=spanner_admin_database_v1.IncrementalBackupSpec(), + ) + request = spanner_admin_database_v1.CreateBackupScheduleRequest( + parent=parent, + backup_schedule_id=schedule_id, + backup_schedule=schedule_pb, + ) + + try: + created = client.create_backup_schedule(request=request) + except exceptions.AlreadyExists as err: + print( + f"error: backup schedule '{schedule_id}' already exists on " + f"database '{database_id}' in instance '{instance_id}': {err.message}", + file=sys.stderr, + ) + except exceptions.GoogleAPICallError as err: + print( + f"error: failed to create incremental backup schedule " + f"'{schedule_id}' on database '{database_id}': {err.message}", + file=sys.stderr, + ) + else: + retention_hours = int(created.retention_duration.total_seconds() // 3600) + print(f"Resource ID: {schedule_id}") + print(f"Cron Expression: {created.spec.cron_spec.text}") + print(f"Retention Hours: {retention_hours}") + + +# [END spanner_create_incremental_backup_schedule] + + +if __name__ == "__main__": + import argparse + import os + + parser = argparse.ArgumentParser( + description="Create a Spanner incremental 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() + + create_incremental_backup_schedule( + project_id=args.project_id, + instance_id=args.instance_id, + database_id=args.database_id, + schedule_id=args.schedule_id, + ) diff --git a/spanner/backups/tests/create_incremental_backup_schedule_test.py b/spanner/backups/tests/create_incremental_backup_schedule_test.py new file mode 100644 index 0000000000..95fc9774d8 --- /dev/null +++ b/spanner/backups/tests/create_incremental_backup_schedule_test.py @@ -0,0 +1,159 @@ +# 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. + +import datetime +import runpy +from unittest import mock +import uuid + +from google.api_core import exceptions +from google.cloud import spanner_admin_database_v1 +import pytest +from spanner_backups import create_incremental_backup_schedule + +from . import conftest + +PROJECT_ID = "example-project-id" +INSTANCE_ID = "example-instance" +DATABASE_ID = "example-db" +SCHEDULE_ID = "example-inc-schedule" +ADMIN_CLIENT = "google.cloud.spanner_admin_database_v1.DatabaseAdminClient" + + +def _setup_admin(mock_client_class: mock.MagicMock) -> None: + client = mock_client_class.return_value + client.database_path.return_value = ( + f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/databases/{DATABASE_ID}" + ) + sched = mock.MagicMock(retention_duration=datetime.timedelta(hours=24)) + sched.spec.cron_spec.text = "0 */4 * * *" + client.create_backup_schedule.return_value = sched + + +@mock.patch(ADMIN_CLIENT) +def test_create_incremental_backup_schedule_success( + mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] +) -> None: + _setup_admin(mock_client_class) + + create_incremental_backup_schedule.create_incremental_backup_schedule( + PROJECT_ID, INSTANCE_ID, DATABASE_ID, SCHEDULE_ID + ) + + out, err = capsys.readouterr() + assert f"Resource ID: {SCHEDULE_ID}" in out + assert "Cron Expression: 0 */4 * * *" in out + assert "Retention Hours: 24" in out + assert PROJECT_ID not in out + assert err == "" + + +@pytest.mark.parametrize( + "error, expected_prefix", + [ + ( + exceptions.AlreadyExists("dup"), + "error: backup schedule 'example-inc-schedule' already exists", + ), + ( + exceptions.FailedPrecondition("edition"), + "error: failed to create incremental backup schedule", + ), + ], +) +@mock.patch(ADMIN_CLIENT) +def test_create_incremental_backup_schedule_errors( + mock_client_class: mock.MagicMock, + capsys: pytest.CaptureFixture[str], + error: Exception, + expected_prefix: str, +) -> None: + _setup_admin(mock_client_class) + mock_client_class.return_value.create_backup_schedule.side_effect = error + + create_incremental_backup_schedule.create_incremental_backup_schedule( + PROJECT_ID, INSTANCE_ID, DATABASE_ID, SCHEDULE_ID + ) + + _out, err = capsys.readouterr() + assert err.startswith(expected_prefix) + assert PROJECT_ID not in err + + +@mock.patch(ADMIN_CLIENT) +def test_create_incremental_backup_schedule_cli_entrypoint( + mock_client_class: mock.MagicMock, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + _setup_admin(mock_client_class) + monkeypatch.setattr( + "sys.argv", + [ + "create_incremental_backup_schedule.py", + "--project-id", + PROJECT_ID, + "--instance-id", + INSTANCE_ID, + "--database-id", + DATABASE_ID, + "--schedule-id", + SCHEDULE_ID, + ], + ) + + runpy.run_module( + "spanner_backups.create_incremental_backup_schedule", run_name="__main__" + ) + + assert "Retention Hours: 24" in capsys.readouterr().out + + +@conftest.live_only +def test_create_incremental_backup_schedule_live( + capsys: pytest.CaptureFixture[str], +) -> None: + admin = spanner_admin_database_v1.DatabaseAdminClient() + db_path = admin.database_path( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_INSTANCE_ID, + conftest.LIVE_DATABASE_ID, + ) + # Remove any default incremental schedule temporarily if present + for existing in admin.list_backup_schedules(parent=db_path): + admin.delete_backup_schedule(name=existing.name) + + sid = f"example-isc-{uuid.uuid4().hex[:6]}" + spath = admin.backup_schedule_path( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_INSTANCE_ID, + conftest.LIVE_DATABASE_ID, + sid, + ) + try: + create_incremental_backup_schedule.create_incremental_backup_schedule( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_INSTANCE_ID, + conftest.LIVE_DATABASE_ID, + sid, + ) + out, err = capsys.readouterr() + assert err == "" + assert conftest.LIVE_PROJECT_ID not in out + assert "Retention Hours: 24" in out + finally: + try: + admin.delete_backup_schedule(name=spath) + except exceptions.NotFound: + pass From 4b37cc76c556c52d0ba287830a5864fffee74ce1 Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Thu, 19 Nov 2026 06:20:45 +0000 Subject: [PATCH 2/2] fix(spanner): address review feedback for create_incremental_backup_schedule 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/backups/tests/create_incremental_backup_schedule_test.py --- .../backups/tests/create_incremental_backup_schedule_test.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spanner/backups/tests/create_incremental_backup_schedule_test.py b/spanner/backups/tests/create_incremental_backup_schedule_test.py index 95fc9774d8..d44ea98af2 100644 --- a/spanner/backups/tests/create_incremental_backup_schedule_test.py +++ b/spanner/backups/tests/create_incremental_backup_schedule_test.py @@ -130,9 +130,10 @@ def test_create_incremental_backup_schedule_live( conftest.LIVE_INSTANCE_ID, conftest.LIVE_DATABASE_ID, ) - # Remove any default incremental schedule temporarily if present + # Remove schedules left behind by earlier runs of these tests. for existing in admin.list_backup_schedules(parent=db_path): - admin.delete_backup_schedule(name=existing.name) + if existing.name.split("/")[-1].startswith(("example-fsc-", "example-isc-")): + admin.delete_backup_schedule(name=existing.name) sid = f"example-isc-{uuid.uuid4().hex[:6]}" spath = admin.backup_schedule_path(