Class Spanner (7.5.0)

[Cloud Spanner](https://cloud.google.com/spanner) is a highly scalable, transactional, managed, NewSQL database service. Cloud Spanner solves the need for a horizontally-scaling database with consistent global transaction and SQL semantics. With Cloud Spanner you don't need to choose between consistency and horizontal scaling — you get both.

Inheritance

GrpcService > Spanner

Package

@google-cloud/spanner

Examples

Install the client library with a href="https://www.npmjs.com/"npm:


npm install --save @google-cloud/spanner

Create a client that uses a href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application"Application Default Credentials (ADC):


const client = new Spanner();

Create a client with a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually"explicit credentials:


const client = new Spanner({ projectId:
'your-project-id', keyFilename: '/path/to/keyfile.json'
});

Full quickstart example:


  // 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));

Constructors

(constructor)(options)

constructor(options?: SpannerOptions);

Constructs a new instance of the Spanner class

Parameter
NameDescription
options SpannerOptions

Properties

auth

auth: GoogleAuth;

clients_

clients_: Map<string, {}>;

COMMIT_TIMESTAMP

static COMMIT_TIMESTAMP: 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.

{string}

directedReadOptions

directedReadOptions: google.spanner.v1.IDirectedReadOptions | null;

GOOGLE_STANDARD_SQL

static GOOGLE_STANDARD_SQL: google.spanner.admin.database.v1.DatabaseDialect;

instanceConfigs_

instanceConfigs_: Map<string, InstanceConfig>;

instances_

instances_: Map<string, Instance>;

options

options: GoogleAuthOptions;

POSTGRESQL

static POSTGRESQL: google.spanner.admin.database.v1.DatabaseDialect;

projectFormattedName_

projectFormattedName_: string;

projectIdReplaced_

projectIdReplaced_: boolean;

resourceHeader_

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

routeToLeaderEnabled

routeToLeaderEnabled: boolean;

Methods

close()

close(): void;

Closes this Spanner client and cleans up all resources used by it.

Returns
TypeDescription
void

createInstance(name, config)

createInstance(name: string, config: CreateInstanceRequest): Promise<CreateInstanceResponse>;

Create an instance.

Wrapper around .

Parameters
NameDescription
name string

The name of the instance to be created.

config CreateInstanceRequest

Configuration object.

Returns
TypeDescription
Promise<CreateInstanceResponse>

{Promise

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

createInstance(name, config, callback)

createInstance(name: string, config: CreateInstanceRequest, callback: CreateInstanceCallback): void;
Parameters
NameDescription
name string
config CreateInstanceRequest
callback CreateInstanceCallback
Returns
TypeDescription
void

createInstanceConfig(name, config)

createInstanceConfig(name: string, config: CreateInstanceConfigRequest): Promise<CreateInstanceConfigResponse>;

Create an instance config.

Wrapper around .

Parameters
NameDescription
name string

The name of the instance config to be created.

config CreateInstanceConfigRequest

Configuration object.

Returns
TypeDescription
Promise<CreateInstanceConfigResponse>

{Promise

Example

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

const [baseInstanceConfig] =
    await spanner.getInstanceConfig(baseInstanceConfigId);
const config = {
  baseConfig: baseInstanceConfig.name,
  replicas: baseInstanceConfig.replicas.concat(baseInstanceConfig.optionalReplicas[0])
};

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

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

spanner.createInstanceConfig('custom-new-instance-config', config, callback);

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

createInstanceConfig(name, config, callback)

createInstanceConfig(name: string, config: CreateInstanceConfigRequest, callback: CreateInstanceConfigCallback): void;
Parameters
NameDescription
name string
config CreateInstanceConfigRequest
callback CreateInstanceConfigCallback
Returns
TypeDescription
void

date(dateString)

static date(dateString?: string): any;
Parameter
NameDescription
dateString string
Returns
TypeDescription
any

date(year, month, date)

static date(year: number, month: number, date: number): any;
Parameters
NameDescription
year number
month number
date number
Returns
TypeDescription
any

float(value)

static float(value: any): Float;

Helper function to get a Cloud Spanner Float64 object.

Parameter
NameDescription
value any

The float as a number or string.

Returns
TypeDescription
Float

{Float}

Example

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

getDatabaseAdminClient()

getDatabaseAdminClient(): v1.DatabaseAdminClient;

Gets the DatabaseAdminClient object. The returned DatabaseAdminClient object is a managed, shared instance and should not be manually closed.

Returns
TypeDescription
DatabaseAdminClient

{v1.DatabaseAdminClient} The DatabaseAdminClient object.

Example

const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner({
   projectId: projectId,
});
const databaseAdminClient = spanner.getDatabaseAdminClient();

getInstanceAdminClient()

getInstanceAdminClient(): v1.InstanceAdminClient;

Gets the InstanceAdminClient object. The returned InstanceAdminClient object is a shared, managed instance and should not be manually closed.

Returns
TypeDescription
InstanceAdminClient

{v1.InstanceAdminClient} The InstanceAdminClient object

Example

``` const {Spanner} = require('@google-cloud/spanner'); const spanner = new Spanner({ projectId: projectId, }); const instanceAdminClient = spanner.getInstanceAdminClient(); ```

getInstanceConfig(name)

getInstanceConfig(name: string): Promise<GetInstanceConfigResponse>;

Get a specific instance config.

Wrapper around .

Parameter
NameDescription
name string

The name of the instance config to get.

Returns
TypeDescription
Promise<GetInstanceConfigResponse>

{Promise

Example

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

spanner.getInstanceConfig('nam6', function(err, instanceConfig) {
  // `instanceConfig` is an instance configuration descriptor.
});

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

getInstanceConfig(name, options)

getInstanceConfig(name: string, options: GetInstanceConfigOptions): Promise<GetInstanceConfigResponse>;
Parameters
NameDescription
name string
options GetInstanceConfigOptions
Returns
TypeDescription
Promise<GetInstanceConfigResponse>

getInstanceConfig(name, callback)

getInstanceConfig(name: string, callback: GetInstanceConfigCallback): void;
Parameters
NameDescription
name string
callback GetInstanceConfigCallback
Returns
TypeDescription
void

getInstanceConfig(name, options, callback)

getInstanceConfig(name: string, options: GetInstanceConfigOptions, callback: GetInstanceConfigCallback): void;
Parameters
NameDescription
name string
options GetInstanceConfigOptions
callback GetInstanceConfigCallback
Returns
TypeDescription
void

getInstanceConfigOperations(options)

getInstanceConfigOperations(options?: GetInstanceConfigOperationsOptions): Promise<GetInstanceConfigOperationsResponse>;

List pending and completed instance config operations.

Parameter
NameDescription
options GetInstanceConfigOperationsOptions

The query object for listing InstanceConfig operations.

Returns
TypeDescription
Promise<GetInstanceConfigOperationsResponse>

{Promise

Example

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

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

getInstanceConfigOperations(callback)

getInstanceConfigOperations(callback: GetInstanceConfigOperationsCallback): void;
Parameter
NameDescription
callback GetInstanceConfigOperationsCallback
Returns
TypeDescription
void

getInstanceConfigOperations(options, callback)

getInstanceConfigOperations(options: GetInstanceConfigOperationsOptions, callback: GetInstanceConfigOperationsCallback): void;
Parameters
NameDescription
options GetInstanceConfigOperationsOptions
callback GetInstanceConfigOperationsCallback
Returns
TypeDescription
void

getInstanceConfigs(query)

getInstanceConfigs(query?: GetInstanceConfigsOptions): Promise<GetInstanceConfigsResponse>;

Get a list of instance configs.

Wrapper around .

Parameter
NameDescription
query GetInstanceConfigsOptions
Returns
TypeDescription
Promise<GetInstanceConfigsResponse>

{Promise

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

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

getInstanceConfigs(callback)

getInstanceConfigs(callback: GetInstanceConfigsCallback): void;
Parameter
NameDescription
callback GetInstanceConfigsCallback
Returns
TypeDescription
void

getInstanceConfigs(query, callback)

getInstanceConfigs(query: GetInstanceConfigsOptions, callback: GetInstanceConfigsCallback): void;
Parameters
NameDescription
query GetInstanceConfigsOptions
callback GetInstanceConfigsCallback
Returns
TypeDescription
void

getInstanceConfigsStream(options)

getInstanceConfigsStream(options?: GetInstanceConfigsOptions): NodeJS.ReadableStream;

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

Wrapper around .

Parameter
NameDescription
options GetInstanceConfigsOptions

Query object for listing instance configs.

Returns
TypeDescription
NodeJS.ReadableStream

{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(options)

getInstances(options?: GetInstancesOptions): Promise<GetInstancesResponse>;

Get a list of instances.

Wrapper around .

Parameter
NameDescription
options GetInstancesOptions

Query object for listing instances.

Returns
TypeDescription
Promise<GetInstancesResponse>

{Promise

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

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

getInstances(callback)

getInstances(callback: GetInstancesCallback): void;
Parameter
NameDescription
callback GetInstancesCallback
Returns
TypeDescription
void

getInstances(query, callback)

getInstances(query: GetInstancesOptions, callback: GetInstancesCallback): void;
Parameters
NameDescription
query GetInstancesOptions
callback GetInstancesCallback
Returns
TypeDescription
void

getInstancesStream(options)

getInstancesStream(options?: GetInstancesOptions): NodeJS.ReadableStream;

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

Wrapper around .

Parameter
NameDescription
options GetInstancesOptions

Query object for listing instances.

Returns
TypeDescription
NodeJS.ReadableStream

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

getSpannerEmulatorHost()

static getSpannerEmulatorHost(): {
        endpoint: string;
        port?: number;
    } | undefined;

Gets the configured Spanner emulator host from an environment variable.

Returns
TypeDescription
{ endpoint: string; port?: number; } | undefined

instance(name)

instance(name: string): Instance;

Get a reference to an Instance object.

Parameter
NameDescription
name string

The name of the instance.

Returns
TypeDescription
Instance

{Instance} An Instance object.

Example

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

instanceConfig(name)

instanceConfig(name: string): InstanceConfig;

Get a reference to an InstanceConfig object.

Parameter
NameDescription
name string

The name of the instance config.

Returns
TypeDescription
InstanceConfig

{InstanceConfig} An InstanceConfig object.

Example

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

int(value)

static int(value: any): Int;

Helper function to get a Cloud Spanner Int64 object.

Parameter
NameDescription
value any

The int as a number or string.

Returns
TypeDescription
Int

{Int}

Example

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

numeric(value)

static numeric(value: any): Numeric;

Helper function to get a Cloud Spanner Numeric object.

Parameter
NameDescription
value any

The numeric value as a string.

Returns
TypeDescription
Numeric

{Numeric}

Example

const {Spanner} = require('@google-cloud/spanner');
const numeric = Spanner.numeric("3.141592653");

pgJsonb(value)

static pgJsonb(value: any): PGJsonb;

Helper function to get a Cloud Spanner pgJsonb object.

Parameter
NameDescription
value any

The pgJsonb value as a string or object.

Returns
TypeDescription
PGJsonb

{PGJsonb}

Example

const {Spanner} = require('@google-cloud/spanner');
const pgJsonb1 = Spanner.pgJsonb({rating: 6});
const pgJsonb2 = Spanner.pgJsonb(`[
        {
          "name": null,
          "open": true
        }]`)

pgNumeric(value)

static pgNumeric(value: any): PGNumeric;

Helper function to get a Cloud Spanner pgNumeric object.

Parameter
NameDescription
value any

The pgNumeric value as a string.

Returns
TypeDescription
PGNumeric

{PGNumeric}

Example

const {Spanner} = require('@google-cloud/spanner');
const pgNumeric = Spanner.pgNumeric("3.141592653");

prepareGapicRequest_(config, callback)

prepareGapicRequest_(config: any, callback: any): void;

Prepare a gapic request. This will cache the GAX client and replace {{projectId}} placeholders, if necessary.

Parameters
NameDescription
config any

Request config

callback any

Callback function

Returns
TypeDescription
void

request(config, callback)

request(config: any, callback?: any): any;

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

Parameters
NameDescription
config any

Configuration object.

callback any

Callback function.

Returns
TypeDescription
any

{Promise}

requestStream(config)

requestStream(config: any): any;

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

Parameter
NameDescription
config any

Configuration object.

Returns
TypeDescription
any

{Stream}

struct(value)

static struct(value?: any): Struct;

Helper function to get a Cloud Spanner Struct object.

Parameter
NameDescription
value any

The struct as a JSON object.

Returns
TypeDescription
Struct

{Struct}

Example

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

timestamp(value)

static timestamp(value?: string | number | p.ITimestamp | PreciseDate): 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
NameDescription
value string | number | common.ITimestamp | PreciseDate
Returns
TypeDescription
PreciseDate

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