|
| 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 | +} |
0 commit comments