@google-cloud/spanner 7.18.0 → 7.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +1 -0
  3. package/build/protos/google/spanner/admin/database/v1/backup.proto +757 -0
  4. package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +230 -0
  5. package/build/protos/google/spanner/admin/database/v1/common.proto +132 -0
  6. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +1209 -0
  7. package/build/protos/google/spanner/admin/instance/v1/common.proto +64 -0
  8. package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +2110 -0
  9. package/build/protos/google/spanner/executor/v1/cloud_executor.proto +1520 -0
  10. package/build/protos/google/spanner/v1/commit_response.proto +59 -0
  11. package/build/protos/google/spanner/v1/keys.proto +163 -0
  12. package/build/protos/google/spanner/v1/mutation.proto +107 -0
  13. package/build/protos/google/spanner/v1/query_plan.proto +128 -0
  14. package/build/protos/google/spanner/v1/result_set.proto +237 -0
  15. package/build/protos/google/spanner/v1/spanner.proto +1389 -0
  16. package/build/protos/google/spanner/v1/transaction.proto +575 -0
  17. package/build/protos/google/spanner/v1/type.proto +214 -0
  18. package/build/protos/protos.d.ts +39317 -0
  19. package/build/protos/protos.js +100360 -0
  20. package/build/protos/protos.json +10271 -0
  21. package/build/src/backup.d.ts +349 -0
  22. package/build/src/backup.js +246 -0
  23. package/build/src/batch-transaction.d.ts +247 -0
  24. package/build/src/batch-transaction.js +384 -0
  25. package/build/src/codec.d.ts +362 -0
  26. package/build/src/codec.js +791 -0
  27. package/build/src/common-grpc/service-object.d.ts +80 -0
  28. package/build/src/common-grpc/service-object.js +101 -0
  29. package/build/src/common-grpc/service.d.ts +445 -0
  30. package/build/src/common-grpc/service.js +826 -0
  31. package/build/src/common.d.ts +66 -0
  32. package/build/src/common.js +54 -0
  33. package/build/src/database.d.ts +2103 -0
  34. package/build/src/database.js +1655 -0
  35. package/build/src/extra_proto_list.json +1 -0
  36. package/build/src/helper.d.ts +45 -0
  37. package/build/src/helper.js +71 -0
  38. package/build/src/index.d.ts +1195 -0
  39. package/build/src/index.js +1059 -0
  40. package/build/src/instance-config.d.ts +294 -0
  41. package/build/src/instance-config.js +216 -0
  42. package/build/src/instance.d.ts +832 -0
  43. package/build/src/instance.js +781 -0
  44. package/build/src/instrument.d.ts +85 -0
  45. package/build/src/instrument.js +215 -0
  46. package/build/src/multiplexed-session.d.ts +136 -0
  47. package/build/src/multiplexed-session.js +197 -0
  48. package/build/src/partial-result-stream.d.ts +253 -0
  49. package/build/src/partial-result-stream.js +400 -0
  50. package/build/src/session-factory.d.ts +100 -0
  51. package/build/src/session-factory.js +93 -0
  52. package/build/src/session-pool.d.ts +471 -0
  53. package/build/src/session-pool.js +754 -0
  54. package/build/src/session.d.ts +258 -0
  55. package/build/src/session.js +348 -0
  56. package/build/src/spanner_grpc_config.json +92 -0
  57. package/build/src/table.d.ts +831 -0
  58. package/build/src/table.js +277 -0
  59. package/build/src/transaction-runner.d.ts +185 -0
  60. package/build/src/transaction-runner.js +282 -0
  61. package/build/src/transaction.d.ts +1691 -0
  62. package/build/src/transaction.js +2004 -0
  63. package/build/src/v1/database_admin_client.d.ts +2301 -0
  64. package/build/src/v1/database_admin_client.js +2286 -0
  65. package/build/src/v1/database_admin_client_config.json +160 -0
  66. package/build/src/v1/database_admin_proto_list.json +6 -0
  67. package/build/src/v1/gapic_metadata.json +27 -0
  68. package/build/src/v1/index.d.ts +4 -0
  69. package/build/src/v1/index.js +29 -0
  70. package/build/src/v1/instance_admin_client.d.ts +1985 -0
  71. package/build/src/v1/instance_admin_client.js +1768 -0
  72. package/build/src/v1/instance_admin_client_config.json +129 -0
  73. package/build/src/v1/instance_admin_proto_list.json +4 -0
  74. package/build/src/v1/spanner_client.d.ts +1250 -0
  75. package/build/src/v1/spanner_client.js +1086 -0
  76. package/build/src/v1/spanner_client_config.json +119 -0
  77. package/build/src/v1/spanner_executor_proxy_client.d.ts +418 -0
  78. package/build/src/v1/spanner_executor_proxy_client.js +706 -0
  79. package/build/src/v1/spanner_executor_proxy_client_config.json +30 -0
  80. package/build/src/v1/spanner_executor_proxy_proto_list.json +14 -0
  81. package/build/src/v1/spanner_proto_list.json +10 -0
  82. package/package.json +1 -1
@@ -0,0 +1,1655 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright 2016 Google Inc. All Rights Reserved.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.Database = void 0;
19
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
20
+ const common = require('./common-grpc/service-object');
21
+ const promisify_1 = require("@google-cloud/promisify");
22
+ const extend = require("extend");
23
+ const streamEvents = require("stream-events");
24
+ const through = require("through2");
25
+ const google_gax_1 = require("google-gax");
26
+ const backup_1 = require("./backup");
27
+ const batch_transaction_1 = require("./batch-transaction");
28
+ const session_factory_1 = require("./session-factory");
29
+ const session_1 = require("./session");
30
+ const session_pool_1 = require("./session-pool");
31
+ const table_1 = require("./table");
32
+ const transaction_runner_1 = require("./transaction-runner");
33
+ const common_1 = require("./common");
34
+ const stream_1 = require("stream");
35
+ const arrify = require("arrify");
36
+ const snakeCase = require("lodash.snakecase");
37
+ const instrument_1 = require("./instrument");
38
+ /**
39
+ * Create a Database object to interact with a Cloud Spanner database.
40
+ *
41
+ * @class
42
+ *
43
+ * @param {string} name Name of the database.
44
+ * @param {SessionPoolOptions|SessionPoolInterface} options Session pool
45
+ * configuration options or custom pool interface.
46
+ * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} queryOptions
47
+ * The default query options to use for queries on the database.
48
+ *
49
+ * @example
50
+ * ```
51
+ * const {Spanner} = require('@google-cloud/spanner');
52
+ * const spanner = new Spanner();
53
+ * const instance = spanner.instance('my-instance');
54
+ * const database = instance.database('my-database');
55
+ * ```
56
+ */
57
+ class Database extends common.GrpcServiceObject {
58
+ constructor(instance, name, poolOptions, queryOptions) {
59
+ var _a;
60
+ const methods = {
61
+ /**
62
+ * Create a database.
63
+ *
64
+ * @method Database#create
65
+ * @param {CreateDatabaseRequest} [options] Configuration object.
66
+ * @param {CreateDatabaseCallback} [callback] Callback function.
67
+ * @returns {Promise<CreateDatabaseResponse>}
68
+ *
69
+ * @example
70
+ * ```
71
+ * const {Spanner} = require('@google-cloud/spanner');
72
+ * const spanner = new Spanner();
73
+ * const instance = spanner.instance('my-instance');
74
+ * const database = instance.database('my-database');
75
+ *
76
+ * database.create(function(err, database, operation, apiResponse) {
77
+ * if (err) {
78
+ * // Error handling omitted.
79
+ * }
80
+ *
81
+ * operation
82
+ * .on('error', function(err) {})
83
+ * .on('complete', function() {
84
+ * // Database created successfully.
85
+ * });
86
+ * });
87
+ *
88
+ * //-
89
+ * // If the callback is omitted, we'll return a Promise.
90
+ * //-
91
+ * database.create()
92
+ * .then(function(data) {
93
+ * const operation = data[0];
94
+ * const apiResponse = data[1];
95
+ *
96
+ * return operation.promise();
97
+ * })
98
+ * .then(function() {
99
+ * // Database created successfully.
100
+ * });
101
+ * ```
102
+ */
103
+ create: true,
104
+ };
105
+ const formattedName_ = Database.formatName_(instance.formattedName_, name);
106
+ super({
107
+ parent: instance,
108
+ id: name,
109
+ methods,
110
+ createMethod: (_, options, callback) => {
111
+ const pool = this.pool_;
112
+ if (pool._pending > 0) {
113
+ // If there are BatchCreateSessions requests pending, then we should
114
+ // wait until these have finished before we try to create the database.
115
+ // Otherwise the results of these requests might be propagated to
116
+ // client requests that are submitted after the database has been
117
+ // created. If the pending requests have not finished within 10 seconds,
118
+ // they will be ignored and the database creation will proceed.
119
+ let timeout;
120
+ const promises = [
121
+ new Promise(resolve => (timeout = setTimeout(resolve, 10000))),
122
+ new Promise(resolve => {
123
+ pool
124
+ .on('available', () => {
125
+ if (pool._pending === 0) {
126
+ clearTimeout(timeout);
127
+ resolve();
128
+ }
129
+ })
130
+ .on('createError', () => {
131
+ if (pool._pending === 0) {
132
+ clearTimeout(timeout);
133
+ resolve();
134
+ }
135
+ });
136
+ }),
137
+ ];
138
+ Promise.race(promises).then(() => instance.createDatabase(formattedName_, options, callback));
139
+ }
140
+ else {
141
+ return instance.createDatabase(formattedName_, options, callback);
142
+ }
143
+ },
144
+ });
145
+ if (typeof poolOptions === 'object') {
146
+ this.databaseRole = poolOptions.databaseRole || null;
147
+ this.labels = poolOptions.labels || null;
148
+ }
149
+ this.formattedName_ = formattedName_;
150
+ this.instance = instance;
151
+ this._observabilityOptions = instance._observabilityOptions;
152
+ this._traceConfig = {
153
+ opts: this._observabilityOptions,
154
+ dbName: this.formattedName_,
155
+ };
156
+ this.request = instance.request;
157
+ this._observabilityOptions = instance._observabilityOptions;
158
+ this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.formattedName_, (_a = this._observabilityOptions) === null || _a === void 0 ? void 0 : _a.enableEndToEndTracing);
159
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
160
+ this.requestStream = instance.requestStream;
161
+ this.sessionFactory_ = new session_factory_1.SessionFactory(this, name, poolOptions);
162
+ this.pool_ = this.sessionFactory_.getPool();
163
+ const sessionPoolInstance = this.pool_;
164
+ if (sessionPoolInstance) {
165
+ sessionPoolInstance._observabilityOptions =
166
+ instance._observabilityOptions;
167
+ }
168
+ this.queryOptions_ = Object.assign(Object.assign({}, queryOptions), Database.getEnvironmentQueryOptions());
169
+ }
170
+ setMetadata(metadata, optionsOrCallback, cb) {
171
+ const gaxOpts = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
172
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
173
+ const reqOpts = {
174
+ database: extend({
175
+ name: this.formattedName_,
176
+ }, metadata),
177
+ updateMask: {
178
+ paths: Object.keys(metadata).map(snakeCase),
179
+ },
180
+ };
181
+ return this.request({
182
+ client: 'DatabaseAdminClient',
183
+ method: 'updateDatabase',
184
+ reqOpts,
185
+ gaxOpts,
186
+ headers: this.commonHeaders_,
187
+ }, callback);
188
+ }
189
+ static getEnvironmentQueryOptions() {
190
+ const options = {};
191
+ if (process.env.SPANNER_OPTIMIZER_VERSION) {
192
+ options.optimizerVersion = process.env.SPANNER_OPTIMIZER_VERSION;
193
+ }
194
+ if (process.env.SPANNER_OPTIMIZER_STATISTICS_PACKAGE) {
195
+ options.optimizerStatisticsPackage =
196
+ process.env.SPANNER_OPTIMIZER_STATISTICS_PACKAGE;
197
+ }
198
+ return options;
199
+ }
200
+ batchCreateSessions(options, callback) {
201
+ if (typeof options === 'number') {
202
+ options = { count: options };
203
+ }
204
+ const count = options.count;
205
+ const labels = options.labels || {};
206
+ const databaseRole = options.databaseRole || this.databaseRole || null;
207
+ const reqOpts = {
208
+ database: this.formattedName_,
209
+ sessionTemplate: { labels: labels, creatorRole: databaseRole },
210
+ sessionCount: count,
211
+ };
212
+ const headers = this.commonHeaders_;
213
+ if (this._getSpanner().routeToLeaderEnabled) {
214
+ (0, common_1.addLeaderAwareRoutingHeader)(headers);
215
+ }
216
+ (0, instrument_1.startTrace)('Database.batchCreateSessions', this._traceConfig, span => {
217
+ this.request({
218
+ client: 'SpannerClient',
219
+ method: 'batchCreateSessions',
220
+ reqOpts,
221
+ gaxOpts: options.gaxOptions,
222
+ headers: headers,
223
+ }, (err, resp) => {
224
+ if (err) {
225
+ (0, instrument_1.setSpanError)(span, err);
226
+ span.end();
227
+ callback(err, null, resp);
228
+ return;
229
+ }
230
+ const sessions = (resp.session || []).map(metadata => {
231
+ const session = this.session(metadata.name);
232
+ session._observabilityOptions = this._traceConfig.opts;
233
+ session.metadata = metadata;
234
+ return session;
235
+ });
236
+ span.end();
237
+ callback(null, sessions, resp);
238
+ });
239
+ });
240
+ }
241
+ /**
242
+ * Get a reference to a {@link BatchTransaction} object.
243
+ *
244
+ * @see {@link BatchTransaction#identifier} to generate an identifier.
245
+ *
246
+ * @param {TransactionIdentifier} identifier The transaction identifier.
247
+ * @param {object} [options] [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds).
248
+ * @returns {BatchTransaction} A batch transaction object.
249
+ *
250
+ * @example
251
+ * ```
252
+ * const {Spanner} = require('@google-cloud/spanner');
253
+ * const spanner = new Spanner();
254
+ *
255
+ * const instance = spanner.instance('my-instance');
256
+ * const database = instance.database('my-database');
257
+ *
258
+ * const transaction = database.batchTransaction({
259
+ * session: 'my-session',
260
+ * transaction: 'my-transaction',
261
+ * readTimestamp: 1518464696657
262
+ * });
263
+ * ```
264
+ */
265
+ batchTransaction(identifier, options) {
266
+ const session = typeof identifier.session === 'string'
267
+ ? this.session(identifier.session)
268
+ : identifier.session;
269
+ const id = identifier.transaction;
270
+ const transaction = new batch_transaction_1.BatchTransaction(session, options);
271
+ transaction.id = id;
272
+ transaction._observabilityOptions = this._traceConfig.opts;
273
+ transaction.readTimestamp = identifier.timestamp;
274
+ return transaction;
275
+ }
276
+ close(callback) {
277
+ const key = this.id.split('/').pop();
278
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
279
+ this.parent.databases_.delete(key);
280
+ this.pool_.close(callback);
281
+ }
282
+ createBatchTransaction(optionsOrCallback, cb) {
283
+ const callback = typeof optionsOrCallback === 'function'
284
+ ? optionsOrCallback
285
+ : cb;
286
+ const options = typeof optionsOrCallback === 'object'
287
+ ? optionsOrCallback
288
+ : {};
289
+ return (0, instrument_1.startTrace)('Database.createBatchTransaction', this._traceConfig, span => {
290
+ this.pool_.getSession((err, session) => {
291
+ if (err) {
292
+ (0, instrument_1.setSpanError)(span, err);
293
+ span.end();
294
+ callback(err, null, undefined);
295
+ return;
296
+ }
297
+ const transaction = this.batchTransaction({ session: session }, options);
298
+ this._releaseOnEnd(session, transaction, span);
299
+ transaction.begin((err, resp) => {
300
+ if (err) {
301
+ (0, instrument_1.setSpanError)(span, err);
302
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
303
+ span.addEvent('No session available', {
304
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
305
+ });
306
+ }
307
+ span.end();
308
+ callback(err, null, resp);
309
+ return;
310
+ }
311
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
312
+ span.end();
313
+ callback(null, transaction, resp);
314
+ });
315
+ });
316
+ });
317
+ }
318
+ createSession(optionsOrCallback, cb) {
319
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
320
+ const options = typeof optionsOrCallback === 'object' && optionsOrCallback
321
+ ? extend({}, optionsOrCallback)
322
+ : {};
323
+ const reqOpts = {
324
+ database: this.formattedName_,
325
+ };
326
+ reqOpts.session = {};
327
+ if (options.multiplexed) {
328
+ reqOpts.session.multiplexed = options.multiplexed;
329
+ }
330
+ reqOpts.session.labels = options.labels || this.labels || null;
331
+ reqOpts.session.creatorRole =
332
+ options.databaseRole || this.databaseRole || null;
333
+ const headers = this.commonHeaders_;
334
+ if (this._getSpanner().routeToLeaderEnabled) {
335
+ (0, common_1.addLeaderAwareRoutingHeader)(headers);
336
+ }
337
+ (0, instrument_1.startTrace)('Database.createSession', this._traceConfig, span => {
338
+ this.request({
339
+ client: 'SpannerClient',
340
+ method: 'createSession',
341
+ reqOpts,
342
+ gaxOpts: options.gaxOptions,
343
+ headers: headers,
344
+ }, (err, resp) => {
345
+ if (err) {
346
+ (0, instrument_1.setSpanError)(span, err);
347
+ span.end();
348
+ callback(err, null, resp);
349
+ return;
350
+ }
351
+ const session = this.session(resp.name);
352
+ session.metadata = resp;
353
+ span.end();
354
+ callback(null, session, resp);
355
+ });
356
+ });
357
+ }
358
+ createTable(schema, gaxOptionsOrCallback, cb) {
359
+ const gaxOptions = typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {};
360
+ const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb;
361
+ this.updateSchema(schema, gaxOptions, (err, operation, resp) => {
362
+ if (err) {
363
+ callback(err, null, null, resp);
364
+ return;
365
+ }
366
+ const tableName = schema.match(/CREATE TABLE `*([^\s`(]+)/)[1];
367
+ const table = this.table(tableName);
368
+ table._observabilityOptions = this._traceConfig.opts;
369
+ callback(null, table, operation, resp);
370
+ });
371
+ }
372
+ /**
373
+ * Decorates transaction so that when end() is called it will return the session
374
+ * back into the pool.
375
+ *
376
+ * @private
377
+ *
378
+ * @param {Session} session The session to release.
379
+ * @param {Transaction} transaction The transaction to observe.
380
+ * @returns {Transaction}
381
+ */
382
+ _releaseOnEnd(session, transaction, span) {
383
+ transaction.once('end', () => {
384
+ try {
385
+ this.pool_.release(session);
386
+ }
387
+ catch (e) {
388
+ (0, instrument_1.setSpanErrorAndException)(span, e);
389
+ this.emit('error', e);
390
+ }
391
+ finally {
392
+ span.end();
393
+ }
394
+ });
395
+ }
396
+ delete(optionsOrCallback, cb) {
397
+ const gaxOpts = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
398
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
399
+ const reqOpts = {
400
+ database: this.formattedName_,
401
+ };
402
+ this.close(() => {
403
+ this.request({
404
+ client: 'DatabaseAdminClient',
405
+ method: 'dropDatabase',
406
+ reqOpts,
407
+ gaxOpts,
408
+ headers: this.commonHeaders_,
409
+ }, callback);
410
+ });
411
+ }
412
+ exists(gaxOptionsOrCallback, cb) {
413
+ const gaxOptions = typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {};
414
+ const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb;
415
+ const NOT_FOUND = 5;
416
+ this.getMetadata(gaxOptions, err => {
417
+ if (err && err.code !== NOT_FOUND) {
418
+ callback(err);
419
+ return;
420
+ }
421
+ const exists = !err || err.code !== NOT_FOUND;
422
+ callback(null, exists);
423
+ });
424
+ }
425
+ get(optionsOrCallback, cb) {
426
+ const options = typeof optionsOrCallback === 'object'
427
+ ? optionsOrCallback
428
+ : {};
429
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
430
+ this.getMetadata(options.gaxOptions, (err, metadata) => {
431
+ if (err) {
432
+ if (options.autoCreate && err.code === 5) {
433
+ this.create(options, (err, database, operation) => {
434
+ if (err) {
435
+ callback(err);
436
+ return;
437
+ }
438
+ operation
439
+ .on('error', callback)
440
+ .on('complete', (metadata) => {
441
+ this.metadata = metadata;
442
+ callback(null, this, metadata);
443
+ });
444
+ });
445
+ return;
446
+ }
447
+ callback(err);
448
+ return;
449
+ }
450
+ callback(null, this, metadata);
451
+ });
452
+ }
453
+ getMetadata(gaxOptionsOrCallback, cb) {
454
+ const callback = typeof gaxOptionsOrCallback === 'function'
455
+ ? gaxOptionsOrCallback
456
+ : cb;
457
+ const gaxOpts = typeof gaxOptionsOrCallback === 'object'
458
+ ? gaxOptionsOrCallback
459
+ : {};
460
+ const reqOpts = {
461
+ name: this.formattedName_,
462
+ };
463
+ return this.request({
464
+ client: 'DatabaseAdminClient',
465
+ method: 'getDatabase',
466
+ reqOpts,
467
+ gaxOpts,
468
+ headers: this.commonHeaders_,
469
+ }, (err, resp) => {
470
+ if (resp) {
471
+ this.metadata = resp;
472
+ }
473
+ callback(err, resp);
474
+ });
475
+ }
476
+ async getRestoreInfo(optionsOrCallback) {
477
+ const gaxOptions = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
478
+ const [metadata] = await this.getMetadata(gaxOptions);
479
+ return metadata.restoreInfo ? metadata.restoreInfo : undefined;
480
+ }
481
+ async getState(optionsOrCallback) {
482
+ const gaxOptions = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
483
+ const [metadata] = await this.getMetadata(gaxOptions);
484
+ return metadata.state || undefined;
485
+ }
486
+ async getDatabaseDialect(optionsOrCallback, callback) {
487
+ const gaxOptions = typeof optionsOrCallback === 'object'
488
+ ? optionsOrCallback
489
+ : {};
490
+ const cb = typeof optionsOrCallback === 'function'
491
+ ? optionsOrCallback
492
+ : callback;
493
+ try {
494
+ if (this.databaseDialect === 'DATABASE_DIALECT_UNSPECIFIED' ||
495
+ this.databaseDialect === null ||
496
+ this.databaseDialect === undefined) {
497
+ const [metadata] = await this.getMetadata(gaxOptions);
498
+ this.databaseDialect = metadata.databaseDialect;
499
+ }
500
+ if (cb) {
501
+ cb(null, this.databaseDialect);
502
+ return;
503
+ }
504
+ return this.databaseDialect || undefined;
505
+ }
506
+ catch (err) {
507
+ cb(err);
508
+ return;
509
+ }
510
+ }
511
+ getSchema(optionsOrCallback, cb) {
512
+ const gaxOpts = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
513
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
514
+ const reqOpts = {
515
+ database: this.formattedName_,
516
+ };
517
+ this.request({
518
+ client: 'DatabaseAdminClient',
519
+ method: 'getDatabaseDdl',
520
+ reqOpts,
521
+ gaxOpts,
522
+ headers: this.commonHeaders_,
523
+ },
524
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
525
+ (err, statements, ...args) => {
526
+ callback(err, statements ? statements.statements : null, ...args);
527
+ });
528
+ }
529
+ getIamPolicy(optionsOrCallback, cb) {
530
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
531
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
532
+ const reqOpts = {
533
+ resource: this.formattedName_,
534
+ options: {
535
+ requestedPolicyVersion: options.requestedPolicyVersion || null,
536
+ },
537
+ };
538
+ this.request({
539
+ client: 'DatabaseAdminClient',
540
+ method: 'getIamPolicy',
541
+ reqOpts,
542
+ gaxOpts: options.gaxOptions,
543
+ headers: this.commonHeaders_,
544
+ }, (err, resp) => {
545
+ callback(err, resp);
546
+ });
547
+ }
548
+ getSessions(optionsOrCallback, cb) {
549
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
550
+ const self = this;
551
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
552
+ const options = typeof optionsOrCallback === 'object'
553
+ ? optionsOrCallback
554
+ : {};
555
+ const gaxOpts = extend(true, {}, options.gaxOptions);
556
+ let reqOpts = extend({}, options, {
557
+ database: this.formattedName_,
558
+ });
559
+ delete reqOpts.gaxOptions;
560
+ // Copy over pageSize and pageToken values from gaxOptions.
561
+ // However values set on options take precedence.
562
+ if (gaxOpts) {
563
+ reqOpts = extend({}, {
564
+ pageSize: gaxOpts.pageSize,
565
+ pageToken: gaxOpts.pageToken,
566
+ }, reqOpts);
567
+ delete gaxOpts.pageSize;
568
+ delete gaxOpts.pageToken;
569
+ }
570
+ return (0, instrument_1.startTrace)('Database.getSessions', this._traceConfig, span => {
571
+ this.request({
572
+ client: 'SpannerClient',
573
+ method: 'listSessions',
574
+ reqOpts,
575
+ gaxOpts,
576
+ headers: this.commonHeaders_,
577
+ }, (err, sessions, nextPageRequest, ...args) => {
578
+ if (err) {
579
+ (0, instrument_1.setSpanError)(span, err);
580
+ }
581
+ let sessionInstances = null;
582
+ if (sessions) {
583
+ sessionInstances = sessions.map(metadata => {
584
+ const session = self.session(metadata.name);
585
+ session.metadata = metadata;
586
+ session._observabilityOptions = this._traceConfig.opts;
587
+ return session;
588
+ });
589
+ }
590
+ span.end();
591
+ const nextQuery = nextPageRequest
592
+ ? extend({}, options, nextPageRequest)
593
+ : null;
594
+ callback(err, sessionInstances, nextQuery, ...args);
595
+ });
596
+ });
597
+ }
598
+ /**
599
+ * Get a list of sessions as a readable object stream.
600
+ *
601
+ * Wrapper around {@link v1.SpannerClient#listSessions}
602
+ *
603
+ * @see {@link v1.SpannerClient#listSessions}
604
+ * @see [ListSessions API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ListSessions)
605
+ *
606
+ * @method Spanner#getSessionsStream
607
+ * @param {GetSessionsOptions} [options] Options object for listing sessions.
608
+ * @returns {ReadableStream} A readable stream that emits {@link Session}
609
+ * instances.
610
+ *
611
+ * @example
612
+ * ```
613
+ * const {Spanner} = require('@google-cloud/spanner');
614
+ * const spanner = new Spanner();
615
+ *
616
+ * const instance = spanner.instance('my-instance');
617
+ * const database = instance.database('my-database');
618
+ *
619
+ * database.getSessionsStream()
620
+ * .on('error', console.error)
621
+ * .on('data', function(database) {
622
+ * // `sessions` is a `Session` object.
623
+ * })
624
+ * .on('end', function() {
625
+ * // All sessions retrieved.
626
+ * });
627
+ *
628
+ * //-
629
+ * // If you anticipate many results, you can end a stream early to prevent
630
+ * // unnecessary processing and API requests.
631
+ * //-
632
+ * database.getSessionsStream()
633
+ * .on('data', function(session) {
634
+ * this.end();
635
+ * });
636
+ * ```
637
+ */
638
+ getSessionsStream(options = {}) {
639
+ const gaxOpts = extend(true, {}, options.gaxOptions);
640
+ let reqOpts = extend({}, options, {
641
+ database: this.formattedName_,
642
+ });
643
+ delete reqOpts.gaxOptions;
644
+ // Copy over pageSize and pageToken values from gaxOptions.
645
+ // However values set on options take precedence.
646
+ if (gaxOpts) {
647
+ reqOpts = extend({}, {
648
+ pageSize: gaxOpts.pageSize,
649
+ pageToken: gaxOpts.pageToken,
650
+ }, reqOpts);
651
+ delete gaxOpts.pageSize;
652
+ delete gaxOpts.pageToken;
653
+ }
654
+ return this.requestStream({
655
+ client: 'SpannerClient',
656
+ method: 'listSessionsStream',
657
+ reqOpts,
658
+ gaxOpts,
659
+ headers: this.commonHeaders_,
660
+ });
661
+ }
662
+ getSnapshot(optionsOrCallback, cb) {
663
+ const callback = typeof optionsOrCallback === 'function'
664
+ ? optionsOrCallback
665
+ : cb;
666
+ const options = typeof optionsOrCallback === 'object'
667
+ ? optionsOrCallback
668
+ : {};
669
+ if (('maxStaleness' in options &&
670
+ options.maxStaleness !== null &&
671
+ options.maxStaleness !== undefined) ||
672
+ ('minReadTimestamp' in options &&
673
+ options.minReadTimestamp !== null &&
674
+ options.minReadTimestamp !== undefined)) {
675
+ const error = Object.assign(new Error('maxStaleness / minReadTimestamp is not supported for multi-use read-only transactions.'), {
676
+ code: 3, // invalid argument
677
+ });
678
+ callback(error);
679
+ return;
680
+ }
681
+ return (0, instrument_1.startTrace)('Database.getSnapshot', this._traceConfig, span => {
682
+ this.pool_.getSession((err, session) => {
683
+ if (err) {
684
+ (0, instrument_1.setSpanError)(span, err);
685
+ span.end();
686
+ callback(err);
687
+ return;
688
+ }
689
+ const snapshot = session.snapshot(options, this.queryOptions_);
690
+ snapshot.begin(err => {
691
+ if (err) {
692
+ (0, instrument_1.setSpanError)(span, err);
693
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
694
+ span.addEvent('No session available', {
695
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
696
+ });
697
+ session.lastError = err;
698
+ this.pool_.release(session);
699
+ span.end();
700
+ this.getSnapshot(options, callback);
701
+ }
702
+ else {
703
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
704
+ this.pool_.release(session);
705
+ span.end();
706
+ callback(err);
707
+ }
708
+ return;
709
+ }
710
+ this._releaseOnEnd(session, snapshot, span);
711
+ span.end();
712
+ callback(err, snapshot);
713
+ });
714
+ });
715
+ });
716
+ }
717
+ getTransaction(optionsOrCallback, callback) {
718
+ const cb = typeof optionsOrCallback === 'function'
719
+ ? optionsOrCallback
720
+ : callback;
721
+ const options = typeof optionsOrCallback === 'object' && optionsOrCallback
722
+ ? optionsOrCallback
723
+ : {};
724
+ return (0, instrument_1.startTrace)('Database.getTransaction', this._traceConfig, span => {
725
+ this.pool_.getSession((err, session, transaction) => {
726
+ if (options.requestOptions) {
727
+ transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
728
+ }
729
+ if (options.optimisticLock) {
730
+ transaction.useOptimisticLock();
731
+ }
732
+ if (options.excludeTxnFromChangeStreams) {
733
+ transaction.excludeTxnFromChangeStreams();
734
+ }
735
+ if (!err) {
736
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
737
+ transaction._observabilityOptions = this._observabilityOptions;
738
+ this._releaseOnEnd(session, transaction, span);
739
+ }
740
+ else {
741
+ (0, instrument_1.setSpanError)(span, err);
742
+ }
743
+ span.end();
744
+ cb(err, transaction);
745
+ });
746
+ });
747
+ }
748
+ async getOperations(optionsOrCallback) {
749
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
750
+ // Create a query that lists database operations only on this database from
751
+ // the instance. Operation name will be prefixed with the database path for
752
+ // all operations on this database
753
+ let dbSpecificFilter = `name:${this.formattedName_}`;
754
+ if (options && options.filter) {
755
+ dbSpecificFilter = `(${dbSpecificFilter}) AND (${options.filter})`;
756
+ }
757
+ const dbSpecificQuery = {
758
+ ...options,
759
+ filter: dbSpecificFilter,
760
+ };
761
+ return this.instance.getDatabaseOperations(dbSpecificQuery);
762
+ }
763
+ getDatabaseRoles(optionsOrCallback, cb) {
764
+ const gaxOpts = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
765
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
766
+ let reqOpts = {
767
+ parent: this.formattedName_,
768
+ };
769
+ // Copy over pageSize and pageToken values from gaxOptions.
770
+ // However, values set on options take precedence.
771
+ if (gaxOpts) {
772
+ reqOpts = extend({}, {
773
+ pageSize: gaxOpts.pageSize,
774
+ pageToken: gaxOpts.pageToken,
775
+ }, reqOpts);
776
+ delete gaxOpts.pageSize;
777
+ delete gaxOpts.pageToken;
778
+ }
779
+ this.request({
780
+ client: 'DatabaseAdminClient',
781
+ method: 'listDatabaseRoles',
782
+ reqOpts,
783
+ gaxOpts,
784
+ headers: this.commonHeaders_,
785
+ }, (err, roles, nextPageRequest, ...args) => {
786
+ const nextQuery = nextPageRequest
787
+ ? extend({}, gaxOpts, nextPageRequest)
788
+ : null;
789
+ callback(err, roles, nextQuery, ...args);
790
+ });
791
+ }
792
+ makePooledRequest_(config, callback) {
793
+ const pool = this.pool_;
794
+ pool.getSession((err, session) => {
795
+ if (err) {
796
+ callback(err, null);
797
+ return;
798
+ }
799
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
800
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
801
+ config.reqOpts.session = session.formattedName_;
802
+ this.request(config, (err, ...args) => {
803
+ pool.release(session);
804
+ callback(err, ...args);
805
+ });
806
+ });
807
+ }
808
+ /**
809
+ * Make an API request as a stream, first assuring an active session is used.
810
+ *
811
+ * @private
812
+ *
813
+ * @param {object} config Request config
814
+ * @returns {Stream}
815
+ */
816
+ makePooledStreamingRequest_(config) {
817
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
818
+ const self = this;
819
+ const pool = this.pool_;
820
+ let requestStream;
821
+ let session;
822
+ const waitForSessionStream = streamEvents(through.obj());
823
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
824
+ waitForSessionStream.abort = () => {
825
+ releaseSession();
826
+ if (requestStream) {
827
+ requestStream.cancel();
828
+ }
829
+ };
830
+ function destroyStream(err) {
831
+ waitForSessionStream.destroy(err);
832
+ }
833
+ function releaseSession() {
834
+ if (session) {
835
+ pool.release(session);
836
+ session = null;
837
+ }
838
+ }
839
+ waitForSessionStream.on('reading', () => {
840
+ pool.getSession((err, session_) => {
841
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
842
+ if (err) {
843
+ (0, instrument_1.setSpanError)(span, err);
844
+ destroyStream(err);
845
+ return;
846
+ }
847
+ span.addEvent('Using Session', { 'session.id': session_ === null || session_ === void 0 ? void 0 : session_.id });
848
+ session = session_;
849
+ config.reqOpts.session = session.formattedName_;
850
+ requestStream = self.requestStream(config);
851
+ requestStream
852
+ .on('error', releaseSession)
853
+ .on('error', destroyStream)
854
+ .on('end', releaseSession)
855
+ .pipe(waitForSessionStream);
856
+ });
857
+ });
858
+ return waitForSessionStream;
859
+ }
860
+ restore(backupName, optionsOrCallback, cb) {
861
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
862
+ const callback = typeof optionsOrCallback === 'function'
863
+ ? optionsOrCallback
864
+ : cb;
865
+ const gaxOpts = 'gaxOptions' in options
866
+ ? options.gaxOptions
867
+ : options;
868
+ const reqOpts = {
869
+ parent: this.instance.formattedName_,
870
+ databaseId: this.id,
871
+ backup: backup_1.Backup.formatName_(this.instance.formattedName_, backupName),
872
+ };
873
+ if ('encryptionConfig' in options &&
874
+ options.encryptionConfig) {
875
+ reqOpts.encryptionConfig = options.encryptionConfig;
876
+ }
877
+ return this.request({
878
+ client: 'DatabaseAdminClient',
879
+ method: 'restoreDatabase',
880
+ reqOpts,
881
+ gaxOpts,
882
+ headers: this.commonHeaders_,
883
+ }, (err, operation, resp) => {
884
+ if (err) {
885
+ callback(err, null, null, resp);
886
+ return;
887
+ }
888
+ callback(null, this, operation, resp);
889
+ });
890
+ }
891
+ run(query, optionsOrCallback, cb) {
892
+ let stats;
893
+ let metadata;
894
+ const rows = [];
895
+ const callback = typeof optionsOrCallback === 'function'
896
+ ? optionsOrCallback
897
+ : cb;
898
+ const options = typeof optionsOrCallback === 'object'
899
+ ? optionsOrCallback
900
+ : {};
901
+ const traceConfig = {
902
+ sql: query,
903
+ ...this._traceConfig,
904
+ };
905
+ return (0, instrument_1.startTrace)('Database.run', traceConfig, span => {
906
+ this.runStream(query, options)
907
+ .on('error', err => {
908
+ (0, instrument_1.setSpanError)(span, err);
909
+ span.end();
910
+ callback(err, rows, stats, metadata);
911
+ })
912
+ .on('response', response => {
913
+ if (response.metadata) {
914
+ metadata = response.metadata;
915
+ }
916
+ })
917
+ .on('stats', _stats => (stats = _stats))
918
+ .on('data', row => {
919
+ rows.push(row);
920
+ })
921
+ .on('end', () => {
922
+ span.end();
923
+ callback(null, rows, stats, metadata);
924
+ });
925
+ });
926
+ }
927
+ runPartitionedUpdate(query, callback) {
928
+ const traceConfig = {
929
+ sql: query,
930
+ ...this._traceConfig,
931
+ };
932
+ return (0, instrument_1.startTrace)('Database.runPartitionedUpdate', traceConfig, span => {
933
+ this.pool_.getSession((err, session) => {
934
+ if (err) {
935
+ (0, instrument_1.setSpanError)(span, err);
936
+ span.end();
937
+ callback(err, 0);
938
+ return;
939
+ }
940
+ this._runPartitionedUpdate(session, query, (err, count) => {
941
+ if (err) {
942
+ (0, instrument_1.setSpanError)(span, err);
943
+ }
944
+ span.end();
945
+ callback(err, count);
946
+ });
947
+ });
948
+ });
949
+ }
950
+ _runPartitionedUpdate(session, query, callback) {
951
+ const transaction = session.partitionedDml();
952
+ if (typeof query !== 'string' && query.excludeTxnFromChangeStreams) {
953
+ transaction.excludeTxnFromChangeStreams();
954
+ }
955
+ transaction.begin(err => {
956
+ if (err) {
957
+ this.pool_.release(session);
958
+ callback(err, 0);
959
+ return;
960
+ }
961
+ transaction.runUpdate(query, (err, updateCount) => {
962
+ if (err) {
963
+ if (err.code !== google_gax_1.grpc.status.ABORTED) {
964
+ this.pool_.release(session);
965
+ callback(err, 0);
966
+ return;
967
+ }
968
+ this._runPartitionedUpdate(session, query, callback);
969
+ }
970
+ else {
971
+ this.pool_.release(session);
972
+ callback(null, updateCount);
973
+ return;
974
+ }
975
+ });
976
+ });
977
+ }
978
+ /**
979
+ * Create a readable object stream to receive resulting rows from a SQL
980
+ * statement.
981
+ *
982
+ * Wrapper around {@link v1.SpannerClient#executeStreamingSql}.
983
+ *
984
+ * @see {@link v1.SpannerClient#executeStreamingSql}
985
+ * @see [Query Syntax](https://cloud.google.com/spanner/docs/query-syntax)
986
+ * @see [ExecuteSql API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ExecuteSql)
987
+ *
988
+ * @fires PartialResultStream#response
989
+ *
990
+ * @param {string|ExecuteSqlRequest} query A SQL query or
991
+ * {@link ExecuteSqlRequest} object.
992
+ * @param {TimestampBounds} [options] Snapshot timestamp bounds.
993
+ * @returns {PartialResultStream} A readable stream that emits rows.
994
+ *
995
+ * @example
996
+ * ```
997
+ * const {Spanner} = require('@google-cloud/spanner');
998
+ * const spanner = new Spanner();
999
+ *
1000
+ * const instance = spanner.instance('my-instance');
1001
+ * const database = instance.database('my-database');
1002
+ *
1003
+ * const query = 'SELECT * FROM Singers';
1004
+ *
1005
+ * database.runStream(query)
1006
+ * .on('error', function(err) {})
1007
+ * .on('data', function(row) {
1008
+ * // row = [
1009
+ * // {
1010
+ * // name: 'SingerId',
1011
+ * // value: '1'
1012
+ * // },
1013
+ * // {
1014
+ * // name: 'Name',
1015
+ * // value: 'Eddie Wilson'
1016
+ * // }
1017
+ * // ]
1018
+ * // ]
1019
+ * })
1020
+ * .on('end', function() {
1021
+ * // All results retrieved.
1022
+ * });
1023
+ *
1024
+ * //-
1025
+ * // Rows are returned as an array of objects. Each object has a `name` and
1026
+ * // `value` property. To get a serialized object, call `toJSON()`.
1027
+ * //-
1028
+ * database.runStream(query)
1029
+ * .on('error', function(err) {})
1030
+ * .on('data', function(row) {
1031
+ * // row.toJSON() = {
1032
+ * // SingerId: '1',
1033
+ * // Name: 'Eddie Wilson'
1034
+ * // }
1035
+ * })
1036
+ * .on('end', function() {
1037
+ * // All results retrieved.
1038
+ * });
1039
+ *
1040
+ * //-
1041
+ * // Alternatively, set `query.json` to `true`, and this step will be performed
1042
+ * // automatically.
1043
+ * //-
1044
+ * query.json = true;
1045
+ *
1046
+ * database.runStream(query)
1047
+ * .on('error', function(err) {})
1048
+ * .on('data', function(row) {
1049
+ * // row = {
1050
+ * // SingerId: '1',
1051
+ * // Name: 'Eddie Wilson'
1052
+ * // }
1053
+ * })
1054
+ * .on('end', function() {
1055
+ * // All results retrieved.
1056
+ * });
1057
+ *
1058
+ * //-
1059
+ * // The SQL query string can contain parameter placeholders. A parameter
1060
+ * // placeholder consists of '@' followed by the parameter name.
1061
+ * //-
1062
+ * const query = {
1063
+ * sql: 'SELECT * FROM Singers WHERE name = @name',
1064
+ * params: {
1065
+ * name: 'Eddie Wilson'
1066
+ * }
1067
+ * };
1068
+ *
1069
+ * database.runStream(query)
1070
+ * .on('error', function(err) {})
1071
+ * .on('data', function(row) {})
1072
+ * .on('end', function() {});
1073
+ *
1074
+ * //-
1075
+ * // If you need to enforce a specific param type, a types map can be provided.
1076
+ * // This is typically useful if your param value can be null.
1077
+ * //-
1078
+ * const query = {
1079
+ * sql: 'SELECT * FROM Singers WHERE name = @name',
1080
+ * params: {
1081
+ * name: 'Eddie Wilson'
1082
+ * },
1083
+ * types: {
1084
+ * name: 'string'
1085
+ * }
1086
+ * };
1087
+ *
1088
+ * database.runStream(query)
1089
+ * .on('error', function(err) {})
1090
+ * .on('data', function(row) {})
1091
+ * .on('end', function() {});
1092
+ *
1093
+ * //-
1094
+ * // If you anticipate many results, you can end a stream early to prevent
1095
+ * // unnecessary processing and API requests.
1096
+ * //-
1097
+ * database.runStream(query)
1098
+ * .on('data', function(row) {
1099
+ * this.end();
1100
+ * });
1101
+ * ```
1102
+ */
1103
+ runStream(query, options) {
1104
+ const proxyStream = through.obj();
1105
+ const traceConfig = {
1106
+ sql: query,
1107
+ ...this._traceConfig,
1108
+ };
1109
+ return (0, instrument_1.startTrace)('Database.runStream', traceConfig, span => {
1110
+ this.pool_.getSession((err, session) => {
1111
+ if (err) {
1112
+ (0, instrument_1.setSpanError)(span, err);
1113
+ proxyStream.destroy(err);
1114
+ span.end();
1115
+ return;
1116
+ }
1117
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
1118
+ const snapshot = session.snapshot(options, this.queryOptions_);
1119
+ this._releaseOnEnd(session, snapshot, span);
1120
+ let dataReceived = false;
1121
+ let dataStream = snapshot.runStream(query);
1122
+ const endListener = () => {
1123
+ snapshot.end();
1124
+ };
1125
+ dataStream
1126
+ .once('data', () => (dataReceived = true))
1127
+ .once('error', err => {
1128
+ (0, instrument_1.setSpanError)(span, err);
1129
+ if (!dataReceived &&
1130
+ (0, session_pool_1.isSessionNotFoundError)(err)) {
1131
+ // If it is a 'Session not found' error and we have not yet received
1132
+ // any data, we can safely retry the query on a new session.
1133
+ // Register the error on the session so the pool can discard it.
1134
+ if (session) {
1135
+ session.lastError = err;
1136
+ }
1137
+ span.addEvent('No session available', {
1138
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1139
+ });
1140
+ // Remove the current data stream from the end user stream.
1141
+ dataStream.unpipe(proxyStream);
1142
+ dataStream.removeListener('end', endListener);
1143
+ dataStream.end();
1144
+ snapshot.end();
1145
+ span.end();
1146
+ // Create a new data stream and add it to the end user stream.
1147
+ dataStream = this.runStream(query, options);
1148
+ dataStream.pipe(proxyStream);
1149
+ }
1150
+ else {
1151
+ proxyStream.destroy(err);
1152
+ snapshot.end();
1153
+ }
1154
+ })
1155
+ .on('stats', stats => proxyStream.emit('stats', stats))
1156
+ .on('response', response => proxyStream.emit('response', response))
1157
+ .once('end', endListener)
1158
+ .pipe(proxyStream);
1159
+ });
1160
+ (0, stream_1.finished)(proxyStream, err => {
1161
+ if (err) {
1162
+ (0, instrument_1.setSpanError)(span, err);
1163
+ }
1164
+ span.end();
1165
+ });
1166
+ return proxyStream;
1167
+ });
1168
+ }
1169
+ runTransaction(optionsOrRunFn, fn) {
1170
+ const runFn = typeof optionsOrRunFn === 'function'
1171
+ ? optionsOrRunFn
1172
+ : fn;
1173
+ const options = typeof optionsOrRunFn === 'object' && optionsOrRunFn
1174
+ ? optionsOrRunFn
1175
+ : {};
1176
+ (0, instrument_1.startTrace)('Database.runTransaction', this._traceConfig, span => {
1177
+ this.pool_.getSession((err, session, transaction) => {
1178
+ if (err) {
1179
+ (0, instrument_1.setSpanError)(span, err);
1180
+ }
1181
+ if (err && (0, session_pool_1.isSessionNotFoundError)(err)) {
1182
+ span.addEvent('No session available', {
1183
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1184
+ });
1185
+ span.end();
1186
+ this.runTransaction(options, runFn);
1187
+ return;
1188
+ }
1189
+ if (err) {
1190
+ span.end();
1191
+ runFn(err);
1192
+ return;
1193
+ }
1194
+ transaction._observabilityOptions = this._observabilityOptions;
1195
+ if (options.optimisticLock) {
1196
+ transaction.useOptimisticLock();
1197
+ }
1198
+ if (options.excludeTxnFromChangeStreams) {
1199
+ transaction.excludeTxnFromChangeStreams();
1200
+ }
1201
+ const release = () => {
1202
+ this.pool_.release(session);
1203
+ span.end();
1204
+ };
1205
+ const runner = new transaction_runner_1.TransactionRunner(session, transaction, runFn, options);
1206
+ runner.run().then(release, err => {
1207
+ (0, instrument_1.setSpanError)(span, err);
1208
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1209
+ span.addEvent('No session available', {
1210
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1211
+ });
1212
+ release();
1213
+ this.runTransaction(options, runFn);
1214
+ }
1215
+ else {
1216
+ setImmediate(runFn, err);
1217
+ release();
1218
+ }
1219
+ });
1220
+ });
1221
+ });
1222
+ }
1223
+ /**
1224
+ * @callback AsyncRunTransactionCallback
1225
+ * @param {Transaction} transaction The transaction object. The transaction has
1226
+ * already been created, and is ready to be queried and committed against.
1227
+ */
1228
+ /**
1229
+ * A transaction in Cloud Spanner is a set of reads and writes that execute
1230
+ * atomically at a single logical point in time across columns, rows, and tables
1231
+ * in a database.
1232
+ *
1233
+ * Note that Cloud Spanner does not support nested transactions. If a new
1234
+ * transaction is started inside of the run function, it will be an independent
1235
+ * transaction.
1236
+ *
1237
+ * The async function you provide will become the "run function". It
1238
+ * will be executed with a {@link Transaction}
1239
+ * object. The Transaction object will let you run queries and queue mutations
1240
+ * until you are ready to {@link Transaction#commit}.
1241
+ *
1242
+ * In the event that an aborted error occurs, we will re-run the `runFn` in its
1243
+ * entirety. If you prefer to handle aborted errors for yourself please refer to
1244
+ * {@link Database#getTransaction}.
1245
+ *
1246
+ * **NOTE:** In the event that you encounter an error while reading/writing,
1247
+ * if you decide to forgo calling {@link Transaction#commit} or
1248
+ * {@link Transaction#rollback}, then you need to call
1249
+ * {@link Transaction#end} to release the underlying {@link Session} object.
1250
+ * **Failure to do could result in a Session leak.**
1251
+ *
1252
+ * For a more complete listing of functionality available to a Transaction, see
1253
+ * the {@link Transaction} API documentation. For a general overview of
1254
+ * transactions within Cloud Spanner, see
1255
+ * [Transactions](https://cloud.google.com/spanner/docs/transactions) from the
1256
+ * official Cloud Spanner documentation.
1257
+ *
1258
+ * @see [Transactions](https://cloud.google.com/spanner/docs/transactions)
1259
+ *
1260
+ * @param {RunTransactionOptions} [options] Transaction runner options.
1261
+ * @param {AsyncRunTransactionCallback} callback A function to execute in the
1262
+ * context of a transaction.
1263
+ * @returns {Promise}
1264
+ *
1265
+ * @example
1266
+ * ```
1267
+ * const {Spanner} = require('@google-cloud/spanner');
1268
+ * const spanner = new Spanner();
1269
+ *
1270
+ * const instance = spanner.instance('my-instance');
1271
+ * const database = instance.database('my-database');
1272
+ *
1273
+ * const data = await database.runTransactionAsync(async (transaction) => {
1274
+ * const [rows] = await transaction.run('SELECT * FROM MyTable');
1275
+ * const data = rows.map(row => row.thing);
1276
+ *
1277
+ * await transaction.commit();
1278
+ * return data;
1279
+ * });
1280
+ * ```
1281
+ */
1282
+ async runTransactionAsync(optionsOrRunFn, fn) {
1283
+ const runFn = typeof optionsOrRunFn === 'function'
1284
+ ? optionsOrRunFn
1285
+ : fn;
1286
+ const options = typeof optionsOrRunFn === 'object'
1287
+ ? optionsOrRunFn
1288
+ : {};
1289
+ let sessionId = '';
1290
+ const getSession = this.pool_.getSession.bind(this.pool_);
1291
+ return (0, instrument_1.startTrace)('Database.runTransactionAsync', this._traceConfig, async (span) => {
1292
+ // Loop to retry 'Session not found' errors.
1293
+ // (and yes, we like while (true) more than for (;;) here)
1294
+ // eslint-disable-next-line no-constant-condition
1295
+ while (true) {
1296
+ try {
1297
+ const [session, transaction] = await (0, promisify_1.promisify)(getSession)();
1298
+ transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1299
+ if (options.optimisticLock) {
1300
+ transaction.useOptimisticLock();
1301
+ }
1302
+ if (options.excludeTxnFromChangeStreams) {
1303
+ transaction.excludeTxnFromChangeStreams();
1304
+ }
1305
+ sessionId = session === null || session === void 0 ? void 0 : session.id;
1306
+ span.addEvent('Using Session', { 'session.id': sessionId });
1307
+ const runner = new transaction_runner_1.AsyncTransactionRunner(session, transaction, runFn, options);
1308
+ try {
1309
+ return await runner.run();
1310
+ }
1311
+ catch (e) {
1312
+ (0, instrument_1.setSpanErrorAndException)(span, e);
1313
+ throw e;
1314
+ }
1315
+ finally {
1316
+ span.end();
1317
+ this.pool_.release(session);
1318
+ }
1319
+ }
1320
+ catch (e) {
1321
+ if ((0, session_pool_1.isSessionNotFoundError)(e)) {
1322
+ span.addEvent('No session available', {
1323
+ 'session.id': sessionId,
1324
+ });
1325
+ }
1326
+ else {
1327
+ span.end();
1328
+ throw e;
1329
+ }
1330
+ }
1331
+ }
1332
+ });
1333
+ }
1334
+ /**
1335
+ * Write a batch of mutations to Spanner.
1336
+ *
1337
+ * All mutations in a group are committed atomically. However, mutations across
1338
+ * groups can be committed non-atomically in an unspecified order and thus, they
1339
+ * must be independent of each other. Partial failure is possible, i.e., some groups
1340
+ * may have been committed successfully, while some may have failed. The results of
1341
+ * individual batches are streamed into the response as the batches are applied.
1342
+ *
1343
+ * batchWriteAtLeastOnce requests are not replay protected, meaning that each mutation group may
1344
+ * be applied more than once. Replays of non-idempotent mutations may have undesirable
1345
+ * effects. For example, replays of an insert mutation may produce an already exists
1346
+ * error or if you use generated or commit timestamp-based keys, it may result in additional
1347
+ * rows being added to the mutation's table. We recommend structuring your mutation groups to
1348
+ * be idempotent to avoid this issue.
1349
+ *
1350
+ * @method Spanner#batchWriteAtLeastOnce
1351
+ *
1352
+ * @param {MutationGroup[]} [mutationGroups] The group of mutations to be applied.
1353
+ * @param {BatchWriteOptions} [options] Options object for batch write request.
1354
+ *
1355
+ * @returns {ReadableStream} An object stream which emits
1356
+ * {@link protos.google.spanner.v1.BatchWriteResponse|BatchWriteResponse}
1357
+ * on 'data' event.
1358
+ *
1359
+ * @example
1360
+ * ```
1361
+ * const {Spanner} = require('@google-cloud/spanner');
1362
+ * const spanner = new Spanner();
1363
+ *
1364
+ * const instance = spanner.instance('my-instance');
1365
+ * const database = instance.database('my-database');
1366
+ * const mutationGroup = new MutationGroup();
1367
+ * mutationGroup.insert('Singers', {
1368
+ * SingerId: '1',
1369
+ * FirstName: 'Marc',
1370
+ * LastName: 'Richards',
1371
+ * });
1372
+ *
1373
+ * database.batchWriteAtLeastOnce([mutationGroup])
1374
+ * .on('error', console.error)
1375
+ * .on('data', response => {
1376
+ * console.log('response: ', response);
1377
+ * })
1378
+ * .on('end', () => {
1379
+ * console.log('Request completed successfully');
1380
+ * });
1381
+ *
1382
+ * //-
1383
+ * // If you anticipate many results, you can end a stream early to prevent
1384
+ * // unnecessary processing and API requests.
1385
+ * //-
1386
+ * database.batchWriteAtLeastOnce()
1387
+ * .on('data', response => {
1388
+ * this.end();
1389
+ * });
1390
+ * ```
1391
+ */
1392
+ batchWriteAtLeastOnce(mutationGroups, options) {
1393
+ const proxyStream = through.obj();
1394
+ return (0, instrument_1.startTrace)('Database.batchWriteAtLeastOnce', this._traceConfig, span => {
1395
+ this.pool_.getSession((err, session) => {
1396
+ if (err) {
1397
+ proxyStream.destroy(err);
1398
+ (0, instrument_1.setSpanError)(span, err);
1399
+ span.end();
1400
+ return;
1401
+ }
1402
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
1403
+ const gaxOpts = extend(true, {}, options === null || options === void 0 ? void 0 : options.gaxOptions);
1404
+ const reqOpts = Object.assign({}, {
1405
+ session: session.formattedName_,
1406
+ mutationGroups: mutationGroups.map(mg => mg.proto()),
1407
+ requestOptions: options === null || options === void 0 ? void 0 : options.requestOptions,
1408
+ excludeTxnFromChangeStream: options === null || options === void 0 ? void 0 : options.excludeTxnFromChangeStreams,
1409
+ });
1410
+ let dataReceived = false;
1411
+ let dataStream = this.requestStream({
1412
+ client: 'SpannerClient',
1413
+ method: 'batchWrite',
1414
+ reqOpts,
1415
+ gaxOpts,
1416
+ headers: this.commonHeaders_,
1417
+ });
1418
+ dataStream
1419
+ .once('data', () => (dataReceived = true))
1420
+ .once('error', err => {
1421
+ (0, instrument_1.setSpanError)(span, err);
1422
+ if (!dataReceived &&
1423
+ (0, session_pool_1.isSessionNotFoundError)(err)) {
1424
+ // If there's a 'Session not found' error and we have not yet received
1425
+ // any data, we can safely retry the writes on a new session.
1426
+ // Register the error on the session so the pool can discard it.
1427
+ if (session) {
1428
+ session.lastError = err;
1429
+ }
1430
+ span.addEvent('No session available', {
1431
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1432
+ });
1433
+ // Remove the current data stream from the end user stream.
1434
+ dataStream.unpipe(proxyStream);
1435
+ dataStream.end();
1436
+ span.end();
1437
+ // Create a new stream and add it to the end user stream.
1438
+ dataStream = this.batchWriteAtLeastOnce(mutationGroups, options);
1439
+ dataStream.pipe(proxyStream);
1440
+ }
1441
+ else {
1442
+ span.end();
1443
+ proxyStream.destroy(err);
1444
+ }
1445
+ })
1446
+ .once('end', () => {
1447
+ span.end();
1448
+ this.pool_.release(session);
1449
+ })
1450
+ .pipe(proxyStream);
1451
+ });
1452
+ return proxyStream;
1453
+ });
1454
+ }
1455
+ writeAtLeastOnce(mutations, optionsOrCallback, callback) {
1456
+ const cb = typeof optionsOrCallback === 'function'
1457
+ ? optionsOrCallback
1458
+ : callback;
1459
+ const options = typeof optionsOrCallback === 'object' && optionsOrCallback
1460
+ ? optionsOrCallback
1461
+ : {};
1462
+ return (0, instrument_1.startTrace)('Database.writeAtLeastOnce', this._traceConfig, span => {
1463
+ this.pool_.getSession((err, session, transaction) => {
1464
+ if (err && (0, session_pool_1.isSessionNotFoundError)(err)) {
1465
+ span.addEvent('No session available', {
1466
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1467
+ });
1468
+ span.end();
1469
+ this.writeAtLeastOnce(mutations, options, cb);
1470
+ return;
1471
+ }
1472
+ if (err) {
1473
+ (0, instrument_1.setSpanError)(span, err);
1474
+ span.end();
1475
+ cb(err);
1476
+ return;
1477
+ }
1478
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
1479
+ this._releaseOnEnd(session, transaction, span);
1480
+ try {
1481
+ transaction === null || transaction === void 0 ? void 0 : transaction.setQueuedMutations(mutations.proto());
1482
+ return transaction === null || transaction === void 0 ? void 0 : transaction.commit(options, (err, resp) => {
1483
+ if (err) {
1484
+ (0, instrument_1.setSpanError)(span, err);
1485
+ }
1486
+ span.end();
1487
+ cb(err, resp);
1488
+ });
1489
+ }
1490
+ catch (e) {
1491
+ (0, instrument_1.setSpanErrorAndException)(span, e);
1492
+ span.end();
1493
+ throw e;
1494
+ }
1495
+ });
1496
+ });
1497
+ }
1498
+ /**
1499
+ * Create a Session object.
1500
+ *
1501
+ * It is unlikely you will need to interact with sessions directly. By default,
1502
+ * sessions are created and utilized for maximum performance automatically.
1503
+ *
1504
+ * @param {string} [name] The name of the session. If not provided, it is
1505
+ * assumed you are going to create it.
1506
+ * @returns {Session} A Session object.
1507
+ *
1508
+ * @example
1509
+ * ```
1510
+ * var session = database.session('session-name');
1511
+ * ```
1512
+ */
1513
+ session(name) {
1514
+ return new session_1.Session(this, name);
1515
+ }
1516
+ setIamPolicy(policy, optionsOrCallback, cb) {
1517
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
1518
+ const callback = typeof optionsOrCallback === 'function'
1519
+ ? optionsOrCallback
1520
+ : cb;
1521
+ const gaxOpts = options;
1522
+ const reqOpts = {
1523
+ resource: this.formattedName_,
1524
+ policy: policy.policy,
1525
+ updateMask: policy.updateMask || null,
1526
+ };
1527
+ this.request({
1528
+ client: 'DatabaseAdminClient',
1529
+ method: 'setIamPolicy',
1530
+ reqOpts,
1531
+ gaxOpts: gaxOpts,
1532
+ headers: this.commonHeaders_,
1533
+ }, (err, resp) => {
1534
+ callback(err, resp);
1535
+ });
1536
+ }
1537
+ table(name) {
1538
+ if (!name) {
1539
+ throw new google_gax_1.GoogleError('A name is required to access a Table object.');
1540
+ }
1541
+ return new table_1.Table(this, name);
1542
+ }
1543
+ updateSchema(statements, optionsOrCallback, cb) {
1544
+ const gaxOpts = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
1545
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
1546
+ if (typeof statements === 'string' || Array.isArray(statements)) {
1547
+ statements = {
1548
+ statements: arrify(statements),
1549
+ };
1550
+ }
1551
+ const reqOpts = extend({
1552
+ database: this.formattedName_,
1553
+ }, statements);
1554
+ return this.request({
1555
+ client: 'DatabaseAdminClient',
1556
+ method: 'updateDatabaseDdl',
1557
+ reqOpts,
1558
+ gaxOpts,
1559
+ headers: this.commonHeaders_,
1560
+ }, callback);
1561
+ }
1562
+ /**
1563
+ * Format the database name to include the instance name.
1564
+ *
1565
+ * @private
1566
+ *
1567
+ * @param {string} instanceName The formatted instance name.
1568
+ * @param {string} name The table name.
1569
+ * @returns {string}
1570
+ *
1571
+ * @example
1572
+ * ```
1573
+ * Database.formatName_(
1574
+ * 'projects/grape-spaceship-123/instances/my-instance',
1575
+ * 'my-database'
1576
+ * );
1577
+ * // 'projects/grape-spaceship-123/instances/my-instance/databases/my-database'
1578
+ * ```
1579
+ */
1580
+ static formatName_(instanceName, name) {
1581
+ if (name.indexOf('/') > -1) {
1582
+ return name;
1583
+ }
1584
+ const databaseName = name.split('/').pop();
1585
+ return instanceName + '/databases/' + databaseName;
1586
+ }
1587
+ /**
1588
+ * Gets the Spanner object
1589
+ *
1590
+ * @private
1591
+ *
1592
+ * @returns {Spanner}
1593
+ */
1594
+ _getSpanner() {
1595
+ return this.instance.parent;
1596
+ }
1597
+ }
1598
+ exports.Database = Database;
1599
+ /*! Developer Documentation
1600
+ *
1601
+ * All async methods (except for streams) will return a Promise in the event
1602
+ * that a callback is omitted.
1603
+ */
1604
+ (0, promisify_1.promisifyAll)(Database, {
1605
+ exclude: [
1606
+ 'batchTransaction',
1607
+ 'batchWriteAtLeastOnce',
1608
+ 'getRestoreInfo',
1609
+ 'getState',
1610
+ 'getDatabaseDialect',
1611
+ 'getOperations',
1612
+ 'runTransaction',
1613
+ 'runTransactionAsync',
1614
+ 'table',
1615
+ 'session',
1616
+ ],
1617
+ });
1618
+ /*! Developer Documentation
1619
+ *
1620
+ * All async methods (except for streams) will return a Promise in the event
1621
+ * that a callback is omitted.
1622
+ */
1623
+ (0, promisify_1.callbackifyAll)(Database, {
1624
+ exclude: [
1625
+ 'create',
1626
+ 'batchCreateSessions',
1627
+ 'batchTransaction',
1628
+ 'batchWriteAtLeastOnce',
1629
+ 'writeAtLeastOnce',
1630
+ 'close',
1631
+ 'createBatchTransaction',
1632
+ 'createSession',
1633
+ 'createTable',
1634
+ 'delete',
1635
+ 'exists',
1636
+ 'get',
1637
+ 'getDatabaseDialect',
1638
+ 'getMetadata',
1639
+ 'getSchema',
1640
+ 'getSessions',
1641
+ 'getSnapshot',
1642
+ 'getTransaction',
1643
+ 'getIamPolicy',
1644
+ 'restore',
1645
+ 'run',
1646
+ 'runPartitionedUpdate',
1647
+ 'runTransaction',
1648
+ 'runTransactionAsync',
1649
+ 'session',
1650
+ 'setMetadata',
1651
+ 'table',
1652
+ 'updateSchema',
1653
+ ],
1654
+ });
1655
+ //# sourceMappingURL=database.js.map