From 35c0e0746ea59c27f4d25a6463a7a2da95133645 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 29 Jul 2026 10:33:20 +0000 Subject: [PATCH] fix(metadata): treat list_tables catalog as a LIKE pattern MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ODBC `SQLTables` treats `CatalogName` as a pattern-value argument under the default `SQL_ATTR_METADATA_ID = SQL_FALSE`, and the Thrift protocol backs this: `TGetTablesReq.catalogName` is a `TPatternOrIdentifier`, so the server wildcards `_` / `%` in the catalog. The kernel's SEA `SHOW` path typed the catalog as an exact `Identifier`, silently dropping the wildcard — a caller passing `comparator_tests` got only that catalog, not the sibling `comparator-tests` a `_` should match. The Databricks `SHOW` grammar has no catalog-pattern position (the `LIKE` clause applies only to schema/table names). Rather than `SHOW TABLES IN ALL CATALOGS` + client-side row filtering — which scans every table in every catalog on the workspace and discards the non-matches — `list_tables` now resolves a wildcard catalog by enumerating catalogs and fanning out one scoped query per match: - Wildcard catalog (`_` / `%`, or a `*`/empty literal the `SHOW` builder would misread as "all catalogs"): `SHOW CATALOGS`, filter the names with a case-insensitive `LikeMatcher`, then run `SHOW TABLES IN CATALOG ` for each match with bounded parallelism (schema/table/type pushed down server-side). Results are concatenated and re-sorted into the JDBC row order. - Literal catalog (no active wildcards, incl. the ODBC `SQL_ATTR_METADATA_ID = SQL_TRUE` identifier case): unescape and scope server-side via `SHOW TABLES IN CATALOG ` — the fast exact path. - Empty catalog pattern: "match nothing" per `LikePattern` — an empty result with no wire call (matches the schema/table `LIKE ''` convention rather than silently broadening to all catalogs). - `None`: a single `SHOW TABLES IN ALL CATALOGS` — genuinely "every catalog", the cheapest correct query. The per-catalog fan-out is strictly cheaper than a whole-workspace scan for selective patterns (per PR review feedback), and because each query is catalog-scoped it also sidesteps the pre-DBR-16 case where `SHOW TABLES IN ALL CATALOGS` omits `catalogName` and rows can't be attributed to a catalog. An object-not-found on a per-catalog query (catalog dropped mid-enumeration) contributes zero rows, per the JDBC empty-result contract. Scope is `list_tables` only. `list_columns` and `list_schemas` keep an exact catalog identifier, matching their Thrift request fields (`TGetColumnsReq.catalogName` / `TGetSchemasReq.catalogName` are both `TIdentifier`, which "must not contain a search pattern"). Adds `pattern_has_wildcards` / `strip_jdbc_escapes` / `is_wildcard_or_empty_scope` helpers and a compiled, reusable `LikeMatcher` to the SQL builder; unit tests (matcher, escapes, merge-sort across catalogs); wiremock tests asserting the emitted SQL per routing path (literal `IN CATALOG`, wildcard fan-out, empty match-nothing); and a live-workspace e2e regression test. Wrapper call sites (pyo3 / napi / C ABI) updated for the `Identifier` -> `LikePattern` signature change. Fixes databricks/databricks-odbc#129 Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- napi/src/metadata.rs | 14 +- pyo3/src/metadata.rs | 16 +- src/c_abi/metadata.rs | 22 +- src/metadata/sql.rs | 288 ++++++++++++++++++++++++- src/metadata/thrift_shape.rs | 124 +++++++++++ src/metadata_v0.rs | 370 ++++++++++++++++++++++++++++---- tests/v0_metadata_e2e.rs | 124 ++++++++++- tests/v0_metadata_wiremock.rs | 392 +++++++++++++++++++++++++++++++++- 8 files changed, 1297 insertions(+), 53 deletions(-) diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index 95f7517d..c7fc14c8 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -152,7 +152,17 @@ impl Connection { .await } - /// Tables filtered by catalog (exact), schema (pattern), table (pattern). + /// Tables filtered by catalog (**pattern**), schema (pattern), table + /// (pattern). + /// + /// The catalog is an ODBC/JDBC LIKE pattern (`%` / `_`), matching + /// Thrift `getTables`: a wildcard catalog matches multiple catalogs; + /// a literal name (or an escaped `\_` / `\%`) takes the fast exact + /// path. `undefined`/omitted catalog means "all catalogs", while an + /// **empty string** means "match nothing" (zero rows) — pass + /// `undefined`, not `""`, for all catalogs. The catalog pattern is + /// validated (whitespace-only / NUL / >255 bytes are rejected with an + /// error). /// /// JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, /// filters rows by `TABLE_TYPE` kernel-side. @@ -172,7 +182,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 cat = LikePattern::from_opt(&catalog)?; let sch = LikePattern::from_opt(&schema_pattern)?; let tbl = LikePattern::from_opt(&table_pattern)?; let types_owned: Option> = table_types diff --git a/pyo3/src/metadata.rs b/pyo3/src/metadata.rs index 0c0a8eed..f2fee899 100644 --- a/pyo3/src/metadata.rs +++ b/pyo3/src/metadata.rs @@ -94,10 +94,16 @@ impl Metadata { Ok(ResultStream::new(stream, self.runtime.clone())) } - /// Tables filtered by catalog (exact), schema (pattern), table - /// (pattern). `table_types` is advisory — Databricks does not - /// honour it server-side; wrappers filter the returned - /// `tableType` column themselves. + /// Tables filtered by catalog (**pattern**), schema (pattern), + /// table (pattern). The catalog is an ODBC/JDBC LIKE pattern + /// (`%` / `_`), matching Thrift `getTables`; a literal catalog name + /// still works and takes the fast exact path. `catalog=None` + /// (the default) means "all catalogs", while `catalog=""` means + /// "match nothing" (zero rows) — pass `None`, not `""`, for all + /// catalogs. The catalog pattern is validated (whitespace-only / NUL + /// / >255 bytes raise `InvalidArgument`). `table_types` is advisory — + /// Databricks does not honour it server-side; wrappers filter the + /// returned `tableType` column themselves. #[pyo3(signature = (*, catalog=None, schema_pattern=None, table_pattern=None, table_types=None))] fn list_tables( &self, @@ -108,7 +114,7 @@ impl Metadata { table_types: Option>, ) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { - let cat = Identifier::from_opt(&catalog)?; + let cat = LikePattern::from_opt(&catalog)?; let sch = LikePattern::from_opt(&schema_pattern)?; let tbl = LikePattern::from_opt(&table_pattern)?; let types_owned: Option> = table_types diff --git a/src/c_abi/metadata.rs b/src/c_abi/metadata.rs index d024d8c1..0729bb94 100644 --- a/src/c_abi/metadata.rs +++ b/src/c_abi/metadata.rs @@ -173,8 +173,24 @@ pub unsafe extern "C" fn kernel_metadata_list_schemas( }) } -/// List tables filtered by catalog (exact), schema / table patterns, -/// and an optional comma-separated `table_types` filter. +/// List tables filtered by catalog (**pattern**), schema / table +/// patterns, and an optional comma-separated `table_types` filter. +/// +/// The catalog is an ODBC/JDBC LIKE pattern here (`%` / `_`), +/// matching Thrift's `TGetTablesReq.catalogName` and ODBC `SQLTables` +/// under the default `SQL_ATTR_METADATA_ID = SQL_FALSE`. A literal +/// catalog (no wildcards, or `SQL_ATTR_METADATA_ID = SQL_TRUE` +/// identifier semantics) still works — it takes the fast exact +/// single-catalog path. See [`Metadata::list_tables`](crate::metadata_v0::Metadata::list_tables). +/// +/// **Empty-string catalog:** at this C ABI boundary a `NULL` **or an +/// empty / whitespace-only** `catalog` is normalized to "all catalogs" +/// (the ODBC convention where drivers pass `""` for "no catalog +/// filter"). This differs from the Rust / pyo3 / napi surface, where an +/// empty-string catalog is a valid `LikePattern` meaning "match +/// nothing" (zero rows). C / ODBC callers who want "match nothing" +/// should not rely on `""`; the pattern-value distinction only exists +/// on the typed surfaces. /// /// # Safety /// `session` must be a live session handle; the string args, if @@ -190,7 +206,7 @@ pub unsafe extern "C" fn kernel_metadata_list_tables( ) -> KernelStatusCode { run_metadata(session, out, |session| { Box::pin(async move { - let catalog = opt_ident(catalog, "catalog")?; + let catalog = opt_pattern(catalog, "catalog")?; let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; let table_pattern = opt_pattern(table_pattern, "table_pattern")?; // Split the comma-separated table types into a borrowed slice. diff --git a/src/metadata/sql.rs b/src/metadata/sql.rs index 0df8a9d1..a5c66035 100644 --- a/src/metadata/sql.rs +++ b/src/metadata/sql.rs @@ -95,6 +95,59 @@ impl SqlCommandBuilder { result } + /// Whether an ODBC/JDBC-style pattern contains an *active* wildcard + /// (`%` or `_`) — i.e. one that is not backslash-escaped. + /// + /// Used by `list_tables` to decide whether a catalog argument needs + /// the enumerate-then-fan-out wildcard path (`SHOW CATALOGS`, filter + /// names, then `SHOW TABLES IN CATALOG ` per match) or can take + /// the fast exact single-catalog path. The Databricks `SHOW` grammar + /// has no catalog-pattern position, and the SEA backend — unlike + /// Thrift's `TGetTablesReq.catalogName` (a `TPatternOrIdentifier`) — + /// cannot wildcard the catalog server-side, so the kernel resolves + /// the pattern against catalog names client-side. + pub fn pattern_has_wildcards(pattern: &str) -> bool { + let mut escaped = false; + for ch in pattern.chars() { + if escaped { + escaped = false; + continue; + } + match ch { + '\\' => escaped = true, + '%' | '_' => return true, + _ => {} + } + } + false + } + + /// Unescape an ODBC/JDBC pattern into a literal identifier: `\%` → + /// `%`, `\_` → `_`, `\\` → `\`. A lone trailing backslash is kept. + /// + /// Only valid to call on a pattern with no *active* wildcards (see + /// [`pattern_has_wildcards`](Self::pattern_has_wildcards)); such a + /// pattern denotes an exact catalog name, and the escapes must be + /// removed before it goes into a backtick-quoted `IN CATALOG` + /// identifier. Mirrors the JDBC driver's `WildcardUtil.stripJdbcEscapes`. + pub fn strip_jdbc_escapes(pattern: &str) -> String { + let mut result = String::with_capacity(pattern.len()); + let mut chars = pattern.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == '\\' { + // Consume the escaped char literally; a lone trailing + // backslash (no following char) is emitted as-is. + match chars.next() { + Some(next) => result.push(next), + None => result.push('\\'), + } + } else { + result.push(ch); + } + } + result + } + /// Escape identifier for use in SQL (backtick-quote). /// /// Use for catalog, schema, table names in SQL statements (e.g., `` `my_catalog` ``). @@ -107,10 +160,39 @@ impl SqlCommandBuilder { fn is_null_or_wildcard(value: &Option) -> bool { match value { None => true, - Some(v) => v.is_empty() || v == "%" || v == "*", + Some(v) => Self::is_wildcard_or_empty_scope(v), } } + /// Whether a catalog string would be reinterpreted as "all catalogs" + /// (rather than an exact scope) by the `SHOW ... IN [CATALOG] …` + /// builder: the empty string, `%`, or `*`. + /// + /// The caller (`list_tables`) uses this to keep the kernel's + /// `pattern_has_wildcards` decision from disagreeing with the + /// builder: a literal catalog that lands in this set must be matched + /// client-side instead of handed to the server as a scope, else e.g. + /// a catalog literally named `*` would silently broaden to every + /// catalog. Single source of truth for [`is_null_or_wildcard`]. + pub fn is_wildcard_or_empty_scope(s: &str) -> bool { + s.is_empty() || s == "%" || s == "*" + } + + /// Whether a LIKE pattern matches **every** name — i.e. it is one or + /// more `%` and nothing else (`%`, `%%`, …). Such a catalog pattern + /// is semantically identical to "no catalog filter", so `list_tables` + /// routes it to a single `SHOW TABLES IN ALL CATALOGS` rather than + /// enumerating catalogs and fanning out one query per match (which + /// would be N round trips for what is really "everything", and would + /// let one inaccessible catalog fail the whole call). + /// + /// A lone `_` does *not* match all (it requires exactly one char), and + /// `*` is a literal char in ODBC LIKE (not a wildcard), so neither + /// qualifies — only runs of `%`. + pub fn pattern_matches_all(s: &str) -> bool { + !s.is_empty() && s.chars().all(|c| c == '%') + } + pub fn build_show_catalogs(&self) -> String { "SHOW CATALOGS".to_string() } @@ -310,6 +392,93 @@ impl SqlCommandBuilder { } } +/// A compiled, case-insensitive ODBC/JDBC LIKE matcher (`%` = any +/// sequence, `_` = any single char, `\` escapes the next char). +/// +/// The pattern is lowercased and decomposed into `char`s **once** at +/// construction so a matcher can be reused across many candidates +/// without re-lowering the invariant pattern per call — the shape +/// `list_tables` needs when filtering catalog *names* from +/// `SHOW CATALOGS` before fanning out per-catalog queries. +/// +/// Matching is anchored (the whole candidate must be consumed) and +/// case-insensitive, mirroring Databricks `SHOW` matching and the Thrift +/// server's catalog matching. Operates on Unicode scalar values (not +/// bytes) so `_` matches exactly one character. +pub struct LikeMatcher { + pattern: Vec, +} + +impl LikeMatcher { + /// Compile `pattern` (lowercased for case-insensitive matching). + pub fn new(pattern: &str) -> Self { + Self { + pattern: pattern.to_lowercase().chars().collect(), + } + } + + /// Whether `candidate` matches the compiled pattern (case-insensitive, + /// anchored: the whole candidate must be consumed). + pub fn matches(&self, candidate: &str) -> bool { + let cand: Vec = candidate.to_lowercase().chars().collect(); + Self::match_inner(&self.pattern, &cand) + } + + /// Recursive LIKE matcher over `char` slices with backtracking on + /// `%`. `pattern` may contain `\`-escaped literals. + fn match_inner(pattern: &[char], candidate: &[char]) -> bool { + let mut pi = 0; + let mut ci = 0; + while pi < pattern.len() { + match pattern[pi] { + '%' => { + // Try to match the remainder at every suffix of + // `candidate` (handles trailing / consecutive `%`). + let rest = &pattern[pi + 1..]; + if rest.is_empty() { + return true; // trailing % matches anything + } + for split in ci..=candidate.len() { + if Self::match_inner(rest, &candidate[split..]) { + return true; + } + } + return false; + } + '_' => { + if ci >= candidate.len() { + return false; + } + pi += 1; + ci += 1; + } + '\\' => { + // Escaped literal: match the next pattern char exactly. + // A trailing backslash matches a literal backslash. + let lit = if pi + 1 < pattern.len() { + pattern[pi + 1] + } else { + '\\' + }; + if ci >= candidate.len() || candidate[ci] != lit { + return false; + } + pi += if pi + 1 < pattern.len() { 2 } else { 1 }; + ci += 1; + } + lit => { + if ci >= candidate.len() || candidate[ci] != lit { + return false; + } + pi += 1; + ci += 1; + } + } + } + ci == candidate.len() + } +} + #[cfg(test)] mod tests { use super::*; @@ -695,4 +864,121 @@ mod tests { fn test_pattern_single_quote_escaped() { assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive("it's"), "it''s"); } + + // --- catalog wildcard helpers (list_tables client-side path) --- + + #[test] + fn test_pattern_has_wildcards() { + assert!(SqlCommandBuilder::pattern_has_wildcards("comp_tests")); + assert!(SqlCommandBuilder::pattern_has_wildcards("comp%")); + assert!(SqlCommandBuilder::pattern_has_wildcards("%mid_dle%")); + assert!(!SqlCommandBuilder::pattern_has_wildcards( + "comparator_tests".replace('_', r"\_").as_str() + )); + assert!(!SqlCommandBuilder::pattern_has_wildcards("plaincatalog")); + // Escaped wildcards are literals, not active wildcards. + assert!(!SqlCommandBuilder::pattern_has_wildcards(r"comp\_tests")); + assert!(!SqlCommandBuilder::pattern_has_wildcards(r"comp\%tests")); + // A `%` after an escaped backslash is active again. + assert!(SqlCommandBuilder::pattern_has_wildcards(r"comp\\%")); + } + + #[test] + fn test_strip_jdbc_escapes() { + assert_eq!( + SqlCommandBuilder::strip_jdbc_escapes(r"comp\_tests"), + "comp_tests" + ); + assert_eq!(SqlCommandBuilder::strip_jdbc_escapes(r"a\%b"), "a%b"); + assert_eq!(SqlCommandBuilder::strip_jdbc_escapes(r"a\\b"), r"a\b"); + assert_eq!(SqlCommandBuilder::strip_jdbc_escapes("plain"), "plain"); + // Lone trailing backslash is preserved. + assert_eq!(SqlCommandBuilder::strip_jdbc_escapes(r"foo\"), r"foo\"); + } + + // Terse wrapper for the compiled matcher used across these tests. + fn like(pattern: &str, candidate: &str) -> bool { + LikeMatcher::new(pattern).matches(candidate) + } + + #[test] + fn test_like_match_ci_basic() { + assert!(like("comparator_tests", "comparator-tests")); + assert!(like("comparator_tests", "comparator_tests")); + // `_` matches exactly one char, so a two-char gap must not match. + assert!(!like("comparator_tests", "comparator--tests")); + } + + #[test] + fn test_like_match_ci_percent() { + assert!(like("comp%", "comparator_tests")); + assert!(like("%tests", "comparator_tests")); + assert!(like("%para%", "comparator_tests")); + assert!(like("%", "anything")); + assert!(!like("comp%", "other")); + } + + #[test] + fn test_like_match_ci_case_insensitive() { + assert!(like("MAIN", "main")); + assert!(like("Comp%", "comparator")); + } + + #[test] + fn test_like_match_ci_escaped_literal() { + // `\_` matches a literal underscore only, not a hyphen. + assert!(like(r"comparator\_tests", "comparator_tests")); + assert!(!like(r"comparator\_tests", "comparator-tests")); + } + + #[test] + fn test_like_match_ci_anchored() { + // No implicit wildcards: pattern must match the whole candidate. + assert!(!like("comp", "comparator")); + assert!(like("comp", "comp")); + } + + #[test] + fn test_like_match_ci_empty_pattern_matches_only_empty() { + // Empty pattern is "match nothing" for any non-empty name, and + // matches only the empty string. `list_tables` never reaches the + // matcher with `""` (it short-circuits to an empty result), but + // the matcher's own contract should still be well-defined. + assert!(!like("", "anything")); + assert!(like("", "")); + } + + #[test] + fn test_matcher_reused_across_candidates() { + // A single compiled matcher must give consistent results across + // many candidates (the catalog-name fan-out reuse path). + let m = LikeMatcher::new("comparator_tests"); + assert!(m.matches("comparator-tests")); + assert!(m.matches("comparator_tests")); + assert!(!m.matches("unrelated")); + } + + #[test] + fn test_pattern_matches_all() { + // Runs of `%` match everything → single all-catalogs query. + assert!(SqlCommandBuilder::pattern_matches_all("%")); + assert!(SqlCommandBuilder::pattern_matches_all("%%")); + // A lone `_` requires exactly one char, `*` is a literal, and any + // anchoring literal narrows — none match all. + assert!(!SqlCommandBuilder::pattern_matches_all("_")); + assert!(!SqlCommandBuilder::pattern_matches_all("*")); + assert!(!SqlCommandBuilder::pattern_matches_all("%a%")); + assert!(!SqlCommandBuilder::pattern_matches_all("")); + } + + #[test] + fn test_is_wildcard_or_empty_scope() { + // These are the strings the SHOW builder reinterprets as + // "all catalogs"; `list_tables` must route them client-side. + assert!(SqlCommandBuilder::is_wildcard_or_empty_scope("")); + assert!(SqlCommandBuilder::is_wildcard_or_empty_scope("%")); + assert!(SqlCommandBuilder::is_wildcard_or_empty_scope("*")); + assert!(!SqlCommandBuilder::is_wildcard_or_empty_scope("main")); + assert!(!SqlCommandBuilder::is_wildcard_or_empty_scope("a*b")); + } } diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index 97158ad5..dc4f3cfa 100644 --- a/src/metadata/thrift_shape.rs +++ b/src/metadata/thrift_shape.rs @@ -470,6 +470,12 @@ pub(crate) fn reshape_schemas( /// that omit it (single-catalog form). `table_types`, when `Some`, /// filters rows to those whose `TABLE_TYPE` appears in the slice /// (matches JDBC `DatabaseMetaData.getTables` behaviour). +/// +/// Catalog *matching* is not done here: a wildcard catalog is resolved +/// in `list_tables` by enumerating catalogs and issuing one scoped +/// `SHOW TABLES IN CATALOG ` per match, so every batch reaching +/// this function is already attributed to a known catalog (either the +/// `catalogName` column or `requested_catalog`). pub(crate) fn reshape_tables( batch: &RecordBatch, requested_catalog: Option<&str>, @@ -538,6 +544,16 @@ pub(crate) fn reshape_tables( sort_tables(&filtered) } +/// Lex-sort a JDBC-shape getTables batch by `TABLE_TYPE, TABLE_CAT, +/// TABLE_SCHEM, TABLE_NAME` to match JDBC / Thrift row ordering. +/// +/// Exposed as [`sort_tables_batch`] so the per-catalog fan-out path in +/// `list_tables` can re-sort the *merged* result across catalogs (each +/// per-catalog `reshape_tables` sorts only its own rows). +pub(crate) fn sort_tables_batch(batch: &RecordBatch) -> Result { + sort_tables(batch) +} + /// Lex-sort a JDBC-shape getTables batch by `TABLE_TYPE, TABLE_CAT, /// TABLE_SCHEM, TABLE_NAME` to match JDBC / Thrift row ordering. fn sort_tables(batch: &RecordBatch) -> Result { @@ -1104,6 +1120,114 @@ mod tests { assert_eq!(cat_arr.value(0), "c"); } + /// Multi-catalog `SHOW TABLES IN ALL CATALOGS` shape, mirroring the + /// issue-#129 repro: two catalogs differing only by `_` vs `-`. + fn server_tables_multi_catalog() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("namespace", DataType::Utf8, false), + Field::new("tableName", DataType::Utf8, false), + Field::new("isTemporary", DataType::Boolean, false), + Field::new("information", DataType::Utf8, true), + Field::new("catalogName", DataType::Utf8, false), + Field::new("tableType", DataType::Utf8, true), + Field::new("remarks", DataType::Utf8, true), + ])); + RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec!["s", "s", "s"])), + Arc::new(StringArray::from(vec!["t1", "t2", "t3"])), + Arc::new(BooleanArray::from(vec![false, false, false])), + Arc::new(StringArray::from(vec![Some(""), Some(""), Some("")])), + Arc::new(StringArray::from(vec![ + "comparator_tests", + "comparator-tests", + "unrelated", + ])), + Arc::new(StringArray::from(vec!["TABLE", "TABLE", "TABLE"])), + Arc::new(StringArray::from(vec![Some(""), Some(""), Some("")])), + ], + ) + .unwrap() + } + + #[test] + fn tables_multi_catalog_reshape_preserves_all_rows() { + // A cross-catalog `SHOW TABLES IN ALL CATALOGS` response reshapes + // all rows and attributes each to its own `catalogName` (catalog + // *filtering* is now done by the fan-out in `list_tables`, not + // here). + let b = server_tables_multi_catalog(); + let out = reshape_tables(&b, None, None).unwrap(); + assert_eq!(out.num_rows(), 3); + let cats = out + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let got: Vec<&str> = (0..out.num_rows()).map(|i| cats.value(i)).collect(); + assert!(got.contains(&"comparator_tests")); + assert!(got.contains(&"comparator-tests")); + assert!(got.contains(&"unrelated")); + } + + #[test] + fn sort_tables_batch_merges_across_catalogs_in_jdbc_order() { + // The fan-out concatenates per-catalog batches then re-sorts the + // merged set by `TABLE_TYPE, TABLE_CAT, TABLE_SCHEM, TABLE_NAME`. + // Feed rows deliberately out of order and assert the JDBC order. + let cat_b = reshape_tables( + &single_row_server_table("b_catalog", "s", "t", "TABLE"), + Some("b_catalog"), + None, + ) + .unwrap(); + let cat_a = reshape_tables( + &single_row_server_table("a_catalog", "s", "t", "TABLE"), + Some("a_catalog"), + None, + ) + .unwrap(); + let merged = + arrow_select::concat::concat_batches(&GET_TABLES_SCHEMA, &[cat_b, cat_a]).unwrap(); + let sorted = sort_tables_batch(&merged).unwrap(); + let cats = sorted + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + // Same TABLE_TYPE, so TABLE_CAT breaks the tie: a_catalog first. + assert_eq!(cats.value(0), "a_catalog"); + assert_eq!(cats.value(1), "b_catalog"); + } + + /// Single-row `SHOW TABLES IN CATALOG` server shape for fan-out tests. + fn single_row_server_table( + catalog: &str, + namespace: &str, + table: &str, + table_type: &str, + ) -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("namespace", DataType::Utf8, false), + Field::new("tableName", DataType::Utf8, false), + Field::new("isTemporary", DataType::Boolean, false), + Field::new("catalogName", DataType::Utf8, false), + Field::new("tableType", DataType::Utf8, true), + ])); + RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec![namespace.to_owned()])), + Arc::new(StringArray::from(vec![table.to_owned()])), + Arc::new(BooleanArray::from(vec![false])), + Arc::new(StringArray::from(vec![catalog.to_owned()])), + Arc::new(StringArray::from(vec![Some(table_type.to_owned())])), + ], + ) + .unwrap() + } + fn server_columns_full() -> RecordBatch { let schema = Arc::new(Schema::new(vec![ Field::new("col_name", DataType::Utf8, false), diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index e0efde55..c33288b5 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -81,17 +81,19 @@ //! addendum A2 for the rationale. use crate::kernel_error::{Error, Result}; +use crate::metadata::sql::{LikeMatcher, SqlCommandBuilder}; use crate::metadata::static_data; use crate::metadata::thrift_shape::{ self, is_object_not_found, ThriftReshapingReader, GET_CATALOGS_SCHEMA, GET_COLUMNS_SCHEMA, GET_CROSS_REFERENCE_SCHEMA, GET_PRIMARY_KEYS_SCHEMA, GET_SCHEMAS_SCHEMA, GET_TABLES_SCHEMA, }; -use crate::reader::EmptyReader; -use crate::result_stream::ResultStream; +use crate::reader::{EmptyReader, InMemoryReader}; +use crate::result_stream::{ResultBatch, ResultStream}; use crate::session::SessionInner; +use arrow_array::Array; use arrow_schema::SchemaRef; use std::sync::Arc; -use tracing::Instrument; +use tracing::{debug, Instrument}; /// JDBC's `DatabaseMetaData` contract: metadata methods return an /// empty result set for non-existent catalogs / schemas / tables @@ -354,8 +356,8 @@ impl Metadata { .await } - /// Tables filtered by catalog (exact), schema (pattern), table - /// (pattern). + /// Tables filtered by catalog (**pattern**), schema (pattern), + /// table (pattern). /// /// JDBC `getTables` shape: 10 columns — `TABLE_CAT, TABLE_SCHEM, /// TABLE_NAME, TABLE_TYPE, REMARKS, TYPE_CAT, TYPE_SCHEM, @@ -363,6 +365,48 @@ impl Metadata { /// last five have no server-side source and are emitted as nulls /// per JDBC spec. /// + /// ## Catalog is a LIKE pattern + /// + /// Unlike every other catalog argument on this surface, `catalog` + /// here is a [`LikePattern`], mirroring the Thrift protocol where + /// `TGetTablesReq.catalogName` is a `TPatternOrIdentifier` (ODBC + /// `SQLTables` treats `CatalogName` as a pattern-value argument + /// under the default `SQL_ATTR_METADATA_ID = SQL_FALSE`). Because + /// the Databricks SEA `SHOW` grammar has **no catalog-pattern + /// position**, the kernel resolves a wildcard catalog by + /// enumerate-then-fan-out rather than by scanning every catalog: + /// + /// - **Wildcard catalog** (`%` / `_` present, unescaped): `SHOW + /// CATALOGS`, filter the catalog *names* with [`LikeMatcher`], then + /// issue one `SHOW TABLES IN CATALOG ` per match (schema / + /// table / type pushed down server-side) with bounded parallelism; + /// the per-catalog results are concatenated and re-sorted into the + /// JDBC row order. This is cheaper than `SHOW TABLES IN ALL + /// CATALOGS` for a selective pattern and needs no client-side row + /// filtering (each query is already catalog-scoped). + /// - **Literal catalog** (no active wildcards, e.g. `main`, or an + /// escaped `foo\_bar`, or the ODBC `SQL_ATTR_METADATA_ID = + /// SQL_TRUE` identifier case): unescape and scope server-side via + /// `SHOW TABLES IN CATALOG ` — the fast exact path. + /// - **`None`**: a single `SHOW TABLES IN ALL CATALOGS` — genuinely + /// "every catalog", so no enumeration is needed. + /// - **Empty pattern** (`Some("")`): "match nothing" per + /// [`LikePattern`] — returns an empty result with no wire call + /// (the schema/table `LIKE ''` convention, applied to the catalog). + /// + /// Catalog *names* are matched by [`LikeMatcher`] (a best-effort + /// reproduction of the server's `SHOW ... LIKE` matching: + /// case-insensitive, anchored), while schema / table patterns are + /// matched *server-side* by the per-catalog queries. If Databricks + /// `SHOW` matching semantics ever drift from `LikeMatcher`, catalog + /// selection could differ from the schema/table dimensions — keep the + /// two in sync if server matching changes. + /// + /// `list_columns` deliberately keeps an exact catalog identifier — + /// the Thrift `TGetColumnsReq.catalogName` is a `TIdentifier` that + /// "must not contain a search pattern", so catalog wildcarding is a + /// `getTables`-only behaviour. + /// /// `table_types`, when `Some(non-empty)`, filters the result to /// rows whose `TABLE_TYPE` matches one of the listed strings — /// matches `java.sql.DatabaseMetaData.getTables` behaviour. @@ -370,51 +414,297 @@ impl Metadata { /// so the filter is applied kernel-side after reshape. pub async fn list_tables( &self, - catalog: Option>, + catalog: Option>, schema_pattern: Option>, table_pattern: Option>, table_types: Option<&[&str]>, ) -> Result { let span = self.session.log_span().clone(); async { - let catalog_str = catalog.as_ref().map(|i| i.as_str().to_owned()); - let types_owned: Option> = - table_types.map(|s| s.iter().map(|t| (*t).to_owned()).collect()); - let raw = match self - .session - .transport() - .list_tables( - self.session.session_id(), - catalog.as_ref().map(|i| i.as_str()), - schema_pattern.as_ref().map(|p| p.as_str()), - table_pattern.as_ref().map(|p| p.as_str()), - table_types, - ) - .await - { - Ok(r) => r, - Err(e) => return not_found_or(e, GET_TABLES_SCHEMA.clone(), Err).await, - }; - let stmt_id = raw.statement_id.clone(); - let reshaped = ThriftReshapingReader::new( - raw.reader, + // Route the catalog argument. The SEA `SHOW` grammar has no + // catalog-pattern position, so a wildcard catalog can't be + // scoped server-side. Rather than `SHOW TABLES IN ALL + // CATALOGS` (which scans every table in every catalog and + // discards non-matches — slow on large workspaces), we + // enumerate catalogs, filter their names client-side, and fan + // out one scoped `SHOW TABLES IN CATALOG ` per match. + match catalog.as_ref().map(|p| p.as_str()) { + // No catalog filter, or a pattern that matches *every* + // catalog (`%`, `%%`, …): genuinely "every catalog". A + // single `SHOW TABLES IN ALL CATALOGS` is the right (and + // cheapest) query — no enumeration or fan-out. Routing `%` + // here (rather than the fan-out arm below) keeps it + // semantically identical to `None`: one round trip, and one + // inaccessible catalog can't fail the whole call. + None => { + self.list_tables_single_catalog( + None, + schema_pattern, + table_pattern, + table_types, + ) + .await + } + Some(pat) if SqlCommandBuilder::pattern_matches_all(pat) => { + self.list_tables_single_catalog( + None, + schema_pattern, + table_pattern, + table_types, + ) + .await + } + // Empty pattern is "match nothing" per `LikePattern` + // (mirrors the schema/table `LIKE ''` convention). Emit an + // empty result without a wire call. + Some("") => { + ResultStream::from_reader(Box::new(EmptyReader::new(GET_TABLES_SCHEMA.clone()))) + .await + } + // A selective wildcard pattern, or a literal the `SHOW` + // builder would misread as "all catalogs" (`*`), is + // resolved by enumerate-then-fan-out. `LikeMatcher` treats a + // literal (no `%` / `_`) as an exact anchored name, so this + // arm covers both "match some catalogs" and the `*`-literal + // edge with one path. (A match-*all* `%` was already routed + // to the single-query path above.) + Some(pat) + if SqlCommandBuilder::pattern_has_wildcards(pat) + || SqlCommandBuilder::is_wildcard_or_empty_scope(pat) => + { + self.list_tables_matching_catalogs( + pat, + schema_pattern, + table_pattern, + table_types, + ) + .await + } + // Literal catalog: scope server-side (fast path). Unescape + // `\_` / `\%` first so the identifier is the intended name. + Some(pat) => { + let literal = SqlCommandBuilder::strip_jdbc_escapes(pat); + self.list_tables_single_catalog( + Some(literal.as_str()), + schema_pattern, + table_pattern, + table_types, + ) + .await + } + } + } + .instrument(span) + .await + } + + /// Enumerate catalogs, keep those matching `pattern` + /// (case-insensitive ODBC/JDBC LIKE), and fan out one scoped + /// `SHOW TABLES IN CATALOG ` per match — reproducing Thrift's + /// catalog wildcarding without the whole-workspace scan of + /// `SHOW TABLES IN ALL CATALOGS`. The per-catalog queries run with + /// bounded parallelism; their reshaped rows are concatenated and + /// re-sorted into the JDBC row order. + async fn list_tables_matching_catalogs( + &self, + pattern: &str, + schema_pattern: Option>, + table_pattern: Option>, + table_types: Option<&[&str]>, + ) -> Result { + use futures::stream::{FuturesUnordered, StreamExt}; + + // 1. Enumerate + filter catalog names client-side. + let matcher = LikeMatcher::new(pattern); + let mut catalogs = self.list_catalogs().await?; + let mut names: Vec = Vec::new(); + let mut enumerated = 0usize; + while let Some(batch) = catalogs.next_batch().await? { + let ResultBatch::Arrow(rb) = batch; + // GET_CATALOGS_SCHEMA is a single `TABLE_CAT: Utf8` column. + let col = rb + .column(0) + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::data_loss().message("TABLE_CAT is not Utf8"))?; + for i in 0..col.len() { + enumerated += 1; + if !col.is_null(i) && matcher.matches(col.value(i)) { + names.push(col.value(i).to_owned()); + } + } + } + catalogs.close(); + // One correlatable line tying the fan-out back to its cause: how + // many catalogs a wildcard `list_tables` matched (and will query), + // vs how many exist. Lets on-call spot fan-out amplification (a + // loose pattern hitting hundreds of catalogs) without counting the + // per-query SQL debug lines from the transport. + debug!( + catalog_pattern = pattern, + catalogs_enumerated = enumerated, + catalogs_matched = names.len(), + "list_tables catalog wildcard fan-out" + ); + + // No catalog matched → typed empty result, no further wire calls. + if names.is_empty() { + return ResultStream::from_reader(Box::new(EmptyReader::new( GET_TABLES_SCHEMA.clone(), - Box::new(move |b| { - let types_ref: Option> = types_owned - .as_ref() - .map(|v| v.iter().map(|s| s.as_str()).collect()); - thrift_shape::reshape_tables(b, catalog_str.as_deref(), types_ref.as_deref()) - }), - ); - ResultStream::from_reader_with_close( - Box::new(reshaped), - Arc::clone(&self.session), - stmt_id, + ))) + .await; + } + + // 2. Fan out `SHOW TABLES IN CATALOG ` per match, bounded. + // Databricks metadata calls are cheap but the warehouse shouldn't + // be hit with an unbounded burst when a loose pattern matches many + // catalogs. + const MAX_INFLIGHT: usize = 8; + let schema_str = schema_pattern.as_ref().map(|p| p.as_str().to_owned()); + let table_str = table_pattern.as_ref().map(|p| p.as_str().to_owned()); + let types_owned: Option> = + table_types.map(|s| s.iter().map(|t| (*t).to_owned()).collect()); + + let mut inflight = FuturesUnordered::new(); + let mut remaining = names.into_iter(); + for name in remaining.by_ref().take(MAX_INFLIGHT) { + inflight.push(self.fetch_tables_for_catalog( + name, + schema_str.clone(), + table_str.clone(), + types_owned.clone(), + )); + } + let mut all_batches: Vec = Vec::new(); + while let Some(result) = inflight.next().await { + all_batches.extend(result?); + if let Some(name) = remaining.next() { + inflight.push(self.fetch_tables_for_catalog( + name, + schema_str.clone(), + table_str.clone(), + types_owned.clone(), + )); + } + } + + // 3. Concatenate + re-sort into the JDBC row order (each + // per-catalog batch was sorted only within its own catalog). + let merged = if all_batches.is_empty() { + None + } else { + let concatenated = + arrow_select::concat::concat_batches(&GET_TABLES_SCHEMA, &all_batches) + .map_err(|e| Error::data_loss().message(format!("merge tables: {e}")))?; + Some(thrift_shape::sort_tables_batch(&concatenated)?) + }; + ResultStream::from_reader(Box::new(InMemoryReader::new( + GET_TABLES_SCHEMA.clone(), + merged.into_iter().collect(), + ))) + .await + } + + /// Fetch + reshape `SHOW TABLES IN CATALOG ` into JDBC-shape + /// batches. An object-not-found error (catalog dropped between + /// enumeration and this call) collapses to zero rows, matching the + /// JDBC empty-result contract. Used by the fan-out path. + async fn fetch_tables_for_catalog( + &self, + catalog: String, + schema_pattern: Option, + table_pattern: Option, + table_types: Option>, + ) -> Result> { + let types_ref: Option> = table_types + .as_ref() + .map(|v| v.iter().map(String::as_str).collect()); + let raw = match self + .session + .transport() + .list_tables( + self.session.session_id(), + Some(catalog.as_str()), + schema_pattern.as_deref(), + table_pattern.as_deref(), + types_ref.as_deref(), ) .await + { + Ok(r) => r, + // Catalog vanished mid-enumeration → contribute no rows. + Err(e) if thrift_shape::is_object_not_found(&e) => return Ok(Vec::new()), + Err(e) => return Err(e), + }; + // Read + reshape into `out`. Capture the result rather than `?`-ing + // out early: the fan-out opens one statement per catalog and + // `ExecuteResult` has no Drop-based close, so a mid-stream read + // error must still close this statement or it leaks server-side + // (unlike the streaming paths, which close via a StatementCloseGuard). + let stmt_id = raw.statement_id.clone(); + let mut reader = raw.reader; + let read: Result> = async { + let mut out = Vec::new(); + while let Some(batch) = reader.next_batch().await? { + out.push(thrift_shape::reshape_tables( + &batch, + Some(catalog.as_str()), + types_ref.as_deref(), + )?); + } + Ok(out) } - .instrument(span) - .await + .await; + // Best-effort close on every exit (success or error). + self.session + .transport() + .close_statement(&stmt_id) + .await + .ok(); + read + } + + /// `SHOW TABLES IN CATALOG ` (or `IN ALL CATALOGS` when + /// `catalog` is None) as a single lazily-streamed query — the exact + /// literal-catalog fast path. + async fn list_tables_single_catalog( + &self, + catalog: Option<&str>, + schema_pattern: Option>, + table_pattern: Option>, + table_types: Option<&[&str]>, + ) -> Result { + let requested_catalog = catalog.map(|c| c.to_owned()); + let types_owned: Option> = + table_types.map(|s| s.iter().map(|t| (*t).to_owned()).collect()); + let raw = match self + .session + .transport() + .list_tables( + self.session.session_id(), + catalog, + schema_pattern.as_ref().map(|p| p.as_str()), + table_pattern.as_ref().map(|p| p.as_str()), + table_types, + ) + .await + { + Ok(r) => r, + Err(e) => return not_found_or(e, GET_TABLES_SCHEMA.clone(), Err).await, + }; + let stmt_id = raw.statement_id.clone(); + let reshaped = ThriftReshapingReader::new( + raw.reader, + GET_TABLES_SCHEMA.clone(), + Box::new(move |b| { + let types_ref: Option> = types_owned + .as_ref() + .map(|v| v.iter().map(|s| s.as_str()).collect()); + thrift_shape::reshape_tables(b, requested_catalog.as_deref(), types_ref.as_deref()) + }), + ); + ResultStream::from_reader_with_close(Box::new(reshaped), Arc::clone(&self.session), stmt_id) + .await } /// Columns of tables matching the filter. Catalog is optional and diff --git a/tests/v0_metadata_e2e.rs b/tests/v0_metadata_e2e.rs index 477ecfea..8e105082 100644 --- a/tests/v0_metadata_e2e.rs +++ b/tests/v0_metadata_e2e.rs @@ -102,6 +102,128 @@ async fn list_catalogs_returns_table_cat_column() { session.close().await.expect("close"); } +/// Collect every value of a named Utf8 column across all batches. +fn string_column_values(batches: &[arrow_array::RecordBatch], name: &str) -> Vec { + batches + .iter() + .flat_map(|rb| { + let idx = rb.schema().index_of(name).expect("column present"); + let arr = rb.column(idx).as_string::(); + (0..arr.len()) + .filter(|&i| !arr.is_null(i)) + .map(|i| arr.value(i).to_string()) + .collect::>() + }) + .collect() +} + +/// Regression test for databricks/databricks-odbc#129: `list_tables` +/// must treat the catalog argument as an ODBC/JDBC LIKE pattern +/// (`_` / `%`), matching Thrift `TGetTablesReq.catalogName`. The SEA +/// `SHOW` grammar has no catalog-pattern position, so the kernel lists +/// across all catalogs and filters `TABLE_CAT` client-side. +/// +/// Self-adapting: derives a `_`-wildcard pattern from a real catalog on +/// the live workspace, so it doesn't depend on the issue's specific +/// `comparator_tests` / `comparator-tests` fixtures existing here. +#[tokio::test] +#[ignore] +async fn list_tables_catalog_wildcard_filters_client_side() { + use databricks_sql_kernel::LikePattern; + + let session = live_session().await; + + // Prefer `samples` — a Databricks-managed catalog present on every + // UC workspace with a well-populated `information_schema.tables`, so + // the wildcard result is non-empty and the assertion has teeth. Fall + // back to any ascii catalog if `samples` is somehow absent. + let (catalogs, _) = collect( + session + .metadata() + .list_catalogs() + .await + .expect("list_catalogs"), + ) + .await; + let catalog_names = string_column_values(&catalogs, "TABLE_CAT"); + let base = catalog_names + .iter() + .find(|c| *c == "samples") + .or_else(|| catalog_names.iter().find(|c| c.len() >= 3 && c.is_ascii())) + .cloned() + .expect("expected `samples` or some ascii catalog name of length >= 3"); + // Replace the 2nd char with `_` (single-char wildcard). For + // `samples` this yields `s_mples`, which must still match `samples`. + let mut chars: Vec = base.chars().collect(); + chars[1] = '_'; + let pattern: String = chars.into_iter().collect(); + let expect_rows = base == "samples"; + + let stream = session + .metadata() + .list_tables( + Some(LikePattern::new(&pattern).unwrap()), + // Narrow to information_schema to keep the result small and + // fast; the catalog wildcard is what we're exercising. + Some(LikePattern::new("information_schema").unwrap()), + Some(LikePattern::new("tables").unwrap()), + None, + ) + .await + .expect("list_tables with wildcard catalog"); + let (batches, rows) = collect(stream).await; + + // With `samples` as the base we KNOW information_schema.tables is + // populated, so the wildcard must return rows (proving the filter is + // inclusive, not silently dropping everything). + if expect_rows { + assert!( + rows > 0, + "wildcard catalog {pattern:?} against samples.information_schema.tables \ + returned no rows — client-side catalog filter dropped valid rows" + ); + } + + // Every returned row's TABLE_CAT must match the `_` pattern — proves + // the client-side catalog filter ran (vs. returning all catalogs). + let returned_cats = string_column_values(&batches, "TABLE_CAT"); + for cat in &returned_cats { + assert!( + like_matches_underscore(&pattern, cat), + "TABLE_CAT {cat:?} does not match wildcard catalog pattern {pattern:?}; \ + returned catalogs: {returned_cats:?}" + ); + } + // The base catalog itself must be represented (it matches its own + // `_`-pattern), so the wildcard is inclusive, not just restrictive. + // Soft-warn rather than hard-fail if the base catalog happens to + // lack an information_schema.tables surface on this workspace. + if !returned_cats.iter().any(|c| c.eq_ignore_ascii_case(&base)) { + eprintln!( + "warning: base catalog {base:?} not present in wildcard result \ + (pattern {pattern:?}); it may lack information_schema.tables. \ + returned: {returned_cats:?}" + ); + } + + session.close().await.expect("close"); +} + +/// Test-local reference implementation of a case-insensitive LIKE match +/// with `_` as a single-char wildcard (no `%`). Deliberately independent +/// of the kernel's matcher so the e2e assertion doesn't just re-run the +/// code under test. +fn like_matches_underscore(pattern: &str, candidate: &str) -> bool { + let p: Vec = pattern.to_lowercase().chars().collect(); + let c: Vec = candidate.to_lowercase().chars().collect(); + if p.len() != c.len() { + return false; + } + p.iter() + .zip(c.iter()) + .all(|(pc, cc)| *pc == '_' || pc == cc) +} + // Tests in this file target the `samples` catalog rather than `main`. // `samples` is a Databricks-managed catalog present on every // Unity-Catalog-enabled workspace; `main` is workspace-configurable @@ -183,7 +305,7 @@ async fn list_tables_returns_jdbc_columns() { let stream = session .metadata() .list_tables( - Some(Identifier::new("samples").unwrap()), + Some(databricks_sql_kernel::LikePattern::new("samples").unwrap()), Some(databricks_sql_kernel::LikePattern::new("information_schema").unwrap()), None, None, diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 3425eb0a..99eafcf6 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -42,7 +42,7 @@ use databricks_sql_kernel::{ }; use serde_json::json; use std::sync::Arc; -use wiremock::matchers::{method, path}; +use wiremock::matchers::{body_string_contains, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; // ─── Helpers ──────────────────────────────────────────────────────── @@ -133,6 +133,25 @@ fn succeeded_inline_response_body(batch: &RecordBatch) -> String { .to_string() } +/// SEA response body for a FAILED statement with the given SQLSTATE + +/// message — drives the kernel's terminal-error path. A `42704` state +/// is treated as object-not-found (skipped in the fan-out); anything +/// else propagates. +fn failed_response_body(sql_state: &str, message: &str) -> String { + json!({ + "statement_id": "stmt-test", + "status": { + "state": "FAILED", + "error": { + "error_code": "BAD_REQUEST", + "message": message, + "sql_state": sql_state, + } + }, + }) + .to_string() +} + async fn mount_execute(server: &MockServer, body: String) { Mock::given(method("POST")) .and(path("/api/2.0/sql/statements")) @@ -141,6 +160,19 @@ async fn mount_execute(server: &MockServer, body: String) { .await; } +/// Mount `/statements` so it only responds when the request body (the +/// SEA statement JSON) contains `sql_substr`. If the kernel emits +/// different SQL, no stub matches and the call fails — so this asserts +/// the exact SQL the routing produced. +async fn mount_execute_expecting_sql(server: &MockServer, sql_substr: &str, body: String) { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_string_contains(sql_substr)) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(server) + .await; +} + fn string_batch(cols: Vec<(&str, Vec>)>) -> RecordBatch { let fields: Vec = cols .iter() @@ -319,6 +351,364 @@ async fn list_tables_returns_jdbc_columns_with_synthesised_nulls() { } } +#[tokio::test] +async fn list_tables_literal_catalog_emits_in_catalog_unescaped() { + // A literal catalog with an escaped underscore (`comp\_tests`) must + // route to the fast exact path: `SHOW TABLES IN CATALOG comp_tests` + // (unescaped, backtick-quoted), NOT the all-catalogs path. The + // body-matched stub only responds if that SQL was emitted. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let raw = string_batch(vec![ + ("namespace", vec![Some("default")]), + ("tableName", vec![Some("t1")]), + ("catalogName", vec![Some("comp_tests")]), + ("tableType", vec![Some("TABLE")]), + ]); + mount_execute_expecting_sql( + &server, + "IN CATALOG `comp_tests`", + succeeded_inline_response_body(&raw), + ) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_tables( + Some(LikePattern::new(r"comp\_tests").unwrap()), + None, + None, + None, + ) + .await + .expect("list_tables literal catalog"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches[0].num_rows(), 1); +} + +#[tokio::test] +async fn list_tables_wildcard_catalog_fans_out_per_matching_catalog() { + // A wildcard catalog (`comp_%`) must NOT scan all catalogs. Instead + // it enumerates catalogs (`SHOW CATALOGS`), filters names, and issues + // one `SHOW TABLES IN CATALOG ` per match. `comp_%` matches + // `comp_tests` and `comp-x` (the `_` is one char) but not `other`. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + // `SHOW CATALOGS` → three catalogs (server column is `catalog`). + let catalogs = string_batch(vec![( + "catalog", + vec![Some("comp_tests"), Some("comp-x"), Some("other")], + )]); + mount_execute_expecting_sql( + &server, + "SHOW CATALOGS", + succeeded_inline_response_body(&catalogs), + ) + .await; + + // Per-catalog `SHOW TABLES IN CATALOG `: one stub per matching + // catalog, each returning its own table so we can assert both were + // queried and that `other` was not. + let tables_comp_tests = string_batch(vec![ + ("namespace", vec![Some("s")]), + ("tableName", vec![Some("t_ct")]), + ("catalogName", vec![Some("comp_tests")]), + ("tableType", vec![Some("TABLE")]), + ]); + mount_execute_expecting_sql( + &server, + "IN CATALOG `comp_tests`", + succeeded_inline_response_body(&tables_comp_tests), + ) + .await; + let tables_comp_x = string_batch(vec![ + ("namespace", vec![Some("s")]), + ("tableName", vec![Some("t_cx")]), + ("catalogName", vec![Some("comp-x")]), + ("tableType", vec![Some("TABLE")]), + ]); + mount_execute_expecting_sql( + &server, + "IN CATALOG `comp-x`", + succeeded_inline_response_body(&tables_comp_x), + ) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_tables(Some(LikePattern::new("comp_%").unwrap()), None, None, None) + .await + .expect("list_tables wildcard catalog"); + let batches = drain_stream(&mut stream).await; + + // Rows from both matching catalogs, none from `other`. (If the kernel + // had queried `other`, no stub matches `IN CATALOG \`other\`` and the + // call would have errored.) + let mut cats: Vec = batches + .iter() + .flat_map(|b| { + let arr = b.column_by_name("TABLE_CAT").unwrap().as_string::(); + (0..arr.len()) + .map(|i| arr.value(i).to_owned()) + .collect::>() + }) + .collect(); + cats.sort(); + assert_eq!(cats, vec!["comp-x".to_owned(), "comp_tests".to_owned()]); +} + +#[tokio::test] +async fn list_tables_percent_catalog_uses_single_all_catalogs_query() { + // `%` matches every catalog and is semantically identical to `None`, + // so it must take the single `SHOW TABLES IN ALL CATALOGS` path, NOT + // enumerate + fan out. The stub only matches `IN ALL CATALOGS`; if the + // kernel instead issued `SHOW CATALOGS` + per-catalog queries, no stub + // would match and the call would fail. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let raw = string_batch(vec![ + ("namespace", vec![Some("s")]), + ("tableName", vec![Some("t1")]), + ("catalogName", vec![Some("anycat")]), + ("tableType", vec![Some("TABLE")]), + ]); + mount_execute_expecting_sql( + &server, + "IN ALL CATALOGS", + succeeded_inline_response_body(&raw), + ) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_tables(Some(LikePattern::new("%").unwrap()), None, None, None) + .await + .expect("list_tables %% catalog"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 1); +} + +#[tokio::test] +async fn list_tables_wildcard_skips_catalog_dropped_mid_enumeration() { + // Resilience contract: a catalog that vanishes between SHOW CATALOGS + // and its SHOW TABLES (object-not-found) contributes zero rows rather + // than failing the whole call. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let catalogs = string_batch(vec![("catalog", vec![Some("comp_a"), Some("comp_b")])]); + mount_execute_expecting_sql( + &server, + "SHOW CATALOGS", + succeeded_inline_response_body(&catalogs), + ) + .await; + + // comp_a returns a table; comp_b was dropped → 42704 not-found. + let tables_a = string_batch(vec![ + ("namespace", vec![Some("s")]), + ("tableName", vec![Some("t_a")]), + ("catalogName", vec![Some("comp_a")]), + ("tableType", vec![Some("TABLE")]), + ]); + mount_execute_expecting_sql( + &server, + "IN CATALOG `comp_a`", + succeeded_inline_response_body(&tables_a), + ) + .await; + mount_execute_expecting_sql( + &server, + "IN CATALOG `comp_b`", + failed_response_body("42704", "catalog not found"), + ) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_tables(Some(LikePattern::new("comp_%").unwrap()), None, None, None) + .await + .expect("list_tables tolerates a dropped catalog"); + let batches = drain_stream(&mut stream).await; + let cats: Vec = batches + .iter() + .flat_map(|b| { + let arr = b.column_by_name("TABLE_CAT").unwrap().as_string::(); + (0..arr.len()) + .map(|i| arr.value(i).to_owned()) + .collect::>() + }) + .collect(); + assert_eq!(cats, vec!["comp_a".to_owned()]); +} + +#[tokio::test] +async fn list_tables_wildcard_propagates_non_not_found_error() { + // A real (non-not-found) per-catalog error must abort the whole call — + // NOT silently return partial results. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let catalogs = string_batch(vec![("catalog", vec![Some("comp_a")])]); + mount_execute_expecting_sql( + &server, + "SHOW CATALOGS", + succeeded_inline_response_body(&catalogs), + ) + .await; + // Permission error (42501), not object-not-found. + mount_execute_expecting_sql( + &server, + "IN CATALOG `comp_a`", + failed_response_body("42501", "insufficient permissions"), + ) + .await; + + let session = open_session(&server).await; + let result = session + .metadata() + .list_tables(Some(LikePattern::new("comp_%").unwrap()), None, None, None) + .await; + match result { + Err(e) => assert!( + e.message.contains("insufficient permissions") + || e.sql_state.as_deref() == Some("42501"), + "expected the permission error to propagate, got: {} / {:?}", + e.message, + e.sql_state + ), + Ok(mut s) => { + // A stream may resolve lazily; draining must surface the error. + let err = async { + while s.next_batch().await?.is_some() {} + Ok::<_, databricks_sql_kernel::Error>(()) + } + .await + .expect_err("non-not-found per-catalog error must propagate"); + assert!( + err.message.contains("insufficient permissions") + || err.sql_state.as_deref() == Some("42501") + ); + } + } +} + +#[tokio::test] +async fn list_tables_wildcard_zero_catalogs_match_returns_empty() { + // A wildcard pattern that matches no catalog returns a typed empty + // result and issues NO per-catalog query (no `IN CATALOG` stub is + // mounted, so any such call would fail). + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let catalogs = string_batch(vec![("catalog", vec![Some("main"), Some("other")])]); + mount_execute_expecting_sql( + &server, + "SHOW CATALOGS", + succeeded_inline_response_body(&catalogs), + ) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_tables(Some(LikePattern::new("zzz%").unwrap()), None, None, None) + .await + .expect("list_tables zero-match"); + 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_tables_wildcard_fans_out_beyond_inflight_cap() { + // >8 matching catalogs exercises the bounded-parallel refill loop: all + // N must be queried and their rows returned, not just the first 8. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let names: Vec = (0..12).map(|i| format!("cat_{i:02}")).collect(); + let name_refs: Vec> = names.iter().map(|s| Some(s.as_str())).collect(); + let catalogs = string_batch(vec![("catalog", name_refs)]); + mount_execute_expecting_sql( + &server, + "SHOW CATALOGS", + succeeded_inline_response_body(&catalogs), + ) + .await; + // One per-catalog stub each, keyed on its exact IN CATALOG SQL. + for name in &names { + let tables = string_batch(vec![ + ("namespace", vec![Some("s")]), + ("tableName", vec![Some("t")]), + ("catalogName", vec![Some(name.as_str())]), + ("tableType", vec![Some("TABLE")]), + ]); + mount_execute_expecting_sql( + &server, + &format!("IN CATALOG `{name}`"), + succeeded_inline_response_body(&tables), + ) + .await; + } + + let session = open_session(&server).await; + // `cat_%` matches all 12 (but is not a match-all `%`, so it fans out). + let mut stream = session + .metadata() + .list_tables(Some(LikePattern::new("cat%").unwrap()), None, None, None) + .await + .expect("list_tables >8 fan-out"); + let batches = drain_stream(&mut stream).await; + let mut cats: Vec = batches + .iter() + .flat_map(|b| { + let arr = b.column_by_name("TABLE_CAT").unwrap().as_string::(); + (0..arr.len()) + .map(|i| arr.value(i).to_owned()) + .collect::>() + }) + .collect(); + cats.sort(); + assert_eq!(cats, names, "all 12 catalogs must be queried and returned"); +} + +#[tokio::test] +async fn list_tables_empty_catalog_matches_nothing_without_wire_call() { + // An empty catalog pattern is "match nothing": no `/statements` stub + // is mounted, so if the kernel made a wire call the test would hang / + // fail. It must instead return an empty result locally. + 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_tables(Some(LikePattern::new("").unwrap()), None, None, None) + .await + .expect("list_tables empty catalog"); + // Still the JDBC getTables shape, zero rows. + assert_eq!(col_names(&stream.schema())[0], "TABLE_CAT"); + let batches = drain_stream(&mut stream).await; + let total: usize = batches.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total, 0); +} + #[tokio::test] async fn list_tables_table_types_filters_kernel_side() { let server = MockServer::start().await;