Class DatabaseAdminClient (2.20.0)

Performs database administration operations on Spanner.

Applications use this class to perform administrative operations on spanner Databases.

Performance

Creating a new DatabaseAdminClient is a relatively expensive operation, new objects establish new connections to the service. In contrast, copying or moving an existing DatabaseAdminClient object is a relatively cheap operation. Copied clients share the underlying resources.

Thread Safety

Instances of this class created via copy-construction or copy-assignment share the underlying pool of connections. Access to these copies via multiple threads is guaranteed to work. Two threads operating on the same instance of this class is not guaranteed to work.

Error Handling

This class uses StatusOr<T> to report errors. When an operation fails to perform its work the returned StatusOr<T> contains the error details. If the ok() member function in the StatusOr<T> returns true then it contains the expected result. For more information, see the Error Handling Guide.

namespace spanner = ::google::cloud::spanner;
using ::google::cloud::StatusOr;
spanner::DatabaseAdminClient client = ...;
StatusOr<google::spanner::admin::database::v1::Database> db =
    client.CreateDatabase(...).get();

if (!db) {
  std::cerr << "Error in CreateDatabase: " << db.status() << "\n";
  return;
}

// Use `db` as a smart pointer here, e.g.:
std::cout << "The database fully qualified name is: " << db->name() << "\n";
Long running operations

Some operations in this class can take minutes to complete. In this case the class returns a google::cloud::future<StatusOr<T>>, the application can then poll the future or associate a callback to be invoked when the operation completes:

namespace spanner = ::google::cloud::spanner;
spanner::DatabaseAdminClient client = ...;
// Make example less verbose.
using ::google::cloud::future;
using ::google::cloud::StatusOr;
using std::chrono::chrono_literals; // C++14

auto database = client.CreateDatabase(...);
if (database.wait_for(5m) == std::future_state::ready) {
  std::cout << "Database created in under 5 minutes, yay!\n";
  return;
}
// Too slow, setup a callback instead:
database.then([](auto f) {
  StatusOr<google::spanner::admin::database::v1::Database> db = f.get();
  if (!db) {
      std::cout << "Failed creating a database!\n";
      return;
  }
  std::cout << "Database created!\n";
});

Constructors

DatabaseAdminClient(ConnectionOptions const &)

Parameter
Name Description
options ConnectionOptions const &

DatabaseAdminClient(std::shared_ptr< DatabaseAdminConnection >)

Create a new client with the given stub. For testing only.

Parameter
Name Description
c std::shared_ptr< DatabaseAdminConnection >

Functions

CreateDatabase(Database, std::vector< std::string >, EncryptionConfig)

Creates a new Cloud Spanner database in the given project and instance.

This function creates a database (using the "CREATE DATABASE" DDL statement) in the given Google Cloud Project and Cloud Spanner instance. The application can provide an optional list of additional DDL statements to atomically create tables and indices as well as the new database.

Note that the database id must be between 2 and 30 characters long, it must start with a lowercase letter ([a-z]), it must end with a lowercase letter or a number ([a-z0-9]) and any characters between the beginning and ending characters must be lower case letters, numbers, underscore (_) or dashes (-), that is, they must belong to the [a-z0-9_-] character set.

encryption_config How to encrypt the database.

Example
void CreateDatabase(google::cloud::spanner_admin::DatabaseAdminClient client,
                    std::string const& project_id,
                    std::string const& instance_id,
                    std::string const& database_id) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  google::spanner::admin::database::v1::CreateDatabaseRequest request;
  request.set_parent(database.instance().FullName());
  request.set_create_statement("CREATE DATABASE `" + database.database_id() +
                               "`");
  request.add_extra_statements(R"""(
      CREATE TABLE Singers (
          SingerId   INT64 NOT NULL,
          FirstName  STRING(1024),
          LastName   STRING(1024),
          SingerInfo BYTES(MAX),
          FullName   STRING(2049)
              AS (ARRAY_TO_STRING([FirstName, LastName], " ")) STORED
      ) PRIMARY KEY (SingerId))""");
  request.add_extra_statements(R"""(
      CREATE TABLE Albums (
          SingerId     INT64 NOT NULL,
          AlbumId      INT64 NOT NULL,
          AlbumTitle   STRING(MAX)
      ) PRIMARY KEY (SingerId, AlbumId),
          INTERLEAVE IN PARENT Singers ON DELETE CASCADE)""");
  auto db = client.CreateDatabase(request).get();
  if (!db) throw std::move(db).status();
  std::cout << "Database " << db->name() << " created.\n";
}
See Also

https://cloud.google.com/spanner/docs/data-definition-language for a full list of the DDL operations

See Also

https://cloud.google.com/spanner/docs/data-definition-language#create_database for the regular expression that must be satisfied by the database id.

Parameters
Name Description
db Database
extra_statements std::vector< std::string >
encryption_config EncryptionConfig
Returns
Type Description
future< StatusOr< google::spanner::admin::database::v1::Database > >

A google::cloud::future that becomes satisfied when the operation completes on the service. Note that this can take minutes in some cases.

GetDatabase(Database)

Retrieve metadata information about a database.

Idempotency

This is a read-only operation and therefore always idempotent. Transient failures are automatically retried.

Example
void GetDatabase(google::cloud::spanner_admin::DatabaseAdminClient client,
                 std::string const& project_id, std::string const& instance_id,
                 std::string const& database_id) {
  namespace spanner = ::google::cloud::spanner;
  auto database = client.GetDatabase(
      spanner::Database(project_id, instance_id, database_id).FullName());
  if (!database) throw std::move(database).status();
  std::cout << "Database metadata is:\n" << database->DebugString();
}
Parameter
Name Description
db Database
Returns
Type Description
StatusOr< google::spanner::admin::database::v1::Database >

GetDatabaseDdl(Database)

Retrieve a database schema.

Idempotency

This is a read-only operation and therefore always idempotent. Transient failures are automatically retried.

Example
void GetDatabaseDdl(google::cloud::spanner_admin::DatabaseAdminClient client,
                    std::string const& project_id,
                    std::string const& instance_id,
                    std::string const& database_id) {
  namespace spanner = ::google::cloud::spanner;
  auto database = client.GetDatabaseDdl(
      spanner::Database(project_id, instance_id, database_id).FullName());
  if (!database) throw std::move(database).status();
  std::cout << "Database metadata is:\n" << database->DebugString();
}
Parameter
Name Description
db Database
Returns
Type Description
StatusOr< google::spanner::admin::database::v1::GetDatabaseDdlResponse >

UpdateDatabase(Database, std::vector< std::string >)

Updates the database using a series of DDL statements.

This function schedules a series of updates to the database using a sequence of DDL statements.

Example
void AddColumn(google::cloud::spanner_admin::DatabaseAdminClient client,
               std::string const& project_id, std::string const& instance_id,
               std::string const& database_id) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  auto metadata =
      client
          .UpdateDatabaseDdl(
              database.FullName(),
              {"ALTER TABLE Albums ADD COLUMN MarketingBudget INT64"})
          .get();
  google::cloud::spanner_testing::LogUpdateDatabaseDdl(  
      client, database, metadata.status());              
  if (!metadata) throw std::move(metadata).status();
  std::cout << "Added MarketingBudget column\n";
}
See Also

https://cloud.google.com/spanner/docs/data-definition-language for a full list of the DDL operations

Parameters
Name Description
db Database
statements std::vector< std::string >
Returns
Type Description
future< StatusOr< google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata > >

A google::cloud::future that becomes satisfied when all the statements complete. Note that Cloud Spanner may fail to execute some of the statements.

DropDatabase(Database)

Drops (deletes) an existing Cloud Spanner database.

Example
void DropDatabase(google::cloud::spanner_admin::DatabaseAdminClient client,
                  std::string const& project_id, std::string const& instance_id,
                  std::string const& database_id) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  auto status = client.DropDatabase(database.FullName());
  if (!status.ok()) throw std::move(status);
  std::cout << "Database " << database << " successfully dropped\n";
}
Parameter
Name Description
db Database
Returns
Type Description
Status

ListDatabases(Instance)

List all the databases in a give project and instance.

Idempotency

This operation is read-only and therefore always idempotent.

Example
void ListDatabases(google::cloud::spanner_admin::DatabaseAdminClient client,
                   std::string const& project_id,
                   std::string const& instance_id) {
  google::cloud::spanner::Instance in(project_id, instance_id);
  int count = 0;
  for (auto& database : client.ListDatabases(in.FullName())) {
    if (!database) throw std::move(database).status();
    std::cout << "Database " << database->name() << " full metadata:\n"
              << database->DebugString();
    ++count;
  }
  if (count == 0) {
    std::cout << "No databases found in instance " << instance_id
              << " for project << " << project_id << "\n";
  }
}
Parameter
Name Description
in Instance
Returns
Type Description
ListDatabaseRange

RestoreDatabase(Database, Backup const &, EncryptionConfig)

Create a new database by restoring from a completed backup.

Idempotency

This is not an idempotent operation. Transient failures are not retried. The new database must be in the same project and in an instance with the same instance configuration as the instance containing the backup.

encryption_config How to encrypt the database.

Example
void RestoreDatabase(google::cloud::spanner_admin::DatabaseAdminClient client,
                     std::string const& project_id,
                     std::string const& instance_id,
                     std::string const& database_id,
                     std::string const& backup_id) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  google::cloud::spanner::Backup backup(database.instance(), backup_id);
  auto restored_db =
      client
          .RestoreDatabase(database.instance().FullName(),
                           database.database_id(), backup.FullName())
          .get();
  if (!restored_db) throw std::move(restored_db).status();
  std::cout << "Database";
  if (restored_db->restore_info().source_type() ==
      google::spanner::admin::database::v1::BACKUP) {
    auto const& backup_info = restored_db->restore_info().backup_info();
    std::cout << " " << backup_info.source_database() << " as of "
              << google::cloud::spanner::MakeTimestamp(
                     backup_info.version_time())
                     .value();
  }
  std::cout << " restored to " << restored_db->name();
  std::cout << " from backup " << backup.FullName();
  std::cout << ".\n";
}
Parameters
Name Description
db Database
backup Backup const &
encryption_config EncryptionConfig
Returns
Type Description
future< StatusOr< google::spanner::admin::database::v1::Database > >

A google::cloud::future that becomes satisfied when the operation completes on the service. Note that this can take minutes in some cases.

RestoreDatabase(Database, google::spanner::admin::database::v1::Backup const &, EncryptionConfig)

Create a new database by restoring from a completed backup.

Idempotency

This is not an idempotent operation. Transient failures are not retried. The new database must be in the same project and in an instance with the same instance configuration as the instance containing the backup.

encryption_config How to encrypt the database.

Parameters
Name Description
db Database
backup google::spanner::admin::database::v1::Backup const &
encryption_config EncryptionConfig
Returns
Type Description
future< StatusOr< google::spanner::admin::database::v1::Database > >

A google::cloud::future that becomes satisfied when the operation completes on the service. Note that this can take minutes in some cases.

GetIamPolicy(Database)

Gets the IAM policy for a database.

Idempotency

This operation is read-only and therefore always idempotent.

Example
void DatabaseGetIamPolicy(
    google::cloud::spanner_admin::DatabaseAdminClient client,
    std::string const& project_id, std::string const& instance_id,
    std::string const& database_id) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  auto actual = client.GetIamPolicy(database.FullName());
  if (!actual) throw std::move(actual).status();

  std::cout << "The IAM policy for database " << database_id << " is:\n"
            << actual->DebugString() << "\n";
}
Parameter
Name Description
db Database
Returns
Type Description
StatusOr< google::iam::v1::Policy >

SetIamPolicy(Database, google::iam::v1::Policy)

Set the IAM policy for the given database.

This function changes the IAM policy configured in the given database to the value of policy.

Idempotency

This function is only idempotent if the etag field in policy is set. Therefore, the underlying RPCs are only retried if the field is set, and the function returns the first RPC error in any other case.

See Also

The Cloud Spanner documentation for a description of the roles and permissions supported by Cloud Spanner.

See Also

IAM Overview for an introduction to Identity and Access Management in Google Cloud Platform.

Parameters
Name Description
db Database
policy google::iam::v1::Policy
Returns
Type Description
StatusOr< google::iam::v1::Policy >

SetIamPolicy(Database const &, IamUpdater const &)

Updates the IAM policy for an instance using an optimistic concurrency control loop.

This function repeatedly reads the current IAM policy in db, and then calls the updater with the this policy. The updater returns an empty optional if no changes are required, or it returns the new desired value for the IAM policy. This function then updates the policy.

Updating an IAM policy can fail with retryable errors or can be aborted because there were simultaneous changes the to IAM policy. In these cases this function reruns the loop until it succeeds.

The function returns the final IAM policy, or an error if the rerun policy for the underlying connection has expired.

Idempotency

This function always sets the etag field on the policy, so the underlying RPCs are retried automatically.

Example
void AddDatabaseReaderOnDatabase(
    google::cloud::spanner_admin::DatabaseAdminClient client,
    std::string const& project_id, std::string const& instance_id,
    std::string const& database_id, std::string const& new_reader) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  auto current = client.GetIamPolicy(database.FullName());
  if (!current) throw std::move(current).status();

  // Find (or create) the binding for "roles/spanner.databaseReader".
  auto& binding = [&current]() -> google::iam::v1::Binding& {
    auto role_pos =
        std::find_if(current->mutable_bindings()->begin(),
                     current->mutable_bindings()->end(),
                     [](google::iam::v1::Binding const& b) {
                       return b.role() == "roles/spanner.databaseReader" &&
                              !b.has_condition();
                     });
    if (role_pos != current->mutable_bindings()->end()) {
      return *role_pos;
    }
    auto& binding = *current->add_bindings();
    binding.set_role("roles/spanner.databaseReader");
    return binding;
  }();

  auto member_pos =
      std::find(binding.members().begin(), binding.members().end(), new_reader);
  if (member_pos != binding.members().end()) {
    std::cout << "The entity " << new_reader
              << " is already a database reader:\n"
              << current->DebugString();
    return;
  }

  binding.add_members(new_reader);
  auto result = client.SetIamPolicy(database.FullName(), *std::move(current));
  if (!result) throw std::move(result).status();

  std::cout << "Successfully added " << new_reader
            << " to the database reader role:\n"
            << result->DebugString();
}
Parameters
Name Description
db Database const &

the identifier for the database where you want to change the IAM policy.

updater IamUpdater const &

a callback to modify the policy. Return an unset optional to indicate that no changes to the policy are needed.

Returns
Type Description
StatusOr< google::iam::v1::Policy >

SetIamPolicy(Database const &, IamUpdater const &, std::unique_ptr< TransactionRerunPolicy >, std::unique_ptr< BackoffPolicy >)

Updates the IAM policy for an instance using an optimistic concurrency control loop.

This function repeatedly reads the current IAM policy in db, and then calls the updater with the this policy. The updater returns an empty optional if no changes are required, or it returns the new desired value for the IAM policy. This function then updates the policy.

Updating an IAM policy can fail with retryable errors or can be aborted because there were simultaneous changes the to IAM policy. In these cases this function reruns the loop until it succeeds.

The function returns the final IAM policy, or an error if the rerun policy for the underlying connection has expired.

Idempotency

This function always sets the etag field on the policy, so the underlying RPCs are retried automatically.

Example
void AddDatabaseReaderOnDatabase(
    google::cloud::spanner_admin::DatabaseAdminClient client,
    std::string const& project_id, std::string const& instance_id,
    std::string const& database_id, std::string const& new_reader) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  auto current = client.GetIamPolicy(database.FullName());
  if (!current) throw std::move(current).status();

  // Find (or create) the binding for "roles/spanner.databaseReader".
  auto& binding = [&current]() -> google::iam::v1::Binding& {
    auto role_pos =
        std::find_if(current->mutable_bindings()->begin(),
                     current->mutable_bindings()->end(),
                     [](google::iam::v1::Binding const& b) {
                       return b.role() == "roles/spanner.databaseReader" &&
                              !b.has_condition();
                     });
    if (role_pos != current->mutable_bindings()->end()) {
      return *role_pos;
    }
    auto& binding = *current->add_bindings();
    binding.set_role("roles/spanner.databaseReader");
    return binding;
  }();

  auto member_pos =
      std::find(binding.members().begin(), binding.members().end(), new_reader);
  if (member_pos != binding.members().end()) {
    std::cout << "The entity " << new_reader
              << " is already a database reader:\n"
              << current->DebugString();
    return;
  }

  binding.add_members(new_reader);
  auto result = client.SetIamPolicy(database.FullName(), *std::move(current));
  if (!result) throw std::move(result).status();

  std::cout << "Successfully added " << new_reader
            << " to the database reader role:\n"
            << result->DebugString();
}
Parameters
Name Description
db Database const &

the identifier for the database where you want to change the IAM policy.

updater IamUpdater const &

a callback to modify the policy. Return an unset optional to indicate that no changes to the policy are needed.

rerun_policy std::unique_ptr< TransactionRerunPolicy >

controls for how long (or how many times) the updater will be rerun after the IAM policy update aborts.

backoff_policy std::unique_ptr< BackoffPolicy >

controls how long SetIamPolicy waits between reruns.

Returns
Type Description
StatusOr< google::iam::v1::Policy >

TestIamPermissions(Database, std::vector< std::string >)

Get the subset of the permissions the caller has on the given database.

This function compares the given list of permissions against those permissions granted to the caller, and returns the subset of the list that the caller actually holds.

Idempotency

This operation is read-only and therefore always idempotent.

Example
void DatabaseTestIamPermissions(
    google::cloud::spanner_admin::DatabaseAdminClient client,
    std::string const& project_id, std::string const& instance_id,
    std::string const& database_id, std::string const& permission) {
  google::cloud::spanner::Database db(project_id, instance_id, database_id);
  auto actual = client.TestIamPermissions(db.FullName(), {permission});
  if (!actual) throw std::move(actual).status();

  char const* msg = actual->permissions().empty() ? "does not" : "does";

  std::cout << "The caller " << msg << " have permission '" << permission
            << "' on the Cloud Spanner database " << db.database_id() << "\n";
}
See Also

The Cloud Spanner documentation for a description of the roles and permissions supported by Cloud Spanner.

See Also

IAM Overview for an introduction to Identity and Access Management in Google Cloud Platform.

Parameters
Name Description
db Database
permissions std::vector< std::string >
Returns
Type Description
StatusOr< google::iam::v1::TestIamPermissionsResponse >

CreateBackup(Database, std::string, Timestamp, absl::optional< Timestamp >, EncryptionConfig)

Creates a new Cloud Spanner backup for the given database.

Idempotency

This is not an idempotent operation. Transient failures are not retried. This function creates a database backup for the given Google Cloud Spanner database.

Note that the backup_id must be unique within the same instance, it must be between 2 and 60 characters long, it must start with a lowercase letter ([a-z]), it must end with a lowercase letter or a number ([a-z0-9]) and any characters between the beginning and ending characters must be lower case letters, numbers, underscore (_) or dashes (-), that is, they must belong to the [a-z0-9_-] character set.

The expire_time must be at least 6 hours and at most 366 days from the time the CreateBackup() request is processed.

The backup will contain an externally consistent copy of the database at version_time, if set. Otherwise, the version_time will be the create_time of the backup.

encryption_config How to encrypt the backup.

Example
void CreateBackup(google::cloud::spanner_admin::DatabaseAdminClient client,
                  std::string const& project_id, std::string const& instance_id,
                  std::string const& database_id, std::string const& backup_id,
                  google::cloud::spanner::Timestamp expire_time,
                  google::cloud::spanner::Timestamp version_time) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  google::spanner::admin::database::v1::CreateBackupRequest request;
  request.set_parent(database.instance().FullName());
  request.set_backup_id(backup_id);
  request.mutable_backup()->set_database(database.FullName());
  *request.mutable_backup()->mutable_expire_time() =
      expire_time.get<google::protobuf::Timestamp>().value();
  *request.mutable_backup()->mutable_version_time() =
      version_time.get<google::protobuf::Timestamp>().value();
  auto backup = client.CreateBackup(request).get();
  if (!backup) throw std::move(backup).status();
  std::cout
      << "Backup " << backup->name() << " of " << backup->database()
      << " of size " << backup->size_bytes() << " bytes as of "
      << google::cloud::spanner::MakeTimestamp(backup->version_time()).value()
      << " was created at "
      << google::cloud::spanner::MakeTimestamp(backup->create_time()).value()
      << ".\n";
}
Parameters
Name Description
db Database
backup_id std::string
expire_time Timestamp
version_time absl::optional< Timestamp >
encryption_config EncryptionConfig
Returns
Type Description
future< StatusOr< google::spanner::admin::database::v1::Backup > >

A google::cloud::future that becomes satisfied when the operation completes on the service. Note that this can take minutes in some cases.

CreateBackup(Database, std::string, std::chrono::system_clock::time_point)

Creates a new Cloud Spanner backup for the given database.

Idempotency

This is not an idempotent operation. Transient failures are not retried. This function creates a database backup for the given Google Cloud Spanner database.

Note that the backup_id must be unique within the same instance, it must be between 2 and 60 characters long, it must start with a lowercase letter ([a-z]), it must end with a lowercase letter or a number ([a-z0-9]) and any characters between the beginning and ending characters must be lower case letters, numbers, underscore (_) or dashes (-), that is, they must belong to the [a-z0-9_-] character set.

The expire_time must be at least 6 hours and at most 366 days from the time the CreateBackup() request is processed.

Parameters
Name Description
db Database
backup_id std::string
expire_time std::chrono::system_clock::time_point
Returns
Type Description
future< StatusOr< google::spanner::admin::database::v1::Backup > >

A google::cloud::future that becomes satisfied when the operation completes on the service. Note that this can take minutes in some cases.

GetBackup(Backup const &)

Retrieve metadata information about a Backup.

Idempotency

This is a read-only operation and therefore always idempotent. Transient failures are automatically retried.

Example
void GetBackup(google::cloud::spanner_admin::DatabaseAdminClient client,
               std::string const& project_id, std::string const& instance_id,
               std::string const& backup_id) {
  google::cloud::spanner::Backup backup_name(
      google::cloud::spanner::Instance(project_id, instance_id), backup_id);
  auto backup = client.GetBackup(backup_name.FullName());
  if (!backup) throw std::move(backup).status();
  std::cout
      << "Backup " << backup->name() << " of size " << backup->size_bytes()
      << " bytes as of "
      << google::cloud::spanner::MakeTimestamp(backup->version_time()).value()
      << " was created at "
      << google::cloud::spanner::MakeTimestamp(backup->create_time()).value()
      << ".\n";
}
Parameter
Name Description
backup Backup const &
Returns
Type Description
StatusOr< google::spanner::admin::database::v1::Backup >

DeleteBackup(google::spanner::admin::database::v1::Backup const &)

Deletes a pending or completed Backup.

Idempotency

We treat this operation as idempotent. Transient failures are automatically retried.

Parameter
Name Description
backup google::spanner::admin::database::v1::Backup const &
Returns
Type Description
Status

DeleteBackup(Backup const &)

Deletes a pending or completed Backup.

Idempotency

We treat this operation as idempotent. Transient failures are automatically retried.

Example
void DeleteBackup(google::cloud::spanner_admin::DatabaseAdminClient client,
                  std::string const& project_id, std::string const& instance_id,
                  std::string const& backup_id) {
  google::cloud::spanner::Backup backup(
      google::cloud::spanner::Instance(project_id, instance_id), backup_id);
  auto status = client.DeleteBackup(backup.FullName());
  if (!status.ok()) throw std::move(status);
  std::cout << "Backup " << backup.FullName() << " was deleted.\n";
}
Parameter
Name Description
backup Backup const &
Returns
Type Description
Status

ListBackups(Instance, std::string)

List all the backups in a given project and instance that match the filter.

Idempotency

This operation is read-only and therefore always idempotent.

Example
void ListBackups(google::cloud::spanner_admin::DatabaseAdminClient client,
                 std::string const& project_id,
                 std::string const& instance_id) {
  google::cloud::spanner::Instance in(project_id, instance_id);
  std::cout << "All backups:\n";
  for (auto& backup : client.ListBackups(in.FullName())) {
    if (!backup) throw std::move(backup).status();
    std::cout << "Backup " << backup->name() << " on database "
              << backup->database() << " with size : " << backup->size_bytes()
              << " bytes.\n";
  }
}
Parameters
Name Description
in Instance

An instance where the backup operations belong to.

filter std::string

A filter expression that filters backups listed in the response. See this documentation for the syntax of the filter expression.

Returns
Type Description
ListBackupsRange

UpdateBackupExpireTime(google::spanner::admin::database::v1::Backup const &, Timestamp)

Update backup's expire_time.

Idempotency

This operation is idempotent as its result does not depend on the previous state of the backup. Note that, as is the case with all operations, it is subject to race conditions if multiple tasks are attempting to change the expire time in the same backup.

Parameters
Name Description
backup google::spanner::admin::database::v1::Backup const &
expire_time Timestamp
Returns
Type Description
StatusOr< google::spanner::admin::database::v1::Backup >

UpdateBackupExpireTime(Backup const &, Timestamp)

Update backup's expire_time.

Idempotency

This operation is idempotent as its result does not depend on the previous state of the backup. Note that, as is the case with all operations, it is subject to race conditions if multiple tasks are attempting to change the expire time in the same backup.

Example
void UpdateBackup(google::cloud::spanner_admin::DatabaseAdminClient client,
                  std::string const& project_id, std::string const& instance_id,
                  std::string const& backup_id,
                  absl::Duration expiry_extension) {
  google::cloud::spanner::Backup backup_name(
      google::cloud::spanner::Instance(project_id, instance_id), backup_id);
  auto backup = client.GetBackup(backup_name.FullName());
  if (!backup) throw std::move(backup).status();
  auto expire_time =
      google::cloud::spanner::MakeTimestamp(backup->expire_time())
          .value()
          .get<absl::Time>()
          .value();
  expire_time += expiry_extension;
  auto max_expire_time =
      google::cloud::spanner::MakeTimestamp(backup->max_expire_time())
          .value()
          .get<absl::Time>()
          .value();
  if (expire_time > max_expire_time) expire_time = max_expire_time;
  google::spanner::admin::database::v1::UpdateBackupRequest request;
  request.mutable_backup()->set_name(backup_name.FullName());
  *request.mutable_backup()->mutable_expire_time() =
      google::cloud::spanner::MakeTimestamp(expire_time)
          .value()
          .get<google::protobuf::Timestamp>()
          .value();
  request.mutable_update_mask()->add_paths("expire_time");
  backup = client.UpdateBackup(request);
  if (!backup) throw std::move(backup).status();
  std::cout
      << "Backup " << backup->name() << " updated to expire at "
      << google::cloud::spanner::MakeTimestamp(backup->expire_time()).value()
      << ".\n";
}
Parameters
Name Description
backup Backup const &
expire_time Timestamp
Returns
Type Description
StatusOr< google::spanner::admin::database::v1::Backup >

UpdateBackupExpireTime(google::spanner::admin::database::v1::Backup const &, std::chrono::system_clock::time_point const &)

Update backup's expire_time.

Idempotency

This operation is idempotent as its result does not depend on the previous state of the backup. Note that, as is the case with all operations, it is subject to race conditions if multiple tasks are attempting to change the expire time in the same backup.

Parameters
Name Description
backup google::spanner::admin::database::v1::Backup const &
expire_time std::chrono::system_clock::time_point const &
Returns
Type Description
StatusOr< google::spanner::admin::database::v1::Backup >

UpdateBackupExpireTime(Backup const &, std::chrono::system_clock::time_point const &)

Update backup's expire_time.

Idempotency

This operation is idempotent as its result does not depend on the previous state of the backup. Note that, as is the case with all operations, it is subject to race conditions if multiple tasks are attempting to change the expire time in the same backup.

Parameters
Name Description
backup Backup const &
expire_time std::chrono::system_clock::time_point const &
Returns
Type Description
StatusOr< google::spanner::admin::database::v1::Backup >

ListBackupOperations(Instance, std::string)

List all the backup operations in a given project and instance that match the filter.

Idempotency

This operation is read-only and therefore always idempotent.

Example
void ListBackupOperations(
    google::cloud::spanner_admin::DatabaseAdminClient client,
    std::string const& project_id, std::string const& instance_id,
    std::string const& database_id, std::string const& backup_id) {
  google::cloud::spanner::Instance in(project_id, instance_id);
  google::cloud::spanner::Database database(in, database_id);
  google::cloud::spanner::Backup backup(in, backup_id);

  google::spanner::admin::database::v1::ListBackupOperationsRequest request;
  request.set_parent(in.FullName());

  request.set_filter(std::string("(metadata.@type=type.googleapis.com/") +
                     "google.spanner.admin.database.v1.CreateBackupMetadata)" +
                     " AND (metadata.database=" + database.FullName() + ")");
  for (auto& operation : client.ListBackupOperations(request)) {
    if (!operation) throw std::move(operation).status();
    google::spanner::admin::database::v1::CreateBackupMetadata metadata;
    operation->metadata().UnpackTo(&metadata);
    std::cout << "Backup " << metadata.name() << " of database "
              << metadata.database() << " is "
              << metadata.progress().progress_percent() << "% complete.\n";
  }

  request.set_filter(std::string("(metadata.@type:type.googleapis.com/") +
                     "google.spanner.admin.database.v1.CopyBackupMetadata)" +
                     " AND (metadata.source_backup=" + backup.FullName() + ")");
  for (auto& operation : client.ListBackupOperations(request)) {
    if (!operation) throw std::move(operation).status();
    google::spanner::admin::database::v1::CopyBackupMetadata metadata;
    operation->metadata().UnpackTo(&metadata);
    std::cout << "Copy " << metadata.name() << " of backup "
              << metadata.source_backup() << " is "
              << metadata.progress().progress_percent() << "% complete.\n";
  }
}
Parameters
Name Description
in Instance

An instance where the backup operations belong to.

filter std::string

A filter expression that filters what operations are returned in the response. See this documentation for the syntax of the filter expression.

Returns
Type Description
ListBackupOperationsRange

ListDatabaseOperations(Instance, std::string)

List all the database operations in a given project and instance that match the filter.

Idempotency

This operation is read-only and therefore always idempotent.

Example
void ListDatabaseOperations(
    google::cloud::spanner_admin::DatabaseAdminClient client,
    std::string const& project_id, std::string const& instance_id) {
  google::cloud::spanner::Instance in(project_id, instance_id);
  google::spanner::admin::database::v1::ListDatabaseOperationsRequest request;
  request.set_parent(in.FullName());
  request.set_filter(
      "(metadata.@type:type.googleapis.com/"
      "google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata)");
  for (auto& operation : client.ListDatabaseOperations(request)) {
    if (!operation) throw std::move(operation).status();
    google::spanner::admin::database::v1::OptimizeRestoredDatabaseMetadata
        metadata;
    operation->metadata().UnpackTo(&metadata);
    std::cout << "Database " << metadata.name() << " restored from backup is "
              << metadata.progress().progress_percent() << "% optimized.\n";
  }
}
Parameters
Name Description
in Instance

An instance where the database operations belong to.

filter std::string

A filter expression that filters what operations are returned in the response. See this documentation for the syntax of the filter expression.

Returns
Type Description
ListDatabaseOperationsRange