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


##########
datafusion/functions-nested/src/array_transform.rs:
##########
@@ -0,0 +1,457 @@
+// 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.
+
+//! [`HigherOrderUDF`] definitions for array_transform function.
+
+use arrow::{
+    array::{
+        Array, ArrayRef, AsArray, FixedSizeListArray, LargeListArray, 
ListArray,
+        new_null_array,
+    },
+    datatypes::{DataType, Field, FieldRef},
+};
+use datafusion_common::{
+    Result, exec_err, plan_err,
+    utils::{adjust_offsets_for_slice, list_values, take_function_args},
+};
+use datafusion_expr::{
+    ColumnarValue, Documentation, HigherOrderFunctionArgs, 
HigherOrderReturnFieldArgs,
+    HigherOrderSignature, HigherOrderUDF, ValueOrLambda, Volatility,
+};
+use datafusion_macros::user_doc;
+use std::{fmt::Debug, sync::Arc};
+
+make_udhof_expr_and_func!(
+    ArrayTransform,
+    array_transform,
+    array lambda,
+    "transforms the values of an array",
+    array_transform_udhof
+);
+
+#[user_doc(
+    doc_section(label = "Array Functions"),
+    description = "transforms the values of an array",
+    syntax_example = "array_transform(array, x -> x*2)",
+    sql_example = r#"```sql
+> select array_transform([1, 2, 3, 4, 5], x -> x*2);
++-------------------------------------------+
+| array_transform([1, 2, 3, 4, 5], x -> x*2)       |
++-------------------------------------------+
+| [2, 4, 6, 8, 10]                          |
++-------------------------------------------+
+```"#,
+    argument(
+        name = "array",
+        description = "Array expression. Can be a constant, column, or 
function, and any combination of array operators."
+    ),
+    argument(name = "lambda", description = "Lambda")
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct ArrayTransform {
+    signature: HigherOrderSignature,
+    aliases: Vec<String>,
+}
+
+impl Default for ArrayTransform {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl ArrayTransform {
+    pub fn new() -> Self {
+        Self {
+            signature: 
HigherOrderSignature::user_defined(Volatility::Immutable),
+            aliases: vec![String::from("list_transform")],
+        }
+    }
+}
+
+impl HigherOrderUDF for ArrayTransform {
+    fn name(&self) -> &str {
+        "array_transform"
+    }
+
+    fn aliases(&self) -> &[String] {
+        &self.aliases
+    }
+
+    fn signature(&self) -> &HigherOrderSignature {
+        &self.signature
+    }
+
+    fn coerce_value_types(&self, arg_types: &[DataType]) -> 
Result<Vec<DataType>> {
+        let list = if arg_types.len() == 1 {
+            &arg_types[0]
+        } else {
+            return plan_err!(
+                "{} function requires 1 value arguments, got {}",
+                self.name(),
+                arg_types.len()
+            );
+        };
+
+        let coerced = match list {
+            DataType::List(_)
+            | DataType::LargeList(_)
+            | DataType::FixedSizeList(_, _) => list.clone(),
+            DataType::ListView(field) => DataType::List(Arc::clone(field)),
+            DataType::LargeListView(field) => 
DataType::LargeList(Arc::clone(field)),
+            _ => {
+                return plan_err!(
+                    "{} expected a list as first argument, got {}",
+                    self.name(),
+                    list
+                );
+            }
+        };
+
+        Ok(vec![coerced])
+    }
+
+    fn lambda_parameters(&self, value_fields: &[FieldRef]) -> 
Result<Vec<Vec<Field>>> {
+        let list = if value_fields.len() == 1 {
+            &value_fields[0]
+        } else {
+            return plan_err!(
+                "{} function requires 1 value arguments, got {}",
+                self.name(),
+                value_fields.len()
+            );
+        };
+
+        let field = match list.data_type() {
+            DataType::List(field) => field,
+            DataType::LargeList(field) => field,
+            DataType::FixedSizeList(field, _) => field,
+            _ => return plan_err!("expected list, got {list}"),
+        };
+
+        // we don't need to check whether the lambda contains more than two 
parameters,
+        // e.g. array_transform([], (v, i, j) -> v+i+j), as datafusion will do 
that for us
+        let value = Field::new("", field.data_type().clone(), 
field.is_nullable())
+            .with_metadata(field.metadata().clone());
+
+        Ok(vec![vec![value]])
+    }
+
+    fn return_field_from_args(
+        &self,
+        args: HigherOrderReturnFieldArgs,
+    ) -> Result<Arc<Field>> {
+        let (list, lambda) = value_lambda_pair(self.name(), args.arg_fields)?;
+
+        //TODO: should metadata be copied into the transformed array?
+
+        // lambda is the resulting field of executing the lambda body
+        // with the parameters returned in lambda_parameters
+        let field = Arc::new(Field::new(
+            Field::LIST_FIELD_DEFAULT_NAME,
+            lambda.data_type().clone(),
+            lambda.is_nullable(),
+        ));
+
+        let return_type = match list.data_type() {
+            DataType::List(_) => DataType::List(field),
+            DataType::LargeList(_) => DataType::LargeList(field),
+            DataType::FixedSizeList(_, size) => DataType::FixedSizeList(field, 
*size),
+            other => plan_err!("expected list, got {other}")?,
+        };
+
+        Ok(Arc::new(Field::new("", return_type, list.is_nullable())))
+    }
+
+    fn invoke_with_args(&self, args: HigherOrderFunctionArgs) -> 
Result<ColumnarValue> {
+        let (list, lambda) = value_lambda_pair(self.name(), &args.args)?;
+
+        let list_array = list.to_array(args.number_rows)?;
+
+        // Fast path for fully null input array and also the only way to 
safely work with
+        // a fully null fixed size list array as it can't be handled by 
remove_list_null_values below
+        if list_array.null_count() == list_array.len() {

Review Comment:
   Doesn't we still need to execute when all values are null ? example: 
`array_transform([NULL], v -> coalesce(v, 2))` 
   
   All empty check added here 
https://github.com/apache/datafusion/commit/9a83018838cefda0a51bd7dd708e85dcc63c8b31#diff-e464d894d5a0fe37392c40f9e54f67590220578259a8dc41fa57b329f6f0d343R190-R204
 , thanks 
   
   
https://github.com/apache/datafusion/blob/9a83018838cefda0a51bd7dd708e85dcc63c8b31/datafusion/functions-nested/src/array_transform.rs#L191-L203



-- 
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