1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::fmt;

use chrono::{NaiveDateTime, NaiveTime, Offset, TimeZone, Timelike};
use mz_lowertest::MzReflect;
use mz_pgtz::timezone::Timezone;
use mz_repr::adt::datetime::{DateTimeField, DateTimeUnits};
use mz_repr::adt::interval::Interval;
use mz_repr::adt::numeric::{DecimalLike, Numeric};
use mz_repr::adt::timestamp::TimeLike;
use mz_repr::{strconv, ColumnType, ScalarType};
use proptest_derive::Arbitrary;
use serde::{Deserialize, Serialize};

use crate::scalar::func::EagerUnaryFunc;
use crate::EvalError;

sqlfunc!(
    #[sqlname = "time_to_text"]
    #[preserves_uniqueness = true]
    #[inverse = to_unary!(super::CastStringToTime)]
    fn cast_time_to_string(a: NaiveTime) -> String {
        let mut buf = String::new();
        strconv::format_time(&mut buf, a);
        buf
    }
);

sqlfunc!(
    #[sqlname = "time_to_interval"]
    #[preserves_uniqueness = true]
    #[inverse = to_unary!(super::CastIntervalToTime)]
    fn cast_time_to_interval<'a>(t: NaiveTime) -> Interval {
        // 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
        let micros: i64 = Interval::convert_date_time_unit(
            DateTimeField::Second,
            DateTimeField::Microseconds,
            i64::from(t.num_seconds_from_midnight()),
        )
        .unwrap()
            + i64::from(t.nanosecond()) / i64::from(Interval::NANOSECOND_PER_MICROSECOND);

        Interval::new(0, 0, micros)
    }
);

pub fn date_part_time_inner<D>(units: DateTimeUnits, time: NaiveTime) -> Result<D, EvalError>
where
    D: DecimalLike,
{
    match units {
        DateTimeUnits::Epoch => Ok(time.extract_epoch()),
        DateTimeUnits::Hour => Ok(D::from(time.hour())),
        DateTimeUnits::Minute => Ok(D::from(time.minute())),
        DateTimeUnits::Second => Ok(time.extract_second()),
        DateTimeUnits::Milliseconds => Ok(time.extract_millisecond()),
        DateTimeUnits::Microseconds => Ok(time.extract_microsecond()),
        DateTimeUnits::Millennium
        | DateTimeUnits::Century
        | DateTimeUnits::Decade
        | DateTimeUnits::Year
        | DateTimeUnits::Quarter
        | DateTimeUnits::Month
        | DateTimeUnits::Week
        | DateTimeUnits::Day
        | DateTimeUnits::DayOfYear
        | DateTimeUnits::DayOfWeek
        | DateTimeUnits::IsoDayOfYear
        | DateTimeUnits::IsoDayOfWeek => Err(EvalError::UnsupportedUnits(
            format!("{}", units),
            "time".to_string(),
        )),
        DateTimeUnits::Timezone | DateTimeUnits::TimezoneHour | DateTimeUnits::TimezoneMinute => {
            Err(EvalError::Unsupported {
                feature: format!("'{}' timestamp units", units),
                issue_no: None,
            })
        }
    }
}

#[derive(
    Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect,
)]
pub struct ExtractTime(pub DateTimeUnits);

impl<'a> EagerUnaryFunc<'a> for ExtractTime {
    type Input = NaiveTime;
    type Output = Result<Numeric, EvalError>;

    fn call(&self, a: NaiveTime) -> Result<Numeric, EvalError> {
        date_part_time_inner(self.0, a)
    }

    fn output_type(&self, input: ColumnType) -> ColumnType {
        ScalarType::Numeric { max_scale: None }.nullable(input.nullable)
    }
}

impl fmt::Display for ExtractTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "extract_{}_t", self.0)
    }
}

#[derive(
    Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect,
)]
pub struct DatePartTime(pub DateTimeUnits);

impl<'a> EagerUnaryFunc<'a> for DatePartTime {
    type Input = NaiveTime;
    type Output = Result<f64, EvalError>;

    fn call(&self, a: NaiveTime) -> Result<f64, EvalError> {
        date_part_time_inner(self.0, a)
    }

    fn output_type(&self, input: ColumnType) -> ColumnType {
        ScalarType::Float64.nullable(input.nullable)
    }
}

impl fmt::Display for DatePartTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "date_part_{}_t", self.0)
    }
}

/// Converts the time `t`, which is assumed to be in UTC, to the timezone `tz`.
/// For example, `EST` and `17:39:14` would return `12:39:14`.
pub fn timezone_time(tz: Timezone, t: NaiveTime, wall_time: &NaiveDateTime) -> NaiveTime {
    let offset = match tz {
        Timezone::FixedOffset(offset) => offset,
        Timezone::Tz(tz) => tz.offset_from_utc_datetime(wall_time).fix(),
    };
    t + offset
}

#[derive(
    Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect,
)]
pub struct TimezoneTime {
    pub tz: Timezone,
    #[proptest(strategy = "crate::func::any_naive_datetime()")]
    pub wall_time: NaiveDateTime,
}

impl<'a> EagerUnaryFunc<'a> for TimezoneTime {
    type Input = NaiveTime;
    type Output = NaiveTime;

    fn call(&self, a: NaiveTime) -> NaiveTime {
        timezone_time(self.tz, a, &self.wall_time)
    }

    fn output_type(&self, input: ColumnType) -> ColumnType {
        ScalarType::Time.nullable(input.nullable)
    }
}

impl fmt::Display for TimezoneTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "timezone_{}_t", self.tz)
    }
}