This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-rust.git
The following commit(s) were added to refs/heads/main by this push:
new a756831a fix(datafusion): resolve registered functions before REST
lookup (#1277)
a756831a is described below
commit a756831aad64026791ca5cfb05807df5b917380b
Author: Jingsong Lee <[email protected]>
AuthorDate: Sun Nov 1 23:49:33 2026 +0800
fix(datafusion): resolve registered functions before REST lookup (#1277)
---
crates/integrations/datafusion/README.md | 8 +
crates/integrations/datafusion/src/catalog.rs | 1 +
crates/integrations/datafusion/src/sql_context.rs | 173 +++++++++++++++++++++
crates/integrations/datafusion/src/sql_function.rs | 66 +++++++-
4 files changed, 241 insertions(+), 7 deletions(-)
diff --git a/crates/integrations/datafusion/README.md
b/crates/integrations/datafusion/README.md
index b12615c4..92e0ba93 100644
--- a/crates/integrations/datafusion/README.md
+++ b/crates/integrations/datafusion/README.md
@@ -100,6 +100,14 @@ RETURN scalar_expression;
Use `SQLContext::sql` for function expansion:
+Bare calls to registered DataFusion scalar, higher-order, aggregate, and
window functions
+(including aliases and session UDFs) resolve locally without a REST function
+lookup. Use `catalog.database.function(...)` to explicitly call a catalog
+function with a colliding name. Catalog lookup errors, including permission
+denials, are preserved for those explicit calls and for unknown bare names.
+SQL lambda syntax for higher-order functions follows DataFusion's configured
+SQL dialect, such as DuckDB.
+
```rust,ignore
let mut ctx = paimon_datafusion::SQLContext::new();
ctx.register_catalog("paimon", rest_catalog).await?;
diff --git a/crates/integrations/datafusion/src/catalog.rs
b/crates/integrations/datafusion/src/catalog.rs
index e5093f14..d6227c4b 100644
--- a/crates/integrations/datafusion/src/catalog.rs
+++ b/crates/integrations/datafusion/src/catalog.rs
@@ -1079,6 +1079,7 @@ impl SchemaProvider for PaimonSchemaProvider {
let catalogs =
HashMap::from([(catalog_name.clone(),
Arc::clone(&catalog))]);
let query = crate::sql_function::expand_sql(
+ &state,
view.query_for("datafusion"),
&catalogs,
&catalog_name,
diff --git a/crates/integrations/datafusion/src/sql_context.rs
b/crates/integrations/datafusion/src/sql_context.rs
index 234952ee..6664835e 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -753,6 +753,7 @@ impl SQLContext {
.default_schema
.clone();
let expanded = crate::sql_function::expand_statement(
+ &self.ctx.state(),
statements[0].clone(),
&self.catalogs,
¤t_catalog,
@@ -848,6 +849,7 @@ impl SQLContext {
.default_schema
.clone();
let expanded = crate::sql_function::expand_sql(
+ &self.ctx.state(),
&rewritten_sql,
&self.catalogs,
¤t_catalog,
@@ -1974,6 +1976,7 @@ impl SQLContext {
state.config_mut().options_mut().catalog.default_schema =
identifier.database().to_string();
let expanded_query = crate::sql_function::expand_sql(
+ &self.ctx.state(),
&query_sql,
&self.catalogs,
&catalog_name,
@@ -2162,6 +2165,7 @@ impl SQLContext {
quote(function.name())
);
let expanded = crate::sql_function::expand_sql_with_candidate(
+ &self.ctx.state(),
&validation_sql,
&self.catalogs,
catalog_name,
@@ -4015,6 +4019,7 @@ mod tests {
use async_trait::async_trait;
use datafusion::arrow::array::StringViewArray;
+ use datafusion::common::ScalarValue;
use datafusion::execution::memory_pool::FairSpillPool;
use datafusion::execution::runtime_env::RuntimeEnvBuilder;
use datafusion::sql::sqlparser::dialect::PostgreSqlDialect;
@@ -4065,6 +4070,8 @@ mod tests {
calls: Mutex<Vec<CatalogCall>>,
existing_table: Mutex<Option<Table>>,
functions: Mutex<HashMap<Identifier, paimon::catalog::Function>>,
+ denied_functions: Mutex<std::collections::HashSet<String>>,
+ function_lookups: Mutex<Vec<Identifier>>,
views: Mutex<HashMap<Identifier, paimon::catalog::View>>,
drop_view_supported: bool,
}
@@ -4075,6 +4082,8 @@ mod tests {
calls: Mutex::new(Vec::new()),
existing_table: Mutex::new(None),
functions: Mutex::new(HashMap::new()),
+ denied_functions: Mutex::new(Default::default()),
+ function_lookups: Mutex::new(Vec::new()),
views: Mutex::new(HashMap::new()),
drop_view_supported: true,
}
@@ -4221,6 +4230,24 @@ mod tests {
&self,
identifier: &Identifier,
) -> paimon::Result<paimon::catalog::Function> {
+ self.function_lookups
+ .lock()
+ .unwrap()
+ .push(identifier.clone());
+ if self
+ .denied_functions
+ .lock()
+ .unwrap()
+ .contains(identifier.object())
+ {
+ return Err(paimon::Error::UnexpectedError {
+ message: format!(
+ "Forbidden: cannot access function {}",
+ identifier.full_name()
+ ),
+ source: None,
+ });
+ }
self.functions
.lock()
.unwrap()
@@ -5614,6 +5641,151 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn registered_functions_bypass_rest_function_lookup() {
+ use datafusion::logical_expr::{create_udf, Volatility};
+ let catalog = Arc::new(MockCatalog::new());
+ catalog
+ .denied_functions
+ .lock()
+ .unwrap()
+ .extend(["count", "abs", "row_number",
"registered_identity"].map(str::to_string));
+ let ctx = make_sql_context(catalog.clone()).await;
+ ctx.ctx().register_udf(create_udf(
+ "registered_identity",
+ vec![ArrowDataType::Int64],
+ ArrowDataType::Int64,
+ Volatility::Immutable,
+ Arc::new(|args| Ok(args[0].clone())),
+ ));
+ let batches = ctx
+ .sql(
+ "SELECT count(*) AS n, abs(-2) AS a, row_number() OVER () AS
r, \
+ registered_identity(CAST(42 AS BIGINT)) AS v",
+ )
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ for (name, expected) in [("n", 1), ("a", 2), ("r", 1), ("v", 42)] {
+ let value =
+
ScalarValue::try_from_array(batches[0].column_by_name(name).unwrap(),
0).unwrap();
+ assert_eq!(value.to_string(), expected.to_string());
+ }
+ assert!(catalog.function_lookups.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn registered_higher_order_functions_bypass_rest_lookup() {
+ let catalog = Arc::new(MockCatalog::new());
+ catalog
+ .denied_functions
+ .lock()
+ .unwrap()
+ .extend(["array_transform", "list_transform"].map(str::to_string));
+ let ctx = make_sql_context(catalog.clone()).await;
+ ctx.sql("SET datafusion.sql_parser.dialect = 'duckdb'")
+ .await
+ .unwrap();
+ ctx.ctx()
+ .sql("SELECT array_transform([1, 2], x -> x + 1) = [2, 3]")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ for function in ["array_transform", "list_transform"] {
+ let batches = ctx
+ .sql(&format!("SELECT {function}([1, 2], x -> x + 1) = [2,
3]"))
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
+ ScalarValue::Boolean(Some(true))
+ );
+ }
+ assert!(catalog.function_lookups.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn nested_rest_function_leaves_registered_functions_local() {
+ let catalog = Arc::new(MockCatalog::new());
+ add_unary_sql_function(&catalog, "local_math", "abs(x) + 1", true);
+ catalog
+ .denied_functions
+ .lock()
+ .unwrap()
+ .insert("abs".into());
+ let ctx = make_sql_context(catalog.clone()).await;
+ add_bigint_view(
+ &catalog,
+ "default",
+ "local_math_view",
+ "SELECT local_math(-41) AS answer",
+ );
+ for sql in [
+ "SELECT local_math(-41) AS answer",
+ "SELECT * FROM local_math_view",
+ ] {
+ let batches = ctx.sql(sql).await.unwrap().collect().await.unwrap();
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
+ ScalarValue::Int64(Some(42))
+ );
+ }
+ assert!(catalog
+ .function_lookups
+ .lock()
+ .unwrap()
+ .iter()
+ .all(|id| id.object() != "abs"));
+ }
+
+ #[tokio::test]
+ async fn qualified_collision_does_not_rebind_nested_local_function() {
+ let catalog = Arc::new(MockCatalog::new());
+ add_unary_sql_function(&catalog, "abs", "x + 100", true);
+ add_unary_sql_function(&catalog, "local_math", "abs(x) + 1", true);
+ let ctx = make_sql_context(catalog).await;
+ let batches = ctx
+ .sql("SELECT paimon.default.abs(1), local_math(-41)")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
+ ScalarValue::Int64(Some(101))
+ );
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(1), 0).unwrap(),
+ ScalarValue::Int64(Some(42))
+ );
+ }
+
+ #[tokio::test]
+ async fn
explicit_rest_function_and_unknown_function_preserve_permission_errors() {
+ let catalog = Arc::new(MockCatalog::new());
+ catalog
+ .denied_functions
+ .lock()
+ .unwrap()
+ .extend(["abs".to_string(), "private_function".to_string()]);
+ let ctx = make_sql_context(catalog).await;
+ for sql in ["SELECT paimon.default.abs(1)", "SELECT
private_function(1)"] {
+ let error = ctx.sql(sql).await.unwrap_err().to_string();
+ assert!(
+ error.contains("Forbidden: cannot access function"),
+ "{error}"
+ );
+ }
+ }
+
#[tokio::test]
async fn bare_rest_sql_function_is_expanded() {
let catalog = Arc::new(MockCatalog::new());
@@ -6031,6 +6203,7 @@ mod tests {
.remove(0);
let error = crate::sql_function::expand_statement_with_budget(
+ &ctx.ctx.state(),
statement,
&ctx.catalogs,
&ctx.current_catalog_name(),
diff --git a/crates/integrations/datafusion/src/sql_function.rs
b/crates/integrations/datafusion/src/sql_function.rs
index 4d6af48a..ad7d643e 100644
--- a/crates/integrations/datafusion/src/sql_function.rs
+++ b/crates/integrations/datafusion/src/sql_function.rs
@@ -20,6 +20,7 @@ use std::ops::ControlFlow;
use std::sync::Arc;
use datafusion::error::{DataFusionError, Result as DFResult};
+use datafusion::execution::SessionState;
use datafusion::sql::planner::IdentNormalizer;
use datafusion::sql::sqlparser::ast::{
visit_expressions, visit_expressions_mut, Expr as SqlExpr, FunctionArg,
FunctionArgExpr,
@@ -35,15 +36,25 @@ const MAX_EXPANDED_CALLS: usize = 1024;
type FunctionReference = (String, Identifier);
pub(crate) async fn expand_sql(
+ state: &SessionState,
sql: &str,
catalogs: &HashMap<String, Arc<dyn Catalog>>,
current_catalog: &str,
current_database: &str,
) -> DFResult<String> {
- expand_sql_internal(sql, catalogs, current_catalog, current_database,
None).await
+ expand_sql_internal(
+ state,
+ sql,
+ catalogs,
+ current_catalog,
+ current_database,
+ None,
+ )
+ .await
}
async fn expand_sql_internal(
+ state: &SessionState,
sql: &str,
catalogs: &HashMap<String, Arc<dyn Catalog>>,
current_catalog: &str,
@@ -59,6 +70,7 @@ async fn expand_sql_internal(
)));
}
let statement = expand_statement_internal(
+ state,
statements.remove(0),
catalogs,
current_catalog,
@@ -71,6 +83,7 @@ async fn expand_sql_internal(
}
pub(crate) async fn expand_sql_with_candidate(
+ state: &SessionState,
sql: &str,
catalogs: &HashMap<String, Arc<dyn Catalog>>,
current_catalog: &str,
@@ -78,6 +91,7 @@ pub(crate) async fn expand_sql_with_candidate(
candidate: &Function,
) -> DFResult<String> {
expand_sql_internal(
+ state,
sql,
catalogs,
current_catalog,
@@ -88,12 +102,14 @@ pub(crate) async fn expand_sql_with_candidate(
}
pub(crate) async fn expand_statement(
+ state: &SessionState,
statement: Statement,
catalogs: &HashMap<String, Arc<dyn Catalog>>,
current_catalog: &str,
current_database: &str,
) -> DFResult<Statement> {
expand_statement_with_budget(
+ state,
statement,
catalogs,
current_catalog,
@@ -104,6 +120,7 @@ pub(crate) async fn expand_statement(
}
pub(crate) async fn expand_statement_with_budget(
+ state: &SessionState,
statement: Statement,
catalogs: &HashMap<String, Arc<dyn Catalog>>,
current_catalog: &str,
@@ -111,6 +128,7 @@ pub(crate) async fn expand_statement_with_budget(
max_expanded_calls: usize,
) -> DFResult<Statement> {
expand_statement_internal(
+ state,
statement,
catalogs,
current_catalog,
@@ -122,6 +140,7 @@ pub(crate) async fn expand_statement_with_budget(
}
async fn expand_statement_internal(
+ state: &SessionState,
mut statement: Statement,
catalogs: &HashMap<String, Arc<dyn Catalog>>,
current_catalog: &str,
@@ -139,7 +158,7 @@ async fn expand_statement_internal(
let _: ControlFlow<()> = visit_expressions(&statement, |expr| {
if let SqlExpr::Function(function) = expr {
if let Some(reference) =
- function_reference(function, current_catalog,
current_database)
+ function_reference(function, current_catalog,
current_database, state)
{
references.insert(reference, ());
}
@@ -172,7 +191,8 @@ async fn expand_statement_internal(
}
};
if let Some(function) = &function {
- let nested = function_dependencies(function, &reference.0,
reference.1.database());
+ let nested =
+ function_dependencies(function, &reference.0,
reference.1.database(), state);
pending.extend(nested.iter().cloned());
dependencies.insert(reference.clone(), nested);
}
@@ -195,7 +215,8 @@ async fn expand_statement_internal(
let SqlExpr::Function(call) = expr else {
return ControlFlow::Continue(());
};
- let Some(reference) = function_reference(call, current_catalog,
current_database)
+ let Some(reference) =
+ function_reference(call, current_catalog, current_database,
state)
else {
return ControlFlow::Continue(());
};
@@ -209,7 +230,7 @@ async fn expand_statement_internal(
}
total_expanded_calls += 1;
- match expand_call(function, call, &reference.0, &functions) {
+ match expand_call(function, call, &reference.0, &functions, state)
{
Ok(expanded) => {
*expr = expanded;
expanded_count += 1;
@@ -235,6 +256,7 @@ fn function_dependencies(
function: &Function,
current_catalog: &str,
current_database: &str,
+ state: &SessionState,
) -> Vec<FunctionReference> {
let Some(definition) = function
.definition("datafusion")
@@ -251,7 +273,20 @@ fn function_dependencies(
let mut dependencies = Vec::new();
let _: ControlFlow<()> = visit_expressions(&body, |expr| {
if let SqlExpr::Function(call) = expr {
- if let Some(reference) = function_reference(call, current_catalog,
current_database) {
+ // A definition's self-reference is recursive even if it shares a
+ // name with a local function. Preserve this validation before
CREATE.
+ if bare_function_name(call)
+ .as_ref()
+ .map(normalize_identifier)
+ .as_deref()
+ == Some(function.name())
+ {
+ dependencies.push((current_catalog.to_string(),
function.identifier().clone()));
+ return ControlFlow::Continue(());
+ }
+ if let Some(reference) =
+ function_reference(call, current_catalog, current_database,
state)
+ {
dependencies.push(reference);
}
}
@@ -304,6 +339,7 @@ fn function_reference(
function: &datafusion::sql::sqlparser::ast::Function,
current_catalog: &str,
current_database: &str,
+ state: &SessionState,
) -> Option<(String, Identifier)> {
let identifiers = function
.name
@@ -312,6 +348,10 @@ fn function_reference(
.map(|part| part.as_ident().map(normalize_identifier))
.collect::<Option<Vec<_>>>()?;
match identifiers.as_slice() {
+ // Local registrations (including aliases) follow DataFusion
resolution first.
+ // An explicitly qualified call still requests the catalog function,
even
+ // when its name collides with a local scalar, aggregate or window
function.
+ [function] if is_registered_function(state, function) => None,
[function] => Some((
current_catalog.to_string(),
Identifier::new(current_database, function),
@@ -327,11 +367,19 @@ fn normalize_identifier(identifier: &Ident) -> String {
IdentNormalizer::default().normalize(identifier.clone())
}
+fn is_registered_function(state: &SessionState, name: &str) -> bool {
+ state.scalar_functions().contains_key(name)
+ || state.higher_order_functions().contains_key(name)
+ || state.aggregate_functions().contains_key(name)
+ || state.window_functions().contains_key(name)
+}
+
fn expand_call(
function: &Function,
call: &datafusion::sql::sqlparser::ast::Function,
owner_catalog: &str,
functions: &HashMap<FunctionReference, Option<Function>>,
+ state: &SessionState,
) -> DFResult<SqlExpr> {
if !function.is_deterministic() {
return Err(DataFusionError::Plan(format!(
@@ -434,6 +482,9 @@ fn expand_call(
return ControlFlow::Continue(());
};
let function_name = normalize_identifier(&function_name);
+ if is_registered_function(state, &function_name) {
+ return ControlFlow::Continue(());
+ }
let reference = (
owner_catalog.to_string(),
Identifier::new(function.identifier().database(), &function_name),
@@ -497,7 +548,8 @@ mod tests {
async fn leaves_bare_functions_for_datafusion_without_a_paimon_catalog() {
let sql = "SELECT vector_from_json('[1, 2.5]')";
- let expanded = expand_sql(sql, &HashMap::new(), "datafusion", "public")
+ let state = datafusion::prelude::SessionContext::new().state();
+ let expanded = expand_sql(&state, sql, &HashMap::new(), "datafusion",
"public")
.await
.unwrap();