更新备份

通过检索并延长备份的过期时间来更新备份。

包含此代码示例的文档页面

如需查看上下文中使用的代码示例,请参阅以下文档:

代码示例

C#

如需了解如何安装和使用 Cloud Spanner 客户端库,请参阅 Cloud Spanner 客户端库


using Google.Cloud.Spanner.Admin.Database.V1;
using Google.Protobuf.WellKnownTypes;
using System;

namespace GoogleCloudSamples.Spanner
{
    public class UpdateBackup
    {
        public static object SpannerUpdateBackup(string projectId, string instanceId, string backupId)
        {
            // Create the DatabaseAdminClient instance.
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

            // Retrieve existing backup.
            BackupName backupName =
                BackupName.FromProjectInstanceBackup(projectId, instanceId, backupId);
            Backup backup = databaseAdminClient.GetBackup(backupName);

            // Add 1 hour to the existing ExpireTime.
            backup.ExpireTime = backup.ExpireTime.ToDateTime().AddHours(1).ToTimestamp();

            UpdateBackupRequest backupUpdateRequest = new UpdateBackupRequest
            {
                UpdateMask = new FieldMask()
                {
                    Paths =
                    {
                        "expire_time"
                    }
                },
                Backup = backup
            };

            // Make the UpdateBackup requests.
            var updatedBackup = databaseAdminClient.UpdateBackup(backupUpdateRequest);

            Console.WriteLine($"Updated Backup ExpireTime: {updatedBackup.ExpireTime}");

            return 0;
        }
    }
}

C++

如需了解如何安装和使用 Cloud Spanner 客户端库,请参阅 Cloud Spanner 客户端库

void UpdateBackup(google::cloud::spanner::DatabaseAdminClient client,
                  std::string const& project_id, std::string const& instance_id,
                  std::string const& backup_id,
                  google::cloud::spanner::Timestamp expire_time) {
  google::cloud::spanner::Backup backup_name(
      google::cloud::spanner::Instance(project_id, instance_id), backup_id);
  auto backup = client.UpdateBackupExpireTime(backup_name, expire_time);
  if (!backup) throw std::runtime_error(backup.status().message());
  std::cout
      << "Backup " << backup->name() << " updated to expire at "
      << google::cloud::spanner::MakeTimestamp(backup->expire_time()).value()
      << ".\n";
}

Go

如需了解如何安装和使用 Cloud Spanner 客户端库,请参阅 Cloud Spanner 客户端库


import (
	"context"
	"fmt"
	"io"
	"regexp"
	"time"

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	pbts "github.com/golang/protobuf/ptypes"
	adminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1"
	"google.golang.org/genproto/protobuf/field_mask"
)

func updateBackup(ctx context.Context, w io.Writer, db, backupID string) error {
	adminClient, err := database.NewDatabaseAdminClient(ctx)
	if err != nil {
		return err
	}
	defer adminClient.Close()

	matches := regexp.MustCompile("^(.*)/databases/(.*)$").FindStringSubmatch(db)
	if matches == nil || len(matches) != 3 {
		return fmt.Errorf("Invalid database id %s", db)
	}
	backupName := matches[1] + "/backups/" + backupID

	backup, err := adminClient.GetBackup(ctx, &adminpb.GetBackupRequest{Name: backupName})
	if err != nil {
		return err
	}

	// Expire time must be within 366 days of the create time of the backup.
	expireTime := time.Unix(backup.CreateTime.Seconds, int64(backup.CreateTime.Nanos)).AddDate(0, 0, 30)
	expirespb, err := pbts.TimestampProto(expireTime)
	if err != nil {
		return err
	}

	_, err = adminClient.UpdateBackup(ctx, &adminpb.UpdateBackupRequest{
		Backup: &adminpb.Backup{
			Name:       backupName,
			ExpireTime: expirespb,
		},
		UpdateMask: &field_mask.FieldMask{Paths: []string{"expire_time"}},
	})
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Updated backup %s\n", backupID)
	return nil
}

Java

如需了解如何安装和使用 Cloud Spanner 客户端库,请参阅 Cloud Spanner 客户端库

static void updateBackup(DatabaseAdminClient dbAdminClient, BackupId backupId) {
  // Get current backup metadata.
  Backup backup = dbAdminClient.newBackupBuilder(backupId).build().reload();
  // Add 30 days to the expire time.
  // Expire time must be within 366 days of the create time of the backup.
  Timestamp expireTime =
      Timestamp.ofTimeMicroseconds(
          TimeUnit.SECONDS.toMicros(backup.getExpireTime().getSeconds())
              + TimeUnit.NANOSECONDS.toMicros(backup.getExpireTime().getNanos())
              + TimeUnit.DAYS.toMicros(30L));
  System.out.println(String.format(
      "Updating expire time of backup [%s] to %s...",
      backupId.toString(),
      LocalDateTime.ofEpochSecond(
          expireTime.getSeconds(),
          expireTime.getNanos(),
          OffsetDateTime.now().getOffset()).toString()));

  // Update expire time.
  backup = backup.toBuilder().setExpireTime(expireTime).build();
  backup.updateExpireTime();
  System.out.println("Updated backup [" + backupId + "]");
}

Node.js

如需了解如何安装和使用 Cloud Spanner 客户端库,请参阅 Cloud Spanner 客户端库

// Imports the Google Cloud client library and precise date library
const {Spanner} = require('@google-cloud/spanner');
const {PreciseDate} = require('@google-cloud/precise-date');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const backupId = 'my-backup';

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

// Gets a reference to a Cloud Spanner instance and backup
const instance = spanner.instance(instanceId);
const backup = instance.backup(backupId);

// Read backup metadata and update expiry time
try {
  const currentExpireTime = await backup.getExpireTime();
  const newExpireTime = new PreciseDate(currentExpireTime);
  newExpireTime.setDate(newExpireTime.getDate() + 30);
  console.log(
    `Backup ${backupId} current expire time: ${currentExpireTime.toISOString()}`
  );
  console.log(`Updating expire time to ${newExpireTime.toISOString()}`);
  await backup.updateExpireTime(newExpireTime);
  console.log('Expire time updated.');
} catch (err) {
  console.error('ERROR:', err);
}

PHP

如需了解如何安装和使用 Cloud Spanner 客户端库,请参阅 Cloud Spanner 客户端库

use Google\Cloud\Spanner\SpannerClient;

/**
 * Update the backup expire time.
 * Example:
 * ```
 * update_backup($instanceId, $backupId);
 * ```
 * @param string $instanceId The Spanner instance ID.
 * @param string $backupId The Spanner backup ID.
 */
function update_backup($instanceId, $backupId)
{
    $spanner = new SpannerClient();
    $instance = $spanner->instance($instanceId);
    $backup = $instance->backup($backupId);

    // Expire time must be within 366 days of the create time of the backup.
    $newTimestamp = new \DateTime('+30 days');
    $backup->updateExpireTime($newTimestamp);

    print("Backup $backupId new expire time: " . $backup->info()['expireTime'] . PHP_EOL);
}

Python

如需了解如何安装和使用 Cloud Spanner 客户端库,请参阅 Cloud Spanner 客户端库

def update_backup(instance_id, backup_id):
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    backup = instance.backup(backup_id)
    backup.reload()

    # Expire time must be within 366 days of the create time of the backup.
    old_expire_time = backup.expire_time
    new_expire_time = old_expire_time + timedelta(days=30)
    backup.update_expire_time(new_expire_time)
    print(
        "Backup {} expire time was updated from {} to {}.".format(
            backup.name, old_expire_time, new_expire_time
        )
    )

Ruby

如需了解如何安装和使用 Cloud Spanner 客户端库,请参阅 Cloud Spanner 客户端库

# project_id  = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# backup_id = "Your Spanner backup ID"

require "google/cloud/spanner"

spanner  = Google::Cloud::Spanner.new project: project_id
instance = spanner.instance instance_id

backup = instance.backup backup_id
backup.expire_time = backup.expire_time + 2_592_000 # Extending the expiry time by 30 days.

puts "Expiration time updated: #{backup.expire_time}"

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器