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    // Each character encodes into this stack buffer, so no row allocates a `String`.
116    let mut encoded = [0u8; 4];
117    for integer_opt in integer_array {
118        match integer_opt {
119            Some(integer) => {
120                if integer < 0 {
121                    builder.append_value(""); // empty string for negative numbers.
122                } else {
123                    match core::char::from_u32((integer % 256) as u32) {
124                        Some(ch) => builder.append_value(ch.encode_utf8(&mut encoded)),
125                        None => {
126                            return exec_err!(
127                                "requested character not compatible for encoding."
128                            );
129                        }
130                    }
131                }
132            }
133            None => builder.append_null(),
134        }
135    }
136
137    Ok(Arc::new(builder.finish()) as ArrayRef)
138}
139
140#[test]
141fn test_char_nullability() -> Result<()> {
142    use arrow::datatypes::{DataType::Utf8, Field, FieldRef};
143    use datafusion_expr::ReturnFieldArgs;
144    use std::sync::Arc;
145
146    let func = CharFunc::new();
147
148    let nullable_field: FieldRef = Arc::new(Field::new("col", Int64, true));
149
150    let out_nullable = func.return_field_from_args(ReturnFieldArgs {
151        arg_fields: &[nullable_field],
152        scalar_arguments: &[None],
153    })?;
154
155    assert!(
156        out_nullable.is_nullable(),
157        "char(col) should be nullable when input column is nullable"
158    );
159    assert_eq!(
160        out_nullable.data_type(),
161        &Utf8,
162        "char always returns Utf8 regardless of input type"
163    );
164
165    let non_nullable_field: FieldRef = Arc::new(Field::new("col", Int64, false));
166
167    let out_non_nullable = func.return_field_from_args(ReturnFieldArgs {
168        arg_fields: &[non_nullable_field],
169        scalar_arguments: &[None],
170    })?;
171
172    assert!(
173        !out_non_nullable.is_nullable(),
174        "char(col) should NOT be nullable when input column is NOT nullable"
175    );
176    assert_eq!(
177        out_non_nullable.data_type(),
178        &Utf8,
179        "char always returns Utf8 regardless of input type"
180    );
181
182    Ok(())
183}