@google-cloud/spanner 8.11.0 → 8.13.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.
@@ -28,7 +28,6 @@ const extend = require("extend");
28
28
  const google_gax_1 = require("google-gax");
29
29
  const retryRequest = require("retry-request");
30
30
  const stream_1 = require("stream");
31
- const helper_2 = require("../helper");
32
31
  const gaxProtoPath = path.join(path.dirname(require.resolve('google-gax')), '..', 'protos');
33
32
  // TODO: convert this object to an array
34
33
  /**
@@ -173,7 +172,7 @@ class ObjectToStructConverter {
173
172
  for (const prop in obj) {
174
173
  if (Object.prototype.hasOwnProperty.call(obj, prop)) {
175
174
  const value = obj[prop];
176
- if ((0, helper_2.isUndefined)(value)) {
175
+ if ((0, helper_1.isUndefined)(value)) {
177
176
  continue;
178
177
  }
179
178
  convertedObject.fields[prop] = this.encodeValue_(value);
@@ -198,22 +197,22 @@ class ObjectToStructConverter {
198
197
  */
199
198
  encodeValue_(value) {
200
199
  let convertedValue;
201
- if ((0, helper_2.isNull)(value)) {
200
+ if ((0, helper_1.isNull)(value)) {
202
201
  convertedValue = {
203
202
  nullValue: 0,
204
203
  };
205
204
  }
206
- else if ((0, helper_2.isNumber)(value)) {
205
+ else if ((0, helper_1.isNumber)(value)) {
207
206
  convertedValue = {
208
207
  numberValue: value,
209
208
  };
210
209
  }
211
- else if ((0, helper_2.isString)(value)) {
210
+ else if ((0, helper_1.isString)(value)) {
212
211
  convertedValue = {
213
212
  stringValue: value,
214
213
  };
215
214
  }
216
- else if ((0, helper_2.isBoolean)(value)) {
215
+ else if ((0, helper_1.isBoolean)(value)) {
217
216
  convertedValue = {
218
217
  boolValue: value,
219
218
  };
@@ -223,7 +222,7 @@ class ObjectToStructConverter {
223
222
  blobValue: value,
224
223
  };
225
224
  }
226
- else if ((0, helper_2.isObject)(value)) {
225
+ else if ((0, helper_1.isObject)(value)) {
227
226
  if (this.seenObjects.has(value)) {
228
227
  // Circular reference.
229
228
  if (!this.removeCircular) {
@@ -242,7 +241,7 @@ class ObjectToStructConverter {
242
241
  };
243
242
  }
244
243
  }
245
- else if ((0, helper_2.isArray)(value)) {
244
+ else if ((0, helper_1.isArray)(value)) {
246
245
  convertedValue = {
247
246
  listValue: {
248
247
  values: value.map(this.encodeValue_.bind(this)),
@@ -531,7 +530,7 @@ class GrpcService extends common_1.Service {
531
530
  const service = this.getService_(protoOpts);
532
531
  const grpcMetadata = this.grpcMetadata;
533
532
  const grpcOpts = {};
534
- if ((0, helper_2.isNumber)(protoOpts.timeout)) {
533
+ if ((0, helper_1.isNumber)(protoOpts.timeout)) {
535
534
  grpcOpts.deadline = GrpcService.createDeadline_(protoOpts.timeout);
536
535
  }
537
536
  try {
@@ -625,7 +624,7 @@ class GrpcService extends common_1.Service {
625
624
  * @return {error|null}
626
625
  */
627
626
  static decorateError_(err) {
628
- const errorObj = (0, helper_2.isError)(err) ? err : {};
627
+ const errorObj = (0, helper_1.isError)(err) ? err : {};
629
628
  return GrpcService.decorateGrpcResponse_(errorObj, err);
630
629
  }
631
630
  /**
@@ -1567,6 +1567,37 @@ declare class Database extends common.GrpcServiceObject {
1567
1567
  run(query: string | ExecuteSqlRequest, options?: TimestampBounds): Promise<RunResponse>;
1568
1568
  run(query: string | ExecuteSqlRequest, callback: RunCallback): void;
1569
1569
  run(query: string | ExecuteSqlRequest, options: TimestampBounds, callback: RunCallback): void;
1570
+ /**
1571
+ * Always runs the query through the full streaming pipeline (Database.prototype.runStream).
1572
+ * Used when runStream has been overridden on Database, or when multiplexed
1573
+ * sessions are disabled (requiring standard session pool checkout and session-not-found retries).
1574
+ *
1575
+ * @private
1576
+ */
1577
+ private _runLegacy;
1578
+ /**
1579
+ * Executes a query using an optimized streaming model:
1580
+ * 1. If all results are returned in a single PartialResultSet, the internal streaming
1581
+ * pipeline is simplified and rows are decoded directly, bypassing Stream overhead.
1582
+ * 2. If there are more than one PartialResultSets, it seamlessly falls back to
1583
+ * the standard streaming model.
1584
+ *
1585
+ * @private
1586
+ */
1587
+ private _run;
1588
+ /**
1589
+ * Acquires a session and executes the query on a snapshot, managing span
1590
+ * lifetimes and session release.
1591
+ *
1592
+ * @private
1593
+ */
1594
+ private _executeRunOnSession;
1595
+ /**
1596
+ * Executes the query on the snapshot and binds session release to snapshot end.
1597
+ *
1598
+ * @private
1599
+ */
1600
+ private _runOnSnapshot;
1570
1601
  /**
1571
1602
  * Partitioned DML transactions are used to execute DML statements with a
1572
1603
  * different execution strategy that provides different, and often better,
@@ -1801,6 +1832,8 @@ declare class Database extends common.GrpcServiceObject {
1801
1832
  */
1802
1833
  runTransaction(runFn: RunTransactionCallback): void;
1803
1834
  runTransaction(options: RunTransactionOptions, runFn: RunTransactionCallback): void;
1835
+ private _runTransaction;
1836
+ private _executeTransactionRunner;
1804
1837
  runTransactionAsync<T = {}>(runFn: AsyncRunTransactionCallback<T>): Promise<T>;
1805
1838
  runTransactionAsync<T = {}>(options: RunTransactionOptions, runFn: AsyncRunTransactionCallback<T>): Promise<T>;
1806
1839
  /**
@@ -29,6 +29,7 @@ const session_factory_1 = require("./session-factory");
29
29
  const session_1 = require("./session");
30
30
  const session_pool_1 = require("./session-pool");
31
31
  const table_1 = require("./table");
32
+ const transaction_1 = require("./transaction");
32
33
  const transaction_runner_1 = require("./transaction-runner");
33
34
  const common_1 = require("./common");
34
35
  const stream_1 = require("stream");
@@ -941,16 +942,31 @@ class Database extends common.GrpcServiceObject {
941
942
  });
942
943
  }
943
944
  run(query, optionsOrCallback, cb) {
944
- let stats;
945
- let metadata;
946
- const rows = [];
947
945
  const callback = typeof optionsOrCallback === 'function'
948
946
  ? optionsOrCallback
949
947
  : cb;
950
948
  const options = typeof optionsOrCallback === 'object'
951
949
  ? optionsOrCallback
952
950
  : {};
953
- return (0, instrument_1.startTrace)('Database.run', {
951
+ if (this.runStream !== Database.prototype.runStream ||
952
+ !this.sessionFactory_.isMultiplexedEnabled()) {
953
+ this._runLegacy(query, options, callback);
954
+ return;
955
+ }
956
+ this._run(query, options, callback);
957
+ }
958
+ /**
959
+ * Always runs the query through the full streaming pipeline (Database.prototype.runStream).
960
+ * Used when runStream has been overridden on Database, or when multiplexed
961
+ * sessions are disabled (requiring standard session pool checkout and session-not-found retries).
962
+ *
963
+ * @private
964
+ */
965
+ _runLegacy(query, options, callback) {
966
+ const rows = [];
967
+ let stats;
968
+ let metadata;
969
+ (0, instrument_1.startTrace)('Database.run', {
954
970
  ...query,
955
971
  ...this._traceConfig,
956
972
  }, span => {
@@ -975,6 +991,89 @@ class Database extends common.GrpcServiceObject {
975
991
  });
976
992
  });
977
993
  }
994
+ /**
995
+ * Executes a query using an optimized streaming model:
996
+ * 1. If all results are returned in a single PartialResultSet, the internal streaming
997
+ * pipeline is simplified and rows are decoded directly, bypassing Stream overhead.
998
+ * 2. If there are more than one PartialResultSets, it seamlessly falls back to
999
+ * the standard streaming model.
1000
+ *
1001
+ * @private
1002
+ */
1003
+ _run(query, options, callback) {
1004
+ const traceConfig = {
1005
+ ...query,
1006
+ ...this._traceConfig,
1007
+ };
1008
+ (0, instrument_1.startTrace)('Database.run', traceConfig, runSpan => {
1009
+ (0, instrument_1.startTrace)('Database.runStream', traceConfig, streamSpan => {
1010
+ this._executeRunOnSession(query, options, runSpan, streamSpan, callback);
1011
+ });
1012
+ });
1013
+ }
1014
+ /**
1015
+ * Acquires a session and executes the query on a snapshot, managing span
1016
+ * lifetimes and session release.
1017
+ *
1018
+ * @private
1019
+ */
1020
+ _executeRunOnSession(query, options, runSpan, streamSpan, callback) {
1021
+ let snapshot;
1022
+ let completed = false;
1023
+ const complete = (error, rows = [], stats, metadata) => {
1024
+ if (completed) {
1025
+ return;
1026
+ }
1027
+ completed = true;
1028
+ if (error) {
1029
+ (0, instrument_1.setSpanError)(streamSpan, error);
1030
+ (0, instrument_1.setSpanError)(runSpan, error);
1031
+ }
1032
+ snapshot?.end();
1033
+ streamSpan.end();
1034
+ runSpan.end();
1035
+ callback(error, rows, stats, metadata);
1036
+ };
1037
+ this.sessionFactory_.getSession((error, session) => {
1038
+ if (error) {
1039
+ complete(error);
1040
+ return;
1041
+ }
1042
+ streamSpan.addEvent('Using Session', { 'session.id': session?.id });
1043
+ snapshot = session.snapshot(options, this.queryOptions_);
1044
+ this._runOnSnapshot(snapshot, session, query, complete);
1045
+ });
1046
+ }
1047
+ /**
1048
+ * Executes the query on the snapshot and binds session release to snapshot end.
1049
+ *
1050
+ * @private
1051
+ */
1052
+ _runOnSnapshot(snapshot, session, query, callback) {
1053
+ snapshot.once('end', () => {
1054
+ try {
1055
+ this.sessionFactory_.release(session);
1056
+ }
1057
+ catch (releaseError) {
1058
+ this.emit('error', releaseError);
1059
+ }
1060
+ });
1061
+ const snapshotWithRun = snapshot;
1062
+ try {
1063
+ if (typeof snapshotWithRun._run === 'function' &&
1064
+ snapshot.runStream === transaction_1.Snapshot.prototype.runStream) {
1065
+ snapshotWithRun._run(query, callback, {
1066
+ startRunSpan: false,
1067
+ });
1068
+ }
1069
+ else {
1070
+ snapshot.run(query, callback);
1071
+ }
1072
+ }
1073
+ catch (syncError) {
1074
+ callback(syncError);
1075
+ }
1076
+ }
978
1077
  runPartitionedUpdate(query, callback) {
979
1078
  return (0, instrument_1.startTrace)('Database.runPartitionedUpdate', {
980
1079
  ...query,
@@ -1229,12 +1328,13 @@ class Database extends common.GrpcServiceObject {
1229
1328
  (0, instrument_1.startTrace)('Database.runTransaction', {
1230
1329
  ...this._traceConfig,
1231
1330
  transactionTag: options.requestOptions?.transactionTag,
1232
- }, span => {
1233
- this.sessionFactory_.getSessionForReadWrite((err, session, transaction) => {
1234
- if (err) {
1235
- (0, instrument_1.setSpanError)(span, err);
1236
- }
1237
- if (err && (0, session_pool_1.isSessionNotFoundError)(err)) {
1331
+ }, span => this._runTransaction(span, options, runFn));
1332
+ }
1333
+ _runTransaction(span, options, runFn) {
1334
+ this.sessionFactory_.getSessionForReadWrite((err, session, transaction) => {
1335
+ if (err) {
1336
+ (0, instrument_1.setSpanError)(span, err);
1337
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1238
1338
  span.addEvent('No session available', {
1239
1339
  'session.id': session?.id,
1240
1340
  });
@@ -1242,34 +1342,46 @@ class Database extends common.GrpcServiceObject {
1242
1342
  this.runTransaction(options, runFn);
1243
1343
  return;
1244
1344
  }
1245
- if (err) {
1246
- span.end();
1247
- runFn(err);
1248
- return;
1249
- }
1250
- transaction._observabilityOptions = this._observabilityOptions;
1251
- transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1252
- transaction.setReadWriteTransactionOptions(options);
1253
- const release = () => {
1254
- this.sessionFactory_.release(session);
1255
- span.end();
1256
- };
1257
- const runner = new transaction_runner_1.TransactionRunner(session, transaction, runFn, options);
1258
- runner.run().then(release, err => {
1259
- (0, instrument_1.setSpanError)(span, err);
1260
- if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1261
- span.addEvent('No session available', {
1262
- 'session.id': session?.id,
1263
- });
1264
- release();
1265
- this.runTransaction(options, runFn);
1266
- }
1267
- else {
1268
- setImmediate(runFn, err);
1269
- release();
1270
- }
1345
+ span.end();
1346
+ runFn(err);
1347
+ return;
1348
+ }
1349
+ this._executeTransactionRunner(session, transaction, span, options, runFn);
1350
+ });
1351
+ }
1352
+ _executeTransactionRunner(session, transaction, span, options, runFn) {
1353
+ transaction._observabilityOptions = this._observabilityOptions;
1354
+ transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1355
+ transaction.setReadWriteTransactionOptions(options);
1356
+ const release = () => {
1357
+ this.sessionFactory_.release(session);
1358
+ span.end();
1359
+ };
1360
+ const runner = new transaction_runner_1.TransactionRunner(session, transaction, runFn, options);
1361
+ runner
1362
+ .run()
1363
+ .then(() => {
1364
+ release();
1365
+ return null;
1366
+ }, err => {
1367
+ (0, instrument_1.setSpanError)(span, err);
1368
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1369
+ span.addEvent('No session available', {
1370
+ 'session.id': session.id,
1271
1371
  });
1272
- });
1372
+ release();
1373
+ this.runTransaction(options, runFn);
1374
+ }
1375
+ else {
1376
+ setImmediate(runFn, err);
1377
+ release();
1378
+ }
1379
+ return null;
1380
+ })
1381
+ .catch(err => {
1382
+ (0, instrument_1.setSpanErrorAndException)(span, err);
1383
+ span.end();
1384
+ this.emit('error', err);
1273
1385
  });
1274
1386
  }
1275
1387
  /**
@@ -1531,11 +1643,19 @@ class Database extends common.GrpcServiceObject {
1531
1643
  return;
1532
1644
  }
1533
1645
  span.addEvent('Using Session', { 'session.id': session?.id });
1534
- this._releaseOnEnd(session, transaction, span);
1646
+ const activeTransaction = transaction ?? session?.transaction(this.queryOptions_);
1647
+ if (!activeTransaction) {
1648
+ const error = new Error('No transaction available to commit');
1649
+ (0, instrument_1.setSpanError)(span, error);
1650
+ span.end();
1651
+ cb(error);
1652
+ return;
1653
+ }
1654
+ this._releaseOnEnd(session, activeTransaction, span);
1535
1655
  try {
1536
- transaction.setReadWriteTransactionOptions(options);
1537
- transaction?.setQueuedMutations(mutations.proto());
1538
- return transaction?.commit(options, (err, resp) => {
1656
+ activeTransaction.setReadWriteTransactionOptions(options);
1657
+ activeTransaction.setQueuedMutations(mutations.proto());
1658
+ return activeTransaction.commit(options, (err, resp) => {
1539
1659
  if (err) {
1540
1660
  (0, instrument_1.setSpanError)(span, err);
1541
1661
  }
@@ -15,10 +15,9 @@
15
15
  declare const common: any;
16
16
  import { protos } from '@google-cloud/spanner-api';
17
17
  import instanceAdmin = protos.google;
18
- import { Operation as GaxOperation } from 'google-gax';
18
+ import { Operation as GaxOperation, CallOptions } from 'google-gax';
19
19
  import { LongRunningCallback, RequestCallback, ResourceCallback, NormalCallback } from './common';
20
20
  import { GetInstanceConfigCallback, GetInstanceConfigOptions, GetInstanceConfigResponse, RequestConfig, Spanner } from './index';
21
- import { CallOptions } from 'google-gax';
22
21
  export type IOperation = instanceAdmin.longrunning.IOperation;
23
22
  export type CreateInstanceConfigCallback = LongRunningCallback<InstanceConfig>;
24
23
  export type SetInstanceConfigMetadataCallback = ResourceCallback<GaxOperation, IOperation>;
@@ -16,10 +16,10 @@
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.InstanceConfig = void 0;
18
18
  const common = require('./common-grpc/service-object');
19
+ const google_gax_1 = require("google-gax");
19
20
  const snakeCase = require("lodash.snakecase");
20
21
  const common_1 = require("./common");
21
22
  const promisify_1 = require("@google-cloud/promisify");
22
- const google_gax_1 = require("google-gax");
23
23
  /**
24
24
  * The {@link InstanceConfig} class represents a possible configuration for a
25
25
  * Cloud Spanner instance.
@@ -16,7 +16,7 @@
16
16
  import { GetConfig } from '@google-cloud/common';
17
17
  declare const common: any;
18
18
  import { Database, SessionPoolConstructor } from './database';
19
- import { Spanner, RequestConfig } from '.';
19
+ import { Spanner, RequestConfig, CreateInstanceRequest } from '.';
20
20
  import { RequestCallback, PagedOptions, PagedResponse, LongRunningCallback, NormalCallback, ResourceCallback, PagedOptionsWithFilter } from './common';
21
21
  import { Duplex } from 'stream';
22
22
  import { SessionPoolOptions, SessionPool } from './session-pool';
@@ -26,7 +26,6 @@ import { protos } from '@google-cloud/spanner-api';
26
26
  import databaseAdmin = protos.google;
27
27
  import instanceAdmin = protos.google;
28
28
  import spannerClient = protos.google;
29
- import { CreateInstanceRequest } from './index';
30
29
  import { ObservabilityOptions } from './instrument';
31
30
  export type IBackup = databaseAdmin.spanner.admin.database.v1.IBackup;
32
31
  export type IDatabase = databaseAdmin.spanner.admin.database.v1.IDatabase;
@@ -80,9 +80,12 @@ const CACHE_TTL_MS = 10000; // 10 seconds TTL
80
80
  * @returns {boolean} True if global tracing is enabled.
81
81
  */
82
82
  function isGlobalTracingEnabled() {
83
+ if (globalTracingEnabled === true) {
84
+ return true;
85
+ }
83
86
  const now = Date.now();
84
87
  if (globalTracingEnabled !== undefined &&
85
- (globalTracingEnabled || now - lastCheckTime < CACHE_TTL_MS)) {
88
+ now - lastCheckTime < CACHE_TTL_MS) {
86
89
  return globalTracingEnabled;
87
90
  }
88
91
  lastCheckTime = now;
@@ -133,7 +136,7 @@ function _resetTracingEnabledForTest() {
133
136
  */
134
137
  function startTrace(spanNameSuffix, config, cb) {
135
138
  if (!isTracingEnabled(config?.opts)) {
136
- return cb(new noopSpan());
139
+ return cb(NOOP_SPAN);
137
140
  }
138
141
  if (!config) {
139
142
  config = {};
@@ -236,17 +239,17 @@ function getActiveOrNoopSpan() {
236
239
  if (span) {
237
240
  return span;
238
241
  }
239
- return new noopSpan();
242
+ return NOOP_SPAN;
240
243
  }
241
244
  /**
242
- * noopSpan is a pass-through Span that does nothing and shall not
245
+ * NoopSpan is a pass-through Span that does nothing and shall not
243
246
  * be exported, nor added into any context. It serves as a placeholder
244
247
  * to allow calls in sensitive areas like sessionPools to transparently
245
248
  * add attributes to spans without lots of ugly null checks.
246
249
  *
247
250
  * It exists because OpenTelemetry-JS does not seem to export the NoopSpan.
248
251
  */
249
- class noopSpan {
252
+ class NoopSpan {
250
253
  constructor() { }
251
254
  spanContext() {
252
255
  return api_1.INVALID_SPAN_CONTEXT;
@@ -278,4 +281,5 @@ class noopSpan {
278
281
  return this;
279
282
  }
280
283
  }
284
+ const NOOP_SPAN = new NoopSpan();
281
285
  //# sourceMappingURL=instrument.js.map
@@ -47,7 +47,10 @@ const MetricInterceptor = (options, nextCall) => {
47
47
  // GFE/AFE latency if available,
48
48
  // or else increase the GFE/AFE connectivity error count
49
49
  if (metricsTracer) {
50
- const serverTimingHeader = metadata.getMap()['server-timing'];
50
+ const serverTimingEntries = metadata.get('server-timing');
51
+ const serverTimingHeader = serverTimingEntries.length > 0
52
+ ? String(serverTimingEntries[0])
53
+ : undefined;
51
54
  const gfeTiming = metricsTracer?.extractGfeLatency(serverTimingHeader);
52
55
  metricsTracer.gfeLatency = gfeTiming ?? null;
53
56
  const afeTiming = metricsTracer?.extractAfeLatency(serverTimingHeader);
@@ -50,7 +50,9 @@ class CloudMonitoringMetricsExporter {
50
50
  return;
51
51
  }
52
52
  this._lastExported = now;
53
- this._exportAsync(metrics).then(resultCallback, err => {
53
+ this._exportAsync(metrics)
54
+ .then(resultCallback)
55
+ .catch(err => {
54
56
  resultCallback({ code: core_1.ExportResultCode.FAILED, error: err });
55
57
  });
56
58
  }
@@ -100,6 +100,9 @@ export declare class MultiplexedSession extends EventEmitter implements Multiple
100
100
  _maintain(): void;
101
101
  /**
102
102
  * Retrieves a session asynchronously and invokes a callback with the session details.
103
+ * Note: The callback receives `(null, session)`. To prevent unnecessary allocations on
104
+ * read query paths, a `Transaction` is not created here. Callers requiring a read-write
105
+ * transaction should use `SessionFactory.prototype.getSessionForReadWrite`.
103
106
  *
104
107
  * @param {GetSessionCallback} callback - The callback to be invoked once the session is acquired or an error occurs.
105
108
  *
@@ -57,10 +57,11 @@ class MultiplexedSession extends events_1.EventEmitter {
57
57
  this._createSession()
58
58
  .then(() => {
59
59
  this._maintain();
60
+ return null;
60
61
  })
61
62
  // Ignore errors here. If this fails, the next user request will
62
63
  // automatically trigger a retry via `_getSession`.
63
- .catch(err => { });
64
+ .catch(() => { });
64
65
  }
65
66
  /**
66
67
  * Creates a new multiplexed session.
@@ -145,6 +146,9 @@ class MultiplexedSession extends events_1.EventEmitter {
145
146
  }
146
147
  /**
147
148
  * Retrieves a session asynchronously and invokes a callback with the session details.
149
+ * Note: The callback receives `(null, session)`. To prevent unnecessary allocations on
150
+ * read query paths, a `Transaction` is not created here. Callers requiring a read-write
151
+ * transaction should use `SessionFactory.prototype.getSessionForReadWrite`.
148
152
  *
149
153
  * @param {GetSessionCallback} callback - The callback to be invoked once the session is acquired or an error occurs.
150
154
  *
@@ -152,7 +156,29 @@ class MultiplexedSession extends events_1.EventEmitter {
152
156
  *
153
157
  */
154
158
  getSession(callback) {
155
- this._getSession().then(session => callback(null, session, session.transaction(session.parent.queryOptions_)), callback);
159
+ if (this._multiplexedSession !== null) {
160
+ const session = this._multiplexedSession;
161
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
162
+ span.addEvent('Cache hit: has usable multiplexed session');
163
+ // Use process.nextTick to guarantee asynchronous callback execution ("never release Zalgo").
164
+ // This avoids microtask and Promise allocation overhead while preventing race conditions
165
+ // where callers (such as Database.prototype.runStream) need to return their stream and
166
+ // register lifecycle listeners before the session callback executes.
167
+ process.nextTick(() => {
168
+ callback(null, session);
169
+ });
170
+ return;
171
+ }
172
+ this._getSession()
173
+ .then(session => {
174
+ callback(null, session);
175
+ return null;
176
+ }, callback)
177
+ .catch(err => {
178
+ process.nextTick(() => {
179
+ throw err;
180
+ });
181
+ });
156
182
  }
157
183
  /**
158
184
  * Attempts to get a session, waiting for it to become available if necessary.
@@ -106,6 +106,39 @@ export interface Row extends Array<Field> {
106
106
  */
107
107
  toJSON(options?: JSONOptions): Json;
108
108
  }
109
+ /**
110
+ * Creates an array of decoder functions for the specified struct fields.
111
+ *
112
+ * @private
113
+ */
114
+ export declare function createFieldDecoders(fields: google.spanner.v1.StructType.Field[], options?: RowOptions): Function[];
115
+ /**
116
+ * Directly creates a plain JSON object from row cell values, bypassing
117
+ * Struct, Row, and WrappedNumber class wrappers when possible.
118
+ *
119
+ * @private
120
+ */
121
+ export declare function createJsonRow(fields: google.spanner.v1.StructType.Field[], decoders: Function[], values: Value[], includeNameless?: boolean): Json;
122
+ /**
123
+ * Converts an array of decoded cell values into a Row.
124
+ *
125
+ * @private
126
+ */
127
+ export declare function createRow(fields: google.spanner.v1.StructType.Field[], decoders: Function[], values: Value[]): Row;
128
+ /**
129
+ * Formats raw row values into either a plain JSON object or a Row instance
130
+ * according to the provided RowOptions.
131
+ *
132
+ * @private
133
+ */
134
+ export declare function formatRow(fields: google.spanner.v1.StructType.Field[], decoders: Function[], values: Value[], options?: RowOptions): Row;
135
+ /**
136
+ * Directly decodes rows from a PartialResultSet without going through the stream
137
+ * pipeline. Used by the fast-path for queries returning small results in a single chunk.
138
+ *
139
+ * @private
140
+ */
141
+ export declare function decodeRowsDirect(chunk: google.spanner.v1.PartialResultSet, options?: RowOptions, existingFields?: google.spanner.v1.StructType.Field[], existingDecoders?: Function[]): Row[];
109
142
  /**
110
143
  * @callback PartialResultStream~rowCallback
111
144
  * @param {Row|object} row The row data.
@@ -165,6 +198,7 @@ export declare class PartialResultStream extends Transform implements ResultEven
165
198
  private _pendingValueForResume?;
166
199
  private _values;
167
200
  private _numPushFailed;
201
+ private _isFirstChunk;
168
202
  constructor(options?: {});
169
203
  /**
170
204
  * Destroys the stream.
@@ -192,6 +226,15 @@ export declare class PartialResultStream extends Transform implements ResultEven
192
226
  * @param {object} chunk The partial result set.
193
227
  */
194
228
  private _addChunk;
229
+ /**
230
+ * Fast-path handler for single-chunk stream responses. Decodes rows directly
231
+ * and pushes them into the stream without incremental chunk buffering.
232
+ *
233
+ * @private
234
+ * @param {google.spanner.v1.PartialResultSet} chunk The partial result set.
235
+ * @returns {boolean} Whether the stream can accept more data.
236
+ */
237
+ private _addSingleChunk;
195
238
  /**
196
239
  * Manages complete values, pushing a completed row into the stream once all
197
240
  * values have been received.