Class Snapshot (7.5.0) Stay organized with collections Save and categorize content based on your preferences.
This transaction type provides guaranteed consistency across several reads, but does not allow writes. Snapshot read-only transactions can be configured to read at timestamps in the past.
When finished with the Snapshot, call to release the underlyingSession. Failure to do so can result in a Session leak.
**This object is created and returned from .**
Inheritance
EventEmitter >SnapshotPackage
@google-cloud/spannerExample
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttimestampBounds={strong:true};database.getSnapshot(timestampBounds,(err,transaction)=>{if(err){// Error handling omitted.}// It should be called when the snapshot finishes.transaction.end();});Constructors
(constructor)(session, options, queryOptions)
constructor(session:Session,options?:TimestampBounds,queryOptions?:IQueryOptions);Constructs a new instance of theSnapshot class
| Parameters | |
|---|---|
| Name | Description |
session | SessionThe parent Session object. |
options | TimestampBoundsSnapshot timestamp bounds. |
queryOptions | IQueryOptionsDefault query options to use when none are specified for a query. |
Properties
_inlineBeginStarted
protected_inlineBeginStarted:any;_options
protected_options:spannerClient.spanner.v1.ITransactionOptions;_seqno
protected_seqno:number;_useInRunner
protected_useInRunner:boolean;_waitingRequests
protected_waitingRequests:Array<()=>void>;ended
ended:boolean;id
id?:Uint8Array|string;metadata
metadata?:spannerClient.spanner.v1.ITransaction;queryOptions
queryOptions?:IQueryOptions;readTimestamp
readTimestamp?:PreciseDate;readTimestampProto
readTimestampProto?:spannerClient.protobuf.ITimestamp;request
request:(config:{},callback:Function)=>void;requestOptions
requestOptions?:Pick<IRequestOptions,'transactionTag'>;requestStream
requestStream:(config:{})=>Readable;resourceHeader_
resourceHeader_:{[k:string]:string;};session
session:Session;Methods
_getDirectedReadOptions(directedReadOptions)
protected_getDirectedReadOptions(directedReadOptions:google.spanner.v1.IDirectedReadOptions|null|undefined):spannerClient.spanner.v1.IDirectedReadOptions|null|undefined;Get directed read options
| Parameter | |
|---|---|
| Name | Description |
directedReadOptions | google.spanner.v1.IDirectedReadOptions | null | undefinedRequest directedReadOptions object. |
| Returns | |
|---|---|
| Type | Description |
spannerClient.spanner.v1.IDirectedReadOptions | null | undefined | |
_getSpanner()
protected_getSpanner():Spanner;Gets the Spanner object
| Returns | |
|---|---|
| Type | Description |
Spanner | {Spanner} |
_releaseWaitingRequests()
_releaseWaitingRequests():void;| Returns | |
|---|---|
| Type | Description |
void | |
_update(resp)
protected_update(resp:spannerClient.spanner.v1.ITransaction):void;Update transaction properties from the response.
| Parameter | |
|---|---|
| Name | Description |
resp | ITransactionResponse object. |
| Returns | |
|---|---|
| Type | Description |
void | |
begin(gaxOptions)
begin(gaxOptions?:CallOptions):Promise<BeginResponse>;Begin a new transaction. Typically, you need not call this unless manually creating transactions viaSession objects.
| Parameter | |
|---|---|
| Name | Description |
gaxOptions | CallOptionsRequest configuration options, SeeCallOptions for more details. |
| Returns | |
|---|---|
| Type | Description |
Promise<BeginResponse> | {Promise |
transaction.begin(function(err){if(!err){// transaction began successfully.}});If the callback is omitted, the function returns a Promise
transaction.begin().then(function(data){constapiResponse=data[0];});begin(callback)
begin(callback:BeginTransactionCallback):void;| Parameter | |
|---|---|
| Name | Description |
callback | BeginTransactionCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
begin(gaxOptions, callback)
begin(gaxOptions:CallOptions,callback:BeginTransactionCallback):void;| Parameters | |
|---|---|
| Name | Description |
gaxOptions | CallOptions |
callback | BeginTransactionCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
configureTagOptions(singleUse, transactionTag, requestOptions)
configureTagOptions(singleUse?:boolean,transactionTag?:string,requestOptions?:{}):IRequestOptions|null;| Parameters | |
|---|---|
| Name | Description |
singleUse | boolean |
transactionTag | string |
requestOptions | {} |
| Returns | |
|---|---|
| Type | Description |
IRequestOptions | null | |
createReadStream(table, request)
createReadStream(table:string,request?:ReadRequest):PartialResultStream;Create a readable object stream to receive rows from the database using key lookups and scans.
Wrapper around .
| Parameters | |
|---|---|
| Name | Description |
table | stringThe table to read from. |
request | ReadRequest |
| Returns | |
|---|---|
| Type | Description |
PartialResultStream | {ReadableStream} A readable stream that emits rows. |
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 forquery.keys to read with a composite key.
constquery={keys:[['Id1','Name1'],['Id2','Name2']],// ...};Rows are returned as an array of object arrays. Each object has aname andvalue property. To get a serialized object, calltoJSON().
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, setquery.json totrue, 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();});encodeKeySet(request)
staticencodeKeySet(request:ReadRequest):spannerClient.spanner.v1.IKeySet;Transforms convenience optionskeys andranges into a KeySet object.
| Parameter | |
|---|---|
| Name | Description |
request | ReadRequestThe read request. |
| Returns | |
|---|---|
| Type | Description |
IKeySet | {object} |
encodeParams(request)
staticencodeParams(request:ExecuteSqlRequest):{params:p.IStruct;paramTypes:{[field:string]:spannerClient.spanner.v1.Type;};};Encodes convenience optionsparam andtypes into the proto formatted.
| Parameter | |
|---|---|
| Name | Description |
request | ExecuteSqlRequestThe SQL request. |
| Returns | |
|---|---|
| Type | Description |
{ params:common.IStruct; paramTypes: { [field: string]:spannerClient.spanner.v1.Type; }; } | {object} |
encodeTimestampBounds(options)
staticencodeTimestampBounds(options:TimestampBounds):spannerClient.spanner.v1.TransactionOptions.IReadOnly;Formats timestamp options into proto format.
| Parameter | |
|---|---|
| Name | Description |
options | TimestampBoundsThe user supplied options. |
| Returns | |
|---|---|
| Type | Description |
IReadOnly | {object} |
end()
end():void;Let the client know you're done with a particular transaction. This should mainly be called forSnapshot objects, however in certain cases you may want to call them forTransaction objects as well.
| Returns | |
|---|---|
| Type | Description |
void | |
Callingend 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();});});Callingend on a read/write transaction
database.runTransaction((err,transaction)=>{if(err){// Error handling omitted.}constquery='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 thetransaction.transaction.end();return;}transaction.commit(err=>{});});});read(table, request)
read(table:string,request:ReadRequest):Promise<ReadResponse>;Performs a read request against the specified Table.
Wrapper around .
| Parameters | |
|---|---|
| Name | Description |
table | stringThe table to read from. |
request | ReadRequest |
| Returns | |
|---|---|
| Type | Description |
Promise<ReadResponse> | {Promise |
constquery={keys:['1'],columns:['SingerId','name']};transaction.read('Singers',query,function(err,rows){if(err){// Error handling omitted.}constfirstRow=rows[0];// firstRow = [// {// name: 'SingerId',// value: '1'// },// {// name: 'Name',// value: 'Eddie Wilson'// }// ]});Provide an array forquery.keys to read with a composite key.
constquery={keys:[['Id1','Name1'],['Id2','Name2']],// ...};Rows are returned as an array of object arrays. Each object has aname andvalue property. To get a serialized object, calltoJSON().
transaction.read('Singers',query,function(err,rows){if(err){// Error handling omitted.}constfirstRow=rows[0];// firstRow.toJSON() = {// SingerId: '1',// Name: 'Eddie Wilson'// }});Alternatively, setquery.json totrue, and this step will perform automatically.
query.json=true;transaction.read('Singers',query,function(err,rows){if(err){// Error handling omitted.}constfirstRow=rows[0];// firstRow = {// SingerId: '1',// Name: 'Eddie Wilson'// }});read(table, callback)
read(table:string,callback:ReadCallback):void;| Parameters | |
|---|---|
| Name | Description |
table | string |
callback | ReadCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
read(table, request, callback)
read(table:string,request:ReadRequest,callback:ReadCallback):void;| Parameters | |
|---|---|
| Name | Description |
table | string |
request | ReadRequest |
callback | ReadCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
run(query)
run(query:string|ExecuteSqlRequest):Promise<RunResponse>;Execute a SQL statement on this database inside of a transaction.
**Performance Considerations:**
This method wraps the streaming method, 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 .
| Parameter | |
|---|---|
| Name | Description |
query | string |ExecuteSqlRequestA SQL query or object. |
| Returns | |
|---|---|
| Type | Description |
Promise<RunResponse> | {Promise |
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.
constquery={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.
constquery={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.}});run(query, callback)
run(query:string|ExecuteSqlRequest,callback:RunCallback):void;| Parameters | |
|---|---|
| Name | Description |
query | string |ExecuteSqlRequest |
callback | RunCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
runStream(query)
runStream(query:string|ExecuteSqlRequest):PartialResultStream;Create a readable object stream to receive resulting rows from a SQL statement.
Wrapper around .
| Parameter | |
|---|---|
| Name | Description |
query | string |ExecuteSqlRequestA SQL query or object. |
| Returns | |
|---|---|
| Type | Description |
PartialResultStream | {ReadableStream} |
constquery='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.
constquery={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();});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.