common_function/system/
timezone.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::{self};
16use std::sync::Arc;
17
18use common_query::error::Result;
19use common_query::prelude::{Signature, Volatility};
20use datatypes::prelude::{ConcreteDataType, ScalarVector};
21use datatypes::vectors::{StringVector, VectorRef};
22
23use crate::function::{Function, FunctionContext};
24
25/// A function to return current session timezone.
26#[derive(Clone, Debug, Default)]
27pub struct TimezoneFunction;
28
29const NAME: &str = "timezone";
30
31impl Function for TimezoneFunction {
32    fn name(&self) -> &str {
33        NAME
34    }
35
36    fn return_type(&self, _input_types: &[ConcreteDataType]) -> Result<ConcreteDataType> {
37        Ok(ConcreteDataType::string_datatype())
38    }
39
40    fn signature(&self) -> Signature {
41        Signature::nullary(Volatility::Immutable)
42    }
43
44    fn eval(&self, func_ctx: &FunctionContext, _columns: &[VectorRef]) -> Result<VectorRef> {
45        let tz = func_ctx.query_ctx.timezone().to_string();
46
47        Ok(Arc::new(StringVector::from_slice(&[&tz])) as _)
48    }
49}
50
51impl fmt::Display for TimezoneFunction {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        write!(f, "TIMEZONE")
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use std::sync::Arc;
60
61    use session::context::QueryContextBuilder;
62
63    use super::*;
64    #[test]
65    fn test_build_function() {
66        let build = TimezoneFunction;
67        assert_eq!("timezone", build.name());
68        assert_eq!(
69            ConcreteDataType::string_datatype(),
70            build.return_type(&[]).unwrap()
71        );
72        assert_eq!(build.signature(), Signature::nullary(Volatility::Immutable));
73
74        let query_ctx = QueryContextBuilder::default().build().into();
75
76        let func_ctx = FunctionContext {
77            query_ctx,
78            ..Default::default()
79        };
80        let vector = build.eval(&func_ctx, &[]).unwrap();
81        let expect: VectorRef = Arc::new(StringVector::from(vec!["UTC"]));
82        assert_eq!(expect, vector);
83    }
84}