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(
123 &mut self,
124 typmod.range(),
125 typmod.precision.map(super::TimePrecision::get),
126 )?;
127 Ok(self)
128 }
129}
130
131/// Why PostgreSQL refuses to read an interval or to compute one, one variant per message it
132/// raises.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
134pub enum IntervalError {
135 /// Text `interval_in` cannot read.
136 #[error("invalid input syntax for type interval")]
137 InvalidSyntax,
138 /// A number of the text beyond the integer its field accumulates in.
139 #[error("interval field value out of range")]
140 FieldValueOutOfRange,
141 /// A value beyond the type, or arithmetic PostgreSQL has no answer for.
142 #[error("interval out of range")]
143 OutOfRange,
144 /// An interval divided by zero.
145 #[error("division by zero")]
146 DivisionByZero,
147}
148
149impl PartialEq for PgInterval {
150 fn eq(&self, other: &Self) -> bool {
151 self.span_microseconds() == other.span_microseconds()
152 }
153}
154
155impl Eq for PgInterval {}
156
157impl PartialOrd for PgInterval {
158 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
159 Some(self.cmp(other))
160 }
161}
162
163impl Ord for PgInterval {
164 fn cmp(&self, other: &Self) -> Ordering {
165 self.span_microseconds().cmp(&other.span_microseconds())
166 }
167}
168
169impl Hash for PgInterval {
170 fn hash<H: Hasher>(&self, state: &mut H) {
171 self.span_microseconds().hash(state);
172 }
173}
174
175/// PostgreSQL's text under the default `postgres` `IntervalStyle`, which [`parse_interval`] reads
176/// back except the clock of `i64::MIN` microseconds that PostgreSQL refuses too.
177impl fmt::Display for PgInterval {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 if self.fields_equal(&Self::INFINITY) {
180 return f.write_str("infinity");
181 }
182 if self.fields_equal(&Self::NEG_INFINITY) {
183 return f.write_str("-infinity");
184 }
185 // `INTSTYLE_POSTGRES` marks a positive count that follows a negative one with `+`.
186 let mut is_zero = true;
187 let mut is_before = false;
188 for (count, unit) in [
189 (self.months / 12, "year"),
190 (self.months % 12, "mon"),
191 (self.days, "day"),
192 ] {
193 if count == 0 {
194 continue;
195 }
196 let separator = if is_zero { "" } else { " " };
197 let plus = if is_before && count > 0 { "+" } else { "" };
198 let plural = if count == 1 { "" } else { "s" };
199 write!(f, "{separator}{plus}{count} {unit}{plural}")?;
200 is_before = count < 0;
201 is_zero = false;
202 }
203 if is_zero || self.microseconds != 0 {
204 let separator = if is_zero { "" } else { " " };
205 let sign = if self.microseconds < 0 {
206 "-"
207 } else if is_before {
208 "+"
209 } else {
210 ""
211 };
212 let magnitude = self.microseconds.unsigned_abs();
213 let seconds = magnitude / USECS_PER_SEC;
214 write!(
215 f,
216 "{separator}{sign}{:02}:{:02}:{:02}",
217 seconds / 3_600,
218 seconds % 3_600 / 60,
219 seconds % 60
220 )?;
221 let mut fraction = magnitude % USECS_PER_SEC;
222 if fraction != 0 {
223 let mut digits = 6;
224 while fraction.is_multiple_of(10) {
225 fraction /= 10;
226 digits -= 1;
227 }
228 write!(f, ".{fraction:0digits$}")?;
229 }
230 }
231 Ok(())
232 }
233}
234
235/// The fields an interval type keeps, as in `interval day to second`.
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
237pub enum IntervalFields {
238 /// `YEAR`.
239 Year,
240 /// `MONTH`.
241 Month,
242 /// `DAY`.
243 Day,
244 /// `HOUR`.
245 Hour,
246 /// `MINUTE`.
247 Minute,
248 /// `SECOND`.
249 Second,
250 /// `YEAR TO MONTH`.
251 YearToMonth,
252 /// `DAY TO HOUR`.
253 DayToHour,
254 /// `DAY TO MINUTE`.
255 DayToMinute,
256 /// `DAY TO SECOND`.
257 DayToSecond,
258 /// `HOUR TO MINUTE`.
259 HourToMinute,
260 /// `HOUR TO SECOND`.
261 HourToSecond,
262 /// `MINUTE TO SECOND`.
263 MinuteToSecond,
264}
265
266impl IntervalFields {
267 /// `INTERVAL_MASK` of every field kept.
268 const fn range(self) -> u16 {
269 match self {
270 Self::Year => RANGE_YEAR,
271 Self::Month => RANGE_MONTH,
272 Self::Day => RANGE_DAY,
273 Self::Hour => RANGE_HOUR,
274 Self::Minute => RANGE_MINUTE,
275 Self::Second => RANGE_SECOND,
276 Self::YearToMonth => RANGE_YEAR | RANGE_MONTH,
277 Self::DayToHour => RANGE_DAY | RANGE_HOUR,
278 Self::DayToMinute => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE,
279 Self::DayToSecond => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
280 Self::HourToMinute => RANGE_HOUR | RANGE_MINUTE,
281 Self::HourToSecond => RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
282 Self::MinuteToSecond => RANGE_MINUTE | RANGE_SECOND,
283 }
284 }
285}
286
287/// The modifier of an interval type, the fields it keeps and the fractional-second digits it
288/// rounds to, where the default is plain `interval`.
289#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
290pub struct IntervalTypmod {
291 fields: Option<IntervalFields>,
292 precision: Option<super::TimePrecision>,
293}
294
295impl IntervalTypmod {
296 /// Preserves every field without rounding fractional seconds.
297 pub const UNMODIFIED: Self = Self {
298 fields: None,
299 precision: None,
300 };
301
302 /// The catalog representation of the modifier.
303 pub(crate) fn catalog_typmod(self) -> i32 {
304 if self.fields.is_none() && self.precision.is_none() {
305 -1
306 } else {
307 (i32::from(self.range()) << 16)
308 | self
309 .precision
310 .map_or(0xffff, |precision| i32::from(precision.get()))
311 }
312 }
313
314 /// Decodes a catalog modifier produced by `intervaltypmodin`.
315 pub(crate) fn from_catalog_typmod(typmod: i32) -> Option<Self> {
316 let range = u16::try_from(typmod >> 16).ok()?;
317 let fields = match range {
318 INTERVAL_FULL_RANGE => None,
319 range => Some(
320 [
321 IntervalFields::Year,
322 IntervalFields::Month,
323 IntervalFields::Day,
324 IntervalFields::Hour,
325 IntervalFields::Minute,
326 IntervalFields::Second,
327 IntervalFields::YearToMonth,
328 IntervalFields::DayToHour,
329 IntervalFields::DayToMinute,
330 IntervalFields::DayToSecond,
331 IntervalFields::HourToMinute,
332 IntervalFields::HourToSecond,
333 IntervalFields::MinuteToSecond,
334 ]
335 .into_iter()
336 .find(|fields| fields.range() == range)?,
337 ),
338 };
339 let precision = match typmod & 0xffff {
340 0xffff => None,
341 precision => Some(u8::try_from(precision).ok()?),
342 };
343 let modifier = Self::new(fields, precision)?;
344 (modifier.catalog_typmod() == typmod).then_some(modifier)
345 }
346
347 /// `intervaltypmodin`, clamping a precision above six independently of the fields.
348 ///
349 /// ```
350 /// use sql_values::postgres::{IntervalFields, IntervalTypmod};
351 ///
352 /// assert!(IntervalTypmod::new(Some(IntervalFields::DayToSecond), Some(3)).is_some());
353 /// assert!(IntervalTypmod::new(None, Some(3)).is_some());
354 /// assert!(IntervalTypmod::new(Some(IntervalFields::Minute), Some(3)).is_some());
355 /// ```
356 #[must_use]
357 pub const fn new(fields: Option<IntervalFields>, precision: Option<u8>) -> Option<Self> {
358 let precision = match precision {
359 Some(precision) => Some(super::TimePrecision::new(precision)),
360 None => None,
361 };
362 Some(Self { fields, precision })
363 }
364
365 const fn range(self) -> u16 {
366 match self.fields {
367 Some(fields) => fields.range(),
368 None => INTERVAL_FULL_RANGE,
369 }
370 }
371}
372
373impl fmt::Display for IntervalTypmod {
374 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
375 if let Some(fields) = self.fields {
376 formatter.write_str(match fields {
377 IntervalFields::Year => " year",
378 IntervalFields::Month => " month",
379 IntervalFields::Day => " day",
380 IntervalFields::Hour => " hour",
381 IntervalFields::Minute => " minute",
382 IntervalFields::Second => " second",
383 IntervalFields::YearToMonth => " year to month",
384 IntervalFields::DayToHour => " day to hour",
385 IntervalFields::DayToMinute => " day to minute",
386 IntervalFields::DayToSecond => " day to second",
387 IntervalFields::HourToMinute => " hour to minute",
388 IntervalFields::HourToSecond => " hour to second",
389 IntervalFields::MinuteToSecond => " minute to second",
390 })?;
391 }
392 if let Some(precision) = self.precision {
393 write!(formatter, "({precision})")?;
394 }
395 Ok(())
396 }
397}
398
399/// Parse an interval as PostgreSQL 18's `interval_in` reads it under the default `IntervalStyle`.
400///
401/// # Errors
402///
403/// The [`IntervalError`] PostgreSQL raises: [`IntervalError::InvalidSyntax`] for text it cannot
404/// read, [`IntervalError::FieldValueOutOfRange`] for a number beyond its field and
405/// [`IntervalError::OutOfRange`] for years and months beyond the type.
406///
407/// ```
408/// use sql_values::postgres::{IntervalError, PgInterval, parse_interval};
409///
410/// let interval = parse_interval("-1 days +02:00:00").unwrap();
411/// assert_eq!(
412/// (interval.months, interval.days, interval.microseconds),
413/// (0, -1, 7_200_000_000),
414/// );
415/// assert_eq!(parse_interval("1.5 days").unwrap().to_string(), "1 day 12:00:00");
416/// assert_eq!(parse_interval("@ 1 hour ago").unwrap().to_string(), "-01:00:00");
417/// assert_eq!(parse_interval("P-.5D").unwrap().to_string(), "-12:00:00");
418/// assert_eq!(parse_interval("-infinity"), Ok(PgInterval::NEG_INFINITY));
419/// assert_eq!(parse_interval("p1d"), Err(IntervalError::InvalidSyntax));
420/// assert_eq!(
421/// parse_interval("P1000000000000000D"),
422/// Err(IntervalError::FieldValueOutOfRange),
423/// );
424/// assert_eq!(parse_interval("178956971 years"), Err(IntervalError::OutOfRange));
425/// ```
426pub fn parse_interval(text: &str) -> Result<PgInterval, IntervalError> {
427 interval_in(text, INTERVAL_FULL_RANGE, None)
428}
429
430/// Parse an interval literal of a restricted type as `interval '…' <fields>` reads it, which
431/// differs from casting a text value to that type.
432///
433/// # Errors
434///
435/// The [`IntervalError`] PostgreSQL raises, as for [`parse_interval`], where rounding the
436/// seconds to the typmod's precision can also leave the type, [`IntervalError::OutOfRange`].
437///
438/// ```
439/// use sql_values::postgres::{
440/// IntervalError, IntervalFields, IntervalTypmod, parse_interval, parse_interval_typmod,
441/// };
442///
443/// let minute = IntervalTypmod::new(Some(IntervalFields::Minute), None).unwrap();
444/// assert_eq!(parse_interval_typmod("90", minute).unwrap().to_string(), "01:30:00");
445///
446/// let to_second = IntervalTypmod::new(Some(IntervalFields::MinuteToSecond), Some(0)).unwrap();
447/// assert_eq!(parse_interval_typmod("1:30.5", to_second).unwrap().to_string(), "00:01:31");
448/// assert_eq!(
449/// parse_interval_typmod("9223372036854775807 usecs", to_second),
450/// Err(IntervalError::OutOfRange),
451/// );
452///
453/// let hour = IntervalTypmod::new(Some(IntervalFields::Hour), None).unwrap();
454/// assert_eq!(parse_interval_typmod("3 4", hour).unwrap().to_string(), "3 days 04:00:00");
455/// assert_eq!(parse_interval("3 4"), Err(IntervalError::InvalidSyntax));
456/// ```
457pub fn parse_interval_typmod(
458 text: &str,
459 typmod: IntervalTypmod,
460) -> Result<PgInterval, IntervalError> {
461 interval_in(
462 text,
463 typmod.range(),
464 typmod.precision.map(super::TimePrecision::get),
465 )
466}