@google-cloud/spanner
Version:
Cloud Spanner Client Library for Node.js
1,046 lines • 60.5 kB
JavaScript
"use strict";
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpannerClient = void 0;
const stream_1 = require("stream");
const jsonProtos = require("../../protos/protos.json");
const google_gax_1 = require("google-gax");
/**
* Client JSON configuration object, loaded from
* `src/v1/spanner_client_config.json`.
* This file defines retry strategy and timeouts for all API methods in this library.
*/
const gapicConfig = require("./spanner_client_config.json");
const version = require('../../../package.json').version;
/**
* Cloud Spanner API
*
* The Cloud Spanner API can be used to manage sessions and execute
* transactions on data stored in Cloud Spanner databases.
* @class
* @memberof v1
*/
class SpannerClient {
_terminated = false;
_opts;
_providedCustomServicePath;
_gaxModule;
_gaxGrpc;
_protos;
_defaults;
_universeDomain;
_servicePath;
_log = google_gax_1.loggingUtils.log('spanner');
auth;
descriptors = {
page: {},
stream: {},
longrunning: {},
batching: {},
};
warn;
innerApiCalls;
pathTemplates;
spannerStub;
/**
* Construct an instance of SpannerClient.
*
* @param {object} [options] - The configuration object.
* The options accepted by the constructor are described in detail
* in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance).
* The common options are:
* @param {object} [options.credentials] - Credentials object.
* @param {string} [options.credentials.client_email]
* @param {string} [options.credentials.private_key]
* @param {string} [options.email] - Account email address. Required when
* using a .pem or .p12 keyFilename.
* @param {string} [options.keyFilename] - Full path to the a .json, .pem, or
* .p12 key downloaded from the Google Developers Console. If you provide
* a path to a JSON file, the projectId option below is not necessary.
* NOTE: .pem and .p12 require you to specify options.email as well.
* @param {number} [options.port] - The port on which to connect to
* the remote host.
* @param {string} [options.projectId] - The project ID from the Google
* Developer's Console, e.g. 'grape-spaceship-123'. We will also check
* the environment variable GCLOUD_PROJECT for your project ID. If your
* app is running in an environment which supports
* {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
* @param {gax.ClientConfig} [options.clientConfig] - Client configuration override.
* Follows the structure of {@link gapicConfig}.
* @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode.
* For more information, please check the
* {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}.
* @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you
* need to avoid loading the default gRPC version and want to use the fallback
* HTTP implementation. Load only fallback version and pass it to the constructor:
* ```
* const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC
* const client = new SpannerClient({fallback: true}, gax);
* ```
*/
constructor(opts, gaxInstance) {
// Ensure that options include all the required fields.
const staticMembers = this.constructor;
if (opts?.universe_domain &&
opts?.universeDomain &&
opts?.universe_domain !== opts?.universeDomain) {
throw new Error('Please set either universe_domain or universeDomain, but not both.');
}
const universeDomainEnvVar = typeof process === 'object' && typeof process.env === 'object'
? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']
: undefined;
this._universeDomain =
opts?.universeDomain ??
opts?.universe_domain ??
universeDomainEnvVar ??
'googleapis.com';
this._servicePath = 'spanner.' + this._universeDomain;
const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath;
this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint);
const port = opts?.port || staticMembers.port;
const clientConfig = opts?.clientConfig ?? {};
const fallback = opts?.fallback ??
(typeof window !== 'undefined' && typeof window?.fetch === 'function');
opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts);
// Request numeric enum values if REST transport is used.
opts.numericEnums = true;
// If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case.
if (servicePath !== this._servicePath && !('scopes' in opts)) {
opts['scopes'] = staticMembers.scopes;
}
// Load google-gax module synchronously if needed
if (!gaxInstance) {
gaxInstance = require('google-gax');
}
// Choose either gRPC or proto-over-HTTP implementation of google-gax.
this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance;
// Create a `gaxGrpc` object, with any grpc-specific options sent to the client.
this._gaxGrpc = new this._gaxModule.GrpcClient(opts);
// Save options to use in initialize() method.
this._opts = opts;
// Save the auth object to the client, for use by other methods.
this.auth = this._gaxGrpc.auth;
// Set useJWTAccessWithScope on the auth object.
this.auth.useJWTAccessWithScope = true;
// Set defaultServicePath on the auth object.
this.auth.defaultServicePath = this._servicePath;
// Set the default scopes in auth client if needed.
if (servicePath === this._servicePath) {
this.auth.defaultScopes = staticMembers.scopes;
}
// Determine the client header string.
const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`];
if (typeof process === 'object' && 'versions' in process) {
clientHeader.push(`gl-node/${process.versions.node}`);
}
else {
clientHeader.push(`gl-web/${this._gaxModule.version}`);
}
if (!opts.fallback) {
clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`);
}
else {
clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`);
}
if (opts.libName && opts.libVersion) {
clientHeader.push(`${opts.libName}/${opts.libVersion}`);
}
// Load the applicable protos.
this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos);
// This API contains "path templates"; forward-slash-separated
// identifiers to uniquely identify resources within the API.
// Create useful helper objects for these.
this.pathTemplates = {
databasePathTemplate: new this._gaxModule.PathTemplate('projects/{project}/instances/{instance}/databases/{database}'),
sessionPathTemplate: new this._gaxModule.PathTemplate('projects/{project}/instances/{instance}/databases/{database}/sessions/{session}'),
};
// Some of the methods on this service return "paged" results,
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this.descriptors.page = {
listSessions: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'sessions'),
};
// Some of the methods on this service provide streaming responses.
// Provide descriptors for these.
this.descriptors.stream = {
executeStreamingSql: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries),
streamingRead: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries),
batchWrite: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries),
};
// Put together the default options sent with requests.
this._defaults = this._gaxGrpc.constructSettings('google.spanner.v1.Spanner', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') });
// Set up a dictionary of "inner API calls"; the core implementation
// of calling the API is handled in `google-gax`, with this code
// merely providing the destination and request information.
this.innerApiCalls = {};
// Add a warn function to the client constructor so it can be easily tested.
this.warn = this._gaxModule.warn;
}
/**
* Initialize the client.
* Performs asynchronous operations (such as authentication) and prepares the client.
* This function will be called automatically when any class method is called for the
* first time, but if you need to initialize it before calling an actual method,
* feel free to call initialize() directly.
*
* You can await on this method if you want to make sure the client is initialized.
*
* @returns {Promise} A promise that resolves to an authenticated service stub.
*/
initialize() {
// If the client stub promise is already initialized, return immediately.
if (this.spannerStub) {
return this.spannerStub;
}
// Put together the "service stub" for
// google.spanner.v1.Spanner.
this.spannerStub = this._gaxGrpc.createStub(this._opts.fallback
? this._protos.lookupService('google.spanner.v1.Spanner')
: // eslint-disable-next-line @typescript-eslint/no-explicit-any
this._protos.google.spanner.v1.Spanner, this._opts, this._providedCustomServicePath);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const spannerStubMethods = [
'createSession',
'batchCreateSessions',
'getSession',
'listSessions',
'deleteSession',
'executeSql',
'executeStreamingSql',
'executeBatchDml',
'read',
'streamingRead',
'beginTransaction',
'commit',
'rollback',
'partitionQuery',
'partitionRead',
'batchWrite',
];
for (const methodName of spannerStubMethods) {
const callPromise = this.spannerStub.then(stub => (...args) => {
if (this._terminated) {
if (methodName in this.descriptors.stream) {
const stream = new stream_1.PassThrough({ objectMode: true });
setImmediate(() => {
stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.'));
});
return stream;
}
return Promise.reject('The client has already been closed.');
}
const func = stub[methodName];
return func.apply(stub, args);
}, (err) => () => {
throw err;
});
const descriptor = this.descriptors.page[methodName] ||
this.descriptors.stream[methodName] ||
undefined;
const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor, this._opts.fallback);
this.innerApiCalls[methodName] = apiCall;
}
return this.spannerStub;
}
/**
* The DNS address for this API service.
* @deprecated Use the apiEndpoint method of the client instance.
* @returns {string} The DNS address for this service.
*/
static get servicePath() {
if (typeof process === 'object' &&
typeof process.emitWarning === 'function') {
process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning');
}
return 'spanner.googleapis.com';
}
/**
* The DNS address for this API service - same as servicePath.
* @deprecated Use the apiEndpoint method of the client instance.
* @returns {string} The DNS address for this service.
*/
static get apiEndpoint() {
if (typeof process === 'object' &&
typeof process.emitWarning === 'function') {
process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning');
}
return 'spanner.googleapis.com';
}
/**
* The DNS address for this API service.
* @returns {string} The DNS address for this service.
*/
get apiEndpoint() {
return this._servicePath;
}
get universeDomain() {
return this._universeDomain;
}
/**
* The port for this API service.
* @returns {number} The default port for this service.
*/
static get port() {
return 443;
}
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
* @returns {string[]} List of default scopes.
*/
static get scopes() {
return [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/spanner.data',
];
}
/**
* Return the project ID used by this class.
* @returns {Promise} A promise that resolves to string containing the project ID.
*/
getProjectId(callback) {
if (callback) {
this.auth.getProjectId(callback);
return;
}
return this.auth.getProjectId();
}
createSession(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
database: request.database ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('createSession request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('createSession response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.createSession(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('createSession response %j', response);
return [response, options, rawResponse];
});
}
batchCreateSessions(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
database: request.database ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('batchCreateSessions request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('batchCreateSessions response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.batchCreateSessions(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('batchCreateSessions response %j', response);
return [response, options, rawResponse];
});
}
getSession(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
name: request.name ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('getSession request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('getSession response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.getSession(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('getSession response %j', response);
return [response, options, rawResponse];
});
}
deleteSession(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
name: request.name ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('deleteSession request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('deleteSession response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.deleteSession(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('deleteSession response %j', response);
return [response, options, rawResponse];
});
}
executeSql(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('executeSql request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('executeSql response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.executeSql(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('executeSql response %j', response);
return [response, options, rawResponse];
});
}
executeBatchDml(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('executeBatchDml request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('executeBatchDml response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.executeBatchDml(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('executeBatchDml response %j', response);
return [response, options, rawResponse];
});
}
read(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('read request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('read response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.read(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('read response %j', response);
return [response, options, rawResponse];
});
}
beginTransaction(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('beginTransaction request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('beginTransaction response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.beginTransaction(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('beginTransaction response %j', response);
return [response, options, rawResponse];
});
}
commit(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('commit request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('commit response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.commit(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('commit response %j', response);
return [response, options, rawResponse];
});
}
rollback(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('rollback request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('rollback response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.rollback(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('rollback response %j', response);
return [response, options, rawResponse];
});
}
partitionQuery(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('partitionQuery request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('partitionQuery response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.partitionQuery(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('partitionQuery response %j', response);
return [response, options, rawResponse];
});
}
partitionRead(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('partitionRead request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('partitionRead response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.partitionRead(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('partitionRead response %j', response);
return [response, options, rawResponse];
});
}
/**
* Like {@link protos.google.spanner.v1.Spanner.ExecuteSql|ExecuteSql}, except returns the
* result set as a stream. Unlike
* {@link protos.google.spanner.v1.Spanner.ExecuteSql|ExecuteSql}, there is no limit on
* the size of the returned result set. However, no individual row in the
* result set can exceed 100 MiB, and no column value can exceed 10 MiB.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.session
* Required. The session in which the SQL query should be performed.
* @param {google.spanner.v1.TransactionSelector} request.transaction
* The transaction to use.
*
* For queries, if none is provided, the default is a temporary read-only
* transaction with strong concurrency.
*
* Standard DML statements require a read-write transaction. To protect
* against replays, single-use transactions are not supported. The caller
* must either supply an existing transaction ID or begin a new transaction.
*
* Partitioned DML requires an existing Partitioned DML transaction ID.
* @param {string} request.sql
* Required. The SQL string.
* @param {google.protobuf.Struct} request.params
* Parameter names and values that bind to placeholders in the SQL string.
*
* A parameter placeholder consists of the `@` character followed by the
* parameter name (for example, `@firstName`). Parameter names must conform
* to the naming requirements of identifiers as specified at
* https://cloud.google.com/spanner/docs/lexical#identifiers.
*
* Parameters can appear anywhere that a literal value is expected. The same
* parameter name can be used more than once, for example:
*
* `"WHERE id > @msg_id AND id < @msg_id + 100"`
*
* It is an error to execute a SQL statement with unbound parameters.
* @param {number[]} request.paramTypes
* It is not always possible for Cloud Spanner to infer the right SQL type
* from a JSON value. For example, values of type `BYTES` and values
* of type `STRING` both appear in
* {@link protos.google.spanner.v1.ExecuteSqlRequest.params|params} as JSON strings.
*
* In these cases, `param_types` can be used to specify the exact
* SQL type for some or all of the SQL statement parameters. See the
* definition of {@link protos.google.spanner.v1.Type|Type} for more information
* about SQL types.
* @param {Buffer} request.resumeToken
* If this request is resuming a previously interrupted SQL statement
* execution, `resume_token` should be copied from the last
* {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} yielded before the
* interruption. Doing this enables the new SQL statement execution to resume
* where the last one left off. The rest of the request parameters must
* exactly match the request that yielded this token.
* @param {google.spanner.v1.ExecuteSqlRequest.QueryMode} request.queryMode
* Used to control the amount of debugging information returned in
* {@link protos.google.spanner.v1.ResultSetStats|ResultSetStats}. If
* {@link protos.google.spanner.v1.ExecuteSqlRequest.partition_token|partition_token} is
* set, {@link protos.google.spanner.v1.ExecuteSqlRequest.query_mode|query_mode} can only
* be set to
* {@link protos.google.spanner.v1.ExecuteSqlRequest.QueryMode.NORMAL|QueryMode.NORMAL}.
* @param {Buffer} request.partitionToken
* If present, results will be restricted to the specified partition
* previously created using PartitionQuery(). There must be an exact
* match for the values of fields common to this message and the
* PartitionQueryRequest message used to create this partition_token.
* @param {number} request.seqno
* A per-transaction sequence number used to identify this request. This field
* makes each request idempotent such that if the request is received multiple
* times, at most one will succeed.
*
* The sequence number must be monotonically increasing within the
* transaction. If a request arrives for the first time with an out-of-order
* sequence number, the transaction may be aborted. Replays of previously
* handled requests will yield the same response as the first execution.
*
* Required for DML statements. Ignored for queries.
* @param {google.spanner.v1.ExecuteSqlRequest.QueryOptions} request.queryOptions
* Query optimizer configuration to use for the given query.
* @param {google.spanner.v1.RequestOptions} request.requestOptions
* Common options for this request.
* @param {google.spanner.v1.DirectedReadOptions} request.directedReadOptions
* Directed read options for this request.
* @param {boolean} request.dataBoostEnabled
* If this is for a partitioned query and this field is set to `true`, the
* request is executed with Spanner Data Boost independent compute resources.
*
* If the field is set to `true` but the request does not set
* `partition_token`, the API returns an `INVALID_ARGUMENT` error.
* @param {boolean} [request.lastStatement]
* Optional. If set to true, this statement marks the end of the transaction.
* The transaction should be committed or aborted after this statement
* executes, and attempts to execute any other requests against this
* transaction (including reads and queries) will be rejected.
*
* For DML statements, setting this option may cause some error reporting to
* be deferred until commit time (e.g. validation of unique constraints).
* Given this, successful execution of a DML statement should not be assumed
* until a subsequent Commit call completes successfully.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} on 'data' event.
* Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation }
* for more details and examples.
*/
executeStreamingSql(request, options) {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('executeStreamingSql stream %j', options);
return this.innerApiCalls.executeStreamingSql(request, options);
}
/**
* Like {@link protos.google.spanner.v1.Spanner.Read|Read}, except returns the result set
* as a stream. Unlike {@link protos.google.spanner.v1.Spanner.Read|Read}, there is no
* limit on the size of the returned result set. However, no individual row in
* the result set can exceed 100 MiB, and no column value can exceed
* 10 MiB.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.session
* Required. The session in which the read should be performed.
* @param {google.spanner.v1.TransactionSelector} request.transaction
* The transaction to use. If none is provided, the default is a
* temporary read-only transaction with strong concurrency.
* @param {string} request.table
* Required. The name of the table in the database to be read.
* @param {string} request.index
* If non-empty, the name of an index on
* {@link protos.google.spanner.v1.ReadRequest.table|table}. This index is used instead of
* the table primary key when interpreting
* {@link protos.google.spanner.v1.ReadRequest.key_set|key_set} and sorting result rows.
* See {@link protos.google.spanner.v1.ReadRequest.key_set|key_set} for further
* information.
* @param {string[]} request.columns
* Required. The columns of {@link protos.google.spanner.v1.ReadRequest.table|table} to be
* returned for each row matching this request.
* @param {google.spanner.v1.KeySet} request.keySet
* Required. `key_set` identifies the rows to be yielded. `key_set` names the
* primary keys of the rows in {@link protos.google.spanner.v1.ReadRequest.table|table} to
* be yielded, unless {@link protos.google.spanner.v1.ReadRequest.index|index} is present.
* If {@link protos.google.spanner.v1.ReadRequest.index|index} is present, then
* {@link protos.google.spanner.v1.ReadRequest.key_set|key_set} instead names index keys
* in {@link protos.google.spanner.v1.ReadRequest.index|index}.
*
* If the {@link protos.google.spanner.v1.ReadRequest.partition_token|partition_token}
* field is empty, rows are yielded in table primary key order (if
* {@link protos.google.spanner.v1.ReadRequest.index|index} is empty) or index key order
* (if {@link protos.google.spanner.v1.ReadRequest.index|index} is non-empty). If the
* {@link protos.google.spanner.v1.ReadRequest.partition_token|partition_token} field is
* not empty, rows will be yielded in an unspecified order.
*
* It is not an error for the `key_set` to name rows that do not
* exist in the database. Read yields nothing for nonexistent rows.
* @param {number} request.limit
* If greater than zero, only the first `limit` rows are yielded. If `limit`
* is zero, the default is no limit. A limit cannot be specified if
* `partition_token` is set.
* @param {Buffer} request.resumeToken
* If this request is resuming a previously interrupted read,
* `resume_token` should be copied from the last
* {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} yielded before the
* interruption. Doing this enables the new read to resume where the last read
* left off. The rest of the request parameters must exactly match the request
* that yielded this token.
* @param {Buffer} request.partitionToken
* If present, results will be restricted to the specified partition
* previously created using PartitionRead(). There must be an exact
* match for the values of fields common to this message and the
* PartitionReadRequest message used to create this partition_token.
* @param {google.spanner.v1.RequestOptions} request.requestOptions
* Common options for this request.
* @param {google.spanner.v1.DirectedReadOptions} request.directedReadOptions
* Directed read options for this request.
* @param {boolean} request.dataBoostEnabled
* If this is for a partitioned read and this field is set to `true`, the
* request is executed with Spanner Data Boost independent compute resources.
*
* If the field is set to `true` but the request does not set
* `partition_token`, the API returns an `INVALID_ARGUMENT` error.
* @param {google.spanner.v1.ReadRequest.OrderBy} [request.orderBy]
* Optional. Order for the returned rows.
*
* By default, Spanner will return result rows in primary key order except for
* PartitionRead requests. For applications that do not require rows to be
* returned in primary key (`ORDER_BY_PRIMARY_KEY`) order, setting
* `ORDER_BY_NO_ORDER` option allows Spanner to optimize row retrieval,
* resulting in lower latencies in certain cases (e.g. bulk point lookups).
* @param {google.spanner.v1.ReadRequest.LockHint} [request.lockHint]
* Optional. Lock Hint for the request, it can only be used with read-write
* transactions.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} on 'data' event.
* Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation }
* for more details and examples.
*/
streamingRead(request, options) {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('streamingRead stream %j', options);
return this.innerApiCalls.streamingRead(request, options);
}
/**
* Batches the supplied mutation groups in a collection of efficient
* transactions. All mutations in a group are committed atomically. However,
* mutations across groups can be committed non-atomically in an unspecified
* order and thus, they must be independent of each other. Partial failure is
* possible, i.e., some groups may have been committed successfully, while
* some may have failed. The results of individual batches are streamed into
* the response as the batches are applied.
*
* BatchWrite requests are not replay protected, meaning that each mutation
* group may be applied more than once. Replays of non-idempotent mutations
* may have undesirable effects. For example, replays of an insert mutation
* may produce an already exists error or if you use generated or commit
* timestamp-based keys, it may result in additional rows being added to the
* mutation's table. We recommend structuring your mutation groups to be
* idempotent to avoid this issue.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.session
* Required. The session in which the batch request is to be run.
* @param {google.spanner.v1.RequestOptions} request.requestOptions
* Common options for this request.
* @param {number[]} request.mutationGroups
* Required. The groups of mutations to be applied.
* @param {boolean} [request.excludeTxnFromChangeStreams]
* Optional. When `exclude_txn_from_change_streams` is set to `true`:
* * Mutations from all transactions in this batch write operation will not
* be recorded in change streams with DDL option `allow_txn_exclusion=true`
* that are tracking columns modified by these transactions.
* * Mutations from all transactions in this batch write operation will be
* recorded in change streams with DDL option `allow_txn_exclusion=false or
* not set` that are tracking columns modified by these transactions.
*
* When `exclude_txn_from_change_streams` is set to `false` or not set,
* mutations from all transactions in this batch write operation will be
* recorded in all change streams that are tracking columns modified by these
* transactions.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits {@link protos.google.spanner.v1.BatchWriteResponse|BatchWriteResponse} on 'data' event.
* Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation }
* for more details and examples.
*/
batchWrite(request, options) {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
session: request.session ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('batchWrite stream %j', options);
return this.innerApiCalls.batchWrite(request, options);
}
listSessions(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
database: request.database ?? '',
});
this.initialize().catch(err => {
throw err;
});
const wrappedCallback = callback
? (error, values, nextPageRequest, rawResponse) => {
this._log.info('listSessions values %j', values);
callback(error, values, nextPageRequest, rawResponse); // We verified callback above.
}
: undefined;
this._log.info(