Skip to main content

PgInterval

Struct PgInterval 

Source
pub struct PgInterval {
    pub months: i32,
    pub days: i32,
    pub microseconds: i64,
}
Expand description

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");

Fields§

§months: i32

Months, twelve of which print as a year.

§days: i32

Days, never folded into months.

§microseconds: i64

Microseconds, never folded into days.

Implementations§

Source§

impl PgInterval

Source

pub fn date_trunc(self, field: DateTruncField) -> Result<Self, DateTruncError>

PostgreSQL’s date_trunc(field, interval), every field finer than field reset, each toward zero, where a year is twelve months and a month never folds into days. An infinity is left as it is.

§Errors

DateTruncError::UnitNotSupported for DateTruncField::Week, since a month holds no whole number of weeks, infinities included.

use sql_values::postgres::{DateTruncError, DateTruncField, parse_interval};

let span = parse_interval("-14 months -3 days -25:02:03.123500").unwrap();
let truncated = span.date_trunc(DateTruncField::Milliseconds).unwrap();
assert_eq!(truncated.to_string(), "-1 years -2 mons -3 days -25:02:03.123");
let quarter = span.date_trunc(DateTruncField::Quarter).unwrap();
assert_eq!(quarter.to_string(), "-1 years");
assert_eq!(span.date_trunc(DateTruncField::Week), Err(DateTruncError::UnitNotSupported));
Source§

impl PgInterval

Source

pub fn to_char( self, template: &str, ) -> Result<Option<String>, TemporalFormatError>

PostgreSQL’s to_char(interval, text) under lc_time C, or None, PostgreSQL’s SQL NULL, for an empty template or an infinite interval.

Years are the months over twelve and months the rest, days and the clock are printed as they are held, each truncated toward zero with its sign, and DDD approximates the whole span in days with a month as 30.

§Errors

TemporalFormatError::InvalidForInterval for a template naming a weekday, a month or day name, an era or a zone field.

use sql_values::postgres::{TemporalFormatError, parse_interval};

let span = parse_interval("1 year 2 months 3 days 25 hours 4 minutes 5.123456 seconds").unwrap();
assert_eq!(
    span.to_char("YYYY MM DD HH24 HH12 MI SS US").unwrap().as_deref(),
    Some("0001 02 03 25 01 04 05 123456"),
);
let negative = parse_interval("-1 year -2 months -3 days -25 hours").unwrap();
assert_eq!(
    negative.to_char("YYYY MM DD HH24 HH12").unwrap().as_deref(),
    Some("-0001 -02 -3 -25 -01"),
);
assert_eq!(span.to_char("IYYY IW ID"), Err(TemporalFormatError::InvalidForInterval));
Source§

impl PgInterval

Source

pub fn extract( self, field: ExtractField, ) -> Result<Option<PgNumeric>, ExtractError>

PostgreSQL’s extract(field FROM interval), each field of the months, days and time split toward zero, and epoch with a year as 365.25 days and a month as 30. An infinite interval has the infinity of its sign in hour, day, the year fields and epoch, and None, SQL NULL, in the others.

§Errors

ExtractError::UnsupportedField for a field of a day of the calendar or a zone.

use sql_values::postgres::{ExtractField, PgNumeric, parse_interval};

let interval = parse_interval("-14 months -3 days -25:02:03.123456").unwrap();
let epoch = interval.extract(ExtractField::Epoch).unwrap().unwrap();
assert_eq!(epoch.to_string(), "-37090923.123456");
assert_eq!(interval.extract(ExtractField::Quarter).unwrap(), Some(PgNumeric::from(-1)));
Source

pub fn date_part( self, field: ExtractField, ) -> Result<Option<PgFloat8>, ExtractError>

PostgreSQL’s date_part(field, interval).

§Errors

ExtractError::UnsupportedField for a field of a day of the calendar or a zone.

Source§

impl PgInterval

Source

pub fn checked_add(self, other: Self) -> Result<Self, IntervalError>

PostgreSQL’s interval_pl, self + other.

§Errors

IntervalError::OutOfRange where a field overflows, the sum spells an infinity, or opposite infinities meet.

use sql_values::postgres::{IntervalError, PgInterval, parse_interval};

let day = parse_interval("1 day").unwrap();
let hour = parse_interval("-01:00:00").unwrap();
assert_eq!(day.checked_add(hour).unwrap().to_string(), "1 day -01:00:00");
assert_eq!(
    PgInterval::INFINITY.checked_add(PgInterval::NEG_INFINITY),
    Err(IntervalError::OutOfRange),
);
Source

pub fn checked_sub(self, other: Self) -> Result<Self, IntervalError>

PostgreSQL’s interval_mi, self - other.

§Errors

IntervalError::OutOfRange where a field overflows, the difference spells an infinity, or like infinities meet.

Source

pub fn checked_neg(self) -> Result<Self, IntervalError>

PostgreSQL’s interval_um, -self.

§Errors

IntervalError::OutOfRange where a field sits at its minimum, or the negation spells an infinity.

use sql_values::postgres::{IntervalError, parse_interval};

let span = parse_interval("1 mon -2 days").unwrap();
assert_eq!(span.checked_neg().unwrap().to_string(), "-1 mons +2 days");
let minimum = parse_interval("-2147483648 days").unwrap();
assert_eq!(minimum.checked_neg(), Err(IntervalError::OutOfRange));
Source

pub fn checked_mul(self, factor: f64) -> Result<Self, IntervalError>

PostgreSQL’s interval_mul, self * factor.

Months and days scale apart, what a month leaves over cascades into days as 30 and what a day leaves over into the clock as 24 hours, each rounded to the microsecond as PostgreSQL rounds it.

§Errors

IntervalError::OutOfRange for a NaN factor, zero against an infinity, an infinite factor against a zero interval, and a product beyond the type.

use sql_values::postgres::{IntervalError, PgInterval, parse_interval};

let month = parse_interval("1 mon 1 day").unwrap();
assert_eq!(month.checked_mul(1.5).unwrap().to_string(), "1 mon 16 days 12:00:00");
assert_eq!(month.checked_mul(f64::INFINITY), Ok(PgInterval::INFINITY));
assert_eq!(month.checked_mul(f64::NAN), Err(IntervalError::OutOfRange));
Source

pub fn checked_div(self, factor: f64) -> Result<Self, IntervalError>

PostgreSQL’s interval_div, self / factor, cascading as checked_mul does.

§Errors

IntervalError::DivisionByZero for a zero factor, and IntervalError::OutOfRange for a NaN factor, an infinity divided by an infinity, and a quotient beyond the type.

use sql_values::postgres::{IntervalError, parse_interval};

let span = parse_interval("1 mon 1 day 00:00:01").unwrap();
assert_eq!(span.checked_div(7.0).unwrap().to_string(), "4 days 10:17:08.6896");
assert_eq!(span.checked_div(f64::INFINITY).unwrap().to_string(), "00:00:00");
assert_eq!(span.checked_div(0.0), Err(IntervalError::DivisionByZero));
Source

pub fn add_to_timestamp( self, at: PgTimestamp, ) -> Result<PgTimestamp, ShiftError>

PostgreSQL’s timestamp_pl_interval, at + self: months added to the calendar month with the day clamped to the month’s last, then days added to the calendar day, then the clock. An infinite timestamp or interval gives an infinity.

§Errors

ShiftError::TimestampOutOfRange where a step leaves PostgreSQL’s timestamps, or where opposite infinities meet.

use sql_values::postgres::{parse_interval, parse_timestamp};

let at = parse_timestamp("2024-01-31 10:00:00").unwrap();
let month = parse_interval("1 mon").unwrap();
assert_eq!(month.add_to_timestamp(at).unwrap().to_string(), "2024-02-29 10:00:00");
Source

pub fn subtract_from_timestamp( self, at: PgTimestamp, ) -> Result<PgTimestamp, ShiftError>

PostgreSQL’s timestamp_mi_interval, at - self, which adds the negated interval.

§Errors

ShiftError::IntervalOutOfRange where interval_um refuses the interval, and the errors of add_to_timestamp.

Source

pub fn add_to_timestamptz( self, at: PgTimestampTz, zone: &PgTimeZone, ) -> Result<PgTimestampTz, ShiftError>

PostgreSQL’s timestamptz_pl_interval with zone as the session’s TimeZone, at + self, with months and days added on the zone’s calendar, each step’s local clock resolved as PgTimestamp::to_timestamptz resolves it, then the microseconds added to the instant.

§Errors

The errors of add_to_timestamp.

use sql_values::postgres::{InputContext, PgTimeZone, PgTimestampTz, parse_interval};

#[cfg(feature = "tzdb")]
{
    let rome = PgTimeZone::parse("Europe/Rome").unwrap();
    let at = PgTimestampTz::parse("2026-03-29 12:00:00+02", InputContext::new()).unwrap();
    let day = parse_interval("1 day").unwrap();
    let before = day.subtract_from_timestamptz(at, &rome).unwrap();
    assert_eq!(before.to_string(), "2026-03-28 11:00:00+00");
}
Source

pub fn subtract_from_timestamptz( self, at: PgTimestampTz, zone: &PgTimeZone, ) -> Result<PgTimestampTz, ShiftError>

PostgreSQL’s timestamptz_mi_interval, at - self, which adds the negated interval.

§Errors

ShiftError::IntervalOutOfRange where interval_um refuses the interval, and the errors of add_to_timestamptz.

Source

pub fn timestamp_difference( later: PgTimestamp, earlier: PgTimestamp, ) -> Result<Self, ShiftError>

PostgreSQL’s timestamp_mi, later - earlier, with whole days carried into the days field as interval_justify_hours carries them. An infinite timestamp gives an infinite interval.

§Errors

ShiftError::IntervalOutOfRange where equal infinities meet, or where the difference passes 2^63 microseconds.

use sql_values::postgres::{PgInterval, parse_timestamp};

let later = parse_timestamp("2024-03-01 06:00:00").unwrap();
let earlier = parse_timestamp("2024-02-28 12:00:00").unwrap();
let span = PgInterval::timestamp_difference(later, earlier).unwrap();
assert_eq!(span.to_string(), "1 day 18:00:00");
Source

pub fn timestamptz_difference( later: PgTimestampTz, earlier: PgTimestampTz, ) -> Result<Self, ShiftError>

PostgreSQL’s timestamptz_mi, later - earlier, the elapsed time between two instants carried into days as timestamp_difference carries it. No zone is consulted, so a day of a daylight saving change counts its 23 or 25 hours.

§Errors

The errors of timestamp_difference.

use sql_values::postgres::{InputContext, PgInterval, PgTimestampTz};

let instant = |text| PgTimestampTz::parse(text, InputContext::new()).unwrap();
let later = instant("2024-11-03 12:00:00-05");
let earlier = instant("2024-11-02 12:00:00-04");
let span = PgInterval::timestamptz_difference(later, earlier).unwrap();
assert_eq!(span.to_string(), "1 day 01:00:00");
Source

pub const fn time_difference(later: PgTime, earlier: PgTime) -> Self

PostgreSQL’s time_mi, later - earlier, the clocks’ difference kept whole in the microseconds, never wrapped within the day nor carried into days.

use sql_values::postgres::{PgInterval, parse_time};

let midnight = parse_time("00:00:00").unwrap();
let end = parse_time("24:00:00").unwrap();
assert_eq!(PgInterval::time_difference(end, midnight).to_string(), "24:00:00");
let late = parse_time("23:30:00").unwrap();
let early = parse_time("00:30:00").unwrap();
assert_eq!(PgInterval::time_difference(early, late).to_string(), "-23:00:00");
Source

pub fn add_to_time(self, at: PgTime) -> Result<PgTime, ShiftError>

PostgreSQL’s time_pl_interval, at + self: the clock moved by the interval’s microseconds, wrapping in 64 bits as PostgreSQL does, then within the day. The months and days are ignored.

§Errors

ShiftError::InfiniteIntervalAddedToTime for an infinite interval.

use sql_values::postgres::{parse_interval, parse_time};

let at = parse_time("23:00:00").unwrap();
let span = parse_interval("1 day 02:30:00").unwrap();
assert_eq!(span.add_to_time(at).unwrap().to_string(), "01:30:00");
Source

pub fn subtract_from_time(self, at: PgTime) -> Result<PgTime, ShiftError>

PostgreSQL’s time_mi_interval, at - self, as add_to_time with the clock subtracted.

§Errors

ShiftError::InfiniteIntervalSubtractedFromTime for an infinite interval.

Source§

impl PgInterval

Source

pub const INFINITY: Self

infinity, PostgreSQL’s INTERVAL_NOEND, above every finite interval.

Source

pub const NEG_INFINITY: Self

-infinity, PostgreSQL’s INTERVAL_NOBEGIN, below every finite interval.

Source

pub const fn is_finite(&self) -> bool

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());
Source

pub fn span_microseconds(&self) -> i128

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);
Source

pub fn adjust_for_typmod( self, typmod: IntervalTypmod, ) -> Result<Self, IntervalError>

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));

Trait Implementations§

Source§

impl Clone for PgInterval

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for PgInterval

Source§

impl Debug for PgInterval

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for PgInterval

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for PgInterval

PostgreSQL’s text under the default postgres IntervalStyle, which parse_interval reads back except the clock of i64::MIN microseconds that PostgreSQL refuses too.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for PgInterval

Source§

impl Hash for PgInterval

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for PgInterval

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for PgInterval

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for PgInterval

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for PgInterval

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.