Skip to main content

sql_values/interval/
arithmetic.rs

1//! PostgreSQL 18's arithmetic on intervals, ported from `timestamp.c` and `date.c` with
2//! PostgreSQL's order of checks.
3
4use core::cmp::Ordering;
5
6use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
7
8use super::{
9    IntervalError, PgInterval,
10    float::{
11        fits_in_i32, fits_in_i64, int_to_f64, round_ties_even, truncate_to_i32, truncate_to_i64,
12        ts_round,
13    },
14};
15
16const DAYS_PER_MONTH: f64 = 30.0;
17const SECS_PER_DAY: f64 = 86_400.0;
18const MONTHS_PER_YEAR: i32 = 12;
19const USECS_PER_DAY: i64 = 86_400_000_000;
20const USECS_PER_SEC: i64 = 1_000_000;
21
22/// `POSTGRES_EPOCH_JDATE`, the Julian day of 2000-01-01.
23const POSTGRES_EPOCH_JDATE: i64 = 2_451_545;
24/// The Julian day of 0001-01-01 less one, as `chrono` counts that day as day 1 of the era.
25const JULIAN_BEFORE_CE: i64 = 1_721_425;
26/// `MIN_TIMESTAMP`, 4714-11-24 BC.
27const MIN_TIMESTAMP: i64 = -211_813_488_000_000_000;
28/// `END_TIMESTAMP`, 294277-01-01, past the last timestamp.
29const END_TIMESTAMP: i64 = 9_223_371_331_200_000_000;
30
31/// Why a timestamp or time shifted by an interval has no value here.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
33pub enum ShiftError {
34    /// The timestamp lies outside PostgreSQL's, or the shift leaves them.
35    #[error("timestamp out of range")]
36    TimestampOutOfRange,
37    /// The interval `timestamp - interval` negates has a field at its minimum.
38    #[error("interval out of range")]
39    IntervalOutOfRange,
40    /// `time + interval` of an infinite interval.
41    #[error("cannot add infinite interval to time")]
42    InfiniteIntervalAddedToTime,
43    /// `time - interval` of an infinite interval.
44    #[error("cannot subtract infinite interval from time")]
45    InfiniteIntervalSubtractedFromTime,
46    /// PostgreSQL answers a timestamp `chrono` cannot hold, `infinity`, `-infinity` or one past
47    /// `chrono`'s last year.
48    #[error("timestamp beyond chrono")]
49    Unrepresentable,
50}
51
52impl PgInterval {
53    /// `Greater` for `infinity`, `Less` for `-infinity`, `None` when finite.
54    const fn infinity(&self) -> Option<Ordering> {
55        if self.fields_equal(&Self::INFINITY) {
56            Some(Ordering::Greater)
57        } else if self.fields_equal(&Self::NEG_INFINITY) {
58            Some(Ordering::Less)
59        } else {
60            None
61        }
62    }
63
64    /// `self` unless its fields spell an infinity, which a finite result may not.
65    const fn finite(self) -> Result<Self, IntervalError> {
66        if self.is_finite() {
67            Ok(self)
68        } else {
69            Err(IntervalError::OutOfRange)
70        }
71    }
72
73    /// The infinity on the side `sign` names.
74    const fn infinite(sign: Ordering) -> Self {
75        match sign {
76            Ordering::Less => Self::NEG_INFINITY,
77            _ => Self::INFINITY,
78        }
79    }
80
81    /// PostgreSQL's `interval_pl`, `self + other`.
82    ///
83    /// # Errors
84    ///
85    /// [`IntervalError::OutOfRange`] where a field overflows, the sum spells an infinity, or
86    /// opposite infinities meet.
87    ///
88    /// ```
89    /// use sql_values::{IntervalError, PgInterval, parse_interval};
90    ///
91    /// let day = parse_interval("1 day").unwrap();
92    /// let hour = parse_interval("-01:00:00").unwrap();
93    /// assert_eq!(day.checked_add(hour).unwrap().to_string(), "1 day -01:00:00");
94    /// assert_eq!(
95    ///     PgInterval::INFINITY.checked_add(PgInterval::NEG_INFINITY),
96    ///     Err(IntervalError::OutOfRange),
97    /// );
98    /// ```
99    pub fn checked_add(self, other: Self) -> Result<Self, IntervalError> {
100        match (self.infinity(), other.infinity()) {
101            (Some(left), Some(right)) if left != right => Err(IntervalError::OutOfRange),
102            (Some(_), _) => Ok(self),
103            (None, Some(_)) => Ok(other),
104            (None, None) => Self::finite_fields(FieldResults {
105                months: self.months.checked_add(other.months),
106                days: self.days.checked_add(other.days),
107                microseconds: self.microseconds.checked_add(other.microseconds),
108            }),
109        }
110    }
111
112    /// PostgreSQL's `interval_mi`, `self - other`.
113    ///
114    /// # Errors
115    ///
116    /// [`IntervalError::OutOfRange`] where a field overflows, the difference spells an infinity,
117    /// or like infinities meet.
118    pub fn checked_sub(self, other: Self) -> Result<Self, IntervalError> {
119        match (self.infinity(), other.infinity()) {
120            (Some(left), Some(right)) if left == right => Err(IntervalError::OutOfRange),
121            (Some(_), _) => Ok(self),
122            (None, Some(right)) => Ok(Self::infinite(right.reverse())),
123            (None, None) => Self::finite_fields(FieldResults {
124                months: self.months.checked_sub(other.months),
125                days: self.days.checked_sub(other.days),
126                microseconds: self.microseconds.checked_sub(other.microseconds),
127            }),
128        }
129    }
130
131    /// PostgreSQL's `interval_um`, `-self`.
132    ///
133    /// # Errors
134    ///
135    /// [`IntervalError::OutOfRange`] where a field sits at its minimum, or the negation spells an
136    /// infinity.
137    ///
138    /// ```
139    /// use sql_values::{IntervalError, parse_interval};
140    ///
141    /// let span = parse_interval("1 mon -2 days").unwrap();
142    /// assert_eq!(span.checked_neg().unwrap().to_string(), "-1 mons +2 days");
143    /// let minimum = parse_interval("-2147483648 days").unwrap();
144    /// assert_eq!(minimum.checked_neg(), Err(IntervalError::OutOfRange));
145    /// ```
146    pub fn checked_neg(self) -> Result<Self, IntervalError> {
147        match self.infinity() {
148            Some(sign) => Ok(Self::infinite(sign.reverse())),
149            None => Self::finite_fields(FieldResults {
150                months: self.months.checked_neg(),
151                days: self.days.checked_neg(),
152                microseconds: self.microseconds.checked_neg(),
153            }),
154        }
155    }
156
157    /// PostgreSQL's `interval_mul`, `self * factor`.
158    ///
159    /// Months and days scale apart, what a month leaves over cascades into days as 30 and what a
160    /// day leaves over into the clock as 24 hours, each rounded to the microsecond as PostgreSQL
161    /// rounds it.
162    ///
163    /// # Errors
164    ///
165    /// [`IntervalError::OutOfRange`] for a `NaN` factor, zero against an infinity, an infinite
166    /// factor against a zero interval, and a product beyond the type.
167    ///
168    /// ```
169    /// use sql_values::{IntervalError, PgInterval, parse_interval};
170    ///
171    /// let month = parse_interval("1 mon 1 day").unwrap();
172    /// assert_eq!(month.checked_mul(1.5).unwrap().to_string(), "1 mon 16 days 12:00:00");
173    /// assert_eq!(month.checked_mul(f64::INFINITY), Ok(PgInterval::INFINITY));
174    /// assert_eq!(month.checked_mul(f64::NAN), Err(IntervalError::OutOfRange));
175    /// ```
176    pub fn checked_mul(self, factor: f64) -> Result<Self, IntervalError> {
177        if factor.is_nan() {
178            return Err(IntervalError::OutOfRange);
179        }
180        if let Some(sign) = self.infinity() {
181            return match factor.partial_cmp(&0.0) {
182                Some(Ordering::Less) => Ok(Self::infinite(sign.reverse())),
183                Some(Ordering::Greater) => Ok(self),
184                _ => Err(IntervalError::OutOfRange),
185            };
186        }
187        if factor.is_infinite() {
188            return match self.span_microseconds().cmp(&0) {
189                Ordering::Equal => Err(IntervalError::OutOfRange),
190                sign if factor < 0.0 => Ok(Self::infinite(sign.reverse())),
191                sign => Ok(Self::infinite(sign)),
192            };
193        }
194        self.cascade(|field| field * factor)
195    }
196
197    /// PostgreSQL's `interval_div`, `self / factor`, cascading as
198    /// [`checked_mul`](Self::checked_mul) does.
199    ///
200    /// # Errors
201    ///
202    /// [`IntervalError::DivisionByZero`] for a zero factor, and [`IntervalError::OutOfRange`] for
203    /// a `NaN` factor, an infinity divided by an infinity, and a quotient beyond the type.
204    ///
205    /// ```
206    /// use sql_values::{IntervalError, parse_interval};
207    ///
208    /// let span = parse_interval("1 mon 1 day 00:00:01").unwrap();
209    /// assert_eq!(span.checked_div(7.0).unwrap().to_string(), "4 days 10:17:08.6896");
210    /// assert_eq!(span.checked_div(f64::INFINITY).unwrap().to_string(), "00:00:00");
211    /// assert_eq!(span.checked_div(0.0), Err(IntervalError::DivisionByZero));
212    /// ```
213    pub fn checked_div(self, factor: f64) -> Result<Self, IntervalError> {
214        if factor == 0.0 {
215            return Err(IntervalError::DivisionByZero);
216        }
217        if factor.is_nan() {
218            return Err(IntervalError::OutOfRange);
219        }
220        if let Some(sign) = self.infinity() {
221            return if factor.is_infinite() {
222                Err(IntervalError::OutOfRange)
223            } else if factor < 0.0 {
224                Ok(Self::infinite(sign.reverse()))
225            } else {
226                Ok(self)
227            };
228        }
229        self.cascade(|field| field / factor)
230    }
231
232    /// The fields of a finite result, each `None` where it overflowed.
233    fn finite_fields(fields: FieldResults) -> Result<Self, IntervalError> {
234        Self {
235            months: fields.months.ok_or(IntervalError::OutOfRange)?,
236            days: fields.days.ok_or(IntervalError::OutOfRange)?,
237            microseconds: fields.microseconds.ok_or(IntervalError::OutOfRange)?,
238        }
239        .finite()
240    }
241
242    /// The finite part of `interval_mul` and `interval_div`, `scale` being the multiplication or
243    /// the division by the factor.
244    fn cascade(self, scale: impl Fn(f64) -> f64) -> Result<Self, IntervalError> {
245        let month_product = scale(f64::from(self.months));
246        if !fits_in_i32(month_product) {
247            return Err(IntervalError::OutOfRange);
248        }
249        let months = truncate_to_i32(month_product);
250        let day_product = scale(f64::from(self.days));
251        if !fits_in_i32(day_product) {
252            return Err(IntervalError::OutOfRange);
253        }
254        let mut days = truncate_to_i32(day_product);
255        // Under 30 in magnitude, the fraction of a month as days.
256        let month_remainder_days = ts_round((month_product - f64::from(months)) * DAYS_PER_MONTH);
257        let whole_remainder_days = truncate_to_i32(month_remainder_days);
258        let mut sec_remainder = ts_round(
259            (day_product - f64::from(days) + month_remainder_days
260                - f64::from(whole_remainder_days))
261                * SECS_PER_DAY,
262        );
263        if sec_remainder.abs() >= SECS_PER_DAY {
264            // Under two days in magnitude, from two fractions below one day each.
265            let carried = truncate_to_i32(sec_remainder / SECS_PER_DAY);
266            days = days.checked_add(carried).ok_or(IntervalError::OutOfRange)?;
267            sec_remainder -= f64::from(carried) * SECS_PER_DAY;
268        }
269        days = days
270            .checked_add(whole_remainder_days)
271            .ok_or(IntervalError::OutOfRange)?;
272        let microseconds = round_ties_even(
273            scale(int_to_f64(self.microseconds)) + sec_remainder * int_to_f64(USECS_PER_SEC),
274        );
275        if !fits_in_i64(microseconds) {
276            return Err(IntervalError::OutOfRange);
277        }
278        Self {
279            months,
280            days,
281            microseconds: truncate_to_i64(microseconds),
282        }
283        .finite()
284    }
285
286    /// PostgreSQL's `timestamp_pl_interval`, `at + self`: months added to the calendar month with
287    /// the day clamped to the month's last, then days added to the calendar day, then the clock.
288    ///
289    /// The timestamp is read to the microsecond, as PostgreSQL holds it.
290    ///
291    /// # Errors
292    ///
293    /// [`ShiftError::TimestampOutOfRange`] where `at` or a step lies outside PostgreSQL's
294    /// timestamps, and [`ShiftError::Unrepresentable`] where PostgreSQL answers `infinity`,
295    /// `-infinity` or a year past `chrono`'s.
296    ///
297    /// ```
298    /// use sql_values::{parse_interval, parse_timestamp};
299    ///
300    /// let at = parse_timestamp("2024-01-31 10:00:00").unwrap();
301    /// let month = parse_interval("1 mon").unwrap();
302    /// assert_eq!(month.add_to_timestamp(at).unwrap().to_string(), "2024-02-29 10:00:00");
303    /// ```
304    pub fn add_to_timestamp(self, at: NaiveDateTime) -> Result<NaiveDateTime, ShiftError> {
305        let timestamp = pg_timestamp(at)?;
306        if !self.is_finite() {
307            return Err(ShiftError::Unrepresentable);
308        }
309        let mut timestamp = timestamp;
310        if self.months != 0 {
311            let (mut year, month, mut day, clock) = timestamp2tm(timestamp);
312            let mut month = month
313                .checked_add(self.months)
314                .ok_or(ShiftError::TimestampOutOfRange)?;
315            // C's truncating division and remainder.
316            if month > MONTHS_PER_YEAR {
317                year += (month - 1) / MONTHS_PER_YEAR;
318                month = (month - 1) % MONTHS_PER_YEAR + 1;
319            } else if month < 1 {
320                year += month / MONTHS_PER_YEAR - 1;
321                month = month % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
322            }
323            day = day.min(days_in_month(year, month));
324            timestamp = tm2timestamp(year, month, day, clock)?;
325        }
326        if self.days != 0 {
327            let (year, month, day, clock) = timestamp2tm(timestamp);
328            let julian = date2j(year, month, day)
329                .checked_add(self.days)
330                .filter(|julian| *julian >= 0)
331                .ok_or(ShiftError::TimestampOutOfRange)?;
332            let (year, month, day) = j2date(julian);
333            timestamp = tm2timestamp(year, month, day, clock)?;
334        }
335        let timestamp = timestamp
336            .checked_add(self.microseconds)
337            .filter(|timestamp| (MIN_TIMESTAMP..END_TIMESTAMP).contains(timestamp))
338            .ok_or(ShiftError::TimestampOutOfRange)?;
339        chrono_timestamp(timestamp)
340    }
341
342    /// PostgreSQL's `timestamp_mi_interval`, `at - self`, which adds the negated interval.
343    ///
344    /// # Errors
345    ///
346    /// [`ShiftError::IntervalOutOfRange`] where `interval_um` refuses the interval, and the
347    /// errors of [`add_to_timestamp`](Self::add_to_timestamp).
348    pub fn subtract_from_timestamp(self, at: NaiveDateTime) -> Result<NaiveDateTime, ShiftError> {
349        self.checked_neg()
350            .map_err(|_| ShiftError::IntervalOutOfRange)?
351            .add_to_timestamp(at)
352    }
353
354    /// PostgreSQL's `timestamp_mi`, `later - earlier`, with whole days carried into the days
355    /// field as `interval_justify_hours` carries them.
356    ///
357    /// # Errors
358    ///
359    /// [`ShiftError::TimestampOutOfRange`] where a timestamp lies outside PostgreSQL's.
360    ///
361    /// ```
362    /// use sql_values::{PgInterval, parse_timestamp};
363    ///
364    /// let later = parse_timestamp("2024-03-01 06:00:00").unwrap();
365    /// let earlier = parse_timestamp("2024-02-28 12:00:00").unwrap();
366    /// let span = PgInterval::timestamp_difference(later, earlier).unwrap();
367    /// assert_eq!(span.to_string(), "1 day 18:00:00");
368    /// ```
369    pub fn timestamp_difference(
370        later: NaiveDateTime,
371        earlier: NaiveDateTime,
372    ) -> Result<Self, ShiftError> {
373        // Both lie within PostgreSQL's range, so their difference fits.
374        let time = pg_timestamp(later)? - pg_timestamp(earlier)?;
375        // Division truncates toward zero, so the days and the clock share the sign of the
376        // difference and the sign corrections of `interval_justify_hours` never apply.
377        // Valid timestamps lie under 2^27 days apart, which `int` holds.
378        let days =
379            i32::try_from(time / USECS_PER_DAY).expect("timestamps lie under 2^27 days apart");
380        Ok(Self {
381            months: 0,
382            days,
383            microseconds: time % USECS_PER_DAY,
384        })
385    }
386
387    /// PostgreSQL's `time_pl_interval`, `at + self`: the clock moved by the interval's
388    /// microseconds, wrapping in 64 bits as PostgreSQL does, then within the day. The months and
389    /// days are ignored.
390    ///
391    /// # Errors
392    ///
393    /// [`ShiftError::InfiniteIntervalAddedToTime`] for an infinite interval.
394    ///
395    /// ```
396    /// use sql_values::{parse_interval, parse_time};
397    ///
398    /// let at = parse_time("23:00:00").unwrap();
399    /// let span = parse_interval("1 day 02:30:00").unwrap();
400    /// assert_eq!(span.add_to_time(at).unwrap().to_string(), "01:30:00");
401    /// ```
402    pub fn add_to_time(self, at: NaiveTime) -> Result<NaiveTime, ShiftError> {
403        if !self.is_finite() {
404            return Err(ShiftError::InfiniteIntervalAddedToTime);
405        }
406        Ok(wrap_time(pg_time(at).wrapping_add(self.microseconds)))
407    }
408
409    /// PostgreSQL's `time_mi_interval`, `at - self`, as [`add_to_time`](Self::add_to_time) with
410    /// the clock subtracted.
411    ///
412    /// # Errors
413    ///
414    /// [`ShiftError::InfiniteIntervalSubtractedFromTime`] for an infinite interval.
415    pub fn subtract_from_time(self, at: NaiveTime) -> Result<NaiveTime, ShiftError> {
416        if !self.is_finite() {
417            return Err(ShiftError::InfiniteIntervalSubtractedFromTime);
418        }
419        Ok(wrap_time(pg_time(at).wrapping_sub(self.microseconds)))
420    }
421}
422
423/// The three fields of an interval result, each `None` where its arithmetic overflowed.
424struct FieldResults {
425    months: Option<i32>,
426    days: Option<i32>,
427    microseconds: Option<i64>,
428}
429
430/// A time as PostgreSQL holds it, microseconds since midnight.
431fn pg_time(at: NaiveTime) -> i64 {
432    i64::from(at.num_seconds_from_midnight()) * USECS_PER_SEC + i64::from(at.nanosecond() / 1_000)
433}
434
435/// The time of `moved` microseconds reduced into the day, as `time_pl_interval` reduces it.
436fn wrap_time(moved: i64) -> NaiveTime {
437    let micros = moved.rem_euclid(USECS_PER_DAY);
438    // `rem_euclid` keeps `micros` within one day, which both parts of the clock fit.
439    let seconds = u32::try_from(micros / USECS_PER_SEC).expect("a second of the day fits u32");
440    let nanos = u32::try_from(micros % USECS_PER_SEC * 1_000).expect("a nanosecond fits u32");
441    NaiveTime::from_num_seconds_from_midnight_opt(seconds, nanos)
442        .expect("a clock within the day is a time")
443}
444
445/// A timestamp as PostgreSQL holds it, microseconds from 2000-01-01.
446fn pg_timestamp(at: NaiveDateTime) -> Result<i64, ShiftError> {
447    let days = i64::from(at.date().num_days_from_ce()) + JULIAN_BEFORE_CE - POSTGRES_EPOCH_JDATE;
448    // `chrono` holds under 2^27 days either side, so the microseconds fit.
449    let timestamp = days * USECS_PER_DAY + pg_time(at.time());
450    if (MIN_TIMESTAMP..END_TIMESTAMP).contains(&timestamp) {
451        Ok(timestamp)
452    } else {
453        Err(ShiftError::TimestampOutOfRange)
454    }
455}
456
457/// The `chrono` timestamp of one PostgreSQL holds.
458fn chrono_timestamp(timestamp: i64) -> Result<NaiveDateTime, ShiftError> {
459    let days = timestamp.div_euclid(USECS_PER_DAY) + POSTGRES_EPOCH_JDATE - JULIAN_BEFORE_CE;
460    let date = i32::try_from(days)
461        .ok()
462        .and_then(NaiveDate::from_num_days_from_ce_opt)
463        .ok_or(ShiftError::Unrepresentable)?;
464    Ok(date.and_time(wrap_time(timestamp)))
465}
466
467/// `timestamp2tm`, the year, month, day and clock of a valid timestamp.
468fn timestamp2tm(timestamp: i64) -> (i32, i32, i32, i64) {
469    let julian = timestamp.div_euclid(USECS_PER_DAY) + POSTGRES_EPOCH_JDATE;
470    // A valid timestamp lies between Julian days 0 and 109203528.
471    let julian = i32::try_from(julian).expect("a valid timestamp's Julian day fits int");
472    let (year, month, day) = j2date(julian);
473    (year, month, day, timestamp.rem_euclid(USECS_PER_DAY))
474}
475
476/// `tm2timestamp`, refusing a date before Julian day 0 or a timestamp out of range.
477fn tm2timestamp(year: i32, month: i32, day: i32, clock: i64) -> Result<i64, ShiftError> {
478    // `IS_VALID_JULIAN`, which keeps `date2j` from overflowing.
479    let valid_julian = (year > -4713 || (year == -4713 && month >= 11))
480        && (year < 5_874_898 || (year == 5_874_898 && month < 6));
481    if !valid_julian {
482        return Err(ShiftError::TimestampOutOfRange);
483    }
484    let days = i64::from(date2j(year, month, day)) - POSTGRES_EPOCH_JDATE;
485    days.checked_mul(USECS_PER_DAY)
486        .and_then(|micros| micros.checked_add(clock))
487        .filter(|timestamp| (MIN_TIMESTAMP..END_TIMESTAMP).contains(timestamp))
488        .ok_or(ShiftError::TimestampOutOfRange)
489}
490
491/// `date2j`, the Julian day of a proleptic Gregorian date within `IS_VALID_JULIAN`.
492const fn date2j(year: i32, month: i32, day: i32) -> i32 {
493    let (year, month) = if month > 2 {
494        (year + 4800, month + 1)
495    } else {
496        (year + 4799, month + 13)
497    };
498    let century = year / 100;
499    let mut julian = year * 365 - 32_167;
500    julian += year / 4 - century + century / 4;
501    julian + 7_834 * month / 256 + day
502}
503
504/// `j2date`, the proleptic Gregorian date of a Julian day from 0.
505const fn j2date(julian_day: i32) -> (i32, i32, i32) {
506    // Unsigned as in C, where every intermediate stays below 2^32.
507    let mut julian = julian_day.cast_unsigned() + 32_044;
508    let mut quad = julian / 146_097;
509    let extra = (julian - quad * 146_097) * 4 + 3;
510    julian += 60 + quad * 3 + extra / 146_097;
511    quad = julian / 1_461;
512    julian -= quad * 1_461;
513    let mut year = julian * 4 / 1_461;
514    julian = if year == 0 {
515        (julian + 306) % 366
516    } else {
517        (julian + 305) % 365
518    } + 123;
519    year += quad * 4;
520    let quad = julian * 2_141 / 65_536;
521    let day = julian - 7_834 * quad / 256;
522    let month = (quad + 10) % 12 + 1;
523    // The year is below 2^31 + 4800 and the day and month below 32.
524    (
525        year.cast_signed() - 4_800,
526        month.cast_signed(),
527        day.cast_signed(),
528    )
529}
530
531/// Days in `month` of the proleptic Gregorian `year`, `0` being 1 BC.
532const fn days_in_month(year: i32, month: i32) -> i32 {
533    let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
534    match month {
535        2 if leap => 29,
536        2 => 28,
537        4 | 6 | 9 | 11 => 30,
538        _ => 31,
539    }
540}
541
542/// The running state of PostgreSQL's `sum(interval)` and `avg(interval)`.
543///
544/// The finite values are summed exactly per field and the infinities are counted, as PostgreSQL
545/// counts them. PostgreSQL adds in scan order and raises on a partial sum leaving a field's range,
546/// so the same rows can sum or raise by the order they are read in. Whenever a field's net total
547/// fits, some order of the rows never leaves the range, and its answer is that net total, which is
548/// the one reported here.
549///
550/// The counts are signed so that a row leaving is the same type as one arriving, and folding
551/// either in is componentwise addition.
552///
553/// ```
554/// use sql_values::{IntervalSum, PgInterval, parse_interval};
555///
556/// let mut total = IntervalSum::default();
557/// for text in ["1 mon", "2 days", "-01:00:00"] {
558///     total.merge(IntervalSum::of(parse_interval(text).unwrap(), 1));
559/// }
560/// assert_eq!(total.sum().unwrap().unwrap().to_string(), "1 mon 2 days -01:00:00");
561/// assert_eq!(total.avg().unwrap().unwrap().to_string(), "10 days 15:40:00");
562///
563/// total.merge(IntervalSum::of(PgInterval::INFINITY, 1));
564/// assert_eq!(total.avg(), Ok(Some(PgInterval::INFINITY)));
565/// ```
566#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
567#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
568pub struct IntervalSum {
569    finite: i64,
570    positive_infinities: i64,
571    negative_infinities: i64,
572    months: i128,
573    days: i128,
574    microseconds: i128,
575}
576
577impl IntervalSum {
578    /// One row's interval contributing with `weight`, `1` for a row arriving and `-1` for one
579    /// leaving.
580    #[must_use]
581    pub fn of(value: PgInterval, weight: i64) -> Self {
582        match value.infinity() {
583            Some(Ordering::Greater) => Self {
584                positive_infinities: weight,
585                ..Self::default()
586            },
587            Some(_) => Self {
588                negative_infinities: weight,
589                ..Self::default()
590            },
591            None => {
592                let wide = i128::from(weight);
593                Self {
594                    finite: weight,
595                    positive_infinities: 0,
596                    negative_infinities: 0,
597                    months: i128::from(value.months) * wide,
598                    days: i128::from(value.days) * wide,
599                    microseconds: i128::from(value.microseconds) * wide,
600                }
601            }
602        }
603    }
604
605    /// The state a database reports for some rows: the sum of the finite ones, how many there
606    /// are, and how many are each infinity.
607    #[must_use]
608    pub fn seeded(
609        finite_sum: Option<PgInterval>,
610        finite: i64,
611        positive_infinities: i64,
612        negative_infinities: i64,
613    ) -> Self {
614        let (months, days, microseconds) =
615            finite_sum.map_or((0, 0, 0), |sum| (sum.months, sum.days, sum.microseconds));
616        Self {
617            finite,
618            positive_infinities,
619            negative_infinities,
620            months: i128::from(months),
621            days: i128::from(days),
622            microseconds: i128::from(microseconds),
623        }
624    }
625
626    /// Fold `other` in, componentwise.
627    pub const fn merge(&mut self, other: Self) {
628        self.finite += other.finite;
629        self.positive_infinities += other.positive_infinities;
630        self.negative_infinities += other.negative_infinities;
631        self.months += other.months;
632        self.days += other.days;
633        self.microseconds += other.microseconds;
634    }
635
636    /// Whether this moves nothing.
637    #[must_use]
638    pub fn is_zero(&self) -> bool {
639        *self == Self::default()
640    }
641
642    /// The rows folded in.
643    #[must_use]
644    pub const fn count(&self) -> i64 {
645        self.finite + self.positive_infinities + self.negative_infinities
646    }
647
648    /// PostgreSQL's `interval_sum`, `None` over no rows.
649    ///
650    /// # Errors
651    ///
652    /// [`IntervalError::OutOfRange`] for infinities of both signs and for a field whose net total
653    /// leaves its range.
654    pub fn sum(&self) -> Result<Option<PgInterval>, IntervalError> {
655        if self.count() <= 0 {
656            return Ok(None);
657        }
658        match (self.positive_infinities > 0, self.negative_infinities > 0) {
659            (true, true) => Err(IntervalError::OutOfRange),
660            (true, false) => Ok(Some(PgInterval::INFINITY)),
661            (false, true) => Ok(Some(PgInterval::NEG_INFINITY)),
662            (false, false) => PgInterval::finite_fields(FieldResults {
663                months: i32::try_from(self.months).ok(),
664                days: i32::try_from(self.days).ok(),
665                microseconds: i64::try_from(self.microseconds).ok(),
666            })
667            .map(Some),
668        }
669    }
670
671    /// PostgreSQL's `interval_avg`, the sum divided by the count of finite rows as
672    /// `interval_div` divides, `None` over no rows.
673    ///
674    /// # Errors
675    ///
676    /// The errors of [`sum`](Self::sum), and [`IntervalError::OutOfRange`] for a quotient beyond
677    /// the type.
678    pub fn avg(&self) -> Result<Option<PgInterval>, IntervalError> {
679        match self.sum()? {
680            Some(sum) if sum.is_finite() => {
681                // Intended loss, as PostgreSQL divides by the count as a `double`.
682                let count = self.finite as f64;
683                sum.checked_div(count).map(Some)
684            }
685            other => Ok(other),
686        }
687    }
688}