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::{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 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::{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::{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::{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::{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: NaiveDateTime, ) -> Result<NaiveDateTime, 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.

The timestamp is read to the microsecond, as PostgreSQL holds it.

§Errors

ShiftError::TimestampOutOfRange where at or a step lies outside PostgreSQL’s timestamps, and ShiftError::Unrepresentable where PostgreSQL answers infinity, -infinity or a year past chrono’s.

use sql_values::{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: NaiveDateTime, ) -> Result<NaiveDateTime, 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 timestamp_difference( later: NaiveDateTime, earlier: NaiveDateTime, ) -> Result<Self, ShiftError>

PostgreSQL’s timestamp_mi, later - earlier, with whole days carried into the days field as interval_justify_hours carries them.

§Errors

ShiftError::TimestampOutOfRange where a timestamp lies outside PostgreSQL’s.

use sql_values::{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 add_to_time(self, at: NaiveTime) -> Result<NaiveTime, 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::{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: NaiveTime) -> Result<NaiveTime, 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::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::parse_interval;

let month = parse_interval("1 mon -1 days").unwrap();
assert_eq!(month.span_microseconds(), 29 * 86_400_000_000);

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.