Skip to content

Commit d8f7a27

Browse files
committed
feat(napi): add Database / Connection / Statement / ResultStream napi classes
Lands the four #[napi] classes that expose the kernel's v0 surface: - Database.open() returns a Database handle (Session) - Connection.execute_statement() returns a Statement handle - Statement.fetch_next_batch() / .schema() / .cancel() / .close() - ResultStream (used internally; not directly exposed) Results cross the FFI as Arrow IPC bytes (see result.rs); the TS adapter decodes them via apache-arrow. Builds on the skeleton commit; cargo check is clean. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
1 parent 619cfdc commit d8f7a27

5 files changed

Lines changed: 512 additions & 5 deletions

File tree

‎napi/src/connection.rs‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
// Copyright (c) 2026 Databricks, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
//! Opaque `Connection` wrapper around the kernel's `Session`.
16+
//!
17+
//! The kernel collapses ADBC's `Database` + `Connection` into a single
18+
//! `Session`. We keep the wrapper name `Connection` on the JS side because
19+
//! that matches the existing Node driver's mental model.
20+
//!
21+
//! M0 surface (Round 2):
22+
//! - `Connection.executeStatement(sql, options)` — builds a kernel
23+
//! `Statement`, sets the spec, awaits `execute()`, wraps the result
24+
//! in a JS-visible `Statement` opaque handle.
25+
//! - `Connection.close()` — explicit async close. Drop schedules a
26+
//! fire-and-forget close on the captured runtime handle if explicit
27+
//! close was never called.
28+
29+
use std::collections::HashMap;
30+
use std::sync::Arc;
31+
use tokio::sync::Mutex;
32+
33+
use databricks_sql_kernel::Session;
34+
35+
use crate::error::napi_err_from_kernel;
36+
use crate::runtime;
37+
use crate::statement::Statement;
38+
use crate::util::guarded;
39+
40+
/// JS-visible per-execute options. M0 only carries
41+
/// initialCatalog / initialSchema / sessionConfig — parameters and
42+
/// per-statement overrides land in M1.
43+
#[napi(object)]
44+
pub struct ExecuteOptions {
45+
/// Default catalog applied to this statement via session conf.
46+
pub initial_catalog: Option<String>,
47+
/// Default schema applied to this statement via session conf.
48+
pub initial_schema: Option<String>,
49+
/// Per-statement session conf overrides (forwarded to SEA
50+
/// `parameters` / Thrift `confOverlay`).
51+
pub session_config: Option<HashMap<String, String>>,
52+
}
53+
54+
/// Opaque connection handle wrapping a kernel `Session`.
55+
///
56+
/// `inner` is `Arc<Mutex<Option<Session>>>` so:
57+
/// - the Drop impl can clone the `Arc` and `.take()` the session on a
58+
/// background tokio task without holding `&mut self` (which Drop is
59+
/// forbidden from doing across an `await`),
60+
/// - `executeStatement` can share immutable access to the session via
61+
/// the `Arc<SessionInner>` clones the kernel makes internally
62+
/// (`Session::statement()` only needs `&self`).
63+
#[napi]
64+
pub struct Connection {
65+
pub(crate) inner: Arc<Mutex<Option<Session>>>,
66+
}
67+
68+
#[napi]
69+
impl Connection {
70+
/// Execute a SQL statement and return a Statement handle that
71+
/// streams batches via `fetchNextBatch()`.
72+
#[napi]
73+
pub async fn execute_statement(
74+
&self,
75+
sql: String,
76+
options: ExecuteOptions,
77+
) -> napi::Result<Statement> {
78+
let inner = Arc::clone(&self.inner);
79+
guarded(async move {
80+
let guard = inner.lock().await;
81+
let session = guard.as_ref().ok_or_else(|| {
82+
napi::Error::new(napi::Status::InvalidArg, "connection already closed")
83+
})?;
84+
85+
// Build a per-statement spec on the kernel's mutable
86+
// Statement. Session conf overrides surface through the
87+
// statement_conf overlay; M0 has no parameter binding.
88+
let mut stmt = session.statement();
89+
stmt.spec().sql(sql);
90+
91+
let mut overlay: HashMap<String, String> =
92+
options.session_config.unwrap_or_default();
93+
if let Some(catalog) = options.initial_catalog {
94+
overlay.insert("default_catalog".to_string(), catalog);
95+
}
96+
if let Some(schema) = options.initial_schema {
97+
overlay.insert("default_schema".to_string(), schema);
98+
}
99+
if !overlay.is_empty() {
100+
stmt.spec().statement_conf(overlay);
101+
}
102+
103+
let executed = stmt.execute().await.map_err(napi_err_from_kernel)?;
104+
Ok(Statement::from_executed(executed))
105+
})
106+
.await
107+
}
108+
109+
/// Explicit close. Marks the connection wrapper as closed so
110+
/// subsequent calls on this `Connection` return `InvalidArg`, then
111+
/// schedules a fire-and-forget server-side close on the runtime.
112+
///
113+
/// **Why fire-and-forget and not `Session::close().await`:** the
114+
/// kernel's `Session::close(self).await` body holds a
115+
/// `tracing::EnteredSpan` (a `!Send` type) across an `.await`, so
116+
/// the future is not `Send`. napi-rs's `execute_tokio_future` glue
117+
/// rejects non-`Send` futures, and `Handle::spawn` does too. The
118+
/// kernel's `SessionInner::Drop` already spawns the
119+
/// `delete_session` RPC on the same runtime handle the napi
120+
/// binding captured, so dropping the value is functionally
121+
/// equivalent — the difference is that JS callers can't observe a
122+
/// `delete_session` failure from `close()`. Tracked as a kernel-
123+
/// side follow-up (clone the span rather than entering it) in
124+
/// Round 3 findings.
125+
#[napi]
126+
pub async fn close(&self) -> napi::Result<()> {
127+
let inner = Arc::clone(&self.inner);
128+
guarded(async move {
129+
let _taken = {
130+
let mut guard = inner.lock().await;
131+
guard.take()
132+
};
133+
// `_taken` drops here. Kernel's `SessionInner::Drop`
134+
// spawns `delete_session` on its captured handle.
135+
Ok(())
136+
})
137+
.await
138+
}
139+
}
140+
141+
impl Drop for Connection {
142+
fn drop(&mut self) {
143+
// Fire-and-forget close on the captured runtime. If `close()`
144+
// was already called, `inner` holds `None` and the spawned
145+
// task is a trivial no-op.
146+
let Some(handle) = runtime::try_get_handle() else {
147+
// No async entry point ever ran — there's nothing to close.
148+
return;
149+
};
150+
let inner = Arc::clone(&self.inner);
151+
handle.spawn(async move {
152+
// Drop the session value on the runtime. The kernel's
153+
// `SessionInner::Drop` already spawns a fire-and-forget
154+
// `delete_session` against its own captured handle. We do
155+
// NOT call `Session::close().await` here because that
156+
// method holds a `tracing::EnteredSpan` (`!Send`) across
157+
// its body, which would conflict with `Handle::spawn`'s
158+
// `Send` bound on the future.
159+
let _taken = {
160+
let mut guard = inner.lock().await;
161+
guard.take()
162+
};
163+
// `_taken` drops here; kernel's SessionInner::Drop fires.
164+
});
165+
}
166+
}

‎napi/src/database.rs‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// Copyright (c) 2026 Databricks, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
//! `openSession()` — the binding's session-construction entry point.
16+
//!
17+
//! The kernel collapses ADBC's `Database` + `Connection` into a single
18+
//! `Session`. The TS adapter layer reconstructs a `DBSQLClient` /
19+
//! `Database` wrapper on top of this binding, so the napi surface itself
20+
//! stays flat: one free function, one opaque `Connection` class.
21+
//!
22+
//! Rationale for a free function over a static class method:
23+
//! - napi-rs v2's static-method codegen for async functions returning a
24+
//! `#[napi]` struct is fragile — the runtime registration sometimes
25+
//! omits the method from the class object. Free `#[napi]` functions
26+
//! go through a different, more stable codegen path.
27+
//! - There is no kernel-side `Database` state to wrap; everything
28+
//! meaningful lives on `Session`. A wrapper class with no fields adds
29+
//! a JS object allocation per session for no benefit.
30+
31+
use std::sync::Arc;
32+
use tokio::sync::Mutex;
33+
34+
use databricks_sql_kernel::{AuthConfig, Session};
35+
36+
use crate::connection::Connection;
37+
use crate::error::napi_err_from_kernel;
38+
use crate::runtime;
39+
use crate::util::guarded;
40+
41+
/// JS-visible options for opening a Databricks SQL session over PAT.
42+
///
43+
/// M0 supports PAT only — `token` is required. OAuth M2M / U2M variants
44+
/// land in M1 along with a discriminated-union shape on the JS side.
45+
#[napi(object)]
46+
pub struct ConnectionOptions {
47+
/// Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel
48+
/// normalises this — bare hostnames get `https://` prepended.
49+
pub host_name: String,
50+
/// JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The
51+
/// kernel parses out the warehouse id.
52+
pub http_path: String,
53+
/// Personal access token. Must be non-empty (the kernel rejects
54+
/// empty PATs at session construction).
55+
pub token: String,
56+
}
57+
58+
/// Open a Databricks SQL session over PAT auth and return an opaque
59+
/// `Connection` wrapping the kernel `Session`.
60+
///
61+
/// The JS-visible name is `openSession` (napi-rs converts snake_case
62+
/// to camelCase for free functions).
63+
#[napi]
64+
pub async fn open_session(options: ConnectionOptions) -> napi::Result<Connection> {
65+
guarded(async move {
66+
// Cache the napi-rs tokio Handle on the very first async call
67+
// so Drop impls (which run on the V8 GC thread, outside any
68+
// tokio context) can still `spawn` cleanup tasks onto the
69+
// runtime that's driving this future.
70+
let _ = runtime::get_handle();
71+
72+
// SessionConfig is `#[non_exhaustive]` — go through the
73+
// builder, which is the only public path that constructs it.
74+
// `http_path()` is the convenience setter that maps a bare
75+
// hostname + `/sql/1.0/warehouses/{id}` path into the kernel's
76+
// `ConnectionConfig`.
77+
let session = Session::builder()
78+
.http_path(options.host_name, options.http_path)
79+
.auth(AuthConfig::Pat {
80+
token: options.token,
81+
})
82+
.open()
83+
.await
84+
.map_err(napi_err_from_kernel)?;
85+
Ok(Connection {
86+
inner: Arc::new(Mutex::new(Some(session))),
87+
})
88+
})
89+
.await
90+
}

‎napi/src/lib.rs‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,10 @@
1515
//! `databricks-sea-native` — napi-rs binding crate for the Databricks
1616
//! SQL Node.js driver's SEA (Statement Execution API) path.
1717
//!
18-
//! **Skeleton commit.** This commit lands the crate's infrastructure:
19-
//! Cargo manifest, build script, error envelope formatter, tokio
20-
//! runtime helper, `tracing` logger bridge, and shared utilities.
21-
//! The actual `#[napi]` classes (`Database`, `Connection`, `Statement`,
22-
//! `ResultStream`) are added in the follow-up commit.
18+
//! Round 2 surface: `Database.open` → `Connection.execute_statement`
19+
//! → `Statement.fetch_next_batch` / `schema` / `cancel` / `close`.
20+
//! Results cross the FFI as Arrow IPC bytes (see `result.rs`); the
21+
//! TS adapter decodes them via `apache-arrow`.
2322
2423
#![deny(unsafe_op_in_unsafe_fn)]
2524
// Skeleton-PR state: every `pub(crate)` item in this crate (error
@@ -38,9 +37,13 @@
3837
#[macro_use]
3938
extern crate napi_derive;
4039

40+
pub(crate) mod connection;
41+
pub(crate) mod database;
4142
pub(crate) mod error;
4243
pub(crate) mod logger;
44+
pub(crate) mod result;
4345
pub(crate) mod runtime;
46+
pub(crate) mod statement;
4447
pub(crate) mod util;
4548

4649
/// Returns the native binding's crate version (`CARGO_PKG_VERSION`).

‎napi/src/result.rs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Copyright (c) 2026 Databricks, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
//! Arrow IPC payload types crossed across the napi boundary.
16+
//!
17+
//! Per sea-design.md Layer 2: "The binding ships the batch across the
18+
//! FFI as Arrow IPC bytes. The adapter converts those bytes into
19+
//! JavaScript rows…" — so the napi boundary is intentionally narrow:
20+
//! one envelope per batch, one envelope per schema.
21+
22+
use napi::bindgen_prelude::Buffer;
23+
24+
/// A single Arrow IPC stream payload encoding one record batch (plus
25+
/// the schema header so the JS-side reader is stateless).
26+
#[napi(object)]
27+
pub struct ArrowBatch {
28+
pub ipc_bytes: Buffer,
29+
}
30+
31+
/// An Arrow IPC stream payload encoding just the result schema (no
32+
/// record-batch messages). Returned by `Statement.schema()`.
33+
#[napi(object)]
34+
pub struct ArrowSchema {
35+
pub ipc_bytes: Buffer,
36+
}

0 commit comments

Comments
 (0)