sql_values/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};
14pub(crate) use decode::strtod;
15use decode::{
16 INTERVAL_FULL_RANGE, RANGE_DAY, RANGE_HOUR, RANGE_MINUTE, RANGE_MONTH, RANGE_SECOND,
17 RANGE_YEAR, interval_in,
18};
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::{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::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::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
98/// Why PostgreSQL refuses to read an interval or to compute one, one variant per message it
99/// raises.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
101pub enum IntervalError {
102 /// Text `interval_in` cannot read.
103 #[error("invalid input syntax for type interval")]
104 InvalidSyntax,
105 /// A number of the text beyond the integer its field accumulates in.
106 #[error("interval field value out of range")]
107 FieldValueOutOfRange,
108 /// A value beyond the type, or arithmetic PostgreSQL has no answer for.
109 #[error("interval out of range")]
110 OutOfRange,
111 /// An interval divided by zero.
112 #[error("division by zero")]
113 DivisionByZero,
114}
115
116impl PartialEq for PgInterval {
117 fn eq(&self, other: &Self) -> bool {
118 self.span_microseconds() == other.span_microseconds()
119 }
120}
121
122impl Eq for PgInterval {}
123
124impl PartialOrd for PgInterval {
125 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
126 Some(self.cmp(other))
127 }
128}
129
130impl Ord for PgInterval {
131 fn cmp(&self, other: &Self) -> Ordering {
132 self.span_microseconds().cmp(&other.span_microseconds())
133 }
134}
135
136impl Hash for PgInterval {
137 fn hash<H: Hasher>(&self, state: &mut H) {
138 self.span_microseconds().hash(state);
139 }
140}
141
142/// PostgreSQL's text under the default `postgres` `IntervalStyle`, which [`parse_interval`] reads
143/// back except the clock of `i64::MIN` microseconds that PostgreSQL refuses too.
144impl fmt::Display for PgInterval {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 if self.fields_equal(&Self::INFINITY) {
147 return f.write_str("infinity");
148 }
149 if self.fields_equal(&Self::NEG_INFINITY) {
150 return f.write_str("-infinity");
151 }
152 // `INTSTYLE_POSTGRES` marks a positive count that follows a negative one with `+`.
153 let mut is_zero = true;
154 let mut is_before = false;
155 for (count, unit) in [
156 (self.months / 12, "year"),
157 (self.months % 12, "mon"),
158 (self.days, "day"),
159 ] {
160 if count == 0 {
161 continue;
162 }
163 let separator = if is_zero { "" } else { " " };
164 let plus = if is_before && count > 0 { "+" } else { "" };
165 let plural = if count == 1 { "" } else { "s" };
166 write!(f, "{separator}{plus}{count} {unit}{plural}")?;
167 is_before = count < 0;
168 is_zero = false;
169 }
170 if is_zero || self.microseconds != 0 {
171 let separator = if is_zero { "" } else { " " };
172 let sign = if self.microseconds < 0 {
173 "-"
174 } else if is_before {
175 "+"
176 } else {
177 ""
178 };
179 let magnitude = self.microseconds.unsigned_abs();
180 let seconds = magnitude / USECS_PER_SEC;
181 write!(
182 f,
183 "{separator}{sign}{:02}:{:02}:{:02}",
184 seconds / 3_600,
185 seconds % 3_600 / 60,
186 seconds % 60
187 )?;
188 let mut fraction = magnitude % USECS_PER_SEC;
189 if fraction != 0 {
190 let mut digits = 6;
191 while fraction.is_multiple_of(10) {
192 fraction /= 10;
193 digits -= 1;
194 }
195 write!(f, ".{fraction:0digits$}")?;
196 }
197 }
198 Ok(())
199 }
200}
201
202/// The fields an interval type keeps, as in `interval day to second`.
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
204pub enum IntervalFields {
205 /// `YEAR`.
206 Year,
207 /// `MONTH`.
208 Month,
209 /// `DAY`.
210 Day,
211 /// `HOUR`.
212 Hour,
213 /// `MINUTE`.
214 Minute,
215 /// `SECOND`.
216 Second,
217 /// `YEAR TO MONTH`.
218 YearToMonth,
219 /// `DAY TO HOUR`.
220 DayToHour,
221 /// `DAY TO MINUTE`.
222 DayToMinute,
223 /// `DAY TO SECOND`.
224 DayToSecond,
225 /// `HOUR TO MINUTE`.
226 HourToMinute,
227 /// `HOUR TO SECOND`.
228 HourToSecond,
229 /// `MINUTE TO SECOND`.
230 MinuteToSecond,
231}
232
233impl IntervalFields {
234 /// `INTERVAL_MASK` of every field kept.
235 const fn range(self) -> u16 {
236 match self {
237 Self::Year => RANGE_YEAR,
238 Self::Month => RANGE_MONTH,
239 Self::Day => RANGE_DAY,
240 Self::Hour => RANGE_HOUR,
241 Self::Minute => RANGE_MINUTE,
242 Self::Second => RANGE_SECOND,
243 Self::YearToMonth => RANGE_YEAR | RANGE_MONTH,
244 Self::DayToHour => RANGE_DAY | RANGE_HOUR,
245 Self::DayToMinute => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE,
246 Self::DayToSecond => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
247 Self::HourToMinute => RANGE_HOUR | RANGE_MINUTE,
248 Self::HourToSecond => RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
249 Self::MinuteToSecond => RANGE_MINUTE | RANGE_SECOND,
250 }
251 }
252
253 /// Whether a precision may follow, which only `SECOND` allows.
254 const fn ends_in_second(self) -> bool {
255 matches!(
256 self,
257 Self::Second | Self::DayToSecond | Self::HourToSecond | Self::MinuteToSecond
258 )
259 }
260}
261
262/// The modifier of an interval type, the fields it keeps and the fractional-second digits it
263/// rounds to, where the default is plain `interval`.
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
265pub struct IntervalTypmod {
266 fields: Option<IntervalFields>,
267 precision: Option<u8>,
268}
269
270/// The most fractional-second digits an interval keeps.
271const MAX_INTERVAL_PRECISION: u8 = 6;
272
273impl IntervalTypmod {
274 /// `intervaltypmodin`, clamping a precision above six as PostgreSQL does, or `None` for a
275 /// precision after fields not ending in `SECOND`.
276 ///
277 /// ```
278 /// use sql_values::{IntervalFields, IntervalTypmod};
279 ///
280 /// assert!(IntervalTypmod::new(Some(IntervalFields::DayToSecond), Some(3)).is_some());
281 /// assert!(IntervalTypmod::new(None, Some(3)).is_some());
282 /// assert!(IntervalTypmod::new(Some(IntervalFields::Minute), Some(3)).is_none());
283 /// ```
284 #[must_use]
285 pub const fn new(fields: Option<IntervalFields>, precision: Option<u8>) -> Option<Self> {
286 let precision = match (fields, precision) {
287 (Some(fields), Some(_)) if !fields.ends_in_second() => return None,
288 (_, Some(precision)) if precision > MAX_INTERVAL_PRECISION => {
289 Some(MAX_INTERVAL_PRECISION)
290 }
291 (_, precision) => precision,
292 };
293 Some(Self { fields, precision })
294 }
295
296 const fn range(self) -> u16 {
297 match self.fields {
298 Some(fields) => fields.range(),
299 None => INTERVAL_FULL_RANGE,
300 }
301 }
302}
303
304/// Parse an interval as PostgreSQL 18's `interval_in` reads it under the default `IntervalStyle`.
305///
306/// # Errors
307///
308/// The [`IntervalError`] PostgreSQL raises: [`IntervalError::InvalidSyntax`] for text it cannot
309/// read, [`IntervalError::FieldValueOutOfRange`] for a number beyond its field and
310/// [`IntervalError::OutOfRange`] for years and months beyond the type.
311///
312/// ```
313/// use sql_values::{IntervalError, PgInterval, parse_interval};
314///
315/// let interval = parse_interval("-1 days +02:00:00").unwrap();
316/// assert_eq!(
317/// (interval.months, interval.days, interval.microseconds),
318/// (0, -1, 7_200_000_000),
319/// );
320/// assert_eq!(parse_interval("1.5 days").unwrap().to_string(), "1 day 12:00:00");
321/// assert_eq!(parse_interval("@ 1 hour ago").unwrap().to_string(), "-01:00:00");
322/// assert_eq!(parse_interval("P-.5D").unwrap().to_string(), "-12:00:00");
323/// assert_eq!(parse_interval("-infinity"), Ok(PgInterval::NEG_INFINITY));
324/// assert_eq!(parse_interval("p1d"), Err(IntervalError::InvalidSyntax));
325/// assert_eq!(
326/// parse_interval("P1000000000000000D"),
327/// Err(IntervalError::FieldValueOutOfRange),
328/// );
329/// assert_eq!(parse_interval("178956971 years"), Err(IntervalError::OutOfRange));
330/// ```
331pub fn parse_interval(text: &str) -> Result<PgInterval, IntervalError> {
332 interval_in(text, INTERVAL_FULL_RANGE, None)
333}
334
335/// Parse an interval literal of a restricted type as `interval '…' <fields>` reads it, which
336/// differs from casting a text value to that type.
337///
338/// # Errors
339///
340/// The [`IntervalError`] PostgreSQL raises, as for [`parse_interval`], where rounding the
341/// seconds to the typmod's precision can also leave the type, [`IntervalError::OutOfRange`].
342///
343/// ```
344/// use sql_values::{
345/// IntervalError, IntervalFields, IntervalTypmod, parse_interval, parse_interval_typmod,
346/// };
347///
348/// let minute = IntervalTypmod::new(Some(IntervalFields::Minute), None).unwrap();
349/// assert_eq!(parse_interval_typmod("90", minute).unwrap().to_string(), "01:30:00");
350///
351/// let to_second = IntervalTypmod::new(Some(IntervalFields::MinuteToSecond), Some(0)).unwrap();
352/// assert_eq!(parse_interval_typmod("1:30.5", to_second).unwrap().to_string(), "00:01:31");
353/// assert_eq!(
354/// parse_interval_typmod("9223372036854775807 usecs", to_second),
355/// Err(IntervalError::OutOfRange),
356/// );
357///
358/// let hour = IntervalTypmod::new(Some(IntervalFields::Hour), None).unwrap();
359/// assert_eq!(parse_interval_typmod("3 4", hour).unwrap().to_string(), "3 days 04:00:00");
360/// assert_eq!(parse_interval("3 4"), Err(IntervalError::InvalidSyntax));
361/// ```
362pub fn parse_interval_typmod(
363 text: &str,
364 typmod: IntervalTypmod,
365) -> Result<PgInterval, IntervalError> {
366 interval_in(text, typmod.range(), typmod.precision)
367}