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
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 14 additions & 10 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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,
Expand Down
14 changes: 11 additions & 3 deletions src/c_abi/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,9 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug {
async fn list_catalogs(&self, session_id: &str) -> Result<ExecuteResult>;

/// 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,
Expand All @@ -410,7 +412,11 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug {
) -> Result<ExecuteResult>;

/// 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,
Expand Down
99 changes: 63 additions & 36 deletions src/metadata/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>) -> 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 == "*"
}
Expand All @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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]
Expand Down
41 changes: 32 additions & 9 deletions src/metadata_v0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -893,15 +904,27 @@ impl Metadata {
) -> Result<ResultStream> {
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()
Expand Down
Loading
Loading