Class Instance (7.3.0)

The Instance class represents a [Cloud Spanner instance](https://cloud.google.com/spanner/docs/instances).

Create an Instance object to interact with a Cloud Spanner instance.

Inheritance

common.GrpcServiceObject > Instance

Package

@google-cloud/spanner

Example


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

Constructors

(constructor)(spanner, name)

constructor(spanner: Spanner, name: string);

Constructs a new instance of the Instance class

Parameters
NameDescription
spanner Spanner
name string

Properties

databases_

databases_: Map<string, Database>;

formattedName_

formattedName_: string;

metadata

metadata?: IInstance;

request

request: InstanceRequest;

requestStream

requestStream: (config: RequestConfig) => Duplex;

resourceHeader_

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

Methods

backup(backupId)

backup(backupId: string): Backup;

Get a reference to a Backup object.

Parameter
NameDescription
backupId string

The name of the backup. {Backup} A Backup object.

Returns
TypeDescription
Backup
Example

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

copyBackup(sourceBackupId, backupId, options, callback)

copyBackup(sourceBackupId: string, backupId: string, options: CopyBackupOptions, callback?: CopyBackupCallback): Promise<CopyBackupResponse> | void;

CopyBackupCallback

Parameters
NameDescription
sourceBackupId string

Full path of the source backup to be copied.

backupId string

The name of the backup.

options CopyBackupOptions
callback CopyBackupCallback
Returns
TypeDescription
Promise<CopyBackupResponse> | void
Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const backup = instance.copyBackup('my-source-backup','my-backup',{
  expireTime: expireTime,
  encryptionConfig: {
    encryptionType: 'CUSTOMER_MANAGED_ENCRYPTION',
    kmsKeyName: 'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key',
  },);

createDatabase(name, options)

createDatabase(name: string, options?: CreateDatabaseOptions): Promise<CreateDatabaseResponse>;

Create a database in this instance.

Wrapper around .

Parameters
NameDescription
name string

The name of the database to create.

options CreateDatabaseOptions

Configuration object.

Returns
TypeDescription
Promise<CreateDatabaseResponse>

{Promise

Examples

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

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

function callback(err, database, operation, apiResponse) {
  if (err) {
    // Error handling omitted.
  }

  operation
    .on('error', function(err) {})
    .on('complete', function() {
      // Database created successfully.
    });
}

instance.createDatabase('new-database-name', callback);

//-
// Set the schema for the database.
//-
instance.createDatabase('new-database-name', {
  schema:
    'CREATE TABLE Singers (' +
    '  SingerId STRING(1024) NOT NULL,' +
    '  Name STRING(1024),' +
    ') PRIMARY KEY(SingerId)'
}, callback);
//-
// If the callback is omitted, we'll return a Promise.
//-
instance.createDatabase('new-database-name')
  .then(function(data) {
    const database = data[0];
    const operation = data[1];
    return operation.promise();
  })
  .then(function() {
    // Database created successfully.
  });

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
  const instance = spanner.instance(instanceId);

  // Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so they
  // must be converted to strings before being inserted as INT64s
  const request = {
    schema: [
      `CREATE TABLE Singers (
        SingerId    INT64 NOT NULL,
        FirstName   STRING(1024),
        LastName    STRING(1024),
        SingerInfo  BYTES(MAX),
        FullName    STRING(2048) AS (ARRAY_TO_STRING([FirstName, LastName], " ")) STORED,
      ) PRIMARY KEY (SingerId)`,
      `CREATE TABLE Albums (
        SingerId    INT64 NOT NULL,
        AlbumId     INT64 NOT NULL,
        AlbumTitle  STRING(MAX)
      ) PRIMARY KEY (SingerId, AlbumId),
      INTERLEAVE IN PARENT Singers ON DELETE CASCADE`,
    ],
  };

  // Creates a database
  const [database, operation] = await instance.createDatabase(
    databaseId,
    request
  );

  console.log(`Waiting for operation on ${database.id} to complete...`);
  await operation.promise();

  console.log(`Created database ${databaseId} on instance ${instanceId}.`);

createDatabase(name, callback)

createDatabase(name: string, callback: CreateDatabaseCallback): void;
Parameters
NameDescription
name string
callback CreateDatabaseCallback
Returns
TypeDescription
void

createDatabase(name, options, callback)

createDatabase(name: string, options: CreateDatabaseOptions, callback: CreateDatabaseCallback): void;
Parameters
NameDescription
name string
options CreateDatabaseOptions
callback CreateDatabaseCallback
Returns
TypeDescription
void

database(name, poolOptions, queryOptions)

database(name: string, poolOptions?: SessionPoolOptions | SessionPoolConstructor, queryOptions?: spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions): Database;

Get a reference to a Database object.

Parameters
NameDescription
name string

The name of the instance.

poolOptions SessionPoolOptions | SessionPoolConstructor

Session pool configuration options.

queryOptions IQueryOptions

Default query options to use with the database. These options will be overridden by any query options set in environment variables or that are specified on a per-query basis. {Database} A Database object.

Returns
TypeDescription
Database
Example

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

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

delete(gaxOptions)

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

Delete the instance.

Wrapper around .

Parameter
NameDescription
gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<DeleteInstanceResponse>

{Promise

Example

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

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

instance.delete(function(err, apiResponse) {
  if (err) {
    // Error handling omitted.
  }

  // Instance was deleted successfully.
});

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

delete(callback)

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

delete(gaxOptions, callback)

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

exists(gaxOptions)

exists(gaxOptions?: CallOptions): Promise<ExistsInstanceResponse>;

Check if an instance exists.

Instance#exists

Parameter
NameDescription
gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<ExistsInstanceResponse>

{Promise

Example

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

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

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

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

exists(callback)

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

exists(gaxOptions, callback)

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

formatName_(projectId, name)

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

Format the instance name to include the project ID.

Parameters
NameDescription
projectId string

The project ID.

name string

The instance name.

Returns
TypeDescription
string

{string}

Example

Instance.formatName_('grape-spaceship-123', 'my-instance');
// 'projects/grape-spaceship-123/instances/my-instance'

get(options)

get(options?: GetInstanceConfig): Promise<GetInstanceResponse>;

Get an instance 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 GetInstanceConfig

Configuration object.

Returns
TypeDescription
Promise<GetInstanceResponse>

{Promise

Example

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

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

instance.get(function(err, instance, apiResponse) {
  // `instance.metadata` has been populated.
});

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

get(callback)

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

get(options, callback)

get(options: GetInstanceConfig, callback: GetInstanceCallback): void;
Parameters
NameDescription
options GetInstanceConfig
callback GetInstanceCallback
Returns
TypeDescription
void

getBackupOperations(options)

getBackupOperations(options?: GetBackupOperationsOptions): Promise<GetBackupOperationsResponse>;

GetBackupOperationsCallback

Parameter
NameDescription
options GetBackupOperationsOptions
Returns
TypeDescription
Promise<GetBackupOperationsResponse>

getBackupOperations(callback)

getBackupOperations(callback: GetBackupOperationsCallback): void;
Parameter
NameDescription
callback GetBackupOperationsCallback
Returns
TypeDescription
void

getBackupOperations(options, callback)

getBackupOperations(options: GetBackupOperationsOptions, callback: GetBackupOperationsCallback): void;
Parameters
NameDescription
options GetBackupOperationsOptions
callback GetBackupOperationsCallback
Returns
TypeDescription
void

getBackups(options)

getBackups(options?: GetBackupsOptions): Promise<GetBackupsResponse>;

List backups on the instance.

Both completed and in-progress backups are listed if no filter is supplied.

Parameter
NameDescription
options GetBackupsOptions

The query object for listing backups.

Returns
TypeDescription
Promise<GetBackupsResponse>

{Promise

Example

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

//-
// To manually handle pagination, set autoPaginate:false in gaxOptions.
//-
let pageToken = undefined;
do {
  const [backups, , response] = await instance.getBackups({
    pageSize: 3,
    pageToken,
    gaxOptions: {autoPaginate: false},
  });
  backups.forEach(backup => {
    // Do something with backup
  });
  pageToken = response.nextPageToken;
} while (pageToken);

getBackups(callback)

getBackups(callback: GetBackupsCallback): void;
Parameter
NameDescription
callback GetBackupsCallback
Returns
TypeDescription
void

getBackups(options, callback)

getBackups(options: GetBackupsOptions, callback: GetBackupsCallback): void;
Parameters
NameDescription
options GetBackupsOptions
callback GetBackupsCallback
Returns
TypeDescription
void

getBackupsStream(options)

getBackupsStream(options?: GetBackupsOptions): NodeJS.ReadableStream;

Get a list of backups as a readable object stream.

Wrapper around .

Parameter
NameDescription
options GetBackupsOptions

Query object for listing backups.

Returns
TypeDescription
NodeJS.ReadableStream

{ReadableStream} A readable stream that emits Backup instances.

Example

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

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

instance.getBackupsStream()
  .on('error', console.error)
  .on('data', function(database) {
    // `backups` is a `Backup` object.
  })
  .on('end', function() {
    // All backups retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
instance.getBackupsStream()
  .on('data', function(database) {
    this.end();
  });

getDatabaseOperations(options)

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

GetDatabaseOperationsCallback

Parameter
NameDescription
options GetDatabaseOperationsOptions
Returns
TypeDescription
Promise<GetDatabaseOperationsResponse>

getDatabaseOperations(callback)

getDatabaseOperations(callback: GetDatabaseOperationsCallback): void;
Parameter
NameDescription
callback GetDatabaseOperationsCallback
Returns
TypeDescription
void

getDatabaseOperations(options, callback)

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

getDatabases(options)

getDatabases(options?: GetDatabasesOptions): Promise<GetDatabasesResponse>;

Get a list of databases.

Wrapper around .

Parameter
NameDescription
options GetDatabasesOptions

Query object for listing databases.

Returns
TypeDescription
Promise<GetDatabasesResponse>

{Promise

Example

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

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

instance.getDatabases(function(err, databases) {
  // `databases` is an array of `Database` objects.
});

//-
// To control how many API requests are made and page through the results
// manually, set `autoPaginate` to `false`.
//-
function callback(err, databases, nextQuery, apiResponse) {
  if (nextQuery) {
    // More results exist.
    instance.getDatabases(nextQuery, callback);
  }
}

instance.getDatabases({
  gaxOptions: {autoPaginate: false}
}, callback);

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

getDatabases(callback)

getDatabases(callback: GetDatabasesCallback): void;
Parameter
NameDescription
callback GetDatabasesCallback
Returns
TypeDescription
void

getDatabases(options, callback)

getDatabases(options: GetDatabasesOptions, callback: GetDatabasesCallback): void;
Parameters
NameDescription
options GetDatabasesOptions
callback GetDatabasesCallback
Returns
TypeDescription
void

getDatabasesStream(options)

getDatabasesStream(options?: GetDatabasesOptions): NodeJS.ReadableStream;

Get a list of databases as a readable object stream.

Wrapper around .

Parameter
NameDescription
options GetDatabasesOptions

Query object for listing databases.

Returns
TypeDescription
NodeJS.ReadableStream

{ReadableStream} A readable stream that emits Database instances.

Example

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

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

instance.getDatabasesStream()
  .on('error', console.error)
  .on('data', function(database) {
    // `database` is a `Database` object.
  })
  .on('end', function() {
    // All databases retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
instance.getDatabasesStream()
  .on('data', function(database) {
    this.end();
  });

getMetadata(options)

getMetadata(options?: GetInstanceMetadataOptions): Promise<GetInstanceMetadataResponse>;

Get the instance's metadata.

Wrapper around .

Parameter
NameDescription
options GetInstanceMetadataOptions

Configuration object

Returns
TypeDescription
Promise<GetInstanceMetadataResponse>

{Promise

Example

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

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

instance.getMetadata(function(err, metadata, apiResponse) {});

//-
// Request only `displayName`.
//-
instance.getMetadata({fieldNames: 'displayName'}, (err, metadata, apiResponse) => {
  // metadata will only contain value for `displayName`
  const displayName = metadata['displayName'];
})

//-
// Request multiple specific field names.
//-
instance.getMetadata({fieldNames: ['displayName', 'nodeCount']}, (err, metadata, apiResponse) => {
  // metadata will only contain value for `displayName` and 'nodeCount'
  const displayName = metadata['displayName'];
  const nodeCount = metadata['nodeCount'];
});

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

getMetadata(callback)

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

getMetadata(options, callback)

getMetadata(options: GetInstanceMetadataOptions, callback: GetInstanceMetadataCallback): void;
Parameters
NameDescription
options GetInstanceMetadataOptions
callback GetInstanceMetadataCallback
Returns
TypeDescription
void

setMetadata(metadata, gaxOptions)

setMetadata(metadata: IInstance, gaxOptions?: CallOptions): Promise<SetInstanceMetadataResponse>;

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

Wrapper around .

Parameters
NameDescription
metadata IInstance

The metadata you wish to set.

gaxOptions CallOptions

Request configuration options, See CallOptions for more details.

Returns
TypeDescription
Promise<SetInstanceMetadataResponse>

{Promise

Example

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

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

const metadata = {
  displayName: 'My Instance'
};

instance.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.
//-
instance.setMetadata(metadata).then(function(data) {
  const operation = data[0];
  const apiResponse = data[1];
});

setMetadata(metadata, callback)

setMetadata(metadata: IInstance, callback: SetInstanceMetadataCallback): void;
Parameters
NameDescription
metadata IInstance
callback SetInstanceMetadataCallback
Returns
TypeDescription
void

setMetadata(metadata, gaxOptions, callback)

setMetadata(metadata: IInstance, gaxOptions: CallOptions, callback: SetInstanceMetadataCallback): void;
Parameters
NameDescription
metadata IInstance
gaxOptions CallOptions
callback SetInstanceMetadataCallback
Returns
TypeDescription
void