Skip to main content

datafusion_functions/datetime/
from_unixtime.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use arrow::datatypes::DataType::{Int64, Timestamp, Utf8};
21use arrow::datatypes::TimeUnit::Second;
22use arrow::datatypes::{DataType, Field, FieldRef};
23use datafusion_common::{Result, ScalarValue, exec_err, internal_err};
24use datafusion_expr::TypeSignature::Exact;
25use datafusion_expr::{
26    ColumnarValue, Documentation, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl,
27    Signature, Volatility,
28};
29use datafusion_macros::user_doc;
30
31#[user_doc(
32    doc_section(label = "Time and Date Functions"),
33    description = "Converts an integer to RFC3339 timestamp format (`YYYY-MM-DDT00:00:00.000000000Z`). Integers and unsigned integers are interpreted as seconds since the unix epoch (`1970-01-01T00:00:00Z`) return the corresponding timestamp.",
34    syntax_example = "from_unixtime(expression[, timezone])",
35    sql_example = r#"```sql
36> select from_unixtime(1599572549, 'America/New_York');
37+-----------------------------------------------------------+
38| from_unixtime(Int64(1599572549),Utf8("America/New_York")) |
39+-----------------------------------------------------------+
40| 2020-09-08T09:42:29-04:00                                 |
41+-----------------------------------------------------------+
42```"#,
43    standard_argument(name = "expression",),
44    argument(
45        name = "timezone",
46        description = "Optional timezone to use when converting the integer to a timestamp. If not provided, the default timezone is UTC."
47    )
48)]
49#[derive(Debug, PartialEq, Eq, Hash)]
50pub struct FromUnixtimeFunc {
51    signature: Signature,
52}
53
54impl Default for FromUnixtimeFunc {
55    fn default() -> Self {
56        Self::new()
57    }
58}
59
60impl FromUnixtimeFunc {
61    pub fn new() -> Self {
62        Self {
63            signature: Signature::one_of(
64                vec![Exact(vec![Int64, Utf8]), Exact(vec![Int64])],
65                Volatility::Immutable,
66            ),
67        }
68    }
69}
70
71impl ScalarUDFImpl for FromUnixtimeFunc {
72    fn name(&self) -> &str {
73        "from_unixtime"
74    }
75
76    fn signature(&self) -> &Signature {
77        &self.signature
78    }
79
80    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
81        // Length check handled in the signature
82        debug_assert!(matches!(args.scalar_arguments.len(), 1 | 2));
83
84        if args.scalar_arguments.len() == 1 {
85            Ok(Field::new(self.name(), Timestamp(Second, None), true).into())
86        } else {
87            args.scalar_arguments[1]
88                .and_then(|sv| {
89                    sv.try_as_str()
90                        .flatten()
91                        .filter(|s| !s.is_empty())
92                        .map(|tz| {
93                            Field::new(
94                                self.name(),
95                                Timestamp(Second, Some(Arc::from(tz.to_string()))),
96                                true,
97                            )
98                        })
99                })
100                .map(Arc::new)
101                .map_or_else(
102                    || {
103                        exec_err!(
104                            "{} requires its second argument to be a constant string",
105                            self.name()
106                        )
107                    },
108                    Ok,
109                )
110        }
111    }
112
113    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
114        internal_err!("call return_field_from_args instead")
115    }
116
117    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
118        let args = args.args;
119        let len = args.len();
120        if len != 1 && len != 2 {
121            return exec_err!(
122                "from_unixtime function requires 1 or 2 argument, got {}",
123                args.len()
124            );
125        }
126
127        if args[0].data_type() != Int64 {
128            return exec_err!(
129                "Unsupported data type {} for function from_unixtime",
130                args[0].data_type()
131            );
132        }
133
134        match len {
135            1 => args[0].cast_to(&Timestamp(Second, None), None),
136            2 => match &args[1] {
137                ColumnarValue::Scalar(ScalarValue::Utf8(Some(tz))) => args[0]
138                    .cast_to(&Timestamp(Second, Some(Arc::from(tz.to_string()))), None),
139                _ => {
140                    exec_err!(
141                        "Unsupported data type {} for function from_unixtime",
142                        args[1].data_type()
143                    )
144                }
145            },
146            _ => unreachable!(),
147        }
148    }
149
150    fn documentation(&self) -> Option<&Documentation> {
151        self.doc()
152    }
153}
154
155#[cfg(test)]
156mod test {
157    use crate::datetime::from_unixtime::FromUnixtimeFunc;
158    use arrow::datatypes::TimeUnit::Second;
159    use arrow::datatypes::{DataType, Field};
160    use datafusion_common::ScalarValue;
161    use datafusion_common::ScalarValue::Int64;
162    use datafusion_common::config::ConfigOptions;
163    use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
164    use std::sync::Arc;
165
166    #[test]
167    fn test_without_timezone() {
168        let arg_field = Arc::new(Field::new("a", DataType::Int64, true));
169        let args = ScalarFunctionArgs {
170            args: vec![ColumnarValue::Scalar(Int64(Some(1729900800)))],
171            arg_fields: vec![arg_field],
172            number_rows: 1,
173            return_field: Field::new("f", DataType::Timestamp(Second, None), true).into(),
174            config_options: Arc::new(ConfigOptions::default()),
175        };
176        let result = FromUnixtimeFunc::new().invoke_with_args(args).unwrap();
177
178        match result {
179            ColumnarValue::Scalar(ScalarValue::TimestampSecond(Some(sec), None)) => {
180                assert_eq!(sec, 1729900800);
181            }
182            _ => panic!("Expected scalar value"),
183        }
184    }
185
186    #[test]
187    fn test_with_timezone() {
188        let arg_fields = vec![
189            Field::new("a", DataType::Int64, true).into(),
190            Field::new("a", DataType::Utf8, true).into(),
191        ];
192        let args = ScalarFunctionArgs {
193            args: vec![
194                ColumnarValue::Scalar(Int64(Some(1729900800))),
195                ColumnarValue::Scalar(ScalarValue::Utf8(Some(
196                    "America/New_York".to_string(),
197                ))),
198            ],
199            arg_fields,
200            number_rows: 2,
201            return_field: Field::new(
202                "f",
203                DataType::Timestamp(Second, Some(Arc::from("America/New_York"))),
204                true,
205            )
206            .into(),
207            config_options: Arc::new(ConfigOptions::default()),
208        };
209        let result = FromUnixtimeFunc::new().invoke_with_args(args).unwrap();
210
211        match result {
212            ColumnarValue::Scalar(ScalarValue::TimestampSecond(Some(sec), Some(tz))) => {
213                assert_eq!(sec, 1729900800);
214                assert_eq!(tz.to_string(), "America/New_York");
215            }
216            _ => panic!("Expected scalar value"),
217        }
218    }
219}