@databricks/sql 1.15.0 → 1.16.0-rc.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.
Files changed (119) hide show
  1. package/dist/DBSQLClient.d.ts +3 -0
  2. package/dist/DBSQLClient.js +97 -56
  3. package/dist/DBSQLClient.js.map +1 -1
  4. package/dist/DBSQLLogger.d.ts +3 -0
  5. package/dist/DBSQLLogger.js +25 -0
  6. package/dist/DBSQLLogger.js.map +1 -1
  7. package/dist/DBSQLOperation.d.ts +36 -17
  8. package/dist/DBSQLOperation.js +133 -214
  9. package/dist/DBSQLOperation.js.map +1 -1
  10. package/dist/DBSQLParameter.d.ts +2 -0
  11. package/dist/DBSQLParameter.js +63 -7
  12. package/dist/DBSQLParameter.js.map +1 -1
  13. package/dist/DBSQLSession.d.ts +24 -17
  14. package/dist/DBSQLSession.js +45 -263
  15. package/dist/DBSQLSession.js.map +1 -1
  16. package/dist/connection/connections/HttpRetryPolicy.d.ts +3 -0
  17. package/dist/connection/connections/HttpRetryPolicy.js +116 -21
  18. package/dist/connection/connections/HttpRetryPolicy.js.map +1 -1
  19. package/dist/connection/connections/ThriftHttpConnection.js +18 -3
  20. package/dist/connection/connections/ThriftHttpConnection.js.map +1 -1
  21. package/dist/contracts/IBackend.d.ts +31 -0
  22. package/dist/contracts/IBackend.js +3 -0
  23. package/dist/contracts/IBackend.js.map +1 -0
  24. package/dist/contracts/IClientContext.d.ts +1 -0
  25. package/dist/contracts/IDBSQLClient.d.ts +31 -0
  26. package/dist/contracts/IDBSQLLogger.d.ts +17 -0
  27. package/dist/contracts/IDBSQLLogger.js.map +1 -1
  28. package/dist/contracts/IDBSQLSession.d.ts +24 -1
  29. package/dist/contracts/IOperation.d.ts +10 -1
  30. package/dist/contracts/IOperationBackend.d.ts +98 -0
  31. package/dist/contracts/IOperationBackend.js +3 -0
  32. package/dist/contracts/IOperationBackend.js.map +1 -0
  33. package/dist/contracts/ISessionBackend.d.ts +36 -0
  34. package/dist/contracts/ISessionBackend.js +3 -0
  35. package/dist/contracts/ISessionBackend.js.map +1 -0
  36. package/dist/contracts/InternalConnectionOptions.d.ts +72 -0
  37. package/dist/contracts/InternalConnectionOptions.js +3 -0
  38. package/dist/contracts/InternalConnectionOptions.js.map +1 -0
  39. package/dist/contracts/OperationStatus.d.ts +76 -0
  40. package/dist/contracts/OperationStatus.js +28 -0
  41. package/dist/contracts/OperationStatus.js.map +1 -0
  42. package/dist/contracts/ResultMetadata.d.ts +34 -0
  43. package/dist/contracts/ResultMetadata.js +16 -0
  44. package/dist/contracts/ResultMetadata.js.map +1 -0
  45. package/dist/errors/AuthenticationError.d.ts +1 -0
  46. package/dist/errors/AuthenticationError.js +4 -0
  47. package/dist/errors/AuthenticationError.js.map +1 -1
  48. package/dist/kernel/KernelArrowIpc.d.ts +54 -0
  49. package/dist/kernel/KernelArrowIpc.js +292 -0
  50. package/dist/kernel/KernelArrowIpc.js.map +1 -0
  51. package/dist/kernel/KernelArrowIpcDurationFix.d.ts +29 -0
  52. package/dist/kernel/KernelArrowIpcDurationFix.js +605 -0
  53. package/dist/kernel/KernelArrowIpcDurationFix.js.map +1 -0
  54. package/dist/kernel/KernelAuth.d.ts +300 -0
  55. package/dist/kernel/KernelAuth.js +463 -0
  56. package/dist/kernel/KernelAuth.js.map +1 -0
  57. package/dist/kernel/KernelBackend.d.ts +53 -0
  58. package/dist/kernel/KernelBackend.js +164 -0
  59. package/dist/kernel/KernelBackend.js.map +1 -0
  60. package/dist/kernel/KernelErrorMapping.d.ts +109 -0
  61. package/dist/kernel/KernelErrorMapping.js +249 -0
  62. package/dist/kernel/KernelErrorMapping.js.map +1 -0
  63. package/dist/kernel/KernelInputValidation.d.ts +16 -0
  64. package/dist/kernel/KernelInputValidation.js +49 -0
  65. package/dist/kernel/KernelInputValidation.js.map +1 -0
  66. package/dist/kernel/KernelLogging.d.ts +63 -0
  67. package/dist/kernel/KernelLogging.js +128 -0
  68. package/dist/kernel/KernelLogging.js.map +1 -0
  69. package/dist/kernel/KernelNativeLoader.d.ts +77 -0
  70. package/dist/kernel/KernelNativeLoader.js +178 -0
  71. package/dist/kernel/KernelNativeLoader.js.map +1 -0
  72. package/dist/kernel/KernelOperationBackend.d.ts +154 -0
  73. package/dist/kernel/KernelOperationBackend.js +640 -0
  74. package/dist/kernel/KernelOperationBackend.js.map +1 -0
  75. package/dist/kernel/KernelOperationLifecycle.d.ts +130 -0
  76. package/dist/kernel/KernelOperationLifecycle.js +245 -0
  77. package/dist/kernel/KernelOperationLifecycle.js.map +1 -0
  78. package/dist/kernel/KernelPositionalParams.d.ts +16 -0
  79. package/dist/kernel/KernelPositionalParams.js +120 -0
  80. package/dist/kernel/KernelPositionalParams.js.map +1 -0
  81. package/dist/kernel/KernelResultsProvider.d.ts +44 -0
  82. package/dist/kernel/KernelResultsProvider.js +102 -0
  83. package/dist/kernel/KernelResultsProvider.js.map +1 -0
  84. package/dist/kernel/KernelServerInfo.d.ts +44 -0
  85. package/dist/kernel/KernelServerInfo.js +73 -0
  86. package/dist/kernel/KernelServerInfo.js.map +1 -0
  87. package/dist/kernel/KernelSessionBackend.d.ts +100 -0
  88. package/dist/kernel/KernelSessionBackend.js +384 -0
  89. package/dist/kernel/KernelSessionBackend.js.map +1 -0
  90. package/dist/result/ArrowResultConverter.d.ts +31 -2
  91. package/dist/result/ArrowResultConverter.js +226 -14
  92. package/dist/result/ArrowResultConverter.js.map +1 -1
  93. package/dist/result/CloudFetchResultHandler.js +36 -8
  94. package/dist/result/CloudFetchResultHandler.js.map +1 -1
  95. package/dist/telemetry/DatabricksTelemetryExporter.js +34 -1
  96. package/dist/telemetry/DatabricksTelemetryExporter.js.map +1 -1
  97. package/dist/telemetry/telemetryTypeMappers.d.ts +1 -1
  98. package/dist/telemetry/telemetryTypeMappers.js +1 -1
  99. package/dist/telemetry/telemetryTypeMappers.js.map +1 -1
  100. package/dist/telemetry/types.d.ts +15 -0
  101. package/dist/thrift-backend/ThriftBackend.d.ts +17 -0
  102. package/dist/thrift-backend/ThriftBackend.js +80 -0
  103. package/dist/thrift-backend/ThriftBackend.js.map +1 -0
  104. package/dist/thrift-backend/ThriftOperationBackend.d.ts +70 -0
  105. package/dist/thrift-backend/ThriftOperationBackend.js +330 -0
  106. package/dist/thrift-backend/ThriftOperationBackend.js.map +1 -0
  107. package/dist/thrift-backend/ThriftSessionBackend.d.ts +36 -0
  108. package/dist/thrift-backend/ThriftSessionBackend.js +266 -0
  109. package/dist/thrift-backend/ThriftSessionBackend.js.map +1 -0
  110. package/dist/thrift-backend/wireSynthesis.d.ts +30 -0
  111. package/dist/thrift-backend/wireSynthesis.js +128 -0
  112. package/dist/thrift-backend/wireSynthesis.js.map +1 -0
  113. package/dist/version.d.ts +1 -1
  114. package/dist/version.js +1 -1
  115. package/dist/version.js.map +1 -1
  116. package/native/kernel/README.md +97 -0
  117. package/native/kernel/index.d.ts +1069 -0
  118. package/native/kernel/index.js +325 -0
  119. package/package.json +13 -2
@@ -0,0 +1,640 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Databricks, Inc.
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ var desc = Object.getOwnPropertyDescriptor(m, k);
18
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
19
+ desc = { enumerable: true, get: function() { return m[k]; } };
20
+ }
21
+ Object.defineProperty(o, k2, desc);
22
+ }) : (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ o[k2] = m[k];
25
+ }));
26
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
27
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
28
+ }) : function(o, v) {
29
+ o["default"] = v;
30
+ });
31
+ var __importStar = (this && this.__importStar) || function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ /**
43
+ * `IOperationBackend` implementation for the kernel path.
44
+ *
45
+ * Combines:
46
+ * - **Fetch pipeline (from kernel-results):**
47
+ * `napi.Statement.fetchNextBatch()` → `KernelResultsProvider` →
48
+ * `ArrowResultConverter` (Phase 1 + Phase 2; reused unchanged) →
49
+ * `ResultSlicer` (chunk-size normalisation; reused unchanged). The M0
50
+ * row shape is byte-identical to the thrift path for every M0
51
+ * datatype (parity gate exercised by `tests/e2e/kernel/results-e2e.test.ts`).
52
+ *
53
+ * - **Lifecycle (from kernel-operation):** `cancel()` / `close()` /
54
+ * `finished()` (alias of `waitUntilReady`) delegate to the helpers
55
+ * in `KernelOperationLifecycle.ts`. The helpers handle idempotency,
56
+ * flag-set-before-await ordering (so cancel-mid-fetch propagates),
57
+ * logging via `IClientContext`, and kernel-error mapping.
58
+ *
59
+ * The lifecycle helpers route fetch-after-cancel / fetch-after-close
60
+ * through `failIfNotActive`, which throws an `OperationStateError`
61
+ * matching the Thrift `failIfClosed` semantics. We call it from
62
+ * `fetchChunk`/`hasMore`/`getResultMetadata` so the cancel-mid-fetch
63
+ * e2e (cancel < 200ms) drives against this backend cleanly.
64
+ */
65
+ const uuid_1 = require("uuid");
66
+ const OperationStatus_1 = require("../contracts/OperationStatus");
67
+ const ResultMetadata_1 = require("../contracts/ResultMetadata");
68
+ const IDBSQLLogger_1 = require("../contracts/IDBSQLLogger");
69
+ const HiveDriverError_1 = __importDefault(require("../errors/HiveDriverError"));
70
+ const OperationStateError_1 = __importStar(require("../errors/OperationStateError"));
71
+ const ArrowResultConverter_1 = __importDefault(require("../result/ArrowResultConverter"));
72
+ const ResultSlicer_1 = __importDefault(require("../result/ResultSlicer"));
73
+ const KernelResultsProvider_1 = __importDefault(require("./KernelResultsProvider"));
74
+ const KernelArrowIpc_1 = require("./KernelArrowIpc");
75
+ const KernelErrorMapping_1 = require("./KernelErrorMapping");
76
+ const KernelOperationLifecycle_1 = require("./KernelOperationLifecycle");
77
+ /** Poll cadence for the async `status()` loop — matches the Thrift backend's 100ms. */
78
+ const STATUS_POLL_INTERVAL_MS = 100;
79
+ function delay(ms) {
80
+ return new Promise((resolve) => {
81
+ setTimeout(resolve, ms);
82
+ });
83
+ }
84
+ /**
85
+ * Map a kernel `AsyncStatement.status()` string to the backend-neutral
86
+ * `OperationState`. The kernel variant names (`Pending` / `Running` /
87
+ * `Succeeded` / `Failed` / `Cancelled` / `Closed` / `Unknown`) line up 1:1
88
+ * with the enum; `Canceled` (one-L spelling) is mapped defensively, and any
89
+ * unrecognised value collapses to `Unknown`.
90
+ */
91
+ // Hoisted out of the (hot, 100ms) async poll loop — `Object.values` would
92
+ // otherwise allocate a fresh array on every status tick.
93
+ const OPERATION_STATE_VALUES = Object.values(OperationStatus_1.OperationState);
94
+ function statusStringToOperationState(state) {
95
+ if (state === 'Canceled') {
96
+ return OperationStatus_1.OperationState.Cancelled;
97
+ }
98
+ if (OPERATION_STATE_VALUES.includes(state)) {
99
+ return state;
100
+ }
101
+ return OperationStatus_1.OperationState.Unknown;
102
+ }
103
+ class KernelOperationBackend {
104
+ constructor({ asyncStatement, statement, cancellableExecution, context, id }) {
105
+ var _a, _b, _c;
106
+ this.lifecycle = (0, KernelOperationLifecycle_1.createLifecycleState)();
107
+ // Exactly one of the three handle kinds must be supplied.
108
+ const providedCount = (asyncStatement !== undefined ? 1 : 0) +
109
+ (statement !== undefined ? 1 : 0) +
110
+ (cancellableExecution !== undefined ? 1 : 0);
111
+ if (providedCount !== 1) {
112
+ throw new HiveDriverError_1.default('KernelOperationBackend: exactly one of `asyncStatement`, `statement`, or `cancellableExecution` must be provided');
113
+ }
114
+ this.asyncStatement = asyncStatement;
115
+ this.cancellableExecution = cancellableExecution;
116
+ this.blockingStatement = statement;
117
+ // Lifecycle surface. The async/metadata handles expose both cancel/close.
118
+ // The sync-execute path uses a composite: `cancel()` always routes to the
119
+ // cancellable execution (lock-free, interrupts a running `result()`
120
+ // mid-compute and is a no-op once terminal); `close()` closes the resolved
121
+ // terminal statement once `result()` produced it, OR — if `result()` is
122
+ // still in flight — proactively cancels the running execution so the server
123
+ // stops computing immediately rather than running on until the kernel's
124
+ // drop-guard fires whenever this handle is eventually GC'd.
125
+ this.lifecycleHandle = cancellableExecution
126
+ ? {
127
+ cancel: () => cancellableExecution.cancel(),
128
+ close: () => (this.blockingStatement ? this.blockingStatement.close() : cancellableExecution.cancel()),
129
+ }
130
+ : (asyncStatement !== null && asyncStatement !== void 0 ? asyncStatement : statement);
131
+ this.context = context;
132
+ this._id =
133
+ (_c = (_b = (_a = id !== null && id !== void 0 ? id : asyncStatement === null || asyncStatement === void 0 ? void 0 : asyncStatement.statementId) !== null && _a !== void 0 ? _a : statement === null || statement === void 0 ? void 0 : statement.statementId) !== null && _b !== void 0 ? _b : cancellableExecution === null || cancellableExecution === void 0 ? void 0 : cancellableExecution.statementId) !== null && _c !== void 0 ? _c : (0, uuid_1.v4)();
134
+ }
135
+ get id() {
136
+ // STABLE for the operation's lifetime. The facade keys telemetry start/
137
+ // complete on this value (DBSQLOperation → MetricsAggregator), so it must
138
+ // NOT mutate — a sync op's server statement_id isn't known until `result()`
139
+ // resolves (mid-execute), and flipping `id` then would split the start/
140
+ // complete records across two keys and silently drop the summary. The
141
+ // resolved server statement_id is instead surfaced via a debug log (see
142
+ // `getFetchHandle`) for server/kernel log correlation. On the async path
143
+ // `_id` already IS the server id (available at submit).
144
+ return this._id;
145
+ }
146
+ hasResultSet() {
147
+ // M0 only routes through KernelOperationBackend for executeStatement
148
+ // calls. DDL/DML without a result set is not exercised through kernel
149
+ // for M0; the napi Statement still produces a schema (empty) in
150
+ // that case, which the converter renders as zero rows. Reporting
151
+ // `true` keeps the facade's fetch path enabled for M0 parity.
152
+ return true;
153
+ }
154
+ // ---------------------------------------------------------------------------
155
+ // Fetch / metadata (owned by the kernel-results pipeline).
156
+ // ---------------------------------------------------------------------------
157
+ async fetchChunk({ limit, disableBuffering, isClosed, }) {
158
+ // Cancel-mid-fetch propagation: if cancel() has flipped the
159
+ // lifecycle flag, fail locally without a wire round-trip.
160
+ (0, KernelOperationLifecycle_1.failIfNotActive)(this.lifecycle);
161
+ // Cooperative cancel (parity with ThriftOperationBackend): the facade
162
+ // supplies `isClosed` and re-checks `failIfClosed()` after we return, so
163
+ // bailing with `[]` at a yield point is the contract-correct way for a
164
+ // concurrent cancel()/close() to interrupt the fetch.
165
+ if (isClosed === null || isClosed === void 0 ? void 0 : isClosed()) {
166
+ return [];
167
+ }
168
+ try {
169
+ const slicer = await this.getResultSlicer();
170
+ if (isClosed === null || isClosed === void 0 ? void 0 : isClosed()) {
171
+ return [];
172
+ }
173
+ return await slicer.fetchNext({ limit, disableBuffering });
174
+ }
175
+ catch (err) {
176
+ // The napi fetch contract leaves the stream in an unspecified state on
177
+ // error ("call close() and discard"). Close the statement so the server
178
+ // reclaims it promptly — best-effort, so a close failure never masks the
179
+ // original fetch error — then surface a typed kernel error.
180
+ //
181
+ // If close() ALSO fails, kernelClose has reset isClosed back to false and
182
+ // the kernel-side statement handle is now leaked (the stream is already
183
+ // wedged, so nothing downstream forces another close). We still don't
184
+ // mask the original fetch error, but log the close failure at warn so
185
+ // the leak is diagnosable rather than completely invisible.
186
+ await (0, KernelOperationLifecycle_1.kernelClose)(this.lifecycle, this.lifecycleHandle, this.context, this._id).catch((closeErr) => {
187
+ const cause = closeErr instanceof Error ? closeErr.message : String(closeErr);
188
+ this.context
189
+ .getLogger()
190
+ .log(IDBSQLLogger_1.LogLevel.warn, `kernel fetch-error cleanup: close() failed for operation ${this._id}; the server-side ` +
191
+ `statement may leak until the session is closed. Cause: ${cause}`);
192
+ });
193
+ throw (0, KernelErrorMapping_1.decodeNapiKernelError)(err);
194
+ }
195
+ }
196
+ async hasMore() {
197
+ (0, KernelOperationLifecycle_1.failIfNotActive)(this.lifecycle);
198
+ const slicer = await this.getResultSlicer();
199
+ return slicer.hasMore();
200
+ }
201
+ async getResultMetadata() {
202
+ (0, KernelOperationLifecycle_1.failIfNotActive)(this.lifecycle);
203
+ if (this.metadata) {
204
+ return this.metadata;
205
+ }
206
+ if (this.metadataPromise) {
207
+ return this.metadataPromise;
208
+ }
209
+ this.metadataPromise = (async () => {
210
+ // The schema lives on the fetch handle: the metadata `Statement`
211
+ // directly, or the async path's `AsyncResultHandle` (materialised by
212
+ // `getFetchHandle()` once the statement is terminal).
213
+ const handle = await this.getFetchHandle();
214
+ if (!handle.schema) {
215
+ throw new HiveDriverError_1.default('KernelOperationBackend: schema() is not available on this handle');
216
+ }
217
+ // `schema()` is a synchronous napi getter (returns `ArrowSchema`, not a
218
+ // Promise) — no `await` needed.
219
+ const arrowSchemaIpc = handle.schema();
220
+ const arrowSchema = (0, KernelArrowIpc_1.decodeIpcSchema)(arrowSchemaIpc.ipcBytes);
221
+ // `ResultMetadata.schema` keeps the Thrift `TTableSchema` shape for
222
+ // back-compat with the public `IOperation.getSchema()` surface.
223
+ const thriftSchema = (0, KernelArrowIpc_1.arrowSchemaToThriftSchema)(arrowSchema);
224
+ const meta = {
225
+ schema: thriftSchema,
226
+ // kernel inline + CloudFetch both surface to JS as Arrow batches;
227
+ // both flow through the same Arrow result converter.
228
+ resultFormat: ResultMetadata_1.ResultFormat.ArrowBased,
229
+ lz4Compressed: false,
230
+ // Carry the *patched* Arrow IPC schema bytes (Duration → Int64 with the
231
+ // `duration_unit` marker) so an ARROW_BASED consumer decoding
232
+ // `arrowSchema` doesn't hit apache-arrow@13's `Unrecognized type
233
+ // "Duration" (18)`. Matches what the per-batch fetch path already does.
234
+ arrowSchema: (0, KernelArrowIpc_1.patchIpcBytes)(arrowSchemaIpc.ipcBytes),
235
+ isStagingOperation: false,
236
+ };
237
+ this.metadata = meta;
238
+ return meta;
239
+ })();
240
+ try {
241
+ return await this.metadataPromise;
242
+ }
243
+ finally {
244
+ this.metadataPromise = undefined;
245
+ }
246
+ }
247
+ // ---------------------------------------------------------------------------
248
+ // Status / lifecycle (owned by the kernel-operation lifecycle helpers).
249
+ // ---------------------------------------------------------------------------
250
+ async status(_progress) {
251
+ // A client-side cancel/close wins over any server state.
252
+ if (this.lifecycle.isCancelled) {
253
+ return { state: OperationStatus_1.OperationState.Cancelled, hasResultSet: true };
254
+ }
255
+ if (this.lifecycle.isClosed) {
256
+ return { state: OperationStatus_1.OperationState.Closed, hasResultSet: true };
257
+ }
258
+ if (this.asyncStatement) {
259
+ // Async query path: report the real kernel state (single
260
+ // GetStatementStatus RPC — no polling here; `waitUntilReady` owns the
261
+ // poll loop). On a terminal Succeeded state, that same GetStatement poll
262
+ // carried the rich status fields (the kernel derives a DML's
263
+ // `numModifiedRows` from the inline count on the terminal response), so
264
+ // surface them — mirroring the sync path. Reading them does not fetch the
265
+ // result.
266
+ const state = statusStringToOperationState(await this.asyncStatement.status());
267
+ if (state === OperationStatus_1.OperationState.Succeeded) {
268
+ return { state, hasResultSet: true, ...(await this.readRichStatusFields()) };
269
+ }
270
+ return { state, hasResultSet: true };
271
+ }
272
+ if (this.cancellableExecution) {
273
+ // Sync (`runAsync: false`) path: the kernel `execute()` blocks and polls
274
+ // server-side; there is no per-status RPC to query while it runs. Report
275
+ // Running until `result()` has materialised the terminal statement, then
276
+ // Succeeded — mirroring the kernel's blocking-then-terminal lifecycle.
277
+ //
278
+ // Gate on `blockingStatement`, NOT on `fetchHandlePromise`: the latter is
279
+ // assigned synchronously when `getFetchHandle()` is first called (e.g. by
280
+ // a concurrent fetch or `waitUntilReady`), while `result()` may still be
281
+ // pending — `blockingStatement` is only set inside the resolve handler.
282
+ // Using the promise's *existence* as a completion proxy would make a
283
+ // concurrent `status()` poll both report Succeeded early AND block on the
284
+ // pending `result()` via `readRichStatusFields()`.
285
+ if (!this.blockingStatement) {
286
+ return { state: OperationStatus_1.OperationState.Running, hasResultSet: true };
287
+ }
288
+ // The blocking `result()` has resolved a terminal `Statement` — surface
289
+ // its rich status fields alongside the Succeeded state.
290
+ return { state: OperationStatus_1.OperationState.Succeeded, hasResultSet: true, ...(await this.readRichStatusFields()) };
291
+ }
292
+ // Metadata path: the kernel statement is already terminal — read its rich
293
+ // fields too (they are `null` for metadata results, by design).
294
+ return { state: OperationStatus_1.OperationState.Succeeded, hasResultSet: true, ...(await this.readRichStatusFields()) };
295
+ }
296
+ async waitUntilReady(options) {
297
+ if (this.asyncStatement) {
298
+ return this.waitUntilReadyAsync(options);
299
+ }
300
+ if (this.cancellableExecution) {
301
+ return this.waitUntilReadyCancellable(options);
302
+ }
303
+ // Metadata path: the kernel statement has already resolved, so there is
304
+ // nothing to poll. kernelFinished fires the progress callback once with a
305
+ // synthesised completion tick, matching the Thrift path's final tick. The
306
+ // rich-field reader is passed lazily so it only runs when a callback is
307
+ // wired (metadata statements report all-null, but the surface stays
308
+ // consistent with the query paths).
309
+ return (0, KernelOperationLifecycle_1.kernelFinished)(this.lifecycle, options, () => this.readRichStatusFields());
310
+ }
311
+ async cancel() {
312
+ return (0, KernelOperationLifecycle_1.kernelCancel)(this.lifecycle, this.lifecycleHandle, this.context, this._id);
313
+ }
314
+ async close() {
315
+ return (0, KernelOperationLifecycle_1.kernelClose)(this.lifecycle, this.lifecycleHandle, this.context, this._id);
316
+ }
317
+ // ---------------------------------------------------------------------------
318
+ // Internals.
319
+ // ---------------------------------------------------------------------------
320
+ /**
321
+ * Read the kernel's rich operation-status fields (`numModifiedRows` /
322
+ * `displayMessage` / `diagnosticInfo` / `errorDetailsJson`) off the terminal
323
+ * sync `Statement`. These accessors live only on the blocking `Statement`
324
+ * (metadata path, or the sync `runAsync:false` path once `result()` has
325
+ * resolved) — not on the async `AsyncStatement` / `AsyncResultHandle` — so:
326
+ *
327
+ * - on the async path we have no `Statement`, so we return all-null;
328
+ * - on the sync path we await `getFetchHandle()` first, which both drives
329
+ * `result()` to completion and stores the resolved `Statement` on
330
+ * `blockingStatement` (the handle that backs the accessors);
331
+ * - if the (older) binding predates these accessors we degrade to all-null
332
+ * rather than throwing — `getOperationStatus()` must never fail just
333
+ * because the rich fields are unavailable.
334
+ *
335
+ * Errors from the individual accessors are swallowed to null: a failed
336
+ * status-field read must not turn a successful operation's status query into
337
+ * a throw. The fields are best-effort metadata, not the operation outcome.
338
+ */
339
+ readRichStatusFields() {
340
+ if (!this.richStatusFieldsPromise) {
341
+ this.richStatusFieldsPromise = this.computeRichStatusFields();
342
+ }
343
+ return this.richStatusFieldsPromise;
344
+ }
345
+ async computeRichStatusFields() {
346
+ const empty = {
347
+ numModifiedRows: null,
348
+ displayMessage: null,
349
+ diagnosticInfo: null,
350
+ errorDetailsJson: null,
351
+ };
352
+ // Async (submit/poll) path: a DML's `numModifiedRows` rides in the result
353
+ // set, which kernel delivers on the terminal `GetStatement` poll. The kernel
354
+ // derives it off that poll (no extra fetch) and exposes it on the
355
+ // `AsyncStatement`'s status accessors — so read them directly. The value is
356
+ // populated once the statement has reached a terminal state via
357
+ // `status()` / `waitUntilReady` (which polled it); it stays null before
358
+ // that and for SELECTs. Reading does NOT force a result materialisation, so
359
+ // async streaming is untouched.
360
+ if (this.asyncStatement) {
361
+ return this.readStatusFieldsFrom(this.asyncStatement);
362
+ }
363
+ // Ensure the sync path's blocking `result()` has resolved and stored the
364
+ // terminal `Statement` on `blockingStatement` (no-op on the metadata path,
365
+ // where `blockingStatement` was set at construction).
366
+ if (this.cancellableExecution) {
367
+ try {
368
+ await this.getFetchHandle();
369
+ }
370
+ catch (_a) {
371
+ // The operation failed/cancelled — its outcome surfaces through the
372
+ // wait/fetch path; status-field reads have nothing to add.
373
+ return empty;
374
+ }
375
+ }
376
+ return this.readStatusFieldsFrom(this.blockingStatement);
377
+ }
378
+ /**
379
+ * Read the four rich-status accessors (`numModifiedRows` / `displayMessage` /
380
+ * `diagnosticInfo` / `errorDetailsJson`) off a kernel handle — the terminal
381
+ * sync `Statement` or the async `AsyncStatement`, which expose the same
382
+ * accessor shape. Per-field read errors are swallowed to `null`: a failed
383
+ * status-field read must never turn a successful operation's status query
384
+ * into a throw. Degrades to all-null for a missing handle or a binding that
385
+ * predates the accessors.
386
+ */
387
+ async readStatusFieldsFrom(handle) {
388
+ const empty = {
389
+ numModifiedRows: null,
390
+ displayMessage: null,
391
+ diagnosticInfo: null,
392
+ errorDetailsJson: null,
393
+ };
394
+ const candidate = handle;
395
+ if (!candidate || typeof candidate.numModifiedRows !== 'function') {
396
+ return empty;
397
+ }
398
+ const richHandle = candidate;
399
+ const readOrNull = async (read) => {
400
+ try {
401
+ return await read();
402
+ }
403
+ catch (err) {
404
+ this.context
405
+ .getLogger()
406
+ .log(IDBSQLLogger_1.LogLevel.debug, `kernel status-field read failed for operation ${this._id}; reporting null. Cause: ` +
407
+ `${err instanceof Error ? err.message : String(err)}`);
408
+ return null;
409
+ }
410
+ };
411
+ const [numModifiedRows, displayMessage, diagnosticInfo, errorDetailsJson] = await Promise.all([
412
+ readOrNull(() => richHandle.numModifiedRows()),
413
+ readOrNull(() => richHandle.displayMessage()),
414
+ readOrNull(() => richHandle.diagnosticInfo()),
415
+ readOrNull(() => richHandle.errorDetailsJson()),
416
+ ]);
417
+ return { numModifiedRows, displayMessage, diagnosticInfo, errorDetailsJson };
418
+ }
419
+ /**
420
+ * Poll the kernel `AsyncStatement` to a terminal state on a fixed 100ms
421
+ * cadence, mirroring the Thrift backend's `waitUntilReady` loop. We poll
422
+ * `status()` (a cheap GetStatementStatus RPC) rather than awaiting
423
+ * `awaitResult()` directly so that `status()` reports the real
424
+ * Pending/Running/Succeeded state to a progress callback each tick, and so a
425
+ * JS-initiated `cancel()`/`close()` is observed between ticks via
426
+ * `failIfNotActive`. On success it materialises the result handle (so the
427
+ * first fetch is free); on a server-driven terminal state it throws the typed
428
+ * error the `IOperationBackend` contract requires.
429
+ *
430
+ * Terminal errors are thrown as `OperationStateError` (NOT plain
431
+ * `HiveDriverError`) for Cancelled/Closed/Unknown, because the DBSQLOperation
432
+ * facade only mirrors its `cancelled`/`closed` flags when
433
+ * `err instanceof OperationStateError` — exactly as the Thrift backend does.
434
+ * The Failed branch surfaces the kernel's typed SQL-error envelope via
435
+ * `awaitResult()`.
436
+ */
437
+ async waitUntilReadyAsync(options) {
438
+ // Already materialised → terminal-and-ready, nothing to wait for.
439
+ if (this.fetchHandlePromise) {
440
+ return;
441
+ }
442
+ for (;;) {
443
+ // A JS-initiated cancel/close short-circuits before the next poll.
444
+ (0, KernelOperationLifecycle_1.failIfNotActive)(this.lifecycle);
445
+ // eslint-disable-next-line no-await-in-loop
446
+ const state = statusStringToOperationState(await this.asyncStatement.status());
447
+ if (options === null || options === void 0 ? void 0 : options.callback) {
448
+ // On the terminal Succeeded tick, carry the rich status fields
449
+ // (numModifiedRows / displayMessage / diagnosticInfo / errorDetailsJson)
450
+ // so the async path's progress callback matches the sync path
451
+ // (`waitUntilReadyCancellable`). The kernel has populated the
452
+ // AsyncStatement's accessors off the just-completed terminal poll, and
453
+ // the read is memoised + does not force result materialisation.
454
+ // eslint-disable-next-line no-await-in-loop
455
+ const richFields = state === OperationStatus_1.OperationState.Succeeded ? await this.readRichStatusFields() : {};
456
+ // eslint-disable-next-line no-await-in-loop
457
+ await Promise.resolve(options.callback({ state, hasResultSet: true, ...richFields }));
458
+ }
459
+ switch (state) {
460
+ case OperationStatus_1.OperationState.Pending:
461
+ case OperationStatus_1.OperationState.Running:
462
+ break;
463
+ case OperationStatus_1.OperationState.Succeeded:
464
+ // Materialise the result stream now so the first fetch/metadata call
465
+ // doesn't pay an extra await_result round-trip.
466
+ // eslint-disable-next-line no-await-in-loop
467
+ await this.getFetchHandle();
468
+ return;
469
+ case OperationStatus_1.OperationState.Failed:
470
+ // `status()` collapses Failed to the variant name only; the real
471
+ // SQL-error envelope (sql_state / error_code / query_id) rides on
472
+ // `awaitResult()`'s rejection — drive it to surface the typed error,
473
+ // then best-effort close the leaked statement before it propagates.
474
+ try {
475
+ // eslint-disable-next-line no-await-in-loop
476
+ await this.throwAsyncError();
477
+ }
478
+ catch (failErr) {
479
+ // eslint-disable-next-line no-await-in-loop
480
+ await this.bestEffortClose();
481
+ throw failErr;
482
+ }
483
+ break;
484
+ case OperationStatus_1.OperationState.Cancelled:
485
+ // eslint-disable-next-line no-await-in-loop
486
+ await this.bestEffortClose();
487
+ throw new OperationStateError_1.default(OperationStateError_1.OperationStateErrorCode.Canceled);
488
+ case OperationStatus_1.OperationState.Closed:
489
+ // eslint-disable-next-line no-await-in-loop
490
+ await this.bestEffortClose();
491
+ throw new OperationStateError_1.default(OperationStateError_1.OperationStateErrorCode.Closed);
492
+ default:
493
+ // eslint-disable-next-line no-await-in-loop
494
+ await this.bestEffortClose();
495
+ throw new OperationStateError_1.default(OperationStateError_1.OperationStateErrorCode.Unknown);
496
+ }
497
+ // Still Pending/Running — sleep before the next poll. (There is no
498
+ // client-side query-timeout deadline: `queryTimeout` is a no-op on kernel.)
499
+ // eslint-disable-next-line no-await-in-loop
500
+ await delay(STATUS_POLL_INTERVAL_MS);
501
+ }
502
+ }
503
+ /**
504
+ * Sync (`runAsync: false`) execute path. Drives the blocking
505
+ * `CancellableExecution.result()` to a terminal `Statement` (the kernel polls
506
+ * to completion server-side). The
507
+ * await is interruptible: a JS-initiated `cancel()` fires the detached
508
+ * canceller, the server flips the statement terminal, and the parked
509
+ * `result()` rejects with `Cancelled` — which we map to the typed
510
+ * `OperationStateError(Canceled)`.
511
+ *
512
+ * Unlike the async path there is no status poll loop (the kernel owns
513
+ * polling), so the progress callback fires once on completion, matching the
514
+ * metadata path's single completion tick.
515
+ */
516
+ async waitUntilReadyCancellable(options) {
517
+ // Already materialised → terminal-and-ready, nothing to wait for.
518
+ if (this.fetchHandlePromise) {
519
+ return;
520
+ }
521
+ // A JS-initiated cancel/close before we start short-circuits to the typed
522
+ // state error rather than dispatching the blocking execute.
523
+ (0, KernelOperationLifecycle_1.failIfNotActive)(this.lifecycle);
524
+ // `getFetchHandle()` drives `result()` and memoises the resolved Statement
525
+ // (also stored on `blockingStatement` so `close()` can reach it).
526
+ await this.getFetchHandle();
527
+ // Single completion tick, matching the metadata path — carrying the rich
528
+ // status fields (numModifiedRows etc.) read off the now-terminal Statement.
529
+ if (options === null || options === void 0 ? void 0 : options.callback) {
530
+ const richFields = await this.readRichStatusFields();
531
+ await Promise.resolve(options.callback({ state: OperationStatus_1.OperationState.Succeeded, hasResultSet: true, ...richFields }));
532
+ }
533
+ }
534
+ /**
535
+ * Drive `awaitResult()` on a Failed statement to surface the kernel's typed
536
+ * SQL-error envelope. Falls back to a generic error if `awaitResult()`
537
+ * unexpectedly resolves instead of rejecting.
538
+ */
539
+ async throwAsyncError() {
540
+ try {
541
+ await this.asyncStatement.awaitResult();
542
+ }
543
+ catch (err) {
544
+ throw (0, KernelErrorMapping_1.decodeNapiKernelError)(err);
545
+ }
546
+ throw new HiveDriverError_1.default(`kernel operation ${this._id} reported Failed but produced a result.`);
547
+ }
548
+ /**
549
+ * Best-effort close of the kernel statement when the poll loop ends on a
550
+ * server-driven terminal error (Failed/Cancelled/Closed/Unknown/Timeout).
551
+ * Without it the kernel-side statement handle leaks until session close (the
552
+ * poll loop, unlike `fetchChunk`, otherwise just throws). Never masks the
553
+ * original error; warn-logs a close failure so the leak is diagnosable.
554
+ */
555
+ async bestEffortClose() {
556
+ await (0, KernelOperationLifecycle_1.kernelClose)(this.lifecycle, this.lifecycleHandle, this.context, this._id).catch((closeErr) => {
557
+ const cause = closeErr instanceof Error ? closeErr.message : String(closeErr);
558
+ this.context
559
+ .getLogger()
560
+ .log(IDBSQLLogger_1.LogLevel.warn, `kernel poll-loop cleanup: close() failed for operation ${this._id}; the server-side ` +
561
+ `statement may leak until the session is closed. Cause: ${cause}`);
562
+ });
563
+ }
564
+ /**
565
+ * Resolve (and memoise) the fetch handle: `awaitResult()`'s `AsyncResultHandle`
566
+ * on the query path, or the already-terminal `Statement` on the metadata path.
567
+ */
568
+ getFetchHandle() {
569
+ if (!this.fetchHandlePromise) {
570
+ if (this.asyncStatement) {
571
+ this.fetchHandlePromise = this.asyncStatement.awaitResult().catch((err) => {
572
+ throw (0, KernelErrorMapping_1.decodeNapiKernelError)(err);
573
+ });
574
+ }
575
+ else if (this.cancellableExecution) {
576
+ // Sync (`runAsync: false`) path: drive the blocking `result()` to the
577
+ // terminal `Statement`. Store it on `blockingStatement` so `close()` can
578
+ // reach it post-execute, and so a subsequent fetch uses it directly.
579
+ this.fetchHandlePromise = this.cancellableExecution
580
+ .result()
581
+ .then((stmt) => {
582
+ this.blockingStatement = stmt;
583
+ // Log the now-known server statement id (NOT surfaced via `id`,
584
+ // which must stay stable for telemetry correlation) so a sync op is
585
+ // correlatable to server/kernel logs by its client operation id.
586
+ const serverId = this.blockingStatement.statementId;
587
+ if (serverId && serverId !== this._id) {
588
+ this.context
589
+ .getLogger()
590
+ .log(IDBSQLLogger_1.LogLevel.debug, `kernel operation ${this._id} resolved to server statement_id ${serverId}`);
591
+ }
592
+ return stmt;
593
+ })
594
+ .catch((err) => {
595
+ const mapped = (0, KernelErrorMapping_1.decodeNapiKernelError)(err);
596
+ // A cancel-induced rejection surfaces as the kernel's Cancelled
597
+ // error; map it to the typed `OperationStateError(Canceled)` so the
598
+ // `DBSQLOperation` facade mirrors its cancelled flag (it only does so
599
+ // for `OperationStateError`), matching the Thrift path. If the
600
+ // operation was cancelled client-side, prefer the typed code
601
+ // regardless of the kernel error text.
602
+ if (this.lifecycle.isCancelled) {
603
+ throw new OperationStateError_1.default(OperationStateError_1.OperationStateErrorCode.Canceled);
604
+ }
605
+ throw mapped;
606
+ });
607
+ }
608
+ else {
609
+ const stmt = this.blockingStatement;
610
+ if (!stmt.fetchNextBatch) {
611
+ throw new HiveDriverError_1.default('KernelOperationBackend: statement.fetchNextBatch() is not available on this handle');
612
+ }
613
+ this.fetchHandlePromise = Promise.resolve(stmt);
614
+ }
615
+ }
616
+ return this.fetchHandlePromise;
617
+ }
618
+ async getResultSlicer() {
619
+ var _a;
620
+ if (this.resultSlicer) {
621
+ return this.resultSlicer;
622
+ }
623
+ const metadata = await this.getResultMetadata();
624
+ const handle = await this.getFetchHandle();
625
+ // KernelResultsProvider consumes only `fetchNextBatch`; both the async result
626
+ // handle and the blocking statement satisfy that surface.
627
+ this.resultsProvider = new KernelResultsProvider_1.default(handle);
628
+ // DECIMAL/BIGINT precision preservation is opt-in via the
629
+ // `preserveBigNumericPrecision` connection option (default off). The kernel
630
+ // always delivers native Arrow Decimal128 / Int64, so when enabled the
631
+ // converter renders DECIMAL as an exact string and BIGINT as a `bigint`.
632
+ const converter = new ArrowResultConverter_1.default(this.context, this.resultsProvider, metadata, {
633
+ preserveBigNumericPrecision: (_a = this.context.getConfig().preserveBigNumericPrecision) !== null && _a !== void 0 ? _a : false,
634
+ });
635
+ this.resultSlicer = new ResultSlicer_1.default(this.context, converter);
636
+ return this.resultSlicer;
637
+ }
638
+ }
639
+ exports.default = KernelOperationBackend;
640
+ //# sourceMappingURL=KernelOperationBackend.js.map