Constructor

BatchTransaction

new BatchTransaction(options)

Parameter

options

Optional

TimestampBounds

Timestamp Bounds.

Extends
Snapshot

Properties

ended

unknown

Whether or not the transaction has ended. If true, make no further requests, and discard the transaction.

Inherited from
Snapshot#ended

id

unknown

The transaction ID.

Inherited from
Snapshot#id

metadata

unknown

The raw transaction response object. It is populated after Snapshot#begin is called.

Inherited from
Snapshot#metadata

readTimestamp

unknown

Snapshot only The timestamp at which all reads are performed.

Inherited from
Snapshot#readTimestamp

readTimestampProto

unknown

Snapshot only The protobuf version of Snapshot#readTimestamp. This is useful if you require microsecond precision.

Inherited from
Snapshot#readTimestampProto

Methods

begin

begin(callback) returns Promise containing TransactionBeginResponse

Begin a new transaction. Typically, you need not call this unless manually creating transactions via Session objects.

Parameter

callback

Optional

Callback function.

Inherited from
Snapshot#begin
See also

BeginTransaction API Documentation

Returns

Examples

transaction.begin(function(err) {
  if (!err) {
    // transaction began successfully.
  }
});
<caption>If the callback is omitted, the function returns a Promise
</caption>
transaction.begin()
  .then(function(data) {
    const apiResponse = data[0];
  });

close

close(callback) returns Promise containing BasicResponse

Closes all open resources.

When the transaction is no longer needed, you should call this method to free up resources allocated by the Batch client.

Calling this method would render the transaction unusable everywhere. In particular if this transaction object was being used across multiple machines, calling this method on any of the machine would make the transaction unusable on all the machines. This should only be called when the transaction is no longer needed anywhere

Parameter

callback

Optional

BasicCallback

Callback function.

Returns

Promise containing BasicResponse 

Example

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

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

database.createBatchTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.close(function(err, apiResponse) {});
});

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

createQueryPartitions

createQueryPartitions(query, callback) returns Promise containing CreateQueryPartitionsResponse

Creates a set of query partitions that can be used to execute a query operation in parallel. Partitions become invalid when the transaction used to create them is closed.

Parameter

query

(string or object)

A SQL query or ExecuteSqlRequest object.

Values in query have the following properties:

Parameter

gaxOptions

Optional

object

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.

params

Optional

object

A map of parameter name to values.

partitionOptions

Optional

object

A map of partition options.

types

Optional

object

A map of parameter types.

callback

Optional

CreateQueryPartitionsCallback

Callback callback function.

Returns

Promise containing CreateQueryPartitionsResponse 

Examples

// 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 identifier = {};

// 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 transaction = database.batchTransaction(identifier);

const query = 'SELECT * FROM Singers';

const [partitions] = await transaction.createQueryPartitions(query);
console.log(`Successfully created ${partitions.length} query partitions.`);

createReadPartitions

createReadPartitions(options, callback) returns Promise containing CreateReadPartitionsResponse

Creates a set of read partitions that can be used to execute a read operation in parallel. Partitions become invalid when the transaction used to create them is closed.

Parameter

options

ReadRequestOptions

Configuration object, describing what to read from.

callback

Optional

CreateReadPartitionsCallback

Callback function.

Returns

Promise containing CreateReadPartitionsResponse 

createReadStream

createReadStream(table, query) returns ReadableStream

Create a readable object stream to receive rows from the database using key lookups and scans.

Wrapper around v1.SpannerClient#streamingRead.

Parameter

table

The table to read from.

query

Configuration object. See official ReadRequest. API documentation.

Inherited from
Snapshot#createReadStream
See also
v1.SpannerClient#streamingRead

StreamingRead API Documentation

ReadRequest API Documentation

Fires
PartialResultStream#event:response
PartialResultStream#event:stats
Returns

A readable stream that emits rows.

Examples

transaction.createReadStream('Singers', {
    keys: ['1'],
    columns: ['SingerId', 'name']
  })
  .on('error', function(err) {})
  .on('data', function(row) {
    // row = [
    //   {
    //     name: 'SingerId',
    //     value: '1'
    //   },
    //   {
    //     name: 'Name',
    //     value: 'Eddie Wilson'
    //   }
    // ]
  })
  .on('end', function() {
    // All results retrieved.
  });
<caption>Provide an array for `query.keys` to read with a
composite key.</caption>
const query = {
  keys: [
    [
      'Id1',
      'Name1'
    ],
    [
      'Id2',
      'Name2'
    ]
  ],
  // ...
};
<caption>Rows are returned as an array of object arrays. Each
object has a `name` and `value` property. To get a serialized object, call
`toJSON()`.</caption>
transaction.createReadStream('Singers', {
    keys: ['1'],
    columns: ['SingerId', 'name']
  })
  .on('error', function(err) {})
  .on('data', function(row) {
    // row.toJSON() = {
    //   SingerId: '1',
    //   Name: 'Eddie Wilson'
    // }
  })
  .on('end', function() {
    // All results retrieved.
  });
<caption>Alternatively, set `query.json` to `true`, and this step
will perform automatically.</caption>
transaction.createReadStream('Singers', {
    keys: ['1'],
    columns: ['SingerId', 'name'],
    json: true,
  })
  .on('error', function(err) {})
  .on('data', function(row) {
    // row = {
    //   SingerId: '1',
    //   Name: 'Eddie Wilson'
    // }
  })
  .on('end', function() {
    // All results retrieved.
  });
<caption>If you anticipate many results, you can end a stream
early to prevent unnecessary processing and API requests.</caption>
transaction.createReadStream('Singers', {
    keys: ['1'],
    columns: ['SingerId', 'name']
  })
  .on('data', function(row) {
    this.end();
  });

end

end()

Let the client know you're done with a particular transaction. This should mainly be called for Snapshot objects, however in certain cases you may want to call them for Transaction objects as well.

Inherited from
Snapshot#end

Examples

Calling `end` on a read only snapshot

database.getSnapshot((err, transaction) => {
  if (err) {
    // Error handling omitted.
  }

  transaction.run('SELECT * FROM Singers', (err, rows) => {
    if (err) {
      // Error handling omitted.
    }

    // End the snapshot.
    transaction.end();
  });
});

Calling `end` on a read/write transaction

database.runTransaction((err, transaction) => {
  if (err) {
    // Error handling omitted.
  }

  const query = 'UPDATE Account SET Balance = 1000 WHERE Key = 1';

  transaction.runUpdate(query, err => {
    if (err) {
      // In the event of an error, there would be nothing to rollback,
so
      // instead of continuing, discard the
transaction. transaction.end(); return;
    }

    transaction.commit(err => {});
  });
});

execute

execute(partition, callback) returns (Promise containing RunResponse or Promise containing TransactionRequestReadResponse)

Executes partition.

Parameter

partition

(ReadPartition or QueryParition)

The partition object.

Values in partition have the following properties:

Parameter

gaxOptions

Optional

object

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.

callback

Optional

(TransactionRequestReadCallback or RunCallback)

Callback function.

See also
Transaction#read when using ReadPartition.
Transaction#run when using QueryParition.
Returns

(Promise containing RunResponse or Promise containing TransactionRequestReadResponse) 

Examples

// 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 identifier = {};
// const partition = {};

// 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 transaction = database.batchTransaction(identifier);

const [rows] = await transaction.execute(partition);
console.log(`Successfully received ${rows.length} from executed partition.`);

executeStream

executeStream(partition) returns ReadableStream

Executes partition in streaming mode.

Parameter

partition

(ReadPartition or QueryPartition)

The partition object.

See also
Transaction#createReadStream when using ReadPartition.
Transaction#runStream when using QueryPartition.
Returns

ReadableStream 

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

database.createBatchTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.createReadPartitions(options, function(err, partitions) {
    const partition = partitions[0];

    transaction
      .executeStream(partition)
      .on('error', function(err) {})
      .on('data', function(row) {
        // row = [
        //   {
        //     name: 'SingerId',
        //     value: '1'
        //   },
        //   {
        //     name: 'Name',
        //     value: 'Eddie Wilson'
        //   }
        // ]
      })
      .on('end', function() {
        // All results retrieved
      });
  });
});

identifier

identifier() returns TransactionIdentifier

Creates a transaction identifier used to reference the transaction in workers.

Returns

TransactionIdentifier 

Example

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

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

database.createBatchTransaction(function(err, transaction) {
  const identifier = transaction.identifier();
});

read

read(table, query, callback) returns Promise containing TransactionRequestReadResponse

Performs a read request against the specified Table.

Wrapper around v1.SpannerClient#read.

Parameter

table

The table to read from.

query

Configuration object. See official ReadRequest. API documentation.

callback

Optional

Callback function.

Inherited from
Snapshot#read
See also
v1.SpannerClient#read
Returns

Examples

const query = {
  keys: ['1'],
  columns: ['SingerId', 'name']
};

transaction.read('Singers', query, function(err, rows) {
  if (err) {
    // Error handling omitted.
  }

  const firstRow = rows[0];

  // firstRow = [
  //   {
  //     name: 'SingerId',
  //     value: '1'
  //   },
  //   {
  //     name: 'Name',
  //     value: 'Eddie Wilson'
  //   }
  // ]
});
<caption>Provide an array for `query.keys` to read with a
composite key.</caption>
const query = {
  keys: [
    [
      'Id1',
      'Name1'
    ],
    [
      'Id2',
      'Name2'
    ]
  ],
  // ...
};
<caption>Rows are returned as an array of object arrays. Each
object has a `name` and `value` property. To get a serialized object, call
`toJSON()`.</caption>
transaction.read('Singers', query, function(err, rows) {
  if (err) {
    // Error handling omitted.
  }

  const firstRow = rows[0];

  // firstRow.toJSON() = {
  //   SingerId: '1',
  //   Name: 'Eddie Wilson'
  // }
});
<caption>Alternatively, set `query.json` to `true`, and this step
will perform automatically.</caption>
query.json = true;

transaction.read('Singers', query, function(err, rows) {
  if (err) {
    // Error handling omitted.
  }

  const firstRow = rows[0];

  // firstRow = {
  //   SingerId: '1',
  //   Name: 'Eddie Wilson'
  // }
});

run

run(query, callback) returns Promise containing RunResponse

Execute a SQL statement on this database inside of a transaction.

Performance Considerations:

This method wraps the streaming method, Snapshot#run for your convenience. All rows are stored in memory before releasing to your callback. If you intend to receive a lot of results from your query, consider using the streaming method, so you can free each result from memory after consuming it.

Wrapper around v1.SpannerClient#executeStreamingSql.

Parameter

query

A SQL query or ExecuteSqlRequest object.

callback

Optional

Callback function.

Inherited from
Snapshot#run
See also
v1.SpannerClient#executeStreamingSql

ExecuteStreamingSql API Documentation

ExecuteSqlRequest API Documentation

Returns

Examples

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

  // rows = [
  //   {
  //     SingerId: '1',
  //     Name: 'Eddie Wilson'
  //   }
  // ]
});
<caption>The SQL query string can contain parameter placeholders.
A parameter placeholder consists of '@' followed by the parameter name.
</caption>
const query = {
  sql: 'SELECT * FROM Singers WHERE name = @name',
  params: {
    name: 'Eddie Wilson'
  }
};

transaction.run(query, function(err, rows) {
  if (err) {
    // Error handling omitted.
  }
});
<caption>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.
</caption>
const query = {
  sql: 'SELECT * FROM Singers WHERE name = @name AND id = @id',
  params: {
    id: spanner.int(8),
    name: null
  },
  types: {
    id: 'int64',
    name: 'string'
  }
};

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

runStream

runStream(query) returns ReadableStream

Create a readable object stream to receive resulting rows from a SQL statement.

Wrapper around v1.SpannerClient#executeStreamingSql.

Parameter

query

A SQL query or ExecuteSqlRequest object.

Inherited from
Snapshot#runStream
See also
v1.SpannerClient#executeStreamingSql

ExecuteStreamingSql API Documentation

ExecuteSqlRequest API Documentation

Fires
PartialResultStream#event:response
PartialResultStream#event:stats
Returns

Examples

const query = 'SELECT * FROM Singers';

transaction.runStream(query)
  .on('error', function(err) {})
  .on('data', function(row) {
    // row = {
    //   SingerId: '1',
    //   Name: 'Eddie Wilson'
    // }
  })
  .on('end', function() {
    // All results retrieved.
  });
<caption>The SQL query string can contain parameter placeholders.
A parameter placeholder consists of '@' followed by the parameter name.
</caption>
const query = {
  sql: 'SELECT * FROM Singers WHERE name = @name',
  params: {
    name: 'Eddie Wilson'
  }
};

transaction.runStream(query)
  .on('error', function(err) {})
  .on('data', function(row) {})
  .on('end', function() {});
<caption>If you anticipate many results, you can end a stream
early to prevent unnecessary processing and API requests.</caption>
transaction.runStream(query)
  .on('data', function(row) {
    this.end();
  });