Constructor

Spanner

new Spanner(options)

Parameter

options

Optional

ClientConfig

Configuration options.

See also

Cloud Spanner Documentation

Cloud Spanner Concepts

Examples

<caption>Install the client library with <a
href="https://www.npmjs.com/">npm</a>:</caption> npm install --save
<caption>Create a client that uses <a
href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application
Default Credentials (ADC)</a>:</caption> const client = new Spanner();
<caption>Create a client with <a
href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit
credentials</a>:</caption> const client = new Spanner({ projectId:
'your-project-id', keyFilename: '/path/to/keyfile.json'
});

Full quickstart example:

async function quickstart(
  projectId = 'YOUR-PROJECT-ID', // Your Google Cloud Platform project ID
  instanceId = 'my-instance', // Your Cloud Spanner instance ID
  databaseId = 'my-database' // Your Cloud Spanner database ID
) {
  // Imports the Google Cloud client library
  const {Spanner} = require('@google-cloud/spanner');

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

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

  // The query to execute
  const query = {
    sql: 'SELECT 1',
  };

  // Execute a simple SQL statement
  const [rows] = await database.run(query);
  console.log(`Query: ${rows.length} found.`);
  rows.forEach(row => console.log(row));
}

Property

COMMIT_TIMESTAMP

static

string

Placeholder used to auto populate a column with the commit timestamp. This can only be used for timestamp columns that have set the option "(allow_commit_timestamp=true)" in the schema.

Methods

date

static

date(date, month, date) returns SpannerDate

Helper function to get a Cloud Spanner Date object.

DATE types represent a logical calendar date, independent of time zone. DATE values do not represent a specific 24-hour period. Rather, a given DATE value represents a different 24-hour period when interpreted in a different time zone. Because of this, all values passed to Spanner.date will be interpreted as local time.

To represent an absolute point in time, use Spanner.timestamp.

Parameter

date

Optional

(string or number)

String representing the date or number representing the year.

month

Optional

number

Number representing the month.

date

Optional

number

Number representing the date.

Returns

SpannerDate 

Example

const {Spanner} = require('@google-cloud/spanner');
const date = Spanner.date('08-20-1969');

float

static

float(value) returns object

Helper function to get a Cloud Spanner Float64 object.

Parameter

value

(string or number)

The float as a number or string.

Returns

object 

Example

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

int

static

int(value) returns object

Helper function to get a Cloud Spanner Int64 object.

Parameter

value

(string or number)

The int as a number or string.

Returns

object 

Example

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

struct

static

struct(value) returns object

Helper function to get a Cloud Spanner Struct object.

Parameter

value

object

The struct as a JSON object.

Returns

object 

Example

const {Spanner} = require('@google-cloud/spanner');
const struct = Spanner.struct({
  user: 'bob',
  age: 32
});

timestamp

static

timestamp(timestamp) returns external:PreciseDate

Helper function to get a Cloud Spanner Timestamp object.

String timestamps should have a canonical format of YYYY-[M]M-[D]D[( |T)[H]H:[M]M:[S]S[.DDDDDDDDD]]Z

Timestamp values must be expressed in Zulu time and cannot include a UTC offset.

Parameter

timestamp

Optional

(string, number, or google.protobuf.Timestamp)

Either a RFC 3339 timestamp formatted string or google.protobuf.Timestamp object.

See also
https://cloud.google.com/spanner/docs/data-types#timestamp-type
Returns

external:PreciseDate 

Examples

const timestamp = Spanner.timestamp('2019-02-08T10:34:29.481145231Z');

With a `google.protobuf.Timestamp` object

const [seconds, nanos] = process.hrtime();
const timestamp = Spanner.timestamp({seconds, nanos});

With a Date timestamp

const timestamp = Spanner.timestamp(Date.now());

createInstance

createInstance(name, config, callback) returns Promise containing CreateInstanceResponse

Create an instance.

Wrapper around v1.InstanceAdminClient#createInstance.

Parameter

name

string

The name of the instance to be created.

config

CreateInstanceRequest

Configuration object.

callback

Optional

CreateInstanceCallback

Callback function.

See also
v1.InstanceAdminClient#createInstance

CreateInstace API Documentation

Throws

Error 

If a name is not provided.

Error 

If a configuration object is not provided.

Returns

Promise containing CreateInstanceResponse 

Example

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

const config = {
  config: 'regional-us-central1',
  nodes: 1
};

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

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

spanner.createInstance('new-instance-name', config, callback);

//-
// If the callback is omitted, we'll return a Promise.
//-
spanner.createInstance('new-instance-name', config)
  .then(function(data) {
    const instance = data[0];
    const operation = data[1];
    return operation.promise();
  })
  .then(function() {
    // Instance created successfully.
  });

getDatabasesStream

getDatabasesStream(query) returns ReadableStream

Get a list of databases as a readable object stream.

Wrapper around v1.DatabaseAdminClient#listDatabases.

Parameter

query

Optional

GetDatabasesRequest

Query object for listing databases.

See also
v1.DatabaseAdminClient#listDatabases

ListDatabases API Documentation

Returns

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();
  });

getInstanceConfigs

getInstanceConfigs(query, callback) returns Promise containing GetInstanceConfigsResponse

Get a list of instance configs.

Wrapper around v1.InstanceAdminClient#listInstanceConfigs.

Parameter

query

Optional

GetInstanceConfigsRequest

Query object for listing instance configs.

callback

Optional

GetInstanceConfigsCallback

Callback function.

See also
v1.InstanceAdminClient#listInstanceConfigs

ListInstanceConfigs API Documentation

Returns

Promise containing GetInstanceConfigsResponse 

Example

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

spanner.getInstanceConfigs(function(err, instanceConfigs) {
  // `instanceConfigs` is an array of instance configuration descriptors.
});

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

spanner.getInstanceConfigs({
  autoPaginate: false
}, callback);

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

getInstanceConfigsStream

getInstanceConfigsStream(query) returns ReadableStream

Get a list of instance configs as a readable object stream.

Wrapper around v1.InstanceAdminClient#listInstanceConfigsStream.

Parameter

query

Optional

GetInstanceConfigsRequest

Query object for listing instance configs.

See also
v1.InstanceAdminClient#listInstanceConfigsStream

ListInstanceConfigs API Documentation

Returns

ReadableStream 

A readable stream that emits instance configs.

Example

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

spanner.getInstanceConfigsStream()
  .on('error', console.error)
  .on('data', function(instanceConfig) {})
  .on('end', function() {
    // All instances retrieved.
  });

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

getInstances

getInstances(query, callback) returns Promise containing GetInstancesResponse

Get a list of instances.

Wrapper around v1.InstanceAdminClient#listInstances.

Parameter

query

Optional

GetInstancesRequest

Query object for listing instances.

callback

Optional

GetInstancesCallback

Callback function.

See also
v1.InstanceAdminClient#listInstances

ListInstances API Documentation

Returns

Promise containing GetInstancesResponse 

Example

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

spanner.getInstances(function(err, instances) {
  // `instances` is an array of `Instance` objects.
});

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

spanner.getInstances({
  autoPaginate: false
}, callback);

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

getInstancesStream

getInstancesStream(query) returns ReadableStream

Get a list of Instance objects as a readable object stream.

Wrapper around v1.InstanceAdminClient#listInstances.

Parameter

query

Optional

GetInstancesRequest

Query object for listing instances.

See also
v1.InstanceAdminClient#listInstances

ListInstances API Documentation

Returns

ReadableStream 

A readable stream that emits Instance instances.

Example

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

spanner.getInstancesStream()
  .on('error', console.error)
  .on('data', function(instance) {
    // `instance` is an `Instance` object.
  })
  .on('end', function() {
    // All instances retrieved.
  });

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

instance

instance(name) returns Instance

Get a reference to an Instance object.

Parameter

name

string

The name of the instance.

Throws

Error 

If a name is not provided.

Returns

Instance 

An Instance object.

Example

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

operation

operation(name) returns Operation

Get a reference to an Operation object.

Parameter

name

string

The name of the operation.

Throws

Error 

If a name is not provided.

Returns

Operation 

An Operation object.

Example

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

request

request(config, callback) returns Promise

Funnel all API requests through this method to be sure we have a project ID.

Parameter

config

object

Configuration object.

Values in config have the following properties:

Parameter

gaxOpts

object

GAX options.

method

function()

The gax method to call.

reqOpts

object

Request options.

callback

Optional

function()

Callback function.

Returns

Promise 

requestStream

requestStream(config, callback) returns Stream

Funnel all streaming API requests through this method to be sure we have a project ID.

Parameter

config

object

Configuration object.

Values in config have the following properties:

Parameter

gaxOpts

object

GAX options.

method

function()

The gax method to call.

reqOpts

object

Request options.

callback

Optional

function()

Callback function.

Returns

Stream