@google-cloud/spanner 7.17.0 → 7.18.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.
- package/CHANGELOG.md +14 -0
- package/package.json +1 -1
- package/build/protos/google/spanner/admin/database/v1/backup.proto +0 -757
- package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +0 -230
- package/build/protos/google/spanner/admin/database/v1/common.proto +0 -132
- package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +0 -1209
- package/build/protos/google/spanner/admin/instance/v1/common.proto +0 -63
- package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +0 -1983
- package/build/protos/google/spanner/executor/v1/cloud_executor.proto +0 -1520
- package/build/protos/google/spanner/v1/commit_response.proto +0 -59
- package/build/protos/google/spanner/v1/keys.proto +0 -163
- package/build/protos/google/spanner/v1/mutation.proto +0 -107
- package/build/protos/google/spanner/v1/query_plan.proto +0 -128
- package/build/protos/google/spanner/v1/result_set.proto +0 -237
- package/build/protos/google/spanner/v1/spanner.proto +0 -1389
- package/build/protos/google/spanner/v1/transaction.proto +0 -575
- package/build/protos/google/spanner/v1/type.proto +0 -210
- package/build/protos/protos.d.ts +0 -38999
- package/build/protos/protos.js +0 -99538
- package/build/protos/protos.json +0 -10182
- package/build/src/backup.d.ts +0 -349
- package/build/src/backup.js +0 -246
- package/build/src/batch-transaction.d.ts +0 -247
- package/build/src/batch-transaction.js +0 -384
- package/build/src/codec.d.ts +0 -362
- package/build/src/codec.js +0 -791
- package/build/src/common-grpc/service-object.d.ts +0 -80
- package/build/src/common-grpc/service-object.js +0 -101
- package/build/src/common-grpc/service.d.ts +0 -445
- package/build/src/common-grpc/service.js +0 -826
- package/build/src/common.d.ts +0 -66
- package/build/src/common.js +0 -54
- package/build/src/database.d.ts +0 -2104
- package/build/src/database.js +0 -1655
- package/build/src/extra_proto_list.json +0 -1
- package/build/src/helper.d.ts +0 -45
- package/build/src/helper.js +0 -71
- package/build/src/index.d.ts +0 -1195
- package/build/src/index.js +0 -1060
- package/build/src/instance-config.d.ts +0 -295
- package/build/src/instance-config.js +0 -216
- package/build/src/instance.d.ts +0 -833
- package/build/src/instance.js +0 -781
- package/build/src/instrument.d.ts +0 -87
- package/build/src/instrument.js +0 -217
- package/build/src/multiplexed-session.d.ts +0 -136
- package/build/src/multiplexed-session.js +0 -197
- package/build/src/partial-result-stream.d.ts +0 -253
- package/build/src/partial-result-stream.js +0 -400
- package/build/src/session-factory.d.ts +0 -101
- package/build/src/session-factory.js +0 -93
- package/build/src/session-pool.d.ts +0 -471
- package/build/src/session-pool.js +0 -754
- package/build/src/session.d.ts +0 -259
- package/build/src/session.js +0 -348
- package/build/src/spanner_grpc_config.json +0 -92
- package/build/src/table.d.ts +0 -831
- package/build/src/table.js +0 -277
- package/build/src/transaction-runner.d.ts +0 -185
- package/build/src/transaction-runner.js +0 -282
- package/build/src/transaction.d.ts +0 -1691
- package/build/src/transaction.js +0 -2004
- package/build/src/v1/database_admin_client.d.ts +0 -2301
- package/build/src/v1/database_admin_client.js +0 -2286
- package/build/src/v1/database_admin_client_config.json +0 -160
- package/build/src/v1/database_admin_proto_list.json +0 -6
- package/build/src/v1/gapic_metadata.json +0 -27
- package/build/src/v1/index.d.ts +0 -4
- package/build/src/v1/index.js +0 -29
- package/build/src/v1/instance_admin_client.d.ts +0 -1982
- package/build/src/v1/instance_admin_client.js +0 -1766
- package/build/src/v1/instance_admin_client_config.json +0 -129
- package/build/src/v1/instance_admin_proto_list.json +0 -4
- package/build/src/v1/spanner_client.d.ts +0 -1250
- package/build/src/v1/spanner_client.js +0 -1086
- package/build/src/v1/spanner_client_config.json +0 -119
- package/build/src/v1/spanner_executor_proxy_client.d.ts +0 -418
- package/build/src/v1/spanner_executor_proxy_client.js +0 -706
- package/build/src/v1/spanner_executor_proxy_client_config.json +0 -30
- package/build/src/v1/spanner_executor_proxy_proto_list.json +0 -14
- package/build/src/v1/spanner_proto_list.json +0 -10
package/build/src/transaction.js
DELETED
|
@@ -1,2004 +0,0 @@
|
|
|
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.PartitionedDml = exports.MutationGroup = exports.MutationSet = exports.Transaction = exports.Dml = exports.Snapshot = void 0;
|
|
19
|
-
const precise_date_1 = require("@google-cloud/precise-date");
|
|
20
|
-
const promisify_1 = require("@google-cloud/promisify");
|
|
21
|
-
const arrify = require("arrify");
|
|
22
|
-
const events_1 = require("events");
|
|
23
|
-
const google_gax_1 = require("google-gax");
|
|
24
|
-
const is = require("is");
|
|
25
|
-
const stream_1 = require("stream");
|
|
26
|
-
const codec_1 = require("./codec");
|
|
27
|
-
const partial_result_stream_1 = require("./partial-result-stream");
|
|
28
|
-
const instrument_1 = require("./instrument");
|
|
29
|
-
const protos_1 = require("../protos/protos");
|
|
30
|
-
const common_1 = require("./common");
|
|
31
|
-
const protos_2 = require("../protos/protos");
|
|
32
|
-
var ReadLockMode = protos_2.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
|
|
33
|
-
const instrument_2 = require("./instrument");
|
|
34
|
-
const RETRY_INFO_TYPE = 'type.googleapis.com/google.rpc.retryinfo';
|
|
35
|
-
const RETRY_INFO_BIN = 'google.rpc.retryinfo-bin';
|
|
36
|
-
/**
|
|
37
|
-
* @typedef {object} TimestampBounds
|
|
38
|
-
* @property {boolean} [strong=true] Read at a timestamp where all previously
|
|
39
|
-
* committed transactions are visible.
|
|
40
|
-
* @property {external:PreciseDate|google.protobuf.Timestamp} [minReadTimestamp]
|
|
41
|
-
* Executes all reads at a `timestamp >= minReadTimestamp`.
|
|
42
|
-
* @property {number|google.protobuf.Timestamp} [maxStaleness] Read data at a
|
|
43
|
-
* `timestamp >= NOW - maxStaleness` (milliseconds).
|
|
44
|
-
* @property {external:PreciseDate|google.protobuf.Timestamp} [readTimestamp]
|
|
45
|
-
* Executes all reads at the given timestamp.
|
|
46
|
-
* @property {number|google.protobuf.Timestamp} [exactStaleness] Executes all
|
|
47
|
-
* reads at a timestamp that is `exactStaleness` (milliseconds) old.
|
|
48
|
-
* @property {boolean} [returnReadTimestamp=true] When true,
|
|
49
|
-
* {@link Snapshot#readTimestamp} will be populated after
|
|
50
|
-
* {@link Snapshot#begin} is called.
|
|
51
|
-
*/
|
|
52
|
-
/**
|
|
53
|
-
* This transaction type provides guaranteed consistency across several reads,
|
|
54
|
-
* but does not allow writes. Snapshot read-only transactions can be configured
|
|
55
|
-
* to read at timestamps in the past.
|
|
56
|
-
*
|
|
57
|
-
* When finished with the Snapshot, call {@link Snapshot#end} to
|
|
58
|
-
* release the underlying {@link Session}. Failure to do so can result in a
|
|
59
|
-
* Session leak.
|
|
60
|
-
*
|
|
61
|
-
* **This object is created and returned from {@link Database#getSnapshot}.**
|
|
62
|
-
*
|
|
63
|
-
* @class
|
|
64
|
-
* @hideconstructor
|
|
65
|
-
*
|
|
66
|
-
* @see [Timestamp Bounds API Documentation](https://cloud.google.com/spanner/docs/timestamp-bounds)
|
|
67
|
-
*
|
|
68
|
-
* @example
|
|
69
|
-
* ```
|
|
70
|
-
* const {Spanner} = require('@google-cloud/spanner');
|
|
71
|
-
* const spanner = new Spanner();
|
|
72
|
-
*
|
|
73
|
-
* const instance = spanner.instance('my-instance');
|
|
74
|
-
* const database = instance.database('my-database');
|
|
75
|
-
*
|
|
76
|
-
* const timestampBounds = {
|
|
77
|
-
* strong: true
|
|
78
|
-
* };
|
|
79
|
-
*
|
|
80
|
-
* database.getSnapshot(timestampBounds, (err, transaction) => {
|
|
81
|
-
* if (err) {
|
|
82
|
-
* // Error handling omitted.
|
|
83
|
-
* }
|
|
84
|
-
*
|
|
85
|
-
* // It should be called when the snapshot finishes.
|
|
86
|
-
* transaction.end();
|
|
87
|
-
* });
|
|
88
|
-
* ```
|
|
89
|
-
*/
|
|
90
|
-
class Snapshot extends events_1.EventEmitter {
|
|
91
|
-
/**
|
|
92
|
-
* The transaction ID.
|
|
93
|
-
*
|
|
94
|
-
* @name Snapshot#id
|
|
95
|
-
* @type {?(string|Buffer)}
|
|
96
|
-
*/
|
|
97
|
-
/**
|
|
98
|
-
* Whether or not the transaction has ended. If true, make no further
|
|
99
|
-
* requests, and discard the transaction.
|
|
100
|
-
*
|
|
101
|
-
* @name Snapshot#ended
|
|
102
|
-
* @type {boolean}
|
|
103
|
-
*/
|
|
104
|
-
/**
|
|
105
|
-
* The raw transaction response object. It is populated after
|
|
106
|
-
* {@link Snapshot#begin} is called.
|
|
107
|
-
*
|
|
108
|
-
* @name Snapshot#metadata
|
|
109
|
-
* @type {?TransactionResponse}
|
|
110
|
-
*/
|
|
111
|
-
/**
|
|
112
|
-
* **Snapshot only**
|
|
113
|
-
* The timestamp at which all reads are performed.
|
|
114
|
-
*
|
|
115
|
-
* @name Snapshot#readTimestamp
|
|
116
|
-
* @type {?external:PreciseDate}
|
|
117
|
-
*/
|
|
118
|
-
/**
|
|
119
|
-
* **Snapshot only**
|
|
120
|
-
* The protobuf version of {@link Snapshot#readTimestamp}. This is useful if
|
|
121
|
-
* you require microsecond precision.
|
|
122
|
-
*
|
|
123
|
-
* @name Snapshot#readTimestampProto
|
|
124
|
-
* @type {?google.protobuf.Timestamp}
|
|
125
|
-
*/
|
|
126
|
-
/**
|
|
127
|
-
* @constructor
|
|
128
|
-
*
|
|
129
|
-
* @param {Session} session The parent Session object.
|
|
130
|
-
* @param {TimestampBounds} [options] Snapshot timestamp bounds.
|
|
131
|
-
* @param {QueryOptions} [queryOptions] Default query options to use when none
|
|
132
|
-
* are specified for a query.
|
|
133
|
-
*/
|
|
134
|
-
constructor(session, options, queryOptions) {
|
|
135
|
-
var _a;
|
|
136
|
-
super();
|
|
137
|
-
this._seqno = 1;
|
|
138
|
-
this._useInRunner = false;
|
|
139
|
-
this.ended = false;
|
|
140
|
-
this.session = session;
|
|
141
|
-
this.queryOptions = Object.assign({}, queryOptions);
|
|
142
|
-
this.request = session.request.bind(session);
|
|
143
|
-
this.requestStream = session.requestStream.bind(session);
|
|
144
|
-
const readOnly = Snapshot.encodeTimestampBounds(options || {});
|
|
145
|
-
this._options = { readOnly };
|
|
146
|
-
this._dbName = this.session.parent.formattedName_;
|
|
147
|
-
this._waitingRequests = [];
|
|
148
|
-
this._inlineBeginStarted = false;
|
|
149
|
-
this._observabilityOptions = session._observabilityOptions;
|
|
150
|
-
this.commonHeaders_ = (0, common_1.getCommonHeaders)(this._dbName, (_a = this._observabilityOptions) === null || _a === void 0 ? void 0 : _a.enableEndToEndTracing);
|
|
151
|
-
}
|
|
152
|
-
begin(gaxOptionsOrCallback, cb) {
|
|
153
|
-
const gaxOpts = typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {};
|
|
154
|
-
const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb;
|
|
155
|
-
const session = this.session.formattedName_;
|
|
156
|
-
const options = this._options;
|
|
157
|
-
const reqOpts = {
|
|
158
|
-
session,
|
|
159
|
-
options,
|
|
160
|
-
};
|
|
161
|
-
// Only hand crafted read-write transactions will be able to set a
|
|
162
|
-
// transaction tag for the BeginTransaction RPC. Also, this.requestOptions
|
|
163
|
-
// is only set in the constructor of Transaction, which is the constructor
|
|
164
|
-
// for read/write transactions.
|
|
165
|
-
if (this.requestOptions) {
|
|
166
|
-
reqOpts.requestOptions = this.requestOptions;
|
|
167
|
-
}
|
|
168
|
-
const headers = this.commonHeaders_;
|
|
169
|
-
if (this._getSpanner().routeToLeaderEnabled &&
|
|
170
|
-
(this._options.readWrite !== undefined ||
|
|
171
|
-
this._options.partitionedDml !== undefined)) {
|
|
172
|
-
(0, common_1.addLeaderAwareRoutingHeader)(headers);
|
|
173
|
-
}
|
|
174
|
-
const traceConfig = {
|
|
175
|
-
opts: this._observabilityOptions,
|
|
176
|
-
dbName: this._dbName,
|
|
177
|
-
};
|
|
178
|
-
return (0, instrument_2.startTrace)('Snapshot.begin', traceConfig, span => {
|
|
179
|
-
span.addEvent('Begin Transaction');
|
|
180
|
-
this.request({
|
|
181
|
-
client: 'SpannerClient',
|
|
182
|
-
method: 'beginTransaction',
|
|
183
|
-
reqOpts,
|
|
184
|
-
gaxOpts,
|
|
185
|
-
headers: headers,
|
|
186
|
-
}, (err, resp) => {
|
|
187
|
-
if (err) {
|
|
188
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
189
|
-
}
|
|
190
|
-
else {
|
|
191
|
-
this._update(resp);
|
|
192
|
-
}
|
|
193
|
-
span.end();
|
|
194
|
-
callback(err, resp);
|
|
195
|
-
});
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* A KeyRange represents a range of rows in a table or index.
|
|
200
|
-
*
|
|
201
|
-
* A range has a start key and an end key. These keys can be open or closed,
|
|
202
|
-
* indicating if the range includes rows with that key.
|
|
203
|
-
*
|
|
204
|
-
* Keys are represented by an array of strings where the nth value in the list
|
|
205
|
-
* corresponds to the nth component of the table or index primary key.
|
|
206
|
-
*
|
|
207
|
-
* @typedef {object} KeyRange
|
|
208
|
-
* @property {string[]} [startClosed] If the start is closed, then the range
|
|
209
|
-
* includes all rows whose first key columns exactly match.
|
|
210
|
-
* @property {string[]} [startOpen] If the start is open, then the range
|
|
211
|
-
* excludes rows whose first key columns exactly match.
|
|
212
|
-
* @property {string[]} [endClosed] If the end is closed, then the range
|
|
213
|
-
* includes all rows whose first key columns exactly match.
|
|
214
|
-
* @property {string[]} [endOpen] If the end is open, then the range excludes
|
|
215
|
-
* rows whose first key columns exactly match.
|
|
216
|
-
*/
|
|
217
|
-
/**
|
|
218
|
-
* Read request options. This includes all standard ReadRequest options as
|
|
219
|
-
* well as several convenience properties.
|
|
220
|
-
*
|
|
221
|
-
* @see [StreamingRead API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.StreamingRead)
|
|
222
|
-
* @see [ReadRequest API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ReadRequest)
|
|
223
|
-
*
|
|
224
|
-
* @typedef {object} ReadRequest
|
|
225
|
-
* @property {string} table The name of the table in the database to be read.
|
|
226
|
-
* @property {string[]} columns The columns of the table to be returned for each
|
|
227
|
-
* row matching this query.
|
|
228
|
-
* @property {string[]|string[][]} keys The primary or index keys of the rows in this table to be
|
|
229
|
-
* yielded. If using a composite key, provide an array within this array.
|
|
230
|
-
* See the example below.
|
|
231
|
-
* @property {KeyRange[]} [ranges] An alternative to the keys property; this can
|
|
232
|
-
* be used to define a range of keys to be yielded.
|
|
233
|
-
* @property {string} [index] The name of an index on the table if a
|
|
234
|
-
* different index than the primary key should be used to determine which rows to return.
|
|
235
|
-
* @property {boolean} [json=false] Receive the rows as serialized objects. This
|
|
236
|
-
* is the equivalent of calling `toJSON()` on each row.
|
|
237
|
-
* @property {JSONOptions} [jsonOptions] Configuration options for the serialized
|
|
238
|
-
* objects.
|
|
239
|
-
* @property {object} [keySet] Defines a collection of keys and/or key ranges to
|
|
240
|
-
* read.
|
|
241
|
-
* @property {number} [limit] The number of rows to yield.
|
|
242
|
-
* @property {Buffer} [partitionToken]
|
|
243
|
-
* If present, results will be restricted to the specified partition
|
|
244
|
-
* previously created using PartitionRead(). There must be an exact
|
|
245
|
-
* match for the values of fields common to this message and the
|
|
246
|
-
* PartitionReadRequest message used to create this partition_token.
|
|
247
|
-
* @property {google.spanner.v1.RequestOptions} [requestOptions]
|
|
248
|
-
* Common options for this request.
|
|
249
|
-
* @property {google.spanner.v1.IDirectedReadOptions} [directedReadOptions]
|
|
250
|
-
* Indicates which replicas or regions should be used for non-transactional reads or queries.
|
|
251
|
-
* @property {object} [gaxOptions]
|
|
252
|
-
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions}
|
|
253
|
-
* for more details.
|
|
254
|
-
*/
|
|
255
|
-
/**
|
|
256
|
-
* Create a readable object stream to receive rows from the database using key
|
|
257
|
-
* lookups and scans.
|
|
258
|
-
*
|
|
259
|
-
* Wrapper around {@link v1.SpannerClient#streamingRead}.
|
|
260
|
-
*
|
|
261
|
-
* @see {@link v1.SpannerClient#streamingRead}
|
|
262
|
-
* @see [StreamingRead API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.StreamingRead)
|
|
263
|
-
* @see [ReadRequest API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ReadRequest)
|
|
264
|
-
*
|
|
265
|
-
* @fires PartialResultStream#response
|
|
266
|
-
* @fires PartialResultStream#stats
|
|
267
|
-
*
|
|
268
|
-
* @param {string} table The table to read from.
|
|
269
|
-
* @param {ReadRequest} query Configuration object. See official
|
|
270
|
-
* [`ReadRequest`](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ReadRequest).
|
|
271
|
-
* API documentation.
|
|
272
|
-
* @returns {ReadableStream} A readable stream that emits rows.
|
|
273
|
-
*
|
|
274
|
-
* @example
|
|
275
|
-
* ```
|
|
276
|
-
* transaction.createReadStream('Singers', {
|
|
277
|
-
* keys: ['1'],
|
|
278
|
-
* columns: ['SingerId', 'name']
|
|
279
|
-
* })
|
|
280
|
-
* .on('error', function(err) {})
|
|
281
|
-
* .on('data', function(row) {
|
|
282
|
-
* // row = [
|
|
283
|
-
* // {
|
|
284
|
-
* // name: 'SingerId',
|
|
285
|
-
* // value: '1'
|
|
286
|
-
* // },
|
|
287
|
-
* // {
|
|
288
|
-
* // name: 'Name',
|
|
289
|
-
* // value: 'Eddie Wilson'
|
|
290
|
-
* // }
|
|
291
|
-
* // ]
|
|
292
|
-
* })
|
|
293
|
-
* .on('end', function() {
|
|
294
|
-
* // All results retrieved.
|
|
295
|
-
* });
|
|
296
|
-
*
|
|
297
|
-
* ```
|
|
298
|
-
* @example Provide an array for `query.keys` to read with a
|
|
299
|
-
* composite key.
|
|
300
|
-
* ```
|
|
301
|
-
* const query = {
|
|
302
|
-
* keys: [
|
|
303
|
-
* [
|
|
304
|
-
* 'Id1',
|
|
305
|
-
* 'Name1'
|
|
306
|
-
* ],
|
|
307
|
-
* [
|
|
308
|
-
* 'Id2',
|
|
309
|
-
* 'Name2'
|
|
310
|
-
* ]
|
|
311
|
-
* ],
|
|
312
|
-
* // ...
|
|
313
|
-
* };
|
|
314
|
-
* ```
|
|
315
|
-
*
|
|
316
|
-
* @example Rows are returned as an array of object arrays. Each
|
|
317
|
-
* object has a `name` and `value` property. To get a serialized object, call
|
|
318
|
-
* `toJSON()`.
|
|
319
|
-
* ```
|
|
320
|
-
* transaction.createReadStream('Singers', {
|
|
321
|
-
* keys: ['1'],
|
|
322
|
-
* columns: ['SingerId', 'name']
|
|
323
|
-
* })
|
|
324
|
-
* .on('error', function(err) {})
|
|
325
|
-
* .on('data', function(row) {
|
|
326
|
-
* // row.toJSON() = {
|
|
327
|
-
* // SingerId: '1',
|
|
328
|
-
* // Name: 'Eddie Wilson'
|
|
329
|
-
* // }
|
|
330
|
-
* })
|
|
331
|
-
* .on('end', function() {
|
|
332
|
-
* // All results retrieved.
|
|
333
|
-
* });
|
|
334
|
-
* ```
|
|
335
|
-
*
|
|
336
|
-
* @example Alternatively, set `query.json` to `true`, and this step
|
|
337
|
-
* will perform automatically.
|
|
338
|
-
* ```
|
|
339
|
-
* transaction.createReadStream('Singers', {
|
|
340
|
-
* keys: ['1'],
|
|
341
|
-
* columns: ['SingerId', 'name'],
|
|
342
|
-
* json: true,
|
|
343
|
-
* })
|
|
344
|
-
* .on('error', function(err) {})
|
|
345
|
-
* .on('data', function(row) {
|
|
346
|
-
* // row = {
|
|
347
|
-
* // SingerId: '1',
|
|
348
|
-
* // Name: 'Eddie Wilson'
|
|
349
|
-
* // }
|
|
350
|
-
* })
|
|
351
|
-
* .on('end', function() {
|
|
352
|
-
* // All results retrieved.
|
|
353
|
-
* });
|
|
354
|
-
* ```
|
|
355
|
-
*
|
|
356
|
-
* @example If you anticipate many results, you can end a stream
|
|
357
|
-
* early to prevent unnecessary processing and API requests.
|
|
358
|
-
* ```
|
|
359
|
-
* transaction.createReadStream('Singers', {
|
|
360
|
-
* keys: ['1'],
|
|
361
|
-
* columns: ['SingerId', 'name']
|
|
362
|
-
* })
|
|
363
|
-
* .on('data', function(row) {
|
|
364
|
-
* this.end();
|
|
365
|
-
* });
|
|
366
|
-
* ```
|
|
367
|
-
*/
|
|
368
|
-
createReadStream(table, request = {}) {
|
|
369
|
-
var _a, _b;
|
|
370
|
-
const { gaxOptions, json, jsonOptions, maxResumeRetries, requestOptions, columnsMetadata, } = request;
|
|
371
|
-
const keySet = Snapshot.encodeKeySet(request);
|
|
372
|
-
const transaction = {};
|
|
373
|
-
if (this.id) {
|
|
374
|
-
transaction.id = this.id;
|
|
375
|
-
}
|
|
376
|
-
else if (this._options.readWrite) {
|
|
377
|
-
transaction.begin = this._options;
|
|
378
|
-
}
|
|
379
|
-
else {
|
|
380
|
-
transaction.singleUse = this._options;
|
|
381
|
-
}
|
|
382
|
-
const directedReadOptions = this._getDirectedReadOptions(request.directedReadOptions);
|
|
383
|
-
request = Object.assign({}, request);
|
|
384
|
-
delete request.gaxOptions;
|
|
385
|
-
delete request.json;
|
|
386
|
-
delete request.jsonOptions;
|
|
387
|
-
delete request.maxResumeRetries;
|
|
388
|
-
delete request.keys;
|
|
389
|
-
delete request.ranges;
|
|
390
|
-
delete request.requestOptions;
|
|
391
|
-
delete request.directedReadOptions;
|
|
392
|
-
delete request.columnsMetadata;
|
|
393
|
-
const reqOpts = Object.assign(request, {
|
|
394
|
-
session: this.session.formattedName_,
|
|
395
|
-
requestOptions: this.configureTagOptions(typeof transaction.singleUse !== 'undefined', (_b = (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag) !== null && _b !== void 0 ? _b : undefined, requestOptions),
|
|
396
|
-
directedReadOptions: directedReadOptions,
|
|
397
|
-
transaction,
|
|
398
|
-
table,
|
|
399
|
-
keySet,
|
|
400
|
-
});
|
|
401
|
-
const headers = this.commonHeaders_;
|
|
402
|
-
if (this._getSpanner().routeToLeaderEnabled &&
|
|
403
|
-
(this._options.readWrite !== undefined ||
|
|
404
|
-
this._options.partitionedDml !== undefined)) {
|
|
405
|
-
(0, common_1.addLeaderAwareRoutingHeader)(headers);
|
|
406
|
-
}
|
|
407
|
-
const traceConfig = {
|
|
408
|
-
tableName: table,
|
|
409
|
-
opts: this._observabilityOptions,
|
|
410
|
-
dbName: this._dbName,
|
|
411
|
-
};
|
|
412
|
-
return (0, instrument_2.startTrace)('Snapshot.createReadStream', traceConfig, span => {
|
|
413
|
-
var _a;
|
|
414
|
-
let attempt = 0;
|
|
415
|
-
const makeRequest = (resumeToken) => {
|
|
416
|
-
if (this.id && transaction.begin) {
|
|
417
|
-
delete transaction.begin;
|
|
418
|
-
transaction.id = this.id;
|
|
419
|
-
}
|
|
420
|
-
attempt++;
|
|
421
|
-
if (!resumeToken) {
|
|
422
|
-
if (attempt === 1) {
|
|
423
|
-
span.addEvent('Starting stream');
|
|
424
|
-
}
|
|
425
|
-
else {
|
|
426
|
-
span.addEvent('Re-attempting start stream', { attempt: attempt });
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
else {
|
|
430
|
-
span.addEvent('Resuming stream', {
|
|
431
|
-
resume_token: resumeToken.toString(),
|
|
432
|
-
attempt: attempt,
|
|
433
|
-
});
|
|
434
|
-
}
|
|
435
|
-
return this.requestStream({
|
|
436
|
-
client: 'SpannerClient',
|
|
437
|
-
method: 'streamingRead',
|
|
438
|
-
reqOpts: Object.assign({}, reqOpts, { resumeToken }),
|
|
439
|
-
gaxOpts: gaxOptions,
|
|
440
|
-
headers: headers,
|
|
441
|
-
});
|
|
442
|
-
};
|
|
443
|
-
const resultStream = (_a = (0, partial_result_stream_1.partialResultStream)(this._wrapWithIdWaiter(makeRequest), {
|
|
444
|
-
json,
|
|
445
|
-
jsonOptions,
|
|
446
|
-
maxResumeRetries,
|
|
447
|
-
columnsMetadata,
|
|
448
|
-
gaxOptions,
|
|
449
|
-
})) === null || _a === void 0 ? void 0 : _a.on('response', response => {
|
|
450
|
-
if (response.metadata && response.metadata.transaction && !this.id) {
|
|
451
|
-
this._update(response.metadata.transaction);
|
|
452
|
-
}
|
|
453
|
-
}).on('error', err => {
|
|
454
|
-
var _a;
|
|
455
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
456
|
-
const wasAborted = isErrorAborted(err);
|
|
457
|
-
if (!this.id && this._useInRunner && !wasAborted) {
|
|
458
|
-
// TODO: resolve https://github.com/googleapis/nodejs-spanner/issues/2170
|
|
459
|
-
this.begin();
|
|
460
|
-
}
|
|
461
|
-
else {
|
|
462
|
-
if (wasAborted) {
|
|
463
|
-
span.addEvent('Stream broken. Not safe to retry', {
|
|
464
|
-
'transaction.id': (_a = this.id) === null || _a === void 0 ? void 0 : _a.toString(),
|
|
465
|
-
});
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
span.end();
|
|
469
|
-
}).on('end', err => {
|
|
470
|
-
if (err) {
|
|
471
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
472
|
-
}
|
|
473
|
-
span.end();
|
|
474
|
-
});
|
|
475
|
-
if (resultStream instanceof stream_1.Stream) {
|
|
476
|
-
(0, stream_1.finished)(resultStream, err => {
|
|
477
|
-
if (err) {
|
|
478
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
479
|
-
}
|
|
480
|
-
span.end();
|
|
481
|
-
});
|
|
482
|
-
}
|
|
483
|
-
return resultStream;
|
|
484
|
-
});
|
|
485
|
-
}
|
|
486
|
-
/**
|
|
487
|
-
* Let the client know you're done with a particular transaction. This should
|
|
488
|
-
* mainly be called for {@link Snapshot} objects, however in certain cases
|
|
489
|
-
* you may want to call them for {@link Transaction} objects as well.
|
|
490
|
-
*
|
|
491
|
-
* @example Calling `end` on a read only snapshot
|
|
492
|
-
* ```
|
|
493
|
-
* database.getSnapshot((err, transaction) => {
|
|
494
|
-
* if (err) {
|
|
495
|
-
* // Error handling omitted.
|
|
496
|
-
* }
|
|
497
|
-
*
|
|
498
|
-
* transaction.run('SELECT * FROM Singers', (err, rows) => {
|
|
499
|
-
* if (err) {
|
|
500
|
-
* // Error handling omitted.
|
|
501
|
-
* }
|
|
502
|
-
*
|
|
503
|
-
* // End the snapshot.
|
|
504
|
-
* transaction.end();
|
|
505
|
-
* });
|
|
506
|
-
* });
|
|
507
|
-
* ```
|
|
508
|
-
*
|
|
509
|
-
* @example Calling `end` on a read/write transaction
|
|
510
|
-
* ```
|
|
511
|
-
* database.runTransaction((err, transaction) => {
|
|
512
|
-
* if (err) {
|
|
513
|
-
* // Error handling omitted.
|
|
514
|
-
* }
|
|
515
|
-
*
|
|
516
|
-
* const query = 'UPDATE Account SET Balance = 1000 WHERE Key = 1';
|
|
517
|
-
*
|
|
518
|
-
* transaction.runUpdate(query, err => {
|
|
519
|
-
* if (err) {
|
|
520
|
-
* // In the event of an error, there would be nothing to rollback,
|
|
521
|
-
* so
|
|
522
|
-
* // instead of continuing, discard the
|
|
523
|
-
* transaction. transaction.end(); return;
|
|
524
|
-
* }
|
|
525
|
-
*
|
|
526
|
-
* transaction.commit(err => {});
|
|
527
|
-
* });
|
|
528
|
-
* });
|
|
529
|
-
* ```
|
|
530
|
-
*/
|
|
531
|
-
end() {
|
|
532
|
-
if (this.ended) {
|
|
533
|
-
return;
|
|
534
|
-
}
|
|
535
|
-
this.ended = true;
|
|
536
|
-
process.nextTick(() => this.emit('end'));
|
|
537
|
-
}
|
|
538
|
-
read(table, requestOrCallback, cb) {
|
|
539
|
-
const rows = [];
|
|
540
|
-
let request;
|
|
541
|
-
let callback;
|
|
542
|
-
if (typeof requestOrCallback === 'function') {
|
|
543
|
-
request = {};
|
|
544
|
-
callback = requestOrCallback;
|
|
545
|
-
}
|
|
546
|
-
else {
|
|
547
|
-
request = requestOrCallback;
|
|
548
|
-
callback = cb;
|
|
549
|
-
}
|
|
550
|
-
const traceConfig = {
|
|
551
|
-
tableName: table,
|
|
552
|
-
opts: this._observabilityOptions,
|
|
553
|
-
dbName: this._dbName,
|
|
554
|
-
};
|
|
555
|
-
return (0, instrument_2.startTrace)('Snapshot.read', traceConfig, span => {
|
|
556
|
-
this.createReadStream(table, request)
|
|
557
|
-
.on('error', err => {
|
|
558
|
-
const e = err;
|
|
559
|
-
(0, instrument_2.setSpanError)(span, e);
|
|
560
|
-
span.end();
|
|
561
|
-
callback(e, null);
|
|
562
|
-
})
|
|
563
|
-
.on('data', row => rows.push(row))
|
|
564
|
-
.on('end', () => {
|
|
565
|
-
span.end();
|
|
566
|
-
callback(null, rows);
|
|
567
|
-
});
|
|
568
|
-
});
|
|
569
|
-
}
|
|
570
|
-
run(query, callback) {
|
|
571
|
-
const rows = [];
|
|
572
|
-
let stats;
|
|
573
|
-
let metadata;
|
|
574
|
-
const traceConfig = {
|
|
575
|
-
sql: query,
|
|
576
|
-
opts: this._observabilityOptions,
|
|
577
|
-
dbName: this._dbName,
|
|
578
|
-
};
|
|
579
|
-
(0, instrument_2.startTrace)('Snapshot.run', traceConfig, span => {
|
|
580
|
-
return this.runStream(query)
|
|
581
|
-
.on('error', (err, rows, stats, metadata) => {
|
|
582
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
583
|
-
span.end();
|
|
584
|
-
callback(err, rows, stats, metadata);
|
|
585
|
-
})
|
|
586
|
-
.on('response', response => {
|
|
587
|
-
if (response.metadata) {
|
|
588
|
-
metadata = response.metadata;
|
|
589
|
-
if (metadata.transaction && !this.id) {
|
|
590
|
-
this._update(metadata.transaction);
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
})
|
|
594
|
-
.on('data', row => rows.push(row))
|
|
595
|
-
.on('stats', _stats => (stats = _stats))
|
|
596
|
-
.on('end', () => {
|
|
597
|
-
span.end();
|
|
598
|
-
callback(null, rows, stats, metadata);
|
|
599
|
-
});
|
|
600
|
-
});
|
|
601
|
-
}
|
|
602
|
-
/**
|
|
603
|
-
* ExecuteSql request options. This includes all standard ExecuteSqlRequest
|
|
604
|
-
* options as well as several convenience properties.
|
|
605
|
-
*
|
|
606
|
-
* @see [Query Syntax](https://cloud.google.com/spanner/docs/query-syntax)
|
|
607
|
-
* @see [ExecuteSql API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ExecuteSql)
|
|
608
|
-
*
|
|
609
|
-
* @typedef {object} ExecuteSqlRequest
|
|
610
|
-
* @property {string} resumeToken The token used to resume getting results.
|
|
611
|
-
* @property {google.spanner.v1.ExecuteSqlRequest.QueryMode} queryMode Query plan and
|
|
612
|
-
* execution statistics for the SQL statement that
|
|
613
|
-
* produced this result set.
|
|
614
|
-
* @property {string} partitionToken The partition token.
|
|
615
|
-
* @property {number} seqno The Sequence number. This option is used internally and will be overridden.
|
|
616
|
-
* @property {string} sql The SQL string.
|
|
617
|
-
* @property {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} [queryOptions]
|
|
618
|
-
* Default query options to use with the database. These options will be
|
|
619
|
-
* overridden by any query options set in environment variables or that
|
|
620
|
-
* are specified on a per-query basis.
|
|
621
|
-
* @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include
|
|
622
|
-
* with the commit request.
|
|
623
|
-
* @property {Object.<string, *>} [params] A map of parameter names to values.
|
|
624
|
-
* @property {Object.<string, (string|ParamType)>} [types] A map of parameter
|
|
625
|
-
* names to types. If omitted the client will attempt to guess for all
|
|
626
|
-
* non-null values.
|
|
627
|
-
* @property {boolean} [json=false] Receive the rows as serialized objects. This
|
|
628
|
-
* is the equivalent of calling `toJSON()` on each row.
|
|
629
|
-
* @property {JSONOptions} [jsonOptions] Configuration options for the
|
|
630
|
-
* serialized objects.
|
|
631
|
-
* @property {object} [gaxOptions] Request configuration options,
|
|
632
|
-
* See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions}
|
|
633
|
-
* for more details.
|
|
634
|
-
* @property {number} [maxResumeRetries] The maximum number of times that the
|
|
635
|
-
* stream will retry to push data downstream, when the downstream indicates
|
|
636
|
-
* that it is not ready for any more data. Increase this value if you
|
|
637
|
-
* experience 'Stream is still not ready to receive data' errors as a
|
|
638
|
-
* result of a slow writer in your receiving stream.
|
|
639
|
-
* @property {object} [directedReadOptions]
|
|
640
|
-
* Indicates which replicas or regions should be used for non-transactional reads or queries.
|
|
641
|
-
*/
|
|
642
|
-
/**
|
|
643
|
-
* Create a readable object stream to receive resulting rows from a SQL
|
|
644
|
-
* statement.
|
|
645
|
-
*
|
|
646
|
-
* Wrapper around {@link v1.SpannerClient#executeStreamingSql}.
|
|
647
|
-
*
|
|
648
|
-
* @see {@link v1.SpannerClient#executeStreamingSql}
|
|
649
|
-
* @see [ExecuteStreamingSql API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ExecuteStreamingSql)
|
|
650
|
-
* @see [ExecuteSqlRequest API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest)
|
|
651
|
-
*
|
|
652
|
-
* @fires PartialResultStream#response
|
|
653
|
-
* @fires PartialResultStream#stats
|
|
654
|
-
*
|
|
655
|
-
* @param {string|ExecuteSqlRequest} query A SQL query or
|
|
656
|
-
* {@link ExecuteSqlRequest} object.
|
|
657
|
-
* @returns {ReadableStream}
|
|
658
|
-
*
|
|
659
|
-
* @example
|
|
660
|
-
* ```
|
|
661
|
-
* const query = 'SELECT * FROM Singers';
|
|
662
|
-
*
|
|
663
|
-
* transaction.runStream(query)
|
|
664
|
-
* .on('error', function(err) {})
|
|
665
|
-
* .on('data', function(row) {
|
|
666
|
-
* // row = {
|
|
667
|
-
* // SingerId: '1',
|
|
668
|
-
* // Name: 'Eddie Wilson'
|
|
669
|
-
* // }
|
|
670
|
-
* })
|
|
671
|
-
* .on('end', function() {
|
|
672
|
-
* // All results retrieved.
|
|
673
|
-
* });
|
|
674
|
-
*
|
|
675
|
-
* ```
|
|
676
|
-
* @example The SQL query string can contain parameter placeholders.
|
|
677
|
-
* A parameter placeholder consists of '@' followed by the parameter name.
|
|
678
|
-
* ```
|
|
679
|
-
* const query = {
|
|
680
|
-
* sql: 'SELECT * FROM Singers WHERE name = @name',
|
|
681
|
-
* params: {
|
|
682
|
-
* name: 'Eddie Wilson'
|
|
683
|
-
* }
|
|
684
|
-
* };
|
|
685
|
-
*
|
|
686
|
-
* transaction.runStream(query)
|
|
687
|
-
* .on('error', function(err) {})
|
|
688
|
-
* .on('data', function(row) {})
|
|
689
|
-
* .on('end', function() {});
|
|
690
|
-
* ```
|
|
691
|
-
*
|
|
692
|
-
* @example If you anticipate many results, you can end a stream
|
|
693
|
-
* early to prevent unnecessary processing and API requests.
|
|
694
|
-
* ```
|
|
695
|
-
* transaction.runStream(query)
|
|
696
|
-
* .on('data', function(row) {
|
|
697
|
-
* this.end();
|
|
698
|
-
* });
|
|
699
|
-
* ```
|
|
700
|
-
*/
|
|
701
|
-
runStream(query) {
|
|
702
|
-
if (typeof query === 'string') {
|
|
703
|
-
query = { sql: query };
|
|
704
|
-
}
|
|
705
|
-
query = Object.assign({}, query);
|
|
706
|
-
query.queryOptions = Object.assign(Object.assign({}, this.queryOptions), query.queryOptions);
|
|
707
|
-
const { gaxOptions, json, jsonOptions, maxResumeRetries, requestOptions, columnsMetadata, } = query;
|
|
708
|
-
let reqOpts;
|
|
709
|
-
const directedReadOptions = this._getDirectedReadOptions(query.directedReadOptions);
|
|
710
|
-
const sanitizeRequest = () => {
|
|
711
|
-
var _a, _b;
|
|
712
|
-
query = query;
|
|
713
|
-
const { params, paramTypes } = Snapshot.encodeParams(query);
|
|
714
|
-
const transaction = {};
|
|
715
|
-
if (this.id) {
|
|
716
|
-
transaction.id = this.id;
|
|
717
|
-
}
|
|
718
|
-
else if (this._options.readWrite) {
|
|
719
|
-
transaction.begin = this._options;
|
|
720
|
-
}
|
|
721
|
-
else {
|
|
722
|
-
transaction.singleUse = this._options;
|
|
723
|
-
}
|
|
724
|
-
delete query.gaxOptions;
|
|
725
|
-
delete query.json;
|
|
726
|
-
delete query.jsonOptions;
|
|
727
|
-
delete query.maxResumeRetries;
|
|
728
|
-
delete query.requestOptions;
|
|
729
|
-
delete query.types;
|
|
730
|
-
delete query.directedReadOptions;
|
|
731
|
-
delete query.columnsMetadata;
|
|
732
|
-
reqOpts = Object.assign(query, {
|
|
733
|
-
session: this.session.formattedName_,
|
|
734
|
-
seqno: this._seqno++,
|
|
735
|
-
requestOptions: this.configureTagOptions(typeof transaction.singleUse !== 'undefined', (_b = (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag) !== null && _b !== void 0 ? _b : undefined, requestOptions),
|
|
736
|
-
directedReadOptions: directedReadOptions,
|
|
737
|
-
transaction,
|
|
738
|
-
params,
|
|
739
|
-
paramTypes,
|
|
740
|
-
});
|
|
741
|
-
};
|
|
742
|
-
const headers = this.commonHeaders_;
|
|
743
|
-
if (this._getSpanner().routeToLeaderEnabled &&
|
|
744
|
-
(this._options.readWrite !== undefined ||
|
|
745
|
-
this._options.partitionedDml !== undefined)) {
|
|
746
|
-
(0, common_1.addLeaderAwareRoutingHeader)(headers);
|
|
747
|
-
}
|
|
748
|
-
const traceConfig = {
|
|
749
|
-
opts: this._observabilityOptions,
|
|
750
|
-
dbName: this._dbName,
|
|
751
|
-
...query,
|
|
752
|
-
};
|
|
753
|
-
return (0, instrument_2.startTrace)('Snapshot.runStream', traceConfig, span => {
|
|
754
|
-
let attempt = 0;
|
|
755
|
-
const makeRequest = (resumeToken) => {
|
|
756
|
-
attempt++;
|
|
757
|
-
if (!resumeToken) {
|
|
758
|
-
if (attempt === 1) {
|
|
759
|
-
span.addEvent('Starting stream');
|
|
760
|
-
}
|
|
761
|
-
else {
|
|
762
|
-
span.addEvent('Re-attempting start stream', { attempt: attempt });
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
else {
|
|
766
|
-
span.addEvent('Resuming stream', {
|
|
767
|
-
resume_token: resumeToken.toString(),
|
|
768
|
-
attempt: attempt,
|
|
769
|
-
});
|
|
770
|
-
}
|
|
771
|
-
if (!reqOpts || (this.id && !reqOpts.transaction.id)) {
|
|
772
|
-
try {
|
|
773
|
-
sanitizeRequest();
|
|
774
|
-
}
|
|
775
|
-
catch (e) {
|
|
776
|
-
const errorStream = new stream_1.PassThrough();
|
|
777
|
-
(0, instrument_2.setSpanErrorAndException)(span, e);
|
|
778
|
-
span.end();
|
|
779
|
-
setImmediate(() => errorStream.destroy(e));
|
|
780
|
-
return errorStream;
|
|
781
|
-
}
|
|
782
|
-
}
|
|
783
|
-
return this.requestStream({
|
|
784
|
-
client: 'SpannerClient',
|
|
785
|
-
method: 'executeStreamingSql',
|
|
786
|
-
reqOpts: Object.assign({}, reqOpts, { resumeToken }),
|
|
787
|
-
gaxOpts: gaxOptions,
|
|
788
|
-
headers: headers,
|
|
789
|
-
});
|
|
790
|
-
};
|
|
791
|
-
const resultStream = (0, partial_result_stream_1.partialResultStream)(this._wrapWithIdWaiter(makeRequest), {
|
|
792
|
-
json,
|
|
793
|
-
jsonOptions,
|
|
794
|
-
maxResumeRetries,
|
|
795
|
-
columnsMetadata,
|
|
796
|
-
gaxOptions,
|
|
797
|
-
})
|
|
798
|
-
.on('response', response => {
|
|
799
|
-
if (response.metadata && response.metadata.transaction && !this.id) {
|
|
800
|
-
this._update(response.metadata.transaction);
|
|
801
|
-
}
|
|
802
|
-
})
|
|
803
|
-
.on('error', err => {
|
|
804
|
-
var _a;
|
|
805
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
806
|
-
const wasAborted = isErrorAborted(err);
|
|
807
|
-
if (!this.id && this._useInRunner && !wasAborted) {
|
|
808
|
-
span.addEvent('Stream broken. Safe to retry');
|
|
809
|
-
// TODO: resolve https://github.com/googleapis/nodejs-spanner/issues/2170
|
|
810
|
-
this.begin();
|
|
811
|
-
}
|
|
812
|
-
else {
|
|
813
|
-
if (wasAborted) {
|
|
814
|
-
span.addEvent('Stream broken. Not safe to retry', {
|
|
815
|
-
'transaction.id': (_a = this.id) === null || _a === void 0 ? void 0 : _a.toString(),
|
|
816
|
-
});
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
span.end();
|
|
820
|
-
})
|
|
821
|
-
.on('end', err => {
|
|
822
|
-
if (err) {
|
|
823
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
824
|
-
}
|
|
825
|
-
span.end();
|
|
826
|
-
});
|
|
827
|
-
if (resultStream instanceof stream_1.Stream) {
|
|
828
|
-
(0, stream_1.finished)(resultStream, err => {
|
|
829
|
-
if (err) {
|
|
830
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
831
|
-
}
|
|
832
|
-
span.end();
|
|
833
|
-
});
|
|
834
|
-
}
|
|
835
|
-
return resultStream;
|
|
836
|
-
});
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
*
|
|
840
|
-
* @private
|
|
841
|
-
*/
|
|
842
|
-
configureTagOptions(singleUse, transactionTag, requestOptions = {}) {
|
|
843
|
-
if (!singleUse && transactionTag) {
|
|
844
|
-
requestOptions.transactionTag = transactionTag;
|
|
845
|
-
}
|
|
846
|
-
return requestOptions;
|
|
847
|
-
}
|
|
848
|
-
/**
|
|
849
|
-
* Transforms convenience options `keys` and `ranges` into a KeySet object.
|
|
850
|
-
*
|
|
851
|
-
* @private
|
|
852
|
-
* @static
|
|
853
|
-
*
|
|
854
|
-
* @param {ReadRequest} request The read request.
|
|
855
|
-
* @returns {object}
|
|
856
|
-
*/
|
|
857
|
-
static encodeKeySet(request) {
|
|
858
|
-
const keySet = request.keySet || {};
|
|
859
|
-
if (request.keys) {
|
|
860
|
-
keySet.keys = arrify(request.keys).map(codec_1.codec.convertToListValue);
|
|
861
|
-
}
|
|
862
|
-
if (request.ranges) {
|
|
863
|
-
keySet.ranges = arrify(request.ranges).map(range => {
|
|
864
|
-
const encodedRange = {};
|
|
865
|
-
Object.keys(range).forEach(bound => {
|
|
866
|
-
encodedRange[bound] = codec_1.codec.convertToListValue(range[bound]);
|
|
867
|
-
});
|
|
868
|
-
return encodedRange;
|
|
869
|
-
});
|
|
870
|
-
}
|
|
871
|
-
if (is.empty(keySet)) {
|
|
872
|
-
keySet.all = true;
|
|
873
|
-
}
|
|
874
|
-
return keySet;
|
|
875
|
-
}
|
|
876
|
-
/**
|
|
877
|
-
* Formats timestamp options into proto format.
|
|
878
|
-
*
|
|
879
|
-
* @private
|
|
880
|
-
* @static
|
|
881
|
-
*
|
|
882
|
-
* @param {TimestampBounds} options The user supplied options.
|
|
883
|
-
* @returns {object}
|
|
884
|
-
*/
|
|
885
|
-
static encodeTimestampBounds(options) {
|
|
886
|
-
const readOnly = {};
|
|
887
|
-
const { returnReadTimestamp = true } = options;
|
|
888
|
-
if (options.minReadTimestamp instanceof precise_date_1.PreciseDate) {
|
|
889
|
-
readOnly.minReadTimestamp = options.minReadTimestamp.toStruct();
|
|
890
|
-
}
|
|
891
|
-
if (options.readTimestamp instanceof precise_date_1.PreciseDate) {
|
|
892
|
-
readOnly.readTimestamp = options.readTimestamp.toStruct();
|
|
893
|
-
}
|
|
894
|
-
if (typeof options.maxStaleness === 'number') {
|
|
895
|
-
readOnly.maxStaleness = codec_1.codec.convertMsToProtoTimestamp(options.maxStaleness);
|
|
896
|
-
}
|
|
897
|
-
if (typeof options.exactStaleness === 'number') {
|
|
898
|
-
readOnly.exactStaleness = codec_1.codec.convertMsToProtoTimestamp(options.exactStaleness);
|
|
899
|
-
}
|
|
900
|
-
// If we didn't detect a convenience format, we'll just assume that
|
|
901
|
-
// they passed in a protobuf timestamp.
|
|
902
|
-
if (is.empty(readOnly)) {
|
|
903
|
-
Object.assign(readOnly, options);
|
|
904
|
-
}
|
|
905
|
-
readOnly.returnReadTimestamp = returnReadTimestamp;
|
|
906
|
-
return readOnly;
|
|
907
|
-
}
|
|
908
|
-
/**
|
|
909
|
-
* Encodes convenience options `param` and `types` into the proto formatted.
|
|
910
|
-
*
|
|
911
|
-
* @private
|
|
912
|
-
* @static
|
|
913
|
-
*
|
|
914
|
-
* @param {ExecuteSqlRequest} request The SQL request.
|
|
915
|
-
* @returns {object}
|
|
916
|
-
*/
|
|
917
|
-
static encodeParams(request) {
|
|
918
|
-
const typeMap = request.types || {};
|
|
919
|
-
const params = {};
|
|
920
|
-
const paramTypes = {};
|
|
921
|
-
if (request.params) {
|
|
922
|
-
const fields = {};
|
|
923
|
-
Object.keys(request.params).forEach(param => {
|
|
924
|
-
const value = request.params[param];
|
|
925
|
-
if (!typeMap[param]) {
|
|
926
|
-
typeMap[param] = codec_1.codec.getType(value);
|
|
927
|
-
}
|
|
928
|
-
fields[param] = codec_1.codec.encode(value);
|
|
929
|
-
});
|
|
930
|
-
params.fields = fields;
|
|
931
|
-
}
|
|
932
|
-
if (!is.empty(typeMap)) {
|
|
933
|
-
Object.keys(typeMap).forEach(param => {
|
|
934
|
-
const type = typeMap[param];
|
|
935
|
-
paramTypes[param] = codec_1.codec.createTypeObject(type);
|
|
936
|
-
});
|
|
937
|
-
}
|
|
938
|
-
return { params, paramTypes };
|
|
939
|
-
}
|
|
940
|
-
/**
|
|
941
|
-
* Get directed read options
|
|
942
|
-
* @private
|
|
943
|
-
* @param {google.spanner.v1.IDirectedReadOptions} directedReadOptions Request directedReadOptions object.
|
|
944
|
-
*/
|
|
945
|
-
_getDirectedReadOptions(directedReadOptions) {
|
|
946
|
-
if (!directedReadOptions &&
|
|
947
|
-
this._getSpanner().directedReadOptions &&
|
|
948
|
-
this._options.readOnly) {
|
|
949
|
-
return this._getSpanner().directedReadOptions;
|
|
950
|
-
}
|
|
951
|
-
return directedReadOptions;
|
|
952
|
-
}
|
|
953
|
-
/**
|
|
954
|
-
* Update transaction properties from the response.
|
|
955
|
-
*
|
|
956
|
-
* @private
|
|
957
|
-
*
|
|
958
|
-
* @param {spannerClient.spanner.v1.ITransaction} resp Response object.
|
|
959
|
-
*/
|
|
960
|
-
_update(resp) {
|
|
961
|
-
const { id, readTimestamp } = resp;
|
|
962
|
-
this.id = id;
|
|
963
|
-
this.metadata = resp;
|
|
964
|
-
const span = (0, instrument_1.getActiveOrNoopSpan)();
|
|
965
|
-
span.addEvent('Transaction Creation Done', { id: this.id.toString() });
|
|
966
|
-
if (readTimestamp) {
|
|
967
|
-
this.readTimestampProto = readTimestamp;
|
|
968
|
-
this.readTimestamp = new precise_date_1.PreciseDate(readTimestamp);
|
|
969
|
-
}
|
|
970
|
-
this._releaseWaitingRequests();
|
|
971
|
-
}
|
|
972
|
-
/**
|
|
973
|
-
* Wrap `makeRequest` function with the lock to make sure the inline begin
|
|
974
|
-
* transaction can happen only once.
|
|
975
|
-
*
|
|
976
|
-
* @param makeRequest
|
|
977
|
-
* @private
|
|
978
|
-
*/
|
|
979
|
-
_wrapWithIdWaiter(makeRequest) {
|
|
980
|
-
if (this.id || !this._options.readWrite) {
|
|
981
|
-
return makeRequest;
|
|
982
|
-
}
|
|
983
|
-
if (!this._inlineBeginStarted) {
|
|
984
|
-
this._inlineBeginStarted = true;
|
|
985
|
-
return makeRequest;
|
|
986
|
-
}
|
|
987
|
-
// Queue subsequent requests.
|
|
988
|
-
return (resumeToken) => {
|
|
989
|
-
const streamProxy = new stream_1.Readable({
|
|
990
|
-
read() { },
|
|
991
|
-
});
|
|
992
|
-
this._waitingRequests.push(() => {
|
|
993
|
-
makeRequest(resumeToken)
|
|
994
|
-
.on('data', chunk => streamProxy.emit('data', chunk))
|
|
995
|
-
.on('error', err => streamProxy.emit('error', err))
|
|
996
|
-
.on('end', () => streamProxy.emit('end'));
|
|
997
|
-
});
|
|
998
|
-
return streamProxy;
|
|
999
|
-
};
|
|
1000
|
-
}
|
|
1001
|
-
_releaseWaitingRequests() {
|
|
1002
|
-
while (this._waitingRequests.length > 0) {
|
|
1003
|
-
const request = this._waitingRequests.shift();
|
|
1004
|
-
request === null || request === void 0 ? void 0 : request();
|
|
1005
|
-
}
|
|
1006
|
-
}
|
|
1007
|
-
/**
|
|
1008
|
-
* Gets the Spanner object
|
|
1009
|
-
*
|
|
1010
|
-
* @private
|
|
1011
|
-
*
|
|
1012
|
-
* @returns {Spanner}
|
|
1013
|
-
*/
|
|
1014
|
-
_getSpanner() {
|
|
1015
|
-
return this.session.parent.parent.parent;
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
exports.Snapshot = Snapshot;
|
|
1019
|
-
/*! Developer Documentation
|
|
1020
|
-
*
|
|
1021
|
-
* All async methods (except for streams) return a Promise in the event
|
|
1022
|
-
* that a callback is omitted.
|
|
1023
|
-
*/
|
|
1024
|
-
(0, promisify_1.promisifyAll)(Snapshot, {
|
|
1025
|
-
exclude: ['configureTagOptions', 'end'],
|
|
1026
|
-
});
|
|
1027
|
-
/**
|
|
1028
|
-
* Never use DML class directly. Instead, it should be extended upon
|
|
1029
|
-
* if a class requires DML capabilities.
|
|
1030
|
-
*
|
|
1031
|
-
* @private
|
|
1032
|
-
* @class
|
|
1033
|
-
*/
|
|
1034
|
-
class Dml extends Snapshot {
|
|
1035
|
-
runUpdate(query, callback) {
|
|
1036
|
-
if (typeof query === 'string') {
|
|
1037
|
-
query = { sql: query };
|
|
1038
|
-
}
|
|
1039
|
-
const traceConfig = {
|
|
1040
|
-
opts: this._observabilityOptions,
|
|
1041
|
-
dbName: this._dbName,
|
|
1042
|
-
...query,
|
|
1043
|
-
};
|
|
1044
|
-
return (0, instrument_2.startTrace)('Dml.runUpdate', traceConfig, span => {
|
|
1045
|
-
this.run(query, (err, rows, stats) => {
|
|
1046
|
-
let rowCount = 0;
|
|
1047
|
-
if (stats && stats.rowCount) {
|
|
1048
|
-
rowCount = Math.floor(stats[stats.rowCount]);
|
|
1049
|
-
}
|
|
1050
|
-
if (err) {
|
|
1051
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
1052
|
-
}
|
|
1053
|
-
span.end();
|
|
1054
|
-
callback(err, rowCount);
|
|
1055
|
-
});
|
|
1056
|
-
});
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
exports.Dml = Dml;
|
|
1060
|
-
/*! Developer Documentation
|
|
1061
|
-
*
|
|
1062
|
-
* All async methods (except for streams) return a Promise in the event
|
|
1063
|
-
* that a callback is omitted.
|
|
1064
|
-
*/
|
|
1065
|
-
(0, promisify_1.promisifyAll)(Dml);
|
|
1066
|
-
/**
|
|
1067
|
-
* This type of transaction is the only way to write data into Cloud Spanner.
|
|
1068
|
-
* These transactions rely on pessimistic locking and, if necessary, two-phase
|
|
1069
|
-
* commit. Locking read-write transactions may abort, requiring the application
|
|
1070
|
-
* to retry.
|
|
1071
|
-
*
|
|
1072
|
-
* Calling either {@link Transaction#commit} or {@link Transaction#rollback}
|
|
1073
|
-
* signals that the transaction is finished and no further requests will be
|
|
1074
|
-
* made. If for some reason you decide not to call one of the aformentioned
|
|
1075
|
-
* methods, call {@link Transaction#end} to release the underlying
|
|
1076
|
-
* {@link Session}.
|
|
1077
|
-
*
|
|
1078
|
-
* Running a transaction via {@link Database#runTransaction} or
|
|
1079
|
-
* {@link Database#runTransactionAsync} automatically re-runs the
|
|
1080
|
-
* transaction on `ABORTED` errors.
|
|
1081
|
-
*
|
|
1082
|
-
* {@link Database#getTransaction} returns a plain {@link Transaction}
|
|
1083
|
-
* object, requiring the user to retry manually.
|
|
1084
|
-
*
|
|
1085
|
-
* @class
|
|
1086
|
-
* @extends Snapshot
|
|
1087
|
-
*
|
|
1088
|
-
* @param {Session} session The parent Session object.
|
|
1089
|
-
*
|
|
1090
|
-
* @example
|
|
1091
|
-
* ```
|
|
1092
|
-
* const {Spanner} = require('@google-cloud/spanner');
|
|
1093
|
-
* const spanner = new Spanner();
|
|
1094
|
-
*
|
|
1095
|
-
* const instance = spanner.instance('my-instance');
|
|
1096
|
-
* const database = instance.database('my-database');
|
|
1097
|
-
*
|
|
1098
|
-
* database.runTransaction(function(err, transaction) {
|
|
1099
|
-
* // The `transaction` object is ready for use.
|
|
1100
|
-
* });
|
|
1101
|
-
*
|
|
1102
|
-
* ```
|
|
1103
|
-
* @example To manually control retrying the transaction, use the
|
|
1104
|
-
* `getTransaction` method.
|
|
1105
|
-
* ```
|
|
1106
|
-
* database.getTransaction(function(err, transaction) {
|
|
1107
|
-
* // The `transaction` object is ready for use.
|
|
1108
|
-
* });
|
|
1109
|
-
* ```
|
|
1110
|
-
*/
|
|
1111
|
-
class Transaction extends Dml {
|
|
1112
|
-
/**
|
|
1113
|
-
* Timestamp at which the transaction was committed. Will be populated once
|
|
1114
|
-
* {@link Transaction#commit} is called.
|
|
1115
|
-
*
|
|
1116
|
-
* @name Transaction#commitTimestamp
|
|
1117
|
-
* @type {?external:PreciseDate}
|
|
1118
|
-
*/
|
|
1119
|
-
/**
|
|
1120
|
-
* The protobuf version of {@link Transaction#commitTimestamp}. This is useful
|
|
1121
|
-
* if you require microsecond precision.
|
|
1122
|
-
*
|
|
1123
|
-
* @name Transaction#commitTimestampProto
|
|
1124
|
-
* @type {?google.protobuf.Timestamp}
|
|
1125
|
-
*/
|
|
1126
|
-
/**
|
|
1127
|
-
* Execute a DML statement and get the affected row count.
|
|
1128
|
-
*
|
|
1129
|
-
* @name Transaction#runUpdate
|
|
1130
|
-
*
|
|
1131
|
-
* @see {@link Transaction#run}
|
|
1132
|
-
*
|
|
1133
|
-
* @param {string|object} query A DML statement or
|
|
1134
|
-
* [`ExecuteSqlRequest`](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest)
|
|
1135
|
-
* object.
|
|
1136
|
-
* @param {object} [query.params] A map of parameter name to values.
|
|
1137
|
-
* @param {object} [query.types] A map of parameter types.
|
|
1138
|
-
* @param {RunUpdateCallback} [callback] Callback function.
|
|
1139
|
-
* @returns {Promise<RunUpdateResponse>}
|
|
1140
|
-
*
|
|
1141
|
-
* @example
|
|
1142
|
-
* ```
|
|
1143
|
-
* const query = 'UPDATE Account SET Balance = 1000 WHERE Key = 1';
|
|
1144
|
-
*
|
|
1145
|
-
* transaction.runUpdate(query, (err, rowCount) => {
|
|
1146
|
-
* if (err) {
|
|
1147
|
-
* // Error handling omitted.
|
|
1148
|
-
* }
|
|
1149
|
-
* });
|
|
1150
|
-
* ```
|
|
1151
|
-
*/
|
|
1152
|
-
constructor(session, options = {}, queryOptions, requestOptions) {
|
|
1153
|
-
super(session, undefined, queryOptions);
|
|
1154
|
-
this._queuedMutations = [];
|
|
1155
|
-
this._options = { readWrite: options };
|
|
1156
|
-
this.requestOptions = requestOptions;
|
|
1157
|
-
}
|
|
1158
|
-
batchUpdate(queries, optionsOrCallback, cb) {
|
|
1159
|
-
var _a, _b;
|
|
1160
|
-
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
|
|
1161
|
-
const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
|
|
1162
|
-
const gaxOpts = 'gaxOptions' in options
|
|
1163
|
-
? options.gaxOptions
|
|
1164
|
-
: options;
|
|
1165
|
-
if (!Array.isArray(queries) || !queries.length) {
|
|
1166
|
-
const rowCounts = [];
|
|
1167
|
-
const error = new Error('batchUpdate requires at least 1 DML statement.');
|
|
1168
|
-
const batchError = Object.assign(error, {
|
|
1169
|
-
code: 3, // invalid argument
|
|
1170
|
-
rowCounts,
|
|
1171
|
-
});
|
|
1172
|
-
callback(batchError, rowCounts);
|
|
1173
|
-
return;
|
|
1174
|
-
}
|
|
1175
|
-
const statements = queries.map(query => {
|
|
1176
|
-
if (typeof query === 'string') {
|
|
1177
|
-
return { sql: query };
|
|
1178
|
-
}
|
|
1179
|
-
const { sql } = query;
|
|
1180
|
-
const { params, paramTypes } = Snapshot.encodeParams(query);
|
|
1181
|
-
return { sql, params, paramTypes };
|
|
1182
|
-
});
|
|
1183
|
-
const transaction = {};
|
|
1184
|
-
if (this.id) {
|
|
1185
|
-
transaction.id = this.id;
|
|
1186
|
-
}
|
|
1187
|
-
else {
|
|
1188
|
-
transaction.begin = this._options;
|
|
1189
|
-
}
|
|
1190
|
-
const reqOpts = {
|
|
1191
|
-
session: this.session.formattedName_,
|
|
1192
|
-
requestOptions: this.configureTagOptions(false, (_b = (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag) !== null && _b !== void 0 ? _b : undefined, options.requestOptions),
|
|
1193
|
-
transaction,
|
|
1194
|
-
seqno: this._seqno++,
|
|
1195
|
-
statements,
|
|
1196
|
-
};
|
|
1197
|
-
const headers = this.commonHeaders_;
|
|
1198
|
-
if (this._getSpanner().routeToLeaderEnabled) {
|
|
1199
|
-
(0, common_1.addLeaderAwareRoutingHeader)(headers);
|
|
1200
|
-
}
|
|
1201
|
-
const traceConfig = {
|
|
1202
|
-
opts: this._observabilityOptions,
|
|
1203
|
-
dbName: this._dbName,
|
|
1204
|
-
};
|
|
1205
|
-
return (0, instrument_2.startTrace)('Transaction.batchUpdate', traceConfig, span => {
|
|
1206
|
-
this.request({
|
|
1207
|
-
client: 'SpannerClient',
|
|
1208
|
-
method: 'executeBatchDml',
|
|
1209
|
-
reqOpts,
|
|
1210
|
-
gaxOpts,
|
|
1211
|
-
headers: headers,
|
|
1212
|
-
}, (err, resp) => {
|
|
1213
|
-
var _a;
|
|
1214
|
-
let batchUpdateError;
|
|
1215
|
-
if (err) {
|
|
1216
|
-
const rowCounts = [];
|
|
1217
|
-
batchUpdateError = Object.assign(err, { rowCounts });
|
|
1218
|
-
(0, instrument_2.setSpanError)(span, batchUpdateError);
|
|
1219
|
-
span.end();
|
|
1220
|
-
callback(batchUpdateError, rowCounts, resp);
|
|
1221
|
-
return;
|
|
1222
|
-
}
|
|
1223
|
-
const { resultSets, status } = resp;
|
|
1224
|
-
for (const resultSet of resultSets) {
|
|
1225
|
-
if (!this.id && ((_a = resultSet.metadata) === null || _a === void 0 ? void 0 : _a.transaction)) {
|
|
1226
|
-
this._update(resultSet.metadata.transaction);
|
|
1227
|
-
}
|
|
1228
|
-
}
|
|
1229
|
-
const rowCounts = resultSets.map(({ stats }) => {
|
|
1230
|
-
return ((stats &&
|
|
1231
|
-
Number(stats[stats.rowCount])) ||
|
|
1232
|
-
0);
|
|
1233
|
-
});
|
|
1234
|
-
if (status && status.code !== 0) {
|
|
1235
|
-
const error = new Error(status.message);
|
|
1236
|
-
batchUpdateError = Object.assign(error, {
|
|
1237
|
-
code: status.code,
|
|
1238
|
-
metadata: Transaction.extractKnownMetadata(status.details),
|
|
1239
|
-
rowCounts,
|
|
1240
|
-
});
|
|
1241
|
-
(0, instrument_2.setSpanError)(span, batchUpdateError);
|
|
1242
|
-
}
|
|
1243
|
-
span.end();
|
|
1244
|
-
callback(batchUpdateError, rowCounts, resp);
|
|
1245
|
-
});
|
|
1246
|
-
});
|
|
1247
|
-
}
|
|
1248
|
-
static extractKnownMetadata(details) {
|
|
1249
|
-
if (details && typeof details[Symbol.iterator] === 'function') {
|
|
1250
|
-
const metadata = new google_gax_1.grpc.Metadata();
|
|
1251
|
-
for (const detail of details) {
|
|
1252
|
-
if (detail.type_url === RETRY_INFO_TYPE && detail.value) {
|
|
1253
|
-
metadata.add(RETRY_INFO_BIN, detail.value);
|
|
1254
|
-
}
|
|
1255
|
-
}
|
|
1256
|
-
return metadata;
|
|
1257
|
-
}
|
|
1258
|
-
return undefined;
|
|
1259
|
-
}
|
|
1260
|
-
/**
|
|
1261
|
-
* This method updates the _queuedMutations property of the transaction.
|
|
1262
|
-
*
|
|
1263
|
-
* @public
|
|
1264
|
-
*
|
|
1265
|
-
* @param {spannerClient.spanner.v1.Mutation[]} [mutation]
|
|
1266
|
-
*/
|
|
1267
|
-
setQueuedMutations(mutation) {
|
|
1268
|
-
this._queuedMutations = mutation;
|
|
1269
|
-
}
|
|
1270
|
-
commit(optionsOrCallback, cb) {
|
|
1271
|
-
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
|
|
1272
|
-
const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
|
|
1273
|
-
const gaxOpts = 'gaxOptions' in options ? options.gaxOptions : options;
|
|
1274
|
-
const mutations = this._queuedMutations;
|
|
1275
|
-
const session = this.session.formattedName_;
|
|
1276
|
-
const requestOptions = options.requestOptions;
|
|
1277
|
-
const reqOpts = { mutations, session, requestOptions };
|
|
1278
|
-
const traceConfig = {
|
|
1279
|
-
opts: this._observabilityOptions,
|
|
1280
|
-
dbName: this._dbName,
|
|
1281
|
-
};
|
|
1282
|
-
return (0, instrument_2.startTrace)('Transaction.commit', traceConfig, span => {
|
|
1283
|
-
if (this.id) {
|
|
1284
|
-
reqOpts.transactionId = this.id;
|
|
1285
|
-
}
|
|
1286
|
-
else if (!this._useInRunner) {
|
|
1287
|
-
reqOpts.singleUseTransaction = this._options;
|
|
1288
|
-
}
|
|
1289
|
-
else {
|
|
1290
|
-
this.begin().then(() => {
|
|
1291
|
-
this.commit(options, (err, resp) => {
|
|
1292
|
-
if (err) {
|
|
1293
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
1294
|
-
}
|
|
1295
|
-
span.end();
|
|
1296
|
-
callback(err, resp);
|
|
1297
|
-
});
|
|
1298
|
-
}, err => {
|
|
1299
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
1300
|
-
span.end();
|
|
1301
|
-
callback(err, null);
|
|
1302
|
-
});
|
|
1303
|
-
return;
|
|
1304
|
-
}
|
|
1305
|
-
if ('returnCommitStats' in options &&
|
|
1306
|
-
options.returnCommitStats) {
|
|
1307
|
-
reqOpts.returnCommitStats = options.returnCommitStats;
|
|
1308
|
-
}
|
|
1309
|
-
if ('maxCommitDelay' in options &&
|
|
1310
|
-
options.maxCommitDelay) {
|
|
1311
|
-
reqOpts.maxCommitDelay = options.maxCommitDelay;
|
|
1312
|
-
}
|
|
1313
|
-
reqOpts.requestOptions = Object.assign(requestOptions || {}, this.requestOptions);
|
|
1314
|
-
const headers = this.commonHeaders_;
|
|
1315
|
-
if (this._getSpanner().routeToLeaderEnabled) {
|
|
1316
|
-
(0, common_1.addLeaderAwareRoutingHeader)(headers);
|
|
1317
|
-
}
|
|
1318
|
-
span.addEvent('Starting Commit');
|
|
1319
|
-
this.request({
|
|
1320
|
-
client: 'SpannerClient',
|
|
1321
|
-
method: 'commit',
|
|
1322
|
-
reqOpts,
|
|
1323
|
-
gaxOpts: gaxOpts,
|
|
1324
|
-
headers: headers,
|
|
1325
|
-
}, (err, resp) => {
|
|
1326
|
-
this.end();
|
|
1327
|
-
if (err) {
|
|
1328
|
-
span.addEvent('Commit failed');
|
|
1329
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
1330
|
-
}
|
|
1331
|
-
else {
|
|
1332
|
-
span.addEvent('Commit Done');
|
|
1333
|
-
}
|
|
1334
|
-
if (resp && resp.commitTimestamp) {
|
|
1335
|
-
this.commitTimestampProto = resp.commitTimestamp;
|
|
1336
|
-
this.commitTimestamp = new precise_date_1.PreciseDate(resp.commitTimestamp);
|
|
1337
|
-
}
|
|
1338
|
-
err = Transaction.decorateCommitError(err, mutations);
|
|
1339
|
-
span.end();
|
|
1340
|
-
callback(err, resp);
|
|
1341
|
-
});
|
|
1342
|
-
});
|
|
1343
|
-
}
|
|
1344
|
-
/**
|
|
1345
|
-
* Decorates an error returned by a commit with additional information for
|
|
1346
|
-
* specific known errors.
|
|
1347
|
-
* @param err the error to check and decorate with additional information if possible
|
|
1348
|
-
* @param mutations the mutations included in the commit request
|
|
1349
|
-
* @private
|
|
1350
|
-
*/
|
|
1351
|
-
static decorateCommitError(err, mutations) {
|
|
1352
|
-
if (!err) {
|
|
1353
|
-
return err;
|
|
1354
|
-
}
|
|
1355
|
-
if (err.code === google_gax_1.Status.FAILED_PRECONDITION) {
|
|
1356
|
-
const mismatchErr = Transaction.decoratePossibleJsonMismatchError(err, mutations);
|
|
1357
|
-
if (mismatchErr) {
|
|
1358
|
-
return mismatchErr;
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
return err;
|
|
1362
|
-
}
|
|
1363
|
-
/**
|
|
1364
|
-
* Decorates an error returned by a commit with additional information if the
|
|
1365
|
-
* error was returned because the application tried to insert an array of
|
|
1366
|
-
* objects into a JSON column. An array of objects will by default be encoded
|
|
1367
|
-
* as ARRAY<JSON>, but can also be interpreted as JSON. An application must
|
|
1368
|
-
* specify a top-level array of objects that should be inserted into a JSON
|
|
1369
|
-
* column as a string instead of as an array of objects.
|
|
1370
|
-
* @param err the error returned by the commit RPC
|
|
1371
|
-
* @param mutations the mutations included in the commit request
|
|
1372
|
-
* @private
|
|
1373
|
-
*/
|
|
1374
|
-
static decoratePossibleJsonMismatchError(err, mutations) {
|
|
1375
|
-
var _a, _b;
|
|
1376
|
-
const errorMessage = /Invalid value for column (?<column>.+) in table (?<table>.+): Expected JSON./;
|
|
1377
|
-
const found = err.message && err.message.match(errorMessage);
|
|
1378
|
-
if (found && found.groups) {
|
|
1379
|
-
const table = found.groups.table;
|
|
1380
|
-
const column = found.groups.column;
|
|
1381
|
-
for (const mutation of mutations) {
|
|
1382
|
-
const write = mutation.insert ||
|
|
1383
|
-
mutation.update ||
|
|
1384
|
-
mutation.insertOrUpdate ||
|
|
1385
|
-
mutation.replace;
|
|
1386
|
-
if (write && write.table === table) {
|
|
1387
|
-
const index = (_a = write.columns) === null || _a === void 0 ? void 0 : _a.indexOf(column);
|
|
1388
|
-
if (index && index > -1 && write.values) {
|
|
1389
|
-
for (const row of write.values) {
|
|
1390
|
-
if (((_b = row.values) === null || _b === void 0 ? void 0 : _b.length) &&
|
|
1391
|
-
row.values.length > index &&
|
|
1392
|
-
row.values[index].listValue) {
|
|
1393
|
-
// If the value is an array, the client library also encoded it as
|
|
1394
|
-
// an array. Inserting an array into a JSON column is not possible,
|
|
1395
|
-
// although if it is encoded as a string containing a top-level JSON
|
|
1396
|
-
// array it will work.
|
|
1397
|
-
const additionalMessage = 'The value is an array. Convert the value to a JSON string containing an array instead in order to insert it into a JSON column. Example: `[{"key": "value 1"}, {"key": "value 2"}]` instead of [{key: "value 1"}, {key: "value 2"}]';
|
|
1398
|
-
return {
|
|
1399
|
-
code: err.code,
|
|
1400
|
-
details: `${err.details} ${additionalMessage}`,
|
|
1401
|
-
message: `${err.message} ${additionalMessage}`,
|
|
1402
|
-
metadata: err.metadata,
|
|
1403
|
-
name: err.name,
|
|
1404
|
-
stack: err.stack,
|
|
1405
|
-
};
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
}
|
|
1411
|
-
}
|
|
1412
|
-
return null;
|
|
1413
|
-
}
|
|
1414
|
-
/**
|
|
1415
|
-
* Delete rows from a table.
|
|
1416
|
-
*
|
|
1417
|
-
* @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit)
|
|
1418
|
-
*
|
|
1419
|
-
* @param {string} table The name of the table.
|
|
1420
|
-
* @param {array} keys The keys for the rows to delete. If using a
|
|
1421
|
-
* composite key, provide an array within this array. See the example
|
|
1422
|
-
* below.
|
|
1423
|
-
*
|
|
1424
|
-
* @example
|
|
1425
|
-
* ```
|
|
1426
|
-
* const keys = ['Id1', 'Id2', 'Id3'];
|
|
1427
|
-
*
|
|
1428
|
-
* database.runTransaction(function(err, transaction) {
|
|
1429
|
-
* if (err) {
|
|
1430
|
-
* // Error handling omitted.
|
|
1431
|
-
* }
|
|
1432
|
-
*
|
|
1433
|
-
* // Queue this mutation until later calling `commit`.
|
|
1434
|
-
* // Note that a callback is not passed to `deleteRows`.
|
|
1435
|
-
* transaction.deleteRows('Singers', keys);
|
|
1436
|
-
*
|
|
1437
|
-
* // Commit the transaction.
|
|
1438
|
-
* transaction.commit(function(err) {
|
|
1439
|
-
* if (!err) {
|
|
1440
|
-
* // The rows were deleted successfully.
|
|
1441
|
-
* }
|
|
1442
|
-
* });
|
|
1443
|
-
* });
|
|
1444
|
-
*
|
|
1445
|
-
* ```
|
|
1446
|
-
* @example Provide an array for `keys` to delete rows with a
|
|
1447
|
-
* composite key.
|
|
1448
|
-
* ```
|
|
1449
|
-
* const keys = [
|
|
1450
|
-
* [
|
|
1451
|
-
* 'Id1',
|
|
1452
|
-
* 'Name1'
|
|
1453
|
-
* ],
|
|
1454
|
-
* [
|
|
1455
|
-
* 'Id2',
|
|
1456
|
-
* 'Name2'
|
|
1457
|
-
* ]
|
|
1458
|
-
* ];
|
|
1459
|
-
* ```
|
|
1460
|
-
*/
|
|
1461
|
-
deleteRows(table, keys) {
|
|
1462
|
-
this._queuedMutations.push(buildDeleteMutation(table, keys));
|
|
1463
|
-
}
|
|
1464
|
-
/**
|
|
1465
|
-
* Insert rows of data into this table.
|
|
1466
|
-
*
|
|
1467
|
-
* @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit)
|
|
1468
|
-
*
|
|
1469
|
-
* @param {string} table The name of the table.
|
|
1470
|
-
* @param {object|object[]} rows A map of names to values of data to insert
|
|
1471
|
-
* into this table.
|
|
1472
|
-
*
|
|
1473
|
-
* @example
|
|
1474
|
-
* ```
|
|
1475
|
-
* const row = {
|
|
1476
|
-
* SingerId: 'Id3',
|
|
1477
|
-
* Name: 'Eddie Wilson'
|
|
1478
|
-
* };
|
|
1479
|
-
*
|
|
1480
|
-
* database.runTransaction(function(err, transaction) {
|
|
1481
|
-
* if (err) {
|
|
1482
|
-
* // Error handling omitted.
|
|
1483
|
-
* }
|
|
1484
|
-
*
|
|
1485
|
-
* // Queue this mutation until later calling `commit`.
|
|
1486
|
-
* // Note that a callback is not passed to `insert`.
|
|
1487
|
-
* transaction.insert('Singers', row);
|
|
1488
|
-
*
|
|
1489
|
-
* // Commit the transaction.
|
|
1490
|
-
* transaction.commit(function(err) {
|
|
1491
|
-
* if (!err) {
|
|
1492
|
-
* // The row was inserted successfully.
|
|
1493
|
-
* }
|
|
1494
|
-
* });
|
|
1495
|
-
* });
|
|
1496
|
-
*
|
|
1497
|
-
* ```
|
|
1498
|
-
* @example Multiple rows can be inserted at once.
|
|
1499
|
-
* ```
|
|
1500
|
-
* const row2 = {
|
|
1501
|
-
* SingerId: 'Id3b',
|
|
1502
|
-
* Name: 'Joe West'
|
|
1503
|
-
* };
|
|
1504
|
-
*
|
|
1505
|
-
* database.runTransaction(function(err, transaction) {
|
|
1506
|
-
* if (err) {
|
|
1507
|
-
* // Error handling omitted.
|
|
1508
|
-
* }
|
|
1509
|
-
*
|
|
1510
|
-
* // Queue multiple mutations until later calling `commit`.
|
|
1511
|
-
* // Note that a callback is not passed to `insert`.
|
|
1512
|
-
* transaction.insert('Singers', [
|
|
1513
|
-
* row,
|
|
1514
|
-
* row2
|
|
1515
|
-
* ]);
|
|
1516
|
-
*
|
|
1517
|
-
* // Commit the transaction.
|
|
1518
|
-
* transaction.commit(function(err) {
|
|
1519
|
-
* if (!err) {
|
|
1520
|
-
* // The rows were inserted successfully.
|
|
1521
|
-
* }
|
|
1522
|
-
* });
|
|
1523
|
-
* });
|
|
1524
|
-
* ```
|
|
1525
|
-
*/
|
|
1526
|
-
insert(table, rows) {
|
|
1527
|
-
this._mutate('insert', table, rows);
|
|
1528
|
-
}
|
|
1529
|
-
/**
|
|
1530
|
-
* Replace rows of data within a table.
|
|
1531
|
-
*
|
|
1532
|
-
* @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit)
|
|
1533
|
-
*
|
|
1534
|
-
* @param {string} table The table to read from.
|
|
1535
|
-
* @param {object|object[]} rows A map of names to values of data to insert
|
|
1536
|
-
* into this table.
|
|
1537
|
-
*
|
|
1538
|
-
* @example
|
|
1539
|
-
* ```
|
|
1540
|
-
* const row = {
|
|
1541
|
-
* SingerId: 'Id3',
|
|
1542
|
-
* Name: 'Joe West'
|
|
1543
|
-
* };
|
|
1544
|
-
*
|
|
1545
|
-
* database.runTransaction(function(err, transaction) {
|
|
1546
|
-
* if (err) {
|
|
1547
|
-
* // Error handling omitted.
|
|
1548
|
-
* }
|
|
1549
|
-
*
|
|
1550
|
-
* // Queue this mutation until later calling `commit`.
|
|
1551
|
-
* // Note that a callback is not passed to `replace`.
|
|
1552
|
-
* transaction.replace('Singers', row);
|
|
1553
|
-
*
|
|
1554
|
-
* // Commit the transaction.
|
|
1555
|
-
* transaction.commit(function(err) {
|
|
1556
|
-
* if (!err) {
|
|
1557
|
-
* // The row was replaced successfully.
|
|
1558
|
-
* }
|
|
1559
|
-
* });
|
|
1560
|
-
* });
|
|
1561
|
-
* ```
|
|
1562
|
-
*/
|
|
1563
|
-
replace(table, rows) {
|
|
1564
|
-
this._mutate('replace', table, rows);
|
|
1565
|
-
}
|
|
1566
|
-
rollback(gaxOptionsOrCallback, cb) {
|
|
1567
|
-
const gaxOpts = typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {};
|
|
1568
|
-
const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb;
|
|
1569
|
-
const traceConfig = {
|
|
1570
|
-
opts: this._observabilityOptions,
|
|
1571
|
-
dbName: this._dbName,
|
|
1572
|
-
};
|
|
1573
|
-
return (0, instrument_2.startTrace)('Transaction.rollback', traceConfig, span => {
|
|
1574
|
-
if (!this.id) {
|
|
1575
|
-
const err = new Error('Transaction ID is unknown, nothing to rollback.');
|
|
1576
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
1577
|
-
span.end();
|
|
1578
|
-
callback(err);
|
|
1579
|
-
return;
|
|
1580
|
-
}
|
|
1581
|
-
const session = this.session.formattedName_;
|
|
1582
|
-
const transactionId = this.id;
|
|
1583
|
-
const reqOpts = {
|
|
1584
|
-
session,
|
|
1585
|
-
transactionId,
|
|
1586
|
-
};
|
|
1587
|
-
const headers = this.commonHeaders_;
|
|
1588
|
-
if (this._getSpanner().routeToLeaderEnabled) {
|
|
1589
|
-
(0, common_1.addLeaderAwareRoutingHeader)(headers);
|
|
1590
|
-
}
|
|
1591
|
-
this.request({
|
|
1592
|
-
client: 'SpannerClient',
|
|
1593
|
-
method: 'rollback',
|
|
1594
|
-
reqOpts,
|
|
1595
|
-
gaxOpts,
|
|
1596
|
-
headers: headers,
|
|
1597
|
-
}, (err) => {
|
|
1598
|
-
if (err) {
|
|
1599
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
1600
|
-
}
|
|
1601
|
-
span.end();
|
|
1602
|
-
this.end();
|
|
1603
|
-
callback(err);
|
|
1604
|
-
});
|
|
1605
|
-
});
|
|
1606
|
-
}
|
|
1607
|
-
/**
|
|
1608
|
-
* Update rows of data within a table.
|
|
1609
|
-
*
|
|
1610
|
-
* @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit)
|
|
1611
|
-
*
|
|
1612
|
-
* @param {string} table The table to read from.
|
|
1613
|
-
* @param {object|object[]} rows A map of names to values of data to insert
|
|
1614
|
-
* into this table.
|
|
1615
|
-
*
|
|
1616
|
-
* @example
|
|
1617
|
-
* ```
|
|
1618
|
-
* const row = {
|
|
1619
|
-
* SingerId: 'Id3',
|
|
1620
|
-
* Name: 'Joe West'
|
|
1621
|
-
* };
|
|
1622
|
-
*
|
|
1623
|
-
* database.runTransaction(function(err, transaction) {
|
|
1624
|
-
* if (err) {
|
|
1625
|
-
* // Error handling omitted.
|
|
1626
|
-
* }
|
|
1627
|
-
*
|
|
1628
|
-
* // Queue this mutation until later calling `commit`.
|
|
1629
|
-
* // Note that a callback is not passed to `update`.
|
|
1630
|
-
* transaction.update('Singers', row);
|
|
1631
|
-
*
|
|
1632
|
-
* // Commit the transaction.
|
|
1633
|
-
* transaction.commit(function(err) {
|
|
1634
|
-
* if (!err) {
|
|
1635
|
-
* // The row was updated successfully.
|
|
1636
|
-
* }
|
|
1637
|
-
* });
|
|
1638
|
-
* });
|
|
1639
|
-
* ```
|
|
1640
|
-
*/
|
|
1641
|
-
update(table, rows) {
|
|
1642
|
-
this._mutate('update', table, rows);
|
|
1643
|
-
}
|
|
1644
|
-
/**
|
|
1645
|
-
* Insert or update rows of data within a table.
|
|
1646
|
-
*
|
|
1647
|
-
* @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit)
|
|
1648
|
-
*
|
|
1649
|
-
* @param {string} table The table to read from.
|
|
1650
|
-
* @param {object|object[]} rows A map of names to values of data to insert
|
|
1651
|
-
* into this table.
|
|
1652
|
-
*
|
|
1653
|
-
* @example
|
|
1654
|
-
* ```
|
|
1655
|
-
* const row = {
|
|
1656
|
-
* SingerId: 'Id3',
|
|
1657
|
-
* Name: 'Joe West'
|
|
1658
|
-
* };
|
|
1659
|
-
*
|
|
1660
|
-
* database.runTransaction(function(err, transaction) {
|
|
1661
|
-
* if (err) {
|
|
1662
|
-
* // Error handling omitted.
|
|
1663
|
-
* }
|
|
1664
|
-
*
|
|
1665
|
-
* // Queue this mutation until later calling `commit`.
|
|
1666
|
-
* // Note that a callback is not passed to `upsert`.
|
|
1667
|
-
* transaction.upsert('Singers', row);
|
|
1668
|
-
*
|
|
1669
|
-
* // Commit the transaction.
|
|
1670
|
-
* transaction.commit(function(err) {
|
|
1671
|
-
* if (!err) {
|
|
1672
|
-
* // The row was updated or inserted successfully.
|
|
1673
|
-
* }
|
|
1674
|
-
* });
|
|
1675
|
-
* });
|
|
1676
|
-
* ```
|
|
1677
|
-
*/
|
|
1678
|
-
upsert(table, rows) {
|
|
1679
|
-
this._mutate('insertOrUpdate', table, rows);
|
|
1680
|
-
}
|
|
1681
|
-
/**
|
|
1682
|
-
* Formats the mutations.
|
|
1683
|
-
*
|
|
1684
|
-
* @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit)
|
|
1685
|
-
*
|
|
1686
|
-
* @private
|
|
1687
|
-
*
|
|
1688
|
-
* @param {string} method CRUD method (insert, update, etc.).
|
|
1689
|
-
* @param {string} table Table to perform mutations in.
|
|
1690
|
-
* @param {object} rows Hash of key value pairs.
|
|
1691
|
-
*/
|
|
1692
|
-
_mutate(method, table, keyVals) {
|
|
1693
|
-
this._queuedMutations.push(buildMutation(method, table, keyVals));
|
|
1694
|
-
}
|
|
1695
|
-
/**
|
|
1696
|
-
* Takes a list of rows and returns all unique column names.
|
|
1697
|
-
*
|
|
1698
|
-
* @private
|
|
1699
|
-
*
|
|
1700
|
-
* @param {object[]} rows The rows.
|
|
1701
|
-
* @returns {string[]}
|
|
1702
|
-
*/
|
|
1703
|
-
static getUniqueKeys(rows) {
|
|
1704
|
-
const allKeys = [];
|
|
1705
|
-
rows.forEach(row => allKeys.push(...Object.keys(row)));
|
|
1706
|
-
const unique = new Set(allKeys);
|
|
1707
|
-
return Array.from(unique).sort();
|
|
1708
|
-
}
|
|
1709
|
-
/**
|
|
1710
|
-
* Mark transaction as started from the runner.
|
|
1711
|
-
*/
|
|
1712
|
-
useInRunner() {
|
|
1713
|
-
this._useInRunner = true;
|
|
1714
|
-
}
|
|
1715
|
-
/**
|
|
1716
|
-
* Use optimistic concurrency control for the transaction.
|
|
1717
|
-
*
|
|
1718
|
-
* In this concurrency mode, operations during the execution phase, i.e.,
|
|
1719
|
-
* reads and queries, are performed without acquiring locks, and transactional
|
|
1720
|
-
* consistency is ensured by running a validation process in the commit phase
|
|
1721
|
-
* (when any needed locks are acquired). The validation process succeeds only
|
|
1722
|
-
* if there are no conflicting committed transactions (that committed
|
|
1723
|
-
* mutations to the read data at a commit timestamp after the read timestamp).
|
|
1724
|
-
*/
|
|
1725
|
-
useOptimisticLock() {
|
|
1726
|
-
this._options.readWrite.readLockMode = ReadLockMode.OPTIMISTIC;
|
|
1727
|
-
}
|
|
1728
|
-
/**
|
|
1729
|
-
* Use option excludeTxnFromChangeStreams to exclude read/write transactions
|
|
1730
|
-
* from being tracked in change streams.
|
|
1731
|
-
*
|
|
1732
|
-
* Enabling this options to true will effectively disable change stream tracking
|
|
1733
|
-
* for a specified transaction, allowing read/write transaction to operate without being
|
|
1734
|
-
* included in change streams.
|
|
1735
|
-
*/
|
|
1736
|
-
excludeTxnFromChangeStreams() {
|
|
1737
|
-
this._options.excludeTxnFromChangeStreams = true;
|
|
1738
|
-
}
|
|
1739
|
-
}
|
|
1740
|
-
exports.Transaction = Transaction;
|
|
1741
|
-
/*! Developer Documentation
|
|
1742
|
-
*
|
|
1743
|
-
* All async methods (except for streams) return a Promise in the event
|
|
1744
|
-
* that a callback is omitted.
|
|
1745
|
-
*/
|
|
1746
|
-
(0, promisify_1.promisifyAll)(Transaction, {
|
|
1747
|
-
exclude: ['deleteRows', 'insert', 'replace', 'update', 'upsert'],
|
|
1748
|
-
});
|
|
1749
|
-
/**
|
|
1750
|
-
* Builds an array of protobuf Mutations from the given row(s).
|
|
1751
|
-
*
|
|
1752
|
-
* @param {string} method - CRUD method (insert, update, etc.).
|
|
1753
|
-
* @param {string} table - Table to perform mutations in.
|
|
1754
|
-
* @param {object | object[]} keyVals - Hash of key-value pairs representing the rows.
|
|
1755
|
-
* @returns {spannerClient.spanner.v1.Mutation} - The formatted mutation.
|
|
1756
|
-
* @throws {GoogleError} - If a row does not contain the correct number of columns.
|
|
1757
|
-
*/
|
|
1758
|
-
function buildMutation(method, table, keyVals) {
|
|
1759
|
-
const rows = arrify(keyVals);
|
|
1760
|
-
const columns = Transaction.getUniqueKeys(rows);
|
|
1761
|
-
const values = rows.map((row, index) => {
|
|
1762
|
-
const keys = Object.keys(row);
|
|
1763
|
-
const missingColumns = columns.filter(column => !keys.includes(column));
|
|
1764
|
-
if (missingColumns.length > 0) {
|
|
1765
|
-
throw new google_gax_1.GoogleError([
|
|
1766
|
-
`Row at index ${index} does not contain the correct number of columns.`,
|
|
1767
|
-
`Missing columns: ${JSON.stringify(missingColumns)}`,
|
|
1768
|
-
].join('\n\n'));
|
|
1769
|
-
}
|
|
1770
|
-
const values = columns.map(column => row[column]);
|
|
1771
|
-
return codec_1.codec.convertToListValue(values);
|
|
1772
|
-
});
|
|
1773
|
-
const mutation = {
|
|
1774
|
-
[method]: { table, columns, values },
|
|
1775
|
-
};
|
|
1776
|
-
return mutation;
|
|
1777
|
-
}
|
|
1778
|
-
/**
|
|
1779
|
-
* Builds a delete mutation.
|
|
1780
|
-
*
|
|
1781
|
-
* @param {string} table - The name of the table.
|
|
1782
|
-
* @param {Key[]} keys - The keys for the rows to delete.
|
|
1783
|
-
* @returns {spannerClient.spanner.v1.Mutation} - The formatted delete mutation.
|
|
1784
|
-
*/
|
|
1785
|
-
function buildDeleteMutation(table, keys) {
|
|
1786
|
-
const keySet = {
|
|
1787
|
-
keys: arrify(keys).map(codec_1.codec.convertToListValue),
|
|
1788
|
-
};
|
|
1789
|
-
const mutation = {
|
|
1790
|
-
delete: { table, keySet },
|
|
1791
|
-
};
|
|
1792
|
-
return mutation;
|
|
1793
|
-
}
|
|
1794
|
-
/**
|
|
1795
|
-
* MutationSet represent a set of changes to be applied atomically to a Cloud Spanner
|
|
1796
|
-
* database with a {@link Transaction}.
|
|
1797
|
-
* Mutations are used to insert, update, upsert(insert or update), replace, or
|
|
1798
|
-
* delete rows within tables.
|
|
1799
|
-
*
|
|
1800
|
-
* Mutations are added to a {@link Transaction} and are not executed until the
|
|
1801
|
-
* transaction is committed via {@link Transaction#commit}.
|
|
1802
|
-
*
|
|
1803
|
-
* If the transaction is rolled back or encounters an error, the mutations are
|
|
1804
|
-
* discarded.
|
|
1805
|
-
*
|
|
1806
|
-
* @example
|
|
1807
|
-
* ```
|
|
1808
|
-
* const {Spanner, Mutation} = require('@google-cloud/spanner');
|
|
1809
|
-
* const spanner = new Spanner();
|
|
1810
|
-
*
|
|
1811
|
-
* const instance = spanner.instance('my-instance');
|
|
1812
|
-
* const database = instance.database('my-database');
|
|
1813
|
-
*
|
|
1814
|
-
* const mutations = new MutationSet();
|
|
1815
|
-
* mutations.insert('Singers', {SingerId: '123', FirstName: 'David'});
|
|
1816
|
-
* mutations.update('Singers', {SingerId: '123', FirstName: 'Marc'});
|
|
1817
|
-
*
|
|
1818
|
-
* try {
|
|
1819
|
-
* database.writeAtLeastOnce(mutations, (err, res) => {
|
|
1820
|
-
* console.log("RESPONSE: ", res);
|
|
1821
|
-
* });
|
|
1822
|
-
* } catch(err) {
|
|
1823
|
-
* console.log("ERROR: ", err);
|
|
1824
|
-
* }
|
|
1825
|
-
* ```
|
|
1826
|
-
*/
|
|
1827
|
-
class MutationSet {
|
|
1828
|
-
/**
|
|
1829
|
-
* Creates a new Mutation object.
|
|
1830
|
-
*/
|
|
1831
|
-
constructor() {
|
|
1832
|
-
this._queuedMutations = [];
|
|
1833
|
-
}
|
|
1834
|
-
/**
|
|
1835
|
-
* Adds an insert operation to the mutation set.
|
|
1836
|
-
* @param {string} table. The name of the table to insert into.
|
|
1837
|
-
* @param {object|object[]} rows. A single row object or an array of row objects to insert.
|
|
1838
|
-
*/
|
|
1839
|
-
insert(table, rows) {
|
|
1840
|
-
this._queuedMutations.push(buildMutation('insert', table, rows));
|
|
1841
|
-
}
|
|
1842
|
-
/**
|
|
1843
|
-
* Adds an update operation to the mutation set.
|
|
1844
|
-
* @param {string} table. The name of the table to update.
|
|
1845
|
-
* @param {object|object[]} rows. A single row object or an array of row objects to update.
|
|
1846
|
-
* Each row object must contain the primary key values to indentify the row to update.
|
|
1847
|
-
*/
|
|
1848
|
-
update(table, rows) {
|
|
1849
|
-
this._queuedMutations.push(buildMutation('update', table, rows));
|
|
1850
|
-
}
|
|
1851
|
-
/**
|
|
1852
|
-
* Adds an upsert operation to the mutation set.
|
|
1853
|
-
* An upsert will insert a new row if it does not exist or update an existing row if it does.
|
|
1854
|
-
* @param {string} table. The name of the table to upsert.
|
|
1855
|
-
* @param {object|object[]} rows. A single row object or an array of row objects to upsert.
|
|
1856
|
-
*/
|
|
1857
|
-
upsert(table, rows) {
|
|
1858
|
-
this._queuedMutations.push(buildMutation('insertOrUpdate', table, rows));
|
|
1859
|
-
}
|
|
1860
|
-
/**
|
|
1861
|
-
* Adds a replace operation to the mutation set.
|
|
1862
|
-
* A replace operation deletes the existing row (if it exists) and inserts the new row.
|
|
1863
|
-
* @param {string} table. The name of the table to replace.
|
|
1864
|
-
* @param {object|object[]} rows. A single row object or an array of row objects to replace.
|
|
1865
|
-
*/
|
|
1866
|
-
replace(table, rows) {
|
|
1867
|
-
this._queuedMutations.push(buildMutation('replace', table, rows));
|
|
1868
|
-
}
|
|
1869
|
-
/**
|
|
1870
|
-
* Adds a deleteRows operation to the mutation set.
|
|
1871
|
-
* This operation deletes rows from the specified table based on their primary keys.
|
|
1872
|
-
* @param {string} table. The name of the table to deleteRows from.
|
|
1873
|
-
* @param {key[]} key. An array of key objects, each represeting the primary key of a row to delete.
|
|
1874
|
-
*/
|
|
1875
|
-
deleteRows(table, keys) {
|
|
1876
|
-
this._queuedMutations.push(buildDeleteMutation(table, keys));
|
|
1877
|
-
}
|
|
1878
|
-
/**
|
|
1879
|
-
* Returns the internal representation of the queued mutations as a protobuf message.
|
|
1880
|
-
* @returns {spannerClient.spanner.v1.Mutation[]}. The protobuf message representing the mutations.
|
|
1881
|
-
*/
|
|
1882
|
-
proto() {
|
|
1883
|
-
return this._queuedMutations;
|
|
1884
|
-
}
|
|
1885
|
-
}
|
|
1886
|
-
exports.MutationSet = MutationSet;
|
|
1887
|
-
/**
|
|
1888
|
-
* A group of mutations to be committed together.
|
|
1889
|
-
* Related mutations should be placed in a group.
|
|
1890
|
-
*
|
|
1891
|
-
* For example, two mutations inserting rows with the same primary
|
|
1892
|
-
* key prefix in both parent and child tables are related.
|
|
1893
|
-
*
|
|
1894
|
-
* This object is created and returned from {@link Database#MutationGroup}.
|
|
1895
|
-
*
|
|
1896
|
-
* @example
|
|
1897
|
-
* ```
|
|
1898
|
-
* const {Spanner} = require('@google-cloud/spanner');
|
|
1899
|
-
* const spanner = new Spanner();
|
|
1900
|
-
*
|
|
1901
|
-
* const instance = spanner.instance('my-instance');
|
|
1902
|
-
* const database = instance.database('my-database');
|
|
1903
|
-
*
|
|
1904
|
-
* const mutationGroup = new MutationGroup();
|
|
1905
|
-
* mutationGroup.insert('Singers', {SingerId: '123', FirstName: 'David'});
|
|
1906
|
-
* mutationGroup.update('Singers', {SingerId: '123', FirstName: 'Marc'});
|
|
1907
|
-
*
|
|
1908
|
-
* database.batchWriteAtLeastOnce([mutationGroup], {})
|
|
1909
|
-
* .on('error', console.error)
|
|
1910
|
-
* .on('data', response => {
|
|
1911
|
-
* console.log('response: ', response);
|
|
1912
|
-
* })
|
|
1913
|
-
* .on('end', () => {
|
|
1914
|
-
* console.log('Request completed successfully');
|
|
1915
|
-
* });
|
|
1916
|
-
* ```
|
|
1917
|
-
*/
|
|
1918
|
-
class MutationGroup {
|
|
1919
|
-
constructor() {
|
|
1920
|
-
this._proto =
|
|
1921
|
-
new protos_1.google.spanner.v1.BatchWriteRequest.MutationGroup();
|
|
1922
|
-
}
|
|
1923
|
-
insert(table, rows) {
|
|
1924
|
-
this._proto.mutations.push(buildMutation('insert', table, rows));
|
|
1925
|
-
}
|
|
1926
|
-
update(table, rows) {
|
|
1927
|
-
this._proto.mutations.push(buildMutation('update', table, rows));
|
|
1928
|
-
}
|
|
1929
|
-
upsert(table, rows) {
|
|
1930
|
-
this._proto.mutations.push(buildMutation('insertOrUpdate', table, rows));
|
|
1931
|
-
}
|
|
1932
|
-
replace(table, rows) {
|
|
1933
|
-
this._proto.mutations.push(buildMutation('replace', table, rows));
|
|
1934
|
-
}
|
|
1935
|
-
deleteRows(table, keys) {
|
|
1936
|
-
this._proto.mutations.push(buildDeleteMutation(table, keys));
|
|
1937
|
-
}
|
|
1938
|
-
proto() {
|
|
1939
|
-
return this._proto;
|
|
1940
|
-
}
|
|
1941
|
-
}
|
|
1942
|
-
exports.MutationGroup = MutationGroup;
|
|
1943
|
-
/**
|
|
1944
|
-
* This type of transaction is used to execute a single Partitioned DML
|
|
1945
|
-
* statement. Partitioned DML partitions the key space and runs the DML
|
|
1946
|
-
* statement over each partition in parallel using separate, internal
|
|
1947
|
-
* transactions that commit independently.
|
|
1948
|
-
*
|
|
1949
|
-
* Chances are, you'll never need to create a partitioned DML transaction
|
|
1950
|
-
* directly, instead you'll want to use {@link Database#runPartitionedUpdate}.
|
|
1951
|
-
*
|
|
1952
|
-
* @class
|
|
1953
|
-
* @extends Snapshot
|
|
1954
|
-
*
|
|
1955
|
-
* @see Database#runPartitionedUpdate
|
|
1956
|
-
*/
|
|
1957
|
-
class PartitionedDml extends Dml {
|
|
1958
|
-
constructor(session, options = {}) {
|
|
1959
|
-
super(session);
|
|
1960
|
-
this._options = { partitionedDml: options };
|
|
1961
|
-
}
|
|
1962
|
-
/**
|
|
1963
|
-
* Use option excludeTxnFromChangeStreams to exclude partitionedDml
|
|
1964
|
-
* queries from being tracked in change streams.
|
|
1965
|
-
*
|
|
1966
|
-
* Enabling this options to true will effectively disable change stream tracking
|
|
1967
|
-
* for a specified partitionedDml query, allowing write queries to operate
|
|
1968
|
-
* without being included in change streams.
|
|
1969
|
-
*/
|
|
1970
|
-
excludeTxnFromChangeStreams() {
|
|
1971
|
-
this._options.excludeTxnFromChangeStreams = true;
|
|
1972
|
-
}
|
|
1973
|
-
runUpdate(query, callback) {
|
|
1974
|
-
const traceConfig = {
|
|
1975
|
-
sql: query,
|
|
1976
|
-
opts: this._observabilityOptions,
|
|
1977
|
-
dbName: this._dbName,
|
|
1978
|
-
};
|
|
1979
|
-
return (0, instrument_2.startTrace)('PartitionedDml.runUpdate', traceConfig, span => {
|
|
1980
|
-
super.runUpdate(query, (err, count) => {
|
|
1981
|
-
if (err) {
|
|
1982
|
-
(0, instrument_2.setSpanError)(span, err);
|
|
1983
|
-
}
|
|
1984
|
-
this.end();
|
|
1985
|
-
span.end();
|
|
1986
|
-
callback(err, count);
|
|
1987
|
-
});
|
|
1988
|
-
});
|
|
1989
|
-
}
|
|
1990
|
-
}
|
|
1991
|
-
exports.PartitionedDml = PartitionedDml;
|
|
1992
|
-
function isErrorAborted(err) {
|
|
1993
|
-
return (err &&
|
|
1994
|
-
typeof err === 'object' &&
|
|
1995
|
-
'code' in err &&
|
|
1996
|
-
err.code === google_gax_1.grpc.status.ABORTED);
|
|
1997
|
-
}
|
|
1998
|
-
/*! Developer Documentation
|
|
1999
|
-
*
|
|
2000
|
-
* All async methods (except for streams) return a Promise in the event
|
|
2001
|
-
* that a callback is omitted.
|
|
2002
|
-
*/
|
|
2003
|
-
(0, promisify_1.promisifyAll)(PartitionedDml);
|
|
2004
|
-
//# sourceMappingURL=transaction.js.map
|