Properties

ended

boolean

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

id

nullable (string or Buffer)

The transaction ID.

metadata

nullable TransactionResponse

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

readTimestamp

nullable external:PreciseDate

Snapshot only The timestamp at which all reads are performed.

readTimestampProto

nullable google.protobuf.Timestamp

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

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

TransactionBeginCallback

Callback function.

See also

BeginTransaction API Documentation

Returns

Promise containing TransactionBeginResponse 

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

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

string

The table to read from.

query

ReadRequest

Configuration object. See official ReadRequest. API documentation.

See also
v1.SpannerClient#streamingRead

StreamingRead API Documentation

ReadRequest API Documentation

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

ReadableStream 

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.

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

read

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

Performs a read request against the specified Table.

Wrapper around v1.SpannerClient#read.

Parameter

table

string

The table to read from.

query

ReadRequest

Configuration object. See official ReadRequest. API documentation.

callback

Optional

TransactionRequestReadCallback

Callback function.

See also
v1.SpannerClient#read
Returns

Promise containing TransactionRequestReadResponse 

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

(string or ExecuteSqlRequest)

A SQL query or ExecuteSqlRequest object.

callback

Optional

RunCallback

Callback function.

See also
v1.SpannerClient#executeStreamingSql

ExecuteStreamingSql API Documentation

ExecuteSqlRequest API Documentation

Returns

Promise containing RunResponse 

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

(string or ExecuteSqlRequest)

A SQL query or ExecuteSqlRequest object.

See also
v1.SpannerClient#executeStreamingSql

ExecuteStreamingSql API Documentation

ExecuteSqlRequest API Documentation

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

ReadableStream 

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