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
28 changes: 26 additions & 2 deletions packages/google-cloud-spanner/tests/system/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
import time
import uuid

from google.api_core import exceptions
from google.api_core import datetime_helpers, exceptions
from google.cloud.spanner_v1 import instance as instance_mod
from test_utils import retry

from google.cloud.spanner_v1 import instance as instance_mod
from tests import _fixtures

CREATE_INSTANCE_ENVVAR = "GOOGLE_CLOUD_TESTS_CREATE_SPANNER_INSTANCE"
Expand Down Expand Up @@ -159,6 +159,30 @@ def cleanup_old_instances(spanner_client):
scrub_instance_ignore_not_found(instance)


def cleanup_stale_databases(instance, cutoff_seconds=600):
"""Delete stale databases in the given instance older than cutoff_seconds."""
cutoff_ms = (int(time.time()) - cutoff_seconds) * 1000

for database_pb in instance.list_databases():
if database_pb.create_time is not None:
create_time_ms = datetime_helpers.to_milliseconds(database_pb.create_time)

if create_time_ms < cutoff_ms:
db = instance.database(database_pb.name.split("/")[-1])
try:
db.reload()
if db.enable_drop_protection:
db.enable_drop_protection = False
operation = db.update(["enable_drop_protection"])
operation.result(DATABASE_OPERATION_TIMEOUT_IN_SECONDS)
db.drop()
except exceptions.NotFound:
pass
except exceptions.GoogleAPIError:
# Ignore other API errors during cleanup
pass


def unique_id(prefix, separator="-"):
# Database name size: Spanner database names are limited to 30 characters.
# See: https://docs.cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#createdatabaserequest
Expand Down
3 changes: 2 additions & 1 deletion packages/google-cloud-spanner/tests/system/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import time

import pytest

from google.cloud import spanner_v1
from google.cloud.spanner_admin_database_v1 import DatabaseDialect
from google.cloud.spanner_admin_database_v1.types.backup import (
Expand Down Expand Up @@ -218,6 +217,8 @@ def shared_instance(
instance = spanner_client.instance(shared_instance_id)
instance.reload()

_helpers.cleanup_stale_databases(instance)

yield instance

if _helpers.CREATE_INSTANCE:
Expand Down
Loading