use core::fmt;
use super::{
PgDate, PgFloat8, PgInterval, PgNumeric, PgTime, PgTimeTz, PgTimeZone, PgTimestamp,
PgTimestampTz, PgType,
datetime::{
POSTGRES_EPOCH_JDATE, UNIX_TO_POSTGRES_SECS, USECS_PER_DAY, USECS_PER_SEC, date2j, j2date,
split_clock, timestamp2tm,
tokens::{
DTK_CENTURY, DTK_DAY, DTK_DECADE, DTK_DOW, DTK_DOY, DTK_EPOCH, DTK_HOUR, DTK_ISODOW,
DTK_ISOYEAR, DTK_JULIAN, DTK_MICROSEC, DTK_MILLENNIUM, DTK_MILLISEC, DTK_MINUTE,
DTK_MONTH, DTK_QUARTER, DTK_SECOND, DTK_TZ, DTK_TZ_HOUR, DTK_TZ_MINUTE, DTK_WEEK,
DTK_YEAR, RESERV, UNITS,
},
utc_offset,
},
float::int_to_f64,
interval::decode_extract_unit,
};
const SECS_PER_DAY: i64 = 86_400;
const EPOCH_MICROS: i64 = -UNIX_TO_POSTGRES_SECS * USECS_PER_SEC;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExtractField {
Microseconds,
Milliseconds,
Second,
Minute,
Hour,
Day,
Week,
Month,
Quarter,
Year,
Decade,
Century,
Millennium,
DayOfWeek,
IsoDayOfWeek,
DayOfYear,
IsoYear,
Epoch,
Julian,
Timezone,
TimezoneHour,
TimezoneMinute,
}
impl ExtractField {
#[must_use]
pub fn parse(text: &str) -> Option<Self> {
match decode_extract_unit(text) {
(RESERV, DTK_EPOCH) => Some(Self::Epoch),
(UNITS, unit) => Some(match unit {
DTK_MICROSEC => Self::Microseconds,
DTK_MILLISEC => Self::Milliseconds,
DTK_SECOND => Self::Second,
DTK_MINUTE => Self::Minute,
DTK_HOUR => Self::Hour,
DTK_DAY => Self::Day,
DTK_WEEK => Self::Week,
DTK_MONTH => Self::Month,
DTK_QUARTER => Self::Quarter,
DTK_YEAR => Self::Year,
DTK_DECADE => Self::Decade,
DTK_CENTURY => Self::Century,
DTK_MILLENNIUM => Self::Millennium,
DTK_DOW => Self::DayOfWeek,
DTK_ISODOW => Self::IsoDayOfWeek,
DTK_DOY => Self::DayOfYear,
DTK_ISOYEAR => Self::IsoYear,
DTK_JULIAN => Self::Julian,
DTK_TZ => Self::Timezone,
DTK_TZ_HOUR => Self::TimezoneHour,
DTK_TZ_MINUTE => Self::TimezoneMinute,
_ => return None,
}),
_ => None,
}
}
const fn grows_with_timestamp(self) -> bool {
matches!(
self,
Self::Year
| Self::Decade
| Self::Century
| Self::Millennium
| Self::Julian
| Self::IsoYear
| Self::Epoch
)
}
}
impl fmt::Display for ExtractField {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Microseconds => "microseconds",
Self::Milliseconds => "milliseconds",
Self::Second => "second",
Self::Minute => "minute",
Self::Hour => "hour",
Self::Day => "day",
Self::Week => "week",
Self::Month => "month",
Self::Quarter => "quarter",
Self::Year => "year",
Self::Decade => "decade",
Self::Century => "century",
Self::Millennium => "millennium",
Self::DayOfWeek => "dow",
Self::IsoDayOfWeek => "isodow",
Self::DayOfYear => "doy",
Self::IsoYear => "isoyear",
Self::Epoch => "epoch",
Self::Julian => "julian",
Self::Timezone => "timezone",
Self::TimezoneHour => "timezone_hour",
Self::TimezoneMinute => "timezone_minute",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
pub enum ExtractError {
#[error("unit \"{field}\" not supported for type {input_type}")]
UnsupportedField {
field: ExtractField,
input_type: PgType,
},
#[error("date out of range for timestamp")]
DateOutOfRangeForTimestamp,
}
trait Part: Sized {
fn integer(value: i64) -> Self;
fn infinity(negative: bool) -> Self;
fn milliseconds(seconds: i64, micros: i64) -> Self;
fn seconds(seconds: i64, micros: i64) -> Self;
fn julian(day: i32, clock: i64) -> Self;
fn timestamp_epoch(micros: i64) -> Self;
fn clock_epoch(clock: i64, zone: i32) -> Self;
fn interval_epoch(interval: PgInterval) -> Self;
}
impl Part for PgNumeric {
fn integer(value: i64) -> Self {
Self::from(value)
}
fn infinity(negative: bool) -> Self {
if negative {
Self::NEG_INFINITY
} else {
Self::INFINITY
}
}
fn milliseconds(seconds: i64, micros: i64) -> Self {
Self::from_scaled_i64(seconds * USECS_PER_SEC + micros, 3)
}
fn seconds(seconds: i64, micros: i64) -> Self {
Self::from_scaled_i64(seconds * USECS_PER_SEC + micros, 6)
}
fn julian(day: i32, clock: i64) -> Self {
Self::from(clock)
.checked_div(&Self::from(USECS_PER_DAY))
.and_then(|fraction| Self::from(day).checked_add(&fraction))
.expect("a Julian day and its fraction fit numeric")
}
fn timestamp_epoch(micros: i64) -> Self {
if micros < i64::MAX + EPOCH_MICROS {
return Self::from_scaled_i64(micros - EPOCH_MICROS, 6);
}
Self::from(micros)
.checked_sub(&Self::from(EPOCH_MICROS))
.and_then(|span| span.checked_div(&Self::from(USECS_PER_SEC)))
.and_then(|seconds| seconds.round(6))
.expect("a timestamp's epoch fits numeric")
}
fn clock_epoch(clock: i64, zone: i32) -> Self {
Self::from_scaled_i64(clock + i64::from(zone) * USECS_PER_SEC, 6)
}
fn interval_epoch(interval: PgInterval) -> Self {
let quarter_days = 1_461 * i64::from(interval.months / 12)
+ 120 * i64::from(interval.months % 12)
+ 4 * i64::from(interval.days);
let seconds = quarter_days * (SECS_PER_DAY / 4);
match seconds
.checked_mul(USECS_PER_SEC)
.and_then(|micros| micros.checked_add(interval.microseconds))
{
Some(micros) => Self::from_scaled_i64(micros, 6),
None => Self::from_scaled_i64(interval.microseconds, 6)
.checked_add(&Self::from(seconds))
.expect("an interval's epoch fits numeric"),
}
}
}
impl Part for PgFloat8 {
fn integer(value: i64) -> Self {
Self::from(int_to_f64(value))
}
fn infinity(negative: bool) -> Self {
Self::from(if negative {
f64::NEG_INFINITY
} else {
f64::INFINITY
})
}
fn milliseconds(seconds: i64, micros: i64) -> Self {
Self::from(int_to_f64(seconds) * 1_000.0 + int_to_f64(micros) / 1_000.0)
}
fn seconds(seconds: i64, micros: i64) -> Self {
Self::from(int_to_f64(seconds) + int_to_f64(micros) / 1_000_000.0)
}
fn julian(day: i32, clock: i64) -> Self {
let seconds =
int_to_f64(clock / USECS_PER_SEC) + int_to_f64(clock % USECS_PER_SEC) / 1_000_000.0;
Self::from(f64::from(day) + seconds / 86_400.0)
}
fn timestamp_epoch(micros: i64) -> Self {
Self::from(if micros < i64::MAX + EPOCH_MICROS {
int_to_f64(micros - EPOCH_MICROS) / 1_000_000.0
} else {
(int_to_f64(micros) - int_to_f64(EPOCH_MICROS)) / 1_000_000.0
})
}
fn clock_epoch(clock: i64, zone: i32) -> Self {
Self::from(int_to_f64(clock) / 1_000_000.0 + f64::from(zone))
}
fn interval_epoch(interval: PgInterval) -> Self {
let mut seconds = int_to_f64(interval.microseconds) / 1_000_000.0;
seconds += 365.25 * 86_400.0 * f64::from(interval.months / 12);
seconds += 30.0 * 86_400.0 * f64::from(interval.months % 12);
seconds += 86_400.0 * f64::from(interval.days);
Self::from(seconds)
}
}
impl ExtractError {
const fn unsupported(field: ExtractField, input_type: PgType) -> Self {
Self::UnsupportedField { field, input_type }
}
}
fn clock_part<P: Part>(field: ExtractField, clock: i64) -> Option<P> {
let (hour, minute, second, micros) = split_clock(clock);
Some(match field {
ExtractField::Microseconds => P::integer(second * USECS_PER_SEC + micros),
ExtractField::Milliseconds => P::milliseconds(second, micros),
ExtractField::Second => P::seconds(second, micros),
ExtractField::Minute => P::integer(minute),
ExtractField::Hour => P::integer(hour),
_ => return None,
})
}
fn calendar_part<P: Part>(field: ExtractField, year: i32, month: i32, day: i32) -> Option<P> {
let julian = date2j(year, month, day);
let value = match field {
ExtractField::Day => day,
ExtractField::Month => month,
ExtractField::Quarter => (month - 1) / 3 + 1,
ExtractField::Week => iso_year_week(year, julian).1,
ExtractField::Year if year > 0 => year,
ExtractField::Year => year - 1,
ExtractField::Decade if year >= 0 => year / 10,
ExtractField::Decade => -((8 - (year - 1)) / 10),
ExtractField::Century if year > 0 => (year + 99) / 100,
ExtractField::Century => -((99 - (year - 1)) / 100),
ExtractField::Millennium if year > 0 => (year + 999) / 1_000,
ExtractField::Millennium => -((999 - (year - 1)) / 1_000),
ExtractField::IsoYear => match iso_year_week(year, julian).0 {
iso_year if iso_year <= 0 => iso_year - 1,
iso_year => iso_year,
},
ExtractField::DayOfWeek => j2day(julian),
ExtractField::IsoDayOfWeek => match j2day(julian) {
0 => 7,
weekday => weekday,
},
ExtractField::DayOfYear => julian - date2j(year, 1, 1) + 1,
_ => return None,
};
Some(P::integer(value.into()))
}
const fn j2day(julian: i32) -> i32 {
(julian + 1).rem_euclid(7)
}
const fn iso_year_start(year: i32) -> i32 {
let fourth = date2j(year, 1, 4);
fourth - j2day(fourth - 1)
}
const fn iso_year_week(year: i32, julian: i32) -> (i32, i32) {
let (mut iso_year, mut start) = (year, iso_year_start(year));
if julian < start {
iso_year -= 1;
start = iso_year_start(iso_year);
}
let week = (julian - start) / 7 + 1;
if week >= 52 {
let next = iso_year_start(iso_year + 1);
if julian >= next {
return (iso_year + 1, (julian - next) / 7 + 1);
}
}
(iso_year, week)
}
fn timestamp_part<P: Part>(
micros: i64,
field: ExtractField,
zone: Option<&PgTimeZone>,
) -> Option<Option<P>> {
if micros == i64::MAX || micros == i64::MIN {
return Some(
field
.grows_with_timestamp()
.then(|| P::infinity(micros == i64::MIN)),
);
}
if field == ExtractField::Epoch {
return Some(Some(P::timestamp_epoch(micros)));
}
let offset = zone.map_or(0, |zone| utc_offset(zone, micros));
let (year, month, day, clock) = timestamp2tm(micros + i64::from(offset) * USECS_PER_SEC);
let part = match field {
ExtractField::Julian => P::julian(date2j(year, month, day), clock),
ExtractField::Timezone if zone.is_some() => P::integer(offset.into()),
ExtractField::TimezoneHour if zone.is_some() => P::integer((offset / 3_600).into()),
ExtractField::TimezoneMinute if zone.is_some() => P::integer((offset / 60 % 60).into()),
_ => clock_part(field, clock).or_else(|| calendar_part(field, year, month, day))?,
};
Some(Some(part))
}
fn timestamp_without_zone_part<P: Part>(
micros: i64,
field: ExtractField,
) -> Result<Option<P>, ExtractError> {
timestamp_part(micros, field, None).ok_or(ExtractError::unsupported(field, PgType::Timestamp))
}
fn timestamptz_part<P: Part>(micros: i64, field: ExtractField, zone: &PgTimeZone) -> Option<P> {
timestamp_part(micros, field, Some(zone)).expect("a timestamptz has every field")
}
fn time_part<P: Part>(
clock: i64,
offset: Option<i32>,
field: ExtractField,
) -> Result<Option<P>, ExtractError> {
let part = match (field, offset) {
(ExtractField::Epoch, _) => P::clock_epoch(clock, -offset.unwrap_or(0)),
(ExtractField::Timezone, Some(offset)) => P::integer(offset.into()),
(ExtractField::TimezoneHour, Some(offset)) => P::integer((offset / 3_600).into()),
(ExtractField::TimezoneMinute, Some(offset)) => P::integer((offset / 60 % 60).into()),
_ => clock_part(field, clock).ok_or_else(|| {
let input_type = if offset.is_some() {
PgType::TimeTz
} else {
PgType::Time
};
ExtractError::unsupported(field, input_type)
})?,
};
Ok(Some(part))
}
impl PgDate {
pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
if !self.is_finite() {
return match field {
ExtractField::Day
| ExtractField::Week
| ExtractField::Month
| ExtractField::Quarter
| ExtractField::DayOfWeek
| ExtractField::IsoDayOfWeek
| ExtractField::DayOfYear => Ok(None),
_ if field.grows_with_timestamp() => {
Ok(Some(PgNumeric::infinity(self == Self::NEG_INFINITY)))
}
_ => Err(ExtractError::unsupported(field, PgType::Date)),
};
}
let julian = self.pg_days() + POSTGRES_EPOCH_JDATE;
let (year, month, day) = j2date(julian);
match field {
ExtractField::Julian => Ok(Some(PgNumeric::from(julian))),
ExtractField::Epoch => Ok(Some(PgNumeric::from(
i64::from(self.pg_days()) * SECS_PER_DAY + UNIX_TO_POSTGRES_SECS,
))),
_ => calendar_part(field, year, month, day)
.map(Some)
.ok_or(ExtractError::unsupported(field, PgType::Date)),
}
}
pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
self.to_timestamp()
.map_err(|_| ExtractError::DateOutOfRangeForTimestamp)?
.date_part(field)
}
}
impl PgTime {
pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
time_part(self.micros(), None, field)
}
pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
time_part(self.micros(), None, field)
}
}
impl PgTimeTz {
pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
time_part(self.time().micros(), Some(self.offset()), field)
}
pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
time_part(self.time().micros(), Some(self.offset()), field)
}
}
impl PgTimestamp {
pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
timestamp_without_zone_part(self.pg_micros(), field)
}
pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
timestamp_without_zone_part(self.pg_micros(), field)
}
}
impl PgTimestampTz {
#[must_use]
pub fn extract(self, field: ExtractField, zone: &PgTimeZone) -> Option<PgNumeric> {
timestamptz_part(self.pg_micros(), field, zone)
}
#[must_use]
pub fn date_part(self, field: ExtractField, zone: &PgTimeZone) -> Option<PgFloat8> {
timestamptz_part(self.pg_micros(), field, zone)
}
}
impl PgInterval {
pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
self.part(field)
}
pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
self.part(field)
}
fn part<P: Part>(self, field: ExtractField) -> Result<Option<P>, ExtractError> {
let unsupported = ExtractError::unsupported(field, PgType::Interval);
if !self.is_finite() {
return match field {
ExtractField::Microseconds
| ExtractField::Milliseconds
| ExtractField::Second
| ExtractField::Minute
| ExtractField::Week
| ExtractField::Month
| ExtractField::Quarter => Ok(None),
ExtractField::Hour
| ExtractField::Day
| ExtractField::Year
| ExtractField::Decade
| ExtractField::Century
| ExtractField::Millennium
| ExtractField::Epoch => Ok(Some(P::infinity(self.months == i32::MIN))),
_ => Err(unsupported),
};
}
let years = self.months / 12;
let value = match field {
ExtractField::Epoch => return Ok(Some(P::interval_epoch(self))),
ExtractField::Day => self.days,
ExtractField::Week => self.days / 7,
ExtractField::Month => self.months % 12,
ExtractField::Quarter if self.months >= 0 => self.months % 12 / 3 + 1,
ExtractField::Quarter => -(self.months.wrapping_neg() % 12 / 3 + 1),
ExtractField::Year => years,
ExtractField::Decade => years / 10,
ExtractField::Century => years / 100,
ExtractField::Millennium => years / 1_000,
_ => {
return clock_part(field, self.microseconds)
.map(Some)
.ok_or(unsupported);
}
};
Ok(Some(P::integer(value.into())))
}
}