Skip to content

Commit dee9218

Browse files
committed
fix(metadata): align GetFunctions with JDBC
Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
1 parent 9882b93 commit dee9218

7 files changed

Lines changed: 266 additions & 84 deletions

File tree

‎src/client/sea.rs‎

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ use crate::types::sea::{
3434
ExecuteStatementRequest, GetChunksResponse, SessionExecutionMode, SessionVersion,
3535
StatementExecutionResponse, StatementState,
3636
};
37+
use arrow_array::{Array, StringArray};
3738
use async_trait::async_trait;
3839
use reqwest::Method;
3940
use std::collections::HashMap;
@@ -786,6 +787,60 @@ impl SeaRestTransport {
786787
);
787788
}
788789
}
790+
791+
/// Resolve the session catalog the same way JDBC's `getFunctions` path
792+
/// does before issuing `SHOW FUNCTIONS IN CATALOG`.
793+
async fn query_current_catalog(&self, session_id: &str) -> Result<Option<String>> {
794+
let mut raw = self
795+
.execute_and_read(
796+
session_id,
797+
"SELECT CURRENT_CATALOG()",
798+
&ExecuteParams::default(),
799+
RequestType::ExecuteMetadataQuery,
800+
None,
801+
)
802+
.await?;
803+
let statement_id = raw.statement_id.clone();
804+
let needs_close = raw.status.state != StatementState::Closed;
805+
806+
let catalog = loop {
807+
match raw.reader.next_batch().await {
808+
Err(e) => break Err(e),
809+
Ok(None) => break Ok(None),
810+
Ok(Some(batch)) if batch.num_rows() == 0 => continue,
811+
Ok(Some(batch)) => {
812+
let Some(column) = batch.columns().first() else {
813+
break Err(Error::data_loss()
814+
.message("CURRENT_CATALOG() returned a row without a column"));
815+
};
816+
let values = arrow_cast::cast(column.as_ref(), &arrow_schema::DataType::Utf8)
817+
.map_err(|e| {
818+
Error::data_loss().message(format!(
819+
"CURRENT_CATALOG() returned a non-string value: {e}"
820+
))
821+
});
822+
break values.and_then(|values| {
823+
let values =
824+
values
825+
.as_any()
826+
.downcast_ref::<StringArray>()
827+
.ok_or_else(|| {
828+
Error::data_loss().message(
829+
"CURRENT_CATALOG() string cast did not yield StringArray",
830+
)
831+
})?;
832+
Ok((!values.is_null(0)).then(|| values.value(0).to_owned()))
833+
});
834+
}
835+
}
836+
};
837+
838+
if needs_close {
839+
self.close_orphaned_statement(&statement_id, "query_current_catalog")
840+
.await;
841+
}
842+
catalog
843+
}
789844
}
790845

791846
/// Convert a parsed `GetChunksResponse` into the kernel-facing
@@ -1444,7 +1499,25 @@ impl Transport for SeaRestTransport {
14441499
schema_pattern: Option<&str>,
14451500
function_pattern: Option<&str>,
14461501
) -> Result<ExecuteResult> {
1447-
let sql = SqlCommandBuilder::build_get_functions(catalog, schema_pattern, function_pattern);
1502+
let resolved_catalog = match catalog {
1503+
Some(catalog) => catalog.to_owned(),
1504+
None => match self.query_current_catalog(session_id).await {
1505+
Ok(Some(catalog)) if !catalog.is_empty() => catalog,
1506+
Ok(_) => "hive_metastore".to_owned(),
1507+
Err(e) => {
1508+
warn!(
1509+
error = %e,
1510+
"failed to query current catalog for list_functions; using hive_metastore"
1511+
);
1512+
"hive_metastore".to_owned()
1513+
}
1514+
},
1515+
};
1516+
let sql = SqlCommandBuilder::build_show_functions(
1517+
&resolved_catalog,
1518+
schema_pattern,
1519+
function_pattern,
1520+
);
14481521
debug!("list_functions: {}", sql);
14491522
self.execute_and_read(
14501523
session_id,

‎src/client/transport.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -477,8 +477,8 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug {
477477

478478
/// List functions, optionally filtered by catalog, schema pattern, and function name pattern.
479479
///
480-
/// Uses `information_schema.routines` filtered by `routine_type = 'FUNCTION'`.
481-
/// When catalog is None, queries `system.information_schema.routines` (cross-catalog).
480+
/// Uses `SHOW FUNCTIONS IN CATALOG`, resolving the session's current
481+
/// catalog (with a `hive_metastore` fallback) when catalog is None.
482482
async fn list_functions(
483483
&self,
484484
session_id: &str,

‎src/metadata/sql.rs‎

Lines changed: 28 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -344,42 +344,27 @@ impl SqlCommandBuilder {
344344
sql
345345
}
346346

347-
/// Build a SELECT query against `information_schema.routines` for
348-
/// `getFunctions`.
349-
///
350-
/// Mirrors [`SqlCommandBuilder::build_get_procedures`] but filters
351-
/// `routine_type = 'FUNCTION'`. Catalog resolution and pattern
352-
/// escaping match the procedures builder, so `escape_sql_string`
353-
/// and `resolve_catalog_prefix` are the single source of truth
354-
/// for both.
355-
pub fn build_get_functions(
356-
catalog: Option<&str>,
347+
/// Build the JDBC-compatible `SHOW FUNCTIONS IN CATALOG` query.
348+
pub fn build_show_functions(
349+
catalog: &str,
357350
schema_pattern: Option<&str>,
358351
function_pattern: Option<&str>,
359352
) -> String {
360-
let prefix = Self::resolve_catalog_prefix(catalog);
361353
let mut sql = format!(
362-
"SELECT routine_catalog, routine_schema, routine_name, comment, specific_name \
363-
FROM {}.information_schema.routines \
364-
WHERE routine_type = 'FUNCTION'",
365-
prefix
354+
"SHOW FUNCTIONS IN CATALOG {}",
355+
Self::escape_identifier(catalog)
366356
);
367357

368358
if let Some(pattern) = schema_pattern {
369359
sql.push_str(&format!(
370-
" AND routine_schema LIKE '{}'",
371-
Self::escape_sql_string(pattern)
360+
" SCHEMA LIKE '{}'",
361+
Self::jdbc_pattern_to_hive(pattern)
372362
));
373363
}
374364

375-
if let Some(pattern) = function_pattern {
376-
sql.push_str(&format!(
377-
" AND routine_name LIKE '{}'",
378-
Self::escape_sql_string(pattern)
379-
));
380-
}
365+
let pattern = function_pattern.unwrap_or("%");
366+
sql.push_str(&format!(" LIKE '{}'", Self::jdbc_pattern_to_hive(pattern)));
381367

382-
sql.push_str(" ORDER BY routine_catalog, routine_schema, routine_name");
383368
sql
384369
}
385370

@@ -939,46 +924,43 @@ mod tests {
939924

940925
// --- getFunctions SQL builder tests ---
941926

942-
#[test]
943-
fn test_get_functions_null_catalog() {
944-
let sql = SqlCommandBuilder::build_get_functions(None, None, None);
945-
assert!(sql.starts_with("SELECT routine_catalog"));
946-
assert!(sql.contains("FROM system.information_schema.routines"));
947-
assert!(sql.contains("WHERE routine_type = 'FUNCTION'"));
948-
assert!(sql.ends_with("ORDER BY routine_catalog, routine_schema, routine_name"));
949-
}
950-
951927
#[test]
952928
fn test_get_functions_specific_catalog() {
953-
let sql = SqlCommandBuilder::build_get_functions(Some("main"), None, None);
954-
assert!(sql.contains("FROM `main`.information_schema.routines"));
929+
let sql = SqlCommandBuilder::build_show_functions("main", None, None);
930+
assert_eq!(sql, "SHOW FUNCTIONS IN CATALOG `main` LIKE '*'");
955931
}
956932

957933
#[test]
958934
fn test_get_functions_with_schema_pattern() {
959-
let sql = SqlCommandBuilder::build_get_functions(None, Some("default%"), None);
960-
assert!(sql.contains("AND routine_schema LIKE 'default%'"));
935+
let sql = SqlCommandBuilder::build_show_functions("main", Some("default%"), None);
936+
assert_eq!(
937+
sql,
938+
"SHOW FUNCTIONS IN CATALOG `main` SCHEMA LIKE 'default*' LIKE '*'"
939+
);
961940
}
962941

963942
#[test]
964943
fn test_get_functions_with_function_pattern() {
965-
let sql = SqlCommandBuilder::build_get_functions(None, None, Some("avg%"));
966-
assert!(sql.contains("AND routine_name LIKE 'avg%'"));
944+
let sql = SqlCommandBuilder::build_show_functions("main", None, Some("avg%"));
945+
assert_eq!(sql, "SHOW FUNCTIONS IN CATALOG `main` LIKE 'avg*'");
967946
}
968947

969948
#[test]
970949
fn test_get_functions_with_all_filters() {
971-
let sql =
972-
SqlCommandBuilder::build_get_functions(Some("prod"), Some("public"), Some("fn_%"));
973-
assert!(sql.contains("FROM `prod`.information_schema.routines"));
974-
assert!(sql.contains("AND routine_schema LIKE 'public'"));
975-
assert!(sql.contains("AND routine_name LIKE 'fn_%'"));
950+
let sql = SqlCommandBuilder::build_show_functions("prod", Some("public"), Some("fn_%"));
951+
assert_eq!(
952+
sql,
953+
"SHOW FUNCTIONS IN CATALOG `prod` SCHEMA LIKE 'public' LIKE 'fn.*'"
954+
);
976955
}
977956

978957
#[test]
979958
fn test_get_functions_sql_injection_escaped() {
980-
let sql = SqlCommandBuilder::build_get_functions(None, Some("it's"), None);
981-
assert!(sql.contains("AND routine_schema LIKE 'it''s'"));
959+
let sql = SqlCommandBuilder::build_show_functions("my`catalog", Some("it's"), None);
960+
assert_eq!(
961+
sql,
962+
"SHOW FUNCTIONS IN CATALOG `my``catalog` SCHEMA LIKE 'it''s' LIKE '*'"
963+
);
982964
}
983965

984966
// --- foreign keys with special characters ---

‎src/metadata/thrift_shape.rs‎

Lines changed: 41 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -837,26 +837,14 @@ pub(crate) fn reshape_procedures(batch: &RecordBatch) -> Result<RecordBatch> {
837837
.map_err(|e| Error::data_loss().message(format!("reshape procedures: {e}")))
838838
}
839839

840-
/// Reshape the `build_get_functions` result (same server columns as
841-
/// `build_get_procedures`) into the JDBC `getFunctions` shape.
842-
///
843-
/// `FUNCTION_TYPE` is constant `functionNoTable` (1) — Databricks functions
844-
/// are scalar / return a value, not a table. (JDBC: `functionResultUnknown`=0,
845-
/// `functionNoTable`=1, `functionReturnsTable`=2.)
840+
/// Reshape the raw `SHOW FUNCTIONS` result into the JDBC `getFunctions` shape.
846841
pub(crate) fn reshape_functions(batch: &RecordBatch) -> Result<RecordBatch> {
847-
let n = batch.num_rows();
848-
let function_cat = utf8_column(batch, "routine_catalog")?;
849-
let function_schem = utf8_column(batch, "routine_schema")?;
850-
let function_name = utf8_column(batch, "routine_name")?;
851-
let remarks = utf8_column(batch, "comment")?;
852-
let specific_name = utf8_column(batch, "specific_name")?;
853-
// FUNCTION_TYPE is reported functionNoTable(1) for every row. Databricks
854-
// supports table-valued functions, which JDBC would report as
855-
// functionReturnsTable(2), but build_get_functions does not select a column
856-
// that distinguishes scalar from table functions, so the reshape cannot tell
857-
// them apart. Known parity gap; distinguishing TVFs would require selecting
858-
// additional information_schema.routines columns in the builder.
859-
let function_type = Arc::new(Int16Array::from(vec![Some(1_i16); n])) as ArrayRef;
842+
let function_cat = utf8_column(batch, "catalogName")?;
843+
let function_schem = utf8_column(batch, "namespace")?;
844+
let function_name = utf8_column(batch, "functionName")?;
845+
let remarks = utf8_column(batch, "remarks")?;
846+
let function_type = int16_column(batch, "functionType")?;
847+
let specific_name = utf8_column(batch, "specificName")?;
860848
RecordBatch::try_new(
861849
GET_FUNCTIONS_SCHEMA.clone(),
862850
vec![
@@ -1991,7 +1979,7 @@ mod tests {
19911979

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

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

2004+
fn server_function_row() -> RecordBatch {
2005+
let schema = Arc::new(Schema::new(vec![
2006+
Field::new("functionName", DataType::Utf8, false),
2007+
Field::new("namespace", DataType::Utf8, true),
2008+
Field::new("catalogName", DataType::Utf8, true),
2009+
Field::new("remarks", DataType::Utf8, true),
2010+
Field::new("functionType", DataType::Int32, true),
2011+
Field::new("specificName", DataType::Utf8, true),
2012+
]));
2013+
RecordBatch::try_new(
2014+
schema,
2015+
vec![
2016+
Arc::new(StringArray::from(vec![Some("sales_total")])),
2017+
Arc::new(StringArray::from(vec![Some("sales")])),
2018+
Arc::new(StringArray::from(vec![Some("main")])),
2019+
Arc::new(StringArray::from(vec![None::<&str>])),
2020+
Arc::new(Int32Array::from(vec![Some(1)])),
2021+
Arc::new(StringArray::from(vec![Some("sales_total")])),
2022+
],
2023+
)
2024+
.unwrap()
2025+
}
2026+
20162027
fn col_names(batch: &RecordBatch) -> Vec<String> {
20172028
batch
20182029
.schema()
@@ -2049,7 +2060,7 @@ mod tests {
20492060

20502061
#[test]
20512062
fn reshape_functions_produces_jdbc_get_functions_shape() {
2052-
let out = reshape_functions(&server_routine_row(None)).unwrap();
2063+
let out = reshape_functions(&server_function_row()).unwrap();
20532064
assert_eq!(
20542065
col_names(&out),
20552066
vec![
@@ -2061,7 +2072,15 @@ mod tests {
20612072
"SPECIFIC_NAME",
20622073
]
20632074
);
2064-
// FUNCTION_TYPE = functionNoTable (1).
2075+
assert_eq!(
2076+
out.column(2)
2077+
.as_any()
2078+
.downcast_ref::<StringArray>()
2079+
.unwrap()
2080+
.value(0),
2081+
"sales_total"
2082+
);
2083+
// The wider server integer is narrowed to JDBC SMALLINT.
20652084
let ftype = out.column(4).as_any().downcast_ref::<Int16Array>().unwrap();
20662085
assert_eq!(ftype.value(0), 1);
20672086
}

0 commit comments

Comments
 (0)