rluvaton commented on code in PR #17220:
URL: https://github.com/apache/datafusion/pull/17220#discussion_r2290433517


##########
datafusion/functions-nested/src/array_filter.rs:
##########
@@ -0,0 +1,364 @@
+// 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.
+
+//! [`ScalarUDFImpl`] definitions for array_filter function.
+
+use arrow::array::{Array, ArrayRef, GenericListArray, OffsetSizeTrait, 
RecordBatch};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute::filter;
+use arrow::datatypes::DataType::{LargeList, List};
+use arrow::datatypes::{DataType, Field, Schema};
+use datafusion_common::cast::{as_boolean_array, as_large_list_array, 
as_list_array};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, plan_err, DFSchema, Result};
+use datafusion_expr::expr::{schema_name_from_exprs_ref, ScalarFunction};
+use datafusion_expr::{
+    ColumnarValue, Documentation, ExprSchemable, ScalarUDFImpl, Signature, 
Volatility,
+};
+use datafusion_expr::{Expr, LambdaPlanner, PhysicalLambda, ScalarUDF};
+use datafusion_macros::user_doc;
+
+use std::any::Any;
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+use crate::utils::make_scalar_function;
+
+make_udf_expr_and_func!(ArrayFilter,
+    array_filter,
+    array lambda, // arg names
+    "filters array elements using a lambda function, returning a new array 
with elements where the lambda returns true.", // doc
+    array_filter_udf // internal function name
+);
+
+/// Implementation of the `array_filter` scalar user-defined function.
+///
+/// This function filters array elements using a lambda function, returning a 
new array
+/// containing only the elements for which the lambda function returns true.
+///
+/// The struct maintains both logical and physical representations of the 
lambda:
+/// - `lambda`: The logical lambda expression from the SQL query
+/// - `physical_lambda`: The planned physical lambda that can be executed
+/// - `signature`: Function signature indicating it operates on arrays
+#[user_doc(
+    doc_section(label = "Array Functions"),
+    description = "Filters array elements using a lambda function.",
+    syntax_example = "array_filter(array, lambda)",
+    sql_example = r#"```sql
+> select array_filter([1, 2, 3, 4, 5], x -> x > 3);
++--------------------------------------------------+
+| array_filter(List([1,2,3,4,5]), x -> x > 3)      |
++--------------------------------------------------+
+| [4, 5]                                           |
++--------------------------------------------------+
+```"#,
+    argument(
+        name = "array",
+        description = "Array expression. Can be a constant, column, or 
function, and any combination of array operators."
+    ),
+    argument(
+        name = "lambda",
+        description = "Lambda function with one argument that returns a 
boolean. The lambda is applied to each element of the array."
+    )
+)]
+pub struct ArrayFilter {
+    signature: Signature,
+    lambda: Option<Box<Expr>>,
+    physical_lambda: Option<Box<dyn PhysicalLambda>>,
+}
+
+impl PartialEq for ArrayFilter {
+    fn eq(&self, other: &Self) -> bool {
+        self.signature == other.signature && self.lambda == other.lambda
+    }
+}
+
+impl Hash for ArrayFilter {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.signature.hash(state);
+        self.lambda.hash(state);
+    }
+}
+
+impl Eq for ArrayFilter {}
+
+impl std::fmt::Debug for ArrayFilter {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("ArrayFilter")
+            .field("signature", &self.signature)
+            .field("lambda", &self.lambda)
+            .field(
+                "physical_lambda",
+                if self.physical_lambda.is_some() {
+                    &"<PhysicalLambda>"
+                } else {
+                    &"<None>"
+                },
+            )
+            .finish()
+    }
+}
+
+impl Default for ArrayFilter {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl ArrayFilter {
+    /// Creates a new instance of ArrayFilter with default settings.
+    ///
+    /// Initializes the function with an array signature and no lambda 
expressions.
+    /// The lambda will be set later during query planning.
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::array(Volatility::Immutable),
+            lambda: None,
+            physical_lambda: None,
+        }
+    }
+
+    /// Creates a new ArrayFilter instance with a physical lambda attached.
+    ///
+    /// This is used during query execution when the logical lambda has been
+    /// planned into an executable physical lambda.
+    ///
+    /// # Arguments
+    /// * `physical_lambda` - The planned physical lambda function
+    fn with_physical_lambda(&self, physical_lambda: Box<dyn PhysicalLambda>) 
-> Self {
+        Self {
+            signature: self.signature.clone(),
+            lambda: self.lambda.clone(),
+            physical_lambda: Some(physical_lambda),
+        }
+    }
+
+    /// Creates a new ArrayFilter instance with a logical lambda expression.
+    ///
+    /// This is used during query planning when the lambda expression has been
+    /// parsed but not yet converted to a physical representation.
+    ///
+    /// # Arguments  
+    /// * `lambda` - The logical lambda expression from the SQL query
+    fn with_lambda(&self, lambda: &Expr) -> Self {
+        Self {
+            signature: self.signature.clone(),
+            lambda: Some(Box::new(lambda.clone())),
+            physical_lambda: None,
+        }
+    }
+}
+
+impl ScalarUDFImpl for ArrayFilter {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "array_filter"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        let [arg_type] = take_function_args(self.name(), arg_types)?;
+        match arg_type {
+            List(_) | LargeList(_) => Ok(arg_type.clone()),
+            _ => plan_err!("{} does not support type {}", self.name(), 
arg_type),
+        }
+    }

Review Comment:
   Can you please implement `return_field_from_args` instead so it won't be 
nullable in case the input is not nullable



-- 
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: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to