List backups

List all backups and access backup data using filters and paging.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

C#

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.


using Google.Api.Gax;
using Google.Cloud.Spanner.Admin.Database.V1;
using Google.Cloud.Spanner.Common.V1;
using System;
using System.Collections.Generic;

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

            InstanceName parentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId);

            // List all backups.
            Console.WriteLine("All backups:");
            var allBackups = databaseAdminClient.ListBackups(parentAsInstanceName);
            PrintBackups(allBackups);

            ListBackupsRequest request = new ListBackupsRequest
            {
                ParentAsInstanceName = parentAsInstanceName,
            };

            // List backups containing backup name.
            Console.WriteLine($"Backups with backup name containing {backupId}:");
            request.Filter = $"name:{backupId}";
            var backupsWithName = databaseAdminClient.ListBackups(request);
            PrintBackups(backupsWithName);

            // List backups on a database containing name.
            Console.WriteLine($"Backups with database name containing {databaseId}:");
            request.Filter = $"database:{databaseId}";
            var backupsWithDatabaseName = databaseAdminClient.ListBackups(request);
            PrintBackups(backupsWithDatabaseName);

            // List backups that expire within 30 days.
            Console.WriteLine("Backups expiring within 30 days:");
            string expireTime = DateTime.UtcNow.AddDays(30).ToString("O");
            request.Filter = $"expire_time < \"{expireTime}\"";
            var expiringBackups = databaseAdminClient.ListBackups(request);
            PrintBackups(expiringBackups);

            // List backups with a size greater than 100 bytes.
            Console.WriteLine("Backups with size > 100 bytes:");
            request.Filter = "size_bytes > 100";
            var backupsWithSize = databaseAdminClient.ListBackups(request);
            PrintBackups(backupsWithSize);

            // List backups created in the last day that are ready.
            Console.WriteLine("Backups created within last day that are ready:");
            string createTime = DateTime.UtcNow.AddDays(-1).ToString("O");
            request.Filter = $"create_time >= \"{createTime}\" AND state:READY";
            var recentReadyBackups = databaseAdminClient.ListBackups(request);
            PrintBackups(recentReadyBackups);

            // List backups in pages.
            Console.WriteLine("Backups in batches of 5:");
            int pageSize = 5;
            string nextPageToken = string.Empty;
            do
            {
                var response = databaseAdminClient.ListBackups(parentAsInstanceName, nextPageToken);
                Page<Backup> currentPage = response.ReadPage(pageSize);
                PrintBackups(currentPage);
                nextPageToken = currentPage.NextPageToken;
            } while (!string.IsNullOrEmpty(nextPageToken));

            return 0;
        }

        private static void PrintBackups(IEnumerable<Backup> backups)
        {
            foreach (Backup backup in backups)
            {
                Console.WriteLine($"Backup Name : {backup.Name}");
            };
        }
    }
}

C++

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

void ListBackups(google::cloud::spanner::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 const& backup : client.ListBackups(in)) {
    if (!backup) throw std::runtime_error(backup.status().message());
    std::cout << "Backup " << backup->name() << " on database "
              << backup->database() << " with size : " << backup->size_bytes()
              << " bytes.\n";
  }
}

Go

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.


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

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	"google.golang.org/api/iterator"
	adminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1"
)

func listBackups(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)
	}
	instanceName := matches[1]

	printBackups := func(iter *database.BackupIterator) error {
		for {
			resp, err := iter.Next()
			if err == iterator.Done {
				return nil
			}
			if err != nil {
				return err
			}
			fmt.Fprintf(w, "Backup %s\n", resp.Name)
		}
	}

	var iter *database.BackupIterator
	var filter string
	// List all backups.
	iter = adminClient.ListBackups(ctx, &adminpb.ListBackupsRequest{
		Parent: instanceName,
	})
	if err := printBackups(iter); err != nil {
		return err
	}

	// List all backups that contain a name.
	iter = adminClient.ListBackups(ctx, &adminpb.ListBackupsRequest{
		Parent: instanceName,
		Filter: "name:" + backupID,
	})
	if err := printBackups(iter); err != nil {
		return err
	}

	// List all backups that expire before a timestamp.
	expireTime := time.Now().AddDate(0, 0, 30)
	filter = fmt.Sprintf(`expire_time < "%s"`, expireTime.Format(time.RFC3339))
	iter = adminClient.ListBackups(ctx, &adminpb.ListBackupsRequest{
		Parent: instanceName,
		Filter: filter,
	})
	if err := printBackups(iter); err != nil {
		return err
	}

	// List all backups for a database that contains a name.
	iter = adminClient.ListBackups(ctx, &adminpb.ListBackupsRequest{
		Parent: instanceName,
		Filter: "database:" + db,
	})
	if err := printBackups(iter); err != nil {
		return err
	}

	// List all backups with a size greater than some bytes.
	iter = adminClient.ListBackups(ctx, &adminpb.ListBackupsRequest{
		Parent: instanceName,
		Filter: "size_bytes > 100",
	})
	if err := printBackups(iter); err != nil {
		return err
	}

	// List backups that were created after a timestamp that are also ready.
	createTime := time.Now().AddDate(0, 0, -1)
	filter = fmt.Sprintf(
		`create_time >= "%s" AND state:READY`,
		createTime.Format(time.RFC3339),
	)
	iter = adminClient.ListBackups(ctx, &adminpb.ListBackupsRequest{
		Parent: instanceName,
		Filter: filter,
	})
	if err := printBackups(iter); err != nil {
		return err
	}

	// List backups with pagination.
	request := &adminpb.ListBackupsRequest{
		Parent:   instanceName,
		PageSize: 10,
	}
	for {
		iter = adminClient.ListBackups(ctx, request)
		if err := printBackups(iter); err != nil {
			return err
		}
		pageToken := iter.PageInfo().Token
		if pageToken == "" {
			break
		} else {
			request.PageToken = pageToken
		}
	}

	fmt.Fprintf(w, "Backups listed.\n")
	return nil
}

Java

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

static void listBackups(
    InstanceAdminClient instanceAdminClient, DatabaseId databaseId, BackupId backupId) {
  Instance instance = instanceAdminClient.getInstance(databaseId.getInstanceId().getInstance());
  // List all backups.
  System.out.println("All backups:");
  for (Backup backup : instance.listBackups().iterateAll()) {
    System.out.println(backup);
  }

  // List all backups with a specific name.
  System.out.println(
      String.format("All backups with backup name containing \"%s\":", backupId.getBackup()));
  for (Backup backup : instance.listBackups(
      Options.filter(String.format("name:%s", backupId.getBackup()))).iterateAll()) {
    System.out.println(backup);
  }

  // List all backups for databases whose name contains a certain text.
  System.out.println(
      String.format(
          "All backups for databases with a name containing \"%s\":",
          databaseId.getDatabase()));
  for (Backup backup : instance.listBackups(
      Options.filter(String.format("database:%s", databaseId.getDatabase()))).iterateAll()) {
    System.out.println(backup);
  }

  // List all backups that expire before a certain time.
  Timestamp expireTime = Timestamp.ofTimeMicroseconds(TimeUnit.MICROSECONDS.convert(
      System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30), TimeUnit.MILLISECONDS));
  System.out.println(String.format("All backups that expire before %s:", expireTime.toString()));
  for (Backup backup :
      instance.listBackups(
          Options.filter(String.format("expire_time < \"%s\"", expireTime.toString())))
      .iterateAll()) {
    System.out.println(backup);
  }

  // List all backups with size greater than a certain number of bytes.
  System.out.println("All backups with size greater than 100 bytes:");
  for (Backup backup : instance.listBackups(Options.filter("size_bytes > 100")).iterateAll()) {
    System.out.println(backup);
  }

  // List all backups with a create time after a certain timestamp and that are also ready.
  Timestamp createTime = Timestamp.ofTimeMicroseconds(TimeUnit.MICROSECONDS.convert(
      System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS));
  System.out.println(
      String.format(
          "All databases created after %s and that are ready:", createTime.toString()));
  for (Backup backup :
      instance
          .listBackups(Options.filter(
              String.format("create_time >= \"%s\" AND state:READY", createTime.toString())))
          .iterateAll()) {
    System.out.println(backup);
  }

  // List backups using pagination.
  System.out.println("All backups, listed using pagination:");
  Page<Backup> page = instance.listBackups(Options.pageSize(10));
  while (true) {
    for (Backup backup : page.getValues()) {
      System.out.println(backup);
    }
    if (!page.hasNextPage()) {
      break;
    }
    page = page.getNextPage();
  }
}

Node.js

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

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

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

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

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

try {
  // List all backups
  const [allBackups] = await instance.getBackups();
  console.log('All backups:');
  allBackups.forEach(backup => {
    console.log(backup.id);
  });

  // List backups filtered by backup name
  const [backupsByName] = await instance.getBackups({
    filter: `Name:${backupId}`,
  });
  console.log('Backups matching backup name:');
  backupsByName.forEach(backup => {
    console.log(backup.id);
  });

  // List backups expiring within 30 days
  const expireTime = new Date();
  expireTime.setDate(expireTime.getDate() + 30);
  const [backupsByExpiry] = await instance.getBackups({
    filter: `expire_time < "${expireTime.toISOString()}"`,
  });
  console.log('Backups expiring within 30 days:');
  backupsByExpiry.forEach(backup => {
    console.log(backup.id);
  });

  // List backups filtered by database name
  const [backupsByDbName] = await instance.getBackups({
    filter: `Database:${databaseId}`,
  });
  console.log('Backups matching database name:');
  backupsByDbName.forEach(backup => {
    console.log(backup.id);
  });

  // List backups filtered by backup size
  const [backupsBySize] = await instance.getBackups({
    filter: 'size_bytes > 100',
  });
  console.log('Backups filtered by size:');
  backupsBySize.forEach(backup => {
    console.log(backup.id);
  });

  // List backups that are ready that were created after a certain time
  const createTime = new Date();
  createTime.setDate(createTime.getDate() - 1);
  const [backupsByCreateTime] = await instance.getBackups({
    filter: `(state:READY) AND (create_time >= "${createTime.toISOString()}")`,
  });
  console.log('Ready backups filtered by create time:');
  backupsByCreateTime.forEach(backup => {
    console.log(backup.id);
  });

  // List backups using pagination
  let getBackupsOptions = {
    pageSize: 3,
    gaxOptions: {autoPaginate: false},
  };
  console.log('Get backups paginated:');
  do {
    const [backups, nextQuery] = await instance.getBackups(getBackupsOptions);
    backups.forEach(backup => {
      console.log(backup.id);
    });
    getBackupsOptions = nextQuery;
  } while (getBackupsOptions);
} catch (err) {
  console.error('ERROR:', err);
}

PHP

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

use Google\Cloud\Spanner\SpannerClient;

/**
 * List backups in an instance.
 * Example:
 * ```
 * list_backups($instanceId, $databaseId);
 * ```
 *
 * @param string $instanceId The Spanner instance ID.
 */
function list_backups($instanceId)
{
    $spanner = new SpannerClient();
    $instance = $spanner->instance($instanceId);

    // List all backups.
    print('All backups:' . PHP_EOL);
    foreach ($instance->backups() as $backup) {
        print('  ' . basename($backup->name()) . PHP_EOL);
    }

    // List all backups that contain a name.
    $backupName = 'backup-test-';
    print("All backups with name containing \"$backupName\":" . PHP_EOL);
    $filter = "name:$backupName";
    foreach ($instance->backups(['filter' => $filter]) as $backup) {
        print('  ' . basename($backup->name()) . PHP_EOL);
    }

    // List all backups for a database that contains a name.
    $databaseId = 'test-';
    print("All backups for a database which name contains \"$databaseId\":" . PHP_EOL);
    $filter = "database:$databaseId";
    foreach ($instance->backups(['filter' => $filter]) as $backup) {
        print('  ' . basename($backup->name()) . PHP_EOL);
    }

    // List all backups that expire before a timestamp.
    $expireTime = $spanner->timestamp(new \DateTime('+30 days'));
    print("All backups that expire before $expireTime:" . PHP_EOL);
    $filter ="expire_time < \"$expireTime\"";
    foreach ($instance->backups(['filter' => $filter]) as $backup) {
        print('  ' . basename($backup->name()) . PHP_EOL);
    }

    // List all backups with a size greater than some bytes.
    $size = 500;
    print("All backups with size greater than $size bytes:" . PHP_EOL);
    $filter = "size_bytes > $size";
    foreach ($instance->backups(['filter' => $filter]) as $backup) {
        print('  ' . basename($backup->name()) . PHP_EOL);
    }

    // List backups that were created after a timestamp that are also ready.
    $createTime = $spanner->timestamp(new \DateTime('-1 day'));
    print("All backups created after $createTime:" . PHP_EOL);
    $filter = "create_time >= \"$createTime\" AND state:READY";
    foreach ($instance->backups(['filter' => $filter]) as $backup) {
        print('  ' . basename($backup->name()) . PHP_EOL);
    }

    // List backups with pagination.
    print('All backups with pagination:' . PHP_EOL);
    $pages = $instance->backups(['pageSize' => 2])->iterateByPage();
    foreach ($pages as $pageNumber => $page) {
        print("All backups, page $pageNumber:" . PHP_EOL);
        foreach ($page as $backup) {
            print('  ' . basename($backup->name()) . PHP_EOL);
        }
    }
}

Python

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

def list_backups(instance_id, database_id, backup_id):
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)

    # List all backups.
    print("All backups:")
    for backup in instance.list_backups():
        print(backup.name)

    # List all backups that contain a name.
    print('All backups with backup name containing "{}":'.format(backup_id))
    for backup in instance.list_backups(filter_="name:{}".format(backup_id)):
        print(backup.name)

    # List all backups for a database that contains a name.
    print('All backups with database name containing "{}":'.format(database_id))
    for backup in instance.list_backups(filter_="database:{}".format(database_id)):
        print(backup.name)

    # List all backups that expire before a timestamp.
    expire_time = datetime.utcnow().replace(microsecond=0) + timedelta(days=30)
    print(
        'All backups with expire_time before "{}-{}-{}T{}:{}:{}Z":'.format(
            *expire_time.timetuple()
        )
    )
    for backup in instance.list_backups(
        filter_='expire_time < "{}-{}-{}T{}:{}:{}Z"'.format(*expire_time.timetuple())
    ):
        print(backup.name)

    # List all backups with a size greater than some bytes.
    print("All backups with backup size more than 100 bytes:")
    for backup in instance.list_backups(filter_="size_bytes > 100"):
        print(backup.name)

    # List backups that were created after a timestamp that are also ready.
    create_time = datetime.utcnow().replace(microsecond=0) - timedelta(days=1)
    print(
        'All backups created after "{}-{}-{}T{}:{}:{}Z" and are READY:'.format(
            *create_time.timetuple()
        )
    )
    for backup in instance.list_backups(
        filter_='create_time >= "{}-{}-{}T{}:{}:{}Z" AND state:READY'.format(
            *create_time.timetuple()
        )
    ):
        print(backup.name)

    print("All backups with pagination")
    # If there are multiple pages, additional ``ListBackup``
    # requests will be made as needed while iterating.
    for backup in instance.list_backups(page_size=2):
        print(backup.name)

Ruby

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

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

require "google/cloud/spanner"

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

puts "All backups"
instance.backups.all.each do |backup|
  puts backup.backup_id
end

puts "All backups with backup name containing \"#{backup_id}\":"
instance.backups(filter: "name:#{backup_id}").all.each do |backup|
  puts backup.backup_id
end

puts "All backups for databases with a name containing \"#{database_id}\":"
instance.backups(filter: "database:#{database_id}").all.each do |backup|
  puts backup.backup_id
end

puts "All backups that expire before a timestamp:"
expire_time = Time.now + 30 * 24 * 3600 # 30 days from now
instance.backups(filter: "expire_time < \"#{expire_time.iso8601}\"").all.each do |backup|
  puts backup.backup_id
end

puts "All backups with a size greater than 500 bytes:"
instance.backups(filter: "size_bytes >= 500").all.each do |backup|
  puts backup.backup_id
end

puts "All backups that were created after a timestamp that are also ready:"
create_time = Time.now - 24 * 3600 # From 1 day ago
instance.backups(filter: "create_time >= \"#{create_time.iso8601}\" AND state:READY").all.each do |backup|
  puts backup.backup_id
end

puts "All backups with pagination:"
list = instance.backups page_size: 5
list.each do |backup|
  puts backup.backup_id
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser