Jefffrey commented on code in PR #17729:
URL: https://github.com/apache/datafusion/pull/17729#discussion_r2425150165


##########
datafusion/spark/src/function/string/mod.rs:
##########
@@ -48,6 +50,11 @@ pub mod expr_fn {
         "Returns the ASCII character having the binary equivalent to col. If 
col is larger than 256 the result is equivalent to char(col % 256).",
         arg1
     ));
+    export_functions!((
+        elt,
+        "Returns the n-th input, e.g., returns input2 when n is 2. The 
function returns NULL if the index exceeds the length of the array.",

Review Comment:
   ```suggestion
           "Returns the n-th input (1-indexed), e.g. returns 2nd input when n 
is 2. The function returns NULL if the index is 0 or exceeds the length of the 
array.",
   ```



##########
datafusion/spark/src/function/string/elt.rs:
##########
@@ -0,0 +1,267 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, AsArray, PrimitiveArray, StringArray, StringBuilder,
+};
+use arrow::compute::{can_cast_types, cast};
+use arrow::datatypes::DataType::{Int64, Utf8};
+use arrow::datatypes::{DataType, Int64Type};
+use datafusion_common::{plan_datafusion_err, DataFusionError, Result};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkElt {
+    signature: Signature,
+}
+
+impl Default for SparkElt {
+    fn default() -> Self {
+        SparkElt::new()
+    }
+}
+
+impl SparkElt {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::user_defined(Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkElt {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "elt"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        Ok(Utf8)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        make_scalar_function(elt, vec![])(&args.args)
+    }
+
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+        let length = arg_types.len();
+        if length < 2 {
+            plan_datafusion_err!(
+                "ELT function expects at least 2 arguments: index, value1"
+            );
+        }
+
+        let idx_dt: &DataType = &arg_types[0];
+        if *idx_dt != Int64 && !can_cast_types(idx_dt, &Int64) {
+            return Err(DataFusionError::Plan(format!(
+                "ELT index must be Int64 (or castable to Int64), got 
{idx_dt:?}"
+            )));
+        }
+        let mut coerced = Vec::with_capacity(arg_types.len());
+        coerced.push(Int64);
+
+        for _ in 1..length {
+            coerced.push(Utf8);
+        }
+
+        Ok(coerced)
+    }
+}
+
+fn elt(args: &[ArrayRef]) -> Result<ArrayRef, DataFusionError> {
+    let n_rows = args[0].len();
+
+    let idx_i64: Option<&PrimitiveArray<Int64Type>> =
+        args[0].as_primitive_opt::<Int64Type>();
+
+    if idx_i64.is_none() {
+        plan_datafusion_err!(
+            "ELT function: first argument must be Int64 (got {:?})",
+            args[0].data_type()
+        );
+    }
+
+    let num_values: usize = args.len() - 1;
+    let mut cols: Vec<Arc<StringArray>> = Vec::with_capacity(num_values);
+    for a in args.iter().skip(1) {
+        let casted = cast(a, &Utf8)?;
+        let sa = casted.as_string::<i32>().clone();
+        cols.push(Arc::new(sa));
+    }

Review Comment:
   Technically `coerce_types()` should have done this casting for us by now



##########
datafusion/spark/src/function/string/elt.rs:
##########
@@ -0,0 +1,267 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, AsArray, PrimitiveArray, StringArray, StringBuilder,
+};
+use arrow::compute::{can_cast_types, cast};
+use arrow::datatypes::DataType::{Int64, Utf8};
+use arrow::datatypes::{DataType, Int64Type};
+use datafusion_common::{plan_datafusion_err, DataFusionError, Result};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkElt {
+    signature: Signature,
+}
+
+impl Default for SparkElt {
+    fn default() -> Self {
+        SparkElt::new()
+    }
+}
+
+impl SparkElt {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::user_defined(Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkElt {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "elt"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        Ok(Utf8)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        make_scalar_function(elt, vec![])(&args.args)
+    }
+
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+        let length = arg_types.len();
+        if length < 2 {
+            plan_datafusion_err!(
+                "ELT function expects at least 2 arguments: index, value1"
+            );
+        }
+
+        let idx_dt: &DataType = &arg_types[0];
+        if *idx_dt != Int64 && !can_cast_types(idx_dt, &Int64) {
+            return Err(DataFusionError::Plan(format!(
+                "ELT index must be Int64 (or castable to Int64), got 
{idx_dt:?}"
+            )));
+        }
+        let mut coerced = Vec::with_capacity(arg_types.len());
+        coerced.push(Int64);
+
+        for _ in 1..length {
+            coerced.push(Utf8);
+        }
+
+        Ok(coerced)
+    }
+}
+
+fn elt(args: &[ArrayRef]) -> Result<ArrayRef, DataFusionError> {
+    let n_rows = args[0].len();
+
+    let idx_i64: Option<&PrimitiveArray<Int64Type>> =
+        args[0].as_primitive_opt::<Int64Type>();
+
+    if idx_i64.is_none() {
+        plan_datafusion_err!(
+            "ELT function: first argument must be Int64 (got {:?})",
+            args[0].data_type()
+        );
+    }

Review Comment:
   Should unwrap `idx_i64` here instead of doing in loop below



##########
datafusion/spark/src/function/string/elt.rs:
##########
@@ -0,0 +1,257 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    Array, ArrayRef, AsArray, PrimitiveArray, StringArray, StringBuilder,
+};
+use arrow::compute::cast;
+use arrow::datatypes::DataType::Utf8;
+use arrow::datatypes::{DataType, Int32Type, Int64Type};
+use datafusion_common::{plan_datafusion_err, DataFusionError, Result};
+use datafusion_expr::Volatility::Immutable;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, 
Signature};
+use datafusion_functions::utils::make_scalar_function;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkElt {
+    signature: Signature,
+}
+
+impl Default for SparkElt {
+    fn default() -> Self {
+        SparkElt::new()
+    }
+}
+
+impl SparkElt {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::variadic_any(Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkElt {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "elt"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        Ok(Utf8)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        make_scalar_function(elt, vec![])(&args.args)
+    }
+}
+
+fn elt(args: &[ArrayRef]) -> Result<ArrayRef, DataFusionError> {
+    if args.len() < 2 {
+        plan_datafusion_err!("elt expects at least 2 arguments: index, 
value1");
+    }
+
+    let n_rows = args[0].len();
+
+    let idx_i32: Option<&PrimitiveArray<Int32Type>> =
+        args[0].as_primitive_opt::<Int32Type>();
+    let idx_i64: Option<&PrimitiveArray<Int64Type>> =
+        args[0].as_primitive_opt::<Int64Type>();
+
+    if idx_i32.is_none() && idx_i64.is_none() {
+        plan_datafusion_err!(
+            "elt: first argument must be Int32 or Int64 (got {:?})",
+            args[0].data_type()
+        );
+    }
+
+    let k: usize = args.len() - 1;
+    let mut cols: Vec<Arc<StringArray>> = Vec::with_capacity(k);
+    for a in args.iter().skip(1) {
+        let casted = cast(a, &Utf8)?;
+        let sa = casted
+            .as_any()
+            .downcast_ref::<StringArray>()
+            .ok_or_else(|| DataFusionError::Internal("downcast Utf8 
failed".into()))?
+            .clone();
+        cols.push(Arc::new(sa));
+    }
+
+    let mut builder = StringBuilder::new();
+
+    for i in 0..n_rows {
+        let n_opt: Option<i64> = if let Some(idx) = idx_i32 {
+            if idx.is_null(i) {
+                None
+            } else {
+                Some(idx.value(i) as i64)
+            }
+        } else {
+            let idx = idx_i64.unwrap();
+            if idx.is_null(i) {
+                None
+            } else {
+                Some(idx.value(i))
+            }
+        };
+
+        let Some(n) = n_opt else {
+            builder.append_null();
+            continue;
+        };
+
+        let ansi_enable: bool = false;

Review Comment:
   We should remove this code itself but leave a TODO comment for ANSI support, 
otherwise it can be confusing why we have a static boolean variable here



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