Modify the leader region of a database

This page explains how to modify theleader regionof a database. You can only change the leader region of a Spannerinstance that uses a dual-region or multi-region instance configuration. The newleader region must be one of the two read-write regions within thedual-regionormulti-regionconfiguration of your database. For more information about changing the leaderregion, seeConfigure the default leader region.

To view data on the database leader distribution of a dual-region ormulti-regioninstance, open the Google Cloud console, and refer to theLeader distributioncharts. For more information, seeSpanner charts and metrics.

Change the leader region of a database

You can change the leader region of a database. To monitor the progress of thischange, you can refer to theLeader distribution chart.

Console

  1. Go to theSpanner Instances page in the Google Cloud console.

    Go to the Instances page

  2. Click the name of the instance that contains the database whose leaderregion you want to change.

  3. Click the database whose leader region you want to change.

  4. Click the pencil icon next toLeader Region.

  5. Modify the DDL statement with your selected leader region asdefault_leader.

gcloud

  1. To change the leader region of an existing database, run the followingcommand:

    gcloud spanner databases ddl updateDATABASE_NAME \--instance=INSTANCE_ID \--ddl='ALTER DATABASE `DATABASE_NAME` \ SET OPTIONS ( default_leader = "REGION" )'

    Replace the following:

    • DATABASE_NAME: the name of your database.
    • INSTANCE_ID: the identifier of your databaseinstance.
    • REGION: the region you want to set as thedefault leader.

Client libraries

C#

usingGoogle.Cloud.Spanner.Admin.Database.V1;usingGoogle.Cloud.Spanner.Common.V1;usingGoogle.LongRunning;usingGoogle.Protobuf.WellKnownTypes;usingSystem;usingSystem.Threading.Tasks;publicclassUpdateDatabaseWithDefaultLeaderAsyncSample{publicasyncTask<Operation<Empty,UpdateDatabaseDdlMetadata>>UpdateDatabaseWithDefaultLeaderAsync(stringprojectId,stringinstanceId,stringdatabaseId,stringdefaultLeader){DatabaseAdminClientdatabaseAdminClient=awaitDatabaseAdminClient.CreateAsync();varalterDatabaseStatement=@$"ALTER DATABASE `{databaseId}` SET OPTIONS(default_leader='{defaultLeader}')";// Create the UpdateDatabaseDdl request and execute it.varrequest=newUpdateDatabaseDdlRequest{DatabaseAsDatabaseName=DatabaseName.FromProjectInstanceDatabase(projectId,instanceId,databaseId),Statements={alterDatabaseStatement}};varoperation=awaitdatabaseAdminClient.UpdateDatabaseDdlAsync(request);// Wait until the operation has finished.Console.WriteLine("Waiting for the operation to finish.");Operation<Empty,UpdateDatabaseDdlMetadata>completedResponse=awaitoperation.PollUntilCompletedAsync();if(completedResponse.IsFaulted){Console.WriteLine($"Error while updating database: {completedResponse.Exception}");throwcompletedResponse.Exception;}Console.WriteLine("Updated default leader");returncompletedResponse;}}

C++

voidUpdateDatabaseWithDefaultLeader(google::cloud::spanner_admin::DatabaseAdminClientclient,std::stringconst&project_id,std::stringconst&instance_id,std::stringconst&database_id,std::stringconst&default_leader){google::cloud::spanner::Databasedatabase(project_id,instance_id,database_id);std::vector<std::string>statements;statements.push_back("ALTER DATABASE `"+database_id+"` "+"SET OPTIONS (default_leader='"+default_leader+"')");autometadata=client.UpdateDatabaseDdl(database.FullName(),std::move(statements)).get();if(!metadata)throwstd::move(metadata).status();std::cout <<"`default_leader` altered, new DDL metadata:\n"            <<metadata->DebugString();}

Go

import("context""fmt""io""regexp"database"cloud.google.com/go/spanner/admin/database/apiv1"adminpb"cloud.google.com/go/spanner/admin/database/apiv1/databasepb")// updateDatabaseWithDefaultLeader updates the default leader for a given databasefuncupdateDatabaseWithDefaultLeader(wio.Writer,dbstring,defaultLeaderstring)error{// db = `projects/<project>/instances/<instance-id>/database/<database-id>`// defaultLeader = `nam3`matches:=regexp.MustCompile("^(.+)/databases/(.+)$").FindStringSubmatch(db)ifmatches==nil||len(matches)!=3{returnfmt.Errorf("updateDatabaseWithDefaultLeader: invalid database id %q",db)}ctx:=context.Background()adminClient,err:=database.NewDatabaseAdminClient(ctx)iferr!=nil{returnerr}deferadminClient.Close()op,err:=adminClient.UpdateDatabaseDdl(ctx,&adminpb.UpdateDatabaseDdlRequest{Database:db,Statements:[]string{fmt.Sprintf("ALTER DATABASE `%s` SET OPTIONS (default_leader = '%s')",matches[2],defaultLeader,),},})iferr!=nil{returnerr}iferr:=op.Wait(ctx);err!=nil{returnerr}fmt.Fprintf(w,"Updated the default leader\n")returnnil}

Java

importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerException;importcom.google.cloud.spanner.SpannerExceptionFactory;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;importcom.google.spanner.admin.database.v1.DatabaseName;importjava.util.Collections;importjava.util.concurrent.ExecutionException;publicclassUpdateDatabaseWithDefaultLeaderSample{staticvoidupdateDatabaseWithDefaultLeader(){// TODO(developer): Replace these variables before running the sample.finalStringprojectId="my-project";finalStringinstanceId="my-instance";finalStringdatabaseId="my-database";finalStringdefaultLeader="my-default-leader";updateDatabaseWithDefaultLeader(projectId,instanceId,databaseId,defaultLeader);}staticvoidupdateDatabaseWithDefaultLeader(StringprojectId,StringinstanceId,StringdatabaseId,StringdefaultLeader){try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();DatabaseAdminClientdatabaseAdminClient=spanner.createDatabaseAdminClient()){databaseAdminClient.updateDatabaseDdlAsync(DatabaseName.of(projectId,instanceId,databaseId),Collections.singletonList(String.format("ALTER DATABASE `%s` SET OPTIONS (default_leader = '%s')",databaseId,defaultLeader))).get();System.out.println("Updated default leader to "+defaultLeader);}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throw(SpannerException)e.getCause();}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}}

Note: The old client library interface code samples for Java are archived inGitHub.

Node.js

/** * TODO(developer): Uncomment the following lines before running the sample. */// const projectId = 'my-project-id';// const instanceId = 'my-instance-id';// const databaseId = 'my-database-id';// const defaultLeader = 'my-default-leader';// Imports the Google Cloud client libraryconst{Spanner}=require('@google-cloud/spanner');// creates a clientconstspanner=newSpanner({projectId:projectId,});constdatabaseAdminClient=spanner.getDatabaseAdminClient();asyncfunctionupdateDatabaseWithDefaultLeader(){console.log(`Updating database${databaseAdminClient.databasePath(projectId,instanceId,databaseId,)}.`,);constsetDefaultLeaderStatement=`    ALTER DATABASE \`${databaseId}\`    SET OPTIONS (default_leader = '${defaultLeader}')`;const[operation]=awaitdatabaseAdminClient.updateDatabaseDdl({database:databaseAdminClient.databasePath(projectId,instanceId,databaseId,),statements:[setDefaultLeaderStatement],});console.log(`Waiting for updating of${databaseId} to complete...`);awaitoperation.promise();console.log(`Updated database${databaseId} with default leader${defaultLeader}.`,);}updateDatabaseWithDefaultLeader();

Note: The old client library interface code samples for Node.js are archived inGitHub.

PHP

use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient;use Google\Cloud\Spanner\Admin\Database\V1\GetDatabaseRequest;use Google\Cloud\Spanner\Admin\Database\V1\UpdateDatabaseDdlRequest;/** * Updates the default leader of the database. * Example: * ``` * update_database_with_default_leader($projectId, $instanceId, $databaseId, $defaultLeader); * ``` * * @param string $projectId The Google Cloud project ID. * @param string $instanceId The Spanner instance ID. * @param string $databaseId The Spanner database ID. * @param string $defaultLeader The leader instance configuration used by default. */function update_database_with_default_leader(    string $projectId,    string $instanceId,    string $databaseId,    string $defaultLeader): void {    $databaseAdminClient = new DatabaseAdminClient();    $databaseName = DatabaseAdminClient::databaseName($projectId, $instanceId, $databaseId);    $statement = "ALTER DATABASE `$databaseId` SET OPTIONS (default_leader = '$defaultLeader')";    $request = new UpdateDatabaseDdlRequest([        'database' => $databaseName,        'statements' => [$statement]    ]);    $operation = $databaseAdminClient->updateDatabaseDdl($request);    print('Waiting for operation to complete...' . PHP_EOL);    $operation->pollUntilComplete();    $database = $databaseAdminClient->getDatabase(        new GetDatabaseRequest(['name' => $databaseName])    );    printf('Updated the default leader to %s' . PHP_EOL, $database->getDefaultLeader());}

Note: The old client library interface code samples for PHP are archived inGitHub.

Python

defupdate_database_with_default_leader(instance_id,database_id,default_leader):"""Updates a database with tables with a default leader."""fromgoogle.cloud.spanner_admin_database_v1.typesimportspanner_database_adminspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_apirequest=spanner_database_admin.UpdateDatabaseDdlRequest(database=database_admin_api.database_path(spanner_client.project,instance_id,database_id),statements=["ALTER DATABASE{}"" SET OPTIONS (default_leader = '{}')".format(database_id,default_leader)],)operation=database_admin_api.update_database_ddl(request)operation.result(OPERATION_TIMEOUT_SECONDS)print("Database{} updated with default leader{}".format(database_id,default_leader))

Note: The old client library interface code samples for Python are archived inGitHub.

Ruby

# project_id  = "Your Google Cloud project ID"# instance_id = "Your Spanner instance ID"# database_id = "Your Spanner database ID"# default_leader = "Spanner database default leader"require"google/cloud/spanner"require"google/cloud/spanner/admin/database"db_admin_client=Google::Cloud::Spanner::Admin::Database.database_adminproject_id:project_iddb_path=db_admin_client.database_pathproject:project_id,instance:instance_id,database:database_idstatements=["ALTER DATABASE `#{database_id}` SET OPTIONS (    default_leader = '#{default_leader}'  )"]job=db_admin_client.update_database_ddldatabase:db_path,statements:statementsjob.wait_until_done!database=job.resultsputs"Updated default leader"

Reset a database leader region to the system default

Console

  1. Go to theSpanner Instances page in the Google Cloud console.

    Go to the Instances page

  2. Click the name of the instance that contains the database whose leaderregion you want to change.

  3. Click the database whose leader region you want to change.

  4. Click the pencil icon next toLeader Region.

  5. Modify the DDL statement with your selected leader region and setdefault_leader toNULL.

gcloud

To reset the leader region of an existing database to the default leaderregion, run the following command:

GoogleSQL

gcloud spanner databases ddl updateDATABASE_NAME \--instance=INSTANCE_ID \--ddl='ALTER DATABASE `DATABASE_NAME` \  SET OPTIONS ( default_leader = NULL )'

Replace the following:

  • DATABASE_NAME: the name of your database.
  • INSTANCE_ID: the identifier of your databaseinstance.

PostgreSQL

gcloud spanner databases ddl updateDATABASE_NAME \--instance=INSTANCE_ID \--ddl='ALTER DATABASEDATABASE_NAME \  RESET spanner.default_leader'

Replace the following:

  • DATABASE_NAME: the name of your database.
  • INSTANCE_ID: the identifier of your databaseinstance.

Set a leader region when creating a database

gcloud

To set the default leader region when creating a database, run the followingcommand:

gcloud spanner databases createDATABASE_NAME \--instance=INSTANCE_ID \--ddl='CREATE TABLETABLE_NAME (a INT64, b INT64) PRIMARY KEY(a); \  ALTER DATABASE `DATABASE_NAME` \  SET OPTIONS (default_leader = "REGION")'

Replace the following:

  • DATABASE_NAME: the name of your database.
  • INSTANCE_ID: the identifier of your databaseinstance.
  • TABLE_NAME: the name of your database table.
  • REGION: the region you want to set as the defaultleader.

Client libraries

C#

usingGoogle.Cloud.Spanner.Admin.Database.V1;usingGoogle.Cloud.Spanner.Common.V1;usingSystem;usingSystem.Threading.Tasks;publicclassCreateDatabaseWithDefaultLeaderAsyncSample{publicasyncTask<Database>CreateDatabaseWithDefaultLeaderAsync(stringprojectId,stringinstanceId,stringdatabaseId,stringdefaultLeader){DatabaseAdminClientdatabaseAdminClient=awaitDatabaseAdminClient.CreateAsync();// Define create table statement for table #1.varcreateSingersTable=@"CREATE TABLE Singers (                SingerId INT64 NOT NULL,                FirstName STRING(1024),                LastName STRING(1024),                ComposerInfo BYTES(MAX)            ) PRIMARY KEY (SingerId)";// Define create table statement for table #2.varcreateAlbumsTable=@"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";// Define alter database statement to set default leader.varalterDatabaseStatement=@$"ALTER DATABASE `{databaseId}` SET OPTIONS (default_leader = '{defaultLeader}')";// Create the CreateDatabase request with default leader and execute it.varrequest=newCreateDatabaseRequest{ParentAsInstanceName=InstanceName.FromProjectInstance(projectId,instanceId),CreateStatement=$"CREATE DATABASE `{databaseId}`",ExtraStatements={createSingersTable,createAlbumsTable,alterDatabaseStatement},};varoperation=awaitdatabaseAdminClient.CreateDatabaseAsync(request);// Wait until the operation has finished.Console.WriteLine("Waiting for the operation to finish.");varcompletedResponse=awaitoperation.PollUntilCompletedAsync();if(completedResponse.IsFaulted){Console.WriteLine($"Error while creating database: {completedResponse.Exception}");throwcompletedResponse.Exception;}vardatabase=completedResponse.Result;Console.WriteLine($"Created database [{databaseId}]");Console.WriteLine($"\t Default leader: {database.DefaultLeader}");returndatabase;}}

C++

voidCreateDatabaseWithDefaultLeader(google::cloud::spanner_admin::DatabaseAdminClientclient,std::stringconst&project_id,std::stringconst&instance_id,std::stringconst&database_id,std::stringconst&default_leader){google::cloud::spanner::Databasedatabase(project_id,instance_id,database_id);google::spanner::admin::database::v1::CreateDatabaseRequestrequest;request.set_parent(database.instance().FullName());request.set_create_statement("CREATE DATABASE `"+database.database_id()+"`");request.add_extra_statements("ALTER DATABASE `"+database_id+"` "+"SET OPTIONS (default_leader='"+default_leader+"')");autodb=client.CreateDatabase(request).get();if(!db)throwstd::move(db).status();std::cout <<"Database " <<db->name() <<" created.\n" <<db->DebugString();}

Go

import("context""fmt""io""regexp"database"cloud.google.com/go/spanner/admin/database/apiv1"adminpb"cloud.google.com/go/spanner/admin/database/apiv1/databasepb")// createDatabaseWithDefaultLeader creates a database with a default leaderfunccreateDatabaseWithDefaultLeader(wio.Writer,dbstring,defaultLeaderstring)error{// db = `projects/<project>/instances/<instance-id>/database/<database-id>`// defaultLeader = `my-default-leader`matches:=regexp.MustCompile("^(.*)/databases/(.*)$").FindStringSubmatch(db)ifmatches==nil||len(matches)!=3{returnfmt.Errorf("createDatabaseWithDefaultLeader: invalid database id %s",db)}ctx:=context.Background()adminClient,err:=database.NewDatabaseAdminClient(ctx)iferr!=nil{returnerr}deferadminClient.Close()alterDatabase:=fmt.Sprintf("ALTER DATABASE `%s` SET OPTIONS (default_leader = '%s')",matches[2],defaultLeader,)req:=adminpb.CreateDatabaseRequest{Parent:matches[1],CreateStatement:"CREATE DATABASE `"+matches[2]+"`",ExtraStatements:[]string{`CREATE TABLE Singers (SingerId   INT64 NOT NULL,FirstName  STRING(1024),LastName   STRING(1024),SingerInfo BYTES(MAX)) PRIMARY KEY (SingerId)`,`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`,alterDatabase,},}op,err:=adminClient.CreateDatabase(ctx,&req)iferr!=nil{returnfmt.Errorf("createDatabaseWithDefaultLeader.CreateDatabase: %w",err)}dbObj,err:=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("createDatabaseWithDefaultLeader.Wait: %w",err)}fmt.Fprintf(w,"Created database [%s] with default leader%q\n",dbObj.Name,dbObj.DefaultLeader)returnnil}

Java

importcom.google.cloud.spanner.SpannerException;importcom.google.cloud.spanner.SpannerExceptionFactory;importcom.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;importcom.google.common.collect.ImmutableList;importcom.google.spanner.admin.database.v1.CreateDatabaseRequest;importcom.google.spanner.admin.database.v1.Database;importjava.io.IOException;importjava.util.concurrent.ExecutionException;publicclassCreateDatabaseWithDefaultLeaderSample{staticvoidcreateDatabaseWithDefaultLeader()throwsIOException{// TODO(developer): Replace these variables before running the sample.finalStringinstanceName="projects/my-project/instances/my-instance-id";finalStringdatabaseId="my-database-name";finalStringdefaultLeader="my-default-leader";createDatabaseWithDefaultLeader(instanceName,databaseId,defaultLeader);}staticvoidcreateDatabaseWithDefaultLeader(StringinstanceName,StringdatabaseId,StringdefaultLeader)throwsIOException{try(DatabaseAdminClientdatabaseAdminClient=DatabaseAdminClient.create()){DatabasecreatedDatabase=databaseAdminClient.createDatabaseAsync(CreateDatabaseRequest.newBuilder().setParent(instanceName).setCreateStatement("CREATE DATABASE `"+databaseId+"`").addAllExtraStatements(ImmutableList.of("CREATE TABLE Singers ("+"  SingerId   INT64 NOT NULL,"+"  FirstName  STRING(1024),"+"  LastName   STRING(1024),"+"  SingerInfo BYTES(MAX)"+") PRIMARY KEY (SingerId)","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","ALTER DATABASE "+"`"+databaseId+"`"+" SET OPTIONS ( default_leader = '"+defaultLeader+"' )")).build()).get();System.out.println("Created database ["+createdDatabase.getName()+"]");System.out.println("\tDefault leader: "+createdDatabase.getDefaultLeader());}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throw(SpannerException)e.getCause();}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}}

Note: The old client library interface code samples for Java are archived inGitHub.

Node.js

/** * TODO(developer): Uncomment the following lines before running the sample. */// const projectId = 'my-project-id';// const instanceId = 'my-instance-id';// const databaseId = 'my-database-id';// const defaultLeader = 'my-default-leader'; example: 'asia-northeast1'// Imports the Google Cloud client libraryconst{Spanner}=require('@google-cloud/spanner');// creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner Database Admin Client objectconstdatabaseAdminClient=spanner.getDatabaseAdminClient();asyncfunctioncreateDatabaseWithDefaultLeader(){// Create a new database with an extra statement which will alter the// database after creation to set the default leader.console.log(`Creating database${databaseAdminClient.databasePath(projectId,instanceId,databaseId,)}.`,);constcreateSingersTableStatement=`    CREATE TABLE Singers (      SingerId   INT64 NOT NULL,      FirstName  STRING(1024),      LastName   STRING(1024),      SingerInfo BYTES(MAX)    ) PRIMARY KEY (SingerId)`;constcreateAlbumsStatement=`    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`;// Default leader is one of the possible values in the leaderOptions field of the// instance config of the instance where the database is created.constsetDefaultLeaderStatement=`    ALTER DATABASE \`${databaseId}\`    SET OPTIONS (default_leader = '${defaultLeader}')`;const[operation]=awaitdatabaseAdminClient.createDatabase({createStatement:'CREATE DATABASE `'+databaseId+'`',extraStatements:[createSingersTableStatement,createAlbumsStatement,setDefaultLeaderStatement,],parent:databaseAdminClient.instancePath(projectId,instanceId),});console.log(`Waiting for creation of${databaseId} to complete...`);awaitoperation.promise();console.log(`Created database${databaseId} with default leader${defaultLeader}.`,);}createDatabaseWithDefaultLeader();

Note: The old client library interface code samples for Node.js are archived inGitHub.

PHP

use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient;use Google\Cloud\Spanner\Admin\Database\V1\CreateDatabaseRequest;use Google\Cloud\Spanner\Admin\Database\V1\GetDatabaseRequest;/** * Creates a database with a default leader. * Example: * ``` * create_database_with_default_leader($projectId, $instanceId, $databaseId, $defaultLeader); * ``` * * @param string $projectId The Google Cloud project ID. * @param string $instanceId The Spanner instance ID. * @param string $databaseId The Spanner database ID. * @param string $defaultLeader The leader instance configuration used by default. */function create_database_with_default_leader(    string $projectId,    string $instanceId,    string $databaseId,    string $defaultLeader): void {    $databaseAdminClient = new DatabaseAdminClient();    $instance = $databaseAdminClient->instanceName($projectId, $instanceId);    $databaseIdFull = $databaseAdminClient->databaseName($projectId, $instanceId, $databaseId);    $operation = $databaseAdminClient->createDatabase(        new CreateDatabaseRequest([            'parent' => $instance,            'create_statement' => sprintf('CREATE DATABASE `%s`', $databaseId),            'extra_statements' => [                'CREATE TABLE Singers (' .                'SingerId     INT64 NOT NULL,' .                'FirstName    STRING(1024),' .                'LastName     STRING(1024),' .                'SingerInfo   BYTES(MAX)' .                ') PRIMARY KEY (SingerId)',                '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',                "ALTER DATABASE `$databaseId` SET OPTIONS(default_leader='$defaultLeader')"            ]        ])    );    print('Waiting for operation to complete...' . PHP_EOL);    $operation->pollUntilComplete();    $database = $databaseAdminClient->getDatabase(        new GetDatabaseRequest(['name' => $databaseIdFull])    );    printf('Created database %s on instance %s with default leader %s' . PHP_EOL,        $databaseId, $instanceId, $database->getDefaultLeader());}

Note: The old client library interface code samples for PHP are archived inGitHub.

Python

defcreate_database_with_default_leader(instance_id,database_id,default_leader):"""Creates a database with tables with a default leader."""fromgoogle.cloud.spanner_admin_database_v1.typesimportspanner_database_adminspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_apirequest=spanner_database_admin.CreateDatabaseRequest(parent=database_admin_api.instance_path(spanner_client.project,instance_id),create_statement=f"CREATE DATABASE `{database_id}`",extra_statements=["""CREATE TABLE Singers (                SingerId     INT64 NOT NULL,                FirstName    STRING(1024),                LastName     STRING(1024),                SingerInfo   BYTES(MAX)            ) PRIMARY KEY (SingerId)""","""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""","ALTER DATABASE{}"" SET OPTIONS (default_leader = '{}')".format(database_id,default_leader),],)operation=database_admin_api.create_database(request=request)print("Waiting for operation to complete...")database=operation.result(OPERATION_TIMEOUT_SECONDS)print("Database{} created with default leader{}".format(database.name,database.default_leader))

Note: The old client library interface code samples for Python are archived inGitHub.

Ruby

# project_id  = "Your Google Cloud project ID"# instance_id = "Your Spanner instance ID"# database_id = "Your Spanner database ID"# default_leader = "Spanner database default leader"require"google/cloud/spanner"require"google/cloud/spanner/admin/database"db_admin_client=Google::Cloud::Spanner::Admin::Database.database_adminproject_id:project_idinstance_path=\db_admin_client.instance_pathproject:project_id,instance:instance_idstatements=["CREATE TABLE Singers (    SingerId     INT64 NOT NULL,    FirstName    STRING(1024),    LastName     STRING(1024),    SingerInfo   BYTES(MAX)  ) PRIMARY KEY (SingerId)","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","ALTER DATABASE `#{database_id}` SET OPTIONS (    default_leader = '#{default_leader}'  )"]job=db_admin_client.create_database\parent:instance_path,create_statement:"CREATE DATABASE `#{database_id}`",extra_statements:statementsjob.wait_until_done!database=job.resultsputs"Created database [#{database.name}] with default leader:#{database.default_leader}"

View the leader region

View the leader region of a database with the Google Cloud console and gcloud

Console

  1. Go to theSpanner Instances page in the Google Cloud console.

    Go to the Instances page

  2. The leader region of your database is listed underLeader region.

gcloud

To view the leader region of an existing database, run the followingcommand:

gcloud spanner databases describeDATABASE_NAME \--instance=INSTANCE_ID

Replace the following:

  • DATABASE_NAME: the name of your database.
  • INSTANCE_ID: the identifier of your databaseinstance.

If a default leader region has been set, it is listed underdefaultLeader.

If a default leader has not been set,defaultLeader is not listed. In thiscase Spanner uses the Google-defined, default leader region for yourdual-regionormulti-regionconfiguration as shown in respective available configurations.

View the leader region in the DDL

gcloud

To view the leader region of an a database in the DDL, run the followingcommand:

gcloud spanner databases ddl describeDATABASE_NAME \--instance=INSTANCE_NAME

Replace the following:

  • DATABASE_NAME: the name of your database database.
  • INSTANCE_ID: the identifier of your databaseinstance.

Client libraries

C#

usingGoogle.Cloud.Spanner.Admin.Database.V1;usingGoogle.Cloud.Spanner.Common.V1;usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;publicclassGetDatabaseDdlAsyncSample{publicasyncTask<GetDatabaseDdlResponse>GetDatabaseDdlAsync(stringprojectId,stringinstanceId,stringdatabaseId){DatabaseAdminClientdatabaseAdminClient=awaitDatabaseAdminClient.CreateAsync();DatabaseNamedatabaseName=DatabaseName.FromProjectInstanceDatabase(projectId,instanceId,databaseId);GetDatabaseDdlResponsedatabaseDdl=awaitdatabaseAdminClient.GetDatabaseDdlAsync(databaseName);Console.WriteLine($"DDL statements for database {databaseId}:");foreach(varstatementindatabaseDdl.Statements){Console.WriteLine(statement);}returndatabaseDdl;}}

C++

voidGetDatabaseDdl(google::cloud::spanner_admin::DatabaseAdminClientclient,std::stringconst&project_id,std::stringconst&instance_id,std::stringconst&database_id){namespacespanner=::google::cloud::spanner;autodatabase=client.GetDatabaseDdl(spanner::Database(project_id,instance_id,database_id).FullName());if(!database)throwstd::move(database).status();std::cout <<"Database metadata is:\n" <<database->DebugString();}

Go

import("context""fmt""io""regexp"database"cloud.google.com/go/spanner/admin/database/apiv1"adminpb"cloud.google.com/go/spanner/admin/database/apiv1/databasepb")// getDatabaseDdl gets the DDL for the databasefuncgetDatabaseDdl(wio.Writer,dbstring)error{// db = `projects/<project>/instances/<instance-id>/database/<database-id>`matches:=regexp.MustCompile("^(.*)/databases/(.*)$").FindStringSubmatch(db)ifmatches==nil||len(matches)!=3{returnfmt.Errorf("getDatabaseDdl: invalid database id %s",db)}ctx:=context.Background()adminClient,err:=database.NewDatabaseAdminClient(ctx)iferr!=nil{returnerr}deferadminClient.Close()op,err:=adminClient.GetDatabaseDdl(ctx,&adminpb.GetDatabaseDdlRequest{Database:db,})iferr!=nil{returnerr}fmt.Fprintf(w,"Database DDL is as follows: \n [%v]",op.GetStatements())returnnil}

Java

importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;importcom.google.spanner.admin.database.v1.DatabaseName;importcom.google.spanner.admin.database.v1.GetDatabaseDdlResponse;publicclassGetDatabaseDdlSample{staticvoidgetDatabaseDdl(){// TODO(developer): Replace these variables before running the sample.finalStringprojectId="my-project";finalStringinstanceId="my-instance";finalStringdatabaseId="my-database";getDatabaseDdl(projectId,instanceId,databaseId);}staticvoidgetDatabaseDdl(StringprojectId,StringinstanceId,StringdatabaseId){try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();DatabaseAdminClientdatabaseAdminClient=spanner.createDatabaseAdminClient()){finalGetDatabaseDdlResponseresponse=databaseAdminClient.getDatabaseDdl(DatabaseName.of(projectId,instanceId,databaseId));System.out.println("Retrieved database DDL for "+databaseId);for(Stringddl:response.getStatementsList()){System.out.println(ddl);}}}}

Note: The old client library interface code samples for Java are archived inGitHub.

Node.js

/** * TODO(developer): Uncomment the following lines before running the sample. */// const projectId = 'my-project-id';// const instanceId = 'my-instance-id';// const databaseId = 'my-database-id';// Imports the Google Cloud client libraryconst{Spanner}=require('@google-cloud/spanner');// creates a clientconstspanner=newSpanner({projectId:projectId,});constdatabaseAdminClient=spanner.getDatabaseAdminClient();asyncfunctiongetDatabaseDdl(){// Get the schema definition of the database.const[ddlStatements]=awaitdatabaseAdminClient.getDatabaseDdl({database:databaseAdminClient.databasePath(projectId,instanceId,databaseId,),});console.log(`Retrieved database DDL for${databaseAdminClient.databasePath(projectId,instanceId,databaseId,)}:`,);ddlStatements.statements.forEach(element=>{console.log(element);});}getDatabaseDdl();

Note: The old client library interface code samples for Node.js are archived inGitHub.

PHP

use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient;use Google\Cloud\Spanner\Admin\Database\V1\GetDatabaseDdlRequest;/** * Gets the database DDL statements. * Example: * ``` * get_database_ddl($projectId, $instanceId, $databaseId); * ``` * * @param string $projectId The Google Cloud project ID. * @param string $instanceId The Spanner instance ID. * @param string $databaseId The Spanner database ID. */function get_database_ddl(string $projectId, string $instanceId, string $databaseId): void{    $databaseAdminClient = new DatabaseAdminClient();    $databaseName = DatabaseAdminClient::databaseName($projectId, $instanceId, $databaseId);    $request = new GetDatabaseDdlRequest(['database' => $databaseName]);    $statements = $databaseAdminClient->getDatabaseDdl($request)->getStatements();    printf("Retrieved database DDL for $databaseId" . PHP_EOL);    foreach ($statements as $statement) {        printf($statement . PHP_EOL);    }}

Note: The old client library interface code samples for PHP are archived inGitHub.

Python

defget_database_ddl(instance_id,database_id):"""Gets the database DDL statements."""spanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_apiddl=database_admin_api.get_database_ddl(database=database_admin_api.database_path(spanner_client.project,instance_id,database_id))print("Retrieved database DDL for{}".format(database_id))forstatementinddl.statements:print(statement)

Note: The old client library interface code samples for Python are archived inGitHub.

Ruby

# project_id  = "Your Google Cloud project ID"# instance_id = "Your Spanner instance ID"# database_id = "Your Spanner database ID"require"google/cloud/spanner"require"google/cloud/spanner/admin/database"db_admin_client=Google::Cloud::Spanner::Admin::Database.database_adminproject_id:project_iddb_path=db_admin_client.database_pathproject:project_id,instance:instance_id,database:database_idddl=db_admin_client.get_database_ddldatabase:db_pathputsddl.statements

View the leader region in the information schema

gcloud

To view the leader region of an existing database, run the followingcommand:

gcloud spanner databases execute-sqlDATABASE_NAME \--instance=INSTANCE_ID \--sql="SELECT s.OPTION_NAME, s.OPTION_VALUE \  FROM INFORMATION_SCHEMA.DATABASE_OPTIONS s \  WHERE s.OPTION_NAME = 'default_leader'"

Replace the following:

  • DATABASE_NAME: the name of your database.
  • INSTANCE_ID: the identifier of your databaseinstance.

Client libraries

C#

usingGoogle.Cloud.Spanner.Data;usingSystem;usingSystem.Threading.Tasks;publicclassGetDatabaseDefaultLeaderFromInformationSchemaAsyncSample{publicasyncTask<string>GetDatabaseDefaultLeaderFromInformationSchemaAsync(stringprojectId,stringinstanceId,stringdatabaseId){stringconnectionString=$"Data Source=projects/{projectId}/instances/{instanceId}/databases/{databaseId}";usingvarconnection=newSpannerConnection(connectionString);varcmd=connection.CreateSelectCommand(@"SELECT                s.OPTION_NAME,                s.OPTION_VALUE            FROM                INFORMATION_SCHEMA.DATABASE_OPTIONS s            WHERE                s.OPTION_NAME = 'default_leader'");vardefaultLeader=string.Empty;Console.WriteLine($"Default leader for {databaseId}:");usingvarreader=awaitcmd.ExecuteReaderAsync();while(awaitreader.ReadAsync()){defaultLeader=reader.GetFieldValue<string>("OPTION_VALUE");Console.WriteLine(defaultLeader);}returndefaultLeader;}}

C++

voidQueryInformationSchemaDatabaseOptions(google::cloud::spanner::Clientclient){namespacespanner=::google::cloud::spanner;// clang-format misinterprets the namespace alias followed by a block as// introducing a sub-namespace and so adds a misleading namespace-closing// comment at the end. This separating comment defeats that.{autorows=client.ExecuteQuery(spanner::SqlStatement(R"""(        SELECT s.OPTION_NAME, s.OPTION_VALUE        FROM INFORMATION_SCHEMA.DATABASE_OPTIONS s        WHERE s.OPTION_NAME = 'default_leader')"""));usingRowType=std::tuple<std::string,std::string>;for(auto&row:spanner::StreamOf<RowType>(rows)){if(!row)throwstd::move(row).status();std::cout <<std::get<0>(*row) <<"=" <<std::get<1>(*row) <<"\n";}}{autorows=client.ExecuteQuery(spanner::SqlStatement(R"""(        SELECT s.OPTION_NAME, s.OPTION_VALUE        FROM INFORMATION_SCHEMA.DATABASE_OPTIONS s        WHERE s.OPTION_NAME = 'version_retention_period')"""));usingRowType=std::tuple<std::string,std::string>;for(auto&row:spanner::StreamOf<RowType>(rows)){if(!row)throwstd::move(row).status();std::cout <<std::get<0>(*row) <<"=" <<std::get<1>(*row) <<"\n";}}}

Go

import("context""fmt""io""regexp""cloud.google.com/go/spanner""google.golang.org/api/iterator")// queryInformationSchemaDatabaseOptions queries the database options from the// information schema table.funcqueryInformationSchemaDatabaseOptions(wio.Writer,dbstring)error{// db = `projects/<project>/instances/<instance-id>/database/<database-id>`matches:=regexp.MustCompile("^(.+)/databases/(.+)$").FindStringSubmatch(db)ifmatches==nil||len(matches)!=3{returnfmt.Errorf("queryInformationSchemaDatabaseOptions: invalid database id %q",db)}databaseID:=matches[2]ctx:=context.Background()client,err:=spanner.NewClient(ctx,db)iferr!=nil{returnerr}deferclient.Close()stmt:=spanner.Statement{SQL:`SELECT OPTION_NAME, OPTION_VALUE                                FROM INFORMATION_SCHEMA.DATABASE_OPTIONS                                    WHERE OPTION_NAME = 'default_leader'`}iter:=client.Single().Query(ctx,stmt)deferiter.Stop()for{row,err:=iter.Next()iferr==iterator.Done{returnnil}iferr!=nil{returnerr}varoption_name,option_valuestringiferr:=row.Columns(&option_name,&option_value);err!=nil{returnerr}fmt.Fprintf(w,"The result of the query to get %s for %s is %s",option_name,databaseID,option_value)}}

Java

importcom.google.cloud.spanner.DatabaseClient;importcom.google.cloud.spanner.DatabaseId;importcom.google.cloud.spanner.ResultSet;importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.Statement;publicclassQueryInformationSchemaDatabaseOptionsSample{staticvoidqueryInformationSchemaDatabaseOptions(){// TODO(developer): Replace these variables before running the sample.finalStringprojectId="my-project";finalStringinstanceId="my-instance";finalStringdatabaseId="my-database";queryInformationSchemaDatabaseOptions(projectId,instanceId,databaseId);}staticvoidqueryInformationSchemaDatabaseOptions(StringprojectId,StringinstanceId,StringdatabaseId){try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService()){finalDatabaseIdid=DatabaseId.of(projectId,instanceId,databaseId);finalDatabaseClientdatabaseClient=spanner.getDatabaseClient(id);try(ResultSetresultSet=databaseClient.singleUse().executeQuery(Statement.of("SELECT OPTION_NAME, OPTION_VALUE"+" FROM INFORMATION_SCHEMA.DATABASE_OPTIONS"+" WHERE OPTION_NAME = 'default_leader'"))){if(resultSet.next()){finalStringoptionName=resultSet.getString("OPTION_NAME");finalStringoptionValue=resultSet.getString("OPTION_VALUE");System.out.println("The "+optionName+" for "+id+" is "+optionValue);}else{System.out.println("Database "+id+" does not have a value for option 'default_leader'");}}}}}

Note: The old client library interface code samples for Java are archived inGitHub.

Node.js

/** * TODO(developer): Uncomment the following lines before running the sample. */// const projectId = 'my-project-id';// const instanceId = 'my-instance-id';// const databaseId = 'my-database-id';// Imports the Google Cloud client libraryconst{Spanner}=require('@google-cloud/spanner');// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and a database.constinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);asyncfunctiongetDatabaseDdl(){// Get the default leader option for the database.const[rows]=awaitdatabase.run({sql:`      SELECT s.OPTION_NAME, s.OPTION_VALUE      FROM INFORMATION_SCHEMA.DATABASE_OPTIONS s      WHERE s.OPTION_NAME = 'default_leader'`,json:true,});if(rows.length >0){constoption=rows[0];console.log(`The${option.OPTION_NAME} for${databaseId} is${option.OPTION_VALUE}`,);}else{console.log(`Database${databaseId} does not have a value for option 'default_leader'`,);}}getDatabaseDdl();

Note: The old client library interface code samples for Node.js are archived inGitHub.

PHP

use Google\Cloud\Spanner\SpannerClient;/** * Queries the default leader of a database. * Example: * ``` * query_information_schema_database_options($instanceId, $databaseId); * ``` * * @param string $instanceId The Spanner instance ID. * @param string $databaseId The Spanner database ID. */function query_information_schema_database_options(string $instanceId, string $databaseId): void{    $spanner = new SpannerClient();    $instance = $spanner->instance($instanceId);    $database = $instance->database($databaseId);    $results = $database->execute(        "SELECT s.OPTION_NAME, s.OPTION_VALUE        FROM INFORMATION_SCHEMA.DATABASE_OPTIONS s        WHERE s.OPTION_NAME = 'default_leader'"    );    foreach ($results as $row) {        $optionName = $row['OPTION_NAME'];        $optionValue = $row['OPTION_VALUE'];        printf("The $optionName for $databaseId is $optionValue" . PHP_EOL);    }    if (!$results->stats()['rowCountExact']) {        printf("Database $databaseId does not have a value for option 'default_leader'");    }}

Note: The old client library interface code samples for PHP are archived inGitHub.

Python

defquery_information_schema_database_options(instance_id,database_id):"""Queries the default leader of a database."""spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.snapshot()assnapshot:results=snapshot.execute_sql("SELECT OPTION_VALUE AS default_leader ""FROM INFORMATION_SCHEMA.DATABASE_OPTIONS ""WHERE SCHEMA_NAME = '' AND OPTION_NAME = 'default_leader'")forresultinresults:print("Database{} has default leader{}".format(database_id,result[0]))

Note: The old client library interface code samples for Python are archived inGitHub.

Ruby

# project_id  = "Your Google Cloud project ID"# instance_id = "Your Spanner instance ID"# database_id = "Your Spanner database IDrequire"google/cloud/spanner"spanner=Google::Cloud::Spanner.newproject:project_idclient=spanner.clientinstance_id,database_idclient.execute("SELECT s.OPTION_NAME, s.OPTION_VALUE "\"FROM INFORMATION_SCHEMA.DATABASE_OPTIONS s "\"WHERE s.OPTION_NAME = 'default_leader'").rows.eachdo|row|putsrowend

View the leader regions for multiple databases

Client libraries

C#

usingGoogle.Cloud.Spanner.Admin.Database.V1;usingGoogle.Cloud.Spanner.Common.V1;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;publicclassListDatabasesSample{publicIEnumerable<Database>ListDatabases(stringprojectId,stringinstanceId){vardatabaseAdminClient=DatabaseAdminClient.Create();varinstanceName=InstanceName.FromProjectInstance(projectId,instanceId);vardatabases=databaseAdminClient.ListDatabases(instanceName);// We print the first 5 elements for demonstration purposes.// You can print all databases in the sequence by removing the call to Take(5).// The sequence will lazily fetch elements in pages as needed.foreach(vardatabaseindatabases.Take(5)){Console.WriteLine($"Default leader for database {database.DatabaseName.DatabaseId}: {database.DefaultLeader}");}returndatabases;}}

C++

voidListDatabases(google::cloud::spanner_admin::DatabaseAdminClientclient,std::stringconst&project_id,std::stringconst&instance_id){google::cloud::spanner::Instancein(project_id,instance_id);intcount=0;for(auto&database:client.ListDatabases(in.FullName())){if(!database)throwstd::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";}}

Go

import("context""fmt""io"database"cloud.google.com/go/spanner/admin/database/apiv1"adminpb"cloud.google.com/go/spanner/admin/database/apiv1/databasepb""google.golang.org/api/iterator")// listDatabases gets list of all databases for an instancefunclistDatabases(wio.Writer,instanceIdstring)error{// instanceId = `projects/<project>/instances/<instance-id>ctx:=context.Background()adminClient,err:=database.NewDatabaseAdminClient(ctx)iferr!=nil{returnerr}deferadminClient.Close()iter:=adminClient.ListDatabases(ctx,&adminpb.ListDatabasesRequest{Parent:instanceId,})fmt.Fprintf(w,"Databases for instance/[%s]",instanceId)for{resp,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Fprintf(w,"%s\n",resp.Name)}returnnil}

Java

importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;importcom.google.cloud.spanner.admin.database.v1.DatabaseAdminClient.ListDatabasesPage;importcom.google.cloud.spanner.admin.database.v1.DatabaseAdminClient.ListDatabasesPagedResponse;importcom.google.spanner.admin.database.v1.Database;importcom.google.spanner.admin.database.v1.InstanceName;publicclassListDatabasesSample{staticvoidlistDatabases(){// TODO(developer): Replace these variables before running the sample.finalStringprojectId="my-project";finalStringinstanceId="my-instance";listDatabases(projectId,instanceId);}staticvoidlistDatabases(StringprojectId,StringinstanceId){try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();DatabaseAdminClientdatabaseAdminClient=spanner.createDatabaseAdminClient()){ListDatabasesPagedResponseresponse=databaseAdminClient.listDatabases(InstanceName.of(projectId,instanceId));System.out.println("Databases for projects/"+projectId+"/instances/"+instanceId);for(ListDatabasesPagepage:response.iteratePages()){for(Databasedatabase:page.iterateAll()){finalStringdefaultLeader=database.getDefaultLeader().equals("")?"":"(default leader = "+database.getDefaultLeader()+")";System.out.println("\t"+database.getName()+" "+defaultLeader);}}}}}

Note: The old client library interface code samples for Java are archived inGitHub.

Node.js

/** * TODO(developer): Uncomment the following lines before running the sample. */// const projectId = 'my-project-id';// const instanceId = 'my-instance-id';// Imports the Google Cloud client libraryconst{Spanner}=require('@google-cloud/spanner');// creates a clientconstspanner=newSpanner({projectId:projectId,});constdatabaseAdminClient=spanner.getDatabaseAdminClient();asyncfunctionlistDatabases(){// Lists all databases on the instance.const[databases]=awaitdatabaseAdminClient.listDatabases({parent:databaseAdminClient.instancePath(projectId,instanceId),});console.log(`Databases for projects/${projectId}/instances/${instanceId}:`);databases.forEach(database=>{constdefaultLeader=database.defaultLeader?`(default leader =${database.defaultLeader})`:'';console.log(`\t${database.name}${defaultLeader}`);});}listDatabases();

Note: The old client library interface code samples for Node.js are archived inGitHub.

PHP

use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient;use Google\Cloud\Spanner\Admin\Database\V1\ListDatabasesRequest;/** * Lists the databases and their leader options. * Example: * ``` * list_databases($projectId, $instanceId); * ``` * * @param string $projectId The Google Cloud project ID. * @param string $instanceId The Spanner instance ID. */function list_databases(string $projectId, string $instanceId): void{    $databaseAdminClient = new DatabaseAdminClient();    $instanceName = DatabaseAdminClient::instanceName($projectId, $instanceId);    $request = new ListDatabasesRequest(['parent' => $instanceName]);    $resp = $databaseAdminClient->listDatabases($request);    $databases = $resp->iterateAllElements();    printf('Databases for %s' . PHP_EOL, $instanceName);    foreach ($databases as $database) {        printf("\t%s (default leader = %s)" . PHP_EOL, $database->getName(), $database->getDefaultLeader());    }}

Note: The old client library interface code samples for PHP are archived inGitHub.

Python

deflist_databases(instance_id):"""Lists databases and their leader options."""fromgoogle.cloud.spanner_admin_database_v1.typesimportspanner_database_adminspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_apirequest=spanner_database_admin.ListDatabasesRequest(parent=database_admin_api.instance_path(spanner_client.project,instance_id))fordatabaseindatabase_admin_api.list_databases(request=request):print("Database{} has default leader{}".format(database.name,database.default_leader))

Note: The old client library interface code samples for Python are archived inGitHub.

Ruby

# project_id  = "Your Google Cloud project ID"# instance_id = "Your Spanner instance ID"require"google/cloud/spanner"require"google/cloud/spanner/admin/database"db_admin_client=Google::Cloud::Spanner::Admin::Database.database_adminproject_id:project_idinstance_path=db_admin_client.instance_pathproject:project_id,instance:instance_iddatabases=db_admin_client.list_databasesparent:instance_pathdatabases.eachdo|db|puts"#{db.name} : default leader#{db.default_leader}"end

View available leader options

View available leader options for an instance configuration

gcloud

To view the regions which you can set to be the default leader region, usethe following command:

gcloud spanner instance-configs describeINSTANCE_CONFIG

Replace the following:

  • INSTANCE_CONFIG: a permanent identifier of yourinstance configuration, which defines the geographic location of theinstance and affects how data is replicated. For custom instanceconfigurations, it starts withcustom-. For more information, seeinstance configurations.

The regions that you can choose are listed underleaderOptions.

Client libraries

C#

usingGoogle.Cloud.Spanner.Admin.Instance.V1;usingSystem;usingSystem.Threading.Tasks;publicclassGetInstanceConfigAsyncSample{publicasyncTask<InstanceConfig>GetInstanceConfigAsync(stringprojectId,stringinstanceConfigId){varinstanceAdminClient=awaitInstanceAdminClient.CreateAsync();varinstanceConfigName=InstanceConfigName.FromProjectInstanceConfig(projectId,instanceConfigId);varinstanceConfig=awaitinstanceAdminClient.GetInstanceConfigAsync(instanceConfigName);Console.WriteLine($"Available leader options for instance config {instanceConfigName.InstanceConfigId}:");foreach(varleaderininstanceConfig.LeaderOptions){Console.WriteLine(leader);}returninstanceConfig;}}

C++

voidGetInstanceConfig(google::cloud::spanner_admin::InstanceAdminClientclient,std::stringconst&project_id,std::stringconst&config_id){autoproject=google::cloud::Project(project_id);autoconfig=client.GetInstanceConfig(project.FullName()+"/instanceConfigs/"+config_id);if(!config)throwstd::move(config).status();std::cout <<"The instanceConfig " <<config->name()            <<" exists and its metadata is:\n"            <<config->DebugString();}

Go

import("context""fmt""io"instance"cloud.google.com/go/spanner/admin/instance/apiv1""cloud.google.com/go/spanner/admin/instance/apiv1/instancepb")// getInstanceConfig gets available leader optionsfuncgetInstanceConfig(wio.Writer,instanceConfigNamestring)error{// defaultLeader = `nam3`ctx:=context.Background()instanceAdmin,err:=instance.NewInstanceAdminClient(ctx)iferr!=nil{returnerr}deferinstanceAdmin.Close()ic,err:=instanceAdmin.GetInstanceConfig(ctx,&instancepb.GetInstanceConfigRequest{Name:instanceConfigName,})iferr!=nil{returnfmt.Errorf("could not get instance config %s: %w",instanceConfigName,err)}fmt.Fprintf(w,"Available leader options for instance config %s: %v",instanceConfigName,ic.LeaderOptions)returnnil}

Java

importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;importcom.google.spanner.admin.instance.v1.InstanceConfig;importcom.google.spanner.admin.instance.v1.InstanceConfigName;publicclassGetInstanceConfigSample{staticvoidgetInstanceConfig(){// TODO(developer): Replace these variables before running the sample.finalStringprojectId="my-project";finalStringinstanceConfigId="nam6";getInstanceConfig(projectId,instanceConfigId);}staticvoidgetInstanceConfig(StringprojectId,StringinstanceConfigId){try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();InstanceAdminClientinstanceAdminClient=spanner.createInstanceAdminClient()){finalInstanceConfigNameinstanceConfigName=InstanceConfigName.of(projectId,instanceConfigId);finalInstanceConfiginstanceConfig=instanceAdminClient.getInstanceConfig(instanceConfigName.toString());System.out.printf("Available leader options for instance config %s: %s%n",instanceConfig.getName(),instanceConfig.getLeaderOptionsList());}}}

Note: The old client library interface code samples for Java are archived inGitHub.

Node.js

/** * TODO(developer): Uncomment the following line before running the sample. */// const projectId = 'my-project-id';// Imports the Google Cloud client libraryconst{Spanner}=require('@google-cloud/spanner');// Creates a clientconstspanner=newSpanner({projectId:projectId,});constinstanceAdminClient=spanner.getInstanceAdminClient();asyncfunctiongetInstanceConfig(){// Get the instance config for the multi-region North America 6 (NAM6).// See https://cloud.google.com/spanner/docs/instance-configurations#configuration for a list of all available// configurations.const[instanceConfig]=awaitinstanceAdminClient.getInstanceConfig({name:instanceAdminClient.instanceConfigPath(projectId,'nam6'),});console.log(`Available leader options for instance config${instanceConfig.name} ('${instanceConfig.displayName}'):${instanceConfig.leaderOptions.join()}`,);}getInstanceConfig();

Note: The old client library interface code samples for Node.js are archived inGitHub.

PHP

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;use Google\Cloud\Spanner\Admin\Instance\V1\GetInstanceConfigRequest;/** * Gets the leader options for the instance configuration. * * @param string $projectId The Google Cloud Project ID. * @param string $instanceConfig The name of the instance configuration. */function get_instance_config(string $projectId, string $instanceConfig): void{    $instanceAdminClient = new InstanceAdminClient();    $instanceConfigName = InstanceAdminClient::instanceConfigName($projectId, $instanceConfig);    $request = (new GetInstanceConfigRequest())        ->setName($instanceConfigName);    $configInfo = $instanceAdminClient->getInstanceConfig($request);    printf('Available leader options for instance config %s: %s' . PHP_EOL,        $instanceConfig,        implode(',', array_keys(iterator_to_array($configInfo->getLeaderOptions())))    );}

Note: The old client library interface code samples for PHP are archived inGitHub.

Python

defget_instance_config(instance_config):"""Gets the leader options for the instance configuration."""spanner_client=spanner.Client()config_name="{}/instanceConfigs/{}".format(spanner_client.project_name,instance_config)config=spanner_client.instance_admin_api.get_instance_config(name=config_name)print("Available leader options for instance config{}:{}".format(instance_config,config.leader_options))

Note: The old client library interface code samples for Python are archived inGitHub.

Ruby

# project_id  = "Your Google Cloud project ID"# instance_config_id = "Spanner instance config ID"require"google/cloud/spanner"require"google/cloud/spanner/admin/instance"instance_admin_client=Google::Cloud::Spanner::Admin::Instance.instance_admininstance_config_path=instance_admin_client.instance_config_path\project:project_id,instance_config:instance_config_idconfig=instance_admin_client.get_instance_configname:instance_config_pathputs"Available leader options for instance config#{config.name} :#{config.leader_options}"

View available leader options for all instance configurations

gcloud

To view the regions which you can set to be the default leader region for allof the instance configs, run the following command:

gcloud spanner instance-configs list

Client libraries

C#

usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Spanner.Admin.Instance.V1;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;publicclassListInstanceConfigsSample{publicIEnumerable<InstanceConfig>ListInstanceConfigs(stringprojectId){varinstanceAdminClient=InstanceAdminClient.Create();varprojectName=ProjectName.FromProject(projectId);varinstanceConfigs=instanceAdminClient.ListInstanceConfigs(projectName);// We print the first 5 elements for demonstration purposes.// You can print all configs in the sequence by removing the call to Take(5).// The sequence will lazily fetch elements in pages as needed.foreach(varinstanceConfigininstanceConfigs.Take(5)){Console.WriteLine($"Available leader options for instance config {instanceConfig.InstanceConfigName.InstanceConfigId}:");foreach(varleaderininstanceConfig.LeaderOptions){Console.WriteLine(leader);}Console.WriteLine($"Available optional replica for instance config {instanceConfig.InstanceConfigName.InstanceConfigId}:");foreach(varoptionalReplicaininstanceConfig.OptionalReplicas){Console.WriteLine($"Replica type - {optionalReplica.Type}, default leader location - {optionalReplica.DefaultLeaderLocation}, location - {optionalReplica.Location}");}}returninstanceConfigs;}}

C++

voidListInstanceConfigs(google::cloud::spanner_admin::InstanceAdminClientclient,std::stringconst&project_id){intcount=0;autoproject=google::cloud::Project(project_id);for(auto&config:client.ListInstanceConfigs(project.FullName())){if(!config)throwstd::move(config).status();++count;std::cout <<"Instance config [" <<count <<"]:\n"              <<config->DebugString();}if(count==0){std::cout <<"No instance configs found in project " <<project_id <<"\n";}}

Go

import("context""fmt""io"instance"cloud.google.com/go/spanner/admin/instance/apiv1""cloud.google.com/go/spanner/admin/instance/apiv1/instancepb""google.golang.org/api/iterator")// istInstanceConfigs gets available leader options for all instancesfunclistInstanceConfigs(wio.Writer,projectNamestring)error{// projectName = `projects/<project>ctx:=context.Background()instanceAdmin,err:=instance.NewInstanceAdminClient(ctx)iferr!=nil{returnerr}deferinstanceAdmin.Close()request:=&instancepb.ListInstanceConfigsRequest{Parent:projectName,}for{iter:=instanceAdmin.ListInstanceConfigs(ctx,request)for{ic,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Fprintf(w,"Available leader options for instance config %s: %v\n",ic.Name,ic.LeaderOptions)}pageToken:=iter.PageInfo().TokenifpageToken==""{break}else{request.PageToken=pageToken}}returnnil}

Java

importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;importcom.google.spanner.admin.instance.v1.InstanceConfig;importcom.google.spanner.admin.instance.v1.ProjectName;publicclassListInstanceConfigsSample{staticvoidlistInstanceConfigs(){// TODO(developer): Replace these variables before running the sample.StringprojectId="my-project";listInstanceConfigs(projectId);}staticvoidlistInstanceConfigs(StringprojectId){try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();InstanceAdminClientinstanceAdminClient=spanner.createInstanceAdminClient()){finalProjectNameprojectName=ProjectName.of(projectId);for(InstanceConfiginstanceConfig:instanceAdminClient.listInstanceConfigs(projectName).iterateAll()){System.out.printf("Available leader options for instance config %s: %s%n",instanceConfig.getName(),instanceConfig.getLeaderOptionsList());}}}}

Note: The old client library interface code samples for Java are archived inGitHub.

Node.js

/** * TODO(developer): Uncomment the following line before running the sample. */// const projectId = 'my-project-id';// Imports the Google Cloud client libraryconst{Spanner}=require('@google-cloud/spanner');// Creates a clientconstspanner=newSpanner({projectId:projectId,});constinstanceAdminClient=spanner.getInstanceAdminClient();asyncfunctionlistInstanceConfigs(){// Lists all available instance configurations in the project.// See https://cloud.google.com/spanner/docs/instance-configurations#configuration for a list of all available// configurations.const[instanceConfigs]=awaitinstanceAdminClient.listInstanceConfigs({parent:instanceAdminClient.projectPath(projectId),});console.log(`Available instance configs for project${projectId}:`);instanceConfigs.forEach(instanceConfig=>{console.log(`Available leader options for instance config${instanceConfig.name} ('${instanceConfig.displayName}'):${instanceConfig.leaderOptions.join()}`,);});}listInstanceConfigs();

Note: The old client library interface code samples for Node.js are archived inGitHub.

PHP

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;use Google\Cloud\Spanner\Admin\Instance\V1\ListInstanceConfigsRequest;/** * Lists the available instance configurations. * Example: * ``` * list_instance_configs(); * ``` * * @param string $projectId The Google Cloud project ID. */function list_instance_configs(string $projectId): void{    $instanceAdminClient = new InstanceAdminClient();    $projectName = InstanceAdminClient::projectName($projectId);    $request = new ListInstanceConfigsRequest();    $request->setParent($projectName);    $resp = $instanceAdminClient->listInstanceConfigs($request);    foreach ($resp as $element) {        printf(            'Available leader options for instance config %s: %s' . PHP_EOL,            $element->getDisplayName(),            implode(',', iterator_to_array($element->getLeaderOptions()))        );    }}

Note: The old client library interface code samples for PHP are archived inGitHub.

Python

deflist_instance_config():"""Lists the available instance configurations."""fromgoogle.cloud.spanner_admin_instance_v1.typesimportspanner_instance_adminspanner_client=spanner.Client()request=spanner_instance_admin.ListInstanceConfigsRequest(parent=spanner_client.project_name)forconfiginspanner_client.instance_admin_api.list_instance_configs(request=request):print("Available leader options for instance config{}:{}".format(config.name,config.leader_options))

Note: The old client library interface code samples for Python are archived inGitHub.

Ruby

# project_id  = "Your Google Cloud project ID"require"google/cloud/spanner"require"google/cloud/spanner/admin/instance"instance_admin_client=Google::Cloud::Spanner::Admin::Instance.instance_adminproject_path=instance_admin_client.project_pathproject:project_idconfigs=instance_admin_client.list_instance_configsparent:project_pathconfigs.eachdo|c|puts"Available leader options for instance config#{c.name} :#{c.leader_options}"end

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-17 UTC.