gstvg commented on code in PR #21679:
URL: https://github.com/apache/datafusion/pull/21679#discussion_r3135637807


##########
datafusion/physical-expr/src/higher_order_function.rs:
##########
@@ -0,0 +1,619 @@
+// 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.
+
+//! Declaration of built-in (higher order) functions.
+//! This module contains built-in functions' enumeration and metadata.
+//!
+//! Generally, a function has:
+//! * a signature
+//! * a return type, that is a function of the incoming argument's types
+//! * the computation, that must accept each valid signature
+//!
+//! * Signature: see `Signature`
+//! * Return type: a function `(arg_types) -> return_type`. E.g. for 
array_transform, ([[f32]], v -> v*2) -> [f32], ([[f32]], v -> v > 3.0) -> 
[bool].
+//!
+//! This module also has a set of coercion rules to improve user experience: 
if an argument i32 is passed
+//! to a function that supports f64, it is coerced to f64.
+
+use std::fmt::{self, Debug, Formatter};
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+use crate::PhysicalExpr;
+use crate::expressions::{LambdaExpr, Literal};
+
+use arrow::array::{Array, RecordBatch};
+use arrow::datatypes::{DataType, FieldRef, Schema};
+use datafusion_common::config::{ConfigEntry, ConfigOptions};
+use datafusion_common::utils::remove_list_null_values;
+use datafusion_common::{
+    Result, ScalarValue, exec_datafusion_err, exec_err, 
internal_datafusion_err,
+    internal_err, plan_err,
+};
+use 
datafusion_expr::type_coercion::functions::value_fields_with_higher_order_udf;
+use datafusion_expr::{
+    ColumnarValue, HigherOrderFunctionArgs, HigherOrderReturnFieldArgs, 
HigherOrderUDF,
+    LambdaArgument, ValueOrLambda, Volatility, expr_vec_fmt,
+};
+
+/// Physical expression of a higher order function
+pub struct HigherOrderFunctionExpr {
+    /// A shared instance of the higher-order function
+    fun: Arc<dyn HigherOrderUDF>,
+    /// The name of the higher-order function
+    name: String,
+    /// List of expressions to feed to the function as arguments
+    ///
+    /// For example, for `array_transform([2, 3], v -> v != 2)`, this will be:
+    ///
+    /// ```text
+    /// ListExpression [2,3]
+    /// LambdaExpression
+    ///     parameters: ["v"]
+    ///     body:
+    ///         BinaryExpression (!=)
+    ///             left:
+    ///                 LambdaVariableExpression("v", Field::new("", Int32, 
false))
+    ///             right:
+    ///                 LiteralExpression("2")
+    /// ```
+    args: Vec<Arc<dyn PhysicalExpr>>,
+    /// Positions in `args` where lambdas can be found, either wrapped or not
+    ///
+    /// For example, for `array_transform([2, 3], v -> v != 2)`, this will be 
`vec![1]`
+    lambda_positions: Vec<usize>,
+    /// The output field associated this expression
+    ///
+    /// For example, for `array_transform([2, 3], v -> v != 2)`, this will be
+    /// `Field::new("", DataType::new_list(DataType::Boolean, true), true)`
+    return_field: FieldRef,
+    /// The config options at execution time
+    config_options: Arc<ConfigOptions>,
+}
+
+impl Debug for HigherOrderFunctionExpr {
+    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+        f.debug_struct("HigherOrderFunctionExpr")
+            .field("fun", &"<FUNC>")
+            .field("name", &self.name)
+            .field("args", &self.args)
+            .field("lambda_positions", &self.lambda_positions)
+            .field("return_field", &self.return_field)
+            .finish()
+    }
+}
+
+impl HigherOrderFunctionExpr {
+    /// Create a new Higher Order function
+    ///
+    /// Note that lambda arguments must be present directly in args as 
[LambdaExpr],
+    /// and not as a wrapped child of any arg
+    pub fn try_new(
+        fun: Arc<dyn HigherOrderUDF>,
+        args: Vec<Arc<dyn PhysicalExpr>>,
+        schema: &Schema,
+        config_options: Arc<ConfigOptions>,
+    ) -> Result<Self> {
+        let name = fun.name().to_string();
+        let mut lambda_positions = vec![];
+        let arg_fields = args
+            .iter()
+            .enumerate()
+            .map(|(i, e)| match e.downcast_ref::<LambdaExpr>() {
+                Some(lambda) => {
+                    lambda_positions.push(i);
+
+                    
Ok(ValueOrLambda::Lambda(lambda.body().return_field(schema)?))
+                }
+                None => Ok(ValueOrLambda::Value(e.return_field(schema)?)),
+            })
+            .collect::<Result<Vec<_>>>()?;

Review Comment:
   Thats intentional and there's already tests that cover this: 
   
   
https://github.com/apache/datafusion/pull/21679/changes/ca260a7ef6623251705f0de7d2e93f6affd5ab89#diff-82f03654507864698a026045144642b3dcda8aedc20d29aea782f28b47b9d0eaR558-R637
   
   
https://github.com/apache/datafusion/blob/ca260a7ef6623251705f0de7d2e93f6affd5ab89/datafusion/physical-expr/src/higher_order_function.rs#L559-L638
   
   runs sucessfully when the lambda get's wrapped via with_new_children, but 
fail with wrapped lambdas via HigherOrderFunction::try_new. There's no reason 
to support wrapped lambdas via HigherOrderFunction::try_new[with_schema]. 
Supporting lambda that get's wrapped/nested via tree node rewrites was added 
after https://github.com/apache/datafusion/pull/18921#discussion_r3075128457 / 
https://github.com/apache/datafusion/commit/ca260a7ef6623251705f0de7d2e93f6affd5ab89
 to not break existing tree rewrites like that: 
   
   ```rust
   expr.transform(|expr| Ok(Transformed::yes(Arc::new(DebugExpr::new(expr)))))
   ```
   
   If breaking those is okay I can add it to the list of breaking changes and 
instruct users to rewrite to this instead:
   
   ```rust
       expr.transform(|expr| {
           if expr.is::<LambdaExpr>() {
               Ok(Transformed::no(expr))
           } else {
               Ok(Transformed::yes(Arc::new(DebugExpr::new(expr))))
           }
       })
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to