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