datafusion_spark/function/string/
char.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use arrow::array::ArrayRef;
19use arrow::array::GenericStringBuilder;
20use arrow::datatypes::DataType::Int64;
21use arrow::datatypes::DataType::Utf8;
22use arrow::datatypes::{DataType, Field, FieldRef};
23use std::{any::Any, sync::Arc};
24
25use datafusion_common::{Result, ScalarValue, cast::as_int64_array, exec_err};
26use datafusion_expr::{
27    ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature,
28    Volatility,
29};
30
31/// Spark-compatible `char` expression
32/// <https://spark.apache.org/docs/latest/api/sql/index.html#char>
33#[derive(Debug, PartialEq, Eq, Hash)]
34pub struct CharFunc {
35    signature: Signature,
36}
37
38impl Default for CharFunc {
39    fn default() -> Self {
40        Self::new()
41    }
42}
43
44impl CharFunc {
45    pub fn new() -> Self {
46        Self {
47            signature: Signature::uniform(1, vec![Int64], Volatility::Immutable),
48        }
49    }
50}
51
52impl ScalarUDFImpl for CharFunc {
53    fn as_any(&self) -> &dyn Any {
54        self
55    }
56
57    fn name(&self) -> &str {
58        "char"
59    }
60
61    fn signature(&self) -> &Signature {
62        &self.signature
63    }
64
65    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
66        datafusion_common::internal_err!(
67            "return_type should not be called, use return_field_from_args instead"
68        )
69    }
70
71    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
72        spark_chr(&args.args)
73    }
74
75    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
76        let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
77        Ok(Arc::new(Field::new(self.name(), Utf8, nullable)))
78    }
79}
80
81/// Returns the ASCII character having the binary equivalent to the input expression.
82/// E.g., chr(65) = 'A'.
83/// Compatible with Apache Spark's Chr function
84fn spark_chr(args: &[ColumnarValue]) -> Result<ColumnarValue> {
85    let array = args[0].clone();
86    match array {
87        ColumnarValue::Array(array) => {
88            let array = chr(&[array])?;
89            Ok(ColumnarValue::Array(array))
90        }
91        ColumnarValue::Scalar(ScalarValue::Int64(Some(value))) => {
92            if value < 0 {
93                Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
94                    "".to_string(),
95                ))))
96            } else {
97                match core::char::from_u32((value % 256) as u32) {
98                    Some(ch) => Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
99                        ch.to_string(),
100                    )))),
101                    None => {
102                        exec_err!("requested character was incompatible for encoding.")
103                    }
104                }
105            }
106        }
107        _ => exec_err!("The argument must be an Int64 array or scalar."),
108    }
109}
110
111fn chr(args: &[ArrayRef]) -> Result<ArrayRef> {
112    let integer_array = as_int64_array(&args[0])?;
113
114    let mut builder = GenericStringBuilder::<i32>::with_capacity(
115        integer_array.len(),
116        integer_array.len(),
117    );
118
119    for integer_opt in integer_array {
120        match integer_opt {
121            Some(integer) => {
122                if integer < 0 {
123                    builder.append_value(""); // empty string for negative numbers.
124                } else {
125                    match core::char::from_u32((integer % 256) as u32) {
126                        Some(ch) => builder.append_value(ch.to_string()),
127                        None => {
128                            return exec_err!(
129                                "requested character not compatible for encoding."
130                            );
131                        }
132                    }
133                }
134            }
135            None => builder.append_null(),
136        }
137    }
138
139    Ok(Arc::new(builder.finish()) as ArrayRef)
140}
141
142#[test]
143fn test_char_nullability() -> Result<()> {
144    use arrow::datatypes::{DataType::Utf8, Field, FieldRef};
145    use datafusion_expr::ReturnFieldArgs;
146    use std::sync::Arc;
147
148    let func = CharFunc::new();
149
150    let nullable_field: FieldRef = Arc::new(Field::new("col", Int64, true));
151
152    let out_nullable = func.return_field_from_args(ReturnFieldArgs {
153        arg_fields: &[nullable_field],
154        scalar_arguments: &[None],
155    })?;
156
157    assert!(
158        out_nullable.is_nullable(),
159        "char(col) should be nullable when input column is nullable"
160    );
161    assert_eq!(
162        out_nullable.data_type(),
163        &Utf8,
164        "char always returns Utf8 regardless of input type"
165    );
166
167    let non_nullable_field: FieldRef = Arc::new(Field::new("col", Int64, false));
168
169    let out_non_nullable = func.return_field_from_args(ReturnFieldArgs {
170        arg_fields: &[non_nullable_field],
171        scalar_arguments: &[None],
172    })?;
173
174    assert!(
175        !out_non_nullable.is_nullable(),
176        "char(col) should NOT be nullable when input column is NOT nullable"
177    );
178    assert_eq!(
179        out_non_nullable.data_type(),
180        &Utf8,
181        "char always returns Utf8 regardless of input type"
182    );
183
184    Ok(())
185}