common_query/
function.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::sync::Arc;
16
17use datafusion_expr::ReturnTypeFunction as DfReturnTypeFunction;
18use datatypes::arrow::datatypes::DataType as ArrowDataType;
19use datatypes::prelude::{ConcreteDataType, DataType};
20
21use crate::error::Result;
22use crate::logical_plan::Accumulator;
23
24/// A function's return type
25pub type ReturnTypeFunction =
26    Arc<dyn Fn(&[ConcreteDataType]) -> Result<Arc<ConcreteDataType>> + Send + Sync>;
27
28/// Accumulator creator that will be used by DataFusion
29pub type AccumulatorFunctionImpl = Arc<dyn Fn() -> Result<Box<dyn Accumulator>> + Send + Sync>;
30
31/// Create Accumulator with the data type of input columns.
32pub type AccumulatorCreatorFunction =
33    Arc<dyn Fn(&[ConcreteDataType]) -> Result<Box<dyn Accumulator>> + Sync + Send>;
34
35/// This signature corresponds to which types an aggregator serializes
36/// its state, given its return datatype.
37pub type StateTypeFunction =
38    Arc<dyn Fn(&ConcreteDataType) -> Result<Arc<Vec<ConcreteDataType>>> + Send + Sync>;
39
40pub fn to_df_return_type(func: ReturnTypeFunction) -> DfReturnTypeFunction {
41    let df_func = move |data_types: &[ArrowDataType]| {
42        // DataFusion DataType -> ConcreteDataType
43        let concrete_data_types = data_types
44            .iter()
45            .map(ConcreteDataType::from_arrow_type)
46            .collect::<Vec<_>>();
47
48        // evaluate ConcreteDataType
49        let eval_result = (func)(&concrete_data_types);
50
51        // ConcreteDataType -> DataFusion DataType
52        eval_result
53            .map(|t| Arc::new(t.as_arrow_type()))
54            .map_err(|e| e.into())
55    };
56    Arc::new(df_func)
57}