1use 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;
25const EPOCH_MICROS: i64 = -UNIX_TO_POSTGRES_SECS * USECS_PER_SEC;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum ExtractField {
40 Microseconds,
42 Milliseconds,
44 Second,
46 Minute,
48 Hour,
50 Day,
52 Week,
54 Month,
56 Quarter,
58 Year,
60 Decade,
62 Century,
64 Millennium,
66 DayOfWeek,
68 IsoDayOfWeek,
70 DayOfYear,
72 IsoYear,
74 Epoch,
76 Julian,
78 Timezone,
80 TimezoneHour,
82 TimezoneMinute,
84}
85
86impl ExtractField {
87 #[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
171pub enum ExtractError {
172 #[error("unit \"{field}\" not supported for type {input_type}")]
174 UnsupportedField {
175 field: ExtractField,
177 input_type: BuiltinType,
179 },
180 #[error("date out of range for timestamp")]
182 DateOutOfRangeForTimestamp,
183}
184
185trait Part: Sized {
188 fn integer(value: i64) -> Self;
190
191 fn infinity(negative: bool) -> Self;
193
194 fn milliseconds(seconds: i64, micros: i64) -> Self;
196
197 fn seconds(seconds: i64, micros: i64) -> Self;
199
200 fn julian(day: i32, clock: i64) -> Self;
202
203 fn timestamp_epoch(micros: i64) -> Self;
205
206 fn clock_epoch(clock: i64, zone: i32) -> Self;
208
209 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 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
328fn 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
342fn 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
374const fn j2day(julian: i32) -> i32 {
376 (julian + 1).rem_euclid(7)
377}
378
379const fn iso_year_start(year: i32) -> i32 {
381 let fourth = date2j(year, 1, 4);
382 fourth - j2day(fourth - 1)
383}
384
385const 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
403fn 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
432fn 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
443fn 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
448fn 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 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 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 pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
553 time_part(self.micros(), None, field)
554 }
555
556 pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
562 time_part(self.micros(), None, field)
563 }
564}
565
566impl PgTimeTz {
567 pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
582 time_part(self.time().micros(), Some(self.offset()), field)
583 }
584
585 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 pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
616 timestamp_without_zone_part(self.pg_micros(), field)
617 }
618
619 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 #[must_use]
654 pub fn extract(self, field: ExtractField, zone: &PgTimeZone) -> Option<PgNumeric> {
655 timestamptz_part(self.pg_micros(), field, zone)
656 }
657
658 #[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 pub fn extract(self, field: ExtractField) -> Result<Option<PgNumeric>, ExtractError> {
684 self.part(field)
685 }
686
687 pub fn date_part(self, field: ExtractField) -> Result<Option<PgFloat8>, ExtractError> {
693 self.part(field)
694 }
695
696 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 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}