@google-cloud/spanner 8.7.1 → 8.8.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.
@@ -178,7 +178,10 @@ class Database extends common.GrpcServiceObject {
178
178
  this._clientId = instance._nthClientId;
179
179
  }
180
180
  this._observabilityOptions = instance._observabilityOptions;
181
- this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.formattedName_, this._observabilityOptions?.enableEndToEndTracing);
181
+ this.commonHeaders_ = {
182
+ ...instance.commonHeaders_,
183
+ [common_1.CLOUD_RESOURCE_HEADER]: this.formattedName_,
184
+ };
182
185
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
183
186
  this.requestStream = instance.requestStream;
184
187
  this.sessionFactory_ = new session_factory_1.SessionFactory(this, name, poolOptions);
@@ -142,3 +142,19 @@ export declare function isInfinite(value: any): boolean;
142
142
  * @returns {Boolean} `true` if the value is an `Error` object, otherwise `false`.
143
143
  */
144
144
  export declare function isError(value: any): boolean;
145
+ /**
146
+ * Checks if a value is a UUID.
147
+ * @param {*} value The value to check.
148
+ * @returns {Boolean} `true` if the value is a UUID, otherwise `false`.
149
+ */
150
+ export declare function isUuid(value: any): boolean;
151
+ /**
152
+ * Populate the `{{projectId}}` placeholder.
153
+ *
154
+ * @throws {Error} If a projectId is required, but one is not provided.
155
+ *
156
+ * @param {*} - Any input value that may contain a placeholder. Arrays and objects will be looped.
157
+ * @param {string} projectId - A projectId. If not provided
158
+ * @return {*} - The original argument with all placeholders populated.
159
+ */
160
+ export declare function replaceProjectIdToken(value: any, projectId: string): any;
@@ -35,7 +35,10 @@ exports.isActualNaN = isActualNaN;
35
35
  exports.isDecimal = isDecimal;
36
36
  exports.isInfinite = isInfinite;
37
37
  exports.isError = isError;
38
+ exports.isUuid = isUuid;
39
+ exports.replaceProjectIdToken = replaceProjectIdToken;
38
40
  const google_gax_1 = require("google-gax");
41
+ const stream_1 = require("stream");
39
42
  /**
40
43
  * Checks whether the given error is a 'Database not found' error.
41
44
  * @param {Error} error The error to check.
@@ -246,4 +249,90 @@ function isError(value) {
246
249
  return (value instanceof Error ||
247
250
  Object.prototype.toString.call(value) === '[object Error]');
248
251
  }
252
+ const UUID_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
253
+ /**
254
+ * Checks if a value is a UUID.
255
+ * @param {*} value The value to check.
256
+ * @returns {Boolean} `true` if the value is a UUID, otherwise `false`.
257
+ */
258
+ function isUuid(value) {
259
+ return typeof value === 'string' && UUID_REGEX.test(value);
260
+ }
261
+ const PROJECT_ID_TOKEN = '{{projectId}}';
262
+ const PROJECT_ID_TOKEN_REGEX = /{{projectId}}/g;
263
+ // Whitelisted request properties that contain, or lead to, resource name strings with project ID placeholders.
264
+ const KEYS_TO_SCAN = new Set([
265
+ 'database',
266
+ 'session',
267
+ 'name',
268
+ 'parent',
269
+ 'instance',
270
+ 'resource',
271
+ 'backup',
272
+ 'instanceConfig',
273
+ 'baseConfig',
274
+ 'kmsKeyName',
275
+ // Intermediate object keys that must be traversed to reach the above leaves
276
+ 'config',
277
+ 'encryptionConfig',
278
+ ]);
279
+ /**
280
+ * Populate the `{{projectId}}` placeholder.
281
+ *
282
+ * @throws {Error} If a projectId is required, but one is not provided.
283
+ *
284
+ * @param {*} - Any input value that may contain a placeholder. Arrays and objects will be looped.
285
+ * @param {string} projectId - A projectId. If not provided
286
+ * @return {*} - The original argument with all placeholders populated.
287
+ */
288
+ function replaceProjectIdToken(value, projectId) {
289
+ if (typeof value === 'string') {
290
+ if (value.includes(PROJECT_ID_TOKEN)) {
291
+ if (!projectId || projectId === PROJECT_ID_TOKEN) {
292
+ throw new MissingProjectIdError();
293
+ }
294
+ return value.replace(PROJECT_ID_TOKEN_REGEX, projectId);
295
+ }
296
+ return value;
297
+ }
298
+ if (value === null || typeof value !== 'object') {
299
+ return value;
300
+ }
301
+ if (Array.isArray(value)) {
302
+ for (let i = 0; i < value.length; i++) {
303
+ const original = value[i];
304
+ const processed = replaceProjectIdToken(original, projectId);
305
+ if (processed !== original) {
306
+ value[i] = processed;
307
+ }
308
+ }
309
+ return value;
310
+ }
311
+ if (value instanceof Buffer || value instanceof stream_1.Stream || isDate(value)) {
312
+ return value;
313
+ }
314
+ for (const key in value) {
315
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
316
+ if (!KEYS_TO_SCAN.has(key)) {
317
+ continue;
318
+ }
319
+ const original = value[key];
320
+ const processed = replaceProjectIdToken(original, projectId);
321
+ if (processed !== original) {
322
+ value[key] = processed;
323
+ }
324
+ }
325
+ }
326
+ return value;
327
+ }
328
+ /**
329
+ * Custom error type for missing project ID errors.
330
+ */
331
+ class MissingProjectIdError extends Error {
332
+ constructor() {
333
+ super(`Sorry, we cannot connect to Cloud Services without a project
334
+ ID. You may specify one with an environment variable named
335
+ "GOOGLE_CLOUD_PROJECT".`.replace(/ +/g, ' '));
336
+ }
337
+ }
249
338
  //# sourceMappingURL=helper.js.map
@@ -18,7 +18,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.Interval = exports.SpannerDate = exports.PGNumeric = exports.Numeric = exports.Struct = exports.Int = exports.Float = exports.Float32 = exports.protos = exports.v1 = exports.MutationSet = 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
- const projectify_1 = require("@google-cloud/projectify");
21
+ const helper_1 = require("./helper");
22
22
  const promisify_1 = require("@google-cloud/promisify");
23
23
  const extend = require("extend");
24
24
  const google_auth_library_1 = require("google-auth-library");
@@ -303,9 +303,11 @@ class Spanner extends service_1.GrpcService {
303
303
  this.directedReadOptions = directedReadOptions;
304
304
  this.defaultTransactionOptions = defaultTransactionOptions;
305
305
  this._observabilityOptions = options.observabilityOptions;
306
+ if ((0, instrument_1.isTracingEnabled)(this._observabilityOptions)) {
307
+ (0, instrument_1.ensureInitialContextManagerSet)();
308
+ }
306
309
  this.sessionLabels = options.sessionLabels || null;
307
310
  this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.projectFormattedName_, this._observabilityOptions?.enableEndToEndTracing);
308
- (0, instrument_1.ensureInitialContextManagerSet)();
309
311
  this._nthClientId = (0, request_id_header_1.nextSpannerClientId)();
310
312
  this._universeDomain = universeEndpoint;
311
313
  this.projectId_ = options.projectId;
@@ -824,31 +826,33 @@ class Spanner extends service_1.GrpcService {
824
826
  }
825
827
  const gaxClient = this.clients_.get(clientName);
826
828
  let reqOpts = extend(true, {}, config.reqOpts);
827
- reqOpts = (0, projectify_1.replaceProjectIdToken)(reqOpts, projectId);
829
+ reqOpts = (0, helper_1.replaceProjectIdToken)(reqOpts, projectId);
828
830
  // It would have been preferable to replace the projectId already in the
829
831
  // constructor of Spanner, but that is not possible as auth.getProjectId
830
832
  // is an async method. This is therefore the first place where we have
831
833
  // access to the value that should be used instead of the placeholder.
832
834
  if (!this.projectIdReplaced_) {
833
- this.projectId = (0, projectify_1.replaceProjectIdToken)(this.projectId, projectId);
834
- this.projectFormattedName_ = (0, projectify_1.replaceProjectIdToken)(this.projectFormattedName_, projectId);
835
+ this.projectId = (0, helper_1.replaceProjectIdToken)(this.projectId, projectId);
836
+ this.projectFormattedName_ = (0, helper_1.replaceProjectIdToken)(this.projectFormattedName_, projectId);
835
837
  this.instances_.forEach(instance => {
836
- instance.formattedName_ = (0, projectify_1.replaceProjectIdToken)(instance.formattedName_, projectId);
838
+ instance.formattedName_ = (0, helper_1.replaceProjectIdToken)(instance.formattedName_, projectId);
837
839
  instance.databases_.forEach(database => {
838
- database.formattedName_ = (0, projectify_1.replaceProjectIdToken)(database.formattedName_, projectId);
840
+ database.formattedName_ = (0, helper_1.replaceProjectIdToken)(database.formattedName_, projectId);
839
841
  });
840
842
  });
841
843
  this.projectIdReplaced_ = true;
842
844
  }
843
- config.headers[common_1.CLOUD_RESOURCE_HEADER] = (0, projectify_1.replaceProjectIdToken)(config.headers[common_1.CLOUD_RESOURCE_HEADER], projectId);
844
- // Do context propagation
845
- api_1.propagation.inject(api_1.context.active(), config.headers, {
846
- set: (carrier, key, value) => {
847
- carrier[key] = value; // Set the span context (trace and span ID)
848
- },
849
- });
850
- // Attach the x-goog-spanner-request-id to the currently active span.
851
- (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
845
+ config.headers[common_1.CLOUD_RESOURCE_HEADER] = (0, helper_1.replaceProjectIdToken)(config.headers[common_1.CLOUD_RESOURCE_HEADER], projectId);
846
+ if ((0, instrument_1.isTracingEnabled)(this._observabilityOptions)) {
847
+ // Do context propagation
848
+ api_1.propagation.inject(api_1.context.active(), config.headers, {
849
+ set: (carrier, key, value) => {
850
+ carrier[key] = value; // Set the span context (trace and span ID)
851
+ },
852
+ });
853
+ // Attach the x-goog-spanner-request-id to the currently active span.
854
+ (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
855
+ }
852
856
  const interceptors = [];
853
857
  if (this._metricsEnabled) {
854
858
  interceptors.push(interceptor_1.MetricInterceptor);
@@ -122,7 +122,10 @@ class Instance extends common.GrpcServiceObject {
122
122
  this.requestStream = spanner.requestStream.bind(spanner);
123
123
  this.databases_ = new Map();
124
124
  this._observabilityOptions = spanner._observabilityOptions;
125
- this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.formattedName_, this._observabilityOptions?.enableEndToEndTracing);
125
+ this.commonHeaders_ = {
126
+ ...spanner.commonHeaders_,
127
+ [common_1.CLOUD_RESOURCE_HEADER]: this.formattedName_,
128
+ };
126
129
  }
127
130
  /**
128
131
  * Get a reference to a Backup object.
@@ -47,6 +47,16 @@ declare const SPAN_NAMESPACE_PREFIX = "CloudSpanner";
47
47
  export { SPAN_NAMESPACE_PREFIX, traceConfig };
48
48
  declare function ensureInitialContextManagerSet(): void;
49
49
  export { ensureInitialContextManagerSet };
50
+ /**
51
+ * isTracingEnabled returns true if tracing is enabled for the given options
52
+ * or globally.
53
+ *
54
+ * @param {ObservabilityOptions} [opts] The observability options.
55
+ * @returns {boolean} True if tracing is enabled.
56
+ */
57
+ export declare function isTracingEnabled(opts?: ObservabilityOptions): boolean;
58
+ /** Only exported for resetting state in unit tests. */
59
+ export declare function _resetTracingEnabledForTest(): void;
50
60
  /**
51
61
  * startTrace begins an active span in the current active context
52
62
  * and passes it back to the set callback function. Each span will
@@ -18,6 +18,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.SPAN_NAMESPACE_PREFIX = exports.TRACER_VERSION = exports.TRACER_NAME = void 0;
19
19
  exports.getTracer = getTracer;
20
20
  exports.ensureInitialContextManagerSet = ensureInitialContextManagerSet;
21
+ exports.isTracingEnabled = isTracingEnabled;
22
+ exports._resetTracingEnabledForTest = _resetTracingEnabledForTest;
21
23
  exports.startTrace = startTrace;
22
24
  exports.setSpanError = setSpanError;
23
25
  exports.setSpanErrorAndException = setSpanErrorAndException;
@@ -46,25 +48,81 @@ function getTracer(tracerProvider) {
46
48
  const SPAN_NAMESPACE_PREFIX = 'CloudSpanner'; // TODO: discuss & standardize this prefix.
47
49
  exports.SPAN_NAMESPACE_PREFIX = SPAN_NAMESPACE_PREFIX;
48
50
  const { AsyncHooksContextManager, } = require('@opentelemetry/context-async-hooks');
51
+ let contextManagerInstallAttempted = false;
49
52
  /*
50
- * This function ensures that async/await works correctly by
51
- * checking if context.active() returns an invalid/unset context
52
- * and if so, sets a global AsyncHooksContextManager otherwise
53
- * spans resulting from async/await invocations won't be correctly
54
- * associated in their respective hierarchies.
53
+ * If no global ContextManager is registered, install an AsyncHooksContextManager
54
+ * so that async/await trace context propagation works for apps that haven't
55
+ * configured OpenTelemetry themselves. If the host app has already installed a
56
+ * ContextManager, leave it alone — tearing down a working manager breaks the
57
+ * host's baggage and span parentage on the next gRPC call.
58
+ *
59
+ * setGlobalContextManager() returns false when a manager is already registered,
60
+ * which is the documented signal that we shouldn't replace it. The
61
+ * `contextManagerInstallAttempted` latch makes the call idempotent so we don't
62
+ * allocate a new AsyncHooksContextManager on each Spanner client construction.
55
63
  */
56
64
  function ensureInitialContextManagerSet() {
57
- if (!api_1.context['_contextManager'] || api_1.context.active() === api_1.ROOT_CONTEXT) {
58
- // If no context manager is currently set, or if the active context is the ROOT_CONTEXT,
59
- // trace context propagation cannot
60
- // function correctly with async/await for OpenTelemetry
61
- // See {@link https://opentelemetry.io/docs/languages/js/context/#active-context}
62
- api_1.context.disable(); // Disable any prior contextManager.
63
- const contextManager = new AsyncHooksContextManager();
65
+ if (contextManagerInstallAttempted)
66
+ return;
67
+ contextManagerInstallAttempted = true;
68
+ const contextManager = new AsyncHooksContextManager();
69
+ if (api_1.context.setGlobalContextManager(contextManager)) {
64
70
  contextManager.enable();
65
- api_1.context.setGlobalContextManager(contextManager);
66
71
  }
67
72
  }
73
+ let globalTracingEnabled = undefined;
74
+ let lastCheckTime = 0;
75
+ const CACHE_TTL_MS = 10000; // 10 seconds TTL
76
+ /**
77
+ * isGlobalTracingEnabled returns true if tracing is enabled globally,
78
+ * respecting cached status and active recording spans.
79
+ *
80
+ * @returns {boolean} True if global tracing is enabled.
81
+ */
82
+ function isGlobalTracingEnabled() {
83
+ const now = Date.now();
84
+ if (globalTracingEnabled !== undefined &&
85
+ (globalTracingEnabled || now - lastCheckTime < CACHE_TTL_MS)) {
86
+ return globalTracingEnabled;
87
+ }
88
+ lastCheckTime = now;
89
+ const globalProvider = api_1.trace.getTracerProvider();
90
+ if (globalProvider) {
91
+ let delegate = globalProvider;
92
+ if (typeof globalProvider.getDelegate === 'function') {
93
+ delegate = globalProvider.getDelegate();
94
+ }
95
+ if (delegate) {
96
+ const name = delegate.constructor.name;
97
+ // Exclude the dummy NoopTracerProvider and uninitialized ProxyTracerProvider
98
+ if (name !== 'NoopTracerProvider' && name !== 'ProxyTracerProvider') {
99
+ globalTracingEnabled = true;
100
+ ensureInitialContextManagerSet();
101
+ return true;
102
+ }
103
+ }
104
+ }
105
+ globalTracingEnabled = false;
106
+ return false;
107
+ }
108
+ /**
109
+ * isTracingEnabled returns true if tracing is enabled for the given options
110
+ * or globally.
111
+ *
112
+ * @param {ObservabilityOptions} [opts] The observability options.
113
+ * @returns {boolean} True if tracing is enabled.
114
+ */
115
+ function isTracingEnabled(opts) {
116
+ if (opts?.tracerProvider) {
117
+ return true;
118
+ }
119
+ return isGlobalTracingEnabled();
120
+ }
121
+ /** Only exported for resetting state in unit tests. */
122
+ function _resetTracingEnabledForTest() {
123
+ globalTracingEnabled = undefined;
124
+ lastCheckTime = 0;
125
+ }
68
126
  /**
69
127
  * startTrace begins an active span in the current active context
70
128
  * and passes it back to the set callback function. Each span will
@@ -74,6 +132,9 @@ function ensureInitialContextManagerSet() {
74
132
  * @returns {Span} The created span.
75
133
  */
76
134
  function startTrace(spanNameSuffix, config, cb) {
135
+ if (!isTracingEnabled(config?.opts)) {
136
+ return cb(new noopSpan());
137
+ }
77
138
  if (!config) {
78
139
  config = {};
79
140
  }
@@ -59,7 +59,7 @@ export declare class MetricsTracerFactory {
59
59
  /**
60
60
  * Resets the singleton instance of the MetricsTracerFactory.
61
61
  */
62
- static resetInstance(projectId?: string): Promise<void>;
62
+ static resetInstance(): Promise<void>;
63
63
  /**
64
64
  * Resets the MeterProvider.
65
65
  */
@@ -17,8 +17,8 @@ exports.MetricsTracerFactory = void 0;
17
17
  const crypto = require("crypto");
18
18
  const os = require("os");
19
19
  const process = require("process");
20
- const uuid_1 = require("uuid");
21
20
  const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
21
+ const api_1 = require("@opentelemetry/api");
22
22
  const resources_1 = require("@opentelemetry/resources");
23
23
  const opentelemetry_resource_util_1 = require("@google-cloud/opentelemetry-resource-util");
24
24
  const Constants = require("./constants");
@@ -78,7 +78,7 @@ class MetricsTracerFactory {
78
78
  }
79
79
  this._clientHash = MetricsTracerFactory._generateClientHash(this._clientUid);
80
80
  // Start the Tracer cleanup task at an interval
81
- this._intervalTracerCleanup = setInterval(this._cleanMetricsTracers.bind(this), Constants.TRACER_CLEANUP_INTERVAL_MS);
81
+ this._intervalTracerCleanup = api_1.context.with(api_1.ROOT_CONTEXT, () => setInterval(this._cleanMetricsTracers.bind(this), Constants.TRACER_CLEANUP_INTERVAL_MS));
82
82
  // unref the interval to prevent it from blocking app termination
83
83
  // in the event loop
84
84
  this._intervalTracerCleanup.unref();
@@ -127,7 +127,7 @@ class MetricsTracerFactory {
127
127
  /**
128
128
  * Resets the singleton instance of the MetricsTracerFactory.
129
129
  */
130
- static async resetInstance(projectId) {
130
+ static async resetInstance() {
131
131
  clearInterval(MetricsTracerFactory._instance?._intervalTracerCleanup);
132
132
  await MetricsTracerFactory._instance?.resetMeterProvider();
133
133
  MetricsTracerFactory._instance = null;
@@ -313,7 +313,7 @@ class MetricsTracerFactory {
313
313
  * @returns A unique string identifier for the client.
314
314
  */
315
315
  static _generateClientUId() {
316
- const identifier = (0, uuid_1.v4)();
316
+ const identifier = crypto.randomUUID();
317
317
  const pid = process.pid.toString();
318
318
  let hostname = 'localhost';
319
319
  try {
@@ -17,6 +17,7 @@
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.MultiplexedSession = void 0;
19
19
  const events_1 = require("events");
20
+ const api_1 = require("@opentelemetry/api");
20
21
  const instrument_1 = require("./instrument");
21
22
  /**
22
23
  * Class used to manage connections to Spanner using multiplexed session.
@@ -83,22 +84,24 @@ class MultiplexedSession extends events_1.EventEmitter {
83
84
  opts: this._observabilityOptions,
84
85
  dbName: this.database.formattedName_,
85
86
  };
86
- return (0, instrument_1.startTrace)('MultiplexedSession.createSession', traceConfig, async (span) => {
87
- span.addEvent('Requesting a multiplexed session');
88
- try {
89
- const [createSessionResponse] = await this.database.createSession({
90
- multiplexed: true,
91
- });
92
- this._multiplexedSession = createSessionResponse;
93
- span.addEvent('Created a multiplexed session');
94
- }
95
- catch (e) {
96
- (0, instrument_1.setSpanError)(span, e);
97
- throw e;
98
- }
99
- finally {
100
- span.end();
101
- }
87
+ return api_1.context.with(api_1.ROOT_CONTEXT, () => {
88
+ return (0, instrument_1.startTrace)('MultiplexedSession.createSession', traceConfig, async (span) => {
89
+ span.addEvent('Requesting a multiplexed session');
90
+ try {
91
+ const [createSessionResponse] = await this.database.createSession({
92
+ multiplexed: true,
93
+ });
94
+ this._multiplexedSession = createSessionResponse;
95
+ span.addEvent('Created a multiplexed session');
96
+ }
97
+ catch (e) {
98
+ (0, instrument_1.setSpanError)(span, e);
99
+ throw e;
100
+ }
101
+ finally {
102
+ span.end();
103
+ }
104
+ });
102
105
  });
103
106
  };
104
107
  // Assign the running task to the shared promise variable, and ensure
@@ -132,9 +135,9 @@ class MultiplexedSession extends events_1.EventEmitter {
132
135
  clearInterval(this._refreshHandle);
133
136
  }
134
137
  const refreshRate = this.refreshRate * 24 * 60 * 60000;
135
- this._refreshHandle = setInterval(async () => {
136
- await this._createSession().catch(() => { });
137
- }, refreshRate);
138
+ this._refreshHandle = api_1.context.with(api_1.ROOT_CONTEXT, () => setInterval(() => {
139
+ this._createSession().catch(() => { });
140
+ }, refreshRate));
138
141
  // Unreference the timer so it does not prevent the Node.js process from exiting.
139
142
  // If the application has finished all other work, this background timer shouldn't
140
143
  // force the process to stay open.
@@ -158,6 +158,7 @@ interface ResultEvents {
158
158
  export declare class PartialResultStream extends Transform implements ResultEvents {
159
159
  private _destroyed;
160
160
  private _fields;
161
+ private _decoders;
161
162
  private _options;
162
163
  private _pendingValue?;
163
164
  private _pendingValueForResume?;
@@ -199,6 +200,16 @@ export declare class PartialResultStream extends Transform implements ResultEven
199
200
  * @param {*} value The complete value.
200
201
  */
201
202
  private _addValue;
203
+ /**
204
+ * Directly creates a plain JSON object from row cell values, bypassing
205
+ * Struct, Row, and WrappedNumber class wrappers when possible.
206
+ *
207
+ * @private
208
+ *
209
+ * @param {Value[]} values The raw cell values for the current row.
210
+ * @returns {Json} The plain JavaScript object representing the row.
211
+ */
212
+ private _createJsonRow;
202
213
  /**
203
214
  * Converts an array of values into a row.
204
215
  *
@@ -29,6 +29,8 @@ const codec_1 = require("./codec");
29
29
  const protos_1 = require("../protos/protos");
30
30
  const stream = require("stream");
31
31
  const helper_1 = require("./helper");
32
+ const originalDecode = codec_1.codec.decode;
33
+ const originalConvertFieldsToJson = codec_1.codec.convertFieldsToJson;
32
34
  /**
33
35
  * The PartialResultStream transforms partial result set objects into Row
34
36
  * objects.
@@ -41,6 +43,7 @@ const helper_1 = require("./helper");
41
43
  class PartialResultStream extends stream_1.Transform {
42
44
  _destroyed;
43
45
  _fields;
46
+ _decoders;
44
47
  _options;
45
48
  _pendingValue;
46
49
  _pendingValueForResume;
@@ -87,10 +90,28 @@ class PartialResultStream extends stream_1.Transform {
87
90
  if (!this._fields && chunk.metadata) {
88
91
  this._fields = chunk.metadata.rowType
89
92
  .fields;
93
+ this._decoders = this._fields.map(({ name, type }) => {
94
+ const columnMetadata = this._options.columnsMetadata &&
95
+ name !== null &&
96
+ name !== undefined &&
97
+ Object.prototype.hasOwnProperty.call(this._options.columnsMetadata, name)
98
+ ? this._options.columnsMetadata[name]
99
+ : undefined;
100
+ if (codec_1.codec.decode !== originalDecode) {
101
+ return val => codec_1.codec.decode(val, type, columnMetadata);
102
+ }
103
+ return codec_1.codec.getDecoder(type, columnMetadata, this._options.json ? this._options.jsonOptions || {} : undefined);
104
+ });
90
105
  }
91
106
  let res = true;
92
107
  if (!(0, helper_1.isEmpty)(chunk.values)) {
93
- res = this._addChunk(chunk);
108
+ try {
109
+ res = this._addChunk(chunk);
110
+ }
111
+ catch (err) {
112
+ next(err);
113
+ return;
114
+ }
94
115
  }
95
116
  if (chunk.last) {
96
117
  this.push(null);
@@ -149,7 +170,12 @@ class PartialResultStream extends stream_1.Transform {
149
170
  * @param {object} chunk The partial result set.
150
171
  */
151
172
  _addChunk(chunk) {
152
- const values = chunk.values.map(service_1.GrpcService.decodeValue_);
173
+ const chunkValues = chunk.values;
174
+ const numValues = chunkValues.length;
175
+ const values = new Array(numValues);
176
+ for (let i = 0; i < numValues; i++) {
177
+ values[i] = service_1.GrpcService.decodeValue_(chunkValues[i]);
178
+ }
153
179
  // If we have a chunk to merge, merge the values now.
154
180
  if (this._pendingValue) {
155
181
  const currentField = this._values.length % this._fields.length;
@@ -170,12 +196,13 @@ class PartialResultStream extends stream_1.Transform {
170
196
  delete this._pendingValueForResume;
171
197
  }
172
198
  let res = true;
173
- values.forEach(value => {
174
- res = this._addValue(value) && res;
199
+ const len = values.length;
200
+ for (let i = 0; i < len; i++) {
201
+ res = this._addValue(values[i]) && res;
175
202
  if (!res) {
176
203
  this.emit('paused');
177
204
  }
178
- });
205
+ }
179
206
  return res;
180
207
  }
181
208
  /**
@@ -193,12 +220,50 @@ class PartialResultStream extends stream_1.Transform {
193
220
  return true;
194
221
  }
195
222
  this._values = [];
223
+ const isJsonStubbed = codec_1.codec.convertFieldsToJson !== originalConvertFieldsToJson;
224
+ if (this._options.json && !isJsonStubbed) {
225
+ return this.push(this._createJsonRow(values));
226
+ }
196
227
  const row = this._createRow(values);
197
228
  if (this._options.json) {
198
229
  return this.push(row.toJSON(this._options.jsonOptions));
199
230
  }
200
231
  return this.push(row);
201
232
  }
233
+ /**
234
+ * Directly creates a plain JSON object from row cell values, bypassing
235
+ * Struct, Row, and WrappedNumber class wrappers when possible.
236
+ *
237
+ * @private
238
+ *
239
+ * @param {Value[]} values The raw cell values for the current row.
240
+ * @returns {Json} The plain JavaScript object representing the row.
241
+ */
242
+ _createJsonRow(values) {
243
+ const json = {};
244
+ const fields = this._fields;
245
+ const decoders = this._decoders;
246
+ const len = fields.length;
247
+ const includeNameless = !!this._options.jsonOptions?.includeNameless;
248
+ for (let i = 0; i < len; i++) {
249
+ const { name } = fields[i];
250
+ if (!name && !includeNameless) {
251
+ continue;
252
+ }
253
+ const fieldName = name ? name : `_${i}`;
254
+ try {
255
+ json[fieldName] = decoders[i](values[i]);
256
+ }
257
+ catch (e) {
258
+ e.message = [
259
+ `Serializing column "${fieldName}" encountered an error: ${e.message}`,
260
+ 'Call row.toJSON({ wrapNumbers: true }) to receive a custom type.',
261
+ ].join(' ');
262
+ throw e;
263
+ }
264
+ }
265
+ return json;
266
+ }
202
267
  /**
203
268
  * Converts an array of values into a row.
204
269
  *
@@ -208,14 +273,16 @@ class PartialResultStream extends stream_1.Transform {
208
273
  * @returns {Row}
209
274
  */
210
275
  _createRow(values) {
211
- const fields = values.map((value, index) => {
212
- const { name, type } = this._fields[index];
213
- const columnMetadata = this._options.columnsMetadata?.[name];
214
- return {
215
- name,
216
- value: codec_1.codec.decode(value, type, columnMetadata),
276
+ const len = values.length;
277
+ const fields = new Array(len);
278
+ const decoders = this._decoders;
279
+ const classFields = this._fields;
280
+ for (let i = 0; i < len; i++) {
281
+ fields[i] = {
282
+ name: classFields[i].name,
283
+ value: decoders[i](values[i]),
217
284
  };
218
- });
285
+ }
219
286
  Object.defineProperty(fields, 'toJSON', {
220
287
  value: (options) => {
221
288
  return codec_1.codec.convertFieldsToJson(fields, options);