datafusion_functions/string/
chr.rs1use std::any::Any;
19use std::sync::Arc;
20
21use arrow::array::ArrayRef;
22use arrow::array::GenericStringBuilder;
23use arrow::datatypes::DataType;
24use arrow::datatypes::DataType::Int64;
25use arrow::datatypes::DataType::Utf8;
26
27use crate::utils::make_scalar_function;
28use datafusion_common::cast::as_int64_array;
29use datafusion_common::{exec_err, Result};
30use datafusion_expr::{ColumnarValue, Documentation, Volatility};
31use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature};
32use datafusion_macros::user_doc;
33
34pub fn chr(args: &[ArrayRef]) -> Result<ArrayRef> {
37 let integer_array = as_int64_array(&args[0])?;
38
39 let mut builder = GenericStringBuilder::<i32>::with_capacity(
40 integer_array.len(),
41 integer_array.len(),
43 );
44
45 let mut buf = [0u8; 4];
46
47 for integer in integer_array {
48 match integer {
49 Some(integer) => {
50 if integer == 0 {
51 return exec_err!("null character not permitted.");
52 } else {
53 match core::char::from_u32(integer as u32) {
54 Some(c) => {
55 builder.append_value(c.encode_utf8(&mut buf));
56 }
57 None => {
58 return exec_err!(
59 "requested character too large for encoding."
60 );
61 }
62 }
63 }
64 }
65 None => {
66 builder.append_null();
67 }
68 }
69 }
70
71 let result = builder.finish();
72
73 Ok(Arc::new(result) as ArrayRef)
74}
75
76#[user_doc(
77 doc_section(label = "String Functions"),
78 description = "Returns the character with the specified ASCII or Unicode code value.",
79 syntax_example = "chr(expression)",
80 sql_example = r#"```sql
81> select chr(128640);
82+--------------------+
83| chr(Int64(128640)) |
84+--------------------+
85| 🚀 |
86+--------------------+
87```"#,
88 standard_argument(name = "expression", prefix = "String"),
89 related_udf(name = "ascii")
90)]
91#[derive(Debug)]
92pub struct ChrFunc {
93 signature: Signature,
94}
95
96impl Default for ChrFunc {
97 fn default() -> Self {
98 Self::new()
99 }
100}
101
102impl ChrFunc {
103 pub fn new() -> Self {
104 Self {
105 signature: Signature::uniform(1, vec![Int64], Volatility::Immutable),
106 }
107 }
108}
109
110impl ScalarUDFImpl for ChrFunc {
111 fn as_any(&self) -> &dyn Any {
112 self
113 }
114
115 fn name(&self) -> &str {
116 "chr"
117 }
118
119 fn signature(&self) -> &Signature {
120 &self.signature
121 }
122
123 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
124 Ok(Utf8)
125 }
126
127 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
128 make_scalar_function(chr, vec![])(&args.args)
129 }
130
131 fn documentation(&self) -> Option<&Documentation> {
132 self.doc()
133 }
134}