Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
3 changes: 3 additions & 0 deletions napi/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
108 changes: 92 additions & 16 deletions napi/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>` → `Option<Identifier<'_>>`
//! or `Option<LikePattern<'_>>`, 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
//!
Expand All @@ -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;

Expand All @@ -81,10 +80,14 @@ where
F: FnOnce() -> Fut + Send + 'static,
Fut: std::future::Future<Output = KResult<ResultStream>>,
{
// 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)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — The run_on_blocking handle acquisition now diverges between build profiles: production uses crate::runtime::get_handle(), but #[cfg(test)] builds use tokio::runtime::Handle::current(). This is a reasonable way to keep the new in-crate wiremock test from mutating/racing the process-global runtime cache, but it means the napi crate's own tests (including the new empty_catalog_metadata_calls_return_empty_without_statement_request) never exercise the production get_handle() path. A regression in the global-handle capture would not be caught by these tests. The tradeoff is documented in the comment, so this is only a coverage note — consider a separate test that specifically covers the get_handle() path if it isn't covered elsewhere.

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
Expand Down Expand Up @@ -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]
Expand All @@ -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)?;
Comment thread
vuanhphung marked this conversation as resolved.
Resolved
meta.list_schemas(cat, pat).await
})
.await?;
Expand Down Expand Up @@ -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]
Expand All @@ -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
Expand Down Expand Up @@ -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<String>` → kernel-newtype conversion now lives on the
// kernel as `Identifier::from_opt` / `LikePattern::from_opt` (tested
Expand Down Expand Up @@ -384,4 +391,73 @@ mod tests {
let input: Option<String> = 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");
}
}
3 changes: 3 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 13 additions & 18 deletions pyo3/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
//!
Expand All @@ -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;
Expand All @@ -64,11 +65,8 @@ impl Metadata {
}
}

// The `Option<String>` → `Option<Identifier>` / `Option<LikePattern>`
// 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 {
Expand All @@ -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,
Expand All @@ -87,8 +86,7 @@ impl Metadata {
schema_pattern: Option<String>,
) -> PyResult<ResultStream> {
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()))
Expand Down Expand Up @@ -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,
Expand All @@ -139,11 +138,7 @@ impl Metadata {
column_pattern: Option<String>,
) -> PyResult<ResultStream> {
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
Expand Down
18 changes: 10 additions & 8 deletions pyo3/tests/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading