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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//LICENSE Portions Copyright 2019-2021 ZomboDB, LLC.
//LICENSE
//LICENSE Portions Copyright 2021-2023 Technology Concepts & Design, Inc.
//LICENSE
//LICENSE Portions Copyright 2023-2023 PgCentral Foundation, Inc. <contact@pgcentral.org>
//LICENSE
//LICENSE All rights reserved.
//LICENSE
//LICENSE Use of this source code is governed by the MIT license that can be found in the LICENSE file.
use crate::datum::datetime_support::IntervalConversionError;
use crate::{direct_function_call, pg_sys, DateTimeParts, FromDatum, IntoDatum, Time, ToIsoString};
use pgrx_sql_entity_graph::metadata::{
    ArgumentError, Returns, ReturnsError, SqlMapping, SqlTranslatable,
};

pub const USECS_PER_SEC: i64 = 1_000_000;
pub const USECS_PER_DAY: i64 = pg_sys::SECS_PER_DAY as i64 * USECS_PER_SEC;

/// From the PG docs  https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-INTERVAL-INPUT
/// Internally interval values are stored as months, days, and microseconds. This is done because the number of days in a month varies,
/// and a day can have 23 or 25hours if a daylight savings time adjustment is involved. The months and days fields are integers while
/// the microseconds field can store fractional seconds. Because intervals are usually created from constant strings or timestamp
/// subtraction, this storage method works well in most cases...
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct Interval(pg_sys::Interval);

impl Interval {
    /// This function takes `months`/`days`/`microseconds` as input to convert directly to the internal PG storage struct `pg_sys::Interval`
    /// - the sign of all units must be all matching in the positive or all matching in the negative direction
    pub fn new(months: i32, days: i32, micros: i64) -> Result<Self, IntervalConversionError> {
        if months < 0 {
            if days > 0 || micros > 0 {
                return Err(IntervalConversionError::MismatchedSigns);
            }
        } else if months > 0 {
            if days < 0 || micros < 0 {
                return Err(IntervalConversionError::MismatchedSigns);
            }
        }

        Ok(Interval(pg_sys::Interval { time: micros, day: days, month: months }))
    }

    pub fn from_years(years: i32) -> Self {
        Self::from(Some(years), None, None, None, None, None, None).unwrap()
    }

    pub fn from_months(months: i32) -> Self {
        Self::from(None, Some(months), None, None, None, None, None).unwrap()
    }

    pub fn from_weeks(weeks: i32) -> Self {
        Self::from(None, None, Some(weeks), None, None, None, None).unwrap()
    }

    pub fn from_days(days: i32) -> Self {
        Self::from(None, None, None, Some(days), None, None, None).unwrap()
    }

    pub fn from_hours(hours: i32) -> Self {
        Self::from(None, None, None, None, Some(hours), None, None).unwrap()
    }

    pub fn from_minutes(minutes: i32) -> Self {
        Self::from(None, None, None, None, None, Some(minutes), None).unwrap()
    }

    pub fn from_seconds(seconds: f64) -> Self {
        Self::from(None, None, None, None, None, None, Some(seconds)).unwrap()
    }

    pub fn from_micros(microseconds: i64) -> Self {
        Self::from_seconds(microseconds as f64 / 1_000_000.0)
    }

    pub fn from(
        years: Option<i32>,
        months: Option<i32>,
        weeks: Option<i32>,
        days: Option<i32>,
        hours: Option<i32>,
        minutes: Option<i32>,
        seconds: Option<f64>,
    ) -> Result<Self, IntervalConversionError> {
        match (years.unwrap_or_default() <= 0
            && months.unwrap_or_default() <= 0
            && weeks.unwrap_or_default() <= 0
            && days.unwrap_or_default() <= 0
            && hours.unwrap_or_default() <= 0
            && minutes.unwrap_or_default() <= 0
            && seconds.unwrap_or_default().is_sign_negative())
            || (years.unwrap_or_default() >= 0
                && months.unwrap_or_default() >= 0
                && weeks.unwrap_or_default() >= 0
                && days.unwrap_or_default() >= 0
                && hours.unwrap_or_default() >= 0
                && minutes.unwrap_or_default() >= 0
                && seconds.unwrap_or_default().is_sign_positive())
        {
            true => unsafe {
                Ok(direct_function_call(
                    pg_sys::make_interval,
                    &[
                        years.into_datum(),
                        months.into_datum(),
                        weeks.into_datum(),
                        days.into_datum(),
                        hours.into_datum(),
                        minutes.into_datum(),
                        seconds.into_datum(),
                    ],
                )
                .unwrap())
            },
            false => Err(IntervalConversionError::MismatchedSigns),
        }
    }

    /// Total number of months before/after 2000-01-01
    #[inline]
    pub fn months(&self) -> i32 {
        self.0.month
    }

    /// Total number of days before/after the `months()` offset (sign must match `months`)
    #[inline]
    pub fn days(&self) -> i32 {
        self.0.day
    }

    /// Total number of microseconds before/after the `days()` offset (sign must match `months`/`days`)
    #[inline]
    pub fn micros(&self) -> i64 {
        self.0.time
    }

    #[inline]
    pub fn as_micros(&self) -> i128 {
        self.micros() as i128
            + self.months() as i128 * pg_sys::DAYS_PER_MONTH as i128 * USECS_PER_DAY as i128
            + self.days() as i128 * USECS_PER_DAY as i128
    }

    #[inline]
    pub fn abs(self) -> Self {
        Interval(pg_sys::Interval {
            time: self.0.time.abs(),
            day: self.0.day.abs(),
            month: self.0.month.abs(),
        })
    }

    #[inline]
    pub fn signum(self) -> Self {
        if self.0.month == 0 && self.0.day == 0 && self.0.time == 0 {
            Interval(pg_sys::Interval { time: 0, day: 0, month: 0 })
        } else if self.is_positive() {
            Interval(pg_sys::Interval { time: 1, day: 0, month: 0 })
        } else {
            Interval(pg_sys::Interval { time: -1, day: 0, month: 0 })
        }
    }

    #[inline]
    pub fn is_positive(self) -> bool {
        !self.is_negative()
    }

    #[inline]
    pub fn is_negative(self) -> bool {
        self.0.month < 0 || self.0.day < 0 || self.0.time < 0
    }

    /// Postgres defines intervals as bounded
    #[deprecated(since = "0.10.0", note = "consider using `true`")]
    pub fn is_finite(&self) -> bool {
        // Yes, really.
        true
    }

    /// Truncate [`Interval`] to specified units
    pub fn truncate(self, units: DateTimeParts) -> Self {
        unsafe {
            direct_function_call(pg_sys::interval_trunc, &[units.into_datum(), self.into_datum()])
                .unwrap()
        }
    }

    /// Promote groups of 30 days to numbers of months
    pub fn justify_days(self) -> Self {
        unsafe {
            direct_function_call(pg_sys::interval_justify_days, &[self.into_datum()]).unwrap()
        }
    }

    /// Promote groups of 24 hours to numbers of days
    pub fn justify_hours(self) -> Self {
        unsafe {
            direct_function_call(pg_sys::interval_justify_hours, &[self.into_datum()]).unwrap()
        }
    }

    /// Promote groups of 24 hours to numbers of days and promote groups of 30 days to numbers of months
    pub fn justify(self) -> Self {
        unsafe {
            direct_function_call(pg_sys::interval_justify_interval, &[self.into_datum()]).unwrap()
        }
    }

    #[inline]
    pub(crate) unsafe fn as_datum(&self) -> Option<pg_sys::Datum> {
        Some(pg_sys::Datum::from(&self.0 as *const _))
    }

    /// Return the backing [`pg_sys::Interval`] value.
    #[inline]
    pub fn into_inner(self) -> pg_sys::Interval {
        self.0
    }
}

impl FromDatum for Interval {
    unsafe fn from_polymorphic_datum(
        datum: pg_sys::Datum,
        is_null: bool,
        _typoid: pg_sys::Oid,
    ) -> Option<Self>
    where
        Self: Sized,
    {
        if is_null {
            None
        } else {
            let ptr = datum.cast_mut_ptr::<pg_sys::Interval>();
            // SAFETY:  Caller asserted the datum points to a pg_sys::Interval
            Some(Interval(ptr.read()))
        }
    }
}

impl IntoDatum for Interval {
    fn into_datum(self) -> Option<pg_sys::Datum> {
        unsafe {
            let ptr =
                pg_sys::palloc(std::mem::size_of::<pg_sys::Interval>()).cast::<pg_sys::Interval>();
            ptr.write(self.0);
            Some(pg_sys::Datum::from(ptr))
        }
    }
    fn type_oid() -> pg_sys::Oid {
        pg_sys::INTERVALOID
    }
}

impl TryFrom<std::time::Duration> for Interval {
    type Error = IntervalConversionError;
    fn try_from(duration: std::time::Duration) -> Result<Interval, Self::Error> {
        let microseconds = duration.as_micros();
        let seconds = microseconds / USECS_PER_SEC as u128;
        let days = seconds / pg_sys::SECS_PER_DAY as u128;
        let months = days / pg_sys::DAYS_PER_MONTH as u128;
        let leftover_days = days - months * pg_sys::DAYS_PER_MONTH as u128;
        let leftover_microseconds = microseconds
            - (leftover_days * USECS_PER_DAY as u128
                + (months * pg_sys::DAYS_PER_MONTH as u128 * USECS_PER_DAY as u128));

        Interval::new(
            months.try_into().map_err(|_| IntervalConversionError::DurationMonthsOutOfBounds)?,
            leftover_days.try_into().expect("bad math during Duration to Interval days"),
            leftover_microseconds.try_into().expect("bad math during Duration to Interval micros"),
        )
    }
}

impl From<Time> for Interval {
    fn from(value: Time) -> Self {
        unsafe { direct_function_call(pg_sys::time_interval, &[value.into_datum()]).unwrap() }
    }
}

impl TryFrom<Interval> for std::time::Duration {
    type Error = IntervalConversionError;

    fn try_from(interval: Interval) -> Result<Self, Self::Error> {
        if interval.0.time < 0 || interval.0.month < 0 || interval.0.day < 0 {
            return Err(IntervalConversionError::NegativeInterval);
        }

        let micros = interval.0.time as u128
            + interval.0.day as u128 * pg_sys::SECS_PER_DAY as u128 * USECS_PER_SEC as u128
            + interval.0.month as u128 * pg_sys::DAYS_PER_MONTH as u128 * USECS_PER_DAY as u128;

        Ok(std::time::Duration::from_micros(
            micros.try_into().map_err(|_| IntervalConversionError::IntervalTooLarge)?,
        ))
    }
}

impl serde::Serialize for Interval {
    fn serialize<S>(
        &self,
        serializer: S,
    ) -> std::result::Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
    where
        S: serde::Serializer,
    {
        serializer
            .serialize_str(&self.to_iso_string())
            .map_err(|e| serde::ser::Error::custom(format!("formatting problem: {:?}", e)))
    }
}

impl<'de> serde::Deserialize<'de> for Interval {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        deserializer.deserialize_str(crate::DateTimeTypeVisitor::<Self>::new())
    }
}
unsafe impl SqlTranslatable for Interval {
    fn argument_sql() -> Result<SqlMapping, ArgumentError> {
        Ok(SqlMapping::literal("interval"))
    }
    fn return_sql() -> Result<Returns, ReturnsError> {
        Ok(Returns::One(SqlMapping::literal("interval")))
    }
}