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 1714a5bf feat(datafusion): evaluate immutable constant CALL arguments 
(#1290)
1714a5bf is described below

commit 1714a5bf553e9cb5d38b296cbab57a2f3230e521
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 2 09:02:16 2026 +0800

    feat(datafusion): evaluate immutable constant CALL arguments (#1290)
---
 crates/integrations/datafusion/src/procedures.rs   | 88 +++++++++++++++++++++-
 .../datafusion/tests/call_constants.rs             | 82 ++++++++++++++++++++
 docs/src/sql.md                                    | 20 +++++
 3 files changed, 187 insertions(+), 3 deletions(-)

diff --git a/crates/integrations/datafusion/src/procedures.rs 
b/crates/integrations/datafusion/src/procedures.rs
index 19df4563..d7f0b2da 100644
--- a/crates/integrations/datafusion/src/procedures.rs
+++ b/crates/integrations/datafusion/src/procedures.rs
@@ -322,7 +322,7 @@ pub async fn execute_procedure(
     proc_name: &str,
     arguments: &FunctionArguments,
 ) -> DFResult<DataFrame> {
-    let args = extract_named_args(arguments)?;
+    let args = extract_named_args(ctx, arguments)?;
     reject_unknown_args(proc_name, &args)?;
 
     match proc_name {
@@ -376,7 +376,10 @@ fn extract_procedure_name(name: &ObjectName) -> 
DFResult<(Option<String>, String
     }
 }
 
-fn extract_named_args(args: &FunctionArguments) -> DFResult<HashMap<String, 
String>> {
+fn extract_named_args(
+    ctx: &SessionContext,
+    args: &FunctionArguments,
+) -> DFResult<HashMap<String, String>> {
     let arg_list = match args {
         FunctionArguments::List(list) => &list.args,
         FunctionArguments::None => return Ok(HashMap::new()),
@@ -395,7 +398,11 @@ fn extract_named_args(args: &FunctionArguments) -> 
DFResult<HashMap<String, Stri
                 arg: FunctionArgExpr::Expr(expr),
                 operator: FunctionArgOperator::RightArrow,
             } => {
-                let value = expr_to_string(expr)?;
+                let value = match expr_to_string(expr) {
+                    Ok(value) => value,
+                    Err(error) if matches!(expr, SqlExpr::Value(_)) => return 
Err(error),
+                    Err(_) => constant_argument(ctx, expr)?,
+                };
                 let name = name.value.to_lowercase();
                 // Java `PaimonProcedureResolver.buildNameToArgumentMap` 
rejects a repeat
                 // rather than letting the last one win.
@@ -437,6 +444,81 @@ fn expr_to_string(expr: &SqlExpr) -> DFResult<String> {
     }
 }
 
+fn constant_argument(ctx: &SessionContext, expr: &SqlExpr) -> DFResult<String> 
{
+    use datafusion::common::{
+        tree_node::{TreeNode, TreeNodeRecursion},
+        DFSchema,
+    };
+    use datafusion::logical_expr::{simplify::SimplifyContext, Expr, 
Volatility};
+    use datafusion::optimizer::simplify_expressions::ExprSimplifier;
+    let schema = DFSchema::empty();
+    let state = ctx.state();
+    let expression = state.create_logical_expr(&expr.to_string(), &schema)?;
+    expression.apply(|node| {
+        let allowed = match node {
+            Expr::Literal(_, _)
+            | Expr::Alias(_)
+            | Expr::Cast(_)
+            | Expr::TryCast(_)
+            | Expr::BinaryExpr(_)
+            | Expr::Negative(_)
+            | Expr::Not(_)
+            | Expr::Case(_)
+            | Expr::IsNull(_)
+            | Expr::IsNotNull(_)
+            | Expr::Between(_)
+            | Expr::InList(_)
+            | Expr::IsTrue(_)
+            | Expr::IsNotTrue(_)
+            | Expr::IsFalse(_)
+            | Expr::IsNotFalse(_)
+            | Expr::IsUnknown(_)
+            | Expr::IsNotUnknown(_)
+            | Expr::Like(_)
+            | Expr::SimilarTo(_) => true,
+            Expr::ScalarFunction(function) => {
+                function.func.signature().volatility == Volatility::Immutable
+            }
+            _ => false,
+        };
+        if !allowed {
+            return Err(DataFusionError::Plan(
+                "CALL arguments must be immutable scalar constant 
expressions".into(),
+            ));
+        }
+        Ok(TreeNodeRecursion::Continue)
+    })?;
+    let simplifier = ExprSimplifier::new(
+        SimplifyContext::builder()
+            .with_schema(Arc::new(schema.clone()))
+            .with_config_options(state.config_options().clone())
+            .build(),
+    );
+    let expression = simplifier.simplify(simplifier.coerce(expression, 
&schema)?)?;
+    let Expr::Literal(value, _) = expression else {
+        return Err(DataFusionError::Plan(
+            "CALL argument did not reduce to a scalar constant".into(),
+        ));
+    };
+    if let Some(Some(value)) = value.try_as_str() {
+        return Ok(value.to_string());
+    }
+    match value {
+        ScalarValue::Int8(Some(_))
+        | ScalarValue::Int16(Some(_))
+        | ScalarValue::Int32(Some(_))
+        | ScalarValue::Int64(Some(_))
+        | ScalarValue::UInt8(Some(_))
+        | ScalarValue::UInt16(Some(_))
+        | ScalarValue::UInt32(Some(_))
+        | ScalarValue::UInt64(Some(_))
+        | ScalarValue::Boolean(Some(_)) => Ok(value.to_string()),
+        _ => Err(DataFusionError::Plan(
+            "CALL arguments must be non-null strings, integers, or 
booleans".into(),
+        )),
+    }
+}
+
 fn require_arg<'a>(args: &'a HashMap<String, String>, name: &str) -> 
DFResult<&'a str> {
     args.get(name)
         .map(|s| s.as_str())
diff --git a/crates/integrations/datafusion/tests/call_constants.rs 
b/crates/integrations/datafusion/tests/call_constants.rs
new file mode 100644
index 00000000..84ebc637
--- /dev/null
+++ b/crates/integrations/datafusion/tests/call_constants.rs
@@ -0,0 +1,82 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+mod common;
+use paimon::{catalog::Identifier, Catalog};
+#[tokio::test]
+async fn call_folds_typed_constant_arguments_before_changing_metadata() {
+    let (_tmp, catalog) = common::create_test_env();
+    let ctx = common::create_sql_context(catalog.clone()).await;
+    ctx.sql("CREATE TABLE default.c (id INT)").await.unwrap();
+    ctx.sql("INSERT INTO default.c VALUES (1)")
+        .await
+        .unwrap()
+        .collect()
+        .await
+        .unwrap();
+    ctx.sql("CALL sys.create_tag(table => concat('default.', 'c'), tag => 
concat('v', '1'), snapshot_id => CAST(1 + 0 AS BIGINT))").await.unwrap();
+    let table = catalog
+        .get_table(&Identifier::new("default", "c"))
+        .await
+        .unwrap();
+    assert_eq!(
+        table.tag_manager().get("v1").await.unwrap().unwrap().id(),
+        1
+    );
+    for expression in [
+        "CAST(NULL AS BIGINT)",
+        "random()",
+        "(SELECT 1)",
+        "missing_column",
+    ] {
+        assert!(ctx.sql(&format!("CALL sys.create_tag(table => 'default.c', 
tag => 'bad', snapshot_id => {expression})")).await.is_err(),"{expression}");
+        assert!(table.tag_manager().get("bad").await.unwrap().is_none());
+    }
+}
+
+#[tokio::test]
+async fn call_folds_boolean_predicates_and_rejects_errors_before_mutation() {
+    let (_tmp, catalog) = common::create_test_env();
+    let ctx = common::create_sql_context(catalog.clone()).await;
+    ctx.sql("CREATE TABLE default.c (id INT)").await.unwrap();
+    ctx.sql("INSERT INTO default.c VALUES (1)")
+        .await
+        .unwrap()
+        .collect()
+        .await
+        .unwrap();
+    for _ in 0..2 {
+        ctx.sql("CALL sys.create_branch(table => 'default.c', branch => CASE 
WHEN 'prod' LIKE 'p%' THEN 'release' ELSE 'wrong' END, ignore_if_exists => 
(1=1) IS TRUE)").await.unwrap();
+    }
+    let table = catalog
+        .get_table(&Identifier::new("default", "c"))
+        .await
+        .unwrap();
+    let before = table.tag_manager().list_all().await.unwrap().len();
+    for expression in [
+        "CAST('bad' AS BIGINT)",
+        "1 / 0",
+        "ARRAY[1,2]",
+        "current_date",
+        "CAST(NULL AS VARCHAR)",
+    ] {
+        assert!(ctx.sql(&format!("CALL sys.create_tag(table => 'default.c', 
tag => 'bad', snapshot_id => {expression})")).await.is_err(),"{expression}");
+        assert_eq!(table.tag_manager().list_all().await.unwrap().len(), 
before);
+    }
+    assert!(ctx.sql("CALL sys.create_tag(table => 'default.c', tag => 'bad', 
snaphot_id => CAST(1 AS BIGINT))").await.is_err());
+    assert!(table.tag_manager().get("bad").await.unwrap().is_none());
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index a57e1879..974286ba 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -1876,6 +1876,26 @@ meaningful for a column mask, so it requires 
`policy_type => 'COLUMN_MASKING'`:
 CALL sys.list_policies(database => 'sales', table => 'orders');
 ```
 
+### Constant procedure arguments
+
+CALL arguments still use named `name => expression` syntax. In addition to
+literals, SQLContext accepts immutable scalar constant expressions such as
+casts, arithmetic, string functions, CASE and boolean predicates.
+
+```sql
+CALL sys.create_tag(
+    table => concat('my_db.', 'events'),
+    tag => concat('release_', '1'),
+    snapshot_id => CAST(1 + 0 AS BIGINT)
+);
+```
+
+Expressions must reduce to non-NULL strings, integers or booleans. Column
+references, subqueries, aggregate/window functions and non-immutable functions
+are rejected. Argument names, duplicates and procedure-specific types are
+validated as before. All arguments are evaluated and validated before the
+procedure performs any metadata changes; evaluation errors are returned.
+
 ## Queries
 
 ### Basic Queries

Reply via email to