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 std::sync::Arc;
101
102    fn to_upper(input: ArrayRef, expected: ArrayRef) -> Result<()> {
103        let func = UpperFunc::new();
104
105        let args = ScalarFunctionArgs {
106            number_rows: input.len(),
107            args: vec![ColumnarValue::Array(input)],
108            return_type: &DataType::Utf8,
109        };
110
111        let result = match func.invoke_with_args(args)? {
112            ColumnarValue::Array(result) => result,
113            _ => unreachable!("upper"),
114        };
115        assert_eq!(&expected, &result);
116        Ok(())
117    }
118
119    #[test]
120    fn upper_maybe_optimization() -> Result<()> {
121        let input = Arc::new(StringArray::from(vec![
122            Some("农历新年"),
123            None,
124            Some("datafusion"),
125            Some("0123456789"),
126            Some(""),
127        ])) as ArrayRef;
128
129        let expected = Arc::new(StringArray::from(vec![
130            Some("农历新年"),
131            None,
132            Some("DATAFUSION"),
133            Some("0123456789"),
134            Some(""),
135        ])) as ArrayRef;
136
137        to_upper(input, expected)
138    }
139
140    #[test]
141    fn upper_full_optimization() -> Result<()> {
142        let input = Arc::new(StringArray::from(vec![
143            Some("arrow"),
144            None,
145            Some("datafusion"),
146            Some("0123456789"),
147            Some(""),
148        ])) as ArrayRef;
149
150        let expected = Arc::new(StringArray::from(vec![
151            Some("ARROW"),
152            None,
153            Some("DATAFUSION"),
154            Some("0123456789"),
155            Some(""),
156        ])) as ArrayRef;
157
158        to_upper(input, expected)
159    }
160
161    #[test]
162    fn upper_partial_optimization() -> Result<()> {
163        let input = Arc::new(StringArray::from(vec![
164            Some("arrow"),
165            None,
166            Some("datafusion"),
167            Some("@_"),
168            Some("0123456789"),
169            Some(""),
170            Some("\t\n"),
171            Some("ὀδυσσεύς"),
172            Some("tschüß"),
173            Some("ⱦ"), // Ⱦ: length change
174            Some("农历新年"),
175        ])) as ArrayRef;
176
177        let expected = Arc::new(StringArray::from(vec![
178            Some("ARROW"),
179            None,
180            Some("DATAFUSION"),
181            Some("@_"),
182            Some("0123456789"),
183            Some(""),
184            Some("\t\n"),
185            Some("ὈΔΥΣΣΕΎΣ"),
186            Some("TSCHÜSS"),
187            Some("Ⱦ"),
188            Some("农历新年"),
189        ])) as ArrayRef;
190
191        to_upper(input, expected)
192    }
193}