BatchTransaction

BatchTransaction

Use a BatchTransaction object to create partitions and read/query against your Cloud Spanner database.

Constructor

new BatchTransaction(optionsopt)

Parameters:
Name Type Attributes Description
options TimestampBounds <optional>

Timestamp Bounds.

Extends

Members

ended :boolean

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

Inherited From:

(nullable) id :string|Buffer

The transaction ID.

Overrides:

(nullable) metadata :TransactionResponse

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

Inherited From:

(nullable) readTimestamp :external:PreciseDate

Snapshot only The timestamp at which all reads are performed.

Overrides:

(nullable) readTimestampProto :google.protobuf.Timestamp

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

Overrides:

Methods

begin(gaxOptionsopt, callbackopt) → {Promise.<TransactionBeginResponse>}

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

Parameters:
Name Type Attributes Description
gaxOptions object <optional>

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

callback TransactionBeginCallback <optional>

Callback function.

Inherited From:
See:
Examples
transaction.begin(function(err) {
  if (!err) {
    // transaction began successfully.
  }
});

If the callback is omitted, the function returns a Promise

transaction.begin()
  .then(function(data) {
    const apiResponse = data[0];
  });

close(callbackopt) → {Promise.<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

Parameters:
Name Type Attributes Description
callback BasicCallback <optional>

Callback function.

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(query, callbackopt) → {Promise.<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.

Parameters:
Name Type Attributes Description
query string | object

A SQL query or ExecuteSqlRequest object.

Properties
Name Type Attributes Description
gaxOptions object <optional>

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

params object <optional>

A map of parameter name to values.

partitionOptions object <optional>

A map of partition options.

types object <optional>

A map of parameter types.

callback CreateQueryPartitionsCallback <optional>

Callback callback function.

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';
  // 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(options, callbackopt) → {Promise.<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.

Parameters:
Name Type Attributes Description
options ReadRequestOptions

Configuration object, describing what to read from.

callback CreateReadPartitionsCallback <optional>

Callback function.

createReadStream(table, query) → {ReadableStream}

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

Wrapper around v1.SpannerClient#streamingRead.

Parameters:
Name Type Description
table string

The table to read from.

query ReadRequest

Configuration object. See official ReadRequest. API documentation.

Inherited From:
See:
Fires:
  • PartialResultStream#event:response
  • PartialResultStream#event:stats
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.
  });

Provide an array for `query.keys` to read with a composite key.

const query = {
  keys: [
    [
      'Id1',
      'Name1'
    ],
    [
      'Id2',
      'Name2'
    ]
  ],
  // ...
};

Rows are returned as an array of object arrays. Each object has a `name` and `value` property. To get a serialized object, call `toJSON()`.

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

Alternatively, set `query.json` to `true`, and this step will perform automatically.

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

If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests.

transaction.createReadStream('Singers', {
    keys: ['1'],
    columns: ['SingerId', 'name']
  })
  .on('data', function(row) {
    this.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:
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(partition, callbackopt) → {Promise.<RunResponse>|Promise.<TransactionRequestReadResponse>}

Executes partition.

Parameters:
Name Type Attributes Description
partition ReadPartition | QueryParition

The partition object.

Properties
Name Type Attributes Description
gaxOptions object <optional>

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

callback TransactionRequestReadCallback | RunCallback <optional>

Callback function.

See:
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';
  // 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(partition) → {ReadableStream}

Executes partition in streaming mode.

Parameters:
Name Type Description
partition ReadPartition | QueryPartition

The partition object.

See:
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() → {TransactionIdentifier}

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

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(table, query, callbackopt) → {Promise.<TransactionRequestReadResponse>}

Performs a read request against the specified Table.

Wrapper around v1.SpannerClient#read.

Parameters:
Name Type Attributes Description
table string

The table to read from.

query ReadRequest

Configuration object. See official ReadRequest. API documentation.

callback TransactionRequestReadCallback <optional>

Callback function.

Inherited From:
See:
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'
  //   }
  // ]
});

Provide an array for `query.keys` to read with a composite key.

const query = {
  keys: [
    [
      'Id1',
      'Name1'
    ],
    [
      'Id2',
      'Name2'
    ]
  ],
  // ...
};

Rows are returned as an array of object arrays. Each object has a `name` and `value` property. To get a serialized object, call `toJSON()`.

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

  const firstRow = rows[0];

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

Alternatively, set `query.json` to `true`, and this step will perform automatically.

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(query, callbackopt) → {Promise.<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.

Parameters:
Name Type Attributes Description
query string | ExecuteSqlRequest

A SQL query or ExecuteSqlRequest object.

callback RunCallback <optional>

Callback function.

Inherited From:
See:
Examples
transaction.run(query, function(err, rows) {
  if (err) {
    // Error handling omitted.
  }

  // rows = [
  //   {
  //     SingerId: '1',
  //     Name: 'Eddie Wilson'
  //   }
  // ]
});

The SQL query string can contain parameter placeholders. A parameter placeholder consists of '@' followed by the parameter name.

const query = {
  sql: 'SELECT * FROM Singers WHERE name = @name',
  params: {
    name: 'Eddie Wilson'
  }
};

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

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.

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(query) → {ReadableStream}

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

Wrapper around v1.SpannerClient#executeStreamingSql.

Parameters:
Name Type Description
query string | ExecuteSqlRequest

A SQL query or ExecuteSqlRequest object.

Inherited From:
See:
Fires:
  • PartialResultStream#event:response
  • PartialResultStream#event:stats
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.
  });

The SQL query string can contain parameter placeholders. A parameter placeholder consists of '@' followed by the parameter name.

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

If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests.

transaction.runStream(query)
  .on('data', function(row) {
    this.end();
  });