Skip to main content

vortex_array/extension/datetime/
matcher.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::sync::Arc;
6
7use vortex_error::VortexResult;
8
9use crate::dtype::extension::ExtDTypeRef;
10use crate::dtype::extension::ExtVTable;
11use crate::dtype::extension::Matcher;
12use crate::extension::datetime::Date;
13use crate::extension::datetime::Duration;
14use crate::extension::datetime::Time;
15use crate::extension::datetime::TimeUnit;
16use crate::extension::datetime::Timestamp;
17
18/// Matcher for temporal extension data types.
19pub struct AnyTemporal;
20
21impl Matcher for AnyTemporal {
22    type Match<'a> = TemporalMetadata<'a>;
23
24    fn try_match<'a>(item: &'a ExtDTypeRef) -> Option<Self::Match<'a>> {
25        if let Some(opts) = item.metadata_opt::<Timestamp>() {
26            return Some(TemporalMetadata::Timestamp(&opts.unit, &opts.tz));
27        }
28        if let Some(opts) = item.metadata_opt::<Date>() {
29            return Some(TemporalMetadata::Date(opts));
30        }
31        if let Some(opts) = item.metadata_opt::<Time>() {
32            return Some(TemporalMetadata::Time(opts));
33        }
34        if let Some(opts) = item.metadata_opt::<Duration>() {
35            return Some(TemporalMetadata::Duration(opts));
36        }
37        None
38    }
39}
40
41/// Metadata for temporal extension data types.
42#[derive(Debug, PartialEq, Eq)]
43pub enum TemporalMetadata<'a> {
44    /// Metadata for Timestamp dtypes, a tuple of time unit and optional timezone.
45    Timestamp(&'a TimeUnit, &'a Option<Arc<str>>),
46    /// Metadata for Date dtypes
47    Date(&'a <Date as ExtVTable>::Metadata),
48    /// Metadata for Time dtypes
49    Time(&'a <Time as ExtVTable>::Metadata),
50    /// Metadata for [`Duration`] dtypes.
51    Duration(&'a <Duration as ExtVTable>::Metadata),
52}
53
54// TODO(ngates): remove this logic in favor of having an ExtScalarVTable in vortex_array::scalar.
55//  Currently this is used largely to implement scalar display hacks.
56impl TemporalMetadata<'_> {
57    /// Get the time unit of the temporal dtype.
58    pub fn time_unit(&self) -> TimeUnit {
59        match self {
60            TemporalMetadata::Time(unit) => **unit,
61            TemporalMetadata::Date(unit) => **unit,
62            TemporalMetadata::Timestamp(unit, _tz) => **unit,
63            TemporalMetadata::Duration(unit) => **unit,
64        }
65    }
66
67    /// Convert a timestamp value to a Jiff value.
68    pub fn to_jiff(&self, v: i64) -> VortexResult<TemporalJiff> {
69        match self {
70            TemporalMetadata::Time(unit) => Ok(TemporalJiff::Time(
71                jiff::civil::Time::MIN.checked_add(unit.to_jiff_span(v)?)?,
72            )),
73            TemporalMetadata::Date(unit) => Ok(TemporalJiff::Date(
74                jiff::civil::Date::new(1970, 1, 1)?.checked_add(unit.to_jiff_span(v)?)?,
75            )),
76            TemporalMetadata::Timestamp(unit, tz) => match tz {
77                None => Ok(TemporalJiff::Unzoned(
78                    jiff::civil::DateTime::new(1970, 1, 1, 0, 0, 0, 0)?
79                        .checked_add(unit.to_jiff_span(v)?)?,
80                )),
81                Some(tz) => Ok(TemporalJiff::Zoned(
82                    jiff::Timestamp::UNIX_EPOCH
83                        .checked_add(unit.to_jiff_span(v)?)?
84                        .in_tz(tz.as_ref())?,
85                )),
86            },
87            TemporalMetadata::Duration(unit) => Ok(TemporalJiff::Duration(unit.to_jiff_span(v)?)),
88        }
89    }
90}
91
92/// A Jiff representation of a temporal value.
93pub enum TemporalJiff {
94    /// A time value.
95    Time(jiff::civil::Time),
96    /// A date value.
97    Date(jiff::civil::Date),
98    /// A zone-naive timestamp value.
99    Unzoned(jiff::civil::DateTime),
100    /// A zoned timestamp value.
101    Zoned(jiff::ZonedDateTime),
102    /// A duration value.
103    Duration(jiff::Span),
104}
105
106impl Display for TemporalJiff {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        match self {
109            TemporalJiff::Time(t) => write!(f, "{t}"),
110            TemporalJiff::Date(d) => write!(f, "{d}"),
111            TemporalJiff::Unzoned(dt) => write!(f, "{dt}"),
112            TemporalJiff::Zoned(z) => write!(f, "{z}"),
113            TemporalJiff::Duration(d) => write!(f, "{d}"),
114        }
115    }
116}