sql-values 0.8.0

SQL values, with PostgreSQL's value rules beside readers of the text PostgreSQL, MySQL and SQLite emit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! PostgreSQL `interval` values read by `interval_in`, printed by `interval_out`, compared by
//! `interval_cmp` and combined by PostgreSQL's interval arithmetic.

mod arithmetic;
mod decode;

use core::{
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
};

pub use arithmetic::{IntervalSum, ShiftError};
use decode::{
    INTERVAL_FULL_RANGE, RANGE_DAY, RANGE_HOUR, RANGE_MINUTE, RANGE_MONTH, RANGE_SECOND,
    RANGE_YEAR, adjust_interval_for_typmod, interval_in,
};
pub(crate) use decode::{decode_extract_unit, decode_units, strtod};

const USECS_PER_DAY: i128 = 86_400_000_000;
const USECS_PER_SEC: u64 = 1_000_000;
const DAYS_PER_MONTH: i64 = 30;

/// A PostgreSQL `interval` as months, days and microseconds, equal, ordered and hashed by
/// PostgreSQL's span with a month as 30 days and a day as 24 hours.
///
/// ```
/// use sql_values::postgres::{PgInterval, parse_interval};
///
/// let month = parse_interval("1 mon").unwrap();
/// let thirty_days = parse_interval("30 days").unwrap();
/// assert_eq!(month, thirty_days);
/// assert_ne!(month.to_string(), thirty_days.to_string());
/// assert!(parse_interval("infinity").unwrap() > month);
/// assert_eq!(PgInterval::NEG_INFINITY.to_string(), "-infinity");
/// ```
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PgInterval {
    /// Months, twelve of which print as a year.
    pub months: i32,
    /// Days, never folded into months.
    pub days: i32,
    /// Microseconds, never folded into days.
    pub microseconds: i64,
}

impl PgInterval {
    /// `infinity`, PostgreSQL's `INTERVAL_NOEND`, above every finite interval.
    pub const INFINITY: Self = Self {
        months: i32::MAX,
        days: i32::MAX,
        microseconds: i64::MAX,
    };

    /// `-infinity`, PostgreSQL's `INTERVAL_NOBEGIN`, below every finite interval.
    pub const NEG_INFINITY: Self = Self {
        months: i32::MIN,
        days: i32::MIN,
        microseconds: i64::MIN,
    };

    /// Whether the interval is neither `infinity` nor `-infinity`.
    ///
    /// ```
    /// use sql_values::postgres::PgInterval;
    ///
    /// assert!(!PgInterval::INFINITY.is_finite());
    /// assert!(PgInterval { months: i32::MAX, days: i32::MAX, microseconds: 0 }.is_finite());
    /// ```
    #[must_use]
    pub const fn is_finite(&self) -> bool {
        !self.fields_equal(&Self::INFINITY) && !self.fields_equal(&Self::NEG_INFINITY)
    }

    const fn fields_equal(&self, other: &Self) -> bool {
        self.months == other.months
            && self.days == other.days
            && self.microseconds == other.microseconds
    }

    /// PostgreSQL's `interval_cmp_value`, the span in microseconds with a month as 30 days and a
    /// day as 24 hours, which orders, equates and hashes the interval.
    ///
    /// ```
    /// use sql_values::postgres::parse_interval;
    ///
    /// let month = parse_interval("1 mon -1 days").unwrap();
    /// assert_eq!(month.span_microseconds(), 29 * 86_400_000_000);
    /// ```
    #[must_use]
    pub fn span_microseconds(&self) -> i128 {
        let days = i64::from(self.months) * DAYS_PER_MONTH + i64::from(self.days);
        i128::from(self.microseconds) + i128::from(days) * USECS_PER_DAY
    }

    /// `interval_scale`, the length coercion of an interval type, which truncates the interval
    /// below the last field the typmod keeps and rounds its seconds, half away from zero, to the
    /// typmod's precision. An infinity is kept.
    ///
    /// # Errors
    ///
    /// [`IntervalError::OutOfRange`] when rounding the seconds leaves the type.
    ///
    /// ```
    /// use sql_values::postgres::{
    ///     IntervalError, IntervalFields, IntervalTypmod, PgInterval, parse_interval,
    /// };
    ///
    /// let hour = IntervalTypmod::new(Some(IntervalFields::Hour), None).unwrap();
    /// let span = parse_interval("1 day 01:30:00").unwrap();
    /// assert_eq!(span.adjust_for_typmod(hour).unwrap().to_string(), "1 day 01:00:00");
    /// assert_eq!(PgInterval::INFINITY.adjust_for_typmod(hour), Ok(PgInterval::INFINITY));
    ///
    /// let whole = IntervalTypmod::new(None, Some(0)).unwrap();
    /// let span = parse_interval("-00:00:01.5").unwrap();
    /// assert_eq!(span.adjust_for_typmod(whole).unwrap().to_string(), "-00:00:02");
    /// let last = PgInterval { months: 0, days: 0, microseconds: i64::MAX - 1 };
    /// assert_eq!(last.adjust_for_typmod(whole), Err(IntervalError::OutOfRange));
    /// ```
    pub fn adjust_for_typmod(mut self, typmod: IntervalTypmod) -> Result<Self, IntervalError> {
        adjust_interval_for_typmod(
            &mut self,
            typmod.range(),
            typmod.precision.map(super::TimePrecision::get),
        )?;
        Ok(self)
    }
}

/// Why PostgreSQL refuses to read an interval or to compute one, one variant per message it
/// raises.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
pub enum IntervalError {
    /// Text `interval_in` cannot read.
    #[error("invalid input syntax for type interval")]
    InvalidSyntax,
    /// A number of the text beyond the integer its field accumulates in.
    #[error("interval field value out of range")]
    FieldValueOutOfRange,
    /// A value beyond the type, or arithmetic PostgreSQL has no answer for.
    #[error("interval out of range")]
    OutOfRange,
    /// An interval divided by zero.
    #[error("division by zero")]
    DivisionByZero,
}

impl PartialEq for PgInterval {
    fn eq(&self, other: &Self) -> bool {
        self.span_microseconds() == other.span_microseconds()
    }
}

impl Eq for PgInterval {}

impl PartialOrd for PgInterval {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for PgInterval {
    fn cmp(&self, other: &Self) -> Ordering {
        self.span_microseconds().cmp(&other.span_microseconds())
    }
}

impl Hash for PgInterval {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.span_microseconds().hash(state);
    }
}

/// PostgreSQL's text under the default `postgres` `IntervalStyle`, which [`parse_interval`] reads
/// back except the clock of `i64::MIN` microseconds that PostgreSQL refuses too.
impl fmt::Display for PgInterval {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.fields_equal(&Self::INFINITY) {
            return f.write_str("infinity");
        }
        if self.fields_equal(&Self::NEG_INFINITY) {
            return f.write_str("-infinity");
        }
        // `INTSTYLE_POSTGRES` marks a positive count that follows a negative one with `+`.
        let mut is_zero = true;
        let mut is_before = false;
        for (count, unit) in [
            (self.months / 12, "year"),
            (self.months % 12, "mon"),
            (self.days, "day"),
        ] {
            if count == 0 {
                continue;
            }
            let separator = if is_zero { "" } else { " " };
            let plus = if is_before && count > 0 { "+" } else { "" };
            let plural = if count == 1 { "" } else { "s" };
            write!(f, "{separator}{plus}{count} {unit}{plural}")?;
            is_before = count < 0;
            is_zero = false;
        }
        if is_zero || self.microseconds != 0 {
            let separator = if is_zero { "" } else { " " };
            let sign = if self.microseconds < 0 {
                "-"
            } else if is_before {
                "+"
            } else {
                ""
            };
            let magnitude = self.microseconds.unsigned_abs();
            let seconds = magnitude / USECS_PER_SEC;
            write!(
                f,
                "{separator}{sign}{:02}:{:02}:{:02}",
                seconds / 3_600,
                seconds % 3_600 / 60,
                seconds % 60
            )?;
            let mut fraction = magnitude % USECS_PER_SEC;
            if fraction != 0 {
                let mut digits = 6;
                while fraction.is_multiple_of(10) {
                    fraction /= 10;
                    digits -= 1;
                }
                write!(f, ".{fraction:0digits$}")?;
            }
        }
        Ok(())
    }
}

/// The fields an interval type keeps, as in `interval day to second`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntervalFields {
    /// `YEAR`.
    Year,
    /// `MONTH`.
    Month,
    /// `DAY`.
    Day,
    /// `HOUR`.
    Hour,
    /// `MINUTE`.
    Minute,
    /// `SECOND`.
    Second,
    /// `YEAR TO MONTH`.
    YearToMonth,
    /// `DAY TO HOUR`.
    DayToHour,
    /// `DAY TO MINUTE`.
    DayToMinute,
    /// `DAY TO SECOND`.
    DayToSecond,
    /// `HOUR TO MINUTE`.
    HourToMinute,
    /// `HOUR TO SECOND`.
    HourToSecond,
    /// `MINUTE TO SECOND`.
    MinuteToSecond,
}

impl IntervalFields {
    /// `INTERVAL_MASK` of every field kept.
    const fn range(self) -> u16 {
        match self {
            Self::Year => RANGE_YEAR,
            Self::Month => RANGE_MONTH,
            Self::Day => RANGE_DAY,
            Self::Hour => RANGE_HOUR,
            Self::Minute => RANGE_MINUTE,
            Self::Second => RANGE_SECOND,
            Self::YearToMonth => RANGE_YEAR | RANGE_MONTH,
            Self::DayToHour => RANGE_DAY | RANGE_HOUR,
            Self::DayToMinute => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE,
            Self::DayToSecond => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
            Self::HourToMinute => RANGE_HOUR | RANGE_MINUTE,
            Self::HourToSecond => RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
            Self::MinuteToSecond => RANGE_MINUTE | RANGE_SECOND,
        }
    }
}

/// The modifier of an interval type, the fields it keeps and the fractional-second digits it
/// rounds to, where the default is plain `interval`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct IntervalTypmod {
    fields: Option<IntervalFields>,
    precision: Option<super::TimePrecision>,
}

impl IntervalTypmod {
    /// Preserves every field without rounding fractional seconds.
    pub const UNMODIFIED: Self = Self {
        fields: None,
        precision: None,
    };

    /// The catalog representation of the modifier.
    pub(crate) fn catalog_typmod(self) -> i32 {
        if self.fields.is_none() && self.precision.is_none() {
            -1
        } else {
            (i32::from(self.range()) << 16)
                | self
                    .precision
                    .map_or(0xffff, |precision| i32::from(precision.get()))
        }
    }

    /// Decodes a catalog modifier produced by `intervaltypmodin`.
    pub(crate) fn from_catalog_typmod(typmod: i32) -> Option<Self> {
        let range = u16::try_from(typmod >> 16).ok()?;
        let fields = match range {
            INTERVAL_FULL_RANGE => None,
            range => Some(
                [
                    IntervalFields::Year,
                    IntervalFields::Month,
                    IntervalFields::Day,
                    IntervalFields::Hour,
                    IntervalFields::Minute,
                    IntervalFields::Second,
                    IntervalFields::YearToMonth,
                    IntervalFields::DayToHour,
                    IntervalFields::DayToMinute,
                    IntervalFields::DayToSecond,
                    IntervalFields::HourToMinute,
                    IntervalFields::HourToSecond,
                    IntervalFields::MinuteToSecond,
                ]
                .into_iter()
                .find(|fields| fields.range() == range)?,
            ),
        };
        let precision = match typmod & 0xffff {
            0xffff => None,
            precision => Some(u8::try_from(precision).ok()?),
        };
        let modifier = Self::new(fields, precision)?;
        (modifier.catalog_typmod() == typmod).then_some(modifier)
    }

    /// `intervaltypmodin`, clamping a precision above six independently of the fields.
    ///
    /// ```
    /// use sql_values::postgres::{IntervalFields, IntervalTypmod};
    ///
    /// assert!(IntervalTypmod::new(Some(IntervalFields::DayToSecond), Some(3)).is_some());
    /// assert!(IntervalTypmod::new(None, Some(3)).is_some());
    /// assert!(IntervalTypmod::new(Some(IntervalFields::Minute), Some(3)).is_some());
    /// ```
    #[must_use]
    pub const fn new(fields: Option<IntervalFields>, precision: Option<u8>) -> Option<Self> {
        let precision = match precision {
            Some(precision) => Some(super::TimePrecision::new(precision)),
            None => None,
        };
        Some(Self { fields, precision })
    }

    const fn range(self) -> u16 {
        match self.fields {
            Some(fields) => fields.range(),
            None => INTERVAL_FULL_RANGE,
        }
    }
}

impl fmt::Display for IntervalTypmod {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(fields) = self.fields {
            formatter.write_str(match fields {
                IntervalFields::Year => " year",
                IntervalFields::Month => " month",
                IntervalFields::Day => " day",
                IntervalFields::Hour => " hour",
                IntervalFields::Minute => " minute",
                IntervalFields::Second => " second",
                IntervalFields::YearToMonth => " year to month",
                IntervalFields::DayToHour => " day to hour",
                IntervalFields::DayToMinute => " day to minute",
                IntervalFields::DayToSecond => " day to second",
                IntervalFields::HourToMinute => " hour to minute",
                IntervalFields::HourToSecond => " hour to second",
                IntervalFields::MinuteToSecond => " minute to second",
            })?;
        }
        if let Some(precision) = self.precision {
            write!(formatter, "({precision})")?;
        }
        Ok(())
    }
}

/// Parse an interval as PostgreSQL 18's `interval_in` reads it under the default `IntervalStyle`.
///
/// # Errors
///
/// The [`IntervalError`] PostgreSQL raises: [`IntervalError::InvalidSyntax`] for text it cannot
/// read, [`IntervalError::FieldValueOutOfRange`] for a number beyond its field and
/// [`IntervalError::OutOfRange`] for years and months beyond the type.
///
/// ```
/// use sql_values::postgres::{IntervalError, PgInterval, parse_interval};
///
/// let interval = parse_interval("-1 days +02:00:00").unwrap();
/// assert_eq!(
///     (interval.months, interval.days, interval.microseconds),
///     (0, -1, 7_200_000_000),
/// );
/// assert_eq!(parse_interval("1.5 days").unwrap().to_string(), "1 day 12:00:00");
/// assert_eq!(parse_interval("@ 1 hour ago").unwrap().to_string(), "-01:00:00");
/// assert_eq!(parse_interval("P-.5D").unwrap().to_string(), "-12:00:00");
/// assert_eq!(parse_interval("-infinity"), Ok(PgInterval::NEG_INFINITY));
/// assert_eq!(parse_interval("p1d"), Err(IntervalError::InvalidSyntax));
/// assert_eq!(
///     parse_interval("P1000000000000000D"),
///     Err(IntervalError::FieldValueOutOfRange),
/// );
/// assert_eq!(parse_interval("178956971 years"), Err(IntervalError::OutOfRange));
/// ```
pub fn parse_interval(text: &str) -> Result<PgInterval, IntervalError> {
    interval_in(text, INTERVAL_FULL_RANGE, None)
}

/// Parse an interval literal of a restricted type as `interval '…' <fields>` reads it, which
/// differs from casting a text value to that type.
///
/// # Errors
///
/// The [`IntervalError`] PostgreSQL raises, as for [`parse_interval`], where rounding the
/// seconds to the typmod's precision can also leave the type, [`IntervalError::OutOfRange`].
///
/// ```
/// use sql_values::postgres::{
///     IntervalError, IntervalFields, IntervalTypmod, parse_interval, parse_interval_typmod,
/// };
///
/// let minute = IntervalTypmod::new(Some(IntervalFields::Minute), None).unwrap();
/// assert_eq!(parse_interval_typmod("90", minute).unwrap().to_string(), "01:30:00");
///
/// let to_second = IntervalTypmod::new(Some(IntervalFields::MinuteToSecond), Some(0)).unwrap();
/// assert_eq!(parse_interval_typmod("1:30.5", to_second).unwrap().to_string(), "00:01:31");
/// assert_eq!(
///     parse_interval_typmod("9223372036854775807 usecs", to_second),
///     Err(IntervalError::OutOfRange),
/// );
///
/// let hour = IntervalTypmod::new(Some(IntervalFields::Hour), None).unwrap();
/// assert_eq!(parse_interval_typmod("3 4", hour).unwrap().to_string(), "3 days 04:00:00");
/// assert_eq!(parse_interval("3 4"), Err(IntervalError::InvalidSyntax));
/// ```
pub fn parse_interval_typmod(
    text: &str,
    typmod: IntervalTypmod,
) -> Result<PgInterval, IntervalError> {
    interval_in(
        text,
        typmod.range(),
        typmod.precision.map(super::TimePrecision::get),
    )
}