zakariya-s commented on code in PR #460:
URL: https://github.com/apache/datafusion-spark/pull/460#discussion_r4802536547


##########
crates/spark/src/function/math/conv.rs/conv.rs:
##########
@@ -0,0 +1,664 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+use std::sync::Arc;

Review Comment:
   Arc is only used in the tests, can this be moved?



##########
crates/spark/src/function/math/conv.rs/conv.rs:
##########


Review Comment:
   Could you move this file to `crates/spark/src/function/math/conv.rs`? Right 
now this is under a conv.rs directory which isn't correct



##########
crates/spark/src/function/math/conv.rs/conv.rs:
##########
@@ -0,0 +1,664 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+use std::sync::Arc;
+
+use crate::EvalMode;
+use crate::function::implicit_cast::{SparkInputType, SparkInputTypes};
+use crate::function::nullability::{SparkNullability, spark_nullability};
+use arrow::array::{
+    Array, ArrayAccessor, ArrayBuilder, ArrayRef, GenericStringBuilder, 
Int32Array,
+    OffsetSizeTrait, StringViewBuilder,
+};
+use arrow::datatypes::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::config::ConfigOptions;
+use datafusion_common::{Result, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, Documentation, ReturnFieldArgs, ScalarFunctionArgs, 
ScalarUDF,
+    ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use datafusion_macros::user_doc;
+
+/// Spark's `Conv` is a null-intolerant `TernaryExpression` whose result is
+/// always nullable: an out-of-range base or an empty input returns NULL even
+/// when every argument is non-NULL.
+const NULLABILITY: SparkNullability =
+    SparkNullability::null_intolerant_always_nullable();
+
+/// Spark's `ARITHMETIC_OVERFLOW` for `conv`, from
+/// `QueryExecutionErrors.overflowInConvError`.
+const ARITHMETIC_OVERFLOW_ERROR: &str = "[ARITHMETIC_OVERFLOW] Overflow in 
function conv(). If necessary set \"spark.sql.ansi.enabled\" to \"false\" to 
bypass this error. SQLSTATE: 22003";
+
+/// Spark-compatible `conv` expression.
+///
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#conv>
+#[user_doc(
+    doc_section(label = "Math Functions"),
+    description = "Converts the number written in `num` from base `from_base` 
to base \
+        `to_base` and returns it as a string, porting Spark's 
`NumberConverter` (Hive's \
+        `UDFConv`). DataFusion has no built-in `conv`. The input is parsed 
into an \
+        unsigned 64-bit value, stopping at the first character that is not a 
digit in \
+        `from_base`; a positive `to_base` prints that value unsigned, a 
negative \
+        `to_base` prints it signed. Digits above 9 are printed in upper case. \
+        Overflow while parsing saturates to `-1` (all bits set) with ANSI off 
and \
+        raises an `ARITHMETIC_OVERFLOW` error with ANSI on. Returns NULL if 
any \
+        argument is NULL, if a base is out of range, or if `num` is empty 
after \
+        trimming.",
+    syntax_example = "conv(num, from_base, to_base)",
+    sql_example = r#"```sql
+> SELECT conv('100', 2, 10);
+4
+> SELECT conv(-10, 16, -10);
+-16
+> SELECT conv('-15', 10, 16);
+FFFFFFFFFFFFFFF1
+> SELECT conv('11abc', 10, 16);
+B
+> SELECT conv('92233720368547758070', 10, 16);
+FFFFFFFFFFFFFFFF
+```"#,
+    argument(
+        name = "num",
+        description = "Number to convert, cast to STRING. Only ASCII spaces 
are trimmed. \
+            NULL returns NULL."
+    ),
+    argument(
+        name = "from_base",
+        description = "Base of `num`, cast to INT. Must be in 2..36, otherwise 
NULL."
+    ),
+    argument(
+        name = "to_base",
+        description = "Base to convert to, cast to INT. Its absolute value 
must \
+            be in 2..36, otherwise NULL. A positive value prints the result 
unsigned, a \
+            negative value signed."
+    )
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkConv {
+    input_types: SparkInputTypes,
+}
+
+impl Default for SparkConv {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkConv {
+    pub fn new() -> Self {
+        Self {
+            // Spark's `Conv.inputTypes`
+            input_types: SparkInputTypes::new(
+                vec![
+                    SparkInputType::String,
+                    SparkInputType::Integer,
+                    SparkInputType::Integer,
+                ],
+                Volatility::Immutable,
+            ),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkConv {
+    fn name(&self) -> &str {
+        "conv"
+    }
+
+    fn signature(&self) -> &Signature {
+        self.input_types.signature()
+    }
+
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+        self.input_types.coerce(self.name(), arg_types)
+    }
+
+    fn with_updated_config(&self, config: &ConfigOptions) -> Option<ScalarUDF> 
{
+        let input_types = self.input_types.with_config(config)?;
+        Some(ScalarUDF::from(Self { input_types }))
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        internal_err!("return_field_from_args should be used instead")
+    }
+
+    fn return_field_from_args(&self, args: ReturnFieldArgs) -> 
Result<FieldRef> {

Review Comment:
   FieldRef has not been imported



##########
crates/spark/src/function/math/conv.rs/conv.rs:
##########
@@ -0,0 +1,664 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+use std::sync::Arc;
+
+use crate::EvalMode;
+use crate::function::implicit_cast::{SparkInputType, SparkInputTypes};
+use crate::function::nullability::{SparkNullability, spark_nullability};
+use arrow::array::{
+    Array, ArrayAccessor, ArrayBuilder, ArrayRef, GenericStringBuilder, 
Int32Array,
+    OffsetSizeTrait, StringViewBuilder,
+};
+use arrow::datatypes::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::config::ConfigOptions;
+use datafusion_common::{Result, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, Documentation, ReturnFieldArgs, ScalarFunctionArgs, 
ScalarUDF,
+    ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use datafusion_macros::user_doc;
+
+/// Spark's `Conv` is a null-intolerant `TernaryExpression` whose result is
+/// always nullable: an out-of-range base or an empty input returns NULL even
+/// when every argument is non-NULL.
+const NULLABILITY: SparkNullability =
+    SparkNullability::null_intolerant_always_nullable();
+
+/// Spark's `ARITHMETIC_OVERFLOW` for `conv`, from
+/// `QueryExecutionErrors.overflowInConvError`.
+const ARITHMETIC_OVERFLOW_ERROR: &str = "[ARITHMETIC_OVERFLOW] Overflow in 
function conv(). If necessary set \"spark.sql.ansi.enabled\" to \"false\" to 
bypass this error. SQLSTATE: 22003";
+
+/// Spark-compatible `conv` expression.
+///
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#conv>
+#[user_doc(
+    doc_section(label = "Math Functions"),
+    description = "Converts the number written in `num` from base `from_base` 
to base \
+        `to_base` and returns it as a string, porting Spark's 
`NumberConverter` (Hive's \
+        `UDFConv`). DataFusion has no built-in `conv`. The input is parsed 
into an \
+        unsigned 64-bit value, stopping at the first character that is not a 
digit in \
+        `from_base`; a positive `to_base` prints that value unsigned, a 
negative \
+        `to_base` prints it signed. Digits above 9 are printed in upper case. \
+        Overflow while parsing saturates to `-1` (all bits set) with ANSI off 
and \
+        raises an `ARITHMETIC_OVERFLOW` error with ANSI on. Returns NULL if 
any \
+        argument is NULL, if a base is out of range, or if `num` is empty 
after \
+        trimming.",
+    syntax_example = "conv(num, from_base, to_base)",
+    sql_example = r#"```sql
+> SELECT conv('100', 2, 10);
+4
+> SELECT conv(-10, 16, -10);
+-16
+> SELECT conv('-15', 10, 16);
+FFFFFFFFFFFFFFF1
+> SELECT conv('11abc', 10, 16);
+B
+> SELECT conv('92233720368547758070', 10, 16);
+FFFFFFFFFFFFFFFF
+```"#,
+    argument(
+        name = "num",
+        description = "Number to convert, cast to STRING. Only ASCII spaces 
are trimmed. \
+            NULL returns NULL."
+    ),
+    argument(
+        name = "from_base",
+        description = "Base of `num`, cast to INT. Must be in 2..36, otherwise 
NULL."
+    ),
+    argument(
+        name = "to_base",
+        description = "Base to convert to, cast to INT. Its absolute value 
must \
+            be in 2..36, otherwise NULL. A positive value prints the result 
unsigned, a \
+            negative value signed."
+    )
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkConv {
+    input_types: SparkInputTypes,
+}
+
+impl Default for SparkConv {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkConv {
+    pub fn new() -> Self {
+        Self {
+            // Spark's `Conv.inputTypes`
+            input_types: SparkInputTypes::new(
+                vec![
+                    SparkInputType::String,
+                    SparkInputType::Integer,
+                    SparkInputType::Integer,
+                ],
+                Volatility::Immutable,
+            ),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkConv {
+    fn name(&self) -> &str {
+        "conv"
+    }
+
+    fn signature(&self) -> &Signature {
+        self.input_types.signature()
+    }
+
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+        self.input_types.coerce(self.name(), arg_types)
+    }
+
+    fn with_updated_config(&self, config: &ConfigOptions) -> Option<ScalarUDF> 
{
+        let input_types = self.input_types.with_config(config)?;
+        Some(ScalarUDF::from(Self { input_types }))
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        internal_err!("return_field_from_args should be used instead")
+    }
+
+    fn return_field_from_args(&self, args: ReturnFieldArgs) -> 
Result<FieldRef> {
+        // Spark's `Conv.dataType` is the type of `num`.
+        Ok(NULLABILITY.return_field(
+            self.name(),
+            args.arg_fields[0].data_type().clone(),
+            args.arg_fields,
+        ))
+    }
+
+    spark_nullability!(NULLABILITY);
+
+    fn documentation(&self) -> Option<&Documentation> {
+        self.doc()
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let eval_mode = EvalMode::from_config(&args.config_options);
+        make_scalar_function(
+            move |arrays: &[ArrayRef]| spark_conv(arrays, eval_mode),
+            vec![],
+        )(&args.args)
+    }
+}
+
+fn spark_conv(args: &[ArrayRef], eval_mode: EvalMode) -> Result<ArrayRef> {
+    let from_bases = as_int32_array(&args[1])?;
+    let to_bases = as_int32_array(&args[2])?;
+    match args[0].data_type() {
+        DataType::Utf8 => spark_conv_generic(
+            &args[0].as_string::<i32>(),
+            from_bases,
+            to_bases,
+            eval_mode,
+            GenericStringBuilder::<i32>::new(),
+        ),
+        DataType::LargeUtf8 => spark_conv_generic(
+            &args[0].as_string::<i64>(),
+            from_bases,
+            to_bases,
+            eval_mode,
+            GenericStringBuilder::<i64>::new(),
+        ),
+        DataType::Utf8View => spark_conv_generic(
+            &args[0].as_string_view(),
+            from_bases,
+            to_bases,
+            eval_mode,
+            StringViewBuilder::new(),
+        ),
+        other => exec_err!(
+            "Unsupported data type {other:?} for function spark_conv, expected 
Utf8View, Utf8 or LargeUtf8."
+        ),
+    }
+}
+
+/// Row-wise `conv`, generic over the input string array and its builder,
+/// following `substring`'s pattern so the output keeps the input's string 
type.
+fn spark_conv_generic<'a, Source, Builder>(
+    nums: &Source,
+    from_bases: &Int32Array,
+    to_bases: &Int32Array,
+    eval_mode: EvalMode,
+    mut builder: Builder,
+) -> Result<ArrayRef>
+where
+    Source: ArrayAccessor<Item = &'a str>,
+    Builder: ConvBuilder,
+{
+    for i in 0..nums.len() {
+        if nums.is_null(i) || from_bases.is_null(i) || to_bases.is_null(i) {
+            builder.append_null();
+            continue;
+        }
+        match spark_conv_value(
+            nums.value(i).as_bytes(),
+            from_bases.value(i),
+            to_bases.value(i),
+            eval_mode,
+        )? {
+            Some(result) => builder.append_value(&result),
+            None => builder.append_null(),
+        }
+    }
+    Ok(builder.finish())
+}
+
+/// A string builder that `spark_conv_generic` can append to, following
+/// `substring`'s `SubstringBuilder`.
+trait ConvBuilder: ArrayBuilder {
+    fn append_value(&mut self, val: &str);
+    fn append_null(&mut self);
+}
+
+impl<O: OffsetSizeTrait> ConvBuilder for GenericStringBuilder<O> {
+    fn append_value(&mut self, val: &str) {
+        GenericStringBuilder::append_value(self, val);
+    }
+    fn append_null(&mut self) {
+        GenericStringBuilder::append_null(self);
+    }
+}
+
+impl ConvBuilder for StringViewBuilder {
+    fn append_value(&mut self, val: &str) {
+        StringViewBuilder::append_value(self, val);
+    }
+    fn append_null(&mut self) {
+        StringViewBuilder::append_null(self);
+    }
+}
+
+/// Converts one row, porting Spark's `NumberConverter.convert`:
+/// 
`sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/NumberConverter.scala`
+///
+/// Returns `Ok(None)` for NULL: an out-of-range base, or an empty input after
+/// trimming. Overflow while parsing saturates to `-1` (all bits set) with ANSI
+/// off and raises `ARITHMETIC_OVERFLOW` with ANSI on.
+fn spark_conv_value(
+    num: &[u8],
+    from_base: i32,
+    to_base: i32,
+    eval_mode: EvalMode,
+) -> Result<Option<String>> {
+    // Only ASCII spaces are trimmed, like `UTF8String.trim`.
+    let mut start = 0;
+    let mut end = num.len();
+    while start < end && num[start] == b' ' {
+        start += 1;
+    }
+    while end > start && num[end - 1] == b' ' {
+        end -= 1;
+    }
+    let num = &num[start..end];
+
+    if !(2..=36).contains(&from_base) {
+        return Ok(None);
+    }
+    // `Math.abs(toBase)`: `i32::MIN` has no absolute value, so it is out of 
range.
+    let abs_to_base = match to_base.checked_abs() {
+        Some(abs) if (2..=36).contains(&abs) => abs,
+        _ => return Ok(None),
+    };
+    if num.is_empty() {
+        return Ok(None);
+    }
+
+    let (negative, digits) = if num[0] == b'-' {
+        (true, &num[1..])
+    } else {
+        (false, num)
+    };
+
+    // Parse the digits into an unsigned 64-bit value, stopping at the first
+    // character that is not a digit in `from_base`.
+    let mut value: u64 = 0;
+    let mut overflow = false;
+    for &byte in digits {
+        let Some(digit) = char_digit(byte, from_base) else {
+            break;
+        };
+        let digit = digit as u64;
+        if value > (u64::MAX - digit) / from_base as u64 {
+            overflow = true;
+            break;
+        }
+        value = value * from_base as u64 + digit;
+    }
+    if overflow {
+        if eval_mode == EvalMode::Ansi {
+            return exec_err!("{ARITHMETIC_OVERFLOW_ERROR}");
+        }
+        value = u64::MAX;
+    }
+
+    // Apply the sign, following the bit-level rules of `NumberConverter`: a
+    // negative input with a positive `to_base` is printed as its unsigned
+    // two's complement, unless the magnitude already fills 64 bits, in which
+    // case it saturates to `-1`; a negative `to_base` prints the value signed.
+    let mut negative = negative;
+    let mut value = value as i64;
+    if negative && to_base > 0 {
+        value = if value < 0 { -1 } else { -value };
+    }
+    if to_base < 0 && value < 0 {
+        // Java's `long` arithmetic wraps, so `-Long.MIN_VALUE` stays 
`Long.MIN_VALUE`.
+        value = value.wrapping_neg();
+        negative = true;
+    }
+
+    // Render the unsigned value in `abs_to_base`, most significant digit
+    // first. `decode` writes the digits into the end of a zero-filled buffer,
+    // so the first non-zero digit (or the last digit, for zero) starts the 
output.
+    let mut temp = [0u8; MAX_OUTPUT_LENGTH];
+    let mut remaining = value as u64;
+    let mut i = MAX_OUTPUT_LENGTH - 1;
+    while remaining != 0 {
+        let quotient = remaining / abs_to_base as u64;
+        temp[i] = (remaining - quotient * abs_to_base as u64) as u8;
+        remaining = quotient;
+        i -= 1;
+    }
+    let first_non_zero = temp
+        .iter()
+        .position(|&byte| byte != 0)
+        .unwrap_or(MAX_OUTPUT_LENGTH - 1);
+
+    let mut result = String::with_capacity(MAX_OUTPUT_LENGTH - first_non_zero 
+ 1);

Review Comment:
   Each row allocates a String, pushes the characters one at a time, and is 
then copied into the builder. The builders also start without capacity 
(`GenericStringBuilder::new()`).
   The digits are already in a 65-byte `temp` array. You could write the ASCII 
digits (and `-`) into its tail and append `&str` straight to a builder created 
with `with_capacity(len, len * 8)`. A lookup table such as 
`b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[digit]` would also remove the expect 
on line 342.
   
   Maybe something like:
   
   ```rust
    /// Spark's `NumberConverter.decode` and `byte2char`: writes `value` in 
`radix` with upper-case
   /// letters to the end of `buffer`, and returns where it starts. Zero is 
written as `0`.
   fn decode(mut value: u64, radix: u64, buffer: &mut [u8; MAX_OUTPUT_LENGTH]) 
-> usize {
       let mut start = buffer.len();
       loop {
           start -= 1;
           buffer[start] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[(value % 
radix) as usize];
           value /= radix;
           if value == 0 {
               return start;
           }
       }
   }
   ```



##########
crates/spark/src/function/math/conv.rs/conv.rs:
##########
@@ -0,0 +1,664 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+use std::sync::Arc;
+
+use crate::EvalMode;
+use crate::function::implicit_cast::{SparkInputType, SparkInputTypes};
+use crate::function::nullability::{SparkNullability, spark_nullability};
+use arrow::array::{
+    Array, ArrayAccessor, ArrayBuilder, ArrayRef, GenericStringBuilder, 
Int32Array,
+    OffsetSizeTrait, StringViewBuilder,
+};
+use arrow::datatypes::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::config::ConfigOptions;
+use datafusion_common::{Result, exec_err, internal_err};
+use datafusion_expr::{
+    ColumnarValue, Documentation, ReturnFieldArgs, ScalarFunctionArgs, 
ScalarUDF,
+    ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use datafusion_macros::user_doc;
+
+/// Spark's `Conv` is a null-intolerant `TernaryExpression` whose result is
+/// always nullable: an out-of-range base or an empty input returns NULL even
+/// when every argument is non-NULL.
+const NULLABILITY: SparkNullability =
+    SparkNullability::null_intolerant_always_nullable();
+
+/// Spark's `ARITHMETIC_OVERFLOW` for `conv`, from
+/// `QueryExecutionErrors.overflowInConvError`.
+const ARITHMETIC_OVERFLOW_ERROR: &str = "[ARITHMETIC_OVERFLOW] Overflow in 
function conv(). If necessary set \"spark.sql.ansi.enabled\" to \"false\" to 
bypass this error. SQLSTATE: 22003";
+
+/// Spark-compatible `conv` expression.
+///
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#conv>
+#[user_doc(
+    doc_section(label = "Math Functions"),
+    description = "Converts the number written in `num` from base `from_base` 
to base \
+        `to_base` and returns it as a string, porting Spark's 
`NumberConverter` (Hive's \
+        `UDFConv`). DataFusion has no built-in `conv`. The input is parsed 
into an \
+        unsigned 64-bit value, stopping at the first character that is not a 
digit in \
+        `from_base`; a positive `to_base` prints that value unsigned, a 
negative \
+        `to_base` prints it signed. Digits above 9 are printed in upper case. \
+        Overflow while parsing saturates to `-1` (all bits set) with ANSI off 
and \
+        raises an `ARITHMETIC_OVERFLOW` error with ANSI on. Returns NULL if 
any \
+        argument is NULL, if a base is out of range, or if `num` is empty 
after \
+        trimming.",
+    syntax_example = "conv(num, from_base, to_base)",
+    sql_example = r#"```sql
+> SELECT conv('100', 2, 10);
+4
+> SELECT conv(-10, 16, -10);
+-16
+> SELECT conv('-15', 10, 16);
+FFFFFFFFFFFFFFF1
+> SELECT conv('11abc', 10, 16);
+B
+> SELECT conv('92233720368547758070', 10, 16);
+FFFFFFFFFFFFFFFF
+```"#,
+    argument(
+        name = "num",
+        description = "Number to convert, cast to STRING. Only ASCII spaces 
are trimmed. \
+            NULL returns NULL."
+    ),
+    argument(
+        name = "from_base",
+        description = "Base of `num`, cast to INT. Must be in 2..36, otherwise 
NULL."
+    ),
+    argument(
+        name = "to_base",
+        description = "Base to convert to, cast to INT. Its absolute value 
must \
+            be in 2..36, otherwise NULL. A positive value prints the result 
unsigned, a \
+            negative value signed."
+    )
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkConv {
+    input_types: SparkInputTypes,
+}
+
+impl Default for SparkConv {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkConv {
+    pub fn new() -> Self {
+        Self {
+            // Spark's `Conv.inputTypes`
+            input_types: SparkInputTypes::new(
+                vec![
+                    SparkInputType::String,
+                    SparkInputType::Integer,
+                    SparkInputType::Integer,
+                ],
+                Volatility::Immutable,
+            ),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkConv {
+    fn name(&self) -> &str {
+        "conv"
+    }
+
+    fn signature(&self) -> &Signature {
+        self.input_types.signature()
+    }
+
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+        self.input_types.coerce(self.name(), arg_types)
+    }
+
+    fn with_updated_config(&self, config: &ConfigOptions) -> Option<ScalarUDF> 
{
+        let input_types = self.input_types.with_config(config)?;
+        Some(ScalarUDF::from(Self { input_types }))
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        internal_err!("return_field_from_args should be used instead")
+    }
+
+    fn return_field_from_args(&self, args: ReturnFieldArgs) -> 
Result<FieldRef> {
+        // Spark's `Conv.dataType` is the type of `num`.
+        Ok(NULLABILITY.return_field(
+            self.name(),
+            args.arg_fields[0].data_type().clone(),
+            args.arg_fields,
+        ))
+    }
+
+    spark_nullability!(NULLABILITY);

Review Comment:
   The result type is always `num`'s type, so `return_type` can compute it from 
`arg_types` instead of returning `internal_err!`. 
`spark_nullability!(NULLABILITY, return_type)` should implement 
`return_field_from_args` for you instead.
   
   ```suggestion
       fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
           Ok(arg_types[0].clone())
       }
   
       spark_nullability!(NULLABILITY, return_type);
   ```



##########
crates/sqllogictest/test_files/math/conv.slt:
##########
@@ -8,12 +8,284 @@
 # For more information, please see:
 #   https://github.com/apache/datafusion/issues/15914
 
+# Expected values below come from apache/datafusion-spark#267, which took them 
from

Review Comment:
   Cases that might be worth adding:
   - implicit casts: `conv(true, 36, 10)` is `1389110`, `conv(DATE 
'2024-01-02', 10, 10)` is `2024`, and `conv(X'3130', 10, 2)` is `1010`;
   - rejected types: a boolean base and an `array` `num` give 
`DATATYPE_MISMATCH.UNEXPECTED_INPUT_TYPE`, and two arguments give 
`WRONG_NUM_ARGS`;
   - `# xfail spark:` records for the casts that still differ from Spark's 
`CAST` (#88):
     - a double such as `123456789`, which Spark writes as `1.23456789E8` and 
so converts to `1`;
     - invalid UTF-8 binary;
     - with ANSI mode off, `'2.5'` and BIGINT bases.



##########
crates/sqllogictest/test_files/math/conv.slt:
##########
@@ -8,12 +8,284 @@
 # For more information, please see:
 #   https://github.com/apache/datafusion/issues/15914
 
+# Expected values below come from apache/datafusion-spark#267, which took them 
from
+# Spark's `NumberConverter` logic and examples. They were not re-verified 
against a
+# running Spark here (no JDK/PySpark on this machine); re-check the trickier
+# cases against PySpark before relying on them.
+
 ## Original Query: SELECT conv('100', 2, 10);
 ## PySpark 3.5.5 Result: {'conv(100, 2, 10)': '4', 'typeof(conv(100, 2, 10))': 
'string', 'typeof(100)': 'string', 'typeof(2)': 'int', 'typeof(10)': 'int'}
-#query
-#SELECT conv('100'::string, 2::int, 10::int);
+query T
+SELECT conv(CAST('100' AS string), CAST(2 AS int), CAST(10 AS int));
+----
+4
 
 ## Original Query: SELECT conv(-10, 16, -10);
 ## PySpark 3.5.5 Result: {'conv(-10, 16, -10)': '-16', 'typeof(conv(-10, 16, 
-10))': 'string', 'typeof(-10)': 'int', 'typeof(16)': 'int'}
-#query
-#SELECT conv(-10::int, 16::int);
+# (The stub dropped the third argument; the query below restores it.)
+query T
+SELECT conv(CAST(-10 AS int), CAST(16 AS int), CAST(-10 AS int));
+----
+-16
+
+# More examples from the issue
+query T
+SELECT conv(CAST('3' AS string), CAST(10 AS int), CAST(2 AS int));
+----
+11
+
+query T
+SELECT conv(CAST('-15' AS string), CAST(10 AS int), CAST(-16 AS int));
+----
+-F
+
+query T
+SELECT conv(CAST('-15' AS string), CAST(10 AS int), CAST(16 AS int));
+----
+FFFFFFFFFFFFFFF1
+
+query T
+SELECT conv(CAST('big' AS string), CAST(36 AS int), CAST(16 AS int));
+----
+3A48
+
+query T
+SELECT conv(CAST('11abc' AS string), CAST(10 AS int), CAST(16 AS int));
+----
+B
+
+query T
+SELECT conv(CAST('9223372036854775808' AS string), CAST(10 AS int), CAST(16 AS 
int));
+----
+8000000000000000
+
+# Overflow with ANSI off (the harness default) saturates to -1, all bits set
+query T
+SELECT conv(CAST('92233720368547758070' AS string), CAST(10 AS int), CAST(16 
AS int));
+----
+FFFFFFFFFFFFFFFF
+
+query T
+SELECT conv(CAST('-9223372036854775807' AS string), CAST(36 AS int), CAST(10 
AS int));
+----
+18446744073709551615
+
+query T
+SELECT conv(CAST('9223372036854775807' AS string), CAST(36 AS int), CAST(10 AS 
int));
+----
+18446744073709551615
+
+query T
+SELECT 
conv(CAST('100000000000000000000000000000000000000000000000000000000000000000' 
AS string), CAST(2 AS int), CAST(8 AS int));
+----
+1777777777777777777777
+
+# Trimming: only ASCII spaces are removed
+query T
+SELECT conv(CAST(' 10 ' AS string), CAST(10 AS int), CAST(2 AS int));
+----
+1010
+
+# A leading tab is an invalid digit, so there are no valid digits and the 
result is 0
+# (the string below starts with a literal tab character)
+query T
+SELECT conv(CAST('     10' AS string), CAST(10 AS int), CAST(2 AS int));
+----
+0
+
+# Parsing stops at the first invalid digit
+query T
+SELECT conv(CAST('1.5' AS string), CAST(10 AS int), CAST(2 AS int));
+----
+1
+
+# No valid digits gives 0
+query T
+SELECT conv(CAST('zz' AS string), CAST(10 AS int), CAST(10 AS int));
+----
+0
+
+query T
+SELECT conv(CAST('-' AS string), CAST(10 AS int), CAST(10 AS int));
+----
+0
+
+# Lower- and upper-case letters are accepted; output letters are upper case
+query T
+SELECT conv(CAST('FF' AS string), CAST(16 AS int), CAST(10 AS int));
+----
+255
+
+query T
+SELECT conv(CAST('ff' AS string), CAST(16 AS int), CAST(10 AS int));
+----
+255
+
+query T
+SELECT conv(CAST('z' AS string), CAST(36 AS int), CAST(10 AS int));
+----
+35
+
+# Non-ASCII bytes are invalid digits, checked one byte at a time
+query T
+SELECT conv(CAST('é' AS string), CAST(10 AS int), CAST(10 AS int));
+----
+0
+
+query T
+SELECT conv(CAST('1é2' AS string), CAST(10 AS int), CAST(10 AS int));
+----
+1
+
+# NULL in any argument returns NULL
+query T
+SELECT conv(CAST(NULL AS string), CAST(10 AS int), CAST(16 AS int));
+----
+NULL
+
+query T
+SELECT conv(CAST('100' AS string), CAST(NULL AS int), CAST(10 AS int));
+----
+NULL
+
+query T
+SELECT conv(CAST('100' AS string), CAST(10 AS int), CAST(NULL AS int));
+----
+NULL
+
+# Out-of-range bases return NULL
+query T
+SELECT conv(CAST('1234' AS string), CAST(1 AS int), CAST(10 AS int));
+----
+NULL
+
+query T
+SELECT conv(CAST('1234' AS string), CAST(37 AS int), CAST(10 AS int));
+----
+NULL
+
+query T
+SELECT conv(CAST('1234' AS string), CAST(10 AS int), CAST(37 AS int));
+----
+NULL
+
+query T
+SELECT conv(CAST('1234' AS string), CAST(10 AS int), CAST(-37 AS int));
+----
+NULL
+
+query T
+SELECT conv(CAST('1234' AS string), CAST(10 AS int), CAST(0 AS int));
+----
+NULL
+
+query T
+SELECT conv(CAST('1234' AS string), CAST(10 AS int), CAST(1 AS int));
+----
+NULL
+
+query T
+SELECT conv(CAST('1234' AS string), CAST(10 AS int), CAST(-1 AS int));
+----
+NULL
+
+# Empty input (after trimming) returns NULL
+query T
+SELECT conv(CAST('' AS string), CAST(10 AS int), CAST(16 AS int));
+----
+NULL
+
+query T
+SELECT conv(CAST('   ' AS string), CAST(10 AS int), CAST(16 AS int));
+----
+NULL
+
+# Sign rules: Long.MinValue with to_base = -2 is the longest output (64 digits 
plus '-')
+query T
+SELECT conv(CAST('9223372036854775808' AS string), CAST(10 AS int), CAST(-2 AS 
int));
+----
+-1000000000000000000000000000000000000000000000000000000000000000
+
+query T
+SELECT conv(CAST('9223372036854775808' AS string), CAST(10 AS int), CAST(-16 
AS int));
+----
+-8000000000000000
+
+query T
+SELECT conv(CAST('-9223372036854775808' AS string), CAST(10 AS int), CAST(16 
AS int));
+----
+FFFFFFFFFFFFFFFF
+
+# A negative zero keeps its sign with a negative to_base
+query T
+SELECT conv(CAST('-0' AS string), CAST(10 AS int), CAST(-10 AS int));
+----
+-0
+
+query T
+SELECT conv(CAST('-0' AS string), CAST(10 AS int), CAST(10 AS int));
+----
+0
+
+# Non-string input is cast to a string first (ImplicitCastInputTypes)
+query T
+SELECT conv(CAST(1.5 AS double), CAST(10 AS int), CAST(2 AS int));
+----
+1
+
+# LargeUtf8 and Utf8View inputs keep their type
+query T
+SELECT conv(arrow_cast('ff', 'LargeUtf8'), CAST(16 AS int), CAST(10 AS int));
+----
+255
+
+query T
+SELECT arrow_typeof(conv(arrow_cast('ff', 'LargeUtf8'), CAST(16 AS int), 
CAST(10 AS int)));
+----
+LargeUtf8
+
+query T
+SELECT conv(arrow_cast('ff', 'Utf8View'), CAST(16 AS int), CAST(10 AS int));
+----
+255
+
+query T
+SELECT arrow_typeof(conv(arrow_cast('ff', 'Utf8View'), CAST(16 AS int), 
CAST(10 AS int)));
+----
+Utf8View
+
+# Overflow with ANSI on raises ARITHMETIC_OVERFLOW
+statement ok
+SET datafusion.execution.enable_ansi_mode = true;
+
+query error \[ARITHMETIC_OVERFLOW\] Overflow in function conv\(\)
+SELECT conv(CAST('92233720368547758070' AS string), CAST(10 AS int), CAST(16 
AS int));
+
+query error \[ARITHMETIC_OVERFLOW\] Overflow in function conv\(\)
+SELECT conv(CAST('-92233720368547758070' AS string), CAST(10 AS int), CAST(16 
AS int));
+
+statement ok
+SET datafusion.execution.enable_ansi_mode = false;
+
+# Array input: a mix of values, invalid digits and NULL rows; bases are columns

Review Comment:
   The only column query has all three arguments as columns, with a NULL only 
in `num`. A few more shapes would exercise `invoke_with_args`.
   
   ```sql
   query T
   SELECT conv(n, CAST(10 AS int), CAST(16 AS int)) FROM (VALUES (CAST('255' AS 
string)), (CAST('-1' AS string)), (CAST('' AS string)), (CAST(NULL AS string)), 
(CAST('  a  ' AS string)), (CAST('92233720368547758070' AS string))) AS t(n);
   ----
   FF
   FFFFFFFFFFFFFFFF
   NULL
   NULL
   0
   FFFFFFFFFFFFFFFF
   
   query T
   SELECT conv(CAST('255' AS string), f, t) FROM (VALUES (CAST(10 AS int), 
CAST(16 AS int)), (CAST(10 AS int), CAST(-16 AS int)), (CAST(16 AS int), 
CAST(10 AS int)), (CAST(10 AS int), CAST(37 AS int)), (CAST(NULL AS int), 
CAST(2 AS int)), (CAST(2 AS int), CAST(10 AS int))) AS t(f, t);
   ----
   FF
   FF
   597
   NULL
   NULL
   0
   ```
   
   With ANSI mode on, two cases are worth checking:
   - a column with one overflowing row should fail
   - a NULL or out-of-range base should still give NULL, because Spark checks 
those before parsing



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