Skip to main content

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::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 name(&self) -> &str {
54        "char"
55    }
56
57    fn signature(&self) -> &Signature {
58        &self.signature
59    }
60
61    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
62        datafusion_common::internal_err!(
63            "return_type should not be called, use return_field_from_args instead"
64        )
65    }
66
67    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
68        spark_chr(&args.args)
69    }
70
71    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
72        let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
73        Ok(Arc::new(Field::new(self.name(), Utf8, nullable)))
74    }
75}
76
77/// Returns the ASCII character having the binary equivalent to the input expression.
78/// E.g., chr(65) = 'A'.
79/// Compatible with Apache Spark's Chr function
80fn spark_chr(args: &[ColumnarValue]) -> Result<ColumnarValue> {
81    let array = args[0].clone();
82    match array {
83        ColumnarValue::Array(array) => {
84            let array = chr(&[array])?;
85            Ok(ColumnarValue::Array(array))
86        }
87        ColumnarValue::Scalar(ScalarValue::Int64(Some(value))) => {
88            if value < 0 {
89                Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
90                    "".to_string(),
91                ))))
92            } else {
93                match core::char::from_u32((value % 256) as u32) {
94                    Some(ch) => Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
95                        ch.to_string(),
96                    )))),
97                    None => {
98                        exec_err!("requested character was incompatible for encoding.")
99                    }
100                }
101            }
102        }
103        _ => exec_err!("The argument must be an Int64 array or scalar."),
104    }
105}
106
107fn chr(args: &[ArrayRef]) -> Result<ArrayRef> {
108    let integer_array = as_int64_array(&args[0])?;
109
110    let mut builder = GenericStringBuilder::<i32>::with_capacity(
111        integer_array.len(),
112        integer_array.len(),
113    );
114
115    for integer_opt in integer_array {
116        match integer_opt {
117            Some(integer) => {
118                if integer < 0 {
119                    builder.append_value(""); // empty string for negative numbers.
120                } else {
121                    match core::char::from_u32((integer % 256) as u32) {
122                        Some(ch) => builder.append_value(ch.to_string()),
123                        None => {
124                            return exec_err!(
125                                "requested character not compatible for encoding."
126                            );
127                        }
128                    }
129                }
130            }
131            None => builder.append_null(),
132        }
133    }
134
135    Ok(Arc::new(builder.finish()) as ArrayRef)
136}
137
138#[test]
139fn test_char_nullability() -> Result<()> {
140    use arrow::datatypes::{DataType::Utf8, Field, FieldRef};
141    use datafusion_expr::ReturnFieldArgs;
142    use std::sync::Arc;
143
144    let func = CharFunc::new();
145
146    let nullable_field: FieldRef = Arc::new(Field::new("col", Int64, true));
147
148    let out_nullable = func.return_field_from_args(ReturnFieldArgs {
149        arg_fields: &[nullable_field],
150        scalar_arguments: &[None],
151    })?;
152
153    assert!(
154        out_nullable.is_nullable(),
155        "char(col) should be nullable when input column is nullable"
156    );
157    assert_eq!(
158        out_nullable.data_type(),
159        &Utf8,
160        "char always returns Utf8 regardless of input type"
161    );
162
163    let non_nullable_field: FieldRef = Arc::new(Field::new("col", Int64, false));
164
165    let out_non_nullable = func.return_field_from_args(ReturnFieldArgs {
166        arg_fields: &[non_nullable_field],
167        scalar_arguments: &[None],
168    })?;
169
170    assert!(
171        !out_non_nullable.is_nullable(),
172        "char(col) should NOT be nullable when input column is NOT nullable"
173    );
174    assert_eq!(
175        out_non_nullable.data_type(),
176        &Utf8,
177        "char always returns Utf8 regardless of input type"
178    );
179
180    Ok(())
181}