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