Instance

Instance

The Instance class represents a Cloud Spanner instance.

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

Constructor

new Instance(spanner, name)

Parameters:
Name Type Description
spanner Spanner

Spanner instance.

name string

Name of the instance.

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

Members

id :string

Source:

Methods

create(config, callbackopt) → {Promise.<CreateInstanceResponse>}

Create an instance.

Wrapper around v1.InstanceAdminClient#createInstance.

Parameters:
Name Type Attributes Description
config CreateInstanceRequest

Configuration object.

callback CreateInstanceCallback <optional>

Callback function.

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

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

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

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

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

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

createDatabase(name, optionsopt, callbackopt) → {Promise.<CreateDatabaseResponse>}

Create a database in this instance.

Wrapper around v1.DatabaseAdminClient#createDatabase.

Parameters:
Name Type Attributes Description
name name

The name of the database to create.

options CreateDatabaseRequest <optional>

Configuration object.

callback CreateDatabaseCallback <optional>

Callback function.

Source:
See:
Throws:

If a name is not provided.

Type
Error
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)
      ) 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}.`);

database(name, poolOptionsopt) → {Database}

Get a reference to a Database object.

Parameters:
Name Type Attributes Description
name string

The name of the instance.

poolOptions SessionPoolOptions | SessionPoolCtor <optional>

Session pool configuration options.

Source:
Throws:

If a name is not provided.

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

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

delete(callbackopt) → {Promise.<DeleteInstanceResponse>}

Delete the instance.

Wrapper around v1.InstanceAdminClient#deleteInstance.

Parameters:
Name Type Attributes Description
callback DeleteInstanceCallback <optional>

Callback function.

Source:
See:
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];
});

exists(callbackopt) → {Promise.<InstanceExistsResponse>}

Check if an instance exists.

Parameters:
Name Type Attributes Description
callback InstanceExistsCallback <optional>

Callback function.

Source:
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];
});

get(optionsopt, callbackopt) → {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.

Parameters:
Name Type Attributes Description
options options <optional>

Configuration object.

Properties
Name Type Attributes Default Description
autoCreate boolean <optional>
false

Automatically create the object if it does not exist.

fieldNames string | Array.<string> <optional>

A list of Instance field names to be requested. Eligible values are: name, displayName, endpointUris, labels, config, nodeCount, state.

callback GetInstanceCallback <optional>

Callback function.

Source:
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];
});

getDatabases(queryopt, callbackopt) → {Promise.<GetDatabasesResponse>}

Get a list of databases.

Wrapper around v1.DatabaseAdminClient#listDatabases.

Parameters:
Name Type Attributes Description
query GetDatabasesRequest <optional>

Query object for listing databases.

callback GetDatabasesCallback <optional>

Callback function.

Source:
See:
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({
  autoPaginate: false
}, callback);

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

getMetadata(optionsopt, callbackopt) → {Promise.<GetInstanceMetadataResponse>}

Get the instance's metadata.

Wrapper around v1.InstanceAdminClient#getInstance.

Parameters:
Name Type Attributes Description
options GetInstanceMetadataOptions <optional>

Configuration object

Properties
Name Type Attributes Description
fieldNames string | Array.<string> <optional>

A list of Instance field names to be requested. Eligible values are: name, displayName, endpointUris, labels, config, nodeCount, state.

callback GetInstanceMetadataCallback <optional>

Callback function.

Source:
See:
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];
});

setMetadata(metadata, callbackopt) → {Promise.<LongRunningOperationResponse>}

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

Wrapper around v1.InstanceAdminClient#updateInstance.

Parameters:
Name Type Attributes Description
metadata object

The metadata you wish to set.

callback SetInstanceMetadataCallback <optional>

Callback function.

Source:
See:
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];
});