Constructor

Transaction

new Transaction(session, options)

Use a Transaction object to read and write against your Cloud Spanner database.

This object is created and returned from Database#runTransaction.

Parameter

session

Session

The parent Session object.

options

Optional

TransactionOptions

Transaction options.

Extends
TransactionRequest

Example

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

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

database.runTransaction(function(err, transaction) {
  // The `transaction` object is ready for use.
});

Property

session

Session

Methods

commit

commit(callback) returns Promise containing BasicResponse

Commit the transaction.

Wrapper around v1.SpannerClient#commit.

Parameter

callback

Optional

BasicCallback

Callback function.

See also
v1.SpannerClient#commit

Commit API Documentation

Throws

Error 

If transaction has already been ended.

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.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  // Queue a mutation (note that there is no callback passed to `insert`).
  transaction.insert('Singers', {
    SingerId: 'Id3b',
    Name: 'Joe West'
  });

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // Mutations were committed successfully.
    }
  });
});

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 ReadRequest.

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

StreamingRead API Documentation

ReadRequest API Documentation

Returns

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.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  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()`.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

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

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.createReadStream('Singers', {
      keys: ['1'],
      columns: ['SingerId', 'name']
    })
    .on('data', function(row) {
      this.end();
    });
});

deleteRows

deleteRows(table, keys)

Delete rows from a table.

Parameter

table

The name of the table.

keys

The keys for the rows to delete. If using a composite key, provide an array within this array. See the example below.

Inherited from
TransactionRequest#deleteRows
See also

Commit API Documentation

Example

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

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

const keys = ['Id1', 'Id2', 'Id3'];

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

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `deleteRows`.
  transaction.deleteRows('Singers', keys);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The rows were deleted successfully.
    }
  });
});

//-
// Provide an array for `keys` to delete rows with a composite key.
//-
const keys = [
  [
    'Id1',
    'Name1'
  ],
  [
    'Id2',
    'Name2'
  ]
];

end

end(callback)

Let the client know you're done with a particular transaction. This should only be called for read-only transactions.

Parameter

callback

function()

Optional callback function to be called after transaction has ended.

Throws

Error 

If transaction has already been ended.

Example

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

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

const options = {
  readOnly: true
};

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

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

    // End the transaction. Note that no callback is provided.
    transaction.end();
  });
});

insert

insert(table, keyVals)

Insert rows of data into this table.

Parameter

table

The name of the table.

keyVals

A map of names to values of data to insert into this table.

Inherited from
TransactionRequest#insert
See also

Commit API Documentation

Example

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

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

const row = {
  SingerId: 'Id3',
  Name: 'Eddie Wilson'
};

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

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `insert`.
  transaction.insert('Singers', row);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The row was inserted successfully.
    }
  });
});

//-
// Multiple rows can be inserted at once.
//-
const row2 = {
  SingerId: 'Id3b',
  Name: 'Joe West'
};

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

  // Queue multiple mutations until later calling `commit`.
  // Note that a callback is not passed to `insert`.
  transaction.insert('Singers', [
    row,
    row2
  ]);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The rows were inserted successfully.
    }
  });
});

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, describing what to read from the table.

callback

Optional

Callback function.

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

Example

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

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

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

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

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

    const row1 = rows[0];

    // row1 = [
    //   {
    //     name: 'SingerId',
    //     value: '1'
    //   },
    //   {
    //     name: 'Name',
    //     value: 'Eddie Wilson'
    //   }
    // ]

    // End the transaction. Note that no callback is provided.
    transaction.end();
  });
});

//-
// 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()`.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

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

    const row1 = rows[0];

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

    // End the transaction. Note that no callback is provided.
    transaction.end();
  });
});

replace

replace(table, keyVals)

Replace rows of data within a table.

Parameter

table

The table to read from.

keyVals

A map of names to values of data to insert into this table.

Inherited from
TransactionRequest#replace
See also

Commit API Documentation

Example

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

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

const row = {
  SingerId: 'Id3',
  Name: 'Joe West'
};

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

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `replace`.
  transaction.replace('Singers', row);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The row was replaced successfully.
    }
  });
});

rollback

rollback(callback) returns Promise containing BasicResponse

Roll back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more queries that you decide not to commit.

Wrapper around v1.SpannerClient#rollback.

Parameter

callback

Optional

BasicCallback

Callback function.

See also
v1.SpannerClient#rollback

Rollback API Documentation

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.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.rollback(function(err) {
    if (!err) {
      // Transaction rolled back successfully.
    }
  });
});

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, Transaction#run for your convenience. All rows will be stored in memory before being released to your callback. If you intend on receiving 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 object)

A SQL query or ExecuteSqlRequest object.

Values in query have the following properties:

Parameter

params

Optional

object

A map of parameter name to values.

types

Optional

object

A map of parameter types.

callback

Optional

RunCallback

Callback function.

See also
v1.SpannerClient#executeStreamingSql

ExecuteStreamingSql API Documentation

ExecuteSqlRequest API Documentation

Returns

Promise containing RunResponse 

Example

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

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

const query = 'SELECT * FROM Singers';

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

  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.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

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

  transaction.run(query, function(err, rows) {});
});

//-
// 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.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

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

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 object)

A SQL query or ExecuteSqlRequest object.

Values in query have the following properties:

Parameter

params

Optional

object

A map of parameter name to values.

types

Optional

object

A map of parameter types.

See also
v1.SpannerClient#executeStreamingSql

ExecuteStreamingSql API Documentation

ExecuteSqlRequest API Documentation

Returns

ReadableStream 

Example

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

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

const query = 'SELECT * FROM Singers';

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

  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.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  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.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

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

shouldRetry_

shouldRetry_(err) returns boolean

Determines whether or not this Transaction should be retried in the event of an ABORTED error.

Parameter

err

error

The request error.

Returns

boolean 

update

update(table, keyVals)

Update rows of data within a table.

Parameter

table

The table to read from.

keyVals

A map of names to values of data to insert into this table.

Inherited from
TransactionRequest#update
See also

Commit API Documentation

Example

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

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

const row = {
  SingerId: 'Id3',
  Name: 'Joe West'
};

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

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `update`.
  transaction.update('Singers', row);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The row was updated successfully.
    }
  });
});

upsert

upsert(table, keyVals)

Insert or update rows of data within a table.

Parameter

table

The table to read from.

keyVals

A map of names to values of data to insert into this table.

Inherited from
TransactionRequest#upsert
See also

Commit API Documentation

Example

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

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

const row = {
  SingerId: 'Id3',
  Name: 'Joe West'
};

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

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `upsert`.
  transaction.upsert('Singers', row);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The row was updated or inserted successfully.
    }
  });
});