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
// 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 chrono::NaiveTime;
use num::traits::CheckedNeg;

use crate::EvalError;
use mz_repr::adt::interval::Interval;
use mz_repr::strconv;

sqlfunc!(
    #[sqlname = "interval_to_text"]
    #[preserves_uniqueness = true]
    #[inverse = to_unary!(super::CastStringToInterval)]
    fn cast_interval_to_string(a: Interval) -> String {
        let mut buf = String::new();
        strconv::format_interval(&mut buf, a);
        buf
    }
);

sqlfunc!(
    #[sqlname = "interval_to_time"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(super::CastTimeToInterval)]
    fn cast_interval_to_time(mut i: Interval) -> NaiveTime {
        // Negative durations have their HH::MM::SS.NS values subtracted from 1 day.
        if i.is_negative() {
            i = Interval::new(0, 0, 86_400_000_000)
                .checked_add(&i.as_time_interval())
                .unwrap();
        }

        // TODO(benesch): remove potentially dangerous usage of `as`.
        #[allow(clippy::as_conversions)]
        NaiveTime::from_hms_nano_opt(
            i.hours() as u32,
            i.minutes() as u32,
            i.seconds::<f64>() as u32,
            i.nanoseconds() as u32,
        )
        .unwrap()
    }
);

sqlfunc!(
    #[sqlname = "-"]
    #[preserves_uniqueness = true]
    #[inverse = to_unary!(super::NegInterval)]
    fn neg_interval(i: Interval) -> Result<Interval, EvalError> {
        i.checked_neg().ok_or(EvalError::IntervalOutOfRange)
    }
);

sqlfunc!(
    #[sqlname = "justify_days"]
    fn justify_days(i: Interval) -> Result<Interval, EvalError> {
        i.justify_days().map_err(|_| EvalError::IntervalOutOfRange)
    }
);

sqlfunc!(
    #[sqlname = "justify_hours"]
    fn justify_hours(i: Interval) -> Result<Interval, EvalError> {
        i.justify_hours().map_err(|_| EvalError::IntervalOutOfRange)
    }
);

sqlfunc!(
    #[sqlname = "justify_interval"]
    fn justify_interval(i: Interval) -> Result<Interval, EvalError> {
        i.justify_interval()
            .map_err(|_| EvalError::IntervalOutOfRange)
    }
);