jayzhan211 commented on code in PR #9617:
URL: https://github.com/apache/arrow-datafusion/pull/9617#discussion_r1527179434


##########
datafusion/functions-array/src/position.rs:
##########
@@ -0,0 +1,400 @@
+// 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_position function.
+
+use arrow_schema::DataType::{FixedSizeList, LargeList, List, UInt64};
+use arrow_schema::{DataType, Field};
+use datafusion_common::plan_err;
+use datafusion_expr::expr::ScalarFunction;
+use datafusion_expr::Expr;
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow_array::types::UInt64Type;
+use arrow_array::{
+    Array, ArrayRef, BooleanArray, GenericListArray, ListArray, 
OffsetSizeTrait, Scalar,
+    UInt32Array, UInt64Array,
+};
+use datafusion_common::cast::{
+    as_generic_list_array, as_int64_array, as_large_list_array, as_list_array,
+};
+use datafusion_common::{exec_err, internal_err};
+use itertools::Itertools;
+
+make_udf_function!(
+    ArrayPosition,
+    array_position,
+    array element index,
+    "searches for an element in the array, returns first occurrence.",
+    array_position_udf
+);
+
+#[derive(Debug)]
+pub(super) struct ArrayPosition {
+    signature: Signature,
+    aliases: Vec<String>,
+}
+impl ArrayPosition {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::array_and_element_and_optional_index(
+                Volatility::Immutable,
+            ),
+            aliases: vec![
+                String::from("array_position"),
+                String::from("list_position"),
+                String::from("array_indexof"),
+                String::from("list_indexof"),
+            ],
+        }
+    }
+}
+
+impl ScalarUDFImpl for ArrayPosition {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+    fn name(&self) -> &str {
+        "array_position"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> 
datafusion_common::Result<DataType> {
+        Ok(match arg_types[0] {
+            List(_) | LargeList(_) | FixedSizeList(_, _) => UInt64,
+            _ => {
+                return plan_err!("The array_position function can only accept 
List/LargeList/FixedSizeList.");
+            }
+        })
+    }
+
+    fn invoke(&self, args: &[ColumnarValue]) -> 
datafusion_common::Result<ColumnarValue> {
+        let args = ColumnarValue::values_to_arrays(args)?;
+        array_position_inner(&args).map(ColumnarValue::Array)
+    }
+
+    fn aliases(&self) -> &[String] {
+        &self.aliases
+    }
+}
+
+/// Array_position SQL function
+pub fn array_position_inner(args: &[ArrayRef]) -> 
datafusion_common::Result<ArrayRef> {
+    if args.len() < 2 || args.len() > 3 {
+        return exec_err!("array_position expects two or three arguments");
+    }
+    match &args[0].data_type() {
+        List(_) => general_position_dispatch::<i32>(args),
+        LargeList(_) => general_position_dispatch::<i64>(args),
+        array_type => exec_err!("array_position does not support type 
'{array_type:?}'."),
+    }
+}
+fn general_position_dispatch<O: OffsetSizeTrait>(
+    args: &[ArrayRef],
+) -> datafusion_common::Result<ArrayRef> {
+    let list_array = as_generic_list_array::<O>(&args[0])?;
+    let element_array = &args[1];
+
+    check_datatypes("array_position", &[list_array.values(), element_array])?;
+
+    let arr_from = if args.len() == 3 {
+        as_int64_array(&args[2])?
+            .values()
+            .to_vec()
+            .iter()
+            .map(|&x| x - 1)
+            .collect::<Vec<_>>()
+    } else {
+        vec![0; list_array.len()]
+    };
+
+    // if `start_from` index is out of bounds, return error
+    for (arr, &from) in list_array.iter().zip(arr_from.iter()) {
+        if let Some(arr) = arr {
+            if from < 0 || from as usize >= arr.len() {
+                return internal_err!("start_from index out of bounds");
+            }
+        } else {
+            // We will get null if we got null in the array, so we don't need 
to check
+        }
+    }
+
+    generic_position::<O>(list_array, element_array, arr_from)
+}
+
+fn check_datatypes(name: &str, args: &[&ArrayRef]) -> 
datafusion_common::Result<()> {

Review Comment:
   We can use function in crate::utils



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

Reply via email to