diff --git a/src/client/mod.rs b/src/client/mod.rs index e2f59a71..c28a4e1e 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -46,6 +46,6 @@ pub use retry::{ pub(crate) use sea::SeaRestTransport; pub(crate) use transport::{ ChunkLinkFetchResult, DirectOutcome, ExecuteResponse, ExecuteResult, ExecuteResultData, - ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo, Transport, - TransportConfig, + ExecutionTimeout, InlineChunkFetchResult, ListFunctionsResult, SessionAttribution, SessionInfo, + Transport, TransportConfig, }; diff --git a/src/client/sea.rs b/src/client/sea.rs index 0ae802ce..437d276f 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -20,8 +20,8 @@ use crate::client::retry::RequestType; use crate::client::{ ChunkLinkFetchResult, DatabricksHttpClient, DirectOutcome, ExecuteResponse, ExecuteResult, - ExecuteResultData, ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo, - Transport, TransportConfig, + ExecuteResultData, ExecutionTimeout, InlineChunkFetchResult, ListFunctionsResult, + SessionAttribution, SessionInfo, Transport, TransportConfig, }; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; @@ -34,6 +34,7 @@ use crate::types::sea::{ ExecuteStatementRequest, GetChunksResponse, SessionExecutionMode, SessionVersion, StatementExecutionResponse, StatementState, }; +use arrow_array::{Array, StringArray}; use async_trait::async_trait; use reqwest::Method; use std::collections::HashMap; @@ -88,10 +89,7 @@ impl MetadataOperation { } fn supports_thrift_native(self) -> bool { - !matches!( - self, - Self::Functions | Self::Procedures | Self::ProcedureColumns - ) + !matches!(self, Self::Procedures | Self::ProcedureColumns) } } @@ -175,6 +173,7 @@ pub(crate) struct SeaRestTransport { warehouse_id: String, config: TransportConfig, session_version: AtomicI64, + session_catalog: OnceLock>, reader_factory: OnceLock, runtime_handle: OnceLock, } @@ -216,6 +215,7 @@ impl SeaRestTransport { warehouse_id: warehouse_id.into(), config, session_version: AtomicI64::new(NO_SESSION_VERSION), + session_catalog: OnceLock::new(), reader_factory: OnceLock::new(), runtime_handle: OnceLock::new(), } @@ -254,6 +254,13 @@ impl SeaRestTransport { } } + fn session_catalog_or_hive_metastore(&self) -> &str { + self.session_catalog + .get() + .and_then(Option::as_deref) + .unwrap_or("hive_metastore") + } + /// Build the `/result/chunks/{idx}` URL, optionally with the /// `row_offset` query parameter set. /// @@ -1023,6 +1030,61 @@ impl SeaRestTransport { ); } } + + /// Resolve the session catalog the same way JDBC's `getFunctions` path + /// does before issuing `SHOW FUNCTIONS IN CATALOG`. + async fn query_current_catalog(&self, session_id: &str) -> Result> { + let mut raw = self + .execute_and_read( + session_id, + "SELECT CURRENT_CATALOG()", + &ExecuteParams::default(), + RequestType::ExecuteMetadataQuery, + None, + ExecutionTimeout::Default, + ) + .await?; + let statement_id = raw.statement_id.clone(); + let needs_close = raw.status.state != StatementState::Closed; + + let catalog = loop { + match raw.reader.next_batch().await { + Err(e) => break Err(e), + Ok(None) => break Ok(None), + Ok(Some(batch)) if batch.num_rows() == 0 => continue, + Ok(Some(batch)) => { + let Some(column) = batch.columns().first() else { + break Err(Error::data_loss() + .message("CURRENT_CATALOG() returned a row without a column")); + }; + let values = arrow_cast::cast(column.as_ref(), &arrow_schema::DataType::Utf8) + .map_err(|e| { + Error::data_loss().message(format!( + "CURRENT_CATALOG() returned a non-string value: {e}" + )) + }); + break values.and_then(|values| { + let values = + values + .as_any() + .downcast_ref::() + .ok_or_else(|| { + Error::data_loss().message( + "CURRENT_CATALOG() string cast did not yield StringArray", + ) + })?; + Ok((!values.is_null(0)).then(|| values.value(0).to_owned())) + }); + } + } + }; + + if needs_close { + self.close_orphaned_statement(&statement_id, "query_current_catalog") + .await; + } + catalog + } } /// Convert a parsed `GetChunksResponse` into the kernel-facing @@ -1103,6 +1165,7 @@ impl Transport for SeaRestTransport { session_config: HashMap, ) -> Result { let url = format!("{}/sessions", self.base_url()); + let _ = self.session_catalog.set(catalog.map(str::to_owned)); let request_body = CreateSessionRequest { warehouse_id: self.warehouse_id.clone(), @@ -1693,18 +1756,41 @@ impl Transport for SeaRestTransport { catalog: Option<&str>, schema_pattern: Option<&str>, function_pattern: Option<&str>, - ) -> Result { - let sql = SqlCommandBuilder::build_get_functions(catalog, schema_pattern, function_pattern); + ) -> Result { + let resolved_catalog = match catalog { + Some(catalog) => catalog.to_owned(), + None => match self.query_current_catalog(session_id).await { + Ok(Some(catalog)) if !catalog.is_empty() => catalog, + Ok(_) => self.session_catalog_or_hive_metastore().to_owned(), + Err(e) => { + warn!( + error = %e, + "failed to query current catalog for list_functions; using session catalog fallback" + ); + self.session_catalog_or_hive_metastore().to_owned() + } + }, + }; + let sql = SqlCommandBuilder::build_show_functions( + &resolved_catalog, + schema_pattern, + function_pattern, + ); debug!("list_functions: {}", sql); - self.execute_and_read( - session_id, - &sql, - &ExecuteParams::default(), - RequestType::ExecuteMetadataQuery, - Some(MetadataOperation::Functions), - ExecutionTimeout::Default, - ) - .await + let execute_result = self + .execute_and_read( + session_id, + &sql, + &ExecuteParams::default(), + RequestType::ExecuteMetadataQuery, + Some(MetadataOperation::Functions), + ExecutionTimeout::Default, + ) + .await?; + Ok(ListFunctionsResult { + execute_result, + resolved_catalog, + }) } async fn list_procedure_columns( diff --git a/src/client/transport.rs b/src/client/transport.rs index 96ed383a..ce3ae594 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -145,6 +145,12 @@ pub(crate) struct ExecuteResult { pub status: StatementStatus, } +/// Result of listing functions, including the catalog used by the SHOW query. +pub(crate) struct ListFunctionsResult { + pub execute_result: ExecuteResult, + pub resolved_catalog: String, +} + impl std::fmt::Debug for ExecuteResult { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ExecuteResult") @@ -495,15 +501,15 @@ 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`, resolving the session's current + /// catalog (with a `hive_metastore` fallback) when catalog is None. async fn list_functions( &self, session_id: &str, catalog: Option<&str>, schema_pattern: Option<&str>, function_pattern: Option<&str>, - ) -> Result; + ) -> Result; /// List procedure parameter / return columns, optionally filtered by /// catalog, schema pattern, procedure name pattern, and column name diff --git a/src/metadata/sql.rs b/src/metadata/sql.rs index 03c56a27..75ca045b 100644 --- a/src/metadata/sql.rs +++ b/src/metadata/sql.rs @@ -55,7 +55,7 @@ impl SqlCommandBuilder { /// Convert JDBC/ADBC-style pattern to Hive-style pattern for `SHOW` commands. /// - /// Use this for `SHOW TABLES/SCHEMAS/COLUMNS` patterns, which use Hive-style wildcards. + /// Use this for `SHOW TABLES/SCHEMAS/COLUMNS/FUNCTIONS` patterns. /// For `information_schema` SQL `LIKE` patterns, use [`escape_sql_string`] instead. /// /// Databricks SHOW commands use Hive-style wildcards, not SQL LIKE wildcards: @@ -65,34 +65,30 @@ impl SqlCommandBuilder { /// - `\_` → `_` (escaped literal underscore) /// - `\\` → `\\` (escaped backslash) /// - /// Also escapes single quotes for safe SQL embedding. - /// Matches JDBC driver's `WildcardUtil.jdbcPatternToHive`. + /// SQL-escape quotes and backslashes once, after wildcard conversion. fn jdbc_pattern_to_hive(pattern: &str) -> String { - let mut result = String::with_capacity(pattern.len()); - let mut escape_next = false; + let mut converted = String::with_capacity(pattern.len()); + let mut escaped = false; for ch in pattern.chars() { - if ch == '\\' && !escape_next { - escape_next = true; + if ch == '\\' && !escaped { + escaped = true; continue; } - if escape_next { - // Escaped character: emit literally - if ch == '\\' { - result.push_str("\\\\"); - } else { - result.push(ch); - } - escape_next = false; + if escaped { + converted.push(ch); + escaped = false; } else { match ch { - '%' => result.push('*'), - '_' => result.push('.'), - '\'' => result.push_str("''"), - _ => result.push(ch), + '%' => converted.push('*'), + '_' => converted.push('.'), + _ => converted.push(ch), } } } - result + if escaped { + converted.push('\\'); + } + Self::escape_sql_string(&converted) } /// Whether an ODBC/JDBC-style pattern contains an *active* wildcard @@ -344,42 +340,27 @@ 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. - pub fn build_get_functions( - catalog: Option<&str>, + /// Build the JDBC-compatible `SHOW FUNCTIONS IN CATALOG` query. + pub fn build_show_functions( + catalog: &str, schema_pattern: Option<&str>, function_pattern: Option<&str>, ) -> String { - let prefix = Self::resolve_catalog_prefix(catalog); 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) + " SCHEMA LIKE '{}'", + Self::jdbc_pattern_to_hive(pattern) )); } - if let Some(pattern) = function_pattern { - sql.push_str(&format!( - " AND routine_name LIKE '{}'", - Self::escape_sql_string(pattern) - )); - } + let pattern = function_pattern.unwrap_or("%"); + sql.push_str(&format!(" LIKE '{}'", Self::jdbc_pattern_to_hive(pattern))); - sql.push_str(" ORDER BY routine_catalog, routine_schema, routine_name"); sql } @@ -705,11 +686,39 @@ mod tests { } #[test] - fn test_escape_pattern_with_single_quote() { - let sql = SqlCommandBuilder::new() - .with_schema_pattern(Some("it's")) - .build_show_schemas(); - assert_eq!(sql, "SHOW SCHEMAS IN ALL CATALOGS LIKE 'it''s'"); + fn test_show_patterns_are_sql_escaped_once() { + for (pattern, escaped) in [ + ("it's", "it''s"), + (r"it\'s", "it''s"), + (r"tail\", r"tail\\"), + (r"slash\\'quote", r"slash\\''quote"), + ] { + let builder = SqlCommandBuilder::new() + .with_catalog(Some("main")) + .with_schema_pattern(Some(pattern)) + .with_table_pattern(Some(pattern)) + .with_column_pattern(Some(pattern)); + assert_eq!( + builder.build_show_schemas(), + format!("SHOW SCHEMAS IN `main` LIKE '{escaped}'") + ); + assert_eq!( + builder.build_show_tables(), + format!("SHOW TABLES IN CATALOG `main` SCHEMA LIKE '{escaped}' LIKE '{escaped}'") + ); + assert_eq!( + builder.build_show_columns(Some("main")), + format!( + "SHOW COLUMNS IN CATALOG `main` SCHEMA LIKE '{escaped}' TABLE LIKE '{escaped}' LIKE '{escaped}'" + ) + ); + assert_eq!( + SqlCommandBuilder::build_show_functions("main", Some(pattern), Some(pattern)), + format!( + "SHOW FUNCTIONS IN CATALOG `main` SCHEMA LIKE '{escaped}' LIKE '{escaped}'" + ) + ); + } } #[test] @@ -939,46 +948,53 @@ mod tests { // --- getFunctions SQL builder 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")); - } - #[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")); + let sql = SqlCommandBuilder::build_show_functions("main", None, None); + 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%'")); + let sql = SqlCommandBuilder::build_show_functions("main", Some("default%"), None); + assert_eq!( + sql, + "SHOW FUNCTIONS IN CATALOG `main` 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%'")); + let sql = SqlCommandBuilder::build_show_functions("main", None, Some("avg%")); + assert_eq!(sql, "SHOW FUNCTIONS IN CATALOG `main` 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_%'")); + let sql = SqlCommandBuilder::build_show_functions("prod", Some("public"), Some("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'")); + let sql = SqlCommandBuilder::build_show_functions("my`catalog", Some("it's"), None); + assert_eq!( + sql, + "SHOW FUNCTIONS IN CATALOG `my``catalog` SCHEMA LIKE 'it''s' LIKE '*'" + ); + } + + #[test] + fn test_get_functions_escaped_quotes_are_sql_escaped_once() { + let sql = + SqlCommandBuilder::build_show_functions("main", Some(r"sch\'ema"), Some(r"fn\'name")); + assert_eq!( + sql, + "SHOW FUNCTIONS IN CATALOG `main` SCHEMA LIKE 'sch''ema' LIKE 'fn''name'" + ); } // --- foreign keys with special characters --- diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index 06ca948c..54fabfde 100644 --- a/src/metadata/thrift_shape.rs +++ b/src/metadata/thrift_shape.rs @@ -837,26 +837,22 @@ pub(crate) fn reshape_procedures(batch: &RecordBatch) -> Result { .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.) -pub(crate) fn reshape_functions(batch: &RecordBatch) -> Result { - 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; +/// Reshape the raw `SHOW FUNCTIONS` result into the JDBC `getFunctions` shape. +pub(crate) fn reshape_functions( + batch: &RecordBatch, + resolved_catalog: &str, +) -> Result { + let function_cat = constant_utf8(batch.num_rows(), Some(resolved_catalog)); + let function_schem = utf8_column(batch, "namespace")?; + let function_name = if column_index(batch.schema_ref(), "functionName").is_some() { + utf8_column(batch, "functionName")? + } else { + // Classic SHOW FUNCTIONS exposes a single column named `function`. + utf8_column(batch, "function")? + }; + 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![ @@ -1991,7 +1987,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), @@ -2013,6 +2009,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, true), + 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("sales_total")])), + Arc::new(StringArray::from(vec![Some("sales")])), + Arc::new(StringArray::from(vec![Some("main")])), + Arc::new(StringArray::from(vec![None::<&str>])), + Arc::new(Int32Array::from(vec![Some(1)])), + Arc::new(StringArray::from(vec![Some("sales_total")])), + ], + ) + .unwrap() + } + fn col_names(batch: &RecordBatch) -> Vec { batch .schema() @@ -2049,7 +2068,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(), "main").unwrap(); assert_eq!( col_names(&out), vec![ @@ -2061,11 +2080,44 @@ mod tests { "SPECIFIC_NAME", ] ); - // FUNCTION_TYPE = functionNoTable (1). + assert_eq!( + out.column(2) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "sales_total" + ); + // The wider server integer is narrowed to JDBC SMALLINT. let ftype = out.column(4).as_any().downcast_ref::().unwrap(); assert_eq!(ftype.value(0), 1); } + #[test] + fn reshape_functions_supports_classic_single_column_shape() { + let source = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "function", + DataType::Utf8, + true, + )])), + vec![Arc::new(StringArray::from(vec![Some( + "system.builtin.abs", + )]))], + ) + .unwrap(); + + let out = reshape_functions(&source, "main").unwrap(); + let names = out + .column(2) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(names.value(0), "system.builtin.abs"); + assert!(out.column(1).is_null(0)); + assert!(out.column(3).is_null(0)); + } + /// `build_get_procedure_columns` raw server shape (information_schema /// numeric metadata arrives as strings over the wire). fn server_parameter_rows() -> RecordBatch { diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index 520592f1..87d934d4 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -95,7 +95,7 @@ use crate::result_stream::{ResultBatch, ResultStream}; use crate::session::SessionInner; use crate::telemetry::{ExecutionResultFormat, OperationType, StatementTelemetry, StatementType}; use crate::types::sea::StatementState; -use arrow_array::Array; +use arrow_array::{Array, ArrayRef, StringArray}; use arrow_schema::SchemaRef; use std::sync::Arc; use tracing::{debug, Instrument}; @@ -138,6 +138,42 @@ fn normalize_native_metadata_batch( }) } +fn normalize_native_functions_batch( + batch: &arrow_array::RecordBatch, + requested_catalog: Option<&str>, +) -> Result { + if batch.num_columns() != GET_FUNCTIONS_SCHEMA.fields().len() { + return Err(Error::data_loss().message(format!( + "invalid Thrift-native functions result: expected {} columns, found {}", + GET_FUNCTIONS_SCHEMA.fields().len(), + batch.num_columns() + ))); + } + let mut columns = batch + .columns() + .iter() + .zip(GET_FUNCTIONS_SCHEMA.fields()) + .map(|(column, field)| { + if column.data_type() == field.data_type() { + Ok(Arc::clone(column)) + } else { + arrow_cast::cast(column.as_ref(), field.data_type()).map_err(|e| { + Error::data_loss().message(format!( + "invalid Thrift-native functions column {:?}: cannot cast {} to {}: {e}", + field.name(), + column.data_type(), + field.data_type() + )) + }) + } + }) + .collect::>>()?; + columns[0] = Arc::new(StringArray::from(vec![requested_catalog; batch.num_rows()])) as ArrayRef; + arrow_array::RecordBatch::try_new(GET_FUNCTIONS_SCHEMA.clone(), columns).map_err(|e| { + Error::data_loss().message(format!("invalid Thrift-native functions result: {e}")) + }) +} + async fn native_or_reshaped_stream( raw: ExecuteResult, session: &Arc, @@ -1184,10 +1220,9 @@ impl Metadata { /// Functions visible to the session. Catalog is exact; schema / /// name are patterns. /// - /// Server shape (`SELECT ... FROM information_schema.routines`): - /// `routine_catalog, routine_schema, routine_name, comment, - /// specific_name`. Reshaped kernel-side into the JDBC `getFunctions` - /// column set by [`thrift_shape::reshape_functions`]. + /// Uses `SHOW FUNCTIONS IN CATALOG`, resolving a null catalog from the + /// session like JDBC. Non-native responses are reshaped kernel-side into + /// the JDBC `getFunctions` column set. pub async fn functions( &self, catalog: Option>, @@ -1198,7 +1233,9 @@ impl Metadata { let telemetry = self.metadata_telemetry(OperationType::ListFunctions); let telemetry_for_body = telemetry.clone(); let result = async { - let raw = match self + // JDBC preserves the original argument, including null, for native rows. + let requested_catalog = catalog.as_ref().map(|catalog| catalog.as_str().to_owned()); + let functions_result = match self .session .transport() .list_functions( @@ -1215,12 +1252,26 @@ impl Metadata { .await } }; + let resolved_catalog = functions_result.resolved_catalog; + let raw = functions_result.execute_result; Self::observe_raw_result(&telemetry_for_body, &raw); - native_or_reshaped_stream( - raw, - &self.session, + let stmt_id = close_id(&raw); + let native = is_native_metadata_result(&raw); + let reshaped = ThriftReshapingReader::new( + raw.reader, GET_FUNCTIONS_SCHEMA.clone(), - Box::new(thrift_shape::reshape_functions), + Box::new(move |batch| { + if native { + normalize_native_functions_batch(batch, requested_catalog.as_deref()) + } else { + thrift_shape::reshape_functions(batch, &resolved_catalog) + } + }), + ); + ResultStream::from_reader_with_close( + Box::new(reshaped), + Arc::clone(&self.session), + stmt_id, ) .await } diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 2ee9314a..261488d1 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1291,12 +1291,17 @@ mod tests { async fn list_functions( &self, _session_id: &str, - _catalog: Option<&str>, + catalog: Option<&str>, _schema_pattern: Option<&str>, _function_pattern: Option<&str>, - ) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) - .await + ) -> Result { + let execute_result = self + .execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) + .await?; + Ok(crate::client::ListFunctionsResult { + execute_result, + resolved_catalog: catalog.unwrap_or("hive_metastore").to_owned(), + }) } async fn list_procedure_columns( diff --git a/src/reader/mod.rs b/src/reader/mod.rs index f91ea791..a9dfe479 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1582,7 +1582,7 @@ mod tests { _: Option<&str>, _: Option<&str>, _: Option<&str>, - ) -> Result { + ) -> Result { unreachable!() } async fn list_procedure_columns( diff --git a/tests/v0_metadata_e2e.rs b/tests/v0_metadata_e2e.rs index 5a41ef38..55817e88 100644 --- a/tests/v0_metadata_e2e.rs +++ b/tests/v0_metadata_e2e.rs @@ -497,9 +497,8 @@ async fn foreign_keys_returns_jdbc_columns() { #[ignore] async fn functions_returns_jdbc_columns() { let session = live_session().await; - // Reshaped kernel-side into the JDBC getFunctions column set - // (the raw information_schema.routines columns are renamed by - // reshape_functions). + // Reshaped kernel-side into the JDBC getFunctions column set when + // the server returns the raw SHOW FUNCTIONS result. let stream = session .metadata() .functions(None, None, None) diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index bcb1ee3b..f8daa9e9 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -33,13 +33,13 @@ //! `primary_keys`, etc.) are also covered here. use arrow_array::cast::AsArray; -use arrow_array::{Array, ArrayRef, RecordBatch, StringArray}; +use arrow_array::{Array, ArrayRef, Int32Array, RecordBatch, StringArray}; use arrow_ipc::writer::StreamWriter; use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::metadata_v0::exact_catalog_and_pattern; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, Identifier, LikePattern, ResultBatch, Session, + AuthConfig, ConnectionConfig, DefaultOpts, Identifier, LikePattern, ResultBatch, Session, }; use serde_json::json; use std::sync::Arc; @@ -63,6 +63,24 @@ async fn open_session(server: &MockServer) -> Session { .expect("Session::open should succeed") } +async fn open_session_with_catalog(server: &MockServer, catalog: &str) -> Session { + let mut defaults = DefaultOpts::default(); + defaults.catalog = Some(catalog.to_owned()); + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .defaults(defaults) + .open() + .await + .expect("Session::open should succeed") +} + async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) .and(path("/api/2.0/sql/sessions")) @@ -217,6 +235,56 @@ fn string_batch(cols: Vec<(&str, Vec>)>) -> RecordBatch { RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).unwrap() } +fn native_functions_batch(function_catalog: Option<&str>) -> RecordBatch { + RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("FUNCTION_CAT", DataType::Utf8, true), + Field::new("FUNCTION_SCHEM", DataType::Utf8, true), + Field::new("FUNCTION_NAME", DataType::Utf8, false), + Field::new("REMARKS", DataType::Utf8, true), + // The native backend reports FUNCTION_TYPE as Int32; the public + // JDBC schema requires SMALLINT / Int16. + Field::new("FUNCTION_TYPE", DataType::Int32, true), + Field::new("SPECIFIC_NAME", DataType::Utf8, true), + ])), + vec![ + Arc::new(StringArray::from(vec![function_catalog])), + Arc::new(StringArray::from(vec![Some("default")])), + Arc::new(StringArray::from(vec![Some("test_function")])), + Arc::new(StringArray::from(vec![None::<&str>])), + Arc::new(Int32Array::from(vec![Some(1)])), + Arc::new(StringArray::from(vec![Some("test_function")])), + ], + ) + .unwrap() +} + +fn show_functions_batch(catalog_name: Option<&str>) -> RecordBatch { + let mut fields = vec![ + Field::new("functionName", DataType::Utf8, false), + Field::new("namespace", DataType::Utf8, true), + ]; + let mut arrays: Vec = vec![ + Arc::new(StringArray::from(vec![Some("test_function")])), + Arc::new(StringArray::from(vec![Some("default")])), + ]; + if let Some(catalog_name) = catalog_name { + fields.push(Field::new("catalogName", DataType::Utf8, true)); + arrays.push(Arc::new(StringArray::from(vec![Some(catalog_name)]))); + } + fields.extend([ + Field::new("remarks", DataType::Utf8, true), + Field::new("functionType", DataType::Int32, true), + Field::new("specificName", DataType::Utf8, true), + ]); + arrays.extend([ + Arc::new(StringArray::from(vec![None::<&str>])) as ArrayRef, + Arc::new(Int32Array::from(vec![Some(1)])) as ArrayRef, + Arc::new(StringArray::from(vec![Some("test_function")])) as ArrayRef, + ]); + RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).unwrap() +} + /// Mixed-type RecordBatch builder for `list_columns` fixtures, which /// need `ordinalPosition: Int32` alongside the string columns. fn columns_batch( @@ -327,6 +395,157 @@ async fn native_catalogs_header_and_result_bypass_show_reshape() { assert_eq!(batches[0].column(0).as_string::().value(0), "main"); } +#[tokio::test] +async fn native_functions_preserve_null_catalog_and_remarks() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let current_catalog = string_batch(vec![("current_catalog()", vec![Some("main")])]); + mount_execute_expecting_sql( + &server, + "SELECT CURRENT_CATALOG()", + closed_inline_response_body(¤t_catalog), + ) + .await; + + let native = native_functions_batch(Some("main")); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_string_contains( + "SHOW FUNCTIONS IN CATALOG `main` LIKE '*'", + )) + .and(header( + "x-databricks-metadata-operation-type", + "GetFunctions", + )) + .and(header( + "x-databricks-require-thrift-native-metadata", + "true", + )) + .respond_with( + ResponseTemplate::new(200).set_body_string(native_inline_response_body(&native)), + ) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .functions(None, None, None) + .await + .expect("native functions"); + + let batches = drain_stream(&mut stream).await; + assert_eq!( + col_names(&stream.schema()), + vec![ + "FUNCTION_CAT", + "FUNCTION_SCHEM", + "FUNCTION_NAME", + "REMARKS", + "FUNCTION_TYPE", + "SPECIFIC_NAME", + ] + ); + assert!(batches[0].column(0).is_null(0)); + assert!(!stream.schema().field(2).is_nullable()); + assert_eq!( + batches[0].column(2).as_string::().value(0), + "test_function" + ); + assert!(batches[0].column(3).is_null(0)); + assert_eq!(batches[0].column(4).data_type(), &DataType::Int16); +} + +#[tokio::test] +async fn fallback_functions_use_explicit_catalog_when_server_omits_it() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let raw = show_functions_batch(None); + mount_execute_expecting_sql( + &server, + "SHOW FUNCTIONS IN CATALOG `main` LIKE '*'", + succeeded_inline_response_body(&raw), + ) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .functions(Some(Identifier::new("main").unwrap()), None, None) + .await + .expect("fallback functions with explicit catalog"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches[0].column(0).as_string::().value(0), "main"); +} + +#[tokio::test] +async fn fallback_functions_use_resolved_catalog_when_request_is_null() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let current_catalog = string_batch(vec![("current_catalog()", vec![Some("main")])]); + mount_execute_expecting_sql( + &server, + "SELECT CURRENT_CATALOG()", + closed_inline_response_body(¤t_catalog), + ) + .await; + let raw = show_functions_batch(Some("")); + mount_execute_expecting_sql( + &server, + "SHOW FUNCTIONS IN CATALOG `main` LIKE '*'", + succeeded_inline_response_body(&raw), + ) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .functions(None, None, None) + .await + .expect("fallback functions with resolved catalog"); + let batches = drain_stream(&mut stream).await; + assert_eq!(batches[0].column(0).as_string::().value(0), "main"); +} + +#[tokio::test] +async fn fallback_functions_use_session_catalog_when_current_catalog_fails() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + mount_execute_expecting_sql( + &server, + "SELECT CURRENT_CATALOG()", + failed_response_body("XX000", "catalog lookup failed"), + ) + .await; + let raw = show_functions_batch(Some("")); + mount_execute_expecting_sql( + &server, + "SHOW FUNCTIONS IN CATALOG `uc_catalog` LIKE '*'", + succeeded_inline_response_body(&raw), + ) + .await; + + let session = open_session_with_catalog(&server, "uc_catalog").await; + let mut stream = session + .metadata() + .functions(None, None, None) + .await + .expect("fallback functions with configured catalog"); + let batches = drain_stream(&mut stream).await; + assert_eq!( + batches[0].column(0).as_string::().value(0), + "uc_catalog" + ); +} + #[tokio::test] async fn list_catalogs_returns_table_cat_column() { let server = MockServer::start().await;