@databricks/sql 1.15.0 → 1.16.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.
Files changed (118) 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/native/kernel/README.md +97 -0
  116. package/native/kernel/index.d.ts +1069 -0
  117. package/native/kernel/index.js +325 -0
  118. package/package.json +13 -2
@@ -0,0 +1,1069 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /* auto-generated by NAPI-RS */
5
+
6
+ /**
7
+ * Per-statement options for `Connection.executeStatement`.
8
+ *
9
+ * Mirrors the kernel `StatementSpec` knobs that are safe to thread
10
+ * through napi without a kernel-side change. Today this covers:
11
+ * - `statementConf` — per-statement Spark conf overlay
12
+ * (`StatementSpec.statement_conf` → SEA `parameters` /
13
+ * Thrift `confOverlay`)
14
+ * - `queryTags` — convenience wrapper over `statementConf` with
15
+ * key `query_tags`; serialised to the same comma-separated
16
+ * `key:value` wire shape NodeJS Thrift's `serializeQueryTags`
17
+ * produces (`lib/utils/queryTags.ts`). Backslashes in keys are
18
+ * doubled; backslash/colon/comma in values are backslash-escaped.
19
+ *
20
+ * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel
21
+ * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`)
22
+ * carry bound query parameters, decoded via `params::parse_typed_value`.
23
+ * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold
24
+ * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.)
25
+ *
26
+ * **Tag-order caveat (M4 parity note).** The napi `queryTags` field
27
+ * is a Rust `HashMap<String, String>` whose iteration order is
28
+ * non-deterministic, so the serialised `query_tags` value may have
29
+ * a different key order than Thrift's `serializeQueryTags` (which
30
+ * iterates `Object.keys(...)` in insertion order) for the same
31
+ * input. The SEA server is order-insensitive on conf values, so
32
+ * the two are functionally equivalent. If a caller needs
33
+ * byte-identical Thrift parity, the JS adapter pre-serialises via
34
+ * `serializeQueryTags` and writes the result into
35
+ * `statementConf["query_tags"]` directly — see
36
+ * `KernelSessionBackend.executeStatement` in the NodeJS driver. This
37
+ * path is the one the production code uses.
38
+ */
39
+ export interface ExecuteOptions {
40
+ /**
41
+ * Per-statement Spark conf overlay. Merged on top of the
42
+ * session-level `sessionConf` at execute time; this map wins
43
+ * on key collisions. Unknown keys are rejected by the server.
44
+ */
45
+ statementConf?: Record<string, string>
46
+ /**
47
+ * Query tags as key→value pairs. Serialised to a comma-
48
+ * separated `key:value` string (backslash-escaping `\`, `:`,
49
+ * `,`) and placed into `statementConf["query_tags"]`, matching
50
+ * NodeJS Thrift's `serializeQueryTags` wire shape. Passing
51
+ * both `queryTags` AND a `query_tags` key in `statementConf`
52
+ * raises `InvalidArgument` — the caller's intent is ambiguous
53
+ * so we refuse to silently pick one over the other.
54
+ *
55
+ * A **`null`** value emits a **bare key** (no colon) — e.g.
56
+ * `{ production: null }` → `"production"` — matching the
57
+ * connectors' `key`-only tag form.
58
+ *
59
+ * See the struct-level "Tag-order caveat" for the
60
+ * HashMap-iteration-order vs `Object.keys`-iteration-order
61
+ * divergence and the byte-identical-Thrift-parity workaround.
62
+ */
63
+ queryTags?: Record<string, string | undefined | null>
64
+ /**
65
+ * Server-side cap on the number of rows this statement returns
66
+ * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to
67
+ * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap.
68
+ */
69
+ rowLimit?: number
70
+ /**
71
+ * Positional parameters, in 1-based wire order. Index `i` in this
72
+ * Vec corresponds to the `i+1`-th `?` placeholder in the SQL.
73
+ * Each entry is a `{ sqlType, value }` pair — `value` is the
74
+ * string-encoded literal or `null` for SQL NULL. Mirrors
75
+ * `StatementSpec::positional_params`; decoded via [`parse_typed_value`].
76
+ */
77
+ positionalParams?: Array<TypedValueInput>
78
+ /**
79
+ * Named parameters (`:name` placeholders). Each carries its `name`
80
+ * alongside the `{ sqlType, value? }` pair. Mapped to a kernel
81
+ * `TypedValue` via the same [`parse_typed_value`] codec and bound with
82
+ * `StatementSpec::param_named`. Named is the SEA-spec-required public
83
+ * param form (`StatementParameter.name` is `openapi_required`);
84
+ * positional is the documented-undocumented variant. The two are
85
+ * mutually exclusive at the SQL level (`?` vs `:name`).
86
+ */
87
+ namedParams?: Array<NamedTypedValueInput>
88
+ }
89
+ /**
90
+ * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a
91
+ * distinct napi object (rather than an optional `name` on `TypedValueInput`)
92
+ * so the positional surface stays a clean ordered list with no name field.
93
+ */
94
+ export interface NamedTypedValueInput {
95
+ name: string
96
+ sqlType: string
97
+ value?: string
98
+ }
99
+ /**
100
+ * Authentication mode selector crossing the napi boundary. The string
101
+ * literals are what napi-rs emits from this `#[napi(string_enum)]` — the
102
+ * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`,
103
+ * `'OAuthM2m'`, `'OAuthU2m'`).
104
+ *
105
+ * Mirrors the kernel [`AuthConfig`] variants this binding supports.
106
+ * `OAuthFederation` / `External` are intentionally not exposed yet — the
107
+ * kernel marks federation as not-yet-implemented and `External` is a
108
+ * Rust-trait escape hatch with no JS-callback bridge.
109
+ */
110
+ export const enum AuthMode {
111
+ /** Personal access token (`token`). */
112
+ Pat = 'Pat',
113
+ /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */
114
+ OAuthM2m = 'OAuthM2m',
115
+ /**
116
+ * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId`
117
+ * + `oauthRedirectPort`.
118
+ */
119
+ OAuthU2m = 'OAuthU2m'
120
+ }
121
+ /**
122
+ * A single extra HTTP header as an explicit `{ name, value }` pair.
123
+ *
124
+ * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors
125
+ * the kernel core's `Vec<(String, String)>` and the pyo3 binding's
126
+ * `http_headers`: order is preserved and duplicate `name`s are allowed.
127
+ * A struct (rather than a raw `[name, value]` tuple) because napi-rs
128
+ * does not marshal Rust tuples through `#[napi(object)]` fields; the
129
+ * struct is the idiomatic, self-documenting equivalent and maps to a JS
130
+ * `{ name: string, value: string }`.
131
+ */
132
+ export interface HeaderEntry {
133
+ name: string
134
+ value: string
135
+ }
136
+ /**
137
+ * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's
138
+ * internal [`ProxyConfig`]. Supplied as a structured object rather than a
139
+ * flattened URL so credentials never have to be percent-encoded into the URL
140
+ * and the bypass-host list can be expressed.
141
+ *
142
+ * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must
143
+ * use the `http://` or `https://` scheme.
144
+ * - `username` / `password` — optional proxy basic-auth, applied via
145
+ * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL).
146
+ * - `bypassHosts` — optional comma-separated host/domain list that should
147
+ * bypass the proxy (e.g. `"localhost,*.internal.corp"`).
148
+ */
149
+ export interface ProxyInput {
150
+ url: string
151
+ username?: string
152
+ password?: string
153
+ bypassHosts?: string
154
+ }
155
+ /**
156
+ * JS-visible options for opening a Databricks SQL session.
157
+ *
158
+ * Authentication is selected by `authMode` (default [`AuthMode::Pat`]):
159
+ * - `Pat` — `token` required.
160
+ * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required.
161
+ * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional
162
+ * (defaults to the `databricks-sql-connector` client on port 8020).
163
+ *
164
+ * Catalog / schema / sessionConf are applied once at session creation
165
+ * and remain in effect for every statement run on the resulting
166
+ * `Connection`. The SEA wire protocol carries them on
167
+ * `CreateSession`, not on `ExecuteStatement` — so there is no
168
+ * per-statement override path on this binding.
169
+ */
170
+ export interface ConnectionOptions {
171
+ /**
172
+ * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel
173
+ * normalises this — bare hostnames get `https://` prepended.
174
+ */
175
+ hostName: string
176
+ /**
177
+ * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The
178
+ * kernel parses out the warehouse id.
179
+ */
180
+ httpPath: string
181
+ /**
182
+ * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat:
183
+ * existing PAT callers pass only `token`).
184
+ */
185
+ authMode?: AuthMode
186
+ /**
187
+ * Personal access token. Required (and non-empty) for
188
+ * [`AuthMode::Pat`]; ignored otherwise.
189
+ */
190
+ token?: string
191
+ /**
192
+ * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for
193
+ * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`).
194
+ */
195
+ oauthClientId?: string
196
+ /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */
197
+ oauthClientSecret?: string
198
+ /**
199
+ * Localhost callback port for the [`AuthMode::OAuthU2m`] browser
200
+ * flow. Omitted ⇒ kernel default (8020).
201
+ */
202
+ oauthRedirectPort?: number
203
+ /**
204
+ * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults
205
+ * (`["all-apis"]` for M2M; `["all-apis", "offline_access"]` for U2M).
206
+ */
207
+ oauthScopes?: Array<string>
208
+ /**
209
+ * Default catalog for statements executed on this session.
210
+ * Routed through the kernel's `DefaultOpts` and onto the SEA
211
+ * `CreateSession.catalog` wire field.
212
+ */
213
+ catalog?: string
214
+ /**
215
+ * Default schema for statements executed on this session.
216
+ * Routed through the kernel's `DefaultOpts` and onto the SEA
217
+ * `CreateSession.schema` wire field.
218
+ */
219
+ schema?: string
220
+ /**
221
+ * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`,
222
+ * query-tag presets, …). Forwarded verbatim to SEA
223
+ * `session_confs`. Unknown keys are rejected server-side.
224
+ */
225
+ sessionConf?: Record<string, string>
226
+ /**
227
+ * Maximum number of pooled HTTP connections per host. Routes
228
+ * through the kernel's [`HttpConfig::pool_max_idle_per_host`].
229
+ * Tunes the underlying `reqwest` connection pool — higher values
230
+ * reduce reconnect overhead when many statements run
231
+ * concurrently against the same warehouse.
232
+ *
233
+ * When the JS caller does NOT provide `maxConnections`, the napi
234
+ * binding applies a NodeJS-driver-appropriate default of
235
+ * [`NAPI_DEFAULT_POOL_MAX_IDLE_PER_HOST`] (100) — chosen to match
236
+ * the JDBC driver's `HttpConnectionPoolSize` default and to close
237
+ * the throughput gap vs the NodeJS Thrift driver's
238
+ * `maxSockets: Infinity` pool for bursty workloads. The kernel
239
+ * core's [`HttpConfig::pool_max_idle_per_host`] default is also 100
240
+ * (matching the same JDBC default), so napi pins its own copy rather
241
+ * than inheriting it. Mirrors the Python connector's
242
+ * `max_connections` kwarg on the SEA backend, which exposes the
243
+ * knob but keeps its own urllib3-aligned default of 10.
244
+ *
245
+ * Napi-rs serialises `u32` as JS `number`; values up to
246
+ * `2^32 - 1` round-trip safely (any reasonable pool size fits).
247
+ */
248
+ maxConnections?: number
249
+ /**
250
+ * Render `INTERVAL` / `DURATION` result columns as strings
251
+ * (`ResultConfig.intervals_as_string`). The kernel default is
252
+ * native Arrow `month_interval` / `duration[us]` types; the NodeJS
253
+ * Thrift driver surfaces intervals as strings, so the SEA driver
254
+ * sets this `true` for byte-compatible parity. Omitted ⇒ kernel
255
+ * default (native Arrow interval types).
256
+ */
257
+ intervalsAsString?: boolean
258
+ /**
259
+ * Render complex (`ARRAY` / `MAP` / `STRUCT` / `VARIANT`) result
260
+ * columns as JSON strings (`ResultConfig.complex_types_as_json`)
261
+ * instead of native Arrow nested types. Omitted ⇒ kernel default
262
+ * (native Arrow nested types, which the NodeJS Arrow decoder
263
+ * already renders identically to the Thrift path).
264
+ */
265
+ complexTypesAsJson?: boolean
266
+ /**
267
+ * Whether to verify the server's TLS certificate.
268
+ *
269
+ * Omitted / `true` ⇒ strict validation against the system / Mozilla
270
+ * trust store (full chain + expiry + hostname), matching JDBC / ODBC
271
+ * and every modern HTTPS client. This is the **default** for the SEA
272
+ * backend — secure by default.
273
+ *
274
+ * `false` ⇒ permissive: accept self-signed / untrusted / expired
275
+ * certs AND skip the hostname-vs-SNI check. This is **insecure** (no
276
+ * protection against active MITM); it exists only as an opt-out for
277
+ * parity with the legacy NodeJS Thrift driver, which hard-codes
278
+ * `rejectUnauthorized: false`. Prefer pairing strict checking with
279
+ * `custom_ca_cert` over disabling verification entirely.
280
+ *
281
+ * This is the master verify toggle: `false` disables chain validation
282
+ * (`TlsConfig::accept_self_signed`) **and** subsumes the hostname
283
+ * check (`skip_hostname_verification`), regardless of
284
+ * `check_server_certificate_hostname`.
285
+ */
286
+ checkServerCertificate?: boolean
287
+ /**
288
+ * Whether to verify that the server certificate matches the host
289
+ * (hostname-vs-SNI check), **independently** of full chain validation.
290
+ *
291
+ * Omitted / `true` ⇒ the hostname check runs (the secure default).
292
+ * `false` ⇒ skip only the hostname check while still validating the
293
+ * chain + expiry against the trust store — for connecting via an IP
294
+ * literal or a host the cert wasn't issued for, without dropping all
295
+ * validation. Ignored (already implied) when
296
+ * `check_server_certificate` is `false`, which disables everything.
297
+ *
298
+ * Mirrors the Python connector's `_tls_verify_hostname` knob and the
299
+ * kernel's [`TlsConfig::skip_hostname_verification`] (= `!check`).
300
+ */
301
+ checkServerCertificateHostname?: boolean
302
+ /**
303
+ * PEM-encoded CA certificate bytes to add to the trust store on
304
+ * top of the system roots. Use for corporate TLS-inspecting
305
+ * proxies that re-sign TLS, or on-prem deployments with an
306
+ * internal CA. Honoured regardless of `check_server_certificate`.
307
+ * Maps onto the kernel [`TlsConfig::custom_ca_cert`].
308
+ */
309
+ customCaCert?: Buffer
310
+ /**
311
+ * PEM-encoded client certificate for mutual TLS (mTLS). Set this
312
+ * together with `client_key_pem` when the server requires the
313
+ * client to present a certificate. A PEM carrying a leaf cert
314
+ * optionally followed by its intermediate chain is accepted.
315
+ * Maps onto the kernel [`TlsConfig::client_cert_pem`].
316
+ *
317
+ * `client_cert_pem` and `client_key_pem` must be supplied together;
318
+ * the kernel rejects setting only one at `open_session` with
319
+ * `InvalidArgument`.
320
+ */
321
+ clientCertPem?: Buffer
322
+ /**
323
+ * PEM-encoded private key for the mTLS client certificate. Set this
324
+ * together with `client_cert_pem`. For portability across the
325
+ * kernel's TLS backends supply a PKCS#8 key (`BEGIN PRIVATE KEY`).
326
+ * Maps onto the kernel [`TlsConfig::client_key_pem`].
327
+ */
328
+ clientKeyPem?: Buffer
329
+ /**
330
+ * Extra HTTP headers to send on every request — the route for
331
+ * caller-supplied headers (the NodeJS driver's `customHeaders` and
332
+ * the composed `User-Agent`). Maps onto the kernel
333
+ * [`HttpConfig::custom_headers`].
334
+ *
335
+ * An **ordered list** of `(name, value)` pairs, mirroring the kernel
336
+ * core's `Vec<(String, String)>` and the pyo3 binding's
337
+ * `http_headers` — order is preserved and duplicate names are
338
+ * allowed (the kernel emits each entry, and for `User-Agent` folds
339
+ * the **last** one into its base UA).
340
+ *
341
+ * Three names are handled specially by the kernel:
342
+ * - `Authorization` / `x-databricks-org-id` are **reserved** — a
343
+ * caller entry for either is silently dropped (skip-and-warn) so
344
+ * auth and multi-tenant routing can't be hijacked by a custom
345
+ * header. (The NodeJS driver also drops these before they cross
346
+ * the FFI, matching the Python connector's double-wall.)
347
+ * - `User-Agent` is **appended** to the kernel base UA (rather than
348
+ * replacing it), preserving the `DatabricksJDBCDriverOSS/...`
349
+ * token the SEA server keys on while still surfacing the caller's
350
+ * identity. The NodeJS driver folds its `userAgentEntry` into a
351
+ * `User-Agent` entry here.
352
+ */
353
+ customHeaders?: Array<HeaderEntry>
354
+ /**
355
+ * Retry/backoff tuning — all optional. An unset field keeps the kernel's
356
+ * built-in policy (1s/60s exponential backoff, 6 total attempts, 900s
357
+ * budget). Mirrors the pyo3 binding's `retry_*` kwargs so the Node.js
358
+ * driver can forward the same retry knobs the Python connector does.
359
+ *
360
+ * Lower bound of the exponential backoff (also clamps a server
361
+ * `Retry-After`). Maps onto [`HttpConfig::retry_min_wait`].
362
+ */
363
+ retryMinWaitSecs?: number
364
+ /**
365
+ * Upper bound of the exponential backoff. Maps onto
366
+ * [`HttpConfig::retry_max_wait`].
367
+ */
368
+ retryMaxWaitSecs?: number
369
+ /**
370
+ * **Total** number of attempts (matching the connector's
371
+ * `_retry_stop_after_attempts_count` and JDBC count semantics). The
372
+ * kernel's [`HttpConfig::retry_max_retries`] counts retries *after* the
373
+ * first attempt, so this is converted with `max(0, attempts - 1)` in
374
+ * [`build_http_config`] — `0` / `1` both mean a single attempt, no retry.
375
+ */
376
+ retryMaxAttempts?: number
377
+ /**
378
+ * Overall retry budget in whole seconds. Maps onto
379
+ * [`HttpConfig::overall_timeout`].
380
+ */
381
+ retryOverallTimeoutSecs?: number
382
+ /**
383
+ * Programmatic HTTP/HTTPS proxy ([`ProxyInput`]) to route all kernel
384
+ * traffic through. Carries the proxy `url`, optional basic-auth
385
+ * `username` / `password`, and an optional `bypassHosts` list — mapped
386
+ * field-for-field onto the kernel [`ProxyConfig`].
387
+ *
388
+ * Omitted ⇒ the kernel does NOT configure a proxy explicitly and
389
+ * `reqwest`'s standard behaviour applies — the `HTTPS_PROXY` /
390
+ * `HTTP_PROXY` / `NO_PROXY` environment variables are still honoured.
391
+ * Setting this **overrides** those env vars. This complements the env-var
392
+ * path: callers who cannot set process env vars (e.g. a long-lived Node
393
+ * server) can now route a single connection through a proxy
394
+ * programmatically.
395
+ */
396
+ proxy?: ProxyInput
397
+ /**
398
+ * Per-connection socket read timeout, in milliseconds. Caps how
399
+ * long a single HTTP round-trip may block waiting on the server
400
+ * before the request errors out. Maps onto the kernel
401
+ * [`HttpConfig::request_timeout`] (the internal reqwest
402
+ * `Client::timeout`).
403
+ *
404
+ * Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs
405
+ * serialises `u32` as JS `number`; the largest representable value
406
+ * (~49.7 days) far exceeds any sensible socket timeout.
407
+ */
408
+ socketTimeoutMs?: number
409
+ }
410
+ /**
411
+ * Open a Databricks SQL session and return an opaque `Connection`
412
+ * wrapping the kernel `Session`. Authentication is selected by
413
+ * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see
414
+ * [`build_auth_config`].
415
+ *
416
+ * The JS-visible name is `openSession` (napi-rs converts snake_case
417
+ * to camelCase for free functions).
418
+ */
419
+ export declare function openSession(options: ConnectionOptions): Promise<Connection>
420
+ /**
421
+ * One kernel log event, as handed to JS. `level` is a lower-case string
422
+ * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its
423
+ * `LogLevel`; `target` is the originating `tracing` target (e.g.
424
+ * `databricks::sql::kernel`); `message` is the rendered event plus any
425
+ * structured `key=value` fields.
426
+ */
427
+ export interface LogRecord {
428
+ level: string
429
+ target: string
430
+ message: string
431
+ }
432
+ /**
433
+ * Install (idempotently) the kernel→JS log bridge and set its level.
434
+ *
435
+ * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`)
436
+ * for each forwarded batch. `level` is one of
437
+ * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown
438
+ * values fall back to `warn`.
439
+ *
440
+ * Safe to call more than once: the process-global subscriber is installed on
441
+ * the first call only, while every call refreshes the sink + level (last
442
+ * writer wins — see module docs).
443
+ */
444
+ export declare function initKernelLogging(callback: (err: Error | null, arg: Array<LogRecord>) => any, level: string): void
445
+ /**
446
+ * Snapshot of the bridge's runtime state for observability.
447
+ *
448
+ * `installed` is `true` only when the process-global subscriber was
449
+ * successfully installed by *this* bridge (and the drain thread started);
450
+ * `false` means another global subscriber was already set or the drain
451
+ * thread could not be spawned, so kernel logs are NOT reaching the JS sink.
452
+ * `dropped` is the cumulative count of records discarded because the
453
+ * bounded channel was full during a burst (drop-newest) — a nonzero,
454
+ * growing value signals the sink can't keep up.
455
+ */
456
+ export interface KernelLoggingStats {
457
+ installed: boolean
458
+ dropped: number
459
+ }
460
+ /**
461
+ * Return the bridge's [`KernelLoggingStats`]. Safe to call before
462
+ * `initKernelLogging` (reports `installed: false`, `dropped: 0`).
463
+ */
464
+ export declare function kernelLoggingStats(): KernelLoggingStats
465
+ /**
466
+ * Live-retarget the bridge's level (one of
467
+ * `off`/`error`/`warn`/`info`/`debug`/`trace`, case-insensitive).
468
+ */
469
+ export declare function setKernelLogLevel(level: string): void
470
+ /**
471
+ * JS-visible binding for a single positional parameter.
472
+ *
473
+ * Shape mirrors the `TSparkParameter` wire object the Thrift backend
474
+ * already emits via `DBSQLParameter.toSparkParameter()` — `type` is the
475
+ * canonical Databricks SQL type name (`"INT"`, `"STRING"`,
476
+ * `"DECIMAL(10,2)"`, ...), `value` is the string-encoded literal or
477
+ * `None` for SQL NULL.
478
+ *
479
+ * Why a string for `value` instead of a tagged JS union: round-tripping
480
+ * arbitrary JS values across the FFI requires either (a) a custom
481
+ * napi `FromNapiValue` per arm, or (b) a `serde_json::Value`-style
482
+ * dynamic dispatch on the Rust side. The Node-driver adapter already
483
+ * stringifies before calling the binding (see `DBSQLParameter` and the
484
+ * existing pyo3 wrapper), so the string-in / string-parsed contract
485
+ * adds no JS-side complexity and keeps the kernel-side validation in
486
+ * one place.
487
+ */
488
+ export interface TypedValueInput {
489
+ /**
490
+ * Canonical Databricks SQL type name. Case-insensitive for the
491
+ * simple variants; for DECIMAL the parenthesised form
492
+ * (`"DECIMAL(10,2)"`) is required so the kernel can extract
493
+ * precision/scale.
494
+ */
495
+ sqlType: string
496
+ /**
497
+ * String-encoded value. `None` always produces `TypedValue::Null`
498
+ * regardless of `sql_type` — matches the connector's
499
+ * `VoidParameter` shape and the pyo3 binding's contract.
500
+ */
501
+ value?: string
502
+ }
503
+ /**
504
+ * A single Arrow IPC stream payload encoding one record batch (plus
505
+ * the schema header so the JS-side reader is stateless).
506
+ */
507
+ export interface ArrowBatch {
508
+ /**
509
+ * Arrow IPC stream payload (schema header + 1 record-batch
510
+ * message). Decode with `apache-arrow`'s `RecordBatchReader`.
511
+ */
512
+ ipcBytes: Buffer
513
+ }
514
+ /**
515
+ * An Arrow IPC stream payload encoding just the result schema (no
516
+ * record-batch messages). Returned by `Statement.schema()`.
517
+ */
518
+ export interface ArrowSchema {
519
+ /**
520
+ * Arrow IPC stream payload (schema header only, no record-batch
521
+ * messages). Decode with `apache-arrow`'s `RecordBatchReader` —
522
+ * the reader will expose the schema and immediately end.
523
+ */
524
+ ipcBytes: Buffer
525
+ }
526
+ /**
527
+ * Returns the native binding's crate version (`CARGO_PKG_VERSION`).
528
+ *
529
+ * Originally the round-1b smoke test; kept as a cheap "is the binding
530
+ * loaded?" probe for the JS-side loader's structured diagnostics.
531
+ */
532
+ export declare function version(): string
533
+ /**
534
+ * Opaque async-statement handle.
535
+ *
536
+ * Returned by `Connection.submitStatement(...)` after the kernel
537
+ * `Statement::submit()` returns (server sent `wait_timeout=0s`, so
538
+ * the response carries a `statement_id` but the statement is still
539
+ * `Pending`/`Running`). JS drives polling via `status()` /
540
+ * `awaitResult()`.
541
+ *
542
+ * Concurrency shape: `status()`, `awaitResult()`, and `close()` take
543
+ * `inner.lock()` and hold the guard across the kernel `.await` (tokio
544
+ * `Mutex` is FIFO), so `status()` / `close()` queue behind any
545
+ * in-flight `awaitResult()` until it returns naturally. `cancel()` is
546
+ * the deliberate exception: it does **not** touch `inner` — it fires
547
+ * through the detached `AsyncStatementCanceller` (session +
548
+ * statement_id, captured at construction), so an explicit
549
+ * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of
550
+ * queueing behind it. The server-side cancel flips the statement
551
+ * terminal, which the parked `awaitResult()` poll loop observes
552
+ * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard`
553
+ * still covers the drop-cancel case (Promise.race / timeout)
554
+ * independently — see module docs.
555
+ */
556
+ export declare class AsyncStatement {
557
+ /**
558
+ * Server-issued statement id. Cached at construction; readable
559
+ * even after `close()` so JS-side log lines can correlate
560
+ * against kernel / server logs which key on the same id.
561
+ */
562
+ get statementId(): string
563
+ /**
564
+ * One-shot status check. Returns a string enum matching the
565
+ * kernel `StatementStatus` shape:
566
+ * `'Pending' | 'Running' | 'Succeeded' | 'Failed' |
567
+ * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the
568
+ * `#[non_exhaustive]` forward-compat catch-all that
569
+ * `StatementStatus::as_str` can return — consumers switching on
570
+ * the state must handle it.) Returns
571
+ * `KernelError(InvalidStatementHandle)` if the statement has
572
+ * been explicitly `close()`d.
573
+ *
574
+ * The `Failed` variant collapses to the string `'Failed'` on
575
+ * the JS side; the underlying error envelope (sql_state /
576
+ * error_code / query_id) is surfaced by `awaitResult()`'s
577
+ * rejection, which is where callers actually need the typed
578
+ * error. `status()` is intended for polling progress UIs
579
+ * that only need the state name.
580
+ */
581
+ status(): Promise<string>
582
+ /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */
583
+ numModifiedRows(): Promise<number | null>
584
+ /**
585
+ * Server-supplied user-facing message (may contain SQL fragments —
586
+ * redact before centralised logging).
587
+ */
588
+ displayMessage(): Promise<string | null>
589
+ /** Server-supplied diagnostic detail. */
590
+ diagnosticInfo(): Promise<string | null>
591
+ /** Server-supplied structured error detail (JSON), when enabled. */
592
+ errorDetailsJson(): Promise<string | null>
593
+ /**
594
+ * Block until the server reaches a terminal state, then return
595
+ * an `AsyncResultHandle` that wraps the materialised result
596
+ * stream. The handle exposes `fetchNextBatch()` / `schema()`
597
+ * for consuming the result, plus `statementId` for log
598
+ * correlation.
599
+ *
600
+ * Drop-cancel safety: kernel `await_result` installs
601
+ * `AwaitResultCancelGuard` which fires a fire-and-forget
602
+ * `cancel_statement` if the future is dropped mid-poll
603
+ * (timeout, tokio::select! loser, JS-side `Promise.race`
604
+ * loser). The `util::guarded` `catch_unwind` here covers the
605
+ * V8-panic-across-boundary case on top. Returns
606
+ * `KernelError(InvalidStatementHandle)` if the statement has
607
+ * been explicitly `close()`d.
608
+ */
609
+ awaitResult(): Promise<AsyncResultHandle>
610
+ /**
611
+ * Server-side cancel. Returns
612
+ * `KernelError(InvalidStatementHandle)` if the statement has
613
+ * been explicitly `close()`d. Idempotent against a server
614
+ * that already reached a terminal state — the kernel's
615
+ * `cancel_statement` is a no-op there.
616
+ *
617
+ * **Lock-free by design.** Unlike `status()` / `awaitResult()` /
618
+ * `close()`, this does not take `inner.lock()` — it fires through
619
+ * the detached `AsyncStatementCanceller` captured at construction.
620
+ * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()`
621
+ * (which holds the mutex for the whole poll) instead of queueing
622
+ * behind it: the server-side cancel flips the statement terminal,
623
+ * the parked `awaitResult()` poll loop observes `Cancelled` and
624
+ * returns. The closed-state check reads a lock-free flag so a
625
+ * cancel after an explicit `close()` still surfaces
626
+ * `InvalidStatementHandle`.
627
+ */
628
+ cancel(): Promise<void>
629
+ /**
630
+ * Explicit close. Idempotent — a second call on an
631
+ * already-closed handle returns `Ok(())`. On `Err`, the napi
632
+ * inner is already `None`, so a JS-side retry sees the
633
+ * closed-handle short-circuit and returns `Ok(())` without
634
+ * re-attempting the wire call. The kernel's own `Drop`
635
+ * fire-and-forget retry runs once in the background.
636
+ */
637
+ close(): Promise<void>
638
+ }
639
+ /**
640
+ * Opaque result-fetch handle returned by
641
+ * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream`
642
+ * directly; structurally analogous to the sync `Statement`'s
643
+ * fetch-side surface (`fetchNextBatch` / `schema` /
644
+ * `statementId`).
645
+ *
646
+ * `cancel()` / `close()` are not exposed: the parent
647
+ * `AsyncStatement` owns server-side lifecycle. A `close()` here
648
+ * would create dual-ownership of the same statement_id with
649
+ * inconsistent close semantics. Callers `close()` the parent
650
+ * `AsyncStatement` after they're done fetching.
651
+ *
652
+ * Schema is cached at construction so it survives the underlying
653
+ * stream being drained; mirrors the sync `Statement.schema()`
654
+ * post-close contract.
655
+ */
656
+ export declare class AsyncResultHandle {
657
+ /**
658
+ * Server-issued statement id. Cached at construction; readable
659
+ * for log correlation. Matches the parent `AsyncStatement`'s
660
+ * `statementId`.
661
+ */
662
+ get statementId(): string
663
+ /**
664
+ * Pull the next batch of results. Returns `null` when the
665
+ * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a
666
+ * complete Arrow IPC stream (schema header + 1 record-batch
667
+ * message), suitable for handing to `apache-arrow`'s
668
+ * `RecordBatchReader`. Byte-identical to the sync
669
+ * `Statement.fetchNextBatch()` payload for the same query.
670
+ */
671
+ fetchNextBatch(): Promise<ArrowBatch | null>
672
+ /**
673
+ * Result schema as an Arrow IPC payload (schema header only,
674
+ * no record-batch message). Available before any batches have
675
+ * been fetched. Sync because the body has no `.await` —
676
+ * `encode_ipc_stream` is pure CPU work over the cached
677
+ * `Arc<Schema>`.
678
+ */
679
+ schema(): ArrowSchema
680
+ }
681
+ /**
682
+ * Handle returned by `Connection.executeStatementCancellable`. Owns the
683
+ * built-but-not-yet-executed kernel `Statement` plus a detached
684
+ * [`StatementCanceller`] captured before dispatch, so JS can fire a
685
+ * server-side cancel while the blocking `result()` is in flight.
686
+ *
687
+ * `pending` is `Arc<Mutex<Option<KernelStatement>>>` so `result()` can
688
+ * `.take()` the statement (the kernel `execute()` borrows it `&mut`,
689
+ * then it moves into the produced `Statement` wrapper to keep its
690
+ * `ValidityFlag` set — see `statement.rs`). A second `result()` call
691
+ * after the first resolved surfaces `InvalidStatementHandle`.
692
+ */
693
+ export declare class CancellableExecution {
694
+ /**
695
+ * The server-issued statement id this execution targets, if the
696
+ * server has issued one yet (`null` before the initial submit
697
+ * round-trip publishes it mid-`result()`). Useful for log
698
+ * correlation while the blocking drive is in flight.
699
+ */
700
+ get statementId(): string | null
701
+ /**
702
+ * Drive the blocking `execute()` and resolve to a `Statement`
703
+ * (identical to what `executeStatement` returns) once the kernel
704
+ * reaches a terminal state and the result stream is ready.
705
+ *
706
+ * Consumes the pending statement: a second `result()` call returns
707
+ * `KernelError(InvalidStatementHandle)`. The future is
708
+ * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState`
709
+ * guard fires a fire-and-forget `cancel_statement` if this future is
710
+ * dropped mid-flight (`Promise.race` / timeout loser), independently
711
+ * of an explicit `cancel()`.
712
+ *
713
+ * On a server-side cancel the kernel's blocking `execute()` currently
714
+ * surfaces `InvalidArgument` (a known kernel quirk — the async path
715
+ * returns `Cancelled`). When this handle's `cancel()` actually dispatched a
716
+ * server-side cancel, we normalise that into `Cancelled` here so JS callers
717
+ * can rely on a single cancelled-status code regardless of execution path.
718
+ *
719
+ * Three outcomes can race the blocking drive: (1) a natural terminal state
720
+ * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a
721
+ * server cancel → this `result()` rejects with a `Cancelled`-coded error
722
+ * (the normalisation above); (3) the future being **dropped** mid-flight
723
+ * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState`
724
+ * drop-guard fires a fire-and-forget `cancel_statement`, but there is no
725
+ * `result()` left to observe a code. Only (2) yields a `Cancelled` error.
726
+ */
727
+ result(): Promise<Statement>
728
+ /**
729
+ * Server-side cancel of the in-flight statement.
730
+ *
731
+ * Lock-free: fires the detached `StatementCanceller` captured at
732
+ * construction rather than taking the mutex `result()` holds, so it
733
+ * interrupts a still-running blocking `result()` instead of queueing
734
+ * behind it. No-op (returns `Ok`) if `result()` already finished
735
+ * successfully, or if no statement id has been observed yet (query still
736
+ * in its initial submit round-trip), and idempotent against a server
737
+ * already in a terminal state.
738
+ */
739
+ cancel(): Promise<void>
740
+ }
741
+ /**
742
+ * Opaque connection handle wrapping a kernel `Session`.
743
+ *
744
+ * `inner` is `Arc<Mutex<Option<Session>>>` so:
745
+ * - the Drop impl can clone the `Arc` and `.take()` the session on a
746
+ * background tokio task without holding `&mut self` (which Drop is
747
+ * forbidden from doing across an `await`),
748
+ * - `close()` can `.take()` the session to consume it for the kernel's
749
+ * move-by-value `Session::close(self)` signature.
750
+ *
751
+ * **Concurrency shape** — both `executeStatement` and
752
+ * `submitStatement` build the kernel `Statement` under `inner.lock()`
753
+ * and then RELEASE the guard before the wire call
754
+ * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()`
755
+ * is `&self`-callable and only clones the session's internal `Arc`, so
756
+ * the built statement is independent of the guard. Concurrent
757
+ * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore
758
+ * serialise only for the microsecond statement-build, not the network
759
+ * round-trip, and `close()` never blocks behind an in-flight execute or
760
+ * submit. See
761
+ * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`.
762
+ */
763
+ export declare class Connection {
764
+ /**
765
+ * Server-issued session id. Cached at construction; readable
766
+ * even after `close()` so JS-side log lines can correlate
767
+ * against kernel / server logs which key on the same id.
768
+ */
769
+ get sessionId(): string
770
+ /**
771
+ * Execute a SQL statement and return a Statement handle that
772
+ * streams batches via `fetchNextBatch()`.
773
+ *
774
+ * Catalog / schema / sessionConf are session-level
775
+ * (`openSession`). Per-statement options on `ExecuteOptions`:
776
+ * - `statementConf` — per-statement Spark conf overlay
777
+ * - `queryTags` — serialised to a comma-separated `key:value`
778
+ * string and placed in `statement_conf["query_tags"]`,
779
+ * matching NodeJS Thrift's `serializeQueryTags` wire shape
780
+ *
781
+ * `options` is omitted/`None` for the no-options path; passing
782
+ * `{ statementConf: {} }` (an empty map) is treated the same as
783
+ * omission to keep the wire shape stable for the common case.
784
+ */
785
+ executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise<Statement>
786
+ /**
787
+ * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement
788
+ * with no `wait_timeout` field (server applies its ~10s default inline wait
789
+ * and auto-closes on success) and returns WITHOUT polling past it:
790
+ *
791
+ * - a **`Statement`** (left arm) when the query finished within the inline
792
+ * wait — terminal, result ready inline, `close()` is a clean release;
793
+ * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel
794
+ * handle the caller drives (`status()` / `awaitResult()` / `cancel()`).
795
+ *
796
+ * JS distinguishes the arms by feature-detecting `awaitResult` (present
797
+ * only on `AsyncStatement`). This is the path that gives mid-run cancel for
798
+ * long queries WITHOUT the eager-handle / close-drives workaround: the
799
+ * returned handle always corresponds to a server-owned statement.
800
+ *
801
+ * **Load-bearing contract:** the kernel's `DirectStatement::{Completed,
802
+ * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so
803
+ * consumers MUST feature-detect via `awaitResult` (the only member unique to
804
+ * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an
805
+ * `awaitResult` member, or every consumer silently misroutes. The pyo3
806
+ * binding makes the same `await_result`-probe assumption.
807
+ */
808
+ executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise<Statement | AsyncStatement>
809
+ /**
810
+ * Execute a SQL statement on the blocking (sync) path, but return a
811
+ * `CancellableExecution` handle so a concurrent JS task can cancel
812
+ * the query *while it is still running server-side*.
813
+ *
814
+ * `executeStatement` builds the kernel `Statement`, awaits the
815
+ * blocking `execute()`, and only then hands JS a `Statement` — so a
816
+ * query that runs for several seconds is uncancellable from JS on
817
+ * that path (there is no handle until the blocking call resolves).
818
+ * This method instead builds the statement, captures a detached
819
+ * `StatementCanceller` **before** dispatching `execute()`, and hands
820
+ * JS a `CancellableExecution` immediately. The caller drives the
821
+ * blocking execution via `result()` (resolves to the same
822
+ * `Statement` `executeStatement` returns) and can fire `cancel()`
823
+ * concurrently to interrupt a still-running query mid-COMPUTE.
824
+ *
825
+ * Option semantics are identical to `executeStatement`.
826
+ * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()`
827
+ * split (PR #121): obtain the canceller before the blocking drive.
828
+ */
829
+ executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise<CancellableExecution>
830
+ /**
831
+ * Submit a SQL statement and return immediately with an
832
+ * `AsyncStatement` handle, without blocking until the query
833
+ * finishes. The kernel's `Statement::submit()` sends
834
+ * `wait_timeout=0s`, so the server responds as soon as it has a
835
+ * `statement_id` (state `Pending`/`Running`); JS drives polling
836
+ * via `AsyncStatement.status()` and materialises results with
837
+ * `AsyncStatement.awaitResult()`.
838
+ *
839
+ * This is the async-execution path the Thrift backend always
840
+ * uses (`runAsync: true`): the SEA backend submits, returns a
841
+ * pending operation handle, and polls to terminal during
842
+ * fetch. Option semantics (statementConf / queryTags /
843
+ * rowLimit / positional + named params) match `executeStatement`.
844
+ * Submit always sends `wait_timeout=0s` so the call returns
845
+ * immediately; the caller drives completion via `status()` /
846
+ * `awaitResult()`. Only the blocking-vs-pending return contract
847
+ * differs from `executeStatement`.
848
+ */
849
+ submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise<AsyncStatement>
850
+ /**
851
+ * Explicit close. Awaits the server-side `DeleteSession` so the
852
+ * JS caller can observe failures (auth revoked mid-session,
853
+ * warehouse stopped, network error). Idempotent — a second call
854
+ * on an already-closed connection returns `Ok`.
855
+ *
856
+ * **Errors are terminal from the JS side.** The kernel session
857
+ * handle is consumed (`take()`) BEFORE the wire `DeleteSession`
858
+ * runs, because `Session::close` takes `self` by value. On `Err`,
859
+ * the napi `inner` is already `None`, so a JS-side retry sees a
860
+ * closed connection and returns `Ok(())` without re-attempting
861
+ * the wire call. The kernel's own `Drop` fire-and-forget retry
862
+ * runs once in the background — the JS caller can log the error
863
+ * but cannot drive a retry. If you need retry-on-failure
864
+ * semantics for `DeleteSession`, layer them above this method.
865
+ */
866
+ close(): Promise<void>
867
+ /**
868
+ * All catalogs visible to the session.
869
+ *
870
+ * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`.
871
+ */
872
+ listCatalogs(): Promise<Statement>
873
+ /**
874
+ * Schemas filtered by catalog (exact) and schema name pattern.
875
+ *
876
+ * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`.
877
+ */
878
+ listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise<Statement>
879
+ /**
880
+ * Tables filtered by catalog (exact), schema (pattern), table (pattern).
881
+ *
882
+ * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided,
883
+ * filters rows by `TABLE_TYPE` kernel-side.
884
+ *
885
+ * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does
886
+ * NOT honour the table-type filter server-side; the kernel applies
887
+ * it client-side after the result returns. Callers expecting
888
+ * server-side rejection of off-type tables should not rely on this.
889
+ */
890
+ listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array<string> | undefined | null): Promise<Statement>
891
+ /**
892
+ * Columns of tables matching the filter.
893
+ *
894
+ * JDBC `getColumns` shape: 23 columns.
895
+ */
896
+ listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise<Statement>
897
+ /**
898
+ * Functions visible to the session. `catalog` is exact;
899
+ * `schemaPattern` and `functionPattern` are SQL LIKE.
900
+ */
901
+ listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise<Statement>
902
+ /**
903
+ * Procedures visible to the session. `catalog` is exact;
904
+ * `schemaPattern` and `procedurePattern` are SQL LIKE.
905
+ */
906
+ listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise<Statement>
907
+ /**
908
+ * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …).
909
+ * No wire call — static in-memory result.
910
+ */
911
+ listTableTypes(): Promise<Statement>
912
+ /**
913
+ * SQL data types supported by the workspace.
914
+ * No wire call — static in-memory result.
915
+ */
916
+ listTypeInfo(): Promise<Statement>
917
+ /**
918
+ * Primary keys for the given table. All three identifiers are
919
+ * exact — ODBC `SQLPrimaryKeys` does not support patterns.
920
+ */
921
+ getPrimaryKeys(catalog: string, schema: string, table: string): Promise<Statement>
922
+ /**
923
+ * Foreign-key relationships. The foreign side must be fully
924
+ * specified (catalog + schema + table); the parent side is
925
+ * optional. All identifiers are exact — no LIKE patterns.
926
+ */
927
+ getCrossReference(parentCatalog: string | undefined | null, parentSchema: string | undefined | null, parentTable: string | undefined | null, foreignCatalog: string, foreignSchema: string, foreignTable: string): Promise<Statement>
928
+ }
929
+ /**
930
+ * Opaque executed-statement handle.
931
+ *
932
+ * **Current concurrency shape** — every method takes `inner.lock()`
933
+ * and holds the guard across the kernel `.await`. tokio `Mutex` is
934
+ * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch`
935
+ * until it returns naturally. This is a known limitation that exists
936
+ * because the napi shape has not yet been split into an
937
+ * `Arc<dyn ExecutedStatementHandle>` (for cancel/close, which the
938
+ * kernel exposes as `&self`-callable) plus a `Mutex<Option<…>>` only
939
+ * for the borrowed-mut fetch path. The lock-shape refactor needs a
940
+ * small kernel-side accessor and lands in a follow-up PR — see
941
+ * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`.
942
+ *
943
+ * `schema` and `statement_id` are cached at construction so they
944
+ * survive `close()` — JS callers building error reports against a
945
+ * disposed statement can still read them.
946
+ */
947
+ export declare class Statement {
948
+ /**
949
+ * Server-issued statement id. Cached at construction; readable
950
+ * even after `close()` so JS-side log lines can correlate against
951
+ * kernel / server logs which key on the same id.
952
+ */
953
+ get statementId(): string
954
+ /**
955
+ * Number of rows modified by the statement (UPDATE / INSERT /
956
+ * DELETE / MERGE). `null` for SELECT and on warehouses that don't
957
+ * surface the counter. Mirrors Thrift's
958
+ * `TGetOperationStatusResp.numModifiedRows`.
959
+ */
960
+ numModifiedRows(): Promise<number | null>
961
+ /**
962
+ * Server-supplied user-facing message. Mirrors Thrift's
963
+ * `TGetOperationStatusResp.displayMessage`. **PII / sensitive-
964
+ * data note:** may contain SQL fragments or parameter values —
965
+ * redact before centralised logging.
966
+ *
967
+ * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`).
968
+ * On terminal-error states (`Failed` / `Cancelled`) the kernel returns
969
+ * an Error instead of a `Statement`, and the same field rides on the JS
970
+ * Error envelope under the same `displayMessage` key.
971
+ */
972
+ displayMessage(): Promise<string | null>
973
+ /**
974
+ * Server-supplied diagnostic detail — multi-line operator /
975
+ * stack context. Mirrors Thrift's
976
+ * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces,
977
+ * not user-facing. Same reachability + PII caveats as
978
+ * `displayMessage`.
979
+ */
980
+ diagnosticInfo(): Promise<string | null>
981
+ /**
982
+ * Server-supplied JSON blob with extended error details. Mirrors
983
+ * Thrift's `TGetOperationStatusResp.errorDetailsJson`.
984
+ * Pass-through string — JS callers parse with `JSON.parse` if
985
+ * they need structured access.
986
+ *
987
+ * **Server-side gating:** populated only when the workspace has
988
+ * `spark.databricks.sql.errorDetailsJson.enabled = true` on the
989
+ * underlying SQL cluster. The flag is internal-only / default-
990
+ * false in the Databricks runtime, so for most JS callers this
991
+ * will return `null`. Admin-enabled workspaces return content
992
+ * shaped like `{"errorClass": "...", "messageTemplate": "..."}`.
993
+ *
994
+ * **Unbounded:** when populated, server can return a multi-MB
995
+ * blob; size before logging.
996
+ */
997
+ errorDetailsJson(): Promise<string | null>
998
+ /**
999
+ * Pull the next batch of results. Returns `null` when the stream
1000
+ * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete
1001
+ * Arrow IPC stream (schema header + 1 record-batch message)
1002
+ * suitable for handing to `apache-arrow`'s `RecordBatchReader`.
1003
+ *
1004
+ * On `Err`, the stream is in an unspecified state — call
1005
+ * `close()` and discard the `Statement`. Subsequent
1006
+ * `fetchNextBatch()` calls after an error are not guaranteed to
1007
+ * succeed or fail consistently.
1008
+ */
1009
+ fetchNextBatch(): Promise<ArrowBatch | null>
1010
+ /**
1011
+ * Result schema as an Arrow IPC payload (schema header only, no
1012
+ * record-batch message). Available before any batches have been
1013
+ * fetched, and remains available after `close()` — the kernel
1014
+ * materialises the schema eagerly so JS callers can build error
1015
+ * reports against a disposed statement.
1016
+ *
1017
+ * Sync because the body has no `.await` — `encode_ipc_stream` is
1018
+ * pure CPU work over an `Arc<Schema>` already cached on the
1019
+ * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync).
1020
+ * napi-rs converts a panic in a sync `#[napi]` entry point into a
1021
+ * thrown JS error via its own macro-expanded boundary, so the
1022
+ * `util::guarded` `catch_unwind` wrapper that the `async fn`
1023
+ * entry points use is not required for this method.
1024
+ */
1025
+ schema(): ArrowSchema
1026
+ /**
1027
+ * Server-side cancel.
1028
+ *
1029
+ * For executed statements: short-circuits to `Ok(())` if
1030
+ * `fetchNextBatch` has already returned `null` (stream
1031
+ * naturally exhausted) — matches the JDBC `Statement.cancel()`
1032
+ * no-op-after-completion contract, so JS callers can fire cancel
1033
+ * defensively without distinguishing "real cancel" from "raced
1034
+ * with natural completion."
1035
+ *
1036
+ * For metadata streams: no-op (the kernel has no in-flight
1037
+ * cancellation surface for metadata calls today).
1038
+ *
1039
+ * Returns `KernelError(InvalidStatementHandle)` if the statement
1040
+ * has been explicitly `close()`d.
1041
+ */
1042
+ cancel(): Promise<void>
1043
+ /**
1044
+ * Explicit close.
1045
+ *
1046
+ * For executed statements: awaits the server-side `CloseStatement`
1047
+ * so the JS caller can observe failures (auth revoked mid-session,
1048
+ * network error, server-side error). Idempotent — a second call
1049
+ * on an already-closed statement returns `Ok`.
1050
+ *
1051
+ * **Errors are terminal from the JS side.** The kernel executed
1052
+ * handle is taken out of `inner` BEFORE the wire `CloseStatement`
1053
+ * runs (so `Drop` knows there's nothing left to clean up). On
1054
+ * `Err`, the napi `inner` is already `None`, so a JS-side retry
1055
+ * sees a closed statement and returns `Ok(())` without re-
1056
+ * attempting the wire call. The kernel-level `ExecutedStatement`
1057
+ * has been consumed at that point and the value is dropped on
1058
+ * the way out of the closure — the kernel's `ExecutedStatement::
1059
+ * Drop` then fires-and-forgets a single retry on the captured
1060
+ * runtime. The JS caller can log the error but cannot drive a
1061
+ * further retry. If you need retry-on-failure semantics for
1062
+ * `CloseStatement`, layer them above this method.
1063
+ *
1064
+ * For metadata streams: drops the stream (no server round-trip
1065
+ * needed — metadata results have no in-flight server-side
1066
+ * resource to release).
1067
+ */
1068
+ close(): Promise<void>
1069
+ }