@google-cloud/spanner 7.8.0 → 7.9.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,28 @@
4
4
 
5
5
  [1]: https://www.npmjs.com/package/nodejs-spanner?activeTab=versions
6
6
 
7
+ ## [7.9.1](https://github.com/googleapis/nodejs-spanner/compare/v7.9.0...v7.9.1) (2024-06-26)
8
+
9
+
10
+ ### Bug Fixes
11
+
12
+ * Retry with timeout ([#2071](https://github.com/googleapis/nodejs-spanner/issues/2071)) ([a943257](https://github.com/googleapis/nodejs-spanner/commit/a943257a0402b26fd80196057a9724fd28fc5c1b))
13
+
14
+ ## [7.9.0](https://github.com/googleapis/nodejs-spanner/compare/v7.8.0...v7.9.0) (2024-06-21)
15
+
16
+
17
+ ### Features
18
+
19
+ * **spanner:** Add support for batchWrite ([#2054](https://github.com/googleapis/nodejs-spanner/issues/2054)) ([06aab6e](https://github.com/googleapis/nodejs-spanner/commit/06aab6e39bbce9e3786f1ac631c80e8909197e92))
20
+
21
+
22
+ ### Bug Fixes
23
+
24
+ * **deps:** Update dependency google-gax to v4.3.4 ([#2051](https://github.com/googleapis/nodejs-spanner/issues/2051)) ([80abf06](https://github.com/googleapis/nodejs-spanner/commit/80abf06ba8ef9497318ffc597b83fb63e4408f9c))
25
+ * **deps:** Update dependency google-gax to v4.3.5 ([#2055](https://github.com/googleapis/nodejs-spanner/issues/2055)) ([702c9b0](https://github.com/googleapis/nodejs-spanner/commit/702c9b0f34e6cc34233c5aa52b97601b19f70980))
26
+ * **deps:** Update dependency google-gax to v4.3.6 ([#2057](https://github.com/googleapis/nodejs-spanner/issues/2057)) ([74ebf1e](https://github.com/googleapis/nodejs-spanner/commit/74ebf1e45cddf614c180295f3a761a8f84c5cb32))
27
+ * **deps:** Update dependency google-gax to v4.3.7 ([#2068](https://github.com/googleapis/nodejs-spanner/issues/2068)) ([28fec6c](https://github.com/googleapis/nodejs-spanner/commit/28fec6ca505d78d725efc123950be978e0c84ab7))
28
+
7
29
  ## [7.8.0](https://github.com/googleapis/nodejs-spanner/compare/v7.7.0...v7.8.0) (2024-05-24)
8
30
 
9
31
 
package/README.md CHANGED
@@ -102,6 +102,7 @@ Samples are in the [`samples/`](https://github.com/googleapis/nodejs-spanner/tre
102
102
  | Backups-restore | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-restore.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-restore.js,samples/README.md) |
103
103
  | Backups-update | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-update.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-update.js,samples/README.md) |
104
104
  | Backups | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups.js,samples/README.md) |
105
+ | Batch Write | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/batch-write.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/batch-write.js,samples/README.md) |
105
106
  | Batch | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/batch.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/batch.js,samples/README.md) |
106
107
  | CRUD | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/crud.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/crud.js,samples/README.md) |
107
108
  | Creates a new database with a specific default leader | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-create-with-default-leader.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-create-with-default-leader.js,samples/README.md) |
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { Big } from 'big.js';
3
2
  import { common as p } from 'protobufjs';
4
3
  import { google as spannerClient } from '../protos/protos';
@@ -13,7 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- /// <reference types="node" />
17
16
  import { Abortable, BodyResponseCallback, DecorateRequestOptions, Service, ServiceConfig } from '@google-cloud/common';
18
17
  import { grpc } from 'google-gax';
19
18
  import { Request, Response } from 'teeny-request';
@@ -15,7 +15,8 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.addLeaderAwareRoutingHeader = exports.LEADER_AWARE_ROUTING_HEADER = exports.CLOUD_RESOURCE_HEADER = void 0;
18
+ exports.LEADER_AWARE_ROUTING_HEADER = exports.CLOUD_RESOURCE_HEADER = void 0;
19
+ exports.addLeaderAwareRoutingHeader = addLeaderAwareRoutingHeader;
19
20
  /*!
20
21
  * HTTP header for the resource prefix to improve routing
21
22
  * by the backend.
@@ -32,5 +33,4 @@ exports.LEADER_AWARE_ROUTING_HEADER = 'x-goog-spanner-route-to-leader';
32
33
  function addLeaderAwareRoutingHeader(headers) {
33
34
  headers[exports.LEADER_AWARE_ROUTING_HEADER] = 'true';
34
35
  }
35
- exports.addLeaderAwareRoutingHeader = addLeaderAwareRoutingHeader;
36
36
  //# sourceMappingURL=common.js.map
@@ -13,8 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- /// <reference types="node" />
17
- /// <reference types="node" />
18
16
  import { ExistsCallback, GetConfig } from '@google-cloud/common';
19
17
  declare const common: any;
20
18
  import * as r from 'teeny-request';
@@ -26,7 +24,7 @@ import { PartialResultStream } from './partial-result-stream';
26
24
  import { Session } from './session';
27
25
  import { SessionPoolCloseCallback, SessionPoolInterface, SessionPoolOptions } from './session-pool';
28
26
  import { CreateTableCallback, CreateTableResponse, Table } from './table';
29
- import { ExecuteSqlRequest, RunCallback, RunResponse, RunUpdateCallback, Snapshot, TimestampBounds, Transaction } from './transaction';
27
+ import { BatchWriteOptions, ExecuteSqlRequest, MutationGroup, RunCallback, RunResponse, RunUpdateCallback, Snapshot, TimestampBounds, Transaction } from './transaction';
30
28
  import { AsyncRunTransactionCallback, RunTransactionCallback, RunTransactionOptions } from './transaction-runner';
31
29
  import { IOperation, LongRunningCallback, NormalCallback, PagedOptionsWithFilter, PagedResponse, RequestCallback, ResourceCallback, Schema } from './common';
32
30
  import { Duplex, Readable } from 'stream';
@@ -1779,6 +1777,65 @@ declare class Database extends common.GrpcServiceObject {
1779
1777
  runTransaction(options: RunTransactionOptions, runFn: RunTransactionCallback): void;
1780
1778
  runTransactionAsync<T = {}>(runFn: AsyncRunTransactionCallback<T>): Promise<T>;
1781
1779
  runTransactionAsync<T = {}>(options: RunTransactionOptions, runFn: AsyncRunTransactionCallback<T>): Promise<T>;
1780
+ /**
1781
+ * Write a batch of mutations to Spanner.
1782
+ *
1783
+ * All mutations in a group are committed atomically. However, mutations across
1784
+ * groups can be committed non-atomically in an unspecified order and thus, they
1785
+ * must be independent of each other. Partial failure is possible, i.e., some groups
1786
+ * may have been committed successfully, while some may have failed. The results of
1787
+ * individual batches are streamed into the response as the batches are applied.
1788
+ *
1789
+ * batchWriteAtLeastOnce requests are not replay protected, meaning that each mutation group may
1790
+ * be applied more than once. Replays of non-idempotent mutations may have undesirable
1791
+ * effects. For example, replays of an insert mutation may produce an already exists
1792
+ * error or if you use generated or commit timestamp-based keys, it may result in additional
1793
+ * rows being added to the mutation's table. We recommend structuring your mutation groups to
1794
+ * be idempotent to avoid this issue.
1795
+ *
1796
+ * @method Spanner#batchWriteAtLeastOnce
1797
+ *
1798
+ * @param {MutationGroup[]} [mutationGroups] The group of mutations to be applied.
1799
+ * @param {BatchWriteOptions} [options] Options object for batch write request.
1800
+ *
1801
+ * @returns {ReadableStream} An object stream which emits
1802
+ * {@link protos.google.spanner.v1.BatchWriteResponse|BatchWriteResponse}
1803
+ * on 'data' event.
1804
+ *
1805
+ * @example
1806
+ * ```
1807
+ * const {Spanner} = require('@google-cloud/spanner');
1808
+ * const spanner = new Spanner();
1809
+ *
1810
+ * const instance = spanner.instance('my-instance');
1811
+ * const database = instance.database('my-database');
1812
+ * const mutationGroup = new MutationGroup();
1813
+ * mutationGroup.insert('Singers', {
1814
+ * SingerId: '1',
1815
+ * FirstName: 'Marc',
1816
+ * LastName: 'Richards',
1817
+ * });
1818
+ *
1819
+ * database.batchWriteAtLeastOnce([mutationGroup])
1820
+ * .on('error', console.error)
1821
+ * .on('data', response => {
1822
+ * console.log('response: ', response);
1823
+ * })
1824
+ * .on('end', () => {
1825
+ * console.log('Request completed successfully');
1826
+ * });
1827
+ *
1828
+ * //-
1829
+ * // If you anticipate many results, you can end a stream early to prevent
1830
+ * // unnecessary processing and API requests.
1831
+ * //-
1832
+ * database.batchWriteAtLeastOnce()
1833
+ * .on('data', response => {
1834
+ * this.end();
1835
+ * });
1836
+ * ```
1837
+ */
1838
+ batchWriteAtLeastOnce(mutationGroups: MutationGroup[], options?: BatchWriteOptions): NodeJS.ReadableStream;
1782
1839
  /**
1783
1840
  * Create a Session object.
1784
1841
  *
@@ -1150,6 +1150,112 @@ class Database extends common.GrpcServiceObject {
1150
1150
  }
1151
1151
  }
1152
1152
  }
1153
+ /**
1154
+ * Write a batch of mutations to Spanner.
1155
+ *
1156
+ * All mutations in a group are committed atomically. However, mutations across
1157
+ * groups can be committed non-atomically in an unspecified order and thus, they
1158
+ * must be independent of each other. Partial failure is possible, i.e., some groups
1159
+ * may have been committed successfully, while some may have failed. The results of
1160
+ * individual batches are streamed into the response as the batches are applied.
1161
+ *
1162
+ * batchWriteAtLeastOnce requests are not replay protected, meaning that each mutation group may
1163
+ * be applied more than once. Replays of non-idempotent mutations may have undesirable
1164
+ * effects. For example, replays of an insert mutation may produce an already exists
1165
+ * error or if you use generated or commit timestamp-based keys, it may result in additional
1166
+ * rows being added to the mutation's table. We recommend structuring your mutation groups to
1167
+ * be idempotent to avoid this issue.
1168
+ *
1169
+ * @method Spanner#batchWriteAtLeastOnce
1170
+ *
1171
+ * @param {MutationGroup[]} [mutationGroups] The group of mutations to be applied.
1172
+ * @param {BatchWriteOptions} [options] Options object for batch write request.
1173
+ *
1174
+ * @returns {ReadableStream} An object stream which emits
1175
+ * {@link protos.google.spanner.v1.BatchWriteResponse|BatchWriteResponse}
1176
+ * on 'data' event.
1177
+ *
1178
+ * @example
1179
+ * ```
1180
+ * const {Spanner} = require('@google-cloud/spanner');
1181
+ * const spanner = new Spanner();
1182
+ *
1183
+ * const instance = spanner.instance('my-instance');
1184
+ * const database = instance.database('my-database');
1185
+ * const mutationGroup = new MutationGroup();
1186
+ * mutationGroup.insert('Singers', {
1187
+ * SingerId: '1',
1188
+ * FirstName: 'Marc',
1189
+ * LastName: 'Richards',
1190
+ * });
1191
+ *
1192
+ * database.batchWriteAtLeastOnce([mutationGroup])
1193
+ * .on('error', console.error)
1194
+ * .on('data', response => {
1195
+ * console.log('response: ', response);
1196
+ * })
1197
+ * .on('end', () => {
1198
+ * console.log('Request completed successfully');
1199
+ * });
1200
+ *
1201
+ * //-
1202
+ * // If you anticipate many results, you can end a stream early to prevent
1203
+ * // unnecessary processing and API requests.
1204
+ * //-
1205
+ * database.batchWriteAtLeastOnce()
1206
+ * .on('data', response => {
1207
+ * this.end();
1208
+ * });
1209
+ * ```
1210
+ */
1211
+ batchWriteAtLeastOnce(mutationGroups, options) {
1212
+ const proxyStream = through.obj();
1213
+ this.pool_.getSession((err, session) => {
1214
+ if (err) {
1215
+ proxyStream.destroy(err);
1216
+ return;
1217
+ }
1218
+ const gaxOpts = extend(true, {}, options === null || options === void 0 ? void 0 : options.gaxOptions);
1219
+ const reqOpts = Object.assign({}, {
1220
+ session: session.formattedName_,
1221
+ mutationGroups: mutationGroups.map(mg => mg.proto()),
1222
+ requestOptions: options === null || options === void 0 ? void 0 : options.requestOptions,
1223
+ });
1224
+ let dataReceived = false;
1225
+ let dataStream = this.requestStream({
1226
+ client: 'SpannerClient',
1227
+ method: 'batchWrite',
1228
+ reqOpts,
1229
+ gaxOpts,
1230
+ headers: this.resourceHeader_,
1231
+ });
1232
+ dataStream
1233
+ .once('data', () => (dataReceived = true))
1234
+ .once('error', err => {
1235
+ if (!dataReceived &&
1236
+ (0, session_pool_1.isSessionNotFoundError)(err)) {
1237
+ // If there's a 'Session not found' error and we have not yet received
1238
+ // any data, we can safely retry the writes on a new session.
1239
+ // Register the error on the session so the pool can discard it.
1240
+ if (session) {
1241
+ session.lastError = err;
1242
+ }
1243
+ // Remove the current data stream from the end user stream.
1244
+ dataStream.unpipe(proxyStream);
1245
+ dataStream.end();
1246
+ // Create a new stream and add it to the end user stream.
1247
+ dataStream = this.batchWriteAtLeastOnce(mutationGroups, options);
1248
+ dataStream.pipe(proxyStream);
1249
+ }
1250
+ else {
1251
+ proxyStream.destroy(err);
1252
+ }
1253
+ })
1254
+ .once('end', () => this.pool_.release(session))
1255
+ .pipe(proxyStream);
1256
+ });
1257
+ return proxyStream;
1258
+ }
1153
1259
  /**
1154
1260
  * Create a Session object.
1155
1261
  *
@@ -1259,6 +1365,7 @@ exports.Database = Database;
1259
1365
  (0, promisify_1.promisifyAll)(Database, {
1260
1366
  exclude: [
1261
1367
  'batchTransaction',
1368
+ 'batchWriteAtLeastOnce',
1262
1369
  'getRestoreInfo',
1263
1370
  'getState',
1264
1371
  'getDatabaseDialect',
@@ -1279,6 +1386,7 @@ exports.Database = Database;
1279
1386
  'create',
1280
1387
  'batchCreateSessions',
1281
1388
  'batchTransaction',
1389
+ 'batchWriteAtLeastOnce',
1282
1390
  'close',
1283
1391
  'createBatchTransaction',
1284
1392
  'createSession',
@@ -13,7 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- /// <reference types="node" />
17
16
  import { GrpcService } from './common-grpc/service';
18
17
  import { PreciseDate } from '@google-cloud/precise-date';
19
18
  import { GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
@@ -29,7 +28,7 @@ import { PagedOptions, PagedResponse, PagedCallback, PagedOptionsWithFilter, Nor
29
28
  import { Session } from './session';
30
29
  import { SessionPool } from './session-pool';
31
30
  import { Table } from './table';
32
- import { PartitionedDml, Snapshot, Transaction } from './transaction';
31
+ import { MutationGroup, PartitionedDml, Snapshot, Transaction } from './transaction';
33
32
  import * as v1 from './v1';
34
33
  export type IOperation = instanceAdmin.longrunning.IOperation;
35
34
  export type GetInstancesOptions = PagedOptionsWithFilter;
@@ -1156,6 +1155,14 @@ export { Snapshot };
1156
1155
  * @type {Constructor}
1157
1156
  */
1158
1157
  export { Transaction };
1158
+ /**
1159
+ * {@link MutationGroup} class.
1160
+ *
1161
+ * @name Spanner.MutationGroup
1162
+ * @see MutationGroup
1163
+ * @type {Constructor}
1164
+ */
1165
+ export { MutationGroup };
1159
1166
  /**
1160
1167
  * @type {object}
1161
1168
  * @property {constructor} DatabaseAdminClient
@@ -15,7 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.SpannerDate = exports.PGNumeric = exports.Numeric = exports.Struct = exports.Int = exports.Float = exports.Float32 = exports.protos = exports.v1 = exports.Transaction = exports.Snapshot = exports.PartitionedDml = exports.Table = exports.SessionPool = exports.Session = exports.Backup = exports.Database = exports.InstanceConfig = exports.Instance = exports.Spanner = void 0;
18
+ exports.SpannerDate = exports.PGNumeric = exports.Numeric = exports.Struct = exports.Int = exports.Float = exports.Float32 = exports.protos = exports.v1 = exports.MutationGroup = exports.Transaction = exports.Snapshot = exports.PartitionedDml = exports.Table = exports.SessionPool = exports.Session = exports.Backup = exports.Database = exports.InstanceConfig = exports.Instance = exports.Spanner = void 0;
19
19
  const service_1 = require("./common-grpc/service");
20
20
  const precise_date_1 = require("@google-cloud/precise-date");
21
21
  const projectify_1 = require("@google-cloud/projectify");
@@ -51,6 +51,7 @@ Object.defineProperty(exports, "SessionPool", { enumerable: true, get: function
51
51
  const table_1 = require("./table");
52
52
  Object.defineProperty(exports, "Table", { enumerable: true, get: function () { return table_1.Table; } });
53
53
  const transaction_1 = require("./transaction");
54
+ Object.defineProperty(exports, "MutationGroup", { enumerable: true, get: function () { return transaction_1.MutationGroup; } });
54
55
  Object.defineProperty(exports, "PartitionedDml", { enumerable: true, get: function () { return transaction_1.PartitionedDml; } });
55
56
  Object.defineProperty(exports, "Snapshot", { enumerable: true, get: function () { return transaction_1.Snapshot; } });
56
57
  Object.defineProperty(exports, "Transaction", { enumerable: true, get: function () { return transaction_1.Transaction; } });
@@ -13,8 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- /// <reference types="node" />
17
- /// <reference types="node" />
18
16
  import { GetConfig } from '@google-cloud/common';
19
17
  declare const common: any;
20
18
  import { Database, SessionPoolConstructor } from './database';
@@ -13,8 +13,8 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- /// <reference types="node" />
17
16
  import { Readable, Transform } from 'stream';
17
+ import { CallOptions } from 'google-gax';
18
18
  import { JSONOptions, Json, Field, Value } from './codec';
19
19
  import { google } from '../protos/protos';
20
20
  export type ResumeToken = string | Uint8Array;
@@ -82,6 +82,7 @@ export interface RowOptions {
82
82
  * };
83
83
  */
84
84
  columnsMetadata?: object;
85
+ gaxOptions?: CallOptions;
85
86
  }
86
87
  /**
87
88
  * By default rows are an Array of values in the form of objects containing
@@ -15,7 +15,8 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.partialResultStream = exports.PartialResultStream = void 0;
18
+ exports.PartialResultStream = void 0;
19
+ exports.partialResultStream = partialResultStream;
19
20
  const service_1 = require("./common-grpc/service");
20
21
  const checkpointStream = require("checkpoint-stream");
21
22
  const eventsIntercept = require("events-intercept");
@@ -283,10 +284,13 @@ exports.PartialResultStream = PartialResultStream;
283
284
  * @returns {PartialResultStream}
284
285
  */
285
286
  function partialResultStream(requestFn, options) {
287
+ var _a, _b;
286
288
  const retryableCodes = [google_gax_1.grpc.status.UNAVAILABLE];
287
289
  const maxQueued = 10;
288
290
  let lastResumeToken;
289
291
  let lastRequestStream;
292
+ const startTime = Date.now();
293
+ const timeout = (_b = (_a = options === null || options === void 0 ? void 0 : options.gaxOptions) === null || _a === void 0 ? void 0 : _a.timeout) !== null && _b !== void 0 ? _b : Infinity;
290
294
  // mergeStream allows multiple streams to be connected into one. This is good;
291
295
  // if we need to retry a request and pipe more data to the user's stream.
292
296
  // We also add an additional stream that can be used to flush any remaining
@@ -335,6 +339,14 @@ function partialResultStream(requestFn, options) {
335
339
  requestsStream.add(lastRequestStream);
336
340
  };
337
341
  const retry = (err) => {
342
+ const elapsed = Date.now() - startTime;
343
+ if (elapsed >= timeout) {
344
+ // The timeout has reached so this will flush any rows the
345
+ // checkpoint stream has queued. After that, we will destroy the
346
+ // user's stream with the Deadline exceeded error.
347
+ setImmediate(() => batchAndSplitOnTokenStream.destroy(new transaction_runner_1.DeadlineError(err)));
348
+ return;
349
+ }
338
350
  if (!(err.code &&
339
351
  (retryableCodes.includes(err.code) || (0, transaction_runner_1.isRetryableInternalError)(err))) ||
340
352
  // If we have received too many chunks without a resume token, it is not
@@ -382,7 +394,6 @@ function partialResultStream(requestFn, options) {
382
394
  .on('paused', () => requestsStream.pause())
383
395
  .on('resumed', () => requestsStream.resume()));
384
396
  }
385
- exports.partialResultStream = partialResultStream;
386
397
  function _hasResumeToken(chunk) {
387
398
  return is.defined(chunk.resumeToken) && chunk.resumeToken.length > 0;
388
399
  }
@@ -13,8 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- /// <reference types="node" />
17
- /// <reference types="node" />
18
16
  import { EventEmitter } from 'events';
19
17
  import PQueue from 'p-queue';
20
18
  import { Database } from './database';
@@ -15,7 +15,13 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.SessionPool = exports.isProjectIdNotSetInEnvironmentError = exports.isDefaultCredentialsNotSetError = exports.isCreateSessionPermissionError = exports.isInstanceNotFoundError = exports.isDatabaseNotFoundError = exports.isSessionNotFoundError = exports.SessionPoolExhaustedError = exports.SessionLeakError = exports.ReleaseError = void 0;
18
+ exports.SessionPool = exports.SessionPoolExhaustedError = exports.SessionLeakError = exports.ReleaseError = void 0;
19
+ exports.isSessionNotFoundError = isSessionNotFoundError;
20
+ exports.isDatabaseNotFoundError = isDatabaseNotFoundError;
21
+ exports.isInstanceNotFoundError = isInstanceNotFoundError;
22
+ exports.isCreateSessionPermissionError = isCreateSessionPermissionError;
23
+ exports.isDefaultCredentialsNotSetError = isDefaultCredentialsNotSetError;
24
+ exports.isProjectIdNotSetInEnvironmentError = isProjectIdNotSetInEnvironmentError;
19
25
  const events_1 = require("events");
20
26
  const is = require("is");
21
27
  const p_queue_1 = require("p-queue");
@@ -82,7 +88,6 @@ function isSessionNotFoundError(error) {
82
88
  error.code === google_gax_1.grpc.status.NOT_FOUND &&
83
89
  error.message.includes('Session not found'));
84
90
  }
85
- exports.isSessionNotFoundError = isSessionNotFoundError;
86
91
  /**
87
92
  * Checks whether the given error is a 'Database not found' error.
88
93
  * @param {Error} error The error to check.
@@ -93,7 +98,6 @@ function isDatabaseNotFoundError(error) {
93
98
  error.code === google_gax_1.grpc.status.NOT_FOUND &&
94
99
  error.message.includes('Database not found'));
95
100
  }
96
- exports.isDatabaseNotFoundError = isDatabaseNotFoundError;
97
101
  /**
98
102
  * Checks whether the given error is an 'Instance not found' error.
99
103
  * @param {Error} error The error to check.
@@ -104,7 +108,6 @@ function isInstanceNotFoundError(error) {
104
108
  error.code === google_gax_1.grpc.status.NOT_FOUND &&
105
109
  error.message.includes('Instance not found'));
106
110
  }
107
- exports.isInstanceNotFoundError = isInstanceNotFoundError;
108
111
  /**
109
112
  * Checks whether the given error is a 'Create session permission' error.
110
113
  * @param {Error} error The error to check.
@@ -115,7 +118,6 @@ function isCreateSessionPermissionError(error) {
115
118
  error.code === google_gax_1.grpc.status.PERMISSION_DENIED &&
116
119
  error.message.includes('spanner.sessions.create'));
117
120
  }
118
- exports.isCreateSessionPermissionError = isCreateSessionPermissionError;
119
121
  /**
120
122
  * Checks whether the given error is a 'Could not load the default credentials' error.
121
123
  * @param {Error} error The error to check.
@@ -125,7 +127,6 @@ function isDefaultCredentialsNotSetError(error) {
125
127
  return (error !== undefined &&
126
128
  error.message.includes('Could not load the default credentials'));
127
129
  }
128
- exports.isDefaultCredentialsNotSetError = isDefaultCredentialsNotSetError;
129
130
  /**
130
131
  * Checks whether the given error is an 'Unable to detect a Project Id in the current environment' error.
131
132
  * @param {Error} error The error to check.
@@ -135,7 +136,6 @@ function isProjectIdNotSetInEnvironmentError(error) {
135
136
  return (error !== undefined &&
136
137
  error.message.includes('Unable to detect a Project Id in the current environment'));
137
138
  }
138
- exports.isProjectIdNotSetInEnvironmentError = isProjectIdNotSetInEnvironmentError;
139
139
  /**
140
140
  * Class used to manage connections to Spanner.
141
141
  *
@@ -15,7 +15,8 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.isRetryableInternalError = exports.AsyncTransactionRunner = exports.TransactionRunner = exports.Runner = exports.DeadlineError = void 0;
18
+ exports.AsyncTransactionRunner = exports.TransactionRunner = exports.Runner = exports.DeadlineError = void 0;
19
+ exports.isRetryableInternalError = isRetryableInternalError;
19
20
  const promisify_1 = require("@google-cloud/promisify");
20
21
  const google_gax_1 = require("google-gax");
21
22
  const protobufjs_1 = require("protobufjs");
@@ -278,5 +279,4 @@ function isRetryableInternalError(err) {
278
279
  err.message.includes('HTTP/2 error code: INTERNAL_ERROR') ||
279
280
  err.message.includes('Connection closed with unknown cause')));
280
281
  }
281
- exports.isRetryableInternalError = isRetryableInternalError;
282
282
  //# sourceMappingURL=transaction-runner.js.map
@@ -13,8 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- /// <reference types="node" />
17
- /// <reference types="node" />
18
16
  import { PreciseDate } from '@google-cloud/precise-date';
19
17
  import Long = require('long');
20
18
  import { EventEmitter } from 'events';
@@ -40,6 +38,10 @@ export interface TimestampBounds {
40
38
  exactStaleness?: number | spannerClient.protobuf.IDuration;
41
39
  returnReadTimestamp?: boolean;
42
40
  }
41
+ export interface BatchWriteOptions {
42
+ requestOptions?: Pick<IRequestOptions, 'priority' | 'transactionTag'>;
43
+ gaxOptions?: CallOptions;
44
+ }
43
45
  export interface RequestOptions {
44
46
  json?: boolean;
45
47
  jsonOptions?: JSONOptions;
@@ -1499,6 +1501,47 @@ export declare class Transaction extends Dml {
1499
1501
  */
1500
1502
  excludeTxnFromChangeStreams(): void;
1501
1503
  }
1504
+ /**
1505
+ * A group of mutations to be committed together.
1506
+ * Related mutations should be placed in a group.
1507
+ *
1508
+ * For example, two mutations inserting rows with the same primary
1509
+ * key prefix in both parent and child tables are related.
1510
+ *
1511
+ * This object is created and returned from {@link Database#MutationGroup}.
1512
+ *
1513
+ * @example
1514
+ * ```
1515
+ * const {Spanner} = require('@google-cloud/spanner');
1516
+ * const spanner = new Spanner();
1517
+ *
1518
+ * const instance = spanner.instance('my-instance');
1519
+ * const database = instance.database('my-database');
1520
+ *
1521
+ * const mutationGroup = new MutationGroup();
1522
+ * mutationGroup.insert('Singers', {SingerId: '123', FirstName: 'David'});
1523
+ * mutationGroup.update('Singers', {SingerId: '123', FirstName: 'Marc'});
1524
+ *
1525
+ * database.batchWriteAtLeastOnce([mutationGroup], {})
1526
+ * .on('error', console.error)
1527
+ * .on('data', response => {
1528
+ * console.log('response: ', response);
1529
+ * })
1530
+ * .on('end', () => {
1531
+ * console.log('Request completed successfully');
1532
+ * });
1533
+ * ```
1534
+ */
1535
+ export declare class MutationGroup {
1536
+ private _proto;
1537
+ constructor();
1538
+ insert(table: string, rows: object | object[]): void;
1539
+ update(table: string, rows: object | object[]): void;
1540
+ upsert(table: string, rows: object | object[]): void;
1541
+ replace(table: string, rows: object | object[]): void;
1542
+ deleteRows(table: string, keys: Key[]): void;
1543
+ proto(): spannerClient.spanner.v1.BatchWriteRequest.IMutationGroup;
1544
+ }
1502
1545
  /**
1503
1546
  * This type of transaction is used to execute a single Partitioned DML
1504
1547
  * statement. Partitioned DML partitions the key space and runs the DML
@@ -15,7 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.PartitionedDml = exports.Transaction = exports.Dml = exports.Snapshot = void 0;
18
+ exports.PartitionedDml = exports.MutationGroup = exports.Transaction = exports.Dml = exports.Snapshot = void 0;
19
19
  const precise_date_1 = require("@google-cloud/precise-date");
20
20
  const promisify_1 = require("@google-cloud/promisify");
21
21
  const arrify = require("arrify");
@@ -25,9 +25,10 @@ const is = require("is");
25
25
  const stream_1 = require("stream");
26
26
  const codec_1 = require("./codec");
27
27
  const partial_result_stream_1 = require("./partial-result-stream");
28
- const common_1 = require("./common");
29
28
  const protos_1 = require("../protos/protos");
30
- var ReadLockMode = protos_1.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
29
+ const common_1 = require("./common");
30
+ const protos_2 = require("../protos/protos");
31
+ var ReadLockMode = protos_2.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
31
32
  const RETRY_INFO_TYPE = 'type.googleapis.com/google.rpc.retryinfo';
32
33
  const RETRY_INFO_BIN = 'google.rpc.retryinfo-bin';
33
34
  /**
@@ -409,6 +410,7 @@ class Snapshot extends events_1.EventEmitter {
409
410
  jsonOptions,
410
411
  maxResumeRetries,
411
412
  columnsMetadata,
413
+ gaxOptions,
412
414
  })) === null || _c === void 0 ? void 0 : _c.on('response', response => {
413
415
  if (response.metadata && response.metadata.transaction && !this.id) {
414
416
  this._update(response.metadata.transaction);
@@ -676,6 +678,7 @@ class Snapshot extends events_1.EventEmitter {
676
678
  jsonOptions,
677
679
  maxResumeRetries,
678
680
  columnsMetadata,
681
+ gaxOptions,
679
682
  })
680
683
  .on('response', response => {
681
684
  if (response.metadata && response.metadata.transaction && !this.id) {
@@ -1251,13 +1254,7 @@ class Transaction extends Dml {
1251
1254
  * ```
1252
1255
  */
1253
1256
  deleteRows(table, keys) {
1254
- const keySet = {
1255
- keys: arrify(keys).map(codec_1.codec.convertToListValue),
1256
- };
1257
- const mutation = {
1258
- delete: { table, keySet },
1259
- };
1260
- this._queuedMutations.push(mutation);
1257
+ this._queuedMutations.push(buildDeleteMutation(table, keys));
1261
1258
  }
1262
1259
  /**
1263
1260
  * Insert rows of data into this table.
@@ -1475,24 +1472,7 @@ class Transaction extends Dml {
1475
1472
  * @param {object} rows Hash of key value pairs.
1476
1473
  */
1477
1474
  _mutate(method, table, keyVals) {
1478
- const rows = arrify(keyVals);
1479
- const columns = Transaction.getUniqueKeys(rows);
1480
- const values = rows.map((row, index) => {
1481
- const keys = Object.keys(row);
1482
- const missingColumns = columns.filter(column => !keys.includes(column));
1483
- if (missingColumns.length > 0) {
1484
- throw new google_gax_1.GoogleError([
1485
- `Row at index ${index} does not contain the correct number of columns.`,
1486
- `Missing columns: ${JSON.stringify(missingColumns)}`,
1487
- ].join('\n\n'));
1488
- }
1489
- const values = columns.map(column => row[column]);
1490
- return codec_1.codec.convertToListValue(values);
1491
- });
1492
- const mutation = {
1493
- [method]: { table, columns, values },
1494
- };
1495
- this._queuedMutations.push(mutation);
1475
+ this._queuedMutations.push(buildMutation(method, table, keyVals));
1496
1476
  }
1497
1477
  /**
1498
1478
  * Takes a list of rows and returns all unique column names.
@@ -1548,6 +1528,107 @@ exports.Transaction = Transaction;
1548
1528
  (0, promisify_1.promisifyAll)(Transaction, {
1549
1529
  exclude: ['deleteRows', 'insert', 'replace', 'update', 'upsert'],
1550
1530
  });
1531
+ /**
1532
+ * Builds an array of protobuf Mutations from the given row(s).
1533
+ *
1534
+ * @param {string} method - CRUD method (insert, update, etc.).
1535
+ * @param {string} table - Table to perform mutations in.
1536
+ * @param {object | object[]} keyVals - Hash of key-value pairs representing the rows.
1537
+ * @returns {spannerClient.spanner.v1.Mutation} - The formatted mutation.
1538
+ * @throws {GoogleError} - If a row does not contain the correct number of columns.
1539
+ */
1540
+ function buildMutation(method, table, keyVals) {
1541
+ const rows = arrify(keyVals);
1542
+ const columns = Transaction.getUniqueKeys(rows);
1543
+ const values = rows.map((row, index) => {
1544
+ const keys = Object.keys(row);
1545
+ const missingColumns = columns.filter(column => !keys.includes(column));
1546
+ if (missingColumns.length > 0) {
1547
+ throw new google_gax_1.GoogleError([
1548
+ `Row at index ${index} does not contain the correct number of columns.`,
1549
+ `Missing columns: ${JSON.stringify(missingColumns)}`,
1550
+ ].join('\n\n'));
1551
+ }
1552
+ const values = columns.map(column => row[column]);
1553
+ return codec_1.codec.convertToListValue(values);
1554
+ });
1555
+ const mutation = {
1556
+ [method]: { table, columns, values },
1557
+ };
1558
+ return mutation;
1559
+ }
1560
+ /**
1561
+ * Builds a delete mutation.
1562
+ *
1563
+ * @param {string} table - The name of the table.
1564
+ * @param {Key[]} keys - The keys for the rows to delete.
1565
+ * @returns {spannerClient.spanner.v1.Mutation} - The formatted delete mutation.
1566
+ */
1567
+ function buildDeleteMutation(table, keys) {
1568
+ const keySet = {
1569
+ keys: arrify(keys).map(codec_1.codec.convertToListValue),
1570
+ };
1571
+ const mutation = {
1572
+ delete: { table, keySet },
1573
+ };
1574
+ return mutation;
1575
+ }
1576
+ /**
1577
+ * A group of mutations to be committed together.
1578
+ * Related mutations should be placed in a group.
1579
+ *
1580
+ * For example, two mutations inserting rows with the same primary
1581
+ * key prefix in both parent and child tables are related.
1582
+ *
1583
+ * This object is created and returned from {@link Database#MutationGroup}.
1584
+ *
1585
+ * @example
1586
+ * ```
1587
+ * const {Spanner} = require('@google-cloud/spanner');
1588
+ * const spanner = new Spanner();
1589
+ *
1590
+ * const instance = spanner.instance('my-instance');
1591
+ * const database = instance.database('my-database');
1592
+ *
1593
+ * const mutationGroup = new MutationGroup();
1594
+ * mutationGroup.insert('Singers', {SingerId: '123', FirstName: 'David'});
1595
+ * mutationGroup.update('Singers', {SingerId: '123', FirstName: 'Marc'});
1596
+ *
1597
+ * database.batchWriteAtLeastOnce([mutationGroup], {})
1598
+ * .on('error', console.error)
1599
+ * .on('data', response => {
1600
+ * console.log('response: ', response);
1601
+ * })
1602
+ * .on('end', () => {
1603
+ * console.log('Request completed successfully');
1604
+ * });
1605
+ * ```
1606
+ */
1607
+ class MutationGroup {
1608
+ constructor() {
1609
+ this._proto =
1610
+ new protos_1.google.spanner.v1.BatchWriteRequest.MutationGroup();
1611
+ }
1612
+ insert(table, rows) {
1613
+ this._proto.mutations.push(buildMutation('insert', table, rows));
1614
+ }
1615
+ update(table, rows) {
1616
+ this._proto.mutations.push(buildMutation('update', table, rows));
1617
+ }
1618
+ upsert(table, rows) {
1619
+ this._proto.mutations.push(buildMutation('insertOrUpdate', table, rows));
1620
+ }
1621
+ replace(table, rows) {
1622
+ this._proto.mutations.push(buildMutation('replace', table, rows));
1623
+ }
1624
+ deleteRows(table, keys) {
1625
+ this._proto.mutations.push(buildDeleteMutation(table, keys));
1626
+ }
1627
+ proto() {
1628
+ return this._proto;
1629
+ }
1630
+ }
1631
+ exports.MutationGroup = MutationGroup;
1551
1632
  /**
1552
1633
  * This type of transaction is used to execute a single Partitioned DML
1553
1634
  * statement. Partitioned DML partitions the key space and runs the DML
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import type * as gax from 'google-gax';
3
2
  import type { Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback } from 'google-gax';
4
3
  import { Transform } from 'stream';
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import type * as gax from 'google-gax';
3
2
  import type { Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback } from 'google-gax';
4
3
  import { Transform } from 'stream';
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import type * as gax from 'google-gax';
3
2
  import type { Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback } from 'google-gax';
4
3
  import { Transform } from 'stream';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@google-cloud/spanner",
3
3
  "description": "Cloud Spanner Client Library for Node.js",
4
- "version": "7.8.0",
4
+ "version": "7.9.1",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Google Inc.",
7
7
  "engines": {
@@ -66,7 +66,7 @@
66
66
  "events-intercept": "^2.0.0",
67
67
  "extend": "^3.0.2",
68
68
  "google-auth-library": "^9.0.0",
69
- "google-gax": "4.3.3",
69
+ "google-gax": "4.3.7",
70
70
  "grpc-gcp": "^1.0.0",
71
71
  "is": "^3.2.1",
72
72
  "lodash.snakecase": "^4.1.1",
@@ -93,7 +93,7 @@
93
93
  "@types/request": "^2.48.3",
94
94
  "@types/sinon": "^17.0.0",
95
95
  "@types/through2": "^2.0.34",
96
- "@types/uuid": "^9.0.0",
96
+ "@types/uuid": "^10.0.0",
97
97
  "binary-search-bounds": "^2.0.4",
98
98
  "c8": "^8.0.1",
99
99
  "codecov": "^3.0.2",
@@ -112,12 +112,12 @@
112
112
  "ncp": "^2.0.0",
113
113
  "p-limit": "^3.0.1",
114
114
  "proxyquire": "^2.0.1",
115
- "sinon": "^17.0.0",
115
+ "sinon": "^18.0.0",
116
116
  "stats-lite": "^2.1.1",
117
117
  "time-span": "^4.0.0",
118
118
  "tmp": "^0.2.0",
119
119
  "typescript": "^5.1.6",
120
- "uuid": "^9.0.0",
120
+ "uuid": "^10.0.0",
121
121
  "yargs": "^17.0.0"
122
122
  }
123
123
  }