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: i32Months, twelve of which print as a year.
days: i32Days, never folded into months.
microseconds: i64Microseconds, never folded into days.
Implementations§
Source§impl PgInterval
impl PgInterval
Sourcepub fn date_trunc(self, field: DateTruncField) -> Result<Self, DateTruncError>
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
impl PgInterval
Sourcepub fn to_char(
self,
template: &str,
) -> Result<Option<String>, TemporalFormatError>
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
impl PgInterval
Sourcepub fn extract(
self,
field: ExtractField,
) -> Result<Option<PgNumeric>, ExtractError>
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)));Sourcepub fn date_part(
self,
field: ExtractField,
) -> Result<Option<PgFloat8>, ExtractError>
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
impl PgInterval
Sourcepub fn checked_add(self, other: Self) -> Result<Self, IntervalError>
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),
);Sourcepub fn checked_sub(self, other: Self) -> Result<Self, IntervalError>
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.
Sourcepub fn checked_neg(self) -> Result<Self, IntervalError>
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));Sourcepub fn checked_mul(self, factor: f64) -> Result<Self, IntervalError>
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));Sourcepub fn checked_div(self, factor: f64) -> Result<Self, IntervalError>
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));Sourcepub fn add_to_timestamp(
self,
at: PgTimestamp,
) -> Result<PgTimestamp, ShiftError>
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");Sourcepub fn subtract_from_timestamp(
self,
at: PgTimestamp,
) -> Result<PgTimestamp, ShiftError>
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.
Sourcepub fn add_to_timestamptz(
self,
at: PgTimestampTz,
zone: &PgTimeZone,
) -> Result<PgTimestampTz, ShiftError>
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");
}Sourcepub fn subtract_from_timestamptz(
self,
at: PgTimestampTz,
zone: &PgTimeZone,
) -> Result<PgTimestampTz, ShiftError>
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.
Sourcepub fn timestamp_difference(
later: PgTimestamp,
earlier: PgTimestamp,
) -> Result<Self, ShiftError>
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");Sourcepub fn timestamptz_difference(
later: PgTimestampTz,
earlier: PgTimestampTz,
) -> Result<Self, ShiftError>
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");Sourcepub const fn time_difference(later: PgTime, earlier: PgTime) -> Self
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");Sourcepub fn add_to_time(self, at: PgTime) -> Result<PgTime, ShiftError>
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");Sourcepub fn subtract_from_time(self, at: PgTime) -> Result<PgTime, ShiftError>
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
impl PgInterval
Sourcepub const NEG_INFINITY: Self
pub const NEG_INFINITY: Self
-infinity, PostgreSQL’s INTERVAL_NOBEGIN, below every finite interval.
Sourcepub const fn is_finite(&self) -> bool
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());Sourcepub fn span_microseconds(&self) -> i128
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);Sourcepub fn adjust_for_typmod(
self,
typmod: IntervalTypmod,
) -> Result<Self, IntervalError>
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
impl Clone for PgInterval
impl Copy for PgInterval
Source§impl Debug for PgInterval
impl Debug for PgInterval
Source§impl<'de> Deserialize<'de> for PgInterval
impl<'de> Deserialize<'de> for PgInterval
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
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.
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.