@google-cloud/spanner 7.19.1 → 7.20.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.
@@ -23,6 +23,7 @@ const is = require("is");
23
23
  const transaction_1 = require("./transaction");
24
24
  const common_1 = require("../src/common");
25
25
  const instrument_1 = require("./instrument");
26
+ const request_id_header_1 = require("./request_id_header");
26
27
  /**
27
28
  * Use a BatchTransaction object to create partitions and read/query against
28
29
  * your Cloud Spanner database.
@@ -139,7 +140,7 @@ class BatchTransaction extends transaction_1.Snapshot {
139
140
  method: 'partitionQuery',
140
141
  reqOpts,
141
142
  gaxOpts: query.gaxOptions,
142
- headers: headers,
143
+ headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session),
143
144
  }, (err, partitions, resp) => {
144
145
  if (err) {
145
146
  (0, instrument_1.setSpanError)(span, err);
@@ -173,10 +174,11 @@ class BatchTransaction extends transaction_1.Snapshot {
173
174
  transaction: { id: this.id },
174
175
  });
175
176
  config.reqOpts = extend({}, query);
176
- config.headers = {
177
+ const headers = {
177
178
  [common_1.CLOUD_RESOURCE_HEADER]: this.session.parent
178
179
  .formattedName_,
179
180
  };
181
+ config.headers = (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session);
180
182
  delete query.partitionOptions;
181
183
  this.session.request(config, (err, resp) => {
182
184
  if (err) {
@@ -251,7 +253,7 @@ class BatchTransaction extends transaction_1.Snapshot {
251
253
  method: 'partitionRead',
252
254
  reqOpts,
253
255
  gaxOpts: options.gaxOptions,
254
- headers: headers,
256
+ headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session),
255
257
  }, (err, partitions, resp) => {
256
258
  if (err) {
257
259
  (0, instrument_1.setSpanError)(span, err);
@@ -205,6 +205,89 @@ export declare class PGOid extends WrappedNumber {
205
205
  constructor(value: string);
206
206
  valueOf(): number;
207
207
  }
208
+ /**
209
+ * @typedef Interval
210
+ * @see Spanner.interval
211
+ */
212
+ export declare class Interval {
213
+ private months;
214
+ private days;
215
+ private nanoseconds;
216
+ private static readonly ISO8601_PATTERN;
217
+ static readonly MONTHS_PER_YEAR: number;
218
+ static readonly DAYS_PER_MONTH: number;
219
+ static readonly HOURS_PER_DAY: number;
220
+ static readonly MINUTES_PER_HOUR: number;
221
+ static readonly SECONDS_PER_MINUTE: number;
222
+ static readonly SECONDS_PER_HOUR: number;
223
+ static readonly MILLISECONDS_PER_SECOND: number;
224
+ static readonly MICROSECONDS_PER_MILLISECOND: number;
225
+ static readonly NANOSECONDS_PER_MICROSECOND: number;
226
+ static readonly NANOSECONDS_PER_MILLISECOND: number;
227
+ static readonly NANOSECONDS_PER_SECOND: number;
228
+ static readonly NANOSECONDS_PER_DAY: bigint;
229
+ static readonly NANOSECONDS_PER_MONTH: bigint;
230
+ static readonly ZERO: Interval;
231
+ /**
232
+ * @param months months part of the `Interval`
233
+ * @param days days part of the `Interval`
234
+ * @param nanoseconds nanoseconds part of the `Interval`
235
+ */
236
+ constructor(months: number, days: number, nanoseconds: bigint);
237
+ /**
238
+ * @returns months part of the `Interval`.
239
+ */
240
+ getMonths(): number;
241
+ /**
242
+ * @returns days part of the `Interval`.
243
+ */
244
+ getDays(): number;
245
+ /**
246
+ * @returns nanoseconds part of the `Interval`.
247
+ */
248
+ getNanoseconds(): bigint;
249
+ /**
250
+ * Constructs an `Interval` with specified months.
251
+ */
252
+ static fromMonths(months: number): Interval;
253
+ /**
254
+ * Constructs an `Interval` with specified days.
255
+ */
256
+ static fromDays(days: number): Interval;
257
+ /**
258
+ * Constructs an `Interval` with specified seconds.
259
+ */
260
+ static fromSeconds(seconds: number): Interval;
261
+ /**
262
+ * Constructs an `Interval` with specified milliseconds.
263
+ */
264
+ static fromMilliseconds(milliseconds: number): Interval;
265
+ /**
266
+ * Constructs an `Interval` with specified microseconds.
267
+ */
268
+ static fromMicroseconds(microseconds: number): Interval;
269
+ /**
270
+ * Constructs an `Interval` with specified nanoseconds.
271
+ */
272
+ static fromNanoseconds(nanoseconds: bigint): Interval;
273
+ /**
274
+ * Constructs an Interval from ISO8601 duration format: `P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S`.
275
+ * Only seconds can be fractional, and can have at most 9 digits after decimal point.
276
+ * Both '.' and ',' are considered valid decimal point.
277
+ */
278
+ static fromISO8601(isoString: string): Interval;
279
+ /**
280
+ * @returns string representation of Interval in ISO8601 duration format: `P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S`
281
+ */
282
+ toISO8601(): string;
283
+ equals(other: Interval): boolean;
284
+ valueOf(): Interval;
285
+ /**
286
+ * @returns JSON representation for Interval.
287
+ * Interval is represented in ISO8601 duration format string in JSON.
288
+ */
289
+ toJSON(): string;
290
+ }
208
291
  /**
209
292
  * @typedef JSONOptions
210
293
  * @property {boolean} [wrapNumbers=false] Indicates if the numbers should be
@@ -276,6 +359,7 @@ interface FieldType extends Type {
276
359
  * - string
277
360
  * - bytes
278
361
  * - json
362
+ * - interval
279
363
  * - proto
280
364
  * - enum
281
365
  * - timestamp
@@ -353,6 +437,7 @@ export declare const codec: {
353
437
  ProtoMessage: typeof ProtoMessage;
354
438
  ProtoEnum: typeof ProtoEnum;
355
439
  PGOid: typeof PGOid;
440
+ Interval: typeof Interval;
356
441
  convertFieldsToJson: typeof convertFieldsToJson;
357
442
  decode: typeof decode;
358
443
  encode: typeof encode;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.codec = exports.PGOid = exports.PGJsonb = exports.ProtoEnum = exports.ProtoMessage = exports.PGNumeric = exports.Numeric = exports.Struct = exports.Int = exports.Float = exports.Float32 = exports.SpannerDate = void 0;
3
+ exports.codec = exports.Interval = exports.PGOid = exports.PGJsonb = exports.ProtoEnum = exports.ProtoMessage = exports.PGNumeric = exports.Numeric = exports.Struct = exports.Int = exports.Float = exports.Float32 = exports.SpannerDate = void 0;
4
4
  /*!
5
5
  * Copyright 2017 Google Inc. All Rights Reserved.
6
6
  *
@@ -306,6 +306,236 @@ class PGOid extends WrappedNumber {
306
306
  }
307
307
  }
308
308
  exports.PGOid = PGOid;
309
+ /**
310
+ * @typedef Interval
311
+ * @see Spanner.interval
312
+ */
313
+ class Interval {
314
+ /**
315
+ * @param months months part of the `Interval`
316
+ * @param days days part of the `Interval`
317
+ * @param nanoseconds nanoseconds part of the `Interval`
318
+ */
319
+ constructor(months, days, nanoseconds) {
320
+ if (!is.integer(months)) {
321
+ throw new google_gax_1.GoogleError(`Invalid months: ${months}, months should be an integral value`);
322
+ }
323
+ if (!is.integer(days)) {
324
+ throw new google_gax_1.GoogleError(`Invalid days: ${days}, days should be an integral value`);
325
+ }
326
+ if (is.null(nanoseconds) || is.undefined(nanoseconds)) {
327
+ throw new google_gax_1.GoogleError(`Invalid nanoseconds: ${nanoseconds}, nanoseconds should be a valid bigint value`);
328
+ }
329
+ this.months = months;
330
+ this.days = days;
331
+ this.nanoseconds = nanoseconds;
332
+ }
333
+ /**
334
+ * @returns months part of the `Interval`.
335
+ */
336
+ getMonths() {
337
+ return this.months;
338
+ }
339
+ /**
340
+ * @returns days part of the `Interval`.
341
+ */
342
+ getDays() {
343
+ return this.days;
344
+ }
345
+ /**
346
+ * @returns nanoseconds part of the `Interval`.
347
+ */
348
+ getNanoseconds() {
349
+ return this.nanoseconds;
350
+ }
351
+ /**
352
+ * Constructs an `Interval` with specified months.
353
+ */
354
+ static fromMonths(months) {
355
+ return new Interval(months, 0, BigInt(0));
356
+ }
357
+ /**
358
+ * Constructs an `Interval` with specified days.
359
+ */
360
+ static fromDays(days) {
361
+ return new Interval(0, days, BigInt(0));
362
+ }
363
+ /**
364
+ * Constructs an `Interval` with specified seconds.
365
+ */
366
+ static fromSeconds(seconds) {
367
+ if (!is.integer(seconds)) {
368
+ throw new google_gax_1.GoogleError(`Invalid seconds: ${seconds}, seconds should be an integral value`);
369
+ }
370
+ return new Interval(0, 0, BigInt(Interval.NANOSECONDS_PER_SECOND) * BigInt(seconds));
371
+ }
372
+ /**
373
+ * Constructs an `Interval` with specified milliseconds.
374
+ */
375
+ static fromMilliseconds(milliseconds) {
376
+ if (!is.integer(milliseconds)) {
377
+ throw new google_gax_1.GoogleError(`Invalid milliseconds: ${milliseconds}, milliseconds should be an integral value`);
378
+ }
379
+ return new Interval(0, 0, BigInt(Interval.NANOSECONDS_PER_MILLISECOND) * BigInt(milliseconds));
380
+ }
381
+ /**
382
+ * Constructs an `Interval` with specified microseconds.
383
+ */
384
+ static fromMicroseconds(microseconds) {
385
+ if (!is.integer(microseconds)) {
386
+ throw new google_gax_1.GoogleError(`Invalid microseconds: ${microseconds}, microseconds should be an integral value`);
387
+ }
388
+ return new Interval(0, 0, BigInt(Interval.NANOSECONDS_PER_MICROSECOND) * BigInt(microseconds));
389
+ }
390
+ /**
391
+ * Constructs an `Interval` with specified nanoseconds.
392
+ */
393
+ static fromNanoseconds(nanoseconds) {
394
+ return new Interval(0, 0, nanoseconds);
395
+ }
396
+ /**
397
+ * Constructs an Interval from ISO8601 duration format: `P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S`.
398
+ * Only seconds can be fractional, and can have at most 9 digits after decimal point.
399
+ * Both '.' and ',' are considered valid decimal point.
400
+ */
401
+ static fromISO8601(isoString) {
402
+ const matcher = Interval.ISO8601_PATTERN.exec(isoString);
403
+ if (!matcher) {
404
+ throw new google_gax_1.GoogleError(`Invalid ISO8601 duration string: ${isoString}`);
405
+ }
406
+ const getNullOrDefault = (groupIdx) => matcher[groupIdx] === undefined ? '0' : matcher[groupIdx];
407
+ const years = parseInt(getNullOrDefault(1).replace('Y', ''));
408
+ const months = parseInt(getNullOrDefault(2).replace('M', ''));
409
+ const days = parseInt(getNullOrDefault(3).replace('D', ''));
410
+ const hours = parseInt(getNullOrDefault(5).replace('H', ''));
411
+ const minutes = parseInt(getNullOrDefault(6).replace('M', ''));
412
+ const seconds = (0, big_js_1.Big)(getNullOrDefault(7).replace('S', '').replace(',', '.'));
413
+ const totalMonths = (0, big_js_1.Big)(years)
414
+ .mul((0, big_js_1.Big)(Interval.MONTHS_PER_YEAR))
415
+ .add((0, big_js_1.Big)(months))
416
+ .toNumber();
417
+ if (!Number.isSafeInteger(totalMonths)) {
418
+ throw new google_gax_1.GoogleError('Total months is outside of the range of safe integer');
419
+ }
420
+ const totalNanoseconds = BigInt(seconds
421
+ .add((0, big_js_1.Big)((BigInt(hours) * BigInt(Interval.SECONDS_PER_HOUR)).toString()))
422
+ .add((0, big_js_1.Big)((BigInt(minutes) * BigInt(Interval.SECONDS_PER_MINUTE)).toString()))
423
+ .mul((0, big_js_1.Big)(this.NANOSECONDS_PER_SECOND))
424
+ .toString());
425
+ return new Interval(totalMonths, days, totalNanoseconds);
426
+ }
427
+ /**
428
+ * @returns string representation of Interval in ISO8601 duration format: `P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S`
429
+ */
430
+ toISO8601() {
431
+ if (this.equals(Interval.ZERO)) {
432
+ return 'P0Y';
433
+ }
434
+ // months part is normalized to years and months.
435
+ let result = 'P';
436
+ if (this.months !== 0) {
437
+ const years_part = Math.trunc(this.months / Interval.MONTHS_PER_YEAR);
438
+ const months_part = this.months - years_part * Interval.MONTHS_PER_YEAR;
439
+ if (years_part !== 0) {
440
+ result += `${years_part}Y`;
441
+ }
442
+ if (months_part !== 0) {
443
+ result += `${months_part}M`;
444
+ }
445
+ }
446
+ if (this.days !== 0) {
447
+ result += `${this.days}D`;
448
+ }
449
+ // Nanoseconds part is normalized to hours, minutes and nanoseconds.
450
+ if (this.nanoseconds !== BigInt(0)) {
451
+ result += 'T';
452
+ let nanoseconds = this.nanoseconds;
453
+ const hours_part = nanoseconds /
454
+ BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_HOUR);
455
+ nanoseconds =
456
+ nanoseconds -
457
+ hours_part *
458
+ BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_HOUR);
459
+ const minutes_part = nanoseconds /
460
+ BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_MINUTE);
461
+ nanoseconds =
462
+ nanoseconds -
463
+ minutes_part *
464
+ BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_MINUTE);
465
+ const zero_bigint = BigInt(0);
466
+ if (hours_part !== zero_bigint) {
467
+ result += `${hours_part}H`;
468
+ }
469
+ if (minutes_part !== zero_bigint) {
470
+ result += `${minutes_part}M`;
471
+ }
472
+ let sign = '';
473
+ if (nanoseconds < zero_bigint) {
474
+ sign = '-';
475
+ nanoseconds = -nanoseconds;
476
+ }
477
+ // Nanoseconds are converted to seconds and fractional part.
478
+ const seconds_part = nanoseconds / BigInt(Interval.NANOSECONDS_PER_SECOND);
479
+ nanoseconds =
480
+ nanoseconds - seconds_part * BigInt(Interval.NANOSECONDS_PER_SECOND);
481
+ if (seconds_part !== zero_bigint || nanoseconds !== zero_bigint) {
482
+ result += `${sign}${seconds_part}`;
483
+ if (nanoseconds !== zero_bigint) {
484
+ // Fractional part is kept in a group of 3
485
+ // For e.g.: PT0.5S will be normalized to PT0.500S
486
+ result += `.${nanoseconds
487
+ .toString()
488
+ .padStart(9, '0')
489
+ .replace(/(0{3})+$/, '')}`;
490
+ }
491
+ result += 'S';
492
+ }
493
+ }
494
+ return result;
495
+ }
496
+ equals(other) {
497
+ if (!other) {
498
+ return false;
499
+ }
500
+ return (this.months === other.months &&
501
+ this.days === other.days &&
502
+ this.nanoseconds === other.nanoseconds);
503
+ }
504
+ valueOf() {
505
+ return this;
506
+ }
507
+ /**
508
+ * @returns JSON representation for Interval.
509
+ * Interval is represented in ISO8601 duration format string in JSON.
510
+ */
511
+ toJSON() {
512
+ return this.toISO8601().toString();
513
+ }
514
+ }
515
+ exports.Interval = Interval;
516
+ // Regex to parse ISO8601 duration format: P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S
517
+ // Only seconds can be fractional, and can have at most 9 digits after decimal point.
518
+ // Both '.' and ',' are considered valid decimal point.
519
+ Interval.ISO8601_PATTERN = /^P(?!$)(-?\d+Y)?(-?\d+M)?(-?\d+D)?(T(?=-?[.,]?\d)(-?\d+H)?(-?\d+M)?(-?(((\d+)([.,]\d{1,9})?)|([.,]\d{1,9}))S)?)?$/;
520
+ Interval.MONTHS_PER_YEAR = 12;
521
+ Interval.DAYS_PER_MONTH = 30;
522
+ Interval.HOURS_PER_DAY = 24;
523
+ Interval.MINUTES_PER_HOUR = 60;
524
+ Interval.SECONDS_PER_MINUTE = 60;
525
+ Interval.SECONDS_PER_HOUR = Interval.MINUTES_PER_HOUR * Interval.SECONDS_PER_MINUTE;
526
+ Interval.MILLISECONDS_PER_SECOND = 1000;
527
+ Interval.MICROSECONDS_PER_MILLISECOND = 1000;
528
+ Interval.NANOSECONDS_PER_MICROSECOND = 1000;
529
+ Interval.NANOSECONDS_PER_MILLISECOND = Interval.MICROSECONDS_PER_MILLISECOND *
530
+ Interval.NANOSECONDS_PER_MICROSECOND;
531
+ Interval.NANOSECONDS_PER_SECOND = Interval.MILLISECONDS_PER_SECOND *
532
+ Interval.MICROSECONDS_PER_MILLISECOND *
533
+ Interval.NANOSECONDS_PER_MICROSECOND;
534
+ Interval.NANOSECONDS_PER_DAY = BigInt(Interval.HOURS_PER_DAY) *
535
+ BigInt(Interval.SECONDS_PER_HOUR) *
536
+ BigInt(Interval.NANOSECONDS_PER_SECOND);
537
+ Interval.NANOSECONDS_PER_MONTH = BigInt(Interval.DAYS_PER_MONTH) * Interval.NANOSECONDS_PER_DAY;
538
+ Interval.ZERO = new Interval(0, 0, BigInt(0));
309
539
  /**
310
540
  * @typedef JSONOptions
311
541
  * @property {boolean} [wrapNumbers=false] Indicates if the numbers should be
@@ -468,6 +698,10 @@ function decode(value, type, columnMetadata) {
468
698
  }
469
699
  decoded = JSON.parse(decoded);
470
700
  break;
701
+ case protos_1.google.spanner.v1.TypeCode.INTERVAL:
702
+ case 'INTERVAL':
703
+ decoded = Interval.fromISO8601(decoded);
704
+ break;
471
705
  case protos_1.google.spanner.v1.TypeCode.ARRAY:
472
706
  case 'ARRAY':
473
707
  decoded = decoded.map(value => {
@@ -542,6 +776,9 @@ function encodeValue(value) {
542
776
  if (value instanceof PGJsonb) {
543
777
  return value.toString();
544
778
  }
779
+ if (value instanceof Interval) {
780
+ return value.toISO8601();
781
+ }
545
782
  if (is.object(value)) {
546
783
  return JSON.stringify(value);
547
784
  }
@@ -568,6 +805,7 @@ const TypeCode = {
568
805
  bytes: 'BYTES',
569
806
  json: 'JSON',
570
807
  jsonb: 'JSON',
808
+ interval: 'INTERVAL',
571
809
  proto: 'PROTO',
572
810
  enum: 'ENUM',
573
811
  array: 'ARRAY',
@@ -588,6 +826,7 @@ const TypeCode = {
588
826
  * - string
589
827
  * - bytes
590
828
  * - json
829
+ * - interval
591
830
  * - proto
592
831
  * - enum
593
832
  * - timestamp
@@ -636,6 +875,9 @@ function getType(value) {
636
875
  if (value instanceof PGOid) {
637
876
  return { type: 'pgOid' };
638
877
  }
878
+ if (value instanceof Interval) {
879
+ return { type: 'interval' };
880
+ }
639
881
  if (value instanceof ProtoMessage) {
640
882
  return { type: 'proto', fullName: value.fullName };
641
883
  }
@@ -782,6 +1024,7 @@ exports.codec = {
782
1024
  ProtoMessage,
783
1025
  ProtoEnum,
784
1026
  PGOid,
1027
+ Interval,
785
1028
  convertFieldsToJson,
786
1029
  decode,
787
1030
  encode,
@@ -20,6 +20,7 @@ import { CallOptions, Operation as GaxOperation } from 'google-gax';
20
20
  import { BatchTransaction, TransactionIdentifier } from './batch-transaction';
21
21
  import { SessionFactoryInterface } from './session-factory';
22
22
  import { google as databaseAdmin, google, google as spannerClient } from '../protos/protos';
23
+ import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel;
23
24
  import { GetDatabaseOperationsOptions, GetDatabaseOperationsResponse, Instance, GetDatabaseOperationsCallback } from './instance';
24
25
  import { PartialResultStream } from './partial-result-stream';
25
26
  import { Session } from './session';
@@ -148,6 +149,9 @@ export interface RestoreOptions {
148
149
  encryptionConfig?: databaseAdmin.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig;
149
150
  gaxOptions?: CallOptions;
150
151
  }
152
+ export interface WriteAtLeastOnceOptions extends CallOptions {
153
+ isolationLevel?: IsolationLevel;
154
+ }
151
155
  /**
152
156
  * Create a Database object to interact with a Cloud Spanner database.
153
157
  *
@@ -184,7 +188,10 @@ declare class Database extends common.GrpcServiceObject {
184
188
  databaseDialect?: EnumKey<typeof databaseAdmin.spanner.admin.database.v1.DatabaseDialect> | null;
185
189
  _observabilityOptions?: ObservabilityOptions;
186
190
  private _traceConfig;
191
+ private _nthRequest;
192
+ _clientId: number;
187
193
  constructor(instance: Instance, name: string, poolOptions?: SessionPoolConstructor | SessionPoolOptions, queryOptions?: spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions);
194
+ _nextNthRequest(): number;
188
195
  /**
189
196
  * @typedef {array} SetDatabaseMetadataResponse
190
197
  * @property {object} 0 The {@link Database} metadata.
@@ -313,6 +320,11 @@ declare class Database extends common.GrpcServiceObject {
313
320
  */
314
321
  batchCreateSessions(options: number | BatchCreateSessionsOptions): Promise<BatchCreateSessionsResponse>;
315
322
  batchCreateSessions(options: number | BatchCreateSessionsOptions, callback: BatchCreateSessionsCallback): void;
323
+ _metadataWithRequestId(nthRequest: number, attempt: number, priorMetadata?: {
324
+ [k: string]: string;
325
+ }): {
326
+ [k: string]: string;
327
+ };
316
328
  /**
317
329
  * Get a reference to a {@link BatchTransaction} object.
318
330
  *
@@ -1896,9 +1908,9 @@ declare class Database extends common.GrpcServiceObject {
1896
1908
  * ```
1897
1909
  */
1898
1910
  writeAtLeastOnce(mutations: MutationSet): Promise<CommitResponse>;
1899
- writeAtLeastOnce(mutations: MutationSet, options: CallOptions): Promise<CommitResponse>;
1911
+ writeAtLeastOnce(mutations: MutationSet, options: WriteAtLeastOnceOptions): Promise<CommitResponse>;
1900
1912
  writeAtLeastOnce(mutations: MutationSet, callback: CommitCallback): void;
1901
- writeAtLeastOnce(mutations: MutationSet, options: CallOptions, callback: CommitCallback): void;
1913
+ writeAtLeastOnce(mutations: MutationSet, options: WriteAtLeastOnceOptions, callback: CommitCallback): void;
1902
1914
  /**
1903
1915
  * Create a Session object.
1904
1916
  *
@@ -35,6 +35,7 @@ const stream_1 = require("stream");
35
35
  const arrify = require("arrify");
36
36
  const snakeCase = require("lodash.snakecase");
37
37
  const instrument_1 = require("./instrument");
38
+ const request_id_header_1 = require("./request_id_header");
38
39
  /**
39
40
  * Create a Database object to interact with a Cloud Spanner database.
40
41
  *
@@ -154,6 +155,13 @@ class Database extends common.GrpcServiceObject {
154
155
  dbName: this.formattedName_,
155
156
  };
156
157
  this.request = instance.request;
158
+ this._nthRequest = (0, request_id_header_1.newAtomicCounter)(0);
159
+ if (this.parent && this.parent.parent) {
160
+ this._clientId = this.parent.parent._nthClientId;
161
+ }
162
+ else {
163
+ this._clientId = instance._nthClientId;
164
+ }
157
165
  this._observabilityOptions = instance._observabilityOptions;
158
166
  this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.formattedName_, (_a = this._observabilityOptions) === null || _a === void 0 ? void 0 : _a.enableEndToEndTracing);
159
167
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -167,6 +175,9 @@ class Database extends common.GrpcServiceObject {
167
175
  }
168
176
  this.queryOptions_ = Object.assign(Object.assign({}, queryOptions), Database.getEnvironmentQueryOptions());
169
177
  }
178
+ _nextNthRequest() {
179
+ return this._nthRequest.increment();
180
+ }
170
181
  setMetadata(metadata, optionsOrCallback, cb) {
171
182
  const gaxOpts = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
172
183
  const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
@@ -213,13 +224,14 @@ class Database extends common.GrpcServiceObject {
213
224
  if (this._getSpanner().routeToLeaderEnabled) {
214
225
  (0, common_1.addLeaderAwareRoutingHeader)(headers);
215
226
  }
227
+ const allHeaders = this._metadataWithRequestId(this._nextNthRequest(), 1, headers);
216
228
  (0, instrument_1.startTrace)('Database.batchCreateSessions', this._traceConfig, span => {
217
229
  this.request({
218
230
  client: 'SpannerClient',
219
231
  method: 'batchCreateSessions',
220
232
  reqOpts,
221
233
  gaxOpts: options.gaxOptions,
222
- headers: headers,
234
+ headers: allHeaders,
223
235
  }, (err, resp) => {
224
236
  if (err) {
225
237
  (0, instrument_1.setSpanError)(span, err);
@@ -238,6 +250,17 @@ class Database extends common.GrpcServiceObject {
238
250
  });
239
251
  });
240
252
  }
253
+ _metadataWithRequestId(nthRequest, attempt, priorMetadata) {
254
+ if (!priorMetadata) {
255
+ priorMetadata = {};
256
+ }
257
+ const withReqId = {
258
+ ...priorMetadata,
259
+ };
260
+ withReqId[request_id_header_1.X_GOOG_SPANNER_REQUEST_ID_HEADER] = (0, request_id_header_1.craftRequestId)(this._clientId || 1, 1, // TODO: Properly infer the channelId
261
+ nthRequest, attempt);
262
+ return withReqId;
263
+ }
241
264
  /**
242
265
  * Get a reference to a {@link BatchTransaction} object.
243
266
  *
@@ -330,7 +353,7 @@ class Database extends common.GrpcServiceObject {
330
353
  reqOpts.session.labels = options.labels || this.labels || null;
331
354
  reqOpts.session.creatorRole =
332
355
  options.databaseRole || this.databaseRole || null;
333
- const headers = this.commonHeaders_;
356
+ const headers = this._metadataWithRequestId(this._nextNthRequest(), 1, this.commonHeaders_);
334
357
  if (this._getSpanner().routeToLeaderEnabled) {
335
358
  (0, common_1.addLeaderAwareRoutingHeader)(headers);
336
359
  }
@@ -568,13 +591,14 @@ class Database extends common.GrpcServiceObject {
568
591
  delete gaxOpts.pageSize;
569
592
  delete gaxOpts.pageToken;
570
593
  }
594
+ const headers = this._metadataWithRequestId(this._nextNthRequest(), 1, this.commonHeaders_);
571
595
  return (0, instrument_1.startTrace)('Database.getSessions', this._traceConfig, span => {
572
596
  this.request({
573
597
  client: 'SpannerClient',
574
598
  method: 'listSessions',
575
599
  reqOpts,
576
600
  gaxOpts,
577
- headers: this.commonHeaders_,
601
+ headers: headers,
578
602
  }, (err, sessions, nextPageRequest, ...args) => {
579
603
  if (err) {
580
604
  (0, instrument_1.setSpanError)(span, err);
@@ -728,12 +752,7 @@ class Database extends common.GrpcServiceObject {
728
752
  if (options.requestOptions) {
729
753
  transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
730
754
  }
731
- if (options.optimisticLock) {
732
- transaction.useOptimisticLock();
733
- }
734
- if (options.excludeTxnFromChangeStreams) {
735
- transaction.excludeTxnFromChangeStreams();
736
- }
755
+ transaction === null || transaction === void 0 ? void 0 : transaction.setReadWriteTransactionOptions(options);
737
756
  if (!err) {
738
757
  span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
739
758
  transaction._observabilityOptions = this._observabilityOptions;
@@ -932,7 +951,7 @@ class Database extends common.GrpcServiceObject {
932
951
  ...this._traceConfig,
933
952
  };
934
953
  return (0, instrument_1.startTrace)('Database.runPartitionedUpdate', traceConfig, span => {
935
- this.pool_.getSession((err, session) => {
954
+ this.sessionFactory_.getSessionForPartitionedOps((err, session) => {
936
955
  if (err) {
937
956
  (0, instrument_1.setSpanError)(span, err);
938
957
  span.end();
@@ -956,21 +975,21 @@ class Database extends common.GrpcServiceObject {
956
975
  }
957
976
  transaction.begin(err => {
958
977
  if (err) {
959
- this.pool_.release(session);
978
+ this.sessionFactory_.release(session);
960
979
  callback(err, 0);
961
980
  return;
962
981
  }
963
982
  transaction.runUpdate(query, (err, updateCount) => {
964
983
  if (err) {
965
984
  if (err.code !== google_gax_1.grpc.status.ABORTED) {
966
- this.pool_.release(session);
985
+ this.sessionFactory_.release(session);
967
986
  callback(err, 0);
968
987
  return;
969
988
  }
970
989
  this._runPartitionedUpdate(session, query, callback);
971
990
  }
972
991
  else {
973
- this.pool_.release(session);
992
+ this.sessionFactory_.release(session);
974
993
  callback(null, updateCount);
975
994
  return;
976
995
  }
@@ -1195,12 +1214,7 @@ class Database extends common.GrpcServiceObject {
1195
1214
  return;
1196
1215
  }
1197
1216
  transaction._observabilityOptions = this._observabilityOptions;
1198
- if (options.optimisticLock) {
1199
- transaction.useOptimisticLock();
1200
- }
1201
- if (options.excludeTxnFromChangeStreams) {
1202
- transaction.excludeTxnFromChangeStreams();
1203
- }
1217
+ transaction.setReadWriteTransactionOptions(options);
1204
1218
  const release = () => {
1205
1219
  this.pool_.release(session);
1206
1220
  span.end();
@@ -1299,12 +1313,7 @@ class Database extends common.GrpcServiceObject {
1299
1313
  try {
1300
1314
  const [session, transaction] = await (0, promisify_1.promisify)(getSession)();
1301
1315
  transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1302
- if (options.optimisticLock) {
1303
- transaction.useOptimisticLock();
1304
- }
1305
- if (options.excludeTxnFromChangeStreams) {
1306
- transaction.excludeTxnFromChangeStreams();
1307
- }
1316
+ transaction.setReadWriteTransactionOptions(options);
1308
1317
  sessionId = session === null || session === void 0 ? void 0 : session.id;
1309
1318
  span.addEvent('Using Session', { 'session.id': sessionId });
1310
1319
  const runner = new transaction_runner_1.AsyncTransactionRunner(session, transaction, runFn, options);
@@ -1483,6 +1492,7 @@ class Database extends common.GrpcServiceObject {
1483
1492
  span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
1484
1493
  this._releaseOnEnd(session, transaction, span);
1485
1494
  try {
1495
+ transaction.setReadWriteTransactionOptions(options);
1486
1496
  transaction === null || transaction === void 0 ? void 0 : transaction.setQueuedMutations(mutations.proto());
1487
1497
  return transaction === null || transaction === void 0 ? void 0 : transaction.commit(options, (err, resp) => {
1488
1498
  if (err) {