diff --git a/CHANGELOG.md b/CHANGELOG.md index 64d4f998..aca699b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,27 @@ cadences and may not move in lockstep with the crate. multi-statement transactions (Private Preview; requires catalog-managed tables server-side). +### Fixed +- **Metadata conformance (catalog match-all wildcard)** — a *literal* + catalog `%`, `*`, or `""` reaching `Metadata::list_schemas` / + `list_tables` is now scoped verbatim (`SHOW … IN [CATALOG] \`%\``) and + matches nothing (0 rows), instead of being silently broadened to + `SHOW … IN ALL CATALOGS`. Only a `None` catalog means "all catalogs"; + `list_columns` already behaved this way. This makes an escaped `\%` + catalog (wildcard-escaping ON) and an exact `Identifier("%")` return + the correct empty result, matching the reference driver. An *unescaped* + `%` `LikePattern` on `list_tables` is still match-all (one + `SHOW TABLES IN ALL CATALOGS`), and the C ABI's NULL/`""` → "all + catalogs" convention is unchanged. Fixes #202, #221. +- **Metadata conformance (`foreign_keys` unspecified foreign table)** — + `Metadata::foreign_keys` with a `None` `foreign_table` now returns an + empty result (0 rows, no `SHOW FOREIGN KEYS` issued) instead of an + `InvalidArgument` error, matching the JDBC SEA `listCrossReferences` + contract and the ODBC primary-keys-only `SQLForeignKeys` form (covers + both the parent-set and both-tables-null cases). `foreign_catalog` / + `foreign_schema` remain required only when a `foreign_table` is + supplied. Fixes #212 (METADATA-037/038). + ## [v0.2.0] - 2026-06-08 **Beta release of the Databricks SQL Kernel.** Bumps the crate out diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 8e545518..272758e9 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -628,13 +628,14 @@ KernelStatusCode kernel_result_stream_close(kernel_result_stream_t* stream); * identifier args are exact. * * NULL string args mean "unfiltered" for the list_* calls (catalogs / - * schemas / tables / columns). The key/constraint calls are stricter: + * schemas / tables / columns). The key/constraint calls differ: * `kernel_metadata_primary_keys` requires a non-NULL catalog, schema, AND - * table (Databricks SHOW KEYS must target a fully-qualified table), and - * `kernel_metadata_foreign_keys` requires the full foreign_* (referencing) - * triple while the parent_* (referenced) triple is optional. Passing NULL - * for a required identifier returns `KernelStatusCode_InvalidArgument` - * with an explanatory last error (see each function's comment). + * table (Databricks SHOW KEYS must target a fully-qualified table), while + * `kernel_metadata_foreign_keys` keys off the foreign (referencing) table + * — a NULL foreign_table returns an empty result (0 rows, no wire call), + * not an error. Passing NULL for a required identifier returns + * `KernelStatusCode_InvalidArgument` with an explanatory last error (see + * each function's comment). */ KernelStatusCode kernel_metadata_list_catalogs(kernel_session_t* session, kernel_result_stream_t** out); @@ -655,10 +656,13 @@ KernelStatusCode kernel_metadata_list_columns(kernel_session_t* session, const c KernelStatusCode kernel_metadata_primary_keys(kernel_session_t* session, const char* catalog, const char* schema, const char* table, kernel_result_stream_t** out); -/* The foreign_* (referencing) triple is REQUIRED (all non-NULL); the - * parent_* (referenced) triple is optional and filters the referenced - * side. NULL for any foreign_* arg returns - * `KernelStatusCode_InvalidArgument`. */ +/* Keys off the foreign (referencing) table. A NULL foreign_table means + * "nothing to look up" and returns an empty result (0 rows, no wire + * call) — this is the ODBC "primary-keys only" SQLForeignKeys form. When + * a foreign_table IS given, foreign_catalog and foreign_schema are then + * required (they scope SHOW FOREIGN KEYS) and a NULL there returns + * `KernelStatusCode_InvalidArgument`. The parent_* (referenced) triple + * is optional and filters the referenced side. */ KernelStatusCode kernel_metadata_foreign_keys(kernel_session_t* session, const char* parent_catalog, const char* parent_schema, const char* parent_table, const char* foreign_catalog, diff --git a/src/c_abi/metadata.rs b/src/c_abi/metadata.rs index 920283da..9ad6ab11 100644 --- a/src/c_abi/metadata.rs +++ b/src/c_abi/metadata.rs @@ -299,9 +299,17 @@ pub unsafe extern "C" fn kernel_metadata_primary_keys( /// Foreign keys. Mirrors ODBC `SQLForeignKeys`: the `parent_*` triple is /// the referenced (primary-key) table, the `foreign_*` triple the -/// referencing table. The kernel requires the `foreign_*` triple (the -/// referencing table) to be fully specified; the `parent_*` triple is -/// optional and filters the referenced side. +/// referencing table. The `parent_*` triple is optional and filters the +/// referenced side. +/// +/// A NULL `foreign_table` means "no referencing table to look up": the +/// call returns an **empty result** (0 rows, no server statement) rather +/// than `InvalidArgument`. This matches the JDBC SEA +/// `listCrossReferences` contract and the ODBC "primary-keys only" +/// `SQLForeignKeys` form (FK table left NULL). Only when a +/// `foreign_table` *is* supplied are `foreign_catalog` / `foreign_schema` +/// required (they scope the `SHOW FOREIGN KEYS` lookup); a NULL there +/// returns `InvalidArgument`. /// /// # Safety /// `session` must be a live session handle; the identifier args, if diff --git a/src/client/transport.rs b/src/client/transport.rs index 1a2515e7..6d0b0469 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -401,7 +401,9 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { async fn list_catalogs(&self, session_id: &str) -> Result; /// List schemas, optionally filtered by catalog and pattern. - /// When catalog is None or wildcard, uses "SHOW SCHEMAS IN ALL CATALOGS". + /// `catalog = None` emits "SHOW SCHEMAS IN ALL CATALOGS"; a `Some` + /// catalog is scoped verbatim (a literal `%` / `*` / `""` matches no + /// real catalog → 0 rows, not "all catalogs"). async fn list_schemas( &self, session_id: &str, @@ -410,7 +412,11 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { ) -> Result; /// List tables, optionally filtered. - /// When catalog is None or wildcard, uses "SHOW TABLES IN ALL CATALOGS". + /// `catalog = None` emits "SHOW TABLES IN ALL CATALOGS"; a `Some` + /// catalog is scoped verbatim (a literal `%` / `*` / `""` matches no + /// real catalog → 0 rows, not "all catalogs"). The higher-level + /// `Metadata::list_tables` resolves real catalog wildcards before + /// this point. async fn list_tables( &self, session_id: &str, diff --git a/src/metadata/sql.rs b/src/metadata/sql.rs index a5c66035..0861c1b2 100644 --- a/src/metadata/sql.rs +++ b/src/metadata/sql.rs @@ -156,24 +156,25 @@ impl SqlCommandBuilder { format!("`{}`", name.replace('`', "``")) } - /// Returns true if the value is None, empty, or a wildcard ("%" or "*"). - fn is_null_or_wildcard(value: &Option) -> bool { - match value { - None => true, - 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 `*`. + /// Whether a catalog string, if handed to the `SHOW ... IN [CATALOG] + /// …` builder as an exact scope, would instead be silently + /// reinterpreted by the Databricks server as "all catalogs": 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`]. + /// `pattern_has_wildcards` decision from disagreeing with the server: + /// a literal catalog that lands in this set must be matched + /// client-side (enumerate-then-fan-out) instead of handed to the + /// server as a scope, else e.g. a catalog literally named `*` would + /// silently broaden to every catalog. + /// + /// Note this is *not* consulted by [`build_show_schemas`](Self::build_show_schemas) + /// / [`build_show_tables`](Self::build_show_tables): those broaden to + /// "all catalogs" only when the catalog is `None`, so a literal `%` / + /// `*` / `""` that reaches them (e.g. an escaped `\%` unescaped to a + /// literal `%`, or an exact `Identifier`) is scoped verbatim and + /// matches nothing — matching JDBC's 0-row contract for a literal + /// catalog that names no catalog. pub fn is_wildcard_or_empty_scope(s: &str) -> bool { s.is_empty() || s == "%" || s == "*" } @@ -198,13 +199,17 @@ impl SqlCommandBuilder { } pub fn build_show_schemas(&self) -> String { - let mut sql = if Self::is_null_or_wildcard(&self.catalog) { - "SHOW SCHEMAS IN ALL CATALOGS".to_string() - } else { - format!( - "SHOW SCHEMAS IN {}", - Self::escape_identifier(self.catalog.as_ref().unwrap()) - ) + // Broaden to "all catalogs" only when no catalog is scoped + // (`None`). A `Some(name)` is an exact literal to scope on — even + // when `name` is `%`, `*`, or `""` (a literal catalog matching no + // real catalog), which must yield 0 rows, not every catalog. + // Mirrors `build_show_columns`'s `Option`-based decision; the + // caller resolves any real wildcards before this point. + let mut sql = match self.catalog { + None => "SHOW SCHEMAS IN ALL CATALOGS".to_string(), + Some(ref catalog) => { + format!("SHOW SCHEMAS IN {}", Self::escape_identifier(catalog)) + } }; if let Some(ref pattern) = self.schema_pattern { @@ -215,13 +220,18 @@ impl SqlCommandBuilder { } pub fn build_show_tables(&self) -> String { - let mut sql = if Self::is_null_or_wildcard(&self.catalog) { - "SHOW TABLES IN ALL CATALOGS".to_string() - } else { - format!( - "SHOW TABLES IN CATALOG {}", - Self::escape_identifier(self.catalog.as_ref().unwrap()) - ) + // Broaden to "all catalogs" only when no catalog is scoped + // (`None`); see `build_show_schemas` for why a literal `%` / `*` + // / `""` catalog is scoped verbatim (0 rows) rather than + // broadened. + let mut sql = match self.catalog { + None => "SHOW TABLES IN ALL CATALOGS".to_string(), + Some(ref catalog) => { + format!( + "SHOW TABLES IN CATALOG {}", + Self::escape_identifier(catalog) + ) + } }; if let Some(ref pattern) = self.schema_pattern { @@ -512,27 +522,44 @@ mod tests { } #[test] - fn test_show_schemas_wildcard_catalog() { + fn test_show_schemas_literal_percent_catalog_scopes_verbatim() { + // A `Some("%")` reaching the builder is a *literal* catalog named + // `%` (the caller resolves real wildcards before this point), so + // it is scoped verbatim — matching no real catalog and yielding 0 + // rows — rather than broadened to "all catalogs". Regression guard + // for the METADATA-036/037 catalog-wildcard conformance fix. let sql = SqlCommandBuilder::new() .with_catalog(Some("%")) .build_show_schemas(); - assert_eq!(sql, "SHOW SCHEMAS IN ALL CATALOGS"); + assert_eq!(sql, "SHOW SCHEMAS IN `%`"); } #[test] - fn test_show_schemas_empty_catalog() { + fn test_show_schemas_empty_catalog_scopes_verbatim() { + // Likewise a literal empty-string catalog scopes to `` (0 rows), + // not "all catalogs". Only `None` means "all catalogs". let sql = SqlCommandBuilder::new() .with_catalog(Some("")) .build_show_schemas(); - assert_eq!(sql, "SHOW SCHEMAS IN ALL CATALOGS"); + assert_eq!(sql, "SHOW SCHEMAS IN ``"); } #[test] - fn test_show_schemas_star_wildcard() { + fn test_show_schemas_star_catalog_scopes_verbatim() { let sql = SqlCommandBuilder::new() .with_catalog(Some("*")) .build_show_schemas(); - assert_eq!(sql, "SHOW SCHEMAS IN ALL CATALOGS"); + assert_eq!(sql, "SHOW SCHEMAS IN `*`"); + } + + #[test] + fn test_show_tables_literal_percent_catalog_scopes_verbatim() { + // Same contract as `build_show_schemas`: a literal `%` catalog is + // scoped verbatim (0 rows), not broadened to all catalogs. + let sql = SqlCommandBuilder::new() + .with_catalog(Some("%")) + .build_show_tables(); + assert_eq!(sql, "SHOW TABLES IN CATALOG `%`"); } #[test] diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index 9cca274a..05dc3e8a 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -867,12 +867,23 @@ impl Metadata { /// Foreign-key relationships. Both parent and foreign sides are /// exact identifiers — ODBC SQLForeignKeys does not support - /// patterns. The **foreign side** must be fully specified - /// (catalog + schema + table); the parent side is optional and - /// matches "any parent" when omitted, matching the underlying - /// `SHOW FOREIGN KEYS IN TABLE` semantics. Wrappers that want to - /// query by parent only should resolve to a foreign-side filter - /// before calling. + /// patterns. The parent side is optional and matches "any parent" + /// when omitted, matching the underlying `SHOW FOREIGN KEYS IN + /// TABLE` semantics. Wrappers that want to query by parent only + /// should resolve to a foreign-side filter before calling. + /// + /// ## Unspecified foreign table → empty result + /// + /// A `None` `foreign_table` means "no foreign table to look up", so + /// the call returns an **empty result set** (0 rows, correct JDBC + /// shape) and issues **no** server statement — never an error. This + /// mirrors the JDBC SEA `listCrossReferences` contract (which keys + /// solely off the foreign table) and covers the ODBC "primary-keys + /// only" call form (`SQLForeignKeys` with the FK table left NULL) as + /// well as the both-tables-NULL case. Only when a `foreign_table` + /// *is* supplied are `foreign_catalog` / `foreign_schema` required — + /// the `SHOW FOREIGN KEYS IN CATALOG … IN SCHEMA … IN TABLE …` + /// grammar needs all three to scope the lookup. /// /// Server shape: same as [`primary_keys`](Self::primary_keys) — /// `SHOW FOREIGN KEYS` shares its result schema with `SHOW KEYS`. @@ -893,15 +904,27 @@ impl Metadata { ) -> Result { let span = self.session.log_span().clone(); async { + // Unspecified foreign table → "nothing to look up": empty + // result, no wire call (JDBC SEA `listCrossReferences` + // contract; also the ODBC PK-only `SQLForeignKeys` form and + // the both-tables-NULL case). Handled before the + // catalog/schema requirements so a null foreign table never + // surfaces as an argument error. + let Some(foreign_table) = foreign_table else { + return ResultStream::from_reader(Box::new(EmptyReader::new( + GET_CROSS_REFERENCE_SCHEMA.clone(), + ))) + .await; + }; + // A foreign table *is* specified, so its catalog and schema + // are required to scope the `SHOW FOREIGN KEYS IN CATALOG … + // IN SCHEMA … IN TABLE …` lookup. let foreign_catalog = foreign_catalog.ok_or_else(|| { Error::invalid_argument().message("foreign_keys requires foreign_catalog") })?; let foreign_schema = foreign_schema.ok_or_else(|| { Error::invalid_argument().message("foreign_keys requires foreign_schema") })?; - let foreign_table = foreign_table.ok_or_else(|| { - Error::invalid_argument().message("foreign_keys requires foreign_table") - })?; let raw = match self .session .transport() diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 1668c5f3..25de939f 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -345,6 +345,69 @@ async fn list_schemas_returns_jdbc_columns_with_synthesised_catalog() { assert_eq!(cat.value(1), "main"); } +#[tokio::test] +async fn list_schemas_literal_percent_catalog_scopes_verbatim_and_empties() { + // Conformance (METADATA-036/037): a *literal* catalog named `%` + // (an exact `Identifier`, not a wildcard — the v0 schemas surface + // takes an `Identifier`) must scope to that catalog and match + // nothing, NOT broaden to "all catalogs". The stub only matches + // `SHOW SCHEMAS IN \`%\``; if the kernel emitted `IN ALL CATALOGS` + // no stub would match and the call would fail. The server answers + // CATALOG_NOT_FOUND, which the kernel maps to an empty result. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + mount_execute_expecting_sql( + &server, + "SHOW SCHEMAS IN `%`", + failed_response_body("42704", "CATALOG_NOT_FOUND: no catalog named `%`"), + ) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_schemas(Some(Identifier::new("%").unwrap()), None) + .await + .expect("list_schemas literal % catalog maps not-found to empty"); + // Still the JDBC getSchemas shape, zero rows. + 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 + // pattern `\%` denotes a literal catalog named `%`. It has no active + // wildcards, so `list_tables` takes the fast exact path, unescapes to + // `%`, and must scope `SHOW TABLES IN CATALOG \`%\`` — NOT broaden to + // "all catalogs". (Contrast `list_tables_percent_catalog_uses_single_ + // all_catalogs_query`, where an *unescaped* `%` is genuinely + // match-all.) The server's not-found maps to an empty result. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + mount_execute_expecting_sql( + &server, + "SHOW TABLES IN CATALOG `%`", + failed_response_body("42704", "CATALOG_NOT_FOUND: no catalog named `%`"), + ) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .list_tables(Some(LikePattern::new(r"\%").unwrap()), None, None, None) + .await + .expect("list_tables escaped % catalog maps not-found to empty"); + 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_returns_jdbc_columns_with_synthesised_nulls() { let server = MockServer::start().await; @@ -1129,6 +1192,84 @@ async fn foreign_keys_reshaped_to_jdbc_columns() { assert!(b.column_by_name("PK_NAME").unwrap().is_null(0)); } +#[tokio::test] +async fn foreign_keys_null_foreign_table_returns_empty_without_wire_call() { + // Conformance (METADATA-037): the PK (parent) side is fully + // specified but the FK (foreign) table is None. Per the JDBC SEA + // `listCrossReferences` contract, an unspecified foreign table is + // "nothing to look up" → empty result, and NO `SHOW FOREIGN KEYS` + // (no `/statements` call). No `/statements` stub is mounted, so a + // wire call would fail the test. + 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() + .foreign_keys( + Some(Identifier::new("main").unwrap()), // parent_catalog + Some(Identifier::new("d").unwrap()), // parent_schema + Some(Identifier::new("parent").unwrap()), // parent_table (PK side set) + Some(Identifier::new("main").unwrap()), // foreign_catalog + Some(Identifier::new("d").unwrap()), // foreign_schema + None, // foreign_table = None → empty + ) + .await + .expect("foreign_keys null foreign table must not error"); + + // Correct JDBC getCrossReference shape, zero rows. + assert_eq!(col_names(&stream.schema())[0], "PKTABLE_CAT"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 0); + // No ExecuteStatement was issued. + let calls = server + .received_requests() + .await + .unwrap() + .iter() + .filter(|r| r.url.path() == "/api/2.0/sql/statements") + .count(); + assert_eq!(calls, 0, "no SHOW FOREIGN KEYS should be issued"); +} + +#[tokio::test] +async fn foreign_keys_both_tables_null_returns_empty_without_wire_call() { + // Conformance (METADATA-038): both parent and foreign tables are + // None. On SEA this follows the JDBC SEA `listCrossReferences` + // contract (keys off the foreign table only) → empty result, no + // wire call — rather than Thrift's both-tables-null 42000 rejection. + 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() + .foreign_keys( + None, // parent_catalog + None, // parent_schema + None, // parent_table + Some(Identifier::new("main").unwrap()), // foreign_catalog + Some(Identifier::new("d").unwrap()), // foreign_schema + None, // foreign_table = None + ) + .await + .expect("foreign_keys both tables null must not error"); + + assert_eq!(col_names(&stream.schema())[0], "PKTABLE_CAT"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 0); + let calls = server + .received_requests() + .await + .unwrap() + .iter() + .filter(|r| r.url.path() == "/api/2.0/sql/statements") + .count(); + assert_eq!(calls, 0, "no SHOW FOREIGN KEYS should be issued"); +} + #[tokio::test] async fn primary_keys_without_schema_errors() { let server = MockServer::start().await;