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
2 changes: 2 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ changes go in their respective binding's NEXT_CHANGELOG.

### Changed

- Route function metadata through the Thrift-native metadata path when supported by the server.

### Updated

### Fixed
Expand Down
6 changes: 2 additions & 4 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,7 @@ impl MetadataOperation {
}

fn supports_thrift_native(self) -> bool {
!matches!(
self,
Self::Functions | Self::Procedures | Self::ProcedureColumns
)
!matches!(self, Self::Procedures | Self::ProcedureColumns)
}
}

Expand Down Expand Up @@ -2215,6 +2212,7 @@ mod tests {
fn native_metadata_support_matches_server_contract() {
assert!(MetadataOperation::Columns.supports_thrift_native());
assert!(MetadataOperation::CrossReference.supports_thrift_native());
assert!(MetadataOperation::Functions.supports_thrift_native());
assert!(!MetadataOperation::Procedures.supports_thrift_native());
assert!(!MetadataOperation::ProcedureColumns.supports_thrift_native());
}
Expand Down
3 changes: 1 addition & 2 deletions src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,8 +495,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug {

/// List functions, optionally filtered by catalog, schema pattern, and function name pattern.
///
/// Uses `information_schema.routines` filtered by `routine_type = 'FUNCTION'`.
/// When catalog is None, queries `system.information_schema.routines` (cross-catalog).
/// Uses `SHOW FUNCTIONS IN CATALOG`, which SEA can route to native `GetFunctions`.
async fn list_functions(
&self,
session_id: &str,
Expand Down
72 changes: 38 additions & 34 deletions src/metadata/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,42 +344,36 @@ impl SqlCommandBuilder {
sql
}

/// Build a SELECT query against `information_schema.routines` for
/// `getFunctions`.
///
/// Mirrors [`SqlCommandBuilder::build_get_procedures`] but filters
/// `routine_type = 'FUNCTION'`. Catalog resolution and pattern
/// escaping match the procedures builder, so `escape_sql_string`
/// and `resolve_catalog_prefix` are the single source of truth
/// for both.
/// Build the `SHOW FUNCTIONS` command consumed by SEA's native
/// `GetFunctions` router. The command remains executable when native
/// routing is unavailable.
pub fn build_get_functions(
catalog: Option<&str>,
schema_pattern: Option<&str>,
function_pattern: Option<&str>,
) -> String {
let prefix = Self::resolve_catalog_prefix(catalog);
// SHOW FUNCTIONS requires a catalog. Match the JDBC driver's fallback
// when no current/default catalog is available to the client.
let catalog = catalog.unwrap_or("hive_metastore");
let mut sql = format!(
"SELECT routine_catalog, routine_schema, routine_name, comment, specific_name \
FROM {}.information_schema.routines \
WHERE routine_type = 'FUNCTION'",
prefix
"SHOW FUNCTIONS IN CATALOG {}",
Self::escape_identifier(catalog)
);

if let Some(pattern) = schema_pattern {
sql.push_str(&format!(
" AND routine_schema LIKE '{}'",
Self::escape_sql_string(pattern)
));
}

if let Some(pattern) = function_pattern {
sql.push_str(&format!(
" AND routine_name LIKE '{}'",
Self::escape_sql_string(pattern)
" SCHEMA LIKE '{}'",
Self::jdbc_pattern_to_hive(pattern)
));
}

sql.push_str(" ORDER BY routine_catalog, routine_schema, routine_name");
// TGetFunctionsReq.functionName is required. Use the all-functions
// pattern when the public API did not narrow by name.
let function_pattern = function_pattern.unwrap_or("%");
sql.push_str(&format!(
" LIKE '{}'",
Self::jdbc_pattern_to_hive(function_pattern)
));
sql
}

Expand Down Expand Up @@ -942,43 +936,53 @@ mod tests {
#[test]
fn test_get_functions_null_catalog() {
let sql = SqlCommandBuilder::build_get_functions(None, None, None);
assert!(sql.starts_with("SELECT routine_catalog"));
assert!(sql.contains("FROM system.information_schema.routines"));
assert!(sql.contains("WHERE routine_type = 'FUNCTION'"));
assert!(sql.ends_with("ORDER BY routine_catalog, routine_schema, routine_name"));
assert_eq!(sql, "SHOW FUNCTIONS IN CATALOG `hive_metastore` LIKE '*'");
}

#[test]
fn test_get_functions_specific_catalog() {
let sql = SqlCommandBuilder::build_get_functions(Some("main"), None, None);
assert!(sql.contains("FROM `main`.information_schema.routines"));
assert_eq!(sql, "SHOW FUNCTIONS IN CATALOG `main` LIKE '*'");
}

#[test]
fn test_get_functions_with_schema_pattern() {
let sql = SqlCommandBuilder::build_get_functions(None, Some("default%"), None);
assert!(sql.contains("AND routine_schema LIKE 'default%'"));
assert_eq!(
sql,
"SHOW FUNCTIONS IN CATALOG `hive_metastore` SCHEMA LIKE 'default*' LIKE '*'"
);
}

#[test]
fn test_get_functions_with_function_pattern() {
let sql = SqlCommandBuilder::build_get_functions(None, None, Some("avg%"));
assert!(sql.contains("AND routine_name LIKE 'avg%'"));
assert_eq!(
sql,
"SHOW FUNCTIONS IN CATALOG `hive_metastore` LIKE 'avg*'"
);
}

#[test]
fn test_get_functions_with_all_filters() {
let sql =
SqlCommandBuilder::build_get_functions(Some("prod"), Some("public"), Some("fn_%"));
assert!(sql.contains("FROM `prod`.information_schema.routines"));
assert!(sql.contains("AND routine_schema LIKE 'public'"));
assert!(sql.contains("AND routine_name LIKE 'fn_%'"));
assert_eq!(
sql,
"SHOW FUNCTIONS IN CATALOG `prod` SCHEMA LIKE 'public' LIKE 'fn.*'"
);
}

#[test]
fn test_get_functions_sql_injection_escaped() {
let sql = SqlCommandBuilder::build_get_functions(None, Some("it's"), None);
assert!(sql.contains("AND routine_schema LIKE 'it''s'"));
assert!(sql.contains("SCHEMA LIKE 'it''s'"));
}

#[test]
fn test_get_functions_catalog_identifier_escaped() {
let sql = SqlCommandBuilder::build_get_functions(Some("my`catalog"), None, None);
assert_eq!(sql, "SHOW FUNCTIONS IN CATALOG `my``catalog` LIKE '*'");
}

// --- foreign keys with special characters ---
Expand Down
70 changes: 46 additions & 24 deletions src/metadata/thrift_shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -837,26 +837,14 @@ pub(crate) fn reshape_procedures(batch: &RecordBatch) -> Result<RecordBatch> {
.map_err(|e| Error::data_loss().message(format!("reshape procedures: {e}")))
}

/// Reshape the `build_get_functions` result (same server columns as
/// `build_get_procedures`) into the JDBC `getFunctions` shape.
///
/// `FUNCTION_TYPE` is constant `functionNoTable` (1) — Databricks functions
/// are scalar / return a value, not a table. (JDBC: `functionResultUnknown`=0,
/// `functionNoTable`=1, `functionReturnsTable`=2.)
/// Reshape the `SHOW FUNCTIONS` result into the JDBC `getFunctions` shape.
Comment thread
vuanhphung marked this conversation as resolved.
Resolved
pub(crate) fn reshape_functions(batch: &RecordBatch) -> Result<RecordBatch> {
let n = batch.num_rows();
let function_cat = utf8_column(batch, "routine_catalog")?;
let function_schem = utf8_column(batch, "routine_schema")?;
let function_name = utf8_column(batch, "routine_name")?;
let remarks = utf8_column(batch, "comment")?;
let specific_name = utf8_column(batch, "specific_name")?;
// FUNCTION_TYPE is reported functionNoTable(1) for every row. Databricks
// supports table-valued functions, which JDBC would report as
// functionReturnsTable(2), but build_get_functions does not select a column
// that distinguishes scalar from table functions, so the reshape cannot tell
// them apart. Known parity gap; distinguishing TVFs would require selecting
// additional information_schema.routines columns in the builder.
let function_type = Arc::new(Int16Array::from(vec![Some(1_i16); n])) as ArrayRef;
let function_cat = utf8_column(batch, "catalogName")?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium — In the SHOW FUNCTIONS fallback path, reshape_functions derives FUNCTION_CAT from the server's catalogName column. The reference JDBC driver does not trust the fallback result's catalog column: in getRowsForFunctions it substitutes the resolved catalog (the same non-null catalog used to build SHOW FUNCTIONS IN CATALOG <x>, defaulting to hive_metastore) into FUNCTION_CAT, and only reads namespace/functionName/remarks/functionType/specificName from the result. The native path here already mirrors JDBC correctly (normalize_native_functions_batch overrides column 0 with the caller's original catalog), but the SHOW-fallback reshape does not.

Consequence: utf8_column returns an all-null array when catalogName is absent (or the server leaves it empty, as the native GetFunctions path is documented to do), so a client on a server that executes the executable fallback can see FUNCTION_CAT = NULL where JDBC guarantees the resolved catalog name. The added fallback test (functions_falls_back_when_current_catalog_is_unavailable) never exercises this: its functions_batch fixture always populates catalogName with the expected catalog, so the divergence is untested. Consider substituting the resolved catalog for FUNCTION_CAT in the fallback reshape (as JDBC does) rather than reading catalogName.

let function_schem = utf8_column(batch, "namespace")?;
let function_name = utf8_column(batch, "functionName")?;
let remarks = utf8_column(batch, "remarks")?;
let function_type = int16_column(batch, "functionType")?;
let specific_name = utf8_column(batch, "specificName")?;
RecordBatch::try_new(
GET_FUNCTIONS_SCHEMA.clone(),
vec![
Expand Down Expand Up @@ -1245,6 +1233,7 @@ impl ResultReader for ThriftReshapingReader {
#[cfg(test)]
mod tests {
use super::*;
use arrow_array::cast::AsArray;
use arrow_array::{BooleanArray, RecordBatch};

// ─── is_object_not_found tests ─────────────────────────────────
Expand Down Expand Up @@ -1991,7 +1980,7 @@ mod tests {

// ─── procedures / functions / procedure-columns reshape ───────────

/// One-row `build_get_procedures` / `build_get_functions` server shape.
/// One-row `build_get_procedures` server shape.
fn server_routine_row(comment: Option<&str>) -> RecordBatch {
let schema = Arc::new(Schema::new(vec![
Field::new("routine_catalog", DataType::Utf8, true),
Expand All @@ -2013,6 +2002,29 @@ mod tests {
.unwrap()
}

fn server_function_row() -> RecordBatch {
let schema = Arc::new(Schema::new(vec![
Field::new("functionName", DataType::Utf8, false),
Field::new("namespace", DataType::Utf8, false),
Field::new("catalogName", DataType::Utf8, true),
Field::new("remarks", DataType::Utf8, true),
Field::new("functionType", DataType::Int32, true),
Field::new("specificName", DataType::Utf8, true),
]));
RecordBatch::try_new(
schema,
vec![
Arc::new(StringArray::from(vec![Some("sp_report")])),
Arc::new(StringArray::from(vec![Some("sales")])),
Arc::new(StringArray::from(vec![Some("main")])),
Arc::new(StringArray::from(vec![Some("nightly report")])),
Arc::new(Int32Array::from(vec![Some(0)])),
Arc::new(StringArray::from(vec![Some("sp_report")])),
],
)
.unwrap()
}

fn col_names(batch: &RecordBatch) -> Vec<String> {
batch
.schema()
Expand Down Expand Up @@ -2049,7 +2061,7 @@ mod tests {

#[test]
fn reshape_functions_produces_jdbc_get_functions_shape() {
let out = reshape_functions(&server_routine_row(None)).unwrap();
let out = reshape_functions(&server_function_row()).unwrap();
assert_eq!(
col_names(&out),
vec![
Expand All @@ -2061,9 +2073,19 @@ mod tests {
"SPECIFIC_NAME",
]
);
// FUNCTION_TYPE = functionNoTable (1).
let ftype = out.column(4).as_any().downcast_ref::<Int16Array>().unwrap();
assert_eq!(ftype.value(0), 1);
assert_eq!(out.column(0).as_string::<i32>().value(0), "main");
assert_eq!(out.column(1).as_string::<i32>().value(0), "sales");
assert_eq!(out.column(2).as_string::<i32>().value(0), "sp_report");
assert_eq!(out.column(3).as_string::<i32>().value(0), "nightly report");
assert_eq!(
out.column(4)
.as_any()
.downcast_ref::<Int16Array>()
.unwrap()
.value(0),
0
);
assert_eq!(out.column(5).as_string::<i32>().value(0), "sp_report");
}

/// `build_get_procedure_columns` raw server shape (information_schema
Expand Down
Loading
Loading