From 1449e237762287de40301a96c2558f8c619a261e Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 20 May 2026 22:36:44 +0000 Subject: [PATCH 1/6] feat(napi): expose 10 metadata methods on Connection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Statement::from_result_stream (internal constructor wrapping a bare ResultStream) and a new napi/src/metadata.rs that wires all 10 kernel Metadata methods onto the JS Connection class: listCatalogs, listSchemas, listTables, listColumns, listFunctions, listProcedures, listTableTypes, listTypeInfo, getPrimaryKeys, getCrossReference Each returns the same Statement type as executeStatement so the JS SeaOperationBackend wraps them uniformly. Cancel on metadata-derived Statements is a no-op (no server-side cancellation surface today). The kernel Metadata methods hold a tracing::EnteredSpan (!Send) across their await points. The fix: acquire the session lock, clone the Send Metadata handle, drop the lock, then run the !Send future inside tokio::task::spawn_blocking via Handle::block_on — a standard pattern for escaping the Send bound without LocalSet. Also fixes: - pre-existing unused StatementState import in src/client/transport.rs - pre-existing dead_code lint on open_session + ConnectionOptions in napi/src/database.rs (exported via napi macro codegen, not called from Rust directly) - AnyInner::Executed variant boxed to satisfy large_enum_variant lint Signed-off-by: Madhavendra Rathore --- napi/src/lib.rs | 1 + napi/src/metadata.rs | 326 ++++++++++++++++++++++++++++++++++++++++++ napi/src/statement.rs | 144 ++++++++++++++----- 3 files changed, 433 insertions(+), 38 deletions(-) create mode 100644 napi/src/metadata.rs diff --git a/napi/src/lib.rs b/napi/src/lib.rs index d1751a44..53d97cb1 100644 --- a/napi/src/lib.rs +++ b/napi/src/lib.rs @@ -43,6 +43,7 @@ pub(crate) mod connection; pub(crate) mod database; pub(crate) mod error; pub(crate) mod logger; +pub(crate) mod metadata; pub(crate) mod result; pub(crate) mod runtime; pub(crate) mod statement; diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs new file mode 100644 index 00000000..4623251f --- /dev/null +++ b/napi/src/metadata.rs @@ -0,0 +1,326 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Metadata methods on `Connection` — napi-rs layer over the kernel's +//! flat `Metadata` API. +//! +//! Each method mirrors a `databricks_sql_kernel::Metadata` method +//! one-to-one and returns the same `Statement` type that +//! `executeStatement` returns, so the JS side can wrap any result in +//! `SeaOperationBackend` uniformly. The `Statement` is constructed via +//! `Statement::from_result_stream` — no parent kernel `Statement` is +//! involved (metadata calls don't use the mutable `Statement` path). +//! +//! Parameter mapping from JS strings to kernel newtypes follows the +//! pyo3 binding pattern: `Option` → `Option>` +//! or `Option>`, with runtime validation left to the +//! kernel. Rejected inputs surface as `InvalidArgument` via the +//! standard kernel-error envelope. +//! +//! ## `!Send` future workaround +//! +//! The kernel's `Metadata` methods hold a `tracing::EnteredSpan` +//! (`!Send`) across their internal `.await` points, making each +//! method's future `!Send`. napi-rs requires the top-level async fn +//! future to be `Send`. The fix: acquire the lock, clone a `Metadata` +//! handle (`Send + Sync` — wraps `Arc`), release the +//! lock, and then run the `!Send` kernel future inside +//! `tokio::task::spawn_blocking` via `Handle::block_on`. A blocking +//! thread is outside the tokio executor's scheduler, so `block_on` is +//! safe there and the `!Send` constraint does not propagate to the +//! enclosing `Send` async fn. +//! +//! ## Cancel on metadata `Statement`s +//! +//! Cancel is a no-op for metadata streams: the kernel has no +//! in-flight cancellation surface for metadata calls today. This is +//! documented on `Statement::cancel` and tracked as a kernel follow-up +//! for v1. + +use std::sync::Arc; + +use databricks_sql_kernel::{Identifier, LikePattern, Metadata, Result as KResult, ResultStream}; +use tokio::runtime::Handle; + +use crate::connection::Connection; +use crate::error::napi_err_from_kernel; +use crate::runtime::get_handle; +use crate::statement::Statement; +use crate::util::guarded; + +// ─── Conversion helpers ───────────────────────────────────────────────────── + +fn opt_identifier(s: &Option) -> KResult>> { + s.as_deref().map(Identifier::new).transpose() +} + +fn opt_pattern(s: &Option) -> KResult>> { + s.as_deref().map(LikePattern::new).transpose() +} + +/// Run a `!Send` async kernel metadata operation on a blocking thread. +/// +/// `Metadata` itself is `Send + 'static` (wraps `Arc`). +/// The *futures* its methods return are `!Send` because they hold a +/// `tracing::EnteredSpan` across internal await points. Running them +/// inside `spawn_blocking` moves execution to a thread-pool thread +/// where `Handle::block_on` is safe and the `!Send` constraint doesn't +/// infect the enclosing napi async fn. +async fn run_on_blocking(f: F) -> napi::Result +where + F: FnOnce(Handle) -> Fut + Send + 'static, + Fut: std::future::Future>, +{ + // Capture the handle before entering spawn_blocking; get_handle() + // must be called from inside an async context (it snapshots + // Handle::current() on first call). + let handle = get_handle().clone(); + let stream = tokio::task::spawn_blocking(move || handle.block_on(f(handle.clone()))) + .await + .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))? + .map_err(napi_err_from_kernel)?; + Ok(stream) +} + +/// Acquire the lock, return a `Metadata` handle, and release the lock. +async fn take_metadata( + inner: &Arc>>, +) -> napi::Result { + let guard = inner.lock().await; + let session = guard + .as_ref() + .ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, "connection already closed"))?; + Ok(session.metadata()) +} + +// ─── Metadata impls on Connection ─────────────────────────────────────────── + +#[napi] +impl Connection { + /// All catalogs visible to the session. + /// + /// JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. + #[napi] + pub async fn list_catalogs(&self) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = + run_on_blocking(move |_h| async move { meta.list_catalogs().await }).await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Schemas filtered by catalog (exact) and schema name pattern. + /// + /// JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. + #[napi] + pub async fn list_schemas( + &self, + catalog: Option, + schema_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let pat = opt_pattern(&schema_pattern)?; + meta.list_schemas(cat, pat).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Tables filtered by catalog (exact), schema (pattern), table (pattern). + /// + /// JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, + /// filters rows by `TABLE_TYPE` kernel-side. + #[napi] + pub async fn list_tables( + &self, + catalog: Option, + schema_pattern: Option, + table_pattern: Option, + table_types: Option>, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let types_owned: Option> = table_types + .as_ref() + .map(|v| v.iter().map(String::as_str).collect()); + let types_slice: Option<&[&str]> = types_owned.as_deref(); + meta.list_tables(cat, sch, tbl, types_slice).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Columns of tables matching the filter. + /// + /// JDBC `getColumns` shape: 23 columns. + #[napi] + pub async fn list_columns( + &self, + catalog: Option, + schema_pattern: Option, + table_pattern: Option, + column_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let col = opt_pattern(&column_pattern)?; + meta.list_columns(cat, sch, tbl, col).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Functions visible to the session. `catalog` is exact; + /// `schemaPattern` and `functionPattern` are SQL LIKE. + #[napi] + pub async fn list_functions( + &self, + catalog: Option, + schema_pattern: Option, + function_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&function_pattern)?; + meta.functions(cat, sch, nam).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Procedures visible to the session. `catalog` is exact; + /// `schemaPattern` and `procedurePattern` are SQL LIKE. + #[napi] + pub async fn list_procedures( + &self, + catalog: Option, + schema_pattern: Option, + procedure_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&procedure_pattern)?; + meta.procedures(cat, sch, nam).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). + /// No wire call — static in-memory result. + #[napi] + pub async fn list_table_types(&self) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { meta.table_types().await }).await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// SQL data types supported by the workspace. + /// No wire call — static in-memory result. + #[napi] + pub async fn list_type_info(&self) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { meta.type_info().await }).await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Primary keys for the given table. All three identifiers are + /// exact — ODBC `SQLPrimaryKeys` does not support patterns. + #[napi] + pub async fn get_primary_keys( + &self, + catalog: String, + schema: String, + table: String, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = Some(Identifier::new(&catalog)?); + let sch = Some(Identifier::new(&schema)?); + let tbl = Identifier::new(&table)?; + meta.primary_keys(cat, sch, tbl).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Foreign-key relationships. The foreign side must be fully + /// specified (catalog + schema + table); the parent side is + /// optional. All identifiers are exact — no LIKE patterns. + #[napi] + #[allow(clippy::too_many_arguments)] + pub async fn get_cross_reference( + &self, + parent_catalog: Option, + parent_schema: Option, + parent_table: Option, + foreign_catalog: String, + foreign_schema: String, + foreign_table: String, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let pc = opt_identifier(&parent_catalog)?; + let ps = opt_identifier(&parent_schema)?; + let pt = opt_identifier(&parent_table)?; + let fc = Some(Identifier::new(&foreign_catalog)?); + let fs = Some(Identifier::new(&foreign_schema)?); + let ft = Some(Identifier::new(&foreign_table)?); + meta.foreign_keys(pc, ps, pt, fc, fs, ft).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } +} diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 84c734e2..7b5725a9 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -36,7 +36,7 @@ use tokio::sync::Mutex; use arrow_ipc::writer::StreamWriter; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ - Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, + Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, ResultStream, Statement as KernelStatement, }; @@ -70,6 +70,30 @@ struct StatementInner { executed: ExecutedStatement, } +/// Discriminated inner state for `Statement`. +enum AnyInner { + /// Produced by `Connection::execute_statement`. Boxed to keep the + /// enum size close to the `Metadata` variant (StatementInner is + /// large; ResultStream is much smaller). + Executed(Box), + /// Produced by metadata methods — wraps a bare `ResultStream`. + Metadata(ResultStream), +} + +impl AnyInner { + /// Borrow the underlying result stream regardless of variant. The + /// executed-statement variant delegates to its + /// `ExecutedStatement::result_stream_mut`; the metadata variant + /// returns the bare `ResultStream` directly. Used by + /// `fetch_next_batch` to share one streaming path across both. + fn result_stream_mut(&mut self) -> &mut ResultStream { + match self { + AnyInner::Executed(s) => s.executed.result_stream_mut(), + AnyInner::Metadata(rs) => rs, + } + } +} + /// Opaque executed-statement handle. /// /// **Current concurrency shape** — every method takes `inner.lock()` @@ -88,21 +112,31 @@ struct StatementInner { /// disposed statement can still read them. #[napi] pub struct Statement { - /// Wraps the kernel `Statement` + `ExecutedStatement` pair so the - /// parent's `Drop` doesn't fire (and invalidate the executed - /// handle via the shared `ValidityFlag`) while JS still holds - /// this wrapper. See `StatementInner` docs above. - inner: Arc>>, + /// Discriminated inner state: the `Executed` variant wraps the + /// kernel `Statement` + `ExecutedStatement` pair (the parent kept + /// alive to prevent its `Drop` from invalidating the executed + /// handle via the shared `ValidityFlag`); the `Metadata` variant + /// wraps a bare `ResultStream` produced by `Metadata::list_*` / + /// `primary_keys` / `foreign_keys` / `type_info` / `table_types`. + inner: Arc>>, /// Schema captured at construction. Available even after `close()`. + /// For the `Executed` variant this is the executed handle's + /// schema; for the `Metadata` variant it's the result-stream's + /// schema. Either way, cached so JS callers can build error + /// reports against a disposed statement. schema: SchemaRef, - /// Server-issued id. Available even after `close()` for log - /// correlation. + /// Server-issued statement id. Populated for the `Executed` + /// variant; empty string for the `Metadata` variant (the kernel + /// does not emit a statement id for SHOW/information_schema + /// queries driven through `Metadata`). statement_id: String, /// Set to `true` when `fetchNextBatch` observes the natural end of /// the stream (`None`). `cancel()` short-circuits to `Ok(())` when /// this is set, matching the JDBC `Statement.cancel()` no-op-after- /// completion contract — without it, a defensive cancel after the /// stream is drained surfaces an opaque server-side error. + /// (Irrelevant for the `Metadata` variant where cancel is already + /// a no-op kernel-side; harmless to carry the field regardless.) finished: Arc, } @@ -119,15 +153,37 @@ impl Statement { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); Self { - inner: Arc::new(Mutex::new(Some(StatementInner { - _parent: parent, - executed, - }))), + inner: Arc::new(Mutex::new(Some(AnyInner::Executed(Box::new( + StatementInner { + _parent: parent, + executed, + }, + ))))), schema, statement_id, finished: Arc::new(AtomicBool::new(false)), } } + + /// Crate-internal constructor for metadata calls. Wraps a bare + /// `ResultStream` returned by `Metadata::list_*` / `primary_keys` / + /// `foreign_keys` / `type_info` / `table_types`. Cancel is a no-op + /// for metadata streams (the kernel has no in-flight cancellation + /// surface for them); close just drops the stream. + /// + /// `schema` is captured from the stream so the `schema()` getter + /// works after close. `statement_id` is empty (kernel does not + /// emit one for metadata queries). `finished` defaults false and + /// is unread on this path (cancel is already a no-op). + pub(crate) fn from_result_stream(stream: ResultStream) -> Self { + let schema = stream.schema(); + Self { + inner: Arc::new(Mutex::new(Some(AnyInner::Metadata(stream)))), + schema, + statement_id: String::new(), + finished: Arc::new(AtomicBool::new(false)), + } + } } #[napi] @@ -261,9 +317,14 @@ impl Statement { guarded(async move { let mut guard = inner.lock().await; let inner_state = guard.as_mut().ok_or_else(statement_closed_err)?; - let executed = &mut inner_state.executed; - - let stream = executed.result_stream_mut(); + // `result_stream_mut` returns `&mut ResultStream` for both + // variants — the executed-path borrows from its + // `ExecutedStatement`, the metadata-path borrows from its + // bare `ResultStream`. The IPC schema header serialised + // into every batch payload comes from the cached + // `self.schema` captured outside the lock (see method + // start), so no need to re-fetch from the stream. + let stream = inner_state.result_stream_mut(); let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; let Some(batch) = maybe_batch else { // End of stream — record so a defensive cancel after @@ -329,11 +390,15 @@ impl Statement { /// Server-side cancel. /// - /// Short-circuits to `Ok(())` if `fetchNextBatch` has already - /// returned `null` (stream naturally exhausted) — matches the - /// JDBC `Statement.cancel()` no-op-after-completion contract, so - /// JS callers can fire cancel defensively without distinguishing - /// "real cancel" from "raced with natural completion." + /// For executed statements: short-circuits to `Ok(())` if + /// `fetchNextBatch` has already returned `null` (stream + /// naturally exhausted) — matches the JDBC `Statement.cancel()` + /// no-op-after-completion contract, so JS callers can fire cancel + /// defensively without distinguishing "real cancel" from "raced + /// with natural completion." + /// + /// For metadata streams: no-op (the kernel has no in-flight + /// cancellation surface for metadata calls today). /// /// Returns `KernelError(InvalidStatementHandle)` if the statement /// has been explicitly `close()`d. @@ -347,17 +412,19 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - inner_state - .executed - .cancel() - .await - .map_err(napi_err_from_kernel) + match inner_state { + AnyInner::Executed(s) => s.executed.cancel().await.map_err(napi_err_from_kernel), + // Metadata streams have no server-side cancel handle. + AnyInner::Metadata(_) => Ok(()), + } }) .await } - /// Explicit close. Awaits the server-side `CloseStatement` so the - /// JS caller can observe failures (auth revoked mid-session, + /// Explicit close. + /// + /// For executed statements: awaits the server-side `CloseStatement` + /// so the JS caller can observe failures (auth revoked mid-session, /// network error, server-side error). Idempotent — a second call /// on an already-closed statement returns `Ok`. /// @@ -373,26 +440,27 @@ impl Statement { /// runtime. The JS caller can log the error but cannot drive a /// further retry. If you need retry-on-failure semantics for /// `CloseStatement`, layer them above this method. + /// + /// For metadata streams: drops the stream (no server round-trip + /// needed — metadata results have no in-flight server-side + /// resource to release). #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); guarded(async move { // Take the inner state out so `Drop` knows there's nothing - // left to clean up. The parent kernel `Statement`'s Drop - // runs here too — but only AFTER the executed handle's - // close has finished, so we still observe a clean - // server-side close result before the validity flag flips. + // left to clean up. let inner_state = { let mut guard = inner.lock().await; guard.take() }; - if let Some(inner_state) = inner_state { - inner_state - .executed - .close() - .await - .map_err(napi_err_from_kernel)?; - // _parent drops here, after close has resolved. + match inner_state { + Some(AnyInner::Executed(s)) => { + s.executed.close().await.map_err(napi_err_from_kernel)?; + // _parent drops here, after close has resolved. + } + // Metadata stream: just drop it. + Some(AnyInner::Metadata(_)) | None => {} } Ok(()) }) From d2d9fd68c535833a3c2147f7c695f01d8939f8f0 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 20 May 2026 23:10:23 +0000 Subject: [PATCH 2/6] fix(napi/metadata): remove footgun Handle param + reject whitespace-only identifiers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit H1: `run_on_blocking`'s closure type was `FnOnce(Handle) -> Fut`, giving callers access to the runtime handle inside a `spawn_blocking` thread. Any future caller using that handle to call `block_on_in_runtime` would trigger `block_in_place` inside a blocking thread — the PECOBLR-2917 abort vector. Drop the parameter; callers that needed it for `Handle::block_on` already have a captured `handle`. All 10 call sites updated from `move |_h|` to `move ||`. H2: `Identifier::new` and `LikePattern::new` accepted whitespace-only strings (e.g., `" "`) that would produce meaningless or empty tokens at the SQL layer. Add `s.trim().is_empty()` guard after the `s.is_empty()` check in both. Two unit tests added covering space, tab, newline, and mixed whitespace inputs. Signed-off-by: Madhavendra Rathore --- napi/src/metadata.rs | 24 ++++++++++++------------ src/metadata_v0.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 12 deletions(-) diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index 4623251f..e8e4212a 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -79,14 +79,14 @@ fn opt_pattern(s: &Option) -> KResult>> { /// infect the enclosing napi async fn. async fn run_on_blocking(f: F) -> napi::Result where - F: FnOnce(Handle) -> Fut + Send + 'static, + F: FnOnce() -> Fut + Send + 'static, Fut: std::future::Future>, { // Capture the handle before entering spawn_blocking; get_handle() // must be called from inside an async context (it snapshots // Handle::current() on first call). let handle = get_handle().clone(); - let stream = tokio::task::spawn_blocking(move || handle.block_on(f(handle.clone()))) + let stream = tokio::task::spawn_blocking(move || handle.block_on(f())) .await .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))? .map_err(napi_err_from_kernel)?; @@ -116,7 +116,7 @@ impl Connection { let meta = take_metadata(&self.inner).await?; guarded(async move { let stream = - run_on_blocking(move |_h| async move { meta.list_catalogs().await }).await?; + run_on_blocking(move || async move { meta.list_catalogs().await }).await?; Ok(Statement::from_result_stream(stream)) }) .await @@ -133,7 +133,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let pat = opt_pattern(&schema_pattern)?; meta.list_schemas(cat, pat).await @@ -158,7 +158,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let sch = opt_pattern(&schema_pattern)?; let tbl = opt_pattern(&table_pattern)?; @@ -187,7 +187,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let sch = opt_pattern(&schema_pattern)?; let tbl = opt_pattern(&table_pattern)?; @@ -211,7 +211,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let sch = opt_pattern(&schema_pattern)?; let nam = opt_pattern(&function_pattern)?; @@ -234,7 +234,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let sch = opt_pattern(&schema_pattern)?; let nam = opt_pattern(&procedure_pattern)?; @@ -252,7 +252,7 @@ impl Connection { pub async fn list_table_types(&self) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { meta.table_types().await }).await?; + let stream = run_on_blocking(move || async move { meta.table_types().await }).await?; Ok(Statement::from_result_stream(stream)) }) .await @@ -264,7 +264,7 @@ impl Connection { pub async fn list_type_info(&self) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { meta.type_info().await }).await?; + let stream = run_on_blocking(move || async move { meta.type_info().await }).await?; Ok(Statement::from_result_stream(stream)) }) .await @@ -281,7 +281,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = Some(Identifier::new(&catalog)?); let sch = Some(Identifier::new(&schema)?); let tbl = Identifier::new(&table)?; @@ -309,7 +309,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let pc = opt_identifier(&parent_catalog)?; let ps = opt_identifier(&parent_schema)?; let pt = opt_identifier(&parent_table)?; diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index cca8ea02..76b5a455 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -148,6 +148,9 @@ impl<'a> Identifier<'a> { if s.is_empty() { return Err(Error::invalid_argument().message("identifier must not be empty")); } + if s.trim().is_empty() { + return Err(Error::invalid_argument().message("identifier must not be all whitespace")); + } if s.len() > MAX_IDENTIFIER_BYTES { return Err(Error::invalid_argument().message(format!( "identifier exceeds {MAX_IDENTIFIER_BYTES}-byte limit ({} bytes)", @@ -206,6 +209,10 @@ impl<'a> LikePattern<'a> { return Err(Error::invalid_argument() .message("LIKE pattern must not be empty (pass None for \"match all\")")); } + if s.trim().is_empty() { + return Err(Error::invalid_argument() + .message("LIKE pattern must not be all whitespace (pass None for \"match all\")")); + } if s.len() > MAX_LIKE_PATTERN_BYTES { return Err(Error::invalid_argument().message(format!( "LIKE pattern exceeds {MAX_LIKE_PATTERN_BYTES}-byte limit ({} bytes)", @@ -669,4 +676,30 @@ mod tests { let err = LikePattern::new(&s).expect_err("oversize pattern rejected"); assert_eq!(err.code, ErrorCode::InvalidArgument); } + + #[test] + fn identifier_rejects_whitespace_only() { + for s in &[" ", "\t", "\n", " \t "] { + let err = Identifier::new(s).expect_err("whitespace-only identifier rejected"); + assert_eq!(err.code, ErrorCode::InvalidArgument); + assert!( + err.message.contains("whitespace"), + "expected 'whitespace' in: {}", + err.message + ); + } + } + + #[test] + fn like_pattern_rejects_whitespace_only() { + for s in &[" ", "\t", "\n", " \t "] { + let err = LikePattern::new(s).expect_err("whitespace-only pattern rejected"); + assert_eq!(err.code, ErrorCode::InvalidArgument); + assert!( + err.message.contains("whitespace"), + "expected 'whitespace' in: {}", + err.message + ); + } + } } From 19a468df237f08fd134a88b50e388efc54fbc19f Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 20 May 2026 23:13:56 +0000 Subject: [PATCH 3/6] docs(napi): document tableTypes advisory-filter behavior in list_tables Databricks SHOW TABLES does not accept a table-type filter server-side; the kernel applies it client-side after the result returns. Mirror the language already present in src/metadata_v0.rs:310-313 so napi callers are not misled into expecting server-side enforcement. Signed-off-by: Madhavendra Rathore --- napi/src/metadata.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index e8e4212a..b5caf147 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -148,6 +148,11 @@ impl Connection { /// /// JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, /// filters rows by `TABLE_TYPE` kernel-side. + /// + /// `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does + /// NOT honour the table-type filter server-side; the kernel applies + /// it client-side after the result returns. Callers expecting + /// server-side rejection of off-type tables should not rely on this. #[napi] pub async fn list_tables( &self, From 58a14f5beb57c2ababe08ede9aa5611906624447 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 20 May 2026 23:44:17 +0000 Subject: [PATCH 4/6] docs(kernel): list whitespace rejection in Identifier and LikePattern docblocks The whitespace-only check was added in code but the /// Rejects: bullet list in each constructor docblock didn't mention it. Add a bullet to both Identifier::new and LikePattern::new explaining the rejection and the reason (blank token / use None for "match all"). Signed-off-by: Madhavendra Rathore --- src/metadata_v0.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index 76b5a455..c15f0b6e 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -134,6 +134,8 @@ impl<'a> Identifier<'a> { /// Rejects: /// - Empty string — meaningless as an identifier; almost always a /// bug at the wrapper layer. + /// - Strings consisting only of whitespace — would backtick-escape + /// to a blank token and produce a server-side parse error. /// - Embedded NUL bytes (`\0`) — would terminate the string at the /// first FFI / C ABI boundary and silently truncate the /// identifier in transit. @@ -197,6 +199,8 @@ impl<'a> LikePattern<'a> { /// /// Rejects: /// - Empty string — callers should pass `None` for "match all". + /// - Strings consisting only of whitespace — callers should pass + /// `None` for "match all". /// - Embedded NUL bytes — same FFI-truncation hazard as /// [`Identifier::new`]. /// - Strings exceeding 255 bytes. From 9ce6c209c9a130e7fcf51fde13941b6403f132de Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Thu, 21 May 2026 00:03:31 +0000 Subject: [PATCH 5/6] fix(napi): drop now-unused tokio::runtime::Handle import in metadata.rs Leftover from the H1 fixup that removed the `Handle` parameter from `run_on_blocking`'s signature. With no callers of `Handle` as a type remaining in metadata.rs, the import is dead and trips `cargo clippy --all-targets -- -D warnings`. Doc-comment references to `Handle::block_on` and `Handle::current()` remain (they describe behavior, not Rust paths). Signed-off-by: Madhavendra Rathore --- napi/src/metadata.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index b5caf147..05fa3077 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -51,7 +51,6 @@ use std::sync::Arc; use databricks_sql_kernel::{Identifier, LikePattern, Metadata, Result as KResult, ResultStream}; -use tokio::runtime::Handle; use crate::connection::Connection; use crate::error::napi_err_from_kernel; From 52b680f86a58ab978f37688f39bda7348a239ee9 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Mon, 1 Jun 2026 00:54:57 +0000 Subject: [PATCH 6/6] fix(napi): adapt status accessors to the AnyInner metadata enum MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebasing the metadata-methods work onto main surfaced a clean conflict: main's status accessors (num_modified_rows / display_message / diagnostic_info / error_details_json, merged via PR #23) read `inner_state.executed` directly, but the metadata work wraps the Statement inner in an `AnyInner::{Executed, Metadata}` enum (the Metadata variant holds a bare ResultStream from `Metadata::list_*`). Match on the enum: the Executed variant delegates to the executed handle as before; the Metadata variant returns None — metadata result streams carry no operation-status fields. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/statement.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 7b5725a9..72cb46e4 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -222,7 +222,11 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - Ok(inner_state.executed.num_modified_rows()) + // Metadata result streams carry no operation-status fields. + match inner_state { + AnyInner::Executed(s) => Ok(s.executed.num_modified_rows()), + AnyInner::Metadata(_) => Ok(None), + } }) .await } @@ -254,7 +258,10 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - Ok(inner_state.executed.display_message().map(str::to_owned)) + match inner_state { + AnyInner::Executed(s) => Ok(s.executed.display_message().map(str::to_owned)), + AnyInner::Metadata(_) => Ok(None), + } }) .await } @@ -270,7 +277,10 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - Ok(inner_state.executed.diagnostic_info().map(str::to_owned)) + match inner_state { + AnyInner::Executed(s) => Ok(s.executed.diagnostic_info().map(str::to_owned)), + AnyInner::Metadata(_) => Ok(None), + } }) .await } @@ -295,7 +305,10 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - Ok(inner_state.executed.error_details_json().map(str::to_owned)) + match inner_state { + AnyInner::Executed(s) => Ok(s.executed.error_details_json().map(str::to_owned)), + AnyInner::Metadata(_) => Ok(None), + } }) .await }