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');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = 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 the Database class

Parameters
NameDescription
instance Instance
name string
poolOptions SessionPoolConstructor | SessionPoolOptions
queryOptions IQueryOptions

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
session Session
query string | ExecuteSqlRequest
callback RunUpdateCallback
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
options number | BatchCreateSessionsOptions

Desired session count or a configuration object.

Returns
TypeDescription
Promise<BatchCreateSessionsResponse>

{Promise

Examples

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const count = 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] = await database.batchCreateSessions(count);

batchCreateSessions(options, callback)

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

batchTransaction(identifier, options)

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

Get a reference to a object.

Parameters
NameDescription
identifier TransactionIdentifier

The transaction identifier.

options TimestampBounds

[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');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const transaction = 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
callback SessionPoolCloseCallback

Callback function.

Returns
TypeDescription
void

{Promise}

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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
options TimestampBounds

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

Returns
TypeDescription
Promise<CreateBatchTransactionResponse>

{Promise

createBatchTransaction(callback)

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

createBatchTransaction(options, callback)

createBatchTransaction(options: TimestampBounds, callback: CreateBatchTransactionCallback): void;
Parameters
NameDescription
options TimestampBounds
callback CreateBatchTransactionCallback
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
options CreateSessionOptions

Configuration object.

Returns
TypeDescription
Promise<CreateSessionResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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) {
  const session = data[0];
  const apiResponse = data[1];
});

createSession(callback)

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

createSession(options, callback)

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

createTable(schema, gaxOptions)

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

Create a table.

Wrapper around .

Parameters
NameDescription
schema Schema

A DDL CREATE statement describing the table.

gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<CreateTableResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const schema =
  '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) {
    const table = data[0];
    const operation = data[1];

    return operation.promise();
  })
  .then(function() {
    // Table created successfully.
  });

createTable(schema, callback)

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

createTable(schema, gaxOptions, callback)

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

delete(gaxOptions)

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

Delete the database.

Wrapper around .

Parameter
NameDescription
gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<DatabaseDeleteResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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) {
  const apiResponse = data[0];
});

delete(callback)

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

delete(gaxOptions, callback)

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

exists(gaxOptions)

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

Check if a database exists.

Database#exists

Parameter
NameDescription
gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<[boolean]>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

database.exists(function(err, exists) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
database.exists().then(function(data) {
  const exists = data[0];
});

exists(callback)

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

exists(gaxOptions, callback)

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

formatName_(instanceName, name)

static formatName_(instanceName: string, name: string): string;

Format the database name to include the instance name.

Parameters
NameDescription
instanceName string

The formatted instance name.

name string

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 with autoCreate set to true. Any extra configuration that is normally required for the create method must be contained within this object as well.

Parameter
NameDescription
options GetDatabaseConfig

Configuration object.

Returns
TypeDescription
Promise<DatabaseResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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) {
  const database = data[0];
  const apiResponse = data[0];
});

get(callback)

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

get(options, callback)

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

getDatabaseRoles(gaxOptions)

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

Gets a list of database roles

Parameter
NameDescription
gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<GetDatabaseRolesResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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`.
//-
function callback(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) {
  const roles = data[0];
});

getDatabaseRoles(callback)

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

getDatabaseRoles(gaxOptions, callback)

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

getEnvironmentQueryOptions()

static getEnvironmentQueryOptions(): 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
options GetIamPolicyOptions

requestedPolicyVersion and gax options(configuration options) See https://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');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const policy = await database.getIamPolicy();
console.log(policy.bindings, policy.version, policy.etag, policy.auditConfigs)
const policyWithVersion specified = await database.getIamPolicy({requestedPolicyVersion: 3});

getIamPolicy(callback)

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

getIamPolicy(options, callback)

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

getMetadata(gaxOptions)

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

Get the database's metadata.

Wrapper around .

Parameter
NameDescription
gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<GetDatabaseMetadataResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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) {
  const metadata = data[0];
  const apiResponse = data[1];
});

getMetadata(callback)

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

getMetadata(gaxOptions, callback)

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

getOperations(options)

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

List pending and completed operations for the database.

Parameter
NameDescription
options GetDatabaseOperationsOptions

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

Returns
TypeDescription
Promise<GetDatabaseOperationsResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const [operations] = await database.getOperations();

//-
// To manually handle pagination, set autoPaginate:false in gaxOptions.
//-
let pageToken = undefined;
do {
  const [operations, , response] = await database.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
callback GetDatabaseOperationsCallback
Returns
TypeDescription
void

getOperations(options, callback)

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

getRestoreInfo(options)

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

Retrieves the restore information of the database.

Parameter
NameDescription
options CallOptions
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');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const restoreInfo = await database.getRestoreInfo();
console.log(`Database restored from ${restoreInfo.backupInfo.backup}`);

getRestoreInfo(callback)

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

getRestoreInfo(options, callback)

getRestoreInfo(options: CallOptions, callback: GetRestoreInfoCallback): void;
Parameters
NameDescription
options CallOptions
callback GetRestoreInfoCallback
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
options CallOptions
Returns
TypeDescription
Promise<GetSchemaResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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) {
  const statements = data[0];
  const apiResponse = data[1];
});

getSchema(callback)

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

getSchema(options, callback)

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

getSessions(options)

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

Gets a list of sessions.

Wrapper around

Parameter
NameDescription
options GetSessionsOptions

Options object for listing sessions.

Returns
TypeDescription
Promise<GetSessionsResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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`.
//-
function callback(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) {
  const sessions = data[0];
});

getSessions(callback)

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

getSessions(options, callback)

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

getSessionsStream(options)

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

Get a list of sessions as a readable object stream.

Wrapper around

Parameter
NameDescription
options GetSessionsOptions

Options object for listing sessions.

Returns
TypeDescription
NodeJS.ReadableStream

{ReadableStream} A readable stream that emits Session instances.

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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 only Snapshot transaction.

Wrapper around .

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

**NOTE:** Since the returned Snapshot transaction is not a single-use transaction, it is invalid to set the minReadTimestamp and maxStaleness 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
options TimestampBounds

Timestamp bounds.

Returns
TypeDescription
Promise<[Snapshot]>

{Promise

Examples

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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) {
  const transaction = data[0];
});

Read-only transaction:


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

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

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

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

  // Gets a transaction object that captures the database state
  // at a specific point in time
  database.getSnapshot(async (err, transaction) => {
    if (err) {
      console.error(err);
      return;
    }
    const queryOne = 'SELECT SingerId, AlbumId, AlbumTitle FROM Albums';

    try {
      // Read #1, using SQL
      const [qOneRows] = await transaction.run(queryOne);

      qOneRows.forEach(row => {
        const json = row.toJSON();
        console.log(
          `SingerId: ${json.SingerId}, AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}`
        );
      });

      const queryTwo = {
        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] = await transaction.read('Albums', queryTwo);

      qTwoRows.forEach(row => {
        const json = 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.
      await database.close();
    }
  });

getSnapshot(callback)

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

getSnapshot(options, callback)

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

getState(options)

getState(options?: CallOptions): Promise<EnumKey<typeof databaseAdmin.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
options CallOptions
Returns
TypeDescription
Promise<EnumKey<typeof databaseAdmin.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');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const state = await database.getState();
const isReady = (state === 'READY');

getState(callback)

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

getState(options, callback)

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

getTransaction()

getTransaction(): Promise<[Transaction]>;

Get a read/write ready Transaction 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 underlying Session object. **Failure to do could result in a Session leak.**

Wrapper around .

Returns
TypeDescription
Promise<[Transaction]>

{Promise

Examples

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

database.getTransaction(function(err, transaction) {});

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


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

getTransaction(callback)

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

makePooledRequest_(config)

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

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

Parameter
NameDescription
config RequestConfig

Request config

Returns
TypeDescription
Promise<Session>

makePooledRequest_(config, callback)

makePooledRequest_(config: RequestConfig, callback: PoolRequestCallback): void;
Parameters
NameDescription
config RequestConfig
callback PoolRequestCallback
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
config RequestConfig

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
backupPath string

The path of the backup to restore.

Returns
TypeDescription
Promise<RestoreDatabaseResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const backupName = 'projects/my-project/instances/my-instance/backups/my-backup';
const [, restoreOperation] = await database.restore(backupName);
// Wait for restore to complete
await restoreOperation.promise();

//-
// Restore database with a different encryption key to the one used by the
// backup.
//-
const [, restoreWithKeyOperation] = await database.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 complete
await restoreWithKeyOperation.promise();

restore(backupPath, options)

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

restore(backupPath, callback)

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

restore(backupPath, options, callback)

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

run(query)

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

Execute a SQL statement on this database.

Wrapper around .

Parameter
NameDescription
query string | ExecuteSqlRequest

A SQL query or object.

Returns
TypeDescription
Promise<RunResponse>

{Promise

Examples

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const query = 'SELECT * FROM Singers';

database.run(query, function(err, rows) {
  if (err) {
    // Error handling omitted.
  }

  const firstRow = 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.
  }

  const firstRow = 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.
  }

  const firstRow = 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.
//-
const query = {
  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.
//-
const query = {
  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) {
  const rows = data[0];
});

Full example:


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

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

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

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

  const query = {
    sql: 'SELECT SingerId, AlbumId, AlbumTitle FROM Albums',
  };

  // Queries rows from the Albums table
  try {
    const [rows] = await database.run(query);

    rows.forEach(row => {
      const json = 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.
    await database.close();
  }

Querying data with an index:


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

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

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

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

  const query = {
    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=""> {
      const json = row.toJSON();
      const marketingBudget = json.MarketingBudget
        ? json.MarketingBudget
        : null; // This value is nullable
      console.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
query string | ExecuteSqlRequest
options TimestampBounds
Returns
TypeDescription
Promise<RunResponse>

run(query, callback)

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

run(query, options, callback)

run(query: string | ExecuteSqlRequest, options: TimestampBounds, callback: RunCallback): void;
Parameters
NameDescription
query string | ExecuteSqlRequest
options TimestampBounds
callback RunCallback
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
query string | ExecuteSqlRequest

A DML statement or object.

Returns
TypeDescription
Promise<[number]>

{Promise

runPartitionedUpdate(query, callback)

runPartitionedUpdate(query: string | ExecuteSqlRequest, callback?: RunUpdateCallback): void;
Parameters
NameDescription
query string | ExecuteSqlRequest
callback RunUpdateCallback
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
query string | ExecuteSqlRequest

A SQL query or object.

options TimestampBounds

Snapshot timestamp bounds.

Returns
TypeDescription
PartialResultStream

{PartialResultStream} A readable stream that emits rows.

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const query = '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.
//-
const query = {
  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.
//-
const query = {
  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 a Transaction 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 the runFn 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 underlying Session object. **Failure to do could result in a Session leak.**

For a more complete listing of functionality available to a Transaction, see the Transaction 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
runFn RunTransactionCallback
Returns
TypeDescription
void
Examples

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = 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 library
  const {Spanner} = require('@google-cloud/spanner');

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

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

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

  const transferAmount = 200000;

  database.runTransaction(async (err, transaction) => {
    if (err) {
      console.error(err);
      return;
    }
    let firstBudget, secondBudget;
    const queryOne = {
      columns: ['MarketingBudget'],
      keys: [[2, 2]], // SingerId: 2, AlbumId: 2
    };

    const queryTwo = {
      columns: ['MarketingBudget'],
      keys: [[1, 1]], // SingerId: 1, AlbumId: 1
    };

    Promise.all([
      // Reads the second album's budget
      transaction.read('Albums', queryOne).then(results => {
        // Gets second album's budget
        const rows = 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 enough
        if (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's budget
        const rows = 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 albums
        firstBudget += 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 database
        return transaction.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 finished
        return database.close();
      });
  });

runTransaction(options, runFn)

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

runTransactionAsync(runFn)

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

runTransactionAsync(options, runFn)

runTransactionAsync<T = {}>(options: RunTransactionOptions, runFn: AsyncRunTransactionCallback<T>): Promise<T>;
Parameters
NameDescription
options RunTransactionOptions
runFn AsyncRunTransactionCallback<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
name string

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

var session = 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
policy SetIamPolicyRequest

requestedPolicyVersion and gax options(configuration options) See https://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');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const binding = {
    role: 'roles/spanner.fineGrainedAccessUser',
    members: ['user:asthamohta@google.com'],
    condition: {
        title: 'new condition',
        expression: 'resource.name.endsWith("/databaseRoles/parent")',
    },
};
const policy = {
    bindings: [newBinding],
    version: 3,
};
const policy = await database.setIamPolicy({policy: policy});

setIamPolicy(policy, options)

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

setIamPolicy(policy, callback)

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

setIamPolicy(policy, options, callback)

setIamPolicy(policy: SetIamPolicyRequest, options: CallOptions, callback: SetIamPolicyCallback): void;
Parameters
NameDescription
policy SetIamPolicyRequest
options CallOptions
callback SetIamPolicyCallback
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
metadata IDatabase

The metadata you wish to set.

gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<SetDatabaseMetadataResponse>

{Promise

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const metadata = {
  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) {
  const operation = data[0];
  const apiResponse = data[1];
});

setMetadata(metadata, callback)

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

setMetadata(metadata, gaxOptions, callback)

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

table(name)

table(name: string): Table;
Parameter
NameDescription
name string
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
statements Schema

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).

gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<UpdateSchemaResponse>

{Promise

Examples

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const statements = [
  '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) {
    const operation = data[0];
    return operation.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 library
  const {Spanner} = require('@google-cloud/spanner');

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

  const databaseAdminClient = spanner.getDatabaseAdminClient();

  // Creates a new index in the database
  try {
    const [operation] = await databaseAdminClient.updateDatabaseDdl({
      database: databaseAdminClient.databasePath(
        projectId,
        instanceId,
        databaseId
      ),
      statements: ['ALTER TABLE Albums ADD COLUMN MarketingBudget INT64'],
    });

    console.log('Waiting for operation to complete...');
    await operation.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 library
  const {Spanner} = require('@google-cloud/spanner');

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

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

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

  const request = ['CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)'];

  // Creates a new index in the database
  try {
    const [operation] = await database.updateSchema(request);

    console.log('Waiting for operation to complete...');
    await operation.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 library
  const {Spanner} = require('@google-cloud/spanner');

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

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

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

  const request = [
    'CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)',
  ];

  // Creates a new index in the database
  try {
    const [operation] = await database.updateSchema(request);

    console.log('Waiting for operation to complete...');
    await operation.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
statements Schema
callback UpdateSchemaCallback
Returns
TypeDescription
void

updateSchema(statements, gaxOptions, callback)

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