Skip to content

Commit 2cf732c

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

7 files changed

Lines changed: 268 additions & 88 deletions

File tree

‎src/client/sea.rs‎

Lines changed: 76 additions & 5 deletions
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;
@@ -88,10 +89,7 @@ impl MetadataOperation {
8889
}
8990

9091
fn supports_thrift_native(self) -> bool {
91-
!matches!(
92-
self,
93-
Self::Functions | Self::Procedures | Self::ProcedureColumns
94-
)
92+
!matches!(self, Self::Procedures | Self::ProcedureColumns)
9593
}
9694
}
9795

@@ -1023,6 +1021,61 @@ impl SeaRestTransport {
10231021
);
10241022
}
10251023
}
1024+
1025+
/// Resolve the session catalog the same way JDBC's `getFunctions` path
1026+
/// does before issuing `SHOW FUNCTIONS IN CATALOG`.
1027+
async fn query_current_catalog(&self, session_id: &str) -> Result<Option<String>> {
1028+
let mut raw = self
1029+
.execute_and_read(
1030+
session_id,
1031+
"SELECT CURRENT_CATALOG()",
1032+
&ExecuteParams::default(),
1033+
RequestType::ExecuteMetadataQuery,
1034+
None,
1035+
ExecutionTimeout::Default,
1036+
)
1037+
.await?;
1038+
let statement_id = raw.statement_id.clone();
1039+
let needs_close = raw.status.state != StatementState::Closed;
1040+
1041+
let catalog = loop {
1042+
match raw.reader.next_batch().await {
1043+
Err(e) => break Err(e),
1044+
Ok(None) => break Ok(None),
1045+
Ok(Some(batch)) if batch.num_rows() == 0 => continue,
1046+
Ok(Some(batch)) => {
1047+
let Some(column) = batch.columns().first() else {
1048+
break Err(Error::data_loss()
1049+
.message("CURRENT_CATALOG() returned a row without a column"));
1050+
};
1051+
let values = arrow_cast::cast(column.as_ref(), &arrow_schema::DataType::Utf8)
1052+
.map_err(|e| {
1053+
Error::data_loss().message(format!(
1054+
"CURRENT_CATALOG() returned a non-string value: {e}"
1055+
))
1056+
});
1057+
break values.and_then(|values| {
1058+
let values =
1059+
values
1060+
.as_any()
1061+
.downcast_ref::<StringArray>()
1062+
.ok_or_else(|| {
1063+
Error::data_loss().message(
1064+
"CURRENT_CATALOG() string cast did not yield StringArray",
1065+
)
1066+
})?;
1067+
Ok((!values.is_null(0)).then(|| values.value(0).to_owned()))
1068+
});
1069+
}
1070+
}
1071+
};
1072+
1073+
if needs_close {
1074+
self.close_orphaned_statement(&statement_id, "query_current_catalog")
1075+
.await;
1076+
}
1077+
catalog
1078+
}
10261079
}
10271080

10281081
/// Convert a parsed `GetChunksResponse` into the kernel-facing
@@ -1694,7 +1747,25 @@ impl Transport for SeaRestTransport {
16941747
schema_pattern: Option<&str>,
16951748
function_pattern: Option<&str>,
16961749
) -> Result<ExecuteResult> {
1697-
let sql = SqlCommandBuilder::build_get_functions(catalog, schema_pattern, function_pattern);
1750+
let resolved_catalog = match catalog {
1751+
Some(catalog) => catalog.to_owned(),
1752+
None => match self.query_current_catalog(session_id).await {
1753+
Ok(Some(catalog)) if !catalog.is_empty() => catalog,
1754+
Ok(_) => "hive_metastore".to_owned(),
1755+
Err(e) => {
1756+
warn!(
1757+
error = %e,
1758+
"failed to query current catalog for list_functions; using hive_metastore"
1759+
);
1760+
"hive_metastore".to_owned()
1761+
}
1762+
},
1763+
};
1764+
let sql = SqlCommandBuilder::build_show_functions(
1765+
&resolved_catalog,
1766+
schema_pattern,
1767+
function_pattern,
1768+
);
16981769
debug!("list_functions: {}", sql);
16991770
self.execute_and_read(
17001771
session_id,

‎src/client/transport.rs‎

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

496496
/// List functions, optionally filtered by catalog, schema pattern, and function name pattern.
497497
///
498-
/// Uses `information_schema.routines` filtered by `routine_type = 'FUNCTION'`.
499-
/// When catalog is None, queries `system.information_schema.routines` (cross-catalog).
498+
/// Uses `SHOW FUNCTIONS IN CATALOG`, resolving the session's current
499+
/// catalog (with a `hive_metastore` fallback) when catalog is None.
500500
async fn list_functions(
501501
&self,
502502
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)