@google-cloud/spanner 7.18.0 → 7.19.0

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