Class Transaction (7.1.0) Stay organized with collections Save and categorize content based on your preferences.
This type of transaction is the only way to write data into Cloud Spanner. These transactions rely on pessimistic locking and, if necessary, two-phase commit. Locking read-write transactions may abort, requiring the application to retry.
Calling either or signals that the transaction is finished and no further requests will be made. If for some reason you decide not to call one of the aformentioned methods, call to release the underlyingSession.
Running a transaction via or automatically re-runs the transaction onABORTED errors.
returns a plainTransaction object, requiring the user to retry manually.
Snapshot
Inheritance
Dml >TransactionPackage
@google-cloud/spannerExamples
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 | |
|---|---|
| Name | Description |
session | Session |
options | ReadWrite |
queryOptions | IQueryOptions |
requestOptions | Pick<IRequestOptions, 'transactionTag'> |
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 | |
|---|---|
| Name | Description |
queries | Array<string |Statement> |
options | BatchUpdateOptions |CallOptionsOptions for configuring the request. |
| Returns | |
|---|---|
| Type | Description |
Promise<BatchUpdateResponse> | {Promise |
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 | |
|---|---|
| Name | Description |
queries | Array<string |Statement> |
callback | BatchUpdateCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
batchUpdate(queries, options, callback)
batchUpdate(queries:Array<string|Statement>,options:BatchUpdateOptions|CallOptions,callback:BatchUpdateCallback):void;| Parameters | |
|---|---|
| Name | Description |
queries | Array<string |Statement> |
options | BatchUpdateOptions |CallOptions |
callback | BatchUpdateCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
commit(options)
commit(options?:CommitOptions|CallOptions):Promise<CommitResponse>;Commit the transaction.
Wrapper around .
| Parameter | |
|---|---|
| Name | Description |
options | CommitOptions |CallOptionsOptions for configuring the request. |
| Returns | |
|---|---|
| Type | Description |
Promise<CommitResponse> | {Promise |
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 | |
|---|---|
| Name | Description |
callback | CommitCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
commit(options, callback)
commit(options:CommitOptions|CallOptions,callback:CommitCallback):void;| Parameters | |
|---|---|
| Name | Description |
options | CommitOptions |CallOptions |
callback | CommitCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
deleteRows(table, keys)
deleteRows(table:string,keys:Key[]):void;Delete rows from a table.
| Parameters | |
|---|---|
| Name | Description |
table | stringThe name of the table. |
keys | Key[]The keys for the rows to delete. If using a composite key, provide an array within this array. See the example below. |
| Returns | |
|---|---|
| Type | Description |
void | |
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 | |
|---|---|
| Name | Description |
rows | object[]The rows. |
| Returns | |
|---|---|
| Type | Description |
string[] | {string[]} |
insert(table, rows)
insert(table:string,rows:object|object[]):void;Insert rows of data into this table.
| Parameters | |
|---|---|
| Name | Description |
table | stringThe name of the table. |
rows | object | object[]A map of names to values of data to insert into this table. |
| Returns | |
|---|---|
| Type | Description |
void | |
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 | |
|---|---|
| Name | Description |
table | stringThe table to read from. |
rows | object | object[]A map of names to values of data to insert into this table. |
| Returns | |
|---|---|
| Type | Description |
void | |
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 | |
|---|---|
| Name | Description |
gaxOptions | CallOptionsRequest configuration options, SeeCallOptions for more details. |
| Returns | |
|---|---|
| Type | Description |
Promise<void> | {Promise |
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 | |
|---|---|
| Name | Description |
callback | RollbackCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
rollback(gaxOptions, callback)
rollback(gaxOptions:CallOptions,callback:spannerClient.spanner.v1.Spanner.RollbackCallback):void;| Parameters | |
|---|---|
| Name | Description |
gaxOptions | CallOptions |
callback | RollbackCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
update(table, rows)
update(table:string,rows:object|object[]):void;Update rows of data within a table.
| Parameters | |
|---|---|
| Name | Description |
table | stringThe table to read from. |
rows | object | object[]A map of names to values of data to insert into this table. |
| Returns | |
|---|---|
| Type | Description |
void | |
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 | |
|---|---|
| Name | Description |
table | stringThe table to read from. |
rows | object | object[]A map of names to values of data to insert into this table. |
| Returns | |
|---|---|
| Type | Description |
void | |
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 | |
|---|---|
| Type | Description |
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 | |
|---|---|
| Type | Description |
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.