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