mz_expr/scalar/func/impls/
time.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::fmt;
11
12use chrono::{NaiveDateTime, NaiveTime, Offset, TimeZone, Timelike};
13use mz_expr_derive::sqlfunc;
14use mz_lowertest::MzReflect;
15use mz_pgtz::timezone::Timezone;
16use mz_repr::adt::datetime::{DateTimeField, DateTimeUnits};
17use mz_repr::adt::interval::Interval;
18use mz_repr::adt::numeric::{DecimalLike, Numeric};
19use mz_repr::adt::timestamp::TimeLike;
20use mz_repr::{SqlColumnType, SqlScalarType, strconv};
21use serde::{Deserialize, Serialize};
22
23use crate::EvalError;
24use crate::scalar::func::EagerUnaryFunc;
25
26#[sqlfunc(
27    sqlname = "time_to_text",
28    preserves_uniqueness = true,
29    inverse = to_unary!(super::CastStringToTime)
30)]
31fn cast_time_to_string(a: NaiveTime) -> String {
32    let mut buf = String::new();
33    strconv::format_time(&mut buf, a);
34    buf
35}
36
37#[sqlfunc(
38    sqlname = "time_to_interval",
39    preserves_uniqueness = true,
40    inverse = to_unary!(super::CastIntervalToTime)
41)]
42fn cast_time_to_interval(t: NaiveTime) -> Interval {
43    // wont overflow because value can't exceed 24 hrs + 1_000_000 ns = 86_400 seconds + 1_000_000 ns = 86_400_001_000 us
44    let micros: i64 = Interval::convert_date_time_unit(
45        DateTimeField::Second,
46        DateTimeField::Microseconds,
47        i64::from(t.num_seconds_from_midnight()),
48    )
49    .unwrap()
50        + i64::from(t.nanosecond()) / i64::from(Interval::NANOSECOND_PER_MICROSECOND);
51
52    Interval::new(0, 0, micros)
53}
54
55pub fn date_part_time_inner<D>(units: DateTimeUnits, time: NaiveTime) -> Result<D, EvalError>
56where
57    D: DecimalLike,
58{
59    match units {
60        DateTimeUnits::Epoch => Ok(time.extract_epoch()),
61        DateTimeUnits::Hour => Ok(D::from(time.hour())),
62        DateTimeUnits::Minute => Ok(D::from(time.minute())),
63        DateTimeUnits::Second => Ok(time.extract_second()),
64        DateTimeUnits::Milliseconds => Ok(time.extract_millisecond()),
65        DateTimeUnits::Microseconds => Ok(time.extract_microsecond()),
66        DateTimeUnits::Millennium
67        | DateTimeUnits::Century
68        | DateTimeUnits::Decade
69        | DateTimeUnits::Year
70        | DateTimeUnits::Quarter
71        | DateTimeUnits::Month
72        | DateTimeUnits::Week
73        | DateTimeUnits::Day
74        | DateTimeUnits::DayOfYear
75        | DateTimeUnits::DayOfWeek
76        | DateTimeUnits::IsoDayOfYear
77        | DateTimeUnits::IsoDayOfWeek => Err(EvalError::UnsupportedUnits(
78            format!("{}", units).into(),
79            "time".into(),
80        )),
81        DateTimeUnits::Timezone | DateTimeUnits::TimezoneHour | DateTimeUnits::TimezoneMinute => {
82            Err(EvalError::Unsupported {
83                feature: format!("'{}' timestamp units", units).into(),
84                discussion_no: None,
85            })
86        }
87    }
88}
89
90#[derive(Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect)]
91pub struct ExtractTime(pub DateTimeUnits);
92
93impl<'a> EagerUnaryFunc<'a> for ExtractTime {
94    type Input = NaiveTime;
95    type Output = Result<Numeric, EvalError>;
96
97    fn call(&self, a: NaiveTime) -> Result<Numeric, EvalError> {
98        date_part_time_inner(self.0, a)
99    }
100
101    fn output_type(&self, input: SqlColumnType) -> SqlColumnType {
102        SqlScalarType::Numeric { max_scale: None }.nullable(input.nullable)
103    }
104}
105
106impl fmt::Display for ExtractTime {
107    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108        write!(f, "extract_{}_t", self.0)
109    }
110}
111
112#[derive(Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect)]
113pub struct DatePartTime(pub DateTimeUnits);
114
115impl<'a> EagerUnaryFunc<'a> for DatePartTime {
116    type Input = NaiveTime;
117    type Output = Result<f64, EvalError>;
118
119    fn call(&self, a: NaiveTime) -> Result<f64, EvalError> {
120        date_part_time_inner(self.0, a)
121    }
122
123    fn output_type(&self, input: SqlColumnType) -> SqlColumnType {
124        SqlScalarType::Float64.nullable(input.nullable)
125    }
126}
127
128impl fmt::Display for DatePartTime {
129    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
130        write!(f, "date_part_{}_t", self.0)
131    }
132}
133
134/// Converts the time `t`, which is assumed to be in UTC, to the timezone `tz`.
135/// For example, `EST` and `17:39:14` would return `12:39:14`.
136pub fn timezone_time(tz: Timezone, t: NaiveTime, wall_time: &NaiveDateTime) -> NaiveTime {
137    let offset = match tz {
138        Timezone::FixedOffset(offset) => offset,
139        Timezone::Tz(tz) => tz.offset_from_utc_datetime(wall_time).fix(),
140    };
141    t + offset
142}
143
144#[derive(Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect)]
145pub struct TimezoneTime {
146    pub tz: Timezone,
147    pub wall_time: NaiveDateTime,
148}
149
150impl<'a> EagerUnaryFunc<'a> for TimezoneTime {
151    type Input = NaiveTime;
152    type Output = NaiveTime;
153
154    fn call(&self, a: NaiveTime) -> NaiveTime {
155        timezone_time(self.tz, a, &self.wall_time)
156    }
157
158    fn output_type(&self, input: SqlColumnType) -> SqlColumnType {
159        SqlScalarType::Time.nullable(input.nullable)
160    }
161}
162
163impl fmt::Display for TimezoneTime {
164    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165        write!(f, "timezone_{}_t", self.tz)
166    }
167}