diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 032eb0bc..072bc95c 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -28,6 +28,9 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed +- Metadata: empty schema/column patterns now return typed empty results without + issuing a server statement. + - Metadata: `Metadata::type_info()` now matches the established Thrift `getTypeInfo` result shape and current 20-row type catalogue. diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 7d477b95..ac50fb60 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -25,6 +25,9 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Fixed +- Empty catalog filters for `listSchemas()` and `listColumns()` now match + nothing instead of returning `InvalidArgument`; non-empty catalogs stay exact. + --- *Note: When making changes, please add your change under the appropriate section with a brief description. At release time, move the entries here diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index c7fc14c8..e3585a29 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -23,10 +23,9 @@ //! 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. +//! pyo3 binding pattern. Empty exact catalog filters become empty +//! patterns (match nothing); other validation remains kernel-owned and +//! surfaces as `InvalidArgument` through the standard error envelope. //! //! ## `!Send` future workaround //! @@ -50,13 +49,13 @@ use std::sync::Arc; +use databricks_sql_kernel::metadata_v0::exact_catalog_and_pattern; use databricks_sql_kernel::{ Error as KernelError, Identifier, LikePattern, Metadata, Result as KResult, ResultStream, }; use crate::connection::{connection_closed_err, Connection}; use crate::error::napi_err_from_kernel; -use crate::runtime::get_handle; use crate::statement::Statement; use crate::util::guarded; @@ -81,10 +80,14 @@ where 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(); + // Capture the handle before entering spawn_blocking. Production uses the + // process-global napi runtime captured by the first async entry point. + // Hostless Rust tests use their current test runtime so they do not mutate + // that global and race the cold-cache runtime test. + #[cfg(not(test))] + let handle = crate::runtime::get_handle().clone(); + #[cfg(test)] + let handle = tokio::runtime::Handle::current(); // Each metadata RPC parks one blocking-pool thread for the whole wire // round-trip (the kernel futures are `!Send`; see the doc above). Bracket // it with debug breadcrumbs so a "metadata hangs under load" incident — a @@ -130,7 +133,8 @@ impl Connection { .await } - /// Schemas filtered by catalog (exact) and schema name pattern. + /// Schemas filtered by catalog (exact) and schema name pattern. An empty + /// catalog matches nothing; non-empty catalogs remain exact identifiers. /// /// JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. #[napi] @@ -142,8 +146,7 @@ impl Connection { let meta = take_metadata(&self.inner).await?; guarded(async move { let stream = run_on_blocking(move || async move { - let cat = Identifier::from_opt(&catalog)?; - let pat = LikePattern::from_opt(&schema_pattern)?; + let (cat, pat) = exact_catalog_and_pattern(&catalog, &schema_pattern)?; meta.list_schemas(cat, pat).await }) .await?; @@ -197,7 +200,8 @@ impl Connection { .await } - /// Columns of tables matching the filter. + /// Columns of tables matching the filter. An empty catalog matches + /// nothing; non-empty catalogs remain exact identifiers. /// /// JDBC `getColumns` shape: 23 columns. #[napi] @@ -211,8 +215,7 @@ impl Connection { let meta = take_metadata(&self.inner).await?; guarded(async move { let stream = run_on_blocking(move || async move { - let cat = Identifier::from_opt(&catalog)?; - let sch = LikePattern::from_opt(&schema_pattern)?; + let (cat, sch) = exact_catalog_and_pattern(&catalog, &schema_pattern)?; let tbl = LikePattern::from_opt(&table_pattern)?; let col = LikePattern::from_opt(&column_pattern)?; meta.list_columns(cat, sch, tbl, col).await @@ -351,7 +354,11 @@ impl Connection { #[cfg(test)] mod tests { use super::*; - use databricks_sql_kernel::ErrorCode; + use databricks_sql_kernel::{AuthConfig, ConnectionConfig, ErrorCode, Session}; + use serde_json::json; + use tokio::sync::Mutex; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; // The `Option` → kernel-newtype conversion now lives on the // kernel as `Identifier::from_opt` / `LikePattern::from_opt` (tested @@ -384,4 +391,73 @@ mod tests { let input: Option = None; assert!(LikePattern::from_opt(&input).unwrap().is_none()); } + + #[tokio::test] + async fn empty_catalog_metadata_calls_return_empty_without_statement_request() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({ "session_id": "sess-napi-metadata" })), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-napi-metadata")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid HTTP path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .open() + .await + .expect("session opens against mock server"); + let connection = Connection { + inner: Arc::new(Mutex::new(Some(session))), + session_id: "sess-napi-metadata".to_owned(), + }; + + let statements = [ + connection + .list_schemas(Some(String::new()), None) + .await + .expect("empty catalog returns empty schemas"), + connection + .list_columns(Some(String::new()), None, None, None) + .await + .expect("empty catalog returns empty columns"), + ]; + for statement in statements { + assert!(statement + .fetch_next_batch() + .await + .expect("empty metadata stream fetch succeeds") + .is_none()); + statement.close().await.expect("statement closes"); + } + + let requests = server.received_requests().await.unwrap_or_default(); + assert_eq!( + requests + .iter() + .filter(|request| { + request.method.as_str() == "POST" + && request.url.path() == "/api/2.0/sql/statements" + }) + .count(), + 0, + "empty catalog must short-circuit before statement execution" + ); + + connection.close().await.expect("connection closes"); + } } diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index ad41d30d..03e5e9ed 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -23,6 +23,9 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Fixed +- Empty catalog filters for `list_schemas()` and `list_columns()` now match + nothing instead of raising `InvalidArgument`; non-empty catalogs stay exact. + --- *Note: When making changes, please add your change under the appropriate section with a brief description. At release time, move the entries here diff --git a/pyo3/src/metadata.rs b/pyo3/src/metadata.rs index f2fee899..c6b69e40 100644 --- a/pyo3/src/metadata.rs +++ b/pyo3/src/metadata.rs @@ -22,9 +22,9 @@ //! patterns (`LikePattern`) at the type level. The Python surface //! collapses both back to `Option[str]` because Python lacks a //! convenient way to express two distinct string-flavoured types at -//! a call site. The kernel's runtime checks (empty, NUL, backticks -//! for identifiers; length caps for both) still apply; bad input -//! surfaces as `KernelError(code='InvalidArgument', ...)`. +//! a call site. Empty exact catalog filters are adapted to an empty +//! pattern (match nothing); other identifier and pattern validation +//! still surfaces as `KernelError(code='InvalidArgument', ...)`. //! //! ## Why the methods aren't fully macro-ised //! @@ -42,6 +42,7 @@ //! conversions stay explicit and grep-able. use crate::result_stream::ResultStream; +use databricks_sql_kernel::metadata_v0::exact_catalog_and_pattern; use databricks_sql_kernel::{Identifier, LikePattern, Metadata as KMetadata}; use pyo3::prelude::*; use std::sync::Arc; @@ -64,11 +65,8 @@ impl Metadata { } } -// The `Option` → `Option` / `Option` -// conversion lives on the kernel newtypes as `Identifier::from_opt` / -// `LikePattern::from_opt` (one home shared by all bindings, with empty / -// NUL / backtick / whitespace rejection kernel-side surfacing as -// `InvalidArgument`). Call sites below use those directly. +// Optional-string conversion lives in the kernel crate so pyo3 and napi +// share validation and empty exact-catalog semantics. #[pymethods] impl Metadata { @@ -78,7 +76,8 @@ impl Metadata { Ok(ResultStream::new(stream, self.runtime.clone())) } - /// Schemas filtered by catalog (exact) and schema name pattern. + /// Schemas filtered by catalog (exact) and schema name pattern. An empty + /// catalog matches nothing; non-empty catalogs remain exact identifiers. #[pyo3(signature = (*, catalog=None, schema_pattern=None))] fn list_schemas( &self, @@ -87,8 +86,7 @@ impl Metadata { schema_pattern: Option, ) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { - let cat = Identifier::from_opt(&catalog)?; - let pat = LikePattern::from_opt(&schema_pattern)?; + let (cat, pat) = exact_catalog_and_pattern(&catalog, &schema_pattern)?; self.inner.list_schemas(cat, pat).await })?; Ok(ResultStream::new(stream, self.runtime.clone())) @@ -127,8 +125,9 @@ impl Metadata { } /// Columns of tables matching the filter. `catalog = None` emits - /// `SHOW COLUMNS IN ALL CATALOGS`; otherwise scoped to the named - /// catalog. Schema / table / column patterns are SQL LIKE. + /// `SHOW COLUMNS IN ALL CATALOGS`; an empty catalog matches nothing; + /// otherwise the catalog is exact. Schema / table / column patterns are + /// SQL LIKE. #[pyo3(signature = (*, catalog=None, schema_pattern=None, table_pattern=None, column_pattern=None))] fn list_columns( &self, @@ -139,11 +138,7 @@ impl Metadata { column_pattern: Option, ) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { - let cat = match catalog.as_deref() { - Some(s) => Some(Identifier::new(s)?), - None => None, - }; - let sch = LikePattern::from_opt(&schema_pattern)?; + let (cat, sch) = exact_catalog_and_pattern(&catalog, &schema_pattern)?; let tbl = LikePattern::from_opt(&table_pattern)?; let col = LikePattern::from_opt(&column_pattern)?; self.inner.list_columns(cat, sch, tbl, col).await diff --git a/pyo3/tests/test_metadata.py b/pyo3/tests/test_metadata.py index c9c57d58..782a7140 100644 --- a/pyo3/tests/test_metadata.py +++ b/pyo3/tests/test_metadata.py @@ -100,14 +100,16 @@ def test_table_types_is_static(session): @live -def test_empty_identifier_rejected(session): - try: - session.metadata().list_schemas(catalog="") - except k.KernelError as e: - assert e.code == "InvalidArgument", e.code - assert "identifier" in e.message.lower(), e.message - else: - raise AssertionError("expected KernelError for empty catalog") +def test_empty_catalog_matches_nothing(session): + metadata = session.metadata() + for result in ( + metadata.list_schemas(catalog=""), + metadata.list_columns(catalog=""), + ): + try: + assert result.fetch_all_arrow().num_rows == 0 + finally: + result.close() @live diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index c7d5883e..2f55875c 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -293,6 +293,30 @@ impl<'a> LikePattern<'a> { } } +/// Convert binding-layer optional strings for an exact catalog plus a +/// pattern filter. +/// +/// Non-empty catalogs remain exact [`Identifier`]s. An empty catalog cannot +/// be represented as an `Identifier`, but JDBC metadata semantics require it +/// to match nothing rather than fail validation. Encode that case as an empty +/// [`LikePattern`] on the accompanying pattern dimension; metadata methods +/// short-circuit empty patterns to a typed empty result before any wire call. +pub fn exact_catalog_and_pattern<'a>( + catalog: &'a Option, + pattern: &'a Option, +) -> Result<(Option>, Option>)> { + if catalog.as_deref() == Some("") { + // `None` alone means all catalogs. It is safe here only because the + // paired empty pattern is checked before list_schemas/list_columns + // reach the transport; keep that short-circuit ahead of any wire call. + return Ok((None, Some(LikePattern::new("")?))); + } + Ok(( + Identifier::from_opt(catalog)?, + LikePattern::from_opt(pattern)?, + )) +} + // ─── Metadata API ─────────────────────────────────────────────────────────── /// Flat catalog-metadata API bound to a session. @@ -336,6 +360,7 @@ impl Metadata { } /// Schemas filtered by catalog (exact) and schema name pattern. + /// An empty schema pattern returns an empty result without a wire call. /// /// JDBC `getSchemas` shape: `TABLE_SCHEM: Utf8 (not null), /// TABLE_CATALOG: Utf8`. When the underlying server response omits @@ -348,6 +373,15 @@ impl Metadata { ) -> Result { let span = self.session.log_span().clone(); async { + if schema_pattern + .as_ref() + .is_some_and(|pattern| pattern.as_str().is_empty()) + { + return ResultStream::from_reader(Box::new(EmptyReader::new( + GET_SCHEMAS_SCHEMA.clone(), + ))) + .await; + } let catalog_str = catalog.as_ref().map(|i| i.as_str().to_owned()); let raw = match self .session @@ -741,6 +775,8 @@ impl Metadata { /// Columns of tables matching the filter. Catalog is optional and /// exact; schema / table / column are patterns. + /// An empty schema, table, or column pattern returns an empty result + /// without a wire call. /// /// `catalog = None` emits `SHOW COLUMNS IN ALL CATALOGS` and /// returns rows from every catalog visible to the session. The @@ -772,6 +808,19 @@ impl Metadata { ) -> Result { let span = self.session.log_span().clone(); async { + if [&schema_pattern, &table_pattern, &column_pattern] + .into_iter() + .any(|pattern| { + pattern + .as_ref() + .is_some_and(|pattern| pattern.as_str().is_empty()) + }) + { + return ResultStream::from_reader(Box::new(EmptyReader::new( + GET_COLUMNS_SCHEMA.clone(), + ))) + .await; + } let catalog_str = catalog.as_ref().map(|i| i.as_str().to_owned()); let raw = match self .session @@ -1189,6 +1238,26 @@ mod tests { assert_eq!(p.as_str(), ""); } + #[test] + fn exact_catalog_and_pattern_keeps_non_empty_catalog_exact() { + let catalog = Some("my_catalog".to_owned()); + let pattern = Some("schema%".to_owned()); + let (catalog, pattern) = exact_catalog_and_pattern(&catalog, &pattern).unwrap(); + + assert_eq!(catalog.unwrap().as_str(), "my_catalog"); + assert_eq!(pattern.unwrap().as_str(), "schema%"); + } + + #[test] + fn exact_catalog_and_pattern_routes_empty_catalog_to_empty_pattern() { + let catalog = Some(String::new()); + let original_pattern = Some("ignored%".to_owned()); + let (catalog, pattern) = exact_catalog_and_pattern(&catalog, &original_pattern).unwrap(); + + assert!(catalog.is_none()); + assert_eq!(pattern.unwrap().as_str(), ""); + } + #[test] fn like_pattern_rejects_nul_byte() { let err = LikePattern::new("foo\0bar").expect_err("NUL byte rejected"); diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 44147a7c..e53da72d 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -37,6 +37,7 @@ use arrow_array::{Array, ArrayRef, RecordBatch, StringArray}; use arrow_ipc::writer::StreamWriter; use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; +use databricks_sql_kernel::metadata_v0::exact_catalog_and_pattern; use databricks_sql_kernel::{ AuthConfig, ConnectionConfig, Identifier, LikePattern, ResultBatch, Session, }; @@ -378,6 +379,28 @@ async fn list_schemas_literal_percent_catalog_scopes_verbatim_and_empties() { assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 0); } +#[tokio::test] +async fn list_schemas_empty_catalog_matches_nothing_without_wire_call() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let catalog = Some(String::new()); + let requested_pattern = Some("ignored%".to_owned()); + let (catalog, schema_pattern) = + exact_catalog_and_pattern(&catalog, &requested_pattern).unwrap(); + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_schemas(catalog, schema_pattern) + .await + .expect("empty catalog returns empty schemas"); + + assert_eq!(col_names(&stream.schema())[0], "TABLE_SCHEM"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 0); +} + #[tokio::test] async fn list_tables_escaped_percent_catalog_scopes_verbatim_and_empties() { // Conformance (METADATA-037, escaping ON): an *escaped* catalog @@ -1023,6 +1046,74 @@ async fn list_columns_without_catalog_emits_all_catalogs_query() { ); } +#[tokio::test] +async fn list_columns_empty_catalog_matches_nothing_without_wire_call() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let catalog = Some(String::new()); + let requested_pattern = Some("ignored%".to_owned()); + let (catalog, schema_pattern) = + exact_catalog_and_pattern(&catalog, &requested_pattern).unwrap(); + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_columns(catalog, schema_pattern, None, None) + .await + .expect("empty catalog returns empty columns"); + + assert_eq!(col_names(&stream.schema())[0], "TABLE_CAT"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 0); +} + +#[tokio::test] +async fn list_columns_empty_table_pattern_matches_nothing_without_wire_call() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_columns( + Some(Identifier::new("main").unwrap()), + None, + Some(LikePattern::new("").unwrap()), + None, + ) + .await + .expect("empty table pattern returns empty columns"); + + assert_eq!(col_names(&stream.schema())[0], "TABLE_CAT"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 0); +} + +#[tokio::test] +async fn list_columns_empty_column_pattern_matches_nothing_without_wire_call() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_columns( + Some(Identifier::new("main").unwrap()), + None, + None, + Some(LikePattern::new("").unwrap()), + ) + .await + .expect("empty column pattern returns empty columns"); + + assert_eq!(col_names(&stream.schema())[0], "TABLE_CAT"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 0); +} + #[tokio::test] async fn primary_keys_reshaped_to_jdbc_columns() { let server = MockServer::start().await;