Class Snapshot (7.0.0)

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 underlying Session. Failure to do so can result in a Session leak.

**This object is created and returned from .**

Inheritance

EventEmitter > Snapshot

Package

@google-cloud/spanner

Example


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

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

const timestampBounds = {
  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 the Snapshot class

Parameters
NameDescription
session Session

The parent Session object.

options TimestampBounds

Snapshot timestamp bounds.

queryOptions IQueryOptions

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

_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
resp ITransaction

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 via Session objects.

Parameter
NameDescription
gaxOptions CallOptions

Request configuration options, See CallOptions 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) {
    const apiResponse = data[0];
  });

begin(callback)

begin(callback: BeginTransactionCallback): void;
Parameter
NameDescription
callback BeginTransactionCallback
Returns
TypeDescription
void

begin(gaxOptions, callback)

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

configureTagOptions(singleUse, transactionTag, requestOptions)

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

The table to read from.

request ReadRequest
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 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().


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, set query.json to true, 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)

static encodeKeySet(request: ReadRequest): spannerClient.spanner.v1.IKeySet;

Transforms convenience options keys and ranges into a KeySet object.

Parameter
NameDescription
request ReadRequest

The read request.

Returns
TypeDescription
IKeySet

{object}

encodeParams(request)

static encodeParams(request: ExecuteSqlRequest): {
        params: p.IStruct;
        paramTypes: {
            [field: string]: spannerClient.spanner.v1.Type;
        };
    };

Encodes convenience options param and types into the proto formatted.

Parameter
NameDescription
request ExecuteSqlRequest

The SQL request.

Returns
TypeDescription
{ params: common.IStruct; paramTypes: { [field: string]: spannerClient.spanner.v1.Type; }; }

{object}

encodeTimestampBounds(options)

static encodeTimestampBounds(options: TimestampBounds): spannerClient.spanner.v1.TransactionOptions.IReadOnly;

Formats timestamp options into proto format.

Parameter
NameDescription
options TimestampBounds

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 for Snapshot objects, however in certain cases you may want to call them for Transaction objects as well.

Returns
TypeDescription
void
Examples

Calling end 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();
  });
});

Calling end on a read/write transaction


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

  const query = '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 the
transaction. 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
table string

The table to read from.

request ReadRequest
Returns
TypeDescription
Promise<ReadResponse>

{Promise

Examples

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

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

  const firstRow = rows[0];

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

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().


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

  const firstRow = rows[0];

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

Alternatively, set query.json to true, and this step will perform automatically.


query.json = true;

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

  const firstRow = rows[0];

  // firstRow = {
  //   SingerId: '1',
  //   Name: 'Eddie Wilson'
  // }
});

read(table, callback)

read(table: string, callback: ReadCallback): void;
Parameters
NameDescription
table string
callback ReadCallback
Returns
TypeDescription
void

read(table, request, callback)

read(table: string, request: ReadRequest, callback: ReadCallback): void;
Parameters
NameDescription
table string
request ReadRequest
callback ReadCallback
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
query string | 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.


const query = {
  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.


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) {
  if (err) {
    // Error handling omitted.
  }
});

run(query, callback)

run(query: string | ExecuteSqlRequest, callback: RunCallback): void;
Parameters
NameDescription
query string | ExecuteSqlRequest
callback RunCallback
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
query string | ExecuteSqlRequest

A SQL query or object.

Returns
TypeDescription
PartialResultStream

{ReadableStream}

Examples

const query = '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.


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.


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