Skip to main content

sql_values/postgres/datetime/
arithmetic.rs

1//! PostgreSQL 18's `date` arithmetic, `date_pli`, `date_mii` and `date_mi`, the cast
2//! `date2timestamp` and the cross-type comparison `date_cmp_timestamp`.
3
4use core::cmp::Ordering;
5
6use super::{PgDate, PgTimestamp, TIMESTAMP_END_DAYS, USECS_PER_DAY, is_valid_date};
7
8/// Why PostgreSQL refuses `date` arithmetic or the cast of a date to `timestamp`, one variant per
9/// message it raises.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
11pub enum DateArithmeticError {
12    /// A result before 4714-11-24 BC or from 5874898-01-01.
13    #[error("date out of range")]
14    DateOutOfRange,
15    /// `date - date` with an infinite date.
16    #[error("cannot subtract infinite dates")]
17    CannotSubtractInfiniteDates,
18    /// A date from 294277-01-01 cast to `timestamp`.
19    #[error("date out of range for timestamp")]
20    DateOutOfRangeForTimestamp,
21}
22
23impl PgDate {
24    /// `date + integer` and `integer + date`, PostgreSQL's `date_pli`, leaving an infinity as it
25    /// is.
26    ///
27    /// # Errors
28    ///
29    /// [`DateArithmeticError::DateOutOfRange`] for a result before 4714-11-24 BC or from
30    /// 5874898-01-01.
31    ///
32    /// ```
33    /// use sql_values::postgres::{DateArithmeticError, PgDate};
34    ///
35    /// let date = PgDate::from_ymd(2026, 1, 31).unwrap();
36    /// assert_eq!(date.checked_add_days(1).unwrap().to_string(), "2026-02-01");
37    /// assert_eq!(PgDate::INFINITY.checked_add_days(1), Ok(PgDate::INFINITY));
38    /// assert_eq!(date.checked_add_days(i32::MAX), Err(DateArithmeticError::DateOutOfRange));
39    /// ```
40    pub fn checked_add_days(self, days: i32) -> Result<Self, DateArithmeticError> {
41        self.shift(self.0.checked_add(days))
42    }
43
44    /// `date - integer`, PostgreSQL's `date_mii`, leaving an infinity as it is.
45    ///
46    /// # Errors
47    ///
48    /// [`DateArithmeticError::DateOutOfRange`] for a result before 4714-11-24 BC or from
49    /// 5874898-01-01.
50    ///
51    /// ```
52    /// use sql_values::postgres::{DateArithmeticError, PgDate};
53    ///
54    /// let first = PgDate::from_ymd(-4713, 11, 24).unwrap();
55    /// assert_eq!(first.checked_sub_days(1), Err(DateArithmeticError::DateOutOfRange));
56    /// ```
57    pub fn checked_sub_days(self, days: i32) -> Result<Self, DateArithmeticError> {
58        self.shift(self.0.checked_sub(days))
59    }
60
61    /// `date - date`, PostgreSQL's `date_mi`, the days from `earlier` to `self`.
62    ///
63    /// # Errors
64    ///
65    /// [`DateArithmeticError::CannotSubtractInfiniteDates`] when either date is infinite.
66    ///
67    /// ```
68    /// use sql_values::postgres::PgDate;
69    ///
70    /// let march = PgDate::from_ymd(2026, 3, 1).unwrap();
71    /// let january = PgDate::from_ymd(2026, 1, 1).unwrap();
72    /// assert_eq!(march.days_since(january), Ok(59));
73    /// assert_eq!(january.days_since(march), Ok(-59));
74    /// ```
75    pub const fn days_since(self, earlier: Self) -> Result<i32, DateArithmeticError> {
76        if self.is_finite() && earlier.is_finite() {
77            // Finite dates lie under 2^31 days apart.
78            Ok(self.0 - earlier.0)
79        } else {
80            Err(DateArithmeticError::CannotSubtractInfiniteDates)
81        }
82    }
83
84    /// The `timestamp` at the start of the date, PostgreSQL's `date2timestamp`, with an infinite
85    /// date the like infinite timestamp.
86    ///
87    /// # Errors
88    ///
89    /// [`DateArithmeticError::DateOutOfRangeForTimestamp`] for a date from 294277-01-01.
90    ///
91    /// ```
92    /// use sql_values::postgres::{DateArithmeticError, PgDate, PgTimestamp};
93    ///
94    /// let date = PgDate::from_ymd(2026, 1, 1).unwrap();
95    /// assert_eq!(date.to_timestamp().unwrap().to_string(), "2026-01-01 00:00:00");
96    /// assert_eq!(PgDate::INFINITY.to_timestamp(), Ok(PgTimestamp::INFINITY));
97    /// let late = PgDate::from_ymd(294_277, 1, 1).unwrap();
98    /// assert_eq!(late.to_timestamp(), Err(DateArithmeticError::DateOutOfRangeForTimestamp));
99    /// ```
100    pub fn to_timestamp(self) -> Result<PgTimestamp, DateArithmeticError> {
101        match self.0 {
102            i32::MAX => Ok(PgTimestamp::INFINITY),
103            i32::MIN => Ok(PgTimestamp::NEG_INFINITY),
104            days if days >= TIMESTAMP_END_DAYS => {
105                Err(DateArithmeticError::DateOutOfRangeForTimestamp)
106            }
107            days => Ok(PgTimestamp(i64::from(days) * USECS_PER_DAY)),
108        }
109    }
110
111    /// The order of the date against a `timestamp`, PostgreSQL's `date_cmp_timestamp`, which
112    /// never fails. A date past the last timestamp sorts after every finite timestamp and before
113    /// `infinity`.
114    ///
115    /// ```
116    /// use core::cmp::Ordering;
117    /// use sql_values::postgres::{InputContext, PgDate, PgTimestamp};
118    ///
119    /// let date = PgDate::from_ymd(2026, 1, 1).unwrap();
120    /// let morning = PgTimestamp::parse("2026-01-01 10:00", InputContext::new()).unwrap();
121    /// assert_eq!(date.cmp_timestamp(morning), Ordering::Less);
122    /// let last = PgDate::from_ymd(5_874_897, 12, 31).unwrap();
123    /// assert_eq!(last.cmp_timestamp(morning), Ordering::Greater);
124    /// assert_eq!(last.cmp_timestamp(PgTimestamp::INFINITY), Ordering::Less);
125    /// ```
126    #[must_use]
127    pub fn cmp_timestamp(self, at: PgTimestamp) -> Ordering {
128        match self.to_timestamp() {
129            Ok(start) => start.cmp(&at),
130            Err(_) if at == PgTimestamp::INFINITY => Ordering::Less,
131            Err(_) => Ordering::Greater,
132        }
133    }
134
135    /// `date_pli`'s result, an infinity left as it is and an overflow or a date outside
136    /// PostgreSQL's refused.
137    fn shift(self, shifted: Option<i32>) -> Result<Self, DateArithmeticError> {
138        if !self.is_finite() {
139            return Ok(self);
140        }
141        match shifted {
142            Some(days) if is_valid_date(days) => Ok(Self(days)),
143            _ => Err(DateArithmeticError::DateOutOfRange),
144        }
145    }
146}