Skip to main content

common_function/scalars/
udf.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::{Debug, Formatter};
16use std::hash::{Hash, Hasher};
17
18use datafusion::arrow::datatypes::DataType;
19use datafusion::logical_expr::{ScalarFunctionArgs, ScalarUDFImpl};
20use datafusion_expr::{ExpressionPlacement, ScalarUDF};
21
22use crate::function::FunctionRef;
23
24struct ScalarUdf {
25    function: FunctionRef,
26    placement: ExpressionPlacement,
27}
28
29impl Debug for ScalarUdf {
30    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
31        f.debug_struct("ScalarUdf")
32            .field("function", &self.function.name())
33            .finish()
34    }
35}
36
37impl PartialEq for ScalarUdf {
38    fn eq(&self, other: &Self) -> bool {
39        // Identity first: many unrelated functions share one signature (for
40        // example `Signature::any(1, Immutable)`), and DataFusion compares
41        // expressions (and therefore `ScalarUDF`s) structurally, so matching on
42        // the signature alone makes different functions interchangeable and
43        // corrupts planning (see `rebase_expr`).
44        self.placement == other.placement
45            && self.function.name() == other.function.name()
46            && self.function.signature() == other.function.signature()
47    }
48}
49
50impl Eq for ScalarUdf {}
51
52impl Hash for ScalarUdf {
53    fn hash<H: Hasher>(&self, state: &mut H) {
54        self.function.name().hash(state);
55        self.function.signature().hash(state);
56    }
57}
58
59impl ScalarUDFImpl for ScalarUdf {
60    fn name(&self) -> &str {
61        self.function.name()
62    }
63
64    fn placement(&self, _args: &[ExpressionPlacement]) -> ExpressionPlacement {
65        self.placement
66    }
67
68    fn aliases(&self) -> &[String] {
69        self.function.aliases()
70    }
71
72    fn signature(&self) -> &datafusion_expr::Signature {
73        self.function.signature()
74    }
75
76    fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result<DataType> {
77        self.function.return_type(arg_types)
78    }
79
80    fn return_field_from_args(
81        &self,
82        args: datafusion_expr::ReturnFieldArgs,
83    ) -> datafusion_common::Result<arrow_schema::FieldRef> {
84        self.function.return_field_from_args(args)
85    }
86
87    fn invoke_with_args(
88        &self,
89        args: ScalarFunctionArgs,
90    ) -> datafusion_common::Result<datafusion_expr::ColumnarValue> {
91        self.function.invoke_with_args(args)
92    }
93}
94
95/// Create a ScalarUdf from function, query context and state.
96pub fn create_udf(function: FunctionRef) -> ScalarUDF {
97    create_udf_with_placement(function, ExpressionPlacement::KeepInPlace)
98}
99
100pub(super) fn create_udf_with_placement(
101    function: FunctionRef,
102    placement: ExpressionPlacement,
103) -> ScalarUDF {
104    ScalarUDF::new_from_impl(ScalarUdf {
105        function,
106        placement,
107    })
108}
109
110#[cfg(test)]
111mod tests {
112    use std::sync::Arc;
113
114    use common_query::prelude::ScalarValue;
115    use datafusion::arrow::array::BooleanArray;
116    use datafusion_common::arrow::array::AsArray;
117    use datafusion_common::arrow::datatypes::DataType as ArrowDataType;
118    use datafusion_common::config::ConfigOptions;
119    use datatypes::arrow::datatypes::Field;
120    use datatypes::data_type::{ConcreteDataType, DataType};
121
122    use super::*;
123    use crate::function::Function;
124    use crate::scalars::test::TestAndFunction;
125
126    #[test]
127    fn test_create_udf() {
128        let f = Arc::new(TestAndFunction::default());
129
130        let args = ScalarFunctionArgs {
131            args: vec![
132                datafusion_expr::ColumnarValue::Array(Arc::new(BooleanArray::from(vec![
133                    true, true, true,
134                ]))),
135                datafusion_expr::ColumnarValue::Array(Arc::new(BooleanArray::from(vec![
136                    true, false, true,
137                ]))),
138            ],
139            arg_fields: vec![],
140            number_rows: 3,
141            return_field: Arc::new(Field::new("x", ArrowDataType::Boolean, true)),
142            config_options: Arc::new(Default::default()),
143        };
144
145        let result = f
146            .invoke_with_args(args)
147            .and_then(|x| x.to_array(3))
148            .unwrap();
149        let vector = result.as_boolean();
150        assert_eq!(3, vector.len());
151
152        assert!(vector.value(0));
153        assert!(!vector.value(1));
154        assert!(vector.value(2));
155
156        // create a udf and test it again
157        let udf = create_udf(f);
158
159        assert_eq!("test_and", udf.name());
160        assert_eq!(
161            ConcreteDataType::boolean_datatype(),
162            udf.return_type(&[])
163                .map(|x| ConcreteDataType::from_arrow_type(&x))
164                .unwrap()
165        );
166
167        let args = vec![
168            datafusion_expr::ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))),
169            datafusion_expr::ColumnarValue::Array(Arc::new(BooleanArray::from(vec![
170                true, false, false, true,
171            ]))),
172        ];
173
174        let arg_fields = vec![
175            Arc::new(Field::new("a", args[0].data_type(), false)),
176            Arc::new(Field::new("b", args[1].data_type(), false)),
177        ];
178        let return_field = Arc::new(Field::new(
179            "x",
180            ConcreteDataType::boolean_datatype().as_arrow_type(),
181            false,
182        ));
183        let args = ScalarFunctionArgs {
184            args,
185            arg_fields,
186            number_rows: 4,
187            return_field,
188            config_options: Arc::new(ConfigOptions::default()),
189        };
190        match udf.invoke_with_args(args).unwrap() {
191            datafusion_expr::ColumnarValue::Array(x) => {
192                let x = x.as_any().downcast_ref::<BooleanArray>().unwrap();
193                assert_eq!(x.len(), 4);
194                assert_eq!(
195                    x.iter().flatten().collect::<Vec<bool>>(),
196                    vec![true, false, false, true]
197                );
198            }
199            _ => unreachable!(),
200        }
201    }
202}