Class Snapshot (7.5.0)

Inheritance

EventEmitter >Snapshot

Package

@google-cloud/spanner

Example

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
NameDescription
sessionSession

The parent Session object.

optionsTimestampBounds

Snapshot timestamp bounds.

queryOptionsIQueryOptions

Default 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
NameDescription
directedReadOptionsgoogle.spanner.v1.IDirectedReadOptions | null | undefined

Request directedReadOptions object.

Returns
TypeDescription
spannerClient.spanner.v1.IDirectedReadOptions | null | undefined

_getSpanner()

protected_getSpanner():Spanner;

Gets the Spanner object

Returns
TypeDescription
Spanner

{Spanner}

_releaseWaitingRequests()

_releaseWaitingRequests():void;
Returns
TypeDescription
void

_update(resp)

protected_update(resp:spannerClient.spanner.v1.ITransaction):void;

Update transaction properties from the response.

Parameter
NameDescription
respITransaction

Response object.

Returns
TypeDescription
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
NameDescription
gaxOptionsCallOptions

Request configuration options, SeeCallOptions for more details.

Returns
TypeDescription
Promise<BeginResponse>

{Promise

Examples
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
NameDescription
callbackBeginTransactionCallback
Returns
TypeDescription
void

begin(gaxOptions, callback)

begin(gaxOptions:CallOptions,callback:BeginTransactionCallback):void;
Parameters
NameDescription
gaxOptionsCallOptions
callbackBeginTransactionCallback
Returns
TypeDescription
void

configureTagOptions(singleUse, transactionTag, requestOptions)

configureTagOptions(singleUse?:boolean,transactionTag?:string,requestOptions?:{}):IRequestOptions|null;
Parameters
NameDescription
singleUseboolean
transactionTagstring
requestOptions{}
Returns
TypeDescription
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
NameDescription
tablestring

The table to read from.

requestReadRequest
Returns
TypeDescription
PartialResultStream

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

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
NameDescription
requestReadRequest

The read request.

Returns
TypeDescription
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
NameDescription
requestExecuteSqlRequest

The SQL request.

Returns
TypeDescription
{ 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
NameDescription
optionsTimestampBounds

The user supplied options.

Returns
TypeDescription
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
TypeDescription
void
Examples

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
NameDescription
tablestring

The table to read from.

requestReadRequest
Returns
TypeDescription
Promise<ReadResponse>

{Promise

Examples
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
NameDescription
tablestring
callbackReadCallback
Returns
TypeDescription
void

read(table, request, callback)

read(table:string,request:ReadRequest,callback:ReadCallback):void;
Parameters
NameDescription
tablestring
requestReadRequest
callbackReadCallback
Returns
TypeDescription
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
NameDescription
querystring |ExecuteSqlRequest

A SQL query or object.

Returns
TypeDescription
Promise<RunResponse>

{Promise

Examples
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
NameDescription
querystring |ExecuteSqlRequest
callbackRunCallback
Returns
TypeDescription
void

runStream(query)

runStream(query:string|ExecuteSqlRequest):PartialResultStream;

Create a readable object stream to receive resulting rows from a SQL statement.

Wrapper around .

Parameter
NameDescription
querystring |ExecuteSqlRequest

A SQL query or object.

Returns
TypeDescription
PartialResultStream

{ReadableStream}

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