datafusion_functions/string/
upper.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 crate::string::common::to_upper;
19use crate::utils::utf8_to_str_type;
20use arrow::datatypes::DataType;
21use datafusion_common::types::logical_string;
22use datafusion_common::Result;
23use datafusion_expr::{
24    Coercion, ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
25    TypeSignatureClass, Volatility,
26};
27use datafusion_macros::user_doc;
28use std::any::Any;
29
30#[user_doc(
31    doc_section(label = "String Functions"),
32    description = "Converts a string to upper-case.",
33    syntax_example = "upper(str)",
34    sql_example = r#"```sql
35> select upper('dataFusion');
36+---------------------------+
37| upper(Utf8("dataFusion")) |
38+---------------------------+
39| DATAFUSION                |
40+---------------------------+
41```"#,
42    standard_argument(name = "str", prefix = "String"),
43    related_udf(name = "initcap"),
44    related_udf(name = "lower")
45)]
46#[derive(Debug)]
47pub struct UpperFunc {
48    signature: Signature,
49}
50
51impl Default for UpperFunc {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl UpperFunc {
58    pub fn new() -> Self {
59        Self {
60            signature: Signature::coercible(
61                vec![Coercion::new_exact(TypeSignatureClass::Native(
62                    logical_string(),
63                ))],
64                Volatility::Immutable,
65            ),
66        }
67    }
68}
69
70impl ScalarUDFImpl for UpperFunc {
71    fn as_any(&self) -> &dyn Any {
72        self
73    }
74
75    fn name(&self) -> &str {
76        "upper"
77    }
78
79    fn signature(&self) -> &Signature {
80        &self.signature
81    }
82
83    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
84        utf8_to_str_type(&arg_types[0], "upper")
85    }
86
87    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
88        to_upper(&args.args, "upper")
89    }
90
91    fn documentation(&self) -> Option<&Documentation> {
92        self.doc()
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use arrow::array::{Array, ArrayRef, StringArray};
100    use arrow::datatypes::DataType::Utf8;
101    use arrow::datatypes::Field;
102    use std::sync::Arc;
103
104    fn to_upper(input: ArrayRef, expected: ArrayRef) -> Result<()> {
105        let func = UpperFunc::new();
106
107        let arg_field = Field::new("a", input.data_type().clone(), true).into();
108        let args = ScalarFunctionArgs {
109            number_rows: input.len(),
110            args: vec![ColumnarValue::Array(input)],
111            arg_fields: vec![arg_field],
112            return_field: Field::new("f", Utf8, true).into(),
113        };
114
115        let result = match func.invoke_with_args(args)? {
116            ColumnarValue::Array(result) => result,
117            _ => unreachable!("upper"),
118        };
119        assert_eq!(&expected, &result);
120        Ok(())
121    }
122
123    #[test]
124    fn upper_maybe_optimization() -> Result<()> {
125        let input = Arc::new(StringArray::from(vec![
126            Some("农历新年"),
127            None,
128            Some("datafusion"),
129            Some("0123456789"),
130            Some(""),
131        ])) as ArrayRef;
132
133        let expected = Arc::new(StringArray::from(vec![
134            Some("农历新年"),
135            None,
136            Some("DATAFUSION"),
137            Some("0123456789"),
138            Some(""),
139        ])) as ArrayRef;
140
141        to_upper(input, expected)
142    }
143
144    #[test]
145    fn upper_full_optimization() -> Result<()> {
146        let input = Arc::new(StringArray::from(vec![
147            Some("arrow"),
148            None,
149            Some("datafusion"),
150            Some("0123456789"),
151            Some(""),
152        ])) as ArrayRef;
153
154        let expected = Arc::new(StringArray::from(vec![
155            Some("ARROW"),
156            None,
157            Some("DATAFUSION"),
158            Some("0123456789"),
159            Some(""),
160        ])) as ArrayRef;
161
162        to_upper(input, expected)
163    }
164
165    #[test]
166    fn upper_partial_optimization() -> Result<()> {
167        let input = Arc::new(StringArray::from(vec![
168            Some("arrow"),
169            None,
170            Some("datafusion"),
171            Some("@_"),
172            Some("0123456789"),
173            Some(""),
174            Some("\t\n"),
175            Some("ὀδυσσεύς"),
176            Some("tschüß"),
177            Some("ⱦ"), // Ⱦ: length change
178            Some("农历新年"),
179        ])) as ArrayRef;
180
181        let expected = Arc::new(StringArray::from(vec![
182            Some("ARROW"),
183            None,
184            Some("DATAFUSION"),
185            Some("@_"),
186            Some("0123456789"),
187            Some(""),
188            Some("\t\n"),
189            Some("ὈΔΥΣΣΕΎΣ"),
190            Some("TSCHÜSS"),
191            Some("Ⱦ"),
192            Some("农历新年"),
193        ])) as ArrayRef;
194
195        to_upper(input, expected)
196    }
197}