andygrove commented on code in PR #448:
URL: https://github.com/apache/datafusion-spark/pull/448#discussion_r4811234264


##########
crates/spark/src/function/string/upper.rs:
##########
@@ -0,0 +1,545 @@
+// 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 arrow::array::{Array, ArrayRef, LargeStringArray, StringArray};
+use arrow::datatypes::{DataType, Field, FieldRef};
+use datafusion_common::cast::{
+    as_binary_array, as_binary_view_array, as_large_binary_array,
+};
+use datafusion_common::config::ConfigOptions;
+use datafusion_common::{Result, ScalarValue, internal_err, plan_err};
+use datafusion_expr::{
+    ColumnarValue, Documentation, ReturnFieldArgs, ScalarFunctionArgs, 
ScalarUDF,
+    ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::string::upper::UpperFunc;
+use datafusion_macros::user_doc;
+use std::sync::Arc;
+
+use crate::function::implicit_cast::{
+    SparkInputType, SparkInputTypes, spark_layout, spark_sql_type,
+};
+use crate::function::nullability::{SparkNullability, spark_nullability};
+
+/// Spark's `Upper` is a null-intolerant `UnaryExpression`.
+const NULLABILITY: SparkNullability = SparkNullability::null_intolerant();
+
+/// Spark-compatible `upper` expression.
+///
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#upper>
+#[user_doc(
+    doc_section(label = "String Functions"),
+    description = "Returns `str` with every character converted to uppercase, 
using \
+        the full Unicode case mapping on code points, so the output can be 
longer \
+        than the input (`ß` becomes `SS`). ASCII-only input takes a per-byte 
fast \
+        path. NULL returns NULL, and an empty string returns an empty string. \
+        Unlike DataFusion's `upper`, other atomic values (integers, decimals, \
+        booleans, binary, dates and times) are cast to a string first, so \
+        `upper(123)` is `123`, and `ucase` is an alias. FLOAT, DOUBLE, 
TIMESTAMP \
+        and interval inputs are not accepted: DataFusion's cast to a string 
formats \
+        them differently from Spark (see apache/datafusion-spark#88). Binary 
input \
+        is decoded as UTF-8, replacing invalid byte sequences with U+FFFD, 
like \
+        `make_valid_utf8`. The mapping follows the locale-insensitive root 
rules, \
+        not Turkish rules, so `i` becomes `I` and `İ` stays `İ`. The case 
mapping \
+        follows the Rust standard library Unicode tables.",
+    syntax_example = "upper(str)",
+    alternative_syntax = "ucase(str)",
+    sql_example = r#"```sql
+> SELECT upper('SparkSql');
+SPARKSQL
+> SELECT ucase('SparkSql');
+SPARKSQL
+> SELECT upper('ß');
+SS
+> SELECT upper('ςαλατα');
+ΣΑΛΑΤΑ
+> SELECT upper(NULL);
+NULL
+```"#,
+    argument(
+        name = "str",
+        description = "String expression. Other atomic values are cast to a 
string \
+            first, except FLOAT, DOUBLE, TIMESTAMP and interval inputs, which 
are \
+            rejected. NULL returns NULL."
+    )
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkUpper {
+    input_types: SparkInputTypes,
+    aliases: Vec<String>,
+}
+
+impl Default for SparkUpper {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkUpper {
+    pub fn new() -> Self {
+        Self {
+            // Spark's `Upper.inputTypes`: `ImplicitCastInputTypes` with 
`StringType`,
+            // so the analyzer casts other atomic inputs to STRING before the 
function
+            // runs, and the kernel only has to handle strings.
+            input_types: SparkInputTypes::new(
+                vec![SparkInputType::String],
+                Volatility::Immutable,
+            ),
+            aliases: vec![String::from("ucase")],
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkUpper {
+    fn name(&self) -> &str {
+        "upper"
+    }
+
+    fn signature(&self) -> &Signature {
+        self.input_types.signature()
+    }
+
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+        if arg_types.len() == 1 {
+            let layout = spark_layout(&arg_types[0]);
+            // FLOAT, DOUBLE, TIMESTAMP and interval inputs are not accepted 
for
+            // now: DataFusion's cast to a string formats them differently from
+            // Spark (for example `upper(CAST(1e20 AS DOUBLE))` is `1E20` here 
but
+            // `1.0E20` in Spark), so accepting them would silently return 
wrong
+            // results. See apache/datafusion-spark#88 for the CAST work that
+            // would close the gap.
+            if matches!(
+                layout,
+                DataType::Float16
+                    | DataType::Float32
+                    | DataType::Float64
+                    | DataType::Timestamp(_, _)
+                    | DataType::Interval(_)
+                    | DataType::Duration(_)
+            ) {
+                return plan_err!(
+                    "[DATATYPE_MISMATCH.UNEXPECTED_INPUT_TYPE] The first 
parameter of \
+                     `upper` requires the \"STRING\" type, however it has the 
type \"{}\". \
+                     SQLSTATE: 42K09",
+                    spark_sql_type(&layout)
+                );
+            }
+            // Binary input stays binary so the kernel can decode it lossily
+            // (see `upper_decode_binary_args`): letting the analyzer cast it
+            // to a string would fail on invalid UTF-8, while Spark decodes it
+            // with U+FFFD replacements.
+            if layout.is_binary() {
+                return Ok(vec![layout]);
+            }
+        }
+        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,
+            aliases: self.aliases.clone(),
+        }))
+    }
+
+    fn aliases(&self) -> &[String] {
+        &self.aliases
+    }
+
+    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> {
+        // Binary input is decoded to a string by the kernel, so the result is
+        // a string type even though the input stays binary through coercion.
+        let return_type = match args.arg_fields[0].data_type() {
+            DataType::Binary | DataType::BinaryView => DataType::Utf8,
+            DataType::LargeBinary => DataType::LargeUtf8,
+            other => other.clone(),
+        };
+        Ok(NULLABILITY.return_field(self.name(), return_type, args.arg_fields))
+    }
+
+    spark_nullability!(NULLABILITY);
+
+    fn documentation(&self) -> Option<&Documentation> {
+        self.doc()
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        // DataFusion's `upper` already implements Spark's kernel: the full 
Unicode
+        // case mapping on code points (`char::to_uppercase`) with an ASCII 
fast
+        // path, for `Utf8`, `LargeUtf8` and `Utf8View`, scalar and array, and 
it
+        // preserves NULLs. Spark's `Upper` only adds the implicit cast to 
STRING
+        // (handled by `SparkInputTypes` above) and the `ucase` alias, so 
delegate
+        // to it instead of re-implementing the kernel.
+        //
+        // Binary input is decoded lossily first (invalid UTF-8 bytes become
+        // U+FFFD), like `make_valid_utf8`: the analyzer would otherwise cast 
it
+        // to a string, which fails on invalid UTF-8, while Spark decodes it.
+        let args = if args
+            .args
+            .first()
+            .is_some_and(|arg| arg.data_type().is_binary())
+        {
+            upper_decode_binary_args(args)?
+        } else {
+            args
+        };
+        UpperFunc::new().invoke_with_args(args)
+    }
+}
+
+/// Decode a binary argument to a string, replacing invalid UTF-8 byte
+/// sequences with U+FFFD, like `make_valid_utf8`.
+///
+/// The argument, its field and the return field are all rewritten to the
+/// matching string type, so the `upper` kernel sees a plain string array.
+fn upper_decode_binary_args(mut args: ScalarFunctionArgs) -> 
Result<ScalarFunctionArgs> {
+    let Some(string_type) = binary_string_type(&args.args[0].data_type()) else 
{
+        return Ok(args);
+    };
+    args.args[0] = match &args.args[0] {
+        ColumnarValue::Array(array) => {
+            ColumnarValue::Array(binary_to_string_array(array)?)
+        }
+        ColumnarValue::Scalar(scalar) => {
+            ColumnarValue::Scalar(binary_to_string_scalar(scalar)?)
+        }
+    };
+    args.arg_fields[0] = Arc::new(Field::new(
+        args.arg_fields[0].name(),
+        string_type.clone(),
+        args.arg_fields[0].is_nullable(),
+    ));
+    args.return_field = Arc::new(Field::new(
+        args.return_field.name(),
+        string_type,
+        args.return_field.is_nullable(),
+    ));
+    Ok(args)
+}
+
+/// The string type a binary type decodes to, or `None` when the type is not 
binary.
+fn binary_string_type(data_type: &DataType) -> Option<DataType> {
+    match data_type {
+        DataType::Binary | DataType::BinaryView => Some(DataType::Utf8),
+        DataType::LargeBinary => Some(DataType::LargeUtf8),
+        _ => None,
+    }
+}
+
+/// Decode a binary array to a string array, replacing invalid UTF-8 byte
+/// sequences with U+FFFD.
+fn binary_to_string_array(array: &ArrayRef) -> Result<ArrayRef> {
+    match array.data_type() {
+        DataType::Binary => Ok(Arc::new(
+            as_binary_array(array)?
+                .iter()
+                .map(|x| x.map(String::from_utf8_lossy))
+                .collect::<StringArray>(),
+        )),
+        DataType::BinaryView => Ok(Arc::new(
+            as_binary_view_array(array)?
+                .iter()
+                .map(|x| x.map(String::from_utf8_lossy))
+                .collect::<StringArray>(),
+        )),
+        DataType::LargeBinary => Ok(Arc::new(
+            as_large_binary_array(array)?
+                .iter()
+                .map(|x| x.map(String::from_utf8_lossy))
+                .collect::<LargeStringArray>(),
+        )),
+        data_type => internal_err!("upper does not support binary input: 
{data_type}"),
+    }
+}
+
+/// Decode a binary scalar to a string scalar, replacing invalid UTF-8 byte
+/// sequences with U+FFFD.
+fn binary_to_string_scalar(scalar: &ScalarValue) -> Result<ScalarValue> {
+    match scalar {
+        ScalarValue::Binary(bytes) => Ok(ScalarValue::Utf8(
+            bytes
+                .as_ref()
+                .map(|b| String::from_utf8_lossy(b).into_owned()),
+        )),
+        ScalarValue::BinaryView(bytes) => Ok(ScalarValue::Utf8View(

Review Comment:
   I found one crash here. A `BinaryView` scalar fails at execution:
   
   ```
   SELECT upper(arrow_cast(X'61FF62', 'BinaryView'));
   -- Internal error: ... Function 'upper' returned value of type 'Utf8View' 
while ... 'Utf8' was promised
   ```
   
   `binary_string_type` says `BinaryView` becomes `Utf8`, but 
`binary_to_string_scalar` builds `ScalarValue::Utf8View`.
   
   `binary_to_string_array` is the same as `spark_make_valid_utf8_inner` in 
`make_valid_utf8.rs`. Could you make that function `pub(super)` and call it 
through `make_scalar_function`, as #398 does? That handles scalars and arrays 
the same way, removes about 60 lines, and fixes this case. A `BinaryView` 
scalar record in `upper.slt` would lock it in.



##########
crates/spark/src/function/string/upper.rs:
##########
@@ -0,0 +1,545 @@
+// 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 arrow::array::{Array, ArrayRef, LargeStringArray, StringArray};
+use arrow::datatypes::{DataType, Field, FieldRef};
+use datafusion_common::cast::{
+    as_binary_array, as_binary_view_array, as_large_binary_array,
+};
+use datafusion_common::config::ConfigOptions;
+use datafusion_common::{Result, ScalarValue, internal_err, plan_err};
+use datafusion_expr::{
+    ColumnarValue, Documentation, ReturnFieldArgs, ScalarFunctionArgs, 
ScalarUDF,
+    ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::string::upper::UpperFunc;
+use datafusion_macros::user_doc;
+use std::sync::Arc;
+
+use crate::function::implicit_cast::{
+    SparkInputType, SparkInputTypes, spark_layout, spark_sql_type,
+};
+use crate::function::nullability::{SparkNullability, spark_nullability};
+
+/// Spark's `Upper` is a null-intolerant `UnaryExpression`.
+const NULLABILITY: SparkNullability = SparkNullability::null_intolerant();
+
+/// Spark-compatible `upper` expression.
+///
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#upper>
+#[user_doc(
+    doc_section(label = "String Functions"),
+    description = "Returns `str` with every character converted to uppercase, 
using \
+        the full Unicode case mapping on code points, so the output can be 
longer \
+        than the input (`ß` becomes `SS`). ASCII-only input takes a per-byte 
fast \
+        path. NULL returns NULL, and an empty string returns an empty string. \
+        Unlike DataFusion's `upper`, other atomic values (integers, decimals, \
+        booleans, binary, dates and times) are cast to a string first, so \
+        `upper(123)` is `123`, and `ucase` is an alias. FLOAT, DOUBLE, 
TIMESTAMP \
+        and interval inputs are not accepted: DataFusion's cast to a string 
formats \
+        them differently from Spark (see apache/datafusion-spark#88). Binary 
input \
+        is decoded as UTF-8, replacing invalid byte sequences with U+FFFD, 
like \
+        `make_valid_utf8`. The mapping follows the locale-insensitive root 
rules, \
+        not Turkish rules, so `i` becomes `I` and `İ` stays `İ`. The case 
mapping \
+        follows the Rust standard library Unicode tables.",
+    syntax_example = "upper(str)",
+    alternative_syntax = "ucase(str)",
+    sql_example = r#"```sql
+> SELECT upper('SparkSql');
+SPARKSQL
+> SELECT ucase('SparkSql');
+SPARKSQL
+> SELECT upper('ß');
+SS
+> SELECT upper('ςαλατα');
+ΣΑΛΑΤΑ
+> SELECT upper(NULL);
+NULL
+```"#,
+    argument(
+        name = "str",
+        description = "String expression. Other atomic values are cast to a 
string \
+            first, except FLOAT, DOUBLE, TIMESTAMP and interval inputs, which 
are \
+            rejected. NULL returns NULL."
+    )
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkUpper {
+    input_types: SparkInputTypes,
+    aliases: Vec<String>,
+}
+
+impl Default for SparkUpper {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkUpper {
+    pub fn new() -> Self {
+        Self {
+            // Spark's `Upper.inputTypes`: `ImplicitCastInputTypes` with 
`StringType`,
+            // so the analyzer casts other atomic inputs to STRING before the 
function
+            // runs, and the kernel only has to handle strings.
+            input_types: SparkInputTypes::new(
+                vec![SparkInputType::String],
+                Volatility::Immutable,
+            ),
+            aliases: vec![String::from("ucase")],
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkUpper {
+    fn name(&self) -> &str {
+        "upper"
+    }
+
+    fn signature(&self) -> &Signature {
+        self.input_types.signature()
+    }
+
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {

Review Comment:
   I need to correct my earlier comment that decimals already match Spark. They 
don't once the scale is above 6. Java's `BigDecimal.toString` switches to 
scientific notation then:
   
   ```
   upper(CAST(0 AS DECIMAL(10,8)))           -- this PR 0.00000000, Spark 0E-8
   upper(CAST(0.00000001 AS DECIMAL(10,8)))  -- this PR 0.00000001, Spark 1E-8
   ```
   
   Could you also reject `Decimal128`/`Decimal256` with scale above 6? Every 
other decimal formats the same as in Spark.
   
   Also, `lower` (#398) and `initcap` (#453) need this same check. What do you 
think about putting it in one helper in `implicit_cast.rs` rather than making 
`spark_layout` and `spark_sql_type` `pub(crate)` and writing the check inline? 
Then the three functions can't drift apart.



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