Skip to main content

sql_values/postgres/
extract.rs

1//! PostgreSQL 18's `extract` and `date_part` of `date`, `time`, `timetz`, `timestamp`,
2//! `timestamptz` and `interval`, a field as `numeric` and as `double precision`.
3
4use core::fmt;
5
6use super::{
7    BuiltinType, PgDate, PgFloat8, PgInterval, PgNumeric, PgTime, PgTimeTz, PgTimeZone,
8    PgTimestamp, PgTimestampTz,
9    datetime::{
10        POSTGRES_EPOCH_JDATE, UNIX_TO_POSTGRES_SECS, USECS_PER_DAY, USECS_PER_SEC, date2j, j2date,
11        split_clock, timestamp2tm,
12        tokens::{
13            DTK_CENTURY, DTK_DAY, DTK_DECADE, DTK_DOW, DTK_DOY, DTK_EPOCH, DTK_HOUR, DTK_ISODOW,
14            DTK_ISOYEAR, DTK_JULIAN, DTK_MICROSEC, DTK_MILLENNIUM, DTK_MILLISEC, DTK_MINUTE,
15            DTK_MONTH, DTK_QUARTER, DTK_SECOND, DTK_TZ, DTK_TZ_HOUR, DTK_TZ_MINUTE, DTK_WEEK,
16            DTK_YEAR, RESERV, UNITS,
17        },
18        utc_offset,
19    },
20    float::int_to_f64,
21    interval::decode_extract_unit,
22};
23
24const SECS_PER_DAY: i64 = 86_400;
25/// `SetEpochTimestamp`, 1970-01-01 00:00:00 as a `timestamp`.
26const EPOCH_MICROS: i64 = -UNIX_TO_POSTGRES_SECS * USECS_PER_SEC;
27
28/// A field `extract` and `date_part` take, printed as PostgreSQL spells it in its errors.
29///
30/// ```
31/// use sql_values::postgres::ExtractField;
32///
33/// assert_eq!(ExtractField::parse("SECS"), Some(ExtractField::Second));
34/// assert_eq!(ExtractField::parse("timezone_hour"), Some(ExtractField::TimezoneHour));
35/// assert_eq!(ExtractField::DayOfWeek.to_string(), "dow");
36/// assert_eq!(ExtractField::parse("fortnight"), None);
37/// ```
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum ExtractField {
40    /// `microseconds`, the seconds with their fraction, in microseconds.
41    Microseconds,
42    /// `milliseconds`, the seconds with their fraction, in milliseconds.
43    Milliseconds,
44    /// `second`, the seconds with their fraction.
45    Second,
46    /// `minute`.
47    Minute,
48    /// `hour`.
49    Hour,
50    /// `day`, of the month, or an interval's days.
51    Day,
52    /// `week`, the ISO 8601 week of the year, or an interval's days in whole weeks.
53    Week,
54    /// `month`, of the year, or an interval's months beyond its whole years.
55    Month,
56    /// `quarter`.
57    Quarter,
58    /// `year`, where 1 BC is `-1`.
59    Year,
60    /// `decade`, the year divided by 10.
61    Decade,
62    /// `century`, where the 21st starts on 2001-01-01.
63    Century,
64    /// `millennium`, where the 3rd starts on 2001-01-01.
65    Millennium,
66    /// `dow`, the day of the week from Sunday as `0`.
67    DayOfWeek,
68    /// `isodow`, the day of the week from Monday as `1` to Sunday as `7`.
69    IsoDayOfWeek,
70    /// `doy`, the day of the year from `1`.
71    DayOfYear,
72    /// `isoyear`, the ISO 8601 week-numbering year.
73    IsoYear,
74    /// `epoch`, seconds since 1970-01-01 00:00:00 UTC, or an interval's length in seconds.
75    Epoch,
76    /// `julian`, the Julian day with the time of day as its fraction.
77    Julian,
78    /// `timezone`, the offset east of UTC in seconds.
79    Timezone,
80    /// `timezone_hour`, the whole hours of the offset.
81    TimezoneHour,
82    /// `timezone_minute`, the minutes of the offset beyond its whole hours.
83    TimezoneMinute,
84}
85
86impl ExtractField {
87    /// The field PostgreSQL reads `text` as, lowercased and looked up by its first 10 bytes among
88    /// the interval units and then the date keywords, so aliases such as `secs`, `msec`, `y`,
89    /// `j` and `timezone_h` name fields too. `None` for any other word, which PostgreSQL refuses
90    /// as not recognized, or as not supported by `date` and `timestamp` when it is a reserved
91    /// word such as `now`.
92    #[must_use]
93    pub fn parse(text: &str) -> Option<Self> {
94        match decode_extract_unit(text) {
95            (RESERV, DTK_EPOCH) => Some(Self::Epoch),
96            (UNITS, unit) => Some(match unit {
97                DTK_MICROSEC => Self::Microseconds,
98                DTK_MILLISEC => Self::Milliseconds,
99                DTK_SECOND => Self::Second,
100                DTK_MINUTE => Self::Minute,
101                DTK_HOUR => Self::Hour,
102                DTK_DAY => Self::Day,
103                DTK_WEEK => Self::Week,
104                DTK_MONTH => Self::Month,
105                DTK_QUARTER => Self::Quarter,
106                DTK_YEAR => Self::Year,
107                DTK_DECADE => Self::Decade,
108                DTK_CENTURY => Self::Century,
109                DTK_MILLENNIUM => Self::Millennium,
110                DTK_DOW => Self::DayOfWeek,
111                DTK_ISODOW => Self::IsoDayOfWeek,
112                DTK_DOY => Self::DayOfYear,
113                DTK_ISOYEAR => Self::IsoYear,
114                DTK_JULIAN => Self::Julian,
115                DTK_TZ => Self::Timezone,
116                DTK_TZ_HOUR => Self::TimezoneHour,
117                DTK_TZ_MINUTE => Self::TimezoneMinute,
118                _ => return None,
119            }),
120            _ => None,
121        }
122    }
123
124    /// Whether an infinite `date`, `timestamp` or `timestamptz` has the infinity of its sign in
125    /// the field, as `NonFiniteTimestampTzPart` sorts the fields, rather than `NULL`.
126    const fn grows_with_timestamp(self) -> bool {
127        matches!(
128            self,
129            Self::Year
130                | Self::Decade
131                | Self::Century
132                | Self::Millennium
133                | Self::Julian
134                | Self::IsoYear
135                | Self::Epoch
136        )
137    }
138}
139
140impl fmt::Display for ExtractField {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.write_str(match self {
143            Self::Microseconds => "microseconds",
144            Self::Milliseconds => "milliseconds",
145            Self::Second => "second",
146            Self::Minute => "minute",
147            Self::Hour => "hour",
148            Self::Day => "day",
149            Self::Week => "week",
150            Self::Month => "month",
151            Self::Quarter => "quarter",
152            Self::Year => "year",
153            Self::Decade => "decade",
154            Self::Century => "century",
155            Self::Millennium => "millennium",
156            Self::DayOfWeek => "dow",
157            Self::IsoDayOfWeek => "isodow",
158            Self::DayOfYear => "doy",
159            Self::IsoYear => "isoyear",
160            Self::Epoch => "epoch",
161            Self::Julian => "julian",
162            Self::Timezone => "timezone",
163            Self::TimezoneHour => "timezone_hour",
164            Self::TimezoneMinute => "timezone_minute",
165        })
166    }
167}
168
169/// Why PostgreSQL refuses `extract` or `date_part`.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
171pub enum ExtractError {
172    /// A field the input's type does not have.
173    #[error("unit \"{field}\" not supported for type {input_type}")]
174    UnsupportedField {
175        /// The field asked for.
176        field: ExtractField,
177        /// The type PostgreSQL extracts from.
178        input_type: BuiltinType,
179    },
180    /// `date_part` of a date from 294277-01-01, which it casts to `timestamp`.
181    #[error("date out of range for timestamp")]
182    DateOutOfRangeForTimestamp,
183}
184
185/// A field as `extract` computes it in `numeric` or `date_part` in `double precision`, each
186/// with PostgreSQL's own arithmetic.
187trait Part: Sized {
188    /// `intresult`.
189    fn integer(value: i64) -> Self;
190
191    /// The infinity of the sign of an infinite input.
192    fn infinity(negative: bool) -> Self;
193
194    /// `milliseconds` of the clock's seconds and microseconds.
195    fn milliseconds(seconds: i64, micros: i64) -> Self;
196
197    /// `second` of the clock's seconds and microseconds.
198    fn seconds(seconds: i64, micros: i64) -> Self;
199
200    /// `julian` of a `timestamp` on the Julian day `day` at `clock` microseconds after midnight.
201    fn julian(day: i32, clock: i64) -> Self;
202
203    /// `epoch` of a finite `timestamp` or `timestamptz`.
204    fn timestamp_epoch(micros: i64) -> Self;
205
206    /// `epoch` of a `time`, or of a `timetz` `zone` seconds west of UTC.
207    fn clock_epoch(clock: i64, zone: i32) -> Self;
208
209    /// `epoch` of a finite `interval`.
210    fn interval_epoch(interval: PgInterval) -> Self;
211}
212
213impl Part for PgNumeric {
214    fn integer(value: i64) -> Self {
215        Self::from(value)
216    }
217
218    fn infinity(negative: bool) -> Self {
219        if negative {
220            Self::NEG_INFINITY
221        } else {
222            Self::INFINITY
223        }
224    }
225
226    fn milliseconds(seconds: i64, micros: i64) -> Self {
227        Self::from_scaled_i64(seconds * USECS_PER_SEC + micros, 3)
228    }
229
230    fn seconds(seconds: i64, micros: i64) -> Self {
231        Self::from_scaled_i64(seconds * USECS_PER_SEC + micros, 6)
232    }
233
234    fn julian(day: i32, clock: i64) -> Self {
235        Self::from(clock)
236            .checked_div(&Self::from(USECS_PER_DAY))
237            .and_then(|fraction| Self::from(day).checked_add(&fraction))
238            .expect("a Julian day and its fraction fit numeric")
239    }
240
241    fn timestamp_epoch(micros: i64) -> Self {
242        if micros < i64::MAX + EPOCH_MICROS {
243            return Self::from_scaled_i64(micros - EPOCH_MICROS, 6);
244        }
245        Self::from(micros)
246            .checked_sub(&Self::from(EPOCH_MICROS))
247            .and_then(|span| span.checked_div(&Self::from(USECS_PER_SEC)))
248            .and_then(|seconds| seconds.round(6))
249            .expect("a timestamp's epoch fits numeric")
250    }
251
252    fn clock_epoch(clock: i64, zone: i32) -> Self {
253        Self::from_scaled_i64(clock + i64::from(zone) * USECS_PER_SEC, 6)
254    }
255
256    fn interval_epoch(interval: PgInterval) -> Self {
257        // PostgreSQL counts quarter days so that a year of 365.25 days stays whole.
258        let quarter_days = 1_461 * i64::from(interval.months / 12)
259            + 120 * i64::from(interval.months % 12)
260            + 4 * i64::from(interval.days);
261        let seconds = quarter_days * (SECS_PER_DAY / 4);
262        match seconds
263            .checked_mul(USECS_PER_SEC)
264            .and_then(|micros| micros.checked_add(interval.microseconds))
265        {
266            Some(micros) => Self::from_scaled_i64(micros, 6),
267            None => Self::from_scaled_i64(interval.microseconds, 6)
268                .checked_add(&Self::from(seconds))
269                .expect("an interval's epoch fits numeric"),
270        }
271    }
272}
273
274impl Part for PgFloat8 {
275    fn integer(value: i64) -> Self {
276        Self::from(int_to_f64(value))
277    }
278
279    fn infinity(negative: bool) -> Self {
280        Self::from(if negative {
281            f64::NEG_INFINITY
282        } else {
283            f64::INFINITY
284        })
285    }
286
287    fn milliseconds(seconds: i64, micros: i64) -> Self {
288        Self::from(int_to_f64(seconds) * 1_000.0 + int_to_f64(micros) / 1_000.0)
289    }
290
291    fn seconds(seconds: i64, micros: i64) -> Self {
292        Self::from(int_to_f64(seconds) + int_to_f64(micros) / 1_000_000.0)
293    }
294
295    fn julian(day: i32, clock: i64) -> Self {
296        let seconds =
297            int_to_f64(clock / USECS_PER_SEC) + int_to_f64(clock % USECS_PER_SEC) / 1_000_000.0;
298        Self::from(f64::from(day) + seconds / 86_400.0)
299    }
300
301    fn timestamp_epoch(micros: i64) -> Self {
302        Self::from(if micros < i64::MAX + EPOCH_MICROS {
303            int_to_f64(micros - EPOCH_MICROS) / 1_000_000.0
304        } else {
305            (int_to_f64(micros) - int_to_f64(EPOCH_MICROS)) / 1_000_000.0
306        })
307    }
308
309    fn clock_epoch(clock: i64, zone: i32) -> Self {
310        Self::from(int_to_f64(clock) / 1_000_000.0 + f64::from(zone))
311    }
312
313    fn interval_epoch(interval: PgInterval) -> Self {
314        let mut seconds = int_to_f64(interval.microseconds) / 1_000_000.0;
315        seconds += 365.25 * 86_400.0 * f64::from(interval.months / 12);
316        seconds += 30.0 * 86_400.0 * f64::from(interval.months % 12);
317        seconds += 86_400.0 * f64::from(interval.days);
318        Self::from(seconds)
319    }
320}
321
322impl ExtractError {
323    const fn unsupported(field: ExtractField, input_type: BuiltinType) -> Self {
324        Self::UnsupportedField { field, input_type }
325    }
326}
327
328/// The clock fields of `clock` microseconds, split toward zero as `time2tm` splits a time of
329/// day and `interval2itm` an interval's time, or `None` for another field.
330fn clock_part<P: Part>(field: ExtractField, clock: i64) -> Option<P> {
331    let (hour, minute, second, micros) = split_clock(clock);
332    Some(match field {
333        ExtractField::Microseconds => P::integer(second * USECS_PER_SEC + micros),
334        ExtractField::Milliseconds => P::milliseconds(second, micros),
335        ExtractField::Second => P::seconds(second, micros),
336        ExtractField::Minute => P::integer(minute),
337        ExtractField::Hour => P::integer(hour),
338        _ => return None,
339    })
340}
341
342/// The calendar fields of a date, year `0` being 1 BC, as `extract_date` and
343/// `timestamp_part_common` compute them, or `None` for another field.
344fn calendar_part<P: Part>(field: ExtractField, year: i32, month: i32, day: i32) -> Option<P> {
345    let julian = date2j(year, month, day);
346    let value = match field {
347        ExtractField::Day => day,
348        ExtractField::Month => month,
349        ExtractField::Quarter => (month - 1) / 3 + 1,
350        ExtractField::Week => iso_year_week(year, julian).1,
351        ExtractField::Year if year > 0 => year,
352        ExtractField::Year => year - 1,
353        ExtractField::Decade if year >= 0 => year / 10,
354        ExtractField::Decade => -((8 - (year - 1)) / 10),
355        ExtractField::Century if year > 0 => (year + 99) / 100,
356        ExtractField::Century => -((99 - (year - 1)) / 100),
357        ExtractField::Millennium if year > 0 => (year + 999) / 1_000,
358        ExtractField::Millennium => -((999 - (year - 1)) / 1_000),
359        ExtractField::IsoYear => match iso_year_week(year, julian).0 {
360            iso_year if iso_year <= 0 => iso_year - 1,
361            iso_year => iso_year,
362        },
363        ExtractField::DayOfWeek => j2day(julian),
364        ExtractField::IsoDayOfWeek => match j2day(julian) {
365            0 => 7,
366            weekday => weekday,
367        },
368        ExtractField::DayOfYear => julian - date2j(year, 1, 1) + 1,
369        _ => return None,
370    };
371    Some(P::integer(value.into()))
372}
373
374/// `j2day`, the day of the week of a Julian day, Sunday being `0`.
375const fn j2day(julian: i32) -> i32 {
376    (julian + 1).rem_euclid(7)
377}
378
379/// The Julian day of the Monday that starts week 1 of the ISO 8601 `year`.
380const fn iso_year_start(year: i32) -> i32 {
381    let fourth = date2j(year, 1, 4);
382    fourth - j2day(fourth - 1)
383}
384
385/// `date2isoyear` and `date2isoweek`, the ISO 8601 year and week of the Julian day `julian` in
386/// the calendar `year`.
387const fn iso_year_week(year: i32, julian: i32) -> (i32, i32) {
388    let (mut iso_year, mut start) = (year, iso_year_start(year));
389    if julian < start {
390        iso_year -= 1;
391        start = iso_year_start(iso_year);
392    }
393    let week = (julian - start) / 7 + 1;
394    if week >= 52 {
395        let next = iso_year_start(iso_year + 1);
396        if julian >= next {
397            return (iso_year + 1, (julian - next) / 7 + 1);
398        }
399    }
400    (iso_year, week)
401}
402
403/// `timestamp_part_common`, or `timestamptz_part_common` in `zone`, `None` for a zone field
404/// without a zone.
405fn timestamp_part<P: Part>(
406    micros: i64,
407    field: ExtractField,
408    zone: Option<&PgTimeZone>,
409) -> Option<Option<P>> {
410    if micros == i64::MAX || micros == i64::MIN {
411        return Some(
412            field
413                .grows_with_timestamp()
414                .then(|| P::infinity(micros == i64::MIN)),
415        );
416    }
417    if field == ExtractField::Epoch {
418        return Some(Some(P::timestamp_epoch(micros)));
419    }
420    let offset = zone.map_or(0, |zone| utc_offset(zone, micros));
421    let (year, month, day, clock) = timestamp2tm(micros + i64::from(offset) * USECS_PER_SEC);
422    let part = match field {
423        ExtractField::Julian => P::julian(date2j(year, month, day), clock),
424        ExtractField::Timezone if zone.is_some() => P::integer(offset.into()),
425        ExtractField::TimezoneHour if zone.is_some() => P::integer((offset / 3_600).into()),
426        ExtractField::TimezoneMinute if zone.is_some() => P::integer((offset / 60 % 60).into()),
427        _ => clock_part(field, clock).or_else(|| calendar_part(field, year, month, day))?,
428    };
429    Some(Some(part))
430}
431
432/// `timestamp_part_common`, which refuses a zone field.
433fn timestamp_without_zone_part<P: Part>(
434    micros: i64,
435    field: ExtractField,
436) -> Result<Option<P>, ExtractError> {
437    timestamp_part(micros, field, None).ok_or(ExtractError::unsupported(
438        field,
439        BuiltinType::Timestamp(None),
440    ))
441}
442
443/// `timestamptz_part_common` in `zone`, which has every field.
444fn timestamptz_part<P: Part>(micros: i64, field: ExtractField, zone: &PgTimeZone) -> Option<P> {
445    timestamp_part(micros, field, Some(zone)).expect("a timestamptz has every field")
446}
447
448/// `time_part_common`, or `timetz_part_common` of a time at `offset` seconds east of UTC.
449fn time_part<P: Part>(
450    clock: i64,
451    offset: Option<i32>,
452    field: ExtractField,
453) -> Result<Option<P>, ExtractError> {
454    let part = match (field, offset) {
455        (ExtractField::Epoch, _) => P::clock_epoch(clock, -offset.unwrap_or(0)),
456        (ExtractField::Timezone, Some(offset)) => P::integer(offset.into()),
457        (ExtractField::TimezoneHour, Some(offset)) => P::integer((offset / 3_600).into()),
458        (ExtractField::TimezoneMinute, Some(offset)) => P::integer((offset / 60 % 60).into()),
459        _ => clock_part(field, clock).ok_or_else(|| {
460            let input_type = if offset.is_some() {
461                BuiltinType::TimeTz(None)
462            } else {
463                BuiltinType::Time(None)
464            };
465            ExtractError::unsupported(field, input_type)
466        })?,
467    };
468    Ok(Some(part))
469}
470
471impl PgDate {
472    /// PostgreSQL's `extract(field FROM date)`, `extract_date`, an integer in `numeric`. An
473    /// infinite date has the infinity of its sign in the fields that grow with time and `None`,
474    /// SQL `NULL`, in the others.
475    ///
476    /// # Errors
477    ///
478    /// [`ExtractError::UnsupportedField`] for a clock or zone field.
479    ///
480    /// ```
481    /// use sql_values::postgres::{ExtractField, PgDate, PgNumeric};
482    ///
483    /// let date = PgDate::from_ymd(2006, 1, 1).unwrap();
484    /// assert_eq!(date.extract(ExtractField::IsoYear).unwrap(), Some(PgNumeric::from(2005)));
485    /// assert!(date.extract(ExtractField::Hour).is_err());
486    /// assert_eq!(PgDate::INFINITY.extract(ExtractField::Day).unwrap(), None);
487    /// ```
488    pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
489        if !self.is_finite() {
490            return match field {
491                ExtractField::Day
492                | ExtractField::Week
493                | ExtractField::Month
494                | ExtractField::Quarter
495                | ExtractField::DayOfWeek
496                | ExtractField::IsoDayOfWeek
497                | ExtractField::DayOfYear => Ok(None),
498                _ if field.grows_with_timestamp() => {
499                    Ok(Some(PgNumeric::infinity(self == Self::NEG_INFINITY)))
500                }
501                _ => Err(ExtractError::unsupported(field, BuiltinType::Date)),
502            };
503        }
504        let julian = self.pg_days() + POSTGRES_EPOCH_JDATE;
505        let (year, month, day) = j2date(julian);
506        match field {
507            ExtractField::Julian => Ok(Some(PgNumeric::from(julian))),
508            ExtractField::Epoch => Ok(Some(PgNumeric::from(
509                i64::from(self.pg_days()) * SECS_PER_DAY + UNIX_TO_POSTGRES_SECS,
510            ))),
511            _ => calendar_part(field, year, month, day)
512                .map(Some)
513                .ok_or(ExtractError::unsupported(field, BuiltinType::Date)),
514        }
515    }
516
517    /// PostgreSQL's `date_part(field, date)`, which casts the date to `timestamp`, so a clock
518    /// field is `0` and a zone field is unsupported by `timestamp`.
519    ///
520    /// # Errors
521    ///
522    /// [`ExtractError::DateOutOfRangeForTimestamp`] for a date from 294277-01-01, and
523    /// [`ExtractError::UnsupportedField`] for a zone field.
524    ///
525    /// ```
526    /// use sql_values::postgres::{ExtractField, PgDate};
527    ///
528    /// let date = PgDate::from_ymd(2006, 1, 1).unwrap();
529    /// assert_eq!(date.date_part(ExtractField::Hour).unwrap().unwrap().value(), 0.0);
530    /// ```
531    pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
532        self.to_timestamp()
533            .map_err(|_| ExtractError::DateOutOfRangeForTimestamp)?
534            .date_part(field)
535    }
536}
537
538impl PgTime {
539    /// PostgreSQL's `extract(field FROM time)`.
540    ///
541    /// # Errors
542    ///
543    /// [`ExtractError::UnsupportedField`] for a field other than a clock field or `epoch`.
544    ///
545    /// ```
546    /// use sql_values::postgres::{ExtractField, PgTime};
547    ///
548    /// let time = PgTime::from_hms_micro(23, 59, 59, 123_456).unwrap();
549    /// let epoch = time.extract(ExtractField::Epoch).unwrap().unwrap();
550    /// assert_eq!(epoch.to_string(), "86399.123456");
551    /// ```
552    pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
553        time_part(self.micros(), None, field)
554    }
555
556    /// PostgreSQL's `date_part(field, time)`.
557    ///
558    /// # Errors
559    ///
560    /// [`ExtractError::UnsupportedField`] for a field other than a clock field or `epoch`.
561    pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
562        time_part(self.micros(), None, field)
563    }
564}
565
566impl PgTimeTz {
567    /// PostgreSQL's `extract(field FROM timetz)`, the clock as written and its own offset.
568    ///
569    /// # Errors
570    ///
571    /// [`ExtractError::UnsupportedField`] for a field other than a clock or zone field or
572    /// `epoch`.
573    ///
574    /// ```
575    /// use sql_values::postgres::{ExtractField, PgNumeric, PgTime, PgTimeTz};
576    ///
577    /// let time = PgTime::from_hms_micro(12, 34, 56, 0).unwrap();
578    /// let india = PgTimeTz::new(time, 19_800).unwrap();
579    /// assert_eq!(india.extract(ExtractField::TimezoneMinute).unwrap(), Some(PgNumeric::from(30)));
580    /// ```
581    pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
582        time_part(self.time().micros(), Some(self.offset()), field)
583    }
584
585    /// PostgreSQL's `date_part(field, timetz)`.
586    ///
587    /// # Errors
588    ///
589    /// [`ExtractError::UnsupportedField`] for a field other than a clock or zone field or
590    /// `epoch`.
591    pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
592        time_part(self.time().micros(), Some(self.offset()), field)
593    }
594}
595
596impl PgTimestamp {
597    /// PostgreSQL's `extract(field FROM timestamp)`, at PostgreSQL's display scale: six digits
598    /// after the point for `second` and `epoch`, three for `milliseconds`, and the quotient's
599    /// for `julian`. An infinite timestamp has the infinity of its sign in the fields that grow
600    /// with time and `None`, SQL `NULL`, in the others.
601    ///
602    /// # Errors
603    ///
604    /// [`ExtractError::UnsupportedField`] for a zone field.
605    ///
606    /// ```
607    /// use sql_values::postgres::{ExtractField, InputContext, PgNumeric, PgTimestamp};
608    ///
609    /// let at = PgTimestamp::parse("2006-01-01 12:34:56.123456", InputContext::new()).unwrap();
610    /// let julian = at.extract(ExtractField::Julian).unwrap().unwrap();
611    /// assert_eq!(julian.to_string(), "2453737.52426068814814814815");
612    /// assert_eq!(at.extract(ExtractField::Week).unwrap(), Some(PgNumeric::from(52)));
613    /// assert_eq!(PgTimestamp::INFINITY.extract(ExtractField::Second).unwrap(), None);
614    /// ```
615    pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
616        timestamp_without_zone_part(self.pg_micros(), field)
617    }
618
619    /// PostgreSQL's `date_part(field, timestamp)`, in `double precision` arithmetic.
620    ///
621    /// # Errors
622    ///
623    /// [`ExtractError::UnsupportedField`] for a zone field.
624    ///
625    /// ```
626    /// use sql_values::postgres::{ExtractField, InputContext, PgTimestamp};
627    ///
628    /// let at = PgTimestamp::parse("0001-12-31 23:59:59.999999 BC", InputContext::new()).unwrap();
629    /// assert_eq!(at.date_part(ExtractField::Epoch).unwrap().unwrap().value(), -62135596800.0);
630    /// ```
631    pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
632        timestamp_without_zone_part(self.pg_micros(), field)
633    }
634}
635
636impl PgTimestampTz {
637    /// PostgreSQL's `extract(field FROM timestamptz)` with `zone` as the session's `TimeZone`:
638    /// the calendar and clock fields of the local clock, the zone fields of the offset at the
639    /// instant, and `epoch` of the instant alone.
640    ///
641    /// ```
642    /// use sql_values::postgres::{ExtractField, InputContext, PgNumeric, PgTimeZone, PgTimestampTz};
643    ///
644    /// #[cfg(feature = "tzdb")]
645    /// {
646    ///     let zone = PgTimeZone::parse("America/New_York").unwrap();
647    ///     let at = PgTimestampTz::parse("2024-03-10 07:30:00+00", InputContext::new()).unwrap();
648    ///     assert_eq!(at.extract(ExtractField::Hour, &zone), Some(PgNumeric::from(3)));
649    ///     let offset = at.extract(ExtractField::Timezone, &zone);
650    ///     assert_eq!(offset, Some(PgNumeric::from(-14_400)));
651    /// }
652    /// ```
653    #[must_use]
654    pub fn extract(self, field: ExtractField, zone: &PgTimeZone) -> Option<PgNumeric> {
655        timestamptz_part(self.pg_micros(), field, zone)
656    }
657
658    /// PostgreSQL's `date_part(field, timestamptz)` with `zone` as the session's `TimeZone`.
659    #[must_use]
660    pub fn date_part(self, field: ExtractField, zone: &PgTimeZone) -> Option<PgFloat8> {
661        timestamptz_part(self.pg_micros(), field, zone)
662    }
663}
664
665impl PgInterval {
666    /// PostgreSQL's `extract(field FROM interval)`, each field of the months, days and time
667    /// split toward zero, and `epoch` with a year as 365.25 days and a month as 30. An infinite
668    /// interval has the infinity of its sign in `hour`, `day`, the year fields and `epoch`, and
669    /// `None`, SQL `NULL`, in the others.
670    ///
671    /// # Errors
672    ///
673    /// [`ExtractError::UnsupportedField`] for a field of a day of the calendar or a zone.
674    ///
675    /// ```
676    /// use sql_values::postgres::{ExtractField, PgNumeric, parse_interval};
677    ///
678    /// let interval = parse_interval("-14 months -3 days -25:02:03.123456").unwrap();
679    /// let epoch = interval.extract(ExtractField::Epoch).unwrap().unwrap();
680    /// assert_eq!(epoch.to_string(), "-37090923.123456");
681    /// assert_eq!(interval.extract(ExtractField::Quarter).unwrap(), Some(PgNumeric::from(-1)));
682    /// ```
683    pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
684        self.part(field)
685    }
686
687    /// PostgreSQL's `date_part(field, interval)`.
688    ///
689    /// # Errors
690    ///
691    /// [`ExtractError::UnsupportedField`] for a field of a day of the calendar or a zone.
692    pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
693        self.part(field)
694    }
695
696    /// `interval_part_common`.
697    fn part<P: Part>(self, field: ExtractField) -> Result<Option<P>, ExtractError> {
698        let unsupported = ExtractError::unsupported(
699            field,
700            BuiltinType::Interval(super::IntervalTypmod::UNMODIFIED),
701        );
702        if !self.is_finite() {
703            return match field {
704                ExtractField::Microseconds
705                | ExtractField::Milliseconds
706                | ExtractField::Second
707                | ExtractField::Minute
708                | ExtractField::Week
709                | ExtractField::Month
710                | ExtractField::Quarter => Ok(None),
711                ExtractField::Hour
712                | ExtractField::Day
713                | ExtractField::Year
714                | ExtractField::Decade
715                | ExtractField::Century
716                | ExtractField::Millennium
717                | ExtractField::Epoch => Ok(Some(P::infinity(self.months == i32::MIN))),
718                _ => Err(unsupported),
719            };
720        }
721        let years = self.months / 12;
722        let value = match field {
723            ExtractField::Epoch => return Ok(Some(P::interval_epoch(self))),
724            ExtractField::Day => self.days,
725            ExtractField::Week => self.days / 7,
726            ExtractField::Month => self.months % 12,
727            ExtractField::Quarter if self.months >= 0 => self.months % 12 / 3 + 1,
728            // PostgreSQL negates the months unchecked, as its `-fwrapv` build wraps.
729            ExtractField::Quarter => -(self.months.wrapping_neg() % 12 / 3 + 1),
730            ExtractField::Year => years,
731            ExtractField::Decade => years / 10,
732            ExtractField::Century => years / 100,
733            ExtractField::Millennium => years / 1_000,
734            _ => {
735                return clock_part(field, self.microseconds)
736                    .map(Some)
737                    .ok_or(unsupported);
738            }
739        };
740        Ok(Some(P::integer(value.into())))
741    }
742}