Class Database (7.5.0)

Create a Database object to interact with a Cloud Spanner database.

Inheritance

common_2.GrpcServiceObject >Database

Package

@google-cloud/spanner

Example

const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');

Constructors

(constructor)(instance, name, poolOptions, queryOptions)

constructor(instance:Instance,name:string,poolOptions?:SessionPoolConstructor|SessionPoolOptions,queryOptions?:spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions);

Constructs a new instance of theDatabase class

Parameters
NameDescription
instanceInstance
namestring
poolOptionsSessionPoolConstructor |SessionPoolOptions
queryOptionsIQueryOptions

Properties

databaseRole

databaseRole?:string|null;

formattedName_

formattedName_:string;

pool_

pool_:SessionPoolInterface;

queryOptions_

queryOptions_?:spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions;

request

request:DatabaseRequest;

resourceHeader_

resourceHeader_:{[k:string]:string;};

Methods

_runPartitionedUpdate(session, query, callback)

_runPartitionedUpdate(session:Session,query:string|ExecuteSqlRequest,callback?:RunUpdateCallback):void|Promise<number>;
Parameters
NameDescription
sessionSession
querystring |ExecuteSqlRequest
callbackRunUpdateCallback
Returns
TypeDescription
void |Promise<number>

batchCreateSessions(options)

batchCreateSessions(options:number|BatchCreateSessionsOptions):Promise<BatchCreateSessionsResponse>;

Create a batch of sessions, which can be used to perform transactions that read and/or modify data.

**It is unlikely you will need to interact with sessions directly. By default, sessions are created and utilized for maximum performance automatically.**

Wrapper around .

Parameter
NameDescription
optionsnumber |BatchCreateSessionsOptions

Desired session count or a configuration object.

Returns
TypeDescription
Promise<BatchCreateSessionsResponse>

{Promise

Examples
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');constcount=5;database.batchCreateSession(count,(err,sessions,response)=>{if(err){// Error handling omitted.}// `sessions` is an array of Session objects.});

If the callback is omitted, we'll return a Promise.

const[sessions,response]=awaitdatabase.batchCreateSessions(count);

batchCreateSessions(options, callback)

batchCreateSessions(options:number|BatchCreateSessionsOptions,callback:BatchCreateSessionsCallback):void;
Parameters
NameDescription
optionsnumber |BatchCreateSessionsOptions
callbackBatchCreateSessionsCallback
Returns
TypeDescription
void

batchTransaction(identifier, options)

batchTransaction(identifier:TransactionIdentifier,options?:TimestampBounds):BatchTransaction;

Get a reference to a object.

Parameters
NameDescription
identifierTransactionIdentifier

The transaction identifier.

optionsTimestampBounds

[Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds).

Returns
TypeDescription
BatchTransaction

{BatchTransaction} A batch transaction object.

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttransaction=database.batchTransaction({session:'my-session',transaction:'my-transaction',readTimestamp:1518464696657});

close(callback)

close(callback:SessionPoolCloseCallback):void;

Close the database connection and destroy all sessions associated with it.

Parameter
NameDescription
callbackSessionPoolCloseCallback

Callback function.

Returns
TypeDescription
void

{Promise}

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.close(function(err){if(err){// Error handling omitted.}});//-// In the event of a session leak, the error object will contain a// `messages` field.//-database.close(function(err){if(err &&err.messages){err.messages.forEach(function(message){console.error(message);});}});

close()

close():Promise<DatabaseCloseResponse>;
Returns
TypeDescription
Promise<DatabaseCloseResponse>

createBatchTransaction(options)

createBatchTransaction(options?:TimestampBounds):Promise<CreateBatchTransactionResponse>;

Create a transaction that can be used for batch querying.

Parameter
NameDescription
optionsTimestampBounds

[Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds).

Returns
TypeDescription
Promise<CreateBatchTransactionResponse>

{Promise

createBatchTransaction(callback)

createBatchTransaction(callback:CreateBatchTransactionCallback):void;
Parameter
NameDescription
callbackCreateBatchTransactionCallback
Returns
TypeDescription
void

createBatchTransaction(options, callback)

createBatchTransaction(options:TimestampBounds,callback:CreateBatchTransactionCallback):void;
Parameters
NameDescription
optionsTimestampBounds
callbackCreateBatchTransactionCallback
Returns
TypeDescription
void

createSession(options)

createSession(options:CreateSessionOptions):Promise<CreateSessionResponse>;

Create a new session, which can be used to perform transactions that read and/or modify data.

Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit.

**It is unlikely you will need to interact with sessions directly. By default, sessions are created and utilized for maximum performance automatically.**

Wrapper around .

Parameter
NameDescription
optionsCreateSessionOptions

Configuration object.

Returns
TypeDescription
Promise<CreateSessionResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.createSession(function(err,session,apiResponse){if(err){// Error handling omitted.}// `session` is a Session object.});//-// If the callback is omitted, we'll return a Promise.//-database.createSession().then(function(data){constsession=data[0];constapiResponse=data[1];});

createSession(callback)

createSession(callback:CreateSessionCallback):void;
Parameter
NameDescription
callbackCreateSessionCallback
Returns
TypeDescription
void

createSession(options, callback)

createSession(options:CreateSessionOptions,callback:CreateSessionCallback):void;
Parameters
NameDescription
optionsCreateSessionOptions
callbackCreateSessionCallback
Returns
TypeDescription
void

createTable(schema, gaxOptions)

createTable(schema:Schema,gaxOptions?:CallOptions):Promise<CreateTableResponse>;

Create a table.

Wrapper around .

Parameters
NameDescription
schemaSchema

A DDL CREATE statement describing the table.

gaxOptionsCallOptions

Request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<CreateTableResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');constschema='CREATE TABLE Singers ('+'  SingerId INT64 NOT NULL,'+'  FirstName STRING(1024),'+'  LastName STRING(1024),'+'  SingerInfo BYTES(MAX),'+') PRIMARY KEY(SingerId)';database.createTable(schema,function(err,table,operation,apiResponse){if(err){// Error handling omitted.}operation.on('error',function(err){}).on('complete',function(){// Table created successfully.});});//-// If the callback is omitted, we'll return a Promise.//-database.createTable(schema).then(function(data){consttable=data[0];constoperation=data[1];returnoperation.promise();}).then(function(){// Table created successfully.});

createTable(schema, callback)

createTable(schema:Schema,callback:CreateTableCallback):void;
Parameters
NameDescription
schemaSchema
callbackCreateTableCallback
Returns
TypeDescription
void

createTable(schema, gaxOptions, callback)

createTable(schema:Schema,gaxOptions:CallOptions,callback:CreateTableCallback):void;
Parameters
NameDescription
schemaSchema
gaxOptionsCallOptions
callbackCreateTableCallback
Returns
TypeDescription
void

delete(gaxOptions)

delete(gaxOptions?:CallOptions):Promise<DatabaseDeleteResponse>;

Delete the database.

Wrapper around .

Parameter
NameDescription
gaxOptionsCallOptions

Request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<DatabaseDeleteResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.delete(function(err,apiResponse){if(err){// Error handling omitted.}// Database was deleted successfully.});//-// If the callback is omitted, we'll return a Promise.//-database.delete().then(function(data){constapiResponse=data[0];});

delete(callback)

delete(callback:DatabaseDeleteCallback):void;
Parameter
NameDescription
callbackDatabaseDeleteCallback
Returns
TypeDescription
void

delete(gaxOptions, callback)

delete(gaxOptions:CallOptions,callback:DatabaseDeleteCallback):void;
Parameters
NameDescription
gaxOptionsCallOptions
callbackDatabaseDeleteCallback
Returns
TypeDescription
void

exists(gaxOptions)

exists(gaxOptions?:CallOptions):Promise<[boolean]>;

Check if a database exists.

Database#exists

Parameter
NameDescription
gaxOptionsCallOptions

Request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<[boolean]>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.exists(function(err,exists){});//-// If the callback is omitted, we'll return a Promise.//-database.exists().then(function(data){constexists=data[0];});

exists(callback)

exists(callback:ExistsCallback):void;
Parameter
NameDescription
callbackExistsCallback
Returns
TypeDescription
void

exists(gaxOptions, callback)

exists(gaxOptions:CallOptions,callback:ExistsCallback):void;
Parameters
NameDescription
gaxOptionsCallOptions
callbackExistsCallback
Returns
TypeDescription
void

formatName_(instanceName, name)

staticformatName_(instanceName:string,name:string):string;

Format the database name to include the instance name.

Parameters
NameDescription
instanceNamestring

The formatted instance name.

namestring

The table name.

Returns
TypeDescription
string

{string}

Example
Database.formatName_('projects/grape-spaceship-123/instances/my-instance','my-database');// 'projects/grape-spaceship-123/instances/my-instance/databases/my-database'

get(options)

get(options?:GetDatabaseConfig):Promise<DatabaseResponse>;

Get a database if it exists.

You may optionally use this to "get or create" an object by providing an object withautoCreate set totrue. Any extra configuration that is normally required for thecreate method must be contained within this object as well.

Parameter
NameDescription
optionsGetDatabaseConfig

Configuration object.

Returns
TypeDescription
Promise<DatabaseResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.get(function(err,database,apiResponse){// `database.metadata` has been populated.});//-// If the callback is omitted, we'll return a Promise.//-database.get().then(function(data){constdatabase=data[0];constapiResponse=data[0];});

get(callback)

get(callback:DatabaseCallback):void;
Parameter
NameDescription
callbackDatabaseCallback
Returns
TypeDescription
void

get(options, callback)

get(options:GetDatabaseConfig,callback:DatabaseCallback):void;
Parameters
NameDescription
optionsGetDatabaseConfig
callbackDatabaseCallback
Returns
TypeDescription
void

getDatabaseRoles(gaxOptions)

getDatabaseRoles(gaxOptions?:CallOptions):Promise<GetDatabaseRolesResponse>;

Gets a list of database roles

Parameter
NameDescription
gaxOptionsCallOptions

Request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<GetDatabaseRolesResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.getDatabaseRoles(function(err,roles){// `roles` is an array of `DatabaseRoles` objects.});//-// To control how many API requests are made and page through the results// manually, set `autoPaginate` to `false`.//-functioncallback(err,roles,nextQuery,apiResponse){if(nextQuery){// More results exist.database.getDatabaseRoles(nextQuery,callback);}}database.getInstances({gaxOptions:{autoPaginate:false}},callback);//-// If the callback is omitted, we'll return a Promise.//-database.getInstances().then(function(data){constroles=data[0];});

getDatabaseRoles(callback)

getDatabaseRoles(callback:GetDatabaseRolesCallback):void;
Parameter
NameDescription
callbackGetDatabaseRolesCallback
Returns
TypeDescription
void

getDatabaseRoles(gaxOptions, callback)

getDatabaseRoles(gaxOptions:CallOptions,callback:GetDatabaseRolesCallback):void;
Parameters
NameDescription
gaxOptionsCallOptions
callbackGetDatabaseRolesCallback
Returns
TypeDescription
void

getEnvironmentQueryOptions()

staticgetEnvironmentQueryOptions():databaseAdmin.spanner.v1.ExecuteSqlRequest.IQueryOptions;
Returns
TypeDescription
IQueryOptions

getIamPolicy(options)

getIamPolicy(options?:GetIamPolicyOptions):Promise<GetIamPolicyResponse>;

Retrieves the policy of the database.

A Policy is a collection of bindings. A binding binds one or more members, or principals, to a single role. Principals can be user accounts, service accounts, Google groups, and domains (such as G Suite). A role is a named list of permissions; each role can be an IAM predefined role or a user-created custom role.

Parameter
NameDescription
optionsGetIamPolicyOptions

requestedPolicyVersion and gax options(configuration options) Seehttps://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html for more details on gax options.

Returns
TypeDescription
Promise<GetIamPolicyResponse>

{Promise<Policy | undefined>} When resolved, contains the current policy of the database.

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');constpolicy=awaitdatabase.getIamPolicy();console.log(policy.bindings,policy.version,policy.etag,policy.auditConfigs)constpolicyWithVersionspecified=awaitdatabase.getIamPolicy({requestedPolicyVersion:3});

getIamPolicy(callback)

getIamPolicy(callback:GetIamPolicyCallback):void;
Parameter
NameDescription
callbackGetIamPolicyCallback
Returns
TypeDescription
void

getIamPolicy(options, callback)

getIamPolicy(options:GetIamPolicyOptions,callback:GetIamPolicyCallback):void;
Parameters
NameDescription
optionsGetIamPolicyOptions
callbackGetIamPolicyCallback
Returns
TypeDescription
void

getMetadata(gaxOptions)

getMetadata(gaxOptions?:CallOptions):Promise<GetDatabaseMetadataResponse>;

Get the database's metadata.

Wrapper around .

Parameter
NameDescription
gaxOptionsCallOptions

Request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<GetDatabaseMetadataResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.getMetadata(function(err,metadata){if(err){// Error handling omitted.}// Database was deleted successfully.});//-// If the callback is omitted, we'll return a Promise.//-database.getMetadata().then(function(data){constmetadata=data[0];constapiResponse=data[1];});

getMetadata(callback)

getMetadata(callback:GetDatabaseMetadataCallback):void;
Parameter
NameDescription
callbackGetDatabaseMetadataCallback
Returns
TypeDescription
void

getMetadata(gaxOptions, callback)

getMetadata(gaxOptions:CallOptions,callback:GetDatabaseMetadataCallback):void;
Parameters
NameDescription
gaxOptionsCallOptions
callbackGetDatabaseMetadataCallback
Returns
TypeDescription
void

getOperations(options)

getOperations(options?:GetDatabaseOperationsOptions):Promise<GetDatabaseOperationsResponse>;

List pending and completed operations for the database.

Parameter
NameDescription
optionsGetDatabaseOperationsOptions

Contains query object for listing database operations and request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<GetDatabaseOperationsResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');const[operations]=awaitdatabase.getOperations();//-// To manually handle pagination, set autoPaginate:false in gaxOptions.//-letpageToken=undefined;do{const[operations,,response]=awaitdatabase.getOperations({pageSize:3,pageToken,gaxOptions:{autoPaginate:false},});operations.forEach(operation=>{// Do something with operation});pageToken=response.nextPageToken;}while(pageToken);

getOperations(callback)

getOperations(callback:GetDatabaseOperationsCallback):void;
Parameter
NameDescription
callbackGetDatabaseOperationsCallback
Returns
TypeDescription
void

getOperations(options, callback)

getOperations(options:GetDatabaseOperationsOptions,callback:GetDatabaseOperationsCallback):void;
Parameters
NameDescription
optionsGetDatabaseOperationsOptions
callbackGetDatabaseOperationsCallback
Returns
TypeDescription
void

getRestoreInfo(options)

getRestoreInfo(options?:CallOptions):Promise<IRestoreInfoTranslatedEnum|undefined>;

Retrieves the restore information of the database.

Parameter
NameDescription
optionsCallOptions
Returns
TypeDescription
Promise<IRestoreInfoTranslatedEnum | undefined>

{Promise<IRestoreInfoTranslatedEnum | undefined>} When resolved, contains the restore information for the database if it was restored from a backup.

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');constrestoreInfo=awaitdatabase.getRestoreInfo();console.log(`Database restored from${restoreInfo.backupInfo.backup}`);

getRestoreInfo(callback)

getRestoreInfo(callback:GetRestoreInfoCallback):void;
Parameter
NameDescription
callbackGetRestoreInfoCallback
Returns
TypeDescription
void

getRestoreInfo(options, callback)

getRestoreInfo(options:CallOptions,callback:GetRestoreInfoCallback):void;
Parameters
NameDescription
optionsCallOptions
callbackGetRestoreInfoCallback
Returns
TypeDescription
void

getSchema(options)

getSchema(options?:CallOptions):Promise<GetSchemaResponse>;

Get this database's schema as a list of formatted DDL statements.

Wrapper around .

Parameter
NameDescription
optionsCallOptions
Returns
TypeDescription
Promise<GetSchemaResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.getSchema(function(err,statements,apiResponse){});//-// If the callback is omitted, we'll return a Promise.//-database.getSchema().then(function(data){conststatements=data[0];constapiResponse=data[1];});

getSchema(callback)

getSchema(callback:GetSchemaCallback):void;
Parameter
NameDescription
callbackGetSchemaCallback
Returns
TypeDescription
void

getSchema(options, callback)

getSchema(options:CallOptions,callback:GetSchemaCallback):void;
Parameters
NameDescription
optionsCallOptions
callbackGetSchemaCallback
Returns
TypeDescription
void

getSessions(options)

getSessions(options?:GetSessionsOptions):Promise<GetSessionsResponse>;

Gets a list of sessions.

Wrapper around

Parameter
NameDescription
optionsGetSessionsOptions

Options object for listing sessions.

Returns
TypeDescription
Promise<GetSessionsResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.getSessions(function(err,sessions){// `sessions` is an array of `Session` objects.});//-// To control how many API requests are made and page through the results// manually, set `autoPaginate` to `false`.//-functioncallback(err,sessions,nextQuery,apiResponse){if(nextQuery){// More results exist.database.getSessions(nextQuery,callback);}}database.getInstances({gaxOptions:{autoPaginate:false}},callback);//-// If the callback is omitted, we'll return a Promise.//-database.getInstances().then(function(data){constsessions=data[0];});

getSessions(callback)

getSessions(callback:GetSessionsCallback):void;
Parameter
NameDescription
callbackGetSessionsCallback
Returns
TypeDescription
void

getSessions(options, callback)

getSessions(options:GetSessionsOptions,callback:GetSessionsCallback):void;
Parameters
NameDescription
optionsGetSessionsOptions
callbackGetSessionsCallback
Returns
TypeDescription
void

getSessionsStream(options)

getSessionsStream(options?:GetSessionsOptions):NodeJS.ReadableStream;

Get a list of sessions as a readable object stream.

Wrapper around

Parameter
NameDescription
optionsGetSessionsOptions

Options object for listing sessions.

Returns
TypeDescription
NodeJS.ReadableStream

{ReadableStream} A readable stream that emitsSession instances.

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.getSessionsStream().on('error',console.error).on('data',function(database){// `sessions` is a `Session` object.}).on('end',function(){// All sessions retrieved.});//-// If you anticipate many results, you can end a stream early to prevent// unnecessary processing and API requests.//-database.getSessionsStream().on('data',function(session){this.end();});

getSnapshot(options)

getSnapshot(options?:TimestampBounds):Promise<[Snapshot]>;

Get a read onlySnapshot transaction.

Wrapper around .

**NOTE:** When finished with the Snapshot, should be called to release the underlyingSession. **Failure to do could result in a Session leak.**

**NOTE:** Since the returnedSnapshot transaction is not a single-use transaction, it is invalid to set theminReadTimestamp andmaxStaleness parameters in as those parameters can only be set for single-use transactions. https://cloud.google.com/spanner/docs/reference/rest/v1/TransactionOptions#bounded-staleness

Parameter
NameDescription
optionsTimestampBounds

Timestamp bounds.

Returns
TypeDescription
Promise<[Snapshot]>

{Promise

Examples
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.getSnapshot(function(err,transaction){if(err){// Error handling omitted.}// Should be called when finished with Snapshot.transaction.end();});

If the callback is omitted, we'll return a Promise.

database.getSnapshot().then(function(data){consttransaction=data[0];});

Read-only transaction:

// Imports the Google Cloud client libraryconst{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';// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);// Gets a transaction object that captures the database state// at a specific point in timedatabase.getSnapshot(async(err,transaction)=>{if(err){console.error(err);return;}constqueryOne='SELECT SingerId, AlbumId, AlbumTitle FROM Albums';try{// Read #1, using SQLconst[qOneRows]=awaittransaction.run(queryOne);qOneRows.forEach(row=>{constjson=row.toJSON();console.log(`SingerId:${json.SingerId}, AlbumId:${json.AlbumId}, AlbumTitle:${json.AlbumTitle}`);});constqueryTwo={columns:['SingerId','AlbumId','AlbumTitle'],};// Read #2, using the `read` method. Even if changes occur// in-between the reads, the transaction ensures that both// return the same data.const[qTwoRows]=awaittransaction.read('Albums',queryTwo);qTwoRows.forEach(row=>{constjson=row.toJSON();console.log(`SingerId:${json.SingerId}, AlbumId:${json.AlbumId}, AlbumTitle:${json.AlbumTitle}`);});console.log('Successfully executed read-only transaction.');}catch(err){console.error('ERROR:',err);}finally{transaction.end();// Close the database when finished.awaitdatabase.close();}});

getSnapshot(callback)

getSnapshot(callback:GetSnapshotCallback):void;
Parameter
NameDescription
callbackGetSnapshotCallback
Returns
TypeDescription
void

getSnapshot(options, callback)

getSnapshot(options:TimestampBounds,callback:GetSnapshotCallback):void;
Parameters
NameDescription
optionsTimestampBounds
callbackGetSnapshotCallback
Returns
TypeDescription
void

getState(options)

getState(options?:CallOptions):Promise<EnumKey<typeofdatabaseAdmin.spanner.admin.database.v1.Database.State>|undefined>;

Retrieves the state of the database.

The database state indicates if the database is ready after creation or after being restored from a backup.

Parameter
NameDescription
optionsCallOptions
Returns
TypeDescription
Promise<EnumKey<typeofdatabaseAdmin.spanner.admin.database.v1.Database.State> | undefined>

{Promise<EnumKey<typeof, google.spanner.admin.database.v1.Database.State> | undefined>} When resolved, contains the current state of the database if the state is defined.

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');conststate=awaitdatabase.getState();constisReady=(state==='READY');

getState(callback)

getState(callback:GetStateCallback):void;
Parameter
NameDescription
callbackGetStateCallback
Returns
TypeDescription
void

getState(options, callback)

getState(options:CallOptions,callback:GetStateCallback):void;
Parameters
NameDescription
optionsCallOptions
callbackGetStateCallback
Returns
TypeDescription
void

getTransaction()

getTransaction():Promise<[Transaction]>;

Get a read/write readyTransaction object.

**NOTE:** In the event that you encounter an error while reading/writing, if you decide to forgo calling or , then you need to call to release the underlyingSession object. **Failure to do could result in a Session leak.**

Wrapper around .

Returns
TypeDescription
Promise<[Transaction]>

{Promise

Examples
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.getTransaction(function(err,transaction){});

If the callback is omitted, we'll return a Promise.

database.getTransaction().then(function(data){consttransaction=data[0];});

getTransaction(callback)

getTransaction(callback:GetTransactionCallback):void;
Parameter
NameDescription
callbackGetTransactionCallback
Returns
TypeDescription
void

makePooledRequest_(config)

makePooledRequest_(config:RequestConfig):Promise<Session>;

Make an API request, first assuring an active session is used.

Parameter
NameDescription
configRequestConfig

Request config

Returns
TypeDescription
Promise<Session>

makePooledRequest_(config, callback)

makePooledRequest_(config:RequestConfig,callback:PoolRequestCallback):void;
Parameters
NameDescription
configRequestConfig
callbackPoolRequestCallback
Returns
TypeDescription
void

makePooledStreamingRequest_(config)

makePooledStreamingRequest_(config:RequestConfig):Readable;

Make an API request as a stream, first assuring an active session is used.

Parameter
NameDescription
configRequestConfig

Request config

Returns
TypeDescription
Readable

{Stream}

restore(backupPath)

restore(backupPath:string):Promise<RestoreDatabaseResponse>;

Restore a backup into this database.

When this call completes, the restore will have commenced but will not necessarily have completed.

Parameter
NameDescription
backupPathstring

The path of the backup to restore.

Returns
TypeDescription
Promise<RestoreDatabaseResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');constbackupName='projects/my-project/instances/my-instance/backups/my-backup';const[,restoreOperation]=awaitdatabase.restore(backupName);// Wait for restore to completeawaitrestoreOperation.promise();//-// Restore database with a different encryption key to the one used by the// backup.//-const[,restoreWithKeyOperation]=awaitdatabase.restore(backupName,{encryptionConfig:{encryptionType:'CUSTOMER_MANAGED_ENCRYPTION',kmsKeyName:'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key',}},);// Wait for restore to completeawaitrestoreWithKeyOperation.promise();

restore(backupPath, options)

restore(backupPath:string,options?:RestoreOptions|CallOptions):Promise<RestoreDatabaseResponse>;
Parameters
NameDescription
backupPathstring
optionsRestoreOptions |CallOptions
Returns
TypeDescription
Promise<RestoreDatabaseResponse>

restore(backupPath, callback)

restore(backupPath:string,callback:RestoreDatabaseCallback):void;
Parameters
NameDescription
backupPathstring
callbackRestoreDatabaseCallback
Returns
TypeDescription
void

restore(backupPath, options, callback)

restore(backupPath:string,options:RestoreOptions|CallOptions,callback:RestoreDatabaseCallback):void;
Parameters
NameDescription
backupPathstring
optionsRestoreOptions |CallOptions
callbackRestoreDatabaseCallback
Returns
TypeDescription
void

run(query)

run(query:string|ExecuteSqlRequest):Promise<RunResponse>;

Execute a SQL statement on this database.

Wrapper around .

Parameter
NameDescription
querystring |ExecuteSqlRequest

A SQL query or object.

Returns
TypeDescription
Promise<RunResponse>

{Promise

Examples
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');constquery='SELECT * FROM Singers';database.run(query,function(err,rows){if(err){// Error handling omitted.}constfirstRow=rows[0];// firstRow = [//   {//     name: 'SingerId',//     value: '1'//   },//   {//     name: 'Name',//     value: 'Eddie Wilson'//   }// ]});//-// Rows are returned as an array of object arrays. Each object has a `name`// and `value` property. To get a serialized object, call `toJSON()`.//-database.run(query,function(err,rows){if(err){// Error handling omitted.}constfirstRow=rows[0];// firstRow.toJSON() = {//   SingerId: '1',//   Name: 'Eddie Wilson'// }});//-// Alternatively, set `query.json` to `true`, and this step will be performed// automatically.//-database.run(query,function(err,rows){if(err){// Error handling omitted.}constfirstRow=rows[0];// firstRow = {//   SingerId: '1',//   Name: 'Eddie Wilson'// }});//-// The SQL query string can contain parameter placeholders. A parameter// placeholder consists of '@' followed by the parameter name.//-constquery={sql:'SELECT * FROM Singers WHERE name = @name',params:{name:'Eddie Wilson'}};database.run(query,function(err,rows){});//-// If you need to enforce a specific param type, a types map can be provided.// This is typically useful if your param value can be null.//-constquery={sql:'SELECT * FROM Singers WHERE name = @name AND id = @id',params:{id:spanner.int(8),name:null},types:{id:'int64',name:'string'}};database.run(query,function(err,rows){});//-// If the callback is omitted, we'll return a Promise.//-database.run(query).then(function(data){constrows=data[0];});

Full example:

// Imports the Google Cloud client libraryconst{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';// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);constquery={sql:'SELECT SingerId, AlbumId, AlbumTitle FROM Albums',};// Queries rows from the Albums tabletry{const[rows]=awaitdatabase.run(query);rows.forEach(row=>{constjson=row.toJSON();console.log(`SingerId:${json.SingerId}, AlbumId:${json.AlbumId}, AlbumTitle:${json.AlbumTitle}`);});}catch(err){console.error('ERROR:',err);}finally{// Close the database when finished.awaitdatabase.close();}

Querying data with an index:

// Imports the Google Cloud client libraryconst{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 startTitle = 'Ardvark';// const endTitle = 'Goo';// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);constquery={sql:`SELECT AlbumId, AlbumTitle, MarketingBudget          FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle}          WHERE AlbumTitle >= @startTitle AND AlbumTitle <= @endtitle`,=""params:=""{=""starttitle:=""starttitle,=""endtitle:=""endtitle,=""},=""};=""queries=""rows=""from=""the=""albums=""table=""try=""{=""const=""[rows]="await"database.run(query);=""rows.foreach(row="">{constjson=row.toJSON();constmarketingBudget=json.MarketingBudget?json.MarketingBudget:null;// This value is nullableconsole.log(`AlbumId:${json.AlbumId}, AlbumTitle:${json.AlbumTitle}, MarketingBudget:${marketingBudget}`);});}catch(err){console.error('ERROR:',err);}finally{// Close the database when finished.database.close();}

run(query, options)

run(query:string|ExecuteSqlRequest,options?:TimestampBounds):Promise<RunResponse>;
Parameters
NameDescription
querystring |ExecuteSqlRequest
optionsTimestampBounds
Returns
TypeDescription
Promise<RunResponse>

run(query, callback)

run(query:string|ExecuteSqlRequest,callback:RunCallback):void;
Parameters
NameDescription
querystring |ExecuteSqlRequest
callbackRunCallback
Returns
TypeDescription
void

run(query, options, callback)

run(query:string|ExecuteSqlRequest,options:TimestampBounds,callback:RunCallback):void;
Parameters
NameDescription
querystring |ExecuteSqlRequest
optionsTimestampBounds
callbackRunCallback
Returns
TypeDescription
void

runPartitionedUpdate(query)

runPartitionedUpdate(query:string|ExecuteSqlRequest):Promise<[number]>;

Partitioned DML transactions are used to execute DML statements with a different execution strategy that provides different, and often better, scalability properties for large, table-wide operations than DML in a Transaction transaction. Smaller scoped statements, such as an OLTP workload, should prefer using Transaction transactions.

Parameter
NameDescription
querystring |ExecuteSqlRequest

A DML statement or object.

Returns
TypeDescription
Promise<[number]>

{Promise

runPartitionedUpdate(query, callback)

runPartitionedUpdate(query:string|ExecuteSqlRequest,callback?:RunUpdateCallback):void;
Parameters
NameDescription
querystring |ExecuteSqlRequest
callbackRunUpdateCallback
Returns
TypeDescription
void

runStream(query, options)

runStream(query:string|ExecuteSqlRequest,options?:TimestampBounds):PartialResultStream;

Create a readable object stream to receive resulting rows from a SQL statement.

Wrapper around .

Parameters
NameDescription
querystring |ExecuteSqlRequest

A SQL query or object.

optionsTimestampBounds

Snapshot timestamp bounds.

Returns
TypeDescription
PartialResultStream

{PartialResultStream} A readable stream that emits rows.

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');constquery='SELECT * FROM Singers';database.runStream(query).on('error',function(err){}).on('data',function(row){// row = [//   {//     name: 'SingerId',//     value: '1'//   },//   {//     name: 'Name',//     value: 'Eddie Wilson'//   }// ]// ]}).on('end',function(){// All results retrieved.});//-// Rows are returned as an array of objects. Each object has a `name` and// `value` property. To get a serialized object, call `toJSON()`.//-database.runStream(query).on('error',function(err){}).on('data',function(row){// row.toJSON() = {//   SingerId: '1',//   Name: 'Eddie Wilson'// }}).on('end',function(){// All results retrieved.});//-// Alternatively, set `query.json` to `true`, and this step will be performed// automatically.//-query.json=true;database.runStream(query).on('error',function(err){}).on('data',function(row){// row = {//   SingerId: '1',//   Name: 'Eddie Wilson'// }}).on('end',function(){// All results retrieved.});//-// The SQL query string can contain parameter placeholders. A parameter// placeholder consists of '@' followed by the parameter name.//-constquery={sql:'SELECT * FROM Singers WHERE name = @name',params:{name:'Eddie Wilson'}};database.runStream(query).on('error',function(err){}).on('data',function(row){}).on('end',function(){});//-// If you need to enforce a specific param type, a types map can be provided.// This is typically useful if your param value can be null.//-constquery={sql:'SELECT * FROM Singers WHERE name = @name',params:{name:'Eddie Wilson'},types:{name:'string'}};database.runStream(query).on('error',function(err){}).on('data',function(row){}).on('end',function(){});//-// If you anticipate many results, you can end a stream early to prevent// unnecessary processing and API requests.//-database.runStream(query).on('data',function(row){this.end();});

runTransaction(runFn)

runTransaction(runFn:RunTransactionCallback):void;

A transaction in Cloud Spanner is a set of reads and writes that execute atomically at a single logical point in time across columns, rows, and tables in a database.

Note that Cloud Spanner does not support nested transactions. If a new transaction is started inside of the run function, it will be an independent transaction.

The callback you provide to this function will become the "run function". It will be executed with either an error or aTransaction object. The Transaction object will let you run queries and queue mutations until you are ready to .

In the event that an aborted error occurs, we will re-run therunFn in its entirety. If you prefer to handle aborted errors for yourself please refer to .

**NOTE:** In the event that you encounter an error while reading/writing, if you decide to forgo calling or , then you need to call to release the underlyingSession object. **Failure to do could result in a Session leak.**

For a more complete listing of functionality available to a Transaction, see theTransaction API documentation. For a general overview of transactions within Cloud Spanner, see [Transactions](https://cloud.google.com/spanner/docs/transactions) from the official Cloud Spanner documentation.

If you would like to run a transaction and receive a promise or use async/await, use .

Parameter
NameDescription
runFnRunTransactionCallback
Returns
TypeDescription
void
Examples
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.runTransaction(function(err,transaction){if(err){// Error handling omitted.}// Run a transactional query.transaction.run('SELECT * FROM Singers',function(err,rows){if(err){// Error handling omitted.}// Queue a mutation (note that there is no callback passed to `insert`).transaction.insert('Singers',{SingerId:'Id3b',Name:'Joe West'});// Commit the transaction.transaction.commit(function(err){if(!err){// Transaction committed successfully.}});});});

Read-write transaction:

// This sample transfers 200,000 from the MarketingBudget field// of the second Album to the first Album, as long as the second// Album has enough money in its budget. Make sure to run the// addColumn and updateData samples first (in that order).// Imports the Google Cloud client libraryconst{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';// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);consttransferAmount=200000;database.runTransaction(async(err,transaction)=>{if(err){console.error(err);return;}letfirstBudget,secondBudget;constqueryOne={columns:['MarketingBudget'],keys:[[2,2]],// SingerId: 2, AlbumId: 2};constqueryTwo={columns:['MarketingBudget'],keys:[[1,1]],// SingerId: 1, AlbumId: 1};Promise.all([// Reads the second album's budgettransaction.read('Albums',queryOne).then(results=>{// Gets second album's budgetconstrows=results[0].map(row=>row.toJSON());secondBudget=rows[0].MarketingBudget;console.log(`The second album's marketing budget:${secondBudget}`);// Makes sure the second album's budget is large enoughif(secondBudget <transferamount)=""{=""throw=""new=""error(=""`the="" second="" album's="" budget="" (${secondbudget})="" is="" less="" than="" the="" transfer="" amount="" (${transferamount}).`="");=""}=""}),=""reads=""the=""first=""album's="" budget="" transaction.read('albums',="" querytwo).then(results=""> {        // Gets first album'sbudgetconstrows=results[0].map(row=>row.toJSON());firstBudget=rows[0].MarketingBudget;console.log(`The first album's marketing budget:${firstBudget}`);}),]).then(()=>{console.log(firstBudget,secondBudget);// Transfers the budgets between the albumsfirstBudget+=transferAmount;secondBudget-=transferAmount;console.log(firstBudget,secondBudget);// Updates the database// Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so they// must be converted (back) to strings before being inserted as INT64s.transaction.update('Albums',[{SingerId:'1',AlbumId:'1',MarketingBudget:firstBudget.toString(),},{SingerId:'2',AlbumId:'2',MarketingBudget:secondBudget.toString(),},]);}).then(()=>{// Commits the transaction and send the changes to the databasereturntransaction.commit();}).then(()=>{console.log(`Successfully executed read-write transaction to transfer${transferAmount} from Album 2 to Album 1.`);}).catch(err=>{console.error('ERROR:',err);}).then(()=>{transaction.end();// Closes the database when finishedreturndatabase.close();});});

runTransaction(options, runFn)

runTransaction(options:RunTransactionOptions,runFn:RunTransactionCallback):void;
Parameters
NameDescription
optionsRunTransactionOptions
runFnRunTransactionCallback
Returns
TypeDescription
void

runTransactionAsync(runFn)

runTransactionAsync<T={}>(runFn:AsyncRunTransactionCallback<T>):Promise<T>;
Parameter
NameDescription
runFnAsyncRunTransactionCallback<T>
Returns
TypeDescription
Promise<T>
Type Parameter
NameDescription
T

runTransactionAsync(options, runFn)

runTransactionAsync<T={}>(options:RunTransactionOptions,runFn:AsyncRunTransactionCallback<T>):Promise<T>;
Parameters
NameDescription
optionsRunTransactionOptions
runFnAsyncRunTransactionCallback<T>
Returns
TypeDescription
Promise<T>
Type Parameter
NameDescription
T

session(name)

session(name?:string):Session;

Create a Session object.

It is unlikely you will need to interact with sessions directly. By default, sessions are created and utilized for maximum performance automatically.

Parameter
NameDescription
namestring

The name of the session. If not provided, it is assumed you are going to create it.

Returns
TypeDescription
Session

{Session} A Session object.

Example
varsession=database.session('session-name');

setIamPolicy(policy)

setIamPolicy(policy:SetIamPolicyRequest):Promise<SetIamPolicyResponse>;

Sets the policy for the database.

A Policy is a collection of bindings. A binding binds one or more members, or principals, to a single role. Principals can be user accounts, service accounts, Google groups, and domains (such as G Suite). A role is a named list of permissions; each role can be an IAM predefined role or a user-created custom role.

Parameter
NameDescription
policySetIamPolicyRequest

requestedPolicyVersion and gax options(configuration options) Seehttps://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html for more details on gax options.

Returns
TypeDescription
Promise<SetIamPolicyResponse>

{Promise<Policy | undefined>} When resolved, contains the current policy of the database.

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');constbinding={role:'roles/spanner.fineGrainedAccessUser',members:['user:asthamohta@google.com'],condition:{title:'new condition',expression:'resource.name.endsWith("/databaseRoles/parent")',},};constpolicy={bindings:[newBinding],version:3,};constpolicy=awaitdatabase.setIamPolicy({policy:policy});

setIamPolicy(policy, options)

setIamPolicy(policy:SetIamPolicyRequest,options?:CallOptions):Promise<SetIamPolicyResponse>;
Parameters
NameDescription
policySetIamPolicyRequest
optionsCallOptions
Returns
TypeDescription
Promise<SetIamPolicyResponse>

setIamPolicy(policy, callback)

setIamPolicy(policy:SetIamPolicyRequest,callback:SetIamPolicyCallback):void;
Parameters
NameDescription
policySetIamPolicyRequest
callbackSetIamPolicyCallback
Returns
TypeDescription
void

setIamPolicy(policy, options, callback)

setIamPolicy(policy:SetIamPolicyRequest,options:CallOptions,callback:SetIamPolicyCallback):void;
Parameters
NameDescription
policySetIamPolicyRequest
optionsCallOptions
callbackSetIamPolicyCallback
Returns
TypeDescription
void

setMetadata(metadata, gaxOptions)

setMetadata(metadata:IDatabase,gaxOptions?:CallOptions):Promise<SetDatabaseMetadataResponse>;

Update the metadata for this database. Note that this method follows PATCH semantics, so previously-configured settings will persist.

Wrapper around .

Parameters
NameDescription
metadataIDatabase

The metadata you wish to set.

gaxOptionsCallOptions

Request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<SetDatabaseMetadataResponse>

{Promise

Example
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');constmetadata={enableDropProtection:true};database.setMetadata(metadata,function(err,operation,apiResponse){if(err){// Error handling omitted.}operation.on('error',function(err){}).on('complete',function(){// Metadata updated successfully.});});//-// If the callback is omitted, we'll return a Promise.//-database.setMetadata(metadata).then(function(data){constoperation=data[0];constapiResponse=data[1];});

setMetadata(metadata, callback)

setMetadata(metadata:IDatabase,callback:SetDatabaseMetadataCallback):void;
Parameters
NameDescription
metadataIDatabase
callbackSetDatabaseMetadataCallback
Returns
TypeDescription
void

setMetadata(metadata, gaxOptions, callback)

setMetadata(metadata:IDatabase,gaxOptions:CallOptions,callback:SetDatabaseMetadataCallback):void;
Parameters
NameDescription
metadataIDatabase
gaxOptionsCallOptions
callbackSetDatabaseMetadataCallback
Returns
TypeDescription
void

table(name)

table(name:string):Table;
Parameter
NameDescription
namestring
Returns
TypeDescription
Table

updateSchema(statements, gaxOptions)

updateSchema(statements:Schema,gaxOptions?:CallOptions):Promise<UpdateSchemaResponse>;

Update the schema of the database by creating/altering/dropping tables, columns, indexes, etc.

This method immediately responds with an Operation object. Register event handlers for the "error" and "complete" events to see how the operation finishes. Follow along with the examples below.

Wrapper around .

Parameters
NameDescription
statementsSchema

An array of database DDL statements, or an [UpdateDatabaseDdlRequest object](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.UpdateDatabaseDdlRequest).

gaxOptionsCallOptions

Request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<UpdateSchemaResponse>

{Promise

Examples
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');conststatements=['CREATE TABLE Singers ('+'  SingerId INT64 NOT NULL,'+'  FirstName STRING(1024),'+'  LastName STRING(1024),'+'  SingerInfo BYTES(MAX),'+') PRIMARY KEY(SingerId)'];database.updateSchema(statements,function(err,operation,apiResponse){if(err){// Error handling omitted.}operation.on('error',function(err){}).on('complete',function(){// Database schema updated successfully.});});//-// If the callback is omitted, we'll return a Promise.//-database.updateSchema(statements).then(function(data){constoperation=data[0];returnoperation.promise();}).then(function(){// Database schema updated successfully.});

Adding a column:

/**   * TODO(developer): Uncomment the following lines before running the sample.   */// const projectId = 'my-project-id';// const instanceId = 'my-instance';// const databaseId = 'my-database';// Imports the Google Cloud client libraryconst{Spanner}=require('@google-cloud/spanner');// creates a clientconstspanner=newSpanner({projectId:projectId,});constdatabaseAdminClient=spanner.getDatabaseAdminClient();// Creates a new index in the databasetry{const[operation]=awaitdatabaseAdminClient.updateDatabaseDdl({database:databaseAdminClient.databasePath(projectId,instanceId,databaseId),statements:['ALTER TABLE Albums ADD COLUMN MarketingBudget INT64'],});console.log('Waiting for operation to complete...');awaitoperation.promise();console.log('Added the MarketingBudget column.');}catch(err){console.error('ERROR:',err);}finally{// Close the spanner client when finished.// The databaseAdminClient does not require explicit closure. The closure of the Spanner client will automatically close the databaseAdminClient.spanner.close();}

Creating an index:

// Imports the Google Cloud client libraryconst{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';// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);constrequest=['CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)'];// Creates a new index in the databasetry{const[operation]=awaitdatabase.updateSchema(request);console.log('Waiting for operation to complete...');awaitoperation.promise();console.log('Added the AlbumsByAlbumTitle index.');}catch(err){console.error('ERROR:',err);}finally{// Close the database when finished.database.close();}

Creating a storing index:

// "Storing" indexes store copies of the columns they index// This speeds up queries, but takes more space compared to normal indexes// See the link below for more information:// https://cloud.google.com/spanner/docs/secondary-indexes#storing_clause// Imports the Google Cloud client libraryconst{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';// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);constrequest=['CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)',];// Creates a new index in the databasetry{const[operation]=awaitdatabase.updateSchema(request);console.log('Waiting for operation to complete...');awaitoperation.promise();console.log('Added the AlbumsByAlbumTitle2 index.');}catch(err){console.error('ERROR:',err);}finally{// Close the database when finished.database.close();}

updateSchema(statements, callback)

updateSchema(statements:Schema,callback:UpdateSchemaCallback):void;
Parameters
NameDescription
statementsSchema
callbackUpdateSchemaCallback
Returns
TypeDescription
void

updateSchema(statements, gaxOptions, callback)

updateSchema(statements:Schema,gaxOptions:CallOptions,callback:UpdateSchemaCallback):void;
Parameters
NameDescription
statementsSchema
gaxOptionsCallOptions
callbackUpdateSchemaCallback
Returns
TypeDescription
void

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-10-30 UTC.