Class Transaction (7.1.0)

Inheritance

Dml >Transaction

Package

@google-cloud/spanner

Examples

const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');database.runTransaction(function(err,transaction){// The `transaction` object is ready for use.});

To manually control retrying the transaction, use thegetTransaction method.

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

Constructors

(constructor)(session, options, queryOptions, requestOptions)

constructor(session:Session,options?:spannerClient.spanner.v1.TransactionOptions.ReadWrite,queryOptions?:IQueryOptions,requestOptions?:Pick<IRequestOptions,'transactionTag'>);

Execute a DML statement and get the affected row count.

Transaction#runUpdate

Parameters
NameDescription
sessionSession
optionsReadWrite
queryOptionsIQueryOptions
requestOptionsPick<IRequestOptions, 'transactionTag'>
Example
constquery='UPDATE Account SET Balance = 1000 WHERE Key = 1';transaction.runUpdate(query,(err,rowCount)=>{if(err){// Error handling omitted.}});

Properties

commitTimestamp

commitTimestamp?:PreciseDate;

commitTimestampProto

commitTimestampProto?:spannerClient.protobuf.ITimestamp;

Methods

batchUpdate(queries, options)

batchUpdate(queries:Array<string|Statement>,options?:BatchUpdateOptions|CallOptions):Promise<BatchUpdateResponse>;

Execute a series of DML statements and get the affected row counts.

If any of the DML statements fail, the returned error will contain a list of results for all successfully executed statements.

Parameters
NameDescription
queriesArray<string |Statement>
optionsBatchUpdateOptions |CallOptions

Options for configuring the request.

Returns
TypeDescription
Promise<BatchUpdateResponse>

{Promise

Examples
constqueries=[{sql:'INSERT INTO MyTable (Key, Value) VALUES (@key, @value)',params:{key:'my-key',value:'my-value'},},{sql:'UPDATE MyTable t SET t.Value = @value WHERE t.KEY = @key',params:{key:'my-other-key',value:'my-other-value'}}];transaction.batchUpdate(queries,(err,rowCounts,apiResponse)=>{if(err){// Error handling omitted.}});

If the callback is omitted, we'll return a Promise.

const[rowCounts,apiResponse]=awaittransaction.batchUpdate(queries);

batchUpdate(queries, callback)

batchUpdate(queries:Array<string|Statement>,callback:BatchUpdateCallback):void;
Parameters
NameDescription
queriesArray<string |Statement>
callbackBatchUpdateCallback
Returns
TypeDescription
void

batchUpdate(queries, options, callback)

batchUpdate(queries:Array<string|Statement>,options:BatchUpdateOptions|CallOptions,callback:BatchUpdateCallback):void;
Parameters
NameDescription
queriesArray<string |Statement>
optionsBatchUpdateOptions |CallOptions
callbackBatchUpdateCallback
Returns
TypeDescription
void

commit(options)

commit(options?:CommitOptions|CallOptions):Promise<CommitResponse>;

Commit the transaction.

Wrapper around .

Parameter
NameDescription
optionsCommitOptions |CallOptions

Options for configuring the request.

Returns
TypeDescription
Promise<CommitResponse>

{Promise

Example
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,apiResponse){if(!err){// Get the commit timestamp on successful commits.const{commitTimestamp}=apiResponse;}});});

commit(callback)

commit(callback:CommitCallback):void;
Parameter
NameDescription
callbackCommitCallback
Returns
TypeDescription
void

commit(options, callback)

commit(options:CommitOptions|CallOptions,callback:CommitCallback):void;
Parameters
NameDescription
optionsCommitOptions |CallOptions
callbackCommitCallback
Returns
TypeDescription
void

deleteRows(table, keys)

deleteRows(table:string,keys:Key[]):void;

Delete rows from a table.

Parameters
NameDescription
tablestring

The name of the table.

keysKey[]

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

Returns
TypeDescription
void
Examples
constkeys=['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 forkeys to delete rows with a composite key.

constkeys=[['Id1','Name1'],['Id2','Name2']];

getUniqueKeys(rows)

staticgetUniqueKeys(rows:object[]):string[];

Takes a list of rows and returns all unique column names.

Parameter
NameDescription
rowsobject[]

The rows.

Returns
TypeDescription
string[]

{string[]}

insert(table, rows)

insert(table:string,rows:object|object[]):void;

Insert rows of data into this table.

Parameters
NameDescription
tablestring

The name of the table.

rowsobject | object[]

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

Returns
TypeDescription
void
Examples
constrow={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.

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

replace(table, rows)

replace(table:string,rows:object|object[]):void;

Replace rows of data within a table.

Parameters
NameDescription
tablestring

The table to read from.

rowsobject | object[]

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

Returns
TypeDescription
void
Example
constrow={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(gaxOptions)

rollback(gaxOptions?:CallOptions):Promise<void>;

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 .

Parameter
NameDescription
gaxOptionsCallOptions

Request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<void>

{Promise

Example
database.runTransaction(function(err,transaction){if(err){// Error handling omitted.}transaction.rollback(function(err){if(!err){// Transaction rolled back successfully.}});});

rollback(callback)

rollback(callback:spannerClient.spanner.v1.Spanner.RollbackCallback):void;
Parameter
NameDescription
callbackRollbackCallback
Returns
TypeDescription
void

rollback(gaxOptions, callback)

rollback(gaxOptions:CallOptions,callback:spannerClient.spanner.v1.Spanner.RollbackCallback):void;
Parameters
NameDescription
gaxOptionsCallOptions
callbackRollbackCallback
Returns
TypeDescription
void

update(table, rows)

update(table:string,rows:object|object[]):void;

Update rows of data within a table.

Parameters
NameDescription
tablestring

The table to read from.

rowsobject | object[]

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

Returns
TypeDescription
void
Example
constrow={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(table, rows)

upsert(table:string,rows:object|object[]):void;

Insert or update rows of data within a table.

Parameters
NameDescription
tablestring

The table to read from.

rowsobject | object[]

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

Returns
TypeDescription
void
Example
constrow={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.}});});

useInRunner()

useInRunner():void;

Mark transaction as started from the runner.

Returns
TypeDescription
void

useOptimisticLock()

useOptimisticLock():void;

Use optimistic concurrency control for the transaction.

In this concurrency mode, operations during the execution phase, i.e., reads and queries, are performed without acquiring locks, and transactional consistency is ensured by running a validation process in the commit phase (when any needed locks are acquired). The validation process succeeds only if there are no conflicting committed transactions (that committed mutations to the read data at a commit timestamp after the read timestamp).

Returns
TypeDescription
void

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-10-30 UTC.