common_function/
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::fmt;
16use std::sync::Arc;
17
18use common_query::error::Result;
19use common_query::prelude::Signature;
20use datatypes::data_type::ConcreteDataType;
21use datatypes::vectors::VectorRef;
22use session::context::{QueryContextBuilder, QueryContextRef};
23
24use crate::state::FunctionState;
25
26/// The function execution context
27#[derive(Clone)]
28pub struct FunctionContext {
29    pub query_ctx: QueryContextRef,
30    pub state: Arc<FunctionState>,
31}
32
33impl FunctionContext {
34    /// Create a mock [`FunctionContext`] for test.
35    #[cfg(any(test, feature = "testing"))]
36    pub fn mock() -> Self {
37        Self {
38            query_ctx: QueryContextBuilder::default().build().into(),
39            state: Arc::new(FunctionState::mock()),
40        }
41    }
42}
43
44impl std::fmt::Display for FunctionContext {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(f, "FunctionContext {{ query_ctx: {} }}", self.query_ctx)
47    }
48}
49
50impl Default for FunctionContext {
51    fn default() -> Self {
52        Self {
53            query_ctx: QueryContextBuilder::default().build().into(),
54            state: Arc::new(FunctionState::default()),
55        }
56    }
57}
58
59/// Scalar function trait, modified from databend to adapt datafusion
60/// TODO(dennis): optimize function by it's features such as monotonicity etc.
61pub trait Function: fmt::Display + Sync + Send {
62    /// Returns the name of the function, should be unique.
63    fn name(&self) -> &str;
64
65    /// The returned data type of function execution.
66    fn return_type(&self, input_types: &[ConcreteDataType]) -> Result<ConcreteDataType>;
67
68    /// The signature of function.
69    fn signature(&self) -> Signature;
70
71    /// Evaluate the function, e.g. run/execute the function.
72    fn eval(&self, ctx: &FunctionContext, columns: &[VectorRef]) -> Result<VectorRef>;
73}
74
75pub type FunctionRef = Arc<dyn Function>;