martin-g commented on code in PR #17561:
URL: https://github.com/apache/datafusion/pull/17561#discussion_r2390183578


##########
datafusion/spark/src/function/string/format_string.rs:
##########
@@ -0,0 +1,2374 @@
+// 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::fmt::Write;
+use std::sync::Arc;
+
+use core::num::FpCategory;
+
+use arrow::{
+    array::{Array, ArrayRef, LargeStringArray, StringArray, StringViewArray},
+    datatypes::DataType,
+};
+use bigdecimal::{
+    num_bigint::{BigInt, Sign},
+    BigDecimal, ToPrimitive,
+};
+use chrono::{DateTime, Datelike, Timelike, Utc};
+use datafusion_common::{
+    exec_datafusion_err, exec_err, plan_err, DataFusionError, Result, 
ScalarValue,
+};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature,
+    Volatility,
+};
+
+/// Spark-compatible `format_string` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#format_string>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct FormatStringFunc {
+    signature: Signature,
+    aliases: Vec<String>,
+}
+
+impl Default for FormatStringFunc {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl FormatStringFunc {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::new(TypeSignature::VariadicAny, 
Volatility::Immutable),
+            aliases: vec![String::from("printf")],
+        }
+    }
+}
+
+impl ScalarUDFImpl for FormatStringFunc {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "format_string"
+    }
+
+    fn aliases(&self) -> &[String] {
+        &self.aliases
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        if arg_types.is_empty() {
+            return plan_err!("The format_string function expects at least one 
argument");
+        }
+        if arg_types[0] == DataType::Null {
+            return Ok(DataType::Utf8);
+        }
+        if !matches!(
+            arg_types[0],
+            DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
+        ) {
+            return plan_err!("The format_string function expects the first 
argument to be Utf8, LargeUtf8 or Utf8View");
+        }
+        Ok(arg_types[0].clone())
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let len = args
+            .args
+            .iter()
+            .fold(Option::<usize>::None, |acc, arg| match arg {
+                ColumnarValue::Scalar(_) => acc,
+                ColumnarValue::Array(a) => Some(a.len()),
+            });
+        let is_scalar = len.is_none();
+        let data_types = args.args[1..]
+            .iter()
+            .map(|arg| arg.data_type())
+            .collect::<Vec<_>>();
+        let fmt_type = args.args[0].data_type();
+
+        match &args.args[0] {
+            ColumnarValue::Scalar(ScalarValue::Null) => {
+                Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None)))
+            }
+            ColumnarValue::Scalar(ScalarValue::Utf8(Some(fmt)))
+            | ColumnarValue::Scalar(ScalarValue::LargeUtf8(Some(fmt)))
+            | ColumnarValue::Scalar(ScalarValue::Utf8View(Some(fmt))) => {
+                let formatter = Formatter::parse(fmt, &data_types)?;
+                let mut result = Vec::with_capacity(len.unwrap_or(1));
+                for i in 0..len.unwrap_or(1) {
+                    let scalars = args.args[1..]
+                        .iter()
+                        .map(|arg| try_to_scalar(arg.clone(), i))
+                        .collect::<Result<Vec<_>>>()?;
+                    let formatted = formatter.format(&scalars)?;
+                    result.push(formatted);
+                }
+                if is_scalar {
+                    match fmt_type {
+                        DataType::Utf8 => 
Ok(ColumnarValue::Scalar(ScalarValue::Utf8(
+                            Some(result.first().unwrap().clone()),
+                        ))),
+                        DataType::LargeUtf8 => Ok(ColumnarValue::Scalar(
+                            
ScalarValue::LargeUtf8(Some(result.first().unwrap().clone())),
+                        )),
+                        DataType::Utf8View => Ok(ColumnarValue::Scalar(
+                            
ScalarValue::Utf8View(Some(result.first().unwrap().clone())),
+                        )),
+                        _ => unreachable!(),
+                    }
+                } else {
+                    let array: ArrayRef = match fmt_type {
+                        DataType::Utf8 => Arc::new(StringArray::from(result)),
+                        DataType::LargeUtf8 => 
Arc::new(LargeStringArray::from(result)),
+                        DataType::Utf8View => 
Arc::new(StringViewArray::from(result)),
+                        _ => unreachable!(),
+                    };
+                    Ok(ColumnarValue::Array(array))
+                }
+            }
+            ColumnarValue::Array(fmts) => {
+                let mut result = Vec::with_capacity(len.unwrap());
+                for i in 0..len.unwrap() {
+                    let fmt = ScalarValue::try_from_array(fmts, i)?;
+                    match fmt.try_as_str() {
+                        Some(Some(fmt)) => {
+                            let formatter = Formatter::parse(fmt, 
&data_types)?;
+                            let scalars = args.args[1..]
+                                .iter()
+                                .map(|arg| try_to_scalar(arg.clone(), i))
+                                .collect::<Result<Vec<_>>>()?;
+                            let formatted = formatter.format(&scalars)?;
+                            result.push(Some(formatted));
+                        }
+                        Some(None) => {
+                            result.push(None);
+                        }
+                        _ => {
+                            return exec_err!(
+                                "Expected string type, got {:?}",
+                                fmt.data_type()
+                            )
+                        }
+                    }
+                }
+                let array: ArrayRef = match fmt_type {
+                    DataType::Utf8 => Arc::new(StringArray::from(result)),
+                    DataType::LargeUtf8 => 
Arc::new(LargeStringArray::from(result)),
+                    DataType::Utf8View => 
Arc::new(StringViewArray::from(result)),
+                    _ => unreachable!(),
+                };
+                Ok(ColumnarValue::Array(array))
+            }
+            _ => exec_err!(
+                "The format_string function expects the first argument to be a 
string"
+            ),
+        }
+    }
+}
+
+fn try_to_scalar(arg: ColumnarValue, index: usize) -> Result<ScalarValue> {
+    match arg {
+        ColumnarValue::Scalar(scalar) => Ok(scalar),
+        ColumnarValue::Array(array) => Ok(ScalarValue::try_from_array(&array, 
index)?),

Review Comment:
   ```suggestion
           ColumnarValue::Array(array) => ScalarValue::try_from_array(&array, 
index),
   ```



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