diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 00a37957..31673499 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -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 diff --git a/src/client/sea.rs b/src/client/sea.rs index 0ae802ce..cd25cf5b 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -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) } } @@ -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()); } diff --git a/src/client/transport.rs b/src/client/transport.rs index 96ed383a..3b4914c0 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -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, diff --git a/src/metadata/sql.rs b/src/metadata/sql.rs index 03c56a27..0b2b857f 100644 --- a/src/metadata/sql.rs +++ b/src/metadata/sql.rs @@ -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 } @@ -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 --- diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index 06ca948c..65728deb 100644 --- a/src/metadata/thrift_shape.rs +++ b/src/metadata/thrift_shape.rs @@ -837,26 +837,14 @@ 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.) +/// Reshape the `SHOW FUNCTIONS` result into the JDBC `getFunctions` shape. 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; + let function_cat = utf8_column(batch, "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![ @@ -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 ───────────────────────────────── @@ -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), @@ -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 { batch .schema() @@ -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![ @@ -2061,9 +2073,19 @@ mod tests { "SPECIFIC_NAME", ] ); - // FUNCTION_TYPE = functionNoTable (1). - let ftype = out.column(4).as_any().downcast_ref::().unwrap(); - assert_eq!(ftype.value(0), 1); + assert_eq!(out.column(0).as_string::().value(0), "main"); + assert_eq!(out.column(1).as_string::().value(0), "sales"); + assert_eq!(out.column(2).as_string::().value(0), "sp_report"); + assert_eq!(out.column(3).as_string::().value(0), "nightly report"); + assert_eq!( + out.column(4) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 0 + ); + assert_eq!(out.column(5).as_string::().value(0), "sp_report"); } /// `build_get_procedure_columns` raw server shape (information_schema diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index e03c6fac..ecb66650 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -93,6 +93,7 @@ use crate::metadata::thrift_shape::{ use crate::reader::{EmptyReader, InMemoryReader}; use crate::result_stream::{ResultBatch, ResultStream}; use crate::session::SessionInner; +use crate::statement::Statement; use crate::telemetry::{ExecutionResultFormat, OperationType, StatementTelemetry, StatementType}; use crate::types::sea::StatementState; use arrow_array::{Array, ArrayRef}; @@ -195,6 +196,26 @@ fn normalize_native_metadata_batch( }) } +fn normalize_native_functions_batch( + batch: &arrow_array::RecordBatch, + schema: SchemaRef, + requested_catalog: Option<&str>, +) -> Result { + let normalized = normalize_native_metadata_batch(batch, schema.clone())?; + let mut columns = normalized.columns().to_vec(); + + // Native GetFunctions searches the session catalog and leaves FUNCTION_CAT + // empty. Match JDBC by reporting the caller's original catalog, including null. + columns[0] = Arc::new(arrow_array::StringArray::from(vec![ + requested_catalog; + normalized.num_rows() + ])); + + arrow_array::RecordBatch::try_new(schema, columns).map_err(|e| { + Error::data_loss().message(format!("invalid Thrift-native GetFunctions result: {e}")) + }) +} + async fn native_or_reshaped_stream( raw: ExecuteResult, session: &Arc, @@ -218,6 +239,32 @@ async fn native_or_reshaped_stream( ResultStream::from_reader_with_close(Box::new(reader), Arc::clone(session), stmt_id).await } +async fn native_or_reshaped_functions_stream( + raw: ExecuteResult, + session: &Arc, + requested_catalog: Option, +) -> Result { + let stmt_id = close_id(&raw); + let native = is_native_metadata_result(&raw); + let native_schema = GET_FUNCTIONS_SCHEMA.clone(); + let reader = ThriftReshapingReader::new( + raw.reader, + GET_FUNCTIONS_SCHEMA.clone(), + Box::new(move |batch| { + if native { + normalize_native_functions_batch( + batch, + native_schema.clone(), + requested_catalog.as_deref(), + ) + } else { + thrift_shape::reshape_functions(batch) + } + }), + ); + ResultStream::from_reader_with_close(Box::new(reader), Arc::clone(session), stmt_id).await +} + /// JDBC's `DatabaseMetaData` contract: metadata methods return an /// empty result set for non-existent catalogs / schemas / tables /// rather than raising. Translate `is_object_not_found` errors into @@ -467,6 +514,65 @@ impl Metadata { } } + async fn current_catalog(&self) -> Result { + let mut statement = Statement::new(Arc::clone(&self.session)); + statement.spec().sql("SELECT CURRENT_CATALOG()"); + let mut executed = statement.execute().await?; + + let catalog = match executed.next_batch().await { + Ok(Some(ResultBatch::Arrow(batch))) => { + if batch.num_columns() == 0 || batch.num_rows() == 0 { + Err(Error::data_loss().message("CURRENT_CATALOG() returned no rows or columns")) + } else { + let catalogs = batch + .column(0) + .as_any() + .downcast_ref::() + .ok_or_else(|| { + Error::data_loss() + .message("CURRENT_CATALOG() result is not a UTF-8 string") + }); + catalogs.and_then(|catalogs| { + if catalogs.is_null(0) { + Err(Error::data_loss().message("CURRENT_CATALOG() returned null")) + } else { + Ok(catalogs.value(0).to_owned()) + } + }) + } + } + Ok(None) => Err(Error::data_loss().message("CURRENT_CATALOG() returned no result")), + Err(error) => Err(error), + }; + + if let Err(error) = executed.close().await { + debug!( + error = %error, + "failed to close CURRENT_CATALOG() statement" + ); + } + catalog + } + + async fn resolve_functions_catalog(&self) -> String { + match self.current_catalog().await { + Ok(catalog) => catalog, + Err(error) => { + let fallback = self + .session + .default_catalog() + .unwrap_or("hive_metastore") + .to_owned(); + debug!( + error = %error, + catalog = %fallback, + "failed to resolve current catalog for list_functions; using fallback" + ); + fallback + } + } + } + /// All catalogs visible to the session. /// /// JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. @@ -1241,10 +1347,11 @@ 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`]. + /// SQL fallback shape (`SHOW FUNCTIONS IN CATALOG ...`): + /// `functionName, namespace, catalogName, remarks, functionType, + /// specificName`. Reshaped kernel-side into the JDBC `getFunctions` + /// column set by [`thrift_shape::reshape_functions`]. Thrift-native + /// results are normalized directly to that public schema. pub async fn functions( &self, catalog: Option>, @@ -1255,12 +1362,17 @@ impl Metadata { let telemetry = self.metadata_telemetry(OperationType::ListFunctions); let telemetry_for_body = telemetry.clone(); let result = async { + let requested_catalog = catalog.as_ref().map(|catalog| catalog.as_str().to_owned()); + let resolved_catalog = match catalog.as_ref() { + Some(catalog) => catalog.as_str().to_owned(), + None => self.resolve_functions_catalog().await, + }; let raw = match self .session .transport() .list_functions( self.session.session_id(), - catalog.as_ref().map(|i| i.as_str()), + Some(resolved_catalog.as_str()), schema_pattern.as_ref().map(|p| p.as_str()), name_pattern.as_ref().map(|p| p.as_str()), ) @@ -1273,13 +1385,7 @@ impl Metadata { } }; Self::observe_raw_result(&telemetry_for_body, &raw); - native_or_reshaped_stream( - raw, - &self.session, - GET_FUNCTIONS_SCHEMA.clone(), - Box::new(thrift_shape::reshape_functions), - ) - .await + native_or_reshaped_functions_stream(raw, &self.session, requested_catalog).await } .instrument(span) .await; diff --git a/src/session.rs b/src/session.rs index 74214243..7f05b065 100644 --- a/src/session.rs +++ b/src/session.rs @@ -156,6 +156,14 @@ impl SessionInner { &self.session_id } + /// Catalog configured as the session default, if any. + pub(crate) fn default_catalog(&self) -> Option<&str> { + self.config + .defaults + .as_ref() + .and_then(|defaults| defaults.catalog.as_deref()) + } + /// Crate-internal accessor for the per-session tracing span. /// Callers clone the span and `.entered()` it at the top of each /// public method body. diff --git a/tests/v0_metadata_e2e.rs b/tests/v0_metadata_e2e.rs index 5a41ef38..9c854caf 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 executes the SHOW fallback; native results already use it. let stream = session .metadata() .functions(None, None, None) diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 5796602c..e8a8c19f 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -39,7 +39,7 @@ 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; @@ -49,7 +49,11 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; // ─── Helpers ──────────────────────────────────────────────────────── async fn open_session(server: &MockServer) -> Session { - Session::builder() + open_session_with_default_catalog(server, None).await +} + +async fn open_session_with_default_catalog(server: &MockServer, catalog: Option<&str>) -> Session { + let builder = Session::builder() .connection( ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") .expect("valid http_path"), @@ -57,10 +61,16 @@ async fn open_session(server: &MockServer) -> Session { .auth(AuthConfig::Pat { token: "dapi_test_token".into(), identity_federation_client_id: None, - }) - .open() - .await - .expect("Session::open should succeed") + }); + let builder = match catalog { + Some(catalog) => { + let mut defaults = DefaultOpts::default(); + defaults.catalog = Some(catalog.to_owned()); + builder.defaults(defaults) + } + None => builder, + }; + builder.open().await.expect("Session::open should succeed") } async fn mount_create_session(server: &MockServer) { @@ -191,6 +201,25 @@ fn closed_inline_response_body(batch: &RecordBatch) -> String { succeeded_inline_response_body(batch).replace(r#""state":"SUCCEEDED""#, r#""state":"CLOSED""#) } +async fn mount_current_catalog(server: &MockServer, catalog: Option<&str>) { + let current_catalog = string_batch(vec![( + "current_catalog()", + catalog + .map(|catalog| vec![Some(catalog)]) + .unwrap_or_default(), + )]); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_string_contains("SELECT CURRENT_CATALOG()")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(closed_inline_response_body(¤t_catalog)), + ) + .expect(1) + .mount(server) + .await; +} + /// Like [`succeeded_inline_response_body`] but with a caller-chosen /// `statement_id` and `status.state`. Used by the wildcard fan-out /// CLOSED-skip test, which stubs several statements in one call and must @@ -217,6 +246,28 @@ fn string_batch(cols: Vec<(&str, Vec>)>) -> RecordBatch { RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).unwrap() } +fn functions_batch(catalog: &str) -> RecordBatch { + RecordBatch::try_new( + 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), + ])), + vec![ + Arc::new(StringArray::from(vec![Some("answer")])), + Arc::new(StringArray::from(vec![Some("default")])), + Arc::new(StringArray::from(vec![Some(catalog)])), + Arc::new(StringArray::from(vec![Some("Returns 42")])), + Arc::new(Int32Array::from(vec![Some(1)])), + Arc::new(StringArray::from(vec![Some("answer")])), + ], + ) + .unwrap() +} + /// Mixed-type RecordBatch builder for `list_columns` fixtures, which /// need `ordinalPosition: Int32` alongside the string columns. fn columns_batch( @@ -416,6 +467,178 @@ async fn native_columns_zero_based_ordinal_is_one_based() { assert_eq!(ordinal.value(0), 1); } +#[tokio::test] +async fn native_functions_header_and_result_match_jdbc() { + for (catalog, expected_sql, expected_catalog) in [ + (None, "SHOW FUNCTIONS IN CATALOG `main` LIKE '*'", None), + ( + Some("main"), + "SHOW FUNCTIONS IN CATALOG `main` LIKE '*'", + Some("main"), + ), + ] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + if catalog.is_none() { + mount_current_catalog(&server, Some("main")).await; + } + + let native = 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), + Field::new("FUNCTION_TYPE", DataType::Int32, true), + Field::new("SPECIFIC_NAME", DataType::Utf8, true), + ])), + vec![ + Arc::new(StringArray::from(vec![Some("")])), + Arc::new(StringArray::from(vec![Some("default")])), + Arc::new(StringArray::from(vec![Some("answer")])), + Arc::new(StringArray::from(vec![Some("Returns 42")])), + Arc::new(Int32Array::from(vec![Some(1)])), + Arc::new(StringArray::from(vec![Some("answer")])), + ], + ) + .unwrap(); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(header( + "x-databricks-metadata-operation-type", + "GetFunctions", + )) + .and(header( + "x-databricks-require-thrift-native-metadata", + "true", + )) + .and(body_string_contains(expected_sql)) + .respond_with( + ResponseTemplate::new(200).set_body_string(native_inline_response_body(&native)), + ) + .mount(&server) + .await; + + let session = open_session(&server).await; + let catalog = catalog.map(|catalog| Identifier::new(catalog).unwrap()); + let mut stream = session + .metadata() + .functions(catalog, None, None) + .await + .expect("native list_functions"); + assert_eq!( + col_names(&stream.schema()), + vec![ + "FUNCTION_CAT", + "FUNCTION_SCHEM", + "FUNCTION_NAME", + "REMARKS", + "FUNCTION_TYPE", + "SPECIFIC_NAME", + ] + ); + + let batches = drain_stream(&mut stream).await; + let function_catalog = batches[0] + .column_by_name("FUNCTION_CAT") + .unwrap() + .as_string::(); + assert_eq!( + (!function_catalog.is_null(0)).then(|| function_catalog.value(0)), + expected_catalog + ); + let function_type = batches[0] + .column_by_name("FUNCTION_TYPE") + .unwrap() + .as_primitive::(); + assert_eq!(function_type.value(0), 1); + } +} + +#[tokio::test] +async fn functions_sql_fallback_uses_current_catalog() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + mount_current_catalog(&server, Some("main")).await; + + let functions = functions_batch("main"); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(header( + "x-databricks-metadata-operation-type", + "GetFunctions", + )) + .and(body_string_contains( + "SHOW FUNCTIONS IN CATALOG `main` LIKE '*'", + )) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_inline_response_body(&functions)), + ) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .functions(None, None, None) + .await + .expect("list_functions SQL fallback"); + let batches = drain_stream(&mut stream).await; + assert_eq!( + batches[0] + .column_by_name("FUNCTION_CAT") + .unwrap() + .as_string::() + .value(0), + "main" + ); +} + +#[tokio::test] +async fn functions_falls_back_when_current_catalog_is_unavailable() { + for (configured_catalog, expected_catalog) in + [(Some("configured"), "configured"), (None, "hive_metastore")] + { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + mount_current_catalog(&server, None).await; + + let functions = functions_batch(expected_catalog); + mount_execute_expecting_sql( + &server, + &format!("SHOW FUNCTIONS IN CATALOG `{expected_catalog}` LIKE '*'"), + succeeded_inline_response_body(&functions), + ) + .await; + + let session = match configured_catalog { + Some(catalog) => open_session_with_default_catalog(&server, Some(catalog)).await, + None => open_session(&server).await, + }; + let mut stream = session + .metadata() + .functions(None, None, None) + .await + .expect("list_functions catalog fallback"); + let batches = drain_stream(&mut stream).await; + assert_eq!( + batches[0] + .column_by_name("FUNCTION_CAT") + .unwrap() + .as_string::() + .value(0), + expected_catalog + ); + } +} + #[tokio::test] async fn list_catalogs_returns_table_cat_column() { let server = MockServer::start().await;