Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
68b5bf7
feat(napi): add Database / Connection / Statement / ResultStream napi…
msrathore-db May 16, 2026
5b8a591
feat(napi)!: move catalog/schema/sessionConf to session-level, drop E…
msrathore-db May 24, 2026
c731bd8
fix(napi): await Session::close so JS callers observe DeleteSession f…
msrathore-db May 24, 2026
acdb6c7
test(napi): add encode_ipc_stream tests + tighten docstrings
msrathore-db May 24, 2026
d428671
fix(napi): address PR #25 round-2 review — typed closed-state errors,…
msrathore-db May 24, 2026
142e43c
fix(napi): map non-Arrow ResultBatch fallback to InvalidArgument
msrathore-db May 24, 2026
9c56fbe
fix(napi,kernel): address PR #25 review — sync schema(), close JSDoc …
msrathore-db May 25, 2026
4acde6a
napi: propagate StatementInner ValidityFlag fix from sea-operation
msrathore-db May 15, 2026
09472d7
krn-napi-binding: reclassify OAuth token-exchange failures as Unauthe…
msrathore-db May 15, 2026
c14c1ff
feat(config): bump HttpConfig pool_max_idle_per_host default 10 -> 100
msrathore-db May 17, 2026
8c0aabc
krn-tls-public-api: expose TlsConfig fields + stop discarding in sess…
msrathore-db May 16, 2026
5265c75
krn-status-fields: expose 5 status accessors on ExecutedStatement
msrathore-db May 16, 2026
c36e286
feat(napi): expose 10 metadata methods on Connection
msrathore-db May 20, 2026
d10e271
fix(napi/metadata): remove footgun Handle param + reject whitespace-o…
msrathore-db May 20, 2026
70938ce
docs(napi): document tableTypes advisory-filter behavior in list_tables
msrathore-db May 20, 2026
804668c
docs(kernel): list whitespace rejection in Identifier and LikePattern…
msrathore-db May 20, 2026
6cda5ec
fix(napi): drop now-unused tokio::runtime::Handle import in metadata.rs
msrathore-db May 21, 2026
66d47c8
feat(napi): accept ExecuteOptions on executeStatement — statementConf…
msrathore-db May 25, 2026
a50b50c
fix(napi): F3 fixup — clippy err_expect + rustfmt on connection.rs
msrathore-db May 25, 2026
be45ab2
fix(napi): F3 round-2 — docstring + parity test fixups (DA M1/M4)
msrathore-db May 25, 2026
16b1bec
feat(napi): TypedValue codec for positional params
msrathore-db May 29, 2026
092ba92
feat(statement,napi): surface row_limit + per-statement query timeout…
msrathore-db May 31, 2026
c65966b
fix(reader): clamp inline result to manifest.total_row_count
msrathore-db May 31, 2026
f34cc9d
feat(napi): expose kernel OAuth (M2M + U2M) on openSession Connection…
msrathore-db May 31, 2026
2c6ba73
Merge branch 'msrathore/krn-napi-metadata-exposure' into msrathore/kr…
msrathore-db May 31, 2026
a5dede8
merge: combined kernel (metadata + OAuth + row_limit/query_timeout + …
msrathore-db May 31, 2026
120babf
feat(napi): expose intervalsAsString + complexTypesAsJson on openSession
msrathore-db May 31, 2026
56ad273
Merge remote-tracking branch 'origin/msrathore/krn-napi-typedvalue-co…
msrathore-db May 31, 2026
3d8c6bd
Merge remote-tracking branch 'origin/msrathore/krn-napi-result-config…
msrathore-db May 31, 2026
c8f59d2
feat(napi): expose named query parameters (param_named) on ExecuteOpt…
msrathore-db May 31, 2026
fbbd32e
fix(kernel,napi): surface close_statement errors + non-blocking concu…
msrathore-db May 31, 2026
ae94dbe
Merge remote-tracking branch 'origin/main' into HEAD
msrathore-db Jun 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions napi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@ arrow-ipc = "57"
# `src/error.rs` without bouncing through a hand-rolled escaper.
serde_json = "1"

# Date/time parsing for the params codec. Already a kernel transitive
# dep (the kernel's `TypedValue::Date`/`Timestamp{,Ntz,Ltz}` variants
# wrap `chrono` types directly); declared here so `params.rs` can name
# `NaiveDate` / `NaiveDateTime` / `DateTime<Utc>` for literal parsing.
# Version kept in lock-step with the kernel's `chrono` dep.
chrono = { version = "0.4", default-features = false, features = ["clock"] }

[build-dependencies]
napi-build = "2"

Expand Down
503 changes: 495 additions & 8 deletions napi/src/connection.rs

Large diffs are not rendered by default.

240 changes: 229 additions & 11 deletions napi/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;

use databricks_sql_kernel::{AuthConfig, DefaultOpts, HttpConfig, Session};
use databricks_sql_kernel::{
AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, ResultConfig, Session,
};

/// NodeJS-driver-appropriate default for `pool_max_idle_per_host`.
///
Expand All @@ -49,8 +51,35 @@ use crate::error::napi_err_from_kernel;
use crate::runtime;
use crate::util::guarded;

/// JS-visible options for opening a Databricks SQL session over PAT.
/// `token` is required.
/// Authentication mode selector crossing the napi boundary. The string
/// literals are what napi-rs emits from this `#[napi(string_enum)]` — the
/// NodeJS SEA adapter (`SeaAuth`) matches them verbatim (`'Pat'`,
/// `'OAuthM2m'`, `'OAuthU2m'`).
///
/// Mirrors the kernel [`AuthConfig`] variants this binding supports.
/// `OAuthFederation` / `External` are intentionally not exposed yet — the
/// kernel marks federation as not-yet-implemented and `External` is a
/// Rust-trait escape hatch with no JS-callback bridge.
#[napi(string_enum)]
#[derive(Default)]
pub enum AuthMode {
/// Personal access token (`token`).
#[default]
Pat,
/// OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`.
OAuthM2m,
/// OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId`
/// + `oauthRedirectPort`.
OAuthU2m,
}

/// JS-visible options for opening a Databricks SQL session.
///
/// Authentication is selected by `authMode` (default [`AuthMode::Pat`]):
/// - `Pat` — `token` required.
/// - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required.
/// - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional (kernel
/// defaults to the `databricks-cli` client on port 8020).
///
/// Catalog / schema / sessionConf are applied once at session creation
/// and remain in effect for every statement run on the resulting
Expand All @@ -69,9 +98,23 @@ pub struct ConnectionOptions {
/// JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The
/// kernel parses out the warehouse id.
pub http_path: String,
/// Personal access token. Must be non-empty (the kernel rejects
/// empty PATs at session construction).
pub token: String,
/// Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat:
/// existing PAT callers pass only `token`).
pub auth_mode: Option<AuthMode>,
/// Personal access token. Required (and non-empty) for
/// [`AuthMode::Pat`]; ignored otherwise.
pub token: Option<String>,
/// OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for
/// [`AuthMode::OAuthU2m`] (kernel defaults to `databricks-cli`).
pub oauth_client_id: Option<String>,
/// OAuth client secret. Required for [`AuthMode::OAuthM2m`].
pub oauth_client_secret: Option<String>,
/// Localhost callback port for the [`AuthMode::OAuthU2m`] browser
/// flow. Omitted ⇒ kernel default (8020).
pub oauth_redirect_port: Option<u16>,
/// OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults
/// (`["all-apis"]` for M2M; `["all-apis", "offline_access"]` for U2M).
pub oauth_scopes: Option<Vec<String>>,
/// Default catalog for statements executed on this session.
/// Routed through the kernel's `DefaultOpts` and onto the SEA
/// `CreateSession.catalog` wire field.
Expand Down Expand Up @@ -105,10 +148,68 @@ pub struct ConnectionOptions {
/// Napi-rs serialises `u32` as JS `number`; values up to
/// `2^32 - 1` round-trip safely (any reasonable pool size fits).
pub max_connections: Option<u32>,
/// Render `INTERVAL` / `DURATION` result columns as strings
/// (`ResultConfig.intervals_as_string`). The kernel default is
/// native Arrow `month_interval` / `duration[us]` types; the NodeJS
/// Thrift driver surfaces intervals as strings, so the SEA driver
/// sets this `true` for byte-compatible parity. Omitted ⇒ kernel
/// default (native Arrow interval types).
pub intervals_as_string: Option<bool>,
/// Render complex (`ARRAY` / `MAP` / `STRUCT` / `VARIANT`) result
/// columns as JSON strings (`ResultConfig.complex_types_as_json`)
/// instead of native Arrow nested types. Omitted ⇒ kernel default
/// (native Arrow nested types, which the NodeJS Arrow decoder
/// already renders identically to the Thrift path).
pub complex_types_as_json: Option<bool>,
}

/// Open a Databricks SQL session over PAT auth and return an opaque
/// `Connection` wrapping the kernel `Session`.
/// Require a non-empty `Option<String>` field for a given auth mode,
/// returning a typed `InvalidArgument` naming the JS field otherwise.
fn require_field(value: &Option<String>, js_name: &str, mode: &str) -> napi::Result<String> {
value.clone().filter(|s| !s.is_empty()).ok_or_else(|| {
napi_err_from_kernel(
KernelError::invalid_argument()
.message(format!("authMode {mode} requires a non-empty `{js_name}`")),
)
})
}

/// Map the JS `ConnectionOptions` auth fields onto the kernel
/// [`AuthConfig`]. Per-mode required-field validation lives here at the
/// binding boundary so the kernel always receives a fully-formed variant.
/// Pure (borrows `options`) so it is unit-testable without opening a
/// session.
fn build_auth_config(options: &ConnectionOptions) -> napi::Result<AuthConfig> {
match options.auth_mode.unwrap_or_default() {
AuthMode::Pat => Ok(AuthConfig::Pat {
token: require_field(&options.token, "token", "Pat")?,
}),
AuthMode::OAuthM2m => Ok(AuthConfig::OAuthM2M {
client_id: require_field(&options.oauth_client_id, "oauthClientId", "OAuthM2m")?,
client_secret: require_field(
&options.oauth_client_secret,
"oauthClientSecret",
"OAuthM2m",
)?,
scopes: options.oauth_scopes.clone(),
token_url_override: None,
}),
AuthMode::OAuthU2m => Ok(AuthConfig::OAuthU2M {
// All U2M fields are optional — the kernel fills `databricks-cli`
// / port 8020 / default scopes when omitted.
client_id: options.oauth_client_id.clone(),
redirect_port: options.oauth_redirect_port,
scopes: options.oauth_scopes.clone(),
token_url_override: None,
callback_timeout: None,
}),
}
}

/// Open a Databricks SQL session and return an opaque `Connection`
/// wrapping the kernel `Session`. Authentication is selected by
/// `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see
/// [`build_auth_config`].
///
/// The JS-visible name is `openSession` (napi-rs converts snake_case
/// to camelCase for free functions).
Expand All @@ -125,16 +226,18 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result<Connection
// runtime that's driving this future.
let _ = runtime::get_handle();

// Resolve auth before the builder moves `host_name` / `http_path`
// out of `options` (validation can fail fast, before any network).
let auth_config = build_auth_config(&options)?;

// SessionConfig is `#[non_exhaustive]` — go through the
// builder, which is the only public path that constructs it.
// `http_path()` is the convenience setter that maps a bare
// hostname + `/sql/1.0/warehouses/{id}` path into the kernel's
// `ConnectionConfig`.
let mut builder = Session::builder()
.http_path(options.host_name, options.http_path)
.auth(AuthConfig::Pat {
token: options.token,
});
.auth(auth_config);
// Only wire `DefaultOpts` when at least one of catalog / schema
// was provided; otherwise leave the config's `defaults` field
// `None` so the kernel can distinguish "no defaults" from
Expand All @@ -150,6 +253,19 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result<Connection
if let Some(conf) = options.session_conf {
builder = builder.session_conf(conf);
}
// Result-config knobs (interval / complex-type rendering). Merge
// into one `ResultConfig` so the two toggles don't clobber each
// other when both are set. Only wire it when at least one is
// requested, leaving the kernel default otherwise. `ResultConfig`
// is `#[non_exhaustive]` — construct via `default()` then mutate.
let intervals_as_string = options.intervals_as_string.unwrap_or(false);
let complex_types_as_json = options.complex_types_as_json.unwrap_or(false);
if intervals_as_string || complex_types_as_json {
let mut result = ResultConfig::default();
result.intervals_as_string = intervals_as_string;
result.complex_types_as_json = complex_types_as_json;
builder = builder.result(result);
}
// `HttpConfig` is `#[non_exhaustive]` — must construct via
// `default()` then mutate. The napi binding ALWAYS sets
// `pool_max_idle_per_host` so the NodeJS-driver-appropriate
Expand All @@ -172,3 +288,105 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result<Connection
})
.await
}

#[cfg(test)]
mod tests {
use super::*;

/// Minimal options with only the required transport fields set;
/// auth fields default to "absent" so each test sets what it needs.
fn base() -> ConnectionOptions {
ConnectionOptions {
host_name: "adb-1.azuredatabricks.net".to_owned(),
http_path: "/sql/1.0/warehouses/abc".to_owned(),
auth_mode: None,
token: None,
oauth_client_id: None,
oauth_client_secret: None,
oauth_redirect_port: None,
oauth_scopes: None,
catalog: None,
schema: None,
session_conf: None,
max_connections: None,
intervals_as_string: None,
complex_types_as_json: None,
}
}

#[test]
fn default_mode_is_pat_and_requires_token() {
let mut o = base();
// No authMode + no token → fail-fast InvalidArgument.
assert!(build_auth_config(&o).is_err());
o.token = Some("dapi-xxx".to_owned());
assert!(matches!(
build_auth_config(&o).unwrap(),
AuthConfig::Pat { .. }
));
}

#[test]
fn pat_rejects_empty_token() {
let mut o = base();
o.auth_mode = Some(AuthMode::Pat);
o.token = Some(String::new());
assert!(build_auth_config(&o).is_err());
}

#[test]
fn m2m_requires_client_id_and_secret() {
let mut o = base();
o.auth_mode = Some(AuthMode::OAuthM2m);
assert!(build_auth_config(&o).is_err(), "missing both");
o.oauth_client_id = Some("cid".to_owned());
assert!(build_auth_config(&o).is_err(), "missing secret");
o.oauth_client_secret = Some("sec".to_owned());
o.oauth_scopes = Some(vec!["all-apis".to_owned()]);
match build_auth_config(&o).unwrap() {
AuthConfig::OAuthM2M {
client_id,
client_secret,
scopes,
..
} => {
assert_eq!(client_id, "cid");
assert_eq!(client_secret, "sec");
assert_eq!(scopes, Some(vec!["all-apis".to_owned()]));
}
other => panic!("expected OAuthM2M, got {other:?}"),
}
}

#[test]
fn u2m_fields_are_all_optional() {
let mut o = base();
o.auth_mode = Some(AuthMode::OAuthU2m);
// Bare U2M: kernel fills databricks-cli / port 8020 / default scopes.
match build_auth_config(&o).unwrap() {
AuthConfig::OAuthU2M {
client_id,
redirect_port,
..
} => {
assert!(client_id.is_none());
assert!(redirect_port.is_none());
}
other => panic!("expected OAuthU2M, got {other:?}"),
}
// Explicit overrides thread through.
o.oauth_client_id = Some("custom-cli".to_owned());
o.oauth_redirect_port = Some(9000);
match build_auth_config(&o).unwrap() {
AuthConfig::OAuthU2M {
client_id,
redirect_port,
..
} => {
assert_eq!(client_id.as_deref(), Some("custom-cli"));
assert_eq!(redirect_port, Some(9000));
}
other => panic!("expected OAuthU2M, got {other:?}"),
}
}
}
2 changes: 2 additions & 0 deletions napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ pub(crate) mod connection;
pub(crate) mod database;
pub(crate) mod error;
pub(crate) mod logger;
pub(crate) mod metadata;
pub(crate) mod params;
pub(crate) mod result;
pub(crate) mod runtime;
pub(crate) mod statement;
Expand Down
Loading
Loading