Skip to main content

sql_values/postgres/
interval.rs

1//! PostgreSQL `interval` values read by `interval_in`, printed by `interval_out`, compared by
2//! `interval_cmp` and combined by PostgreSQL's interval arithmetic.
3
4mod arithmetic;
5mod decode;
6
7use core::{
8    cmp::Ordering,
9    fmt,
10    hash::{Hash, Hasher},
11};
12
13pub use arithmetic::{IntervalSum, ShiftError};
14use decode::{
15    INTERVAL_FULL_RANGE, RANGE_DAY, RANGE_HOUR, RANGE_MINUTE, RANGE_MONTH, RANGE_SECOND,
16    RANGE_YEAR, adjust_interval_for_typmod, interval_in,
17};
18pub(crate) use decode::{decode_extract_unit, decode_units, strtod};
19
20const USECS_PER_DAY: i128 = 86_400_000_000;
21const USECS_PER_SEC: u64 = 1_000_000;
22const DAYS_PER_MONTH: i64 = 30;
23
24/// A PostgreSQL `interval` as months, days and microseconds, equal, ordered and hashed by
25/// PostgreSQL's span with a month as 30 days and a day as 24 hours.
26///
27/// ```
28/// use sql_values::postgres::{PgInterval, parse_interval};
29///
30/// let month = parse_interval("1 mon").unwrap();
31/// let thirty_days = parse_interval("30 days").unwrap();
32/// assert_eq!(month, thirty_days);
33/// assert_ne!(month.to_string(), thirty_days.to_string());
34/// assert!(parse_interval("infinity").unwrap() > month);
35/// assert_eq!(PgInterval::NEG_INFINITY.to_string(), "-infinity");
36/// ```
37#[derive(Debug, Clone, Copy)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39pub struct PgInterval {
40    /// Months, twelve of which print as a year.
41    pub months: i32,
42    /// Days, never folded into months.
43    pub days: i32,
44    /// Microseconds, never folded into days.
45    pub microseconds: i64,
46}
47
48impl PgInterval {
49    /// `infinity`, PostgreSQL's `INTERVAL_NOEND`, above every finite interval.
50    pub const INFINITY: Self = Self {
51        months: i32::MAX,
52        days: i32::MAX,
53        microseconds: i64::MAX,
54    };
55
56    /// `-infinity`, PostgreSQL's `INTERVAL_NOBEGIN`, below every finite interval.
57    pub const NEG_INFINITY: Self = Self {
58        months: i32::MIN,
59        days: i32::MIN,
60        microseconds: i64::MIN,
61    };
62
63    /// Whether the interval is neither `infinity` nor `-infinity`.
64    ///
65    /// ```
66    /// use sql_values::postgres::PgInterval;
67    ///
68    /// assert!(!PgInterval::INFINITY.is_finite());
69    /// assert!(PgInterval { months: i32::MAX, days: i32::MAX, microseconds: 0 }.is_finite());
70    /// ```
71    #[must_use]
72    pub const fn is_finite(&self) -> bool {
73        !self.fields_equal(&Self::INFINITY) && !self.fields_equal(&Self::NEG_INFINITY)
74    }
75
76    const fn fields_equal(&self, other: &Self) -> bool {
77        self.months == other.months
78            && self.days == other.days
79            && self.microseconds == other.microseconds
80    }
81
82    /// PostgreSQL's `interval_cmp_value`, the span in microseconds with a month as 30 days and a
83    /// day as 24 hours, which orders, equates and hashes the interval.
84    ///
85    /// ```
86    /// use sql_values::postgres::parse_interval;
87    ///
88    /// let month = parse_interval("1 mon -1 days").unwrap();
89    /// assert_eq!(month.span_microseconds(), 29 * 86_400_000_000);
90    /// ```
91    #[must_use]
92    pub fn span_microseconds(&self) -> i128 {
93        let days = i64::from(self.months) * DAYS_PER_MONTH + i64::from(self.days);
94        i128::from(self.microseconds) + i128::from(days) * USECS_PER_DAY
95    }
96
97    /// `interval_scale`, the length coercion of an interval type, which truncates the interval
98    /// below the last field the typmod keeps and rounds its seconds, half away from zero, to the
99    /// typmod's precision. An infinity is kept.
100    ///
101    /// # Errors
102    ///
103    /// [`IntervalError::OutOfRange`] when rounding the seconds leaves the type.
104    ///
105    /// ```
106    /// use sql_values::postgres::{
107    ///     IntervalError, IntervalFields, IntervalTypmod, PgInterval, parse_interval,
108    /// };
109    ///
110    /// let hour = IntervalTypmod::new(Some(IntervalFields::Hour), None).unwrap();
111    /// let span = parse_interval("1 day 01:30:00").unwrap();
112    /// assert_eq!(span.adjust_for_typmod(hour).unwrap().to_string(), "1 day 01:00:00");
113    /// assert_eq!(PgInterval::INFINITY.adjust_for_typmod(hour), Ok(PgInterval::INFINITY));
114    ///
115    /// let whole = IntervalTypmod::new(None, Some(0)).unwrap();
116    /// let span = parse_interval("-00:00:01.5").unwrap();
117    /// assert_eq!(span.adjust_for_typmod(whole).unwrap().to_string(), "-00:00:02");
118    /// let last = PgInterval { months: 0, days: 0, microseconds: i64::MAX - 1 };
119    /// assert_eq!(last.adjust_for_typmod(whole), Err(IntervalError::OutOfRange));
120    /// ```
121    pub fn adjust_for_typmod(mut self, typmod: IntervalTypmod) -> Result<Self, IntervalError> {
122        adjust_interval_for_typmod(&mut self, typmod.range(), typmod.precision)?;
123        Ok(self)
124    }
125}
126
127/// Why PostgreSQL refuses to read an interval or to compute one, one variant per message it
128/// raises.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
130pub enum IntervalError {
131    /// Text `interval_in` cannot read.
132    #[error("invalid input syntax for type interval")]
133    InvalidSyntax,
134    /// A number of the text beyond the integer its field accumulates in.
135    #[error("interval field value out of range")]
136    FieldValueOutOfRange,
137    /// A value beyond the type, or arithmetic PostgreSQL has no answer for.
138    #[error("interval out of range")]
139    OutOfRange,
140    /// An interval divided by zero.
141    #[error("division by zero")]
142    DivisionByZero,
143}
144
145impl PartialEq for PgInterval {
146    fn eq(&self, other: &Self) -> bool {
147        self.span_microseconds() == other.span_microseconds()
148    }
149}
150
151impl Eq for PgInterval {}
152
153impl PartialOrd for PgInterval {
154    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
155        Some(self.cmp(other))
156    }
157}
158
159impl Ord for PgInterval {
160    fn cmp(&self, other: &Self) -> Ordering {
161        self.span_microseconds().cmp(&other.span_microseconds())
162    }
163}
164
165impl Hash for PgInterval {
166    fn hash<H: Hasher>(&self, state: &mut H) {
167        self.span_microseconds().hash(state);
168    }
169}
170
171/// PostgreSQL's text under the default `postgres` `IntervalStyle`, which [`parse_interval`] reads
172/// back except the clock of `i64::MIN` microseconds that PostgreSQL refuses too.
173impl fmt::Display for PgInterval {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        if self.fields_equal(&Self::INFINITY) {
176            return f.write_str("infinity");
177        }
178        if self.fields_equal(&Self::NEG_INFINITY) {
179            return f.write_str("-infinity");
180        }
181        // `INTSTYLE_POSTGRES` marks a positive count that follows a negative one with `+`.
182        let mut is_zero = true;
183        let mut is_before = false;
184        for (count, unit) in [
185            (self.months / 12, "year"),
186            (self.months % 12, "mon"),
187            (self.days, "day"),
188        ] {
189            if count == 0 {
190                continue;
191            }
192            let separator = if is_zero { "" } else { " " };
193            let plus = if is_before && count > 0 { "+" } else { "" };
194            let plural = if count == 1 { "" } else { "s" };
195            write!(f, "{separator}{plus}{count} {unit}{plural}")?;
196            is_before = count < 0;
197            is_zero = false;
198        }
199        if is_zero || self.microseconds != 0 {
200            let separator = if is_zero { "" } else { " " };
201            let sign = if self.microseconds < 0 {
202                "-"
203            } else if is_before {
204                "+"
205            } else {
206                ""
207            };
208            let magnitude = self.microseconds.unsigned_abs();
209            let seconds = magnitude / USECS_PER_SEC;
210            write!(
211                f,
212                "{separator}{sign}{:02}:{:02}:{:02}",
213                seconds / 3_600,
214                seconds % 3_600 / 60,
215                seconds % 60
216            )?;
217            let mut fraction = magnitude % USECS_PER_SEC;
218            if fraction != 0 {
219                let mut digits = 6;
220                while fraction.is_multiple_of(10) {
221                    fraction /= 10;
222                    digits -= 1;
223                }
224                write!(f, ".{fraction:0digits$}")?;
225            }
226        }
227        Ok(())
228    }
229}
230
231/// The fields an interval type keeps, as in `interval day to second`.
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
233pub enum IntervalFields {
234    /// `YEAR`.
235    Year,
236    /// `MONTH`.
237    Month,
238    /// `DAY`.
239    Day,
240    /// `HOUR`.
241    Hour,
242    /// `MINUTE`.
243    Minute,
244    /// `SECOND`.
245    Second,
246    /// `YEAR TO MONTH`.
247    YearToMonth,
248    /// `DAY TO HOUR`.
249    DayToHour,
250    /// `DAY TO MINUTE`.
251    DayToMinute,
252    /// `DAY TO SECOND`.
253    DayToSecond,
254    /// `HOUR TO MINUTE`.
255    HourToMinute,
256    /// `HOUR TO SECOND`.
257    HourToSecond,
258    /// `MINUTE TO SECOND`.
259    MinuteToSecond,
260}
261
262impl IntervalFields {
263    /// `INTERVAL_MASK` of every field kept.
264    const fn range(self) -> u16 {
265        match self {
266            Self::Year => RANGE_YEAR,
267            Self::Month => RANGE_MONTH,
268            Self::Day => RANGE_DAY,
269            Self::Hour => RANGE_HOUR,
270            Self::Minute => RANGE_MINUTE,
271            Self::Second => RANGE_SECOND,
272            Self::YearToMonth => RANGE_YEAR | RANGE_MONTH,
273            Self::DayToHour => RANGE_DAY | RANGE_HOUR,
274            Self::DayToMinute => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE,
275            Self::DayToSecond => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
276            Self::HourToMinute => RANGE_HOUR | RANGE_MINUTE,
277            Self::HourToSecond => RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
278            Self::MinuteToSecond => RANGE_MINUTE | RANGE_SECOND,
279        }
280    }
281
282    /// Whether a precision may follow, which only `SECOND` allows.
283    const fn ends_in_second(self) -> bool {
284        matches!(
285            self,
286            Self::Second | Self::DayToSecond | Self::HourToSecond | Self::MinuteToSecond
287        )
288    }
289}
290
291/// The modifier of an interval type, the fields it keeps and the fractional-second digits it
292/// rounds to, where the default is plain `interval`.
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
294pub struct IntervalTypmod {
295    fields: Option<IntervalFields>,
296    precision: Option<u8>,
297}
298
299/// The most fractional-second digits an interval keeps.
300const MAX_INTERVAL_PRECISION: u8 = 6;
301
302impl IntervalTypmod {
303    /// `intervaltypmodin`, clamping a precision above six as PostgreSQL does, or `None` for a
304    /// precision after fields not ending in `SECOND`.
305    ///
306    /// ```
307    /// use sql_values::postgres::{IntervalFields, IntervalTypmod};
308    ///
309    /// assert!(IntervalTypmod::new(Some(IntervalFields::DayToSecond), Some(3)).is_some());
310    /// assert!(IntervalTypmod::new(None, Some(3)).is_some());
311    /// assert!(IntervalTypmod::new(Some(IntervalFields::Minute), Some(3)).is_none());
312    /// ```
313    #[must_use]
314    pub const fn new(fields: Option<IntervalFields>, precision: Option<u8>) -> Option<Self> {
315        let precision = match (fields, precision) {
316            (Some(fields), Some(_)) if !fields.ends_in_second() => return None,
317            (_, Some(precision)) if precision > MAX_INTERVAL_PRECISION => {
318                Some(MAX_INTERVAL_PRECISION)
319            }
320            (_, precision) => precision,
321        };
322        Some(Self { fields, precision })
323    }
324
325    const fn range(self) -> u16 {
326        match self.fields {
327            Some(fields) => fields.range(),
328            None => INTERVAL_FULL_RANGE,
329        }
330    }
331}
332
333/// Parse an interval as PostgreSQL 18's `interval_in` reads it under the default `IntervalStyle`.
334///
335/// # Errors
336///
337/// The [`IntervalError`] PostgreSQL raises: [`IntervalError::InvalidSyntax`] for text it cannot
338/// read, [`IntervalError::FieldValueOutOfRange`] for a number beyond its field and
339/// [`IntervalError::OutOfRange`] for years and months beyond the type.
340///
341/// ```
342/// use sql_values::postgres::{IntervalError, PgInterval, parse_interval};
343///
344/// let interval = parse_interval("-1 days +02:00:00").unwrap();
345/// assert_eq!(
346///     (interval.months, interval.days, interval.microseconds),
347///     (0, -1, 7_200_000_000),
348/// );
349/// assert_eq!(parse_interval("1.5 days").unwrap().to_string(), "1 day 12:00:00");
350/// assert_eq!(parse_interval("@ 1 hour ago").unwrap().to_string(), "-01:00:00");
351/// assert_eq!(parse_interval("P-.5D").unwrap().to_string(), "-12:00:00");
352/// assert_eq!(parse_interval("-infinity"), Ok(PgInterval::NEG_INFINITY));
353/// assert_eq!(parse_interval("p1d"), Err(IntervalError::InvalidSyntax));
354/// assert_eq!(
355///     parse_interval("P1000000000000000D"),
356///     Err(IntervalError::FieldValueOutOfRange),
357/// );
358/// assert_eq!(parse_interval("178956971 years"), Err(IntervalError::OutOfRange));
359/// ```
360pub fn parse_interval(text: &str) -> Result<PgInterval, IntervalError> {
361    interval_in(text, INTERVAL_FULL_RANGE, None)
362}
363
364/// Parse an interval literal of a restricted type as `interval '…' <fields>` reads it, which
365/// differs from casting a text value to that type.
366///
367/// # Errors
368///
369/// The [`IntervalError`] PostgreSQL raises, as for [`parse_interval`], where rounding the
370/// seconds to the typmod's precision can also leave the type, [`IntervalError::OutOfRange`].
371///
372/// ```
373/// use sql_values::postgres::{
374///     IntervalError, IntervalFields, IntervalTypmod, parse_interval, parse_interval_typmod,
375/// };
376///
377/// let minute = IntervalTypmod::new(Some(IntervalFields::Minute), None).unwrap();
378/// assert_eq!(parse_interval_typmod("90", minute).unwrap().to_string(), "01:30:00");
379///
380/// let to_second = IntervalTypmod::new(Some(IntervalFields::MinuteToSecond), Some(0)).unwrap();
381/// assert_eq!(parse_interval_typmod("1:30.5", to_second).unwrap().to_string(), "00:01:31");
382/// assert_eq!(
383///     parse_interval_typmod("9223372036854775807 usecs", to_second),
384///     Err(IntervalError::OutOfRange),
385/// );
386///
387/// let hour = IntervalTypmod::new(Some(IntervalFields::Hour), None).unwrap();
388/// assert_eq!(parse_interval_typmod("3 4", hour).unwrap().to_string(), "3 days 04:00:00");
389/// assert_eq!(parse_interval("3 4"), Err(IntervalError::InvalidSyntax));
390/// ```
391pub fn parse_interval_typmod(
392    text: &str,
393    typmod: IntervalTypmod,
394) -> Result<PgInterval, IntervalError> {
395    interval_in(text, typmod.range(), typmod.precision)
396}