Skip to main content

vortex_array/extension/datetime/
date.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt;
5
6use vortex_error::VortexExpect;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10use vortex_session::registry::CachedId;
11
12use crate::dtype::DType;
13use crate::dtype::Nullability;
14use crate::dtype::PType;
15use crate::dtype::extension::ExtDType;
16use crate::dtype::extension::ExtId;
17use crate::dtype::extension::ExtVTable;
18use crate::extension::datetime::TimeUnit;
19use crate::scalar::ScalarValue;
20
21/// The Unix epoch date (1970-01-01).
22const EPOCH: jiff::civil::Date = jiff::civil::Date::constant(1970, 1, 1);
23
24/// Date DType.
25#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
26pub struct Date;
27
28fn date_ptype(time_unit: &TimeUnit) -> Option<PType> {
29    match time_unit {
30        TimeUnit::Nanoseconds => None,
31        TimeUnit::Microseconds => None,
32        TimeUnit::Milliseconds => Some(PType::I64),
33        TimeUnit::Seconds => None,
34        TimeUnit::Days => Some(PType::I32),
35    }
36}
37
38impl Date {
39    /// Creates a new Date extension dtype with the given time unit and nullability.
40    ///
41    /// Note that only Milliseconds and Days time units are supported for Date.
42    pub fn try_new(time_unit: TimeUnit, nullability: Nullability) -> VortexResult<ExtDType<Self>> {
43        ExtDType::try_new(time_unit, nullability)
44    }
45
46    /// Creates a new Date extension dtype with the given time unit and nullability.
47    ///
48    /// # Panics
49    ///
50    /// Panics if the `time_unit` is not supported by date types.
51    pub fn new(time_unit: TimeUnit, nullability: Nullability) -> ExtDType<Self> {
52        Self::try_new(time_unit, nullability).vortex_expect("failed to create date dtype")
53    }
54}
55
56/// Unpacked value of a [`Date`] extension scalar.
57pub enum DateValue {
58    /// Days since the Unix epoch.
59    Days(i32),
60    /// Milliseconds since the Unix epoch.
61    Milliseconds(i64),
62}
63
64impl fmt::Display for DateValue {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        let (unit, value) = match *self {
67            DateValue::Days(days) => (TimeUnit::Days, i64::from(days)),
68            DateValue::Milliseconds(ms) => (TimeUnit::Milliseconds, ms),
69        };
70
71        // jiff cannot hold every storage value, such as any date after the year 9999.
72        let Ok(date) = unit
73            .to_jiff_span(value)
74            .and_then(|span| Ok(EPOCH.checked_add(span)?))
75        else {
76            return write!(f, "{value}{unit}");
77        };
78
79        write!(f, "{date}")
80    }
81}
82
83impl ExtVTable for Date {
84    type Metadata = TimeUnit;
85    type StoredMetadata = Self::Metadata;
86    type NativeValue<'a> = DateValue;
87
88    fn id(&self) -> ExtId {
89        static ID: CachedId = CachedId::new("vortex.date");
90        *ID
91    }
92
93    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
94        Ok(vec![u8::from(*metadata)])
95    }
96
97    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::StoredMetadata> {
98        vortex_ensure!(!metadata.is_empty(), "Date metadata must not be empty");
99        let tag = metadata[0];
100        TimeUnit::try_from(tag)
101    }
102
103    fn metadata_from_storage(
104        &self,
105        stored_metadata: Self::StoredMetadata,
106        _storage_dtype: &DType,
107    ) -> VortexResult<Self::Metadata> {
108        Ok(stored_metadata)
109    }
110
111    fn storage_dtype(metadata: &Self::Metadata) -> DType {
112        let ptype = date_ptype(metadata)
113            .vortex_expect("Date::validate_metadata accepts only days and milliseconds");
114        DType::Primitive(ptype, Nullability::NonNullable)
115    }
116
117    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
118        vortex_ensure!(
119            date_ptype(metadata).is_some(),
120            "Date time unit must be days or milliseconds, got {metadata}"
121        );
122
123        Ok(())
124    }
125
126    fn unpack_native<'a>(
127        ext_dtype: &'a ExtDType<Self>,
128        storage_value: &'a ScalarValue,
129    ) -> VortexResult<Self::NativeValue<'a>> {
130        let metadata = ext_dtype.metadata();
131        match metadata {
132            TimeUnit::Milliseconds => Ok(DateValue::Milliseconds(
133                storage_value.as_primitive().cast::<i64>()?,
134            )),
135            TimeUnit::Days => Ok(DateValue::Days(storage_value.as_primitive().cast::<i32>()?)),
136            _ => vortex_bail!("Date type does not support time unit {}", metadata),
137        }
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use rstest::rstest;
144    use vortex_error::VortexResult;
145
146    use crate::dtype::DType;
147    use crate::dtype::Nullability::Nullable;
148    use crate::dtype::extension::ExtDTypePlugin;
149    use crate::extension::datetime::Date;
150    use crate::extension::datetime::DateValue;
151    use crate::extension::datetime::TimeUnit;
152    use crate::scalar::PValue;
153    use crate::scalar::Scalar;
154    use crate::scalar::ScalarValue;
155
156    #[test]
157    fn test_read_rejects_non_primitive_storage() {
158        let result = Date.deserialize(&[u8::from(TimeUnit::Days)], DType::Utf8(Nullable));
159        assert!(result.is_err_and(|error| {
160            error
161                .to_string()
162                .contains("vortex.date storage must be i32?, got utf8?")
163        }));
164    }
165
166    #[test]
167    fn validate_date_scalar() -> VortexResult<()> {
168        let days_dtype = DType::Extension(Date::new(TimeUnit::Days, Nullable).erased());
169        Scalar::try_new(days_dtype, Some(ScalarValue::Primitive(PValue::I32(0))))?;
170
171        let ms_dtype = DType::Extension(Date::new(TimeUnit::Milliseconds, Nullable).erased());
172        Scalar::try_new(
173            ms_dtype,
174            Some(ScalarValue::Primitive(PValue::I64(86_400_000))),
175        )?;
176
177        Ok(())
178    }
179
180    #[test]
181    fn reject_date_with_overflowing_value() {
182        // Days storage is `I32`, so an `I64` value that overflows `i32` should fail the cast.
183        let dtype = DType::Extension(Date::new(TimeUnit::Days, Nullable).erased());
184        let result = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(i64::MAX))));
185        assert!(result.is_err());
186    }
187
188    #[test]
189    fn display_date_scalar() {
190        let dtype = DType::Extension(Date::new(TimeUnit::Days, Nullable).erased());
191
192        let scalar = Scalar::new(dtype.clone(), Some(ScalarValue::Primitive(PValue::I32(0))));
193        assert_eq!(format!("{}", scalar.as_extension()), "1970-01-01");
194
195        let scalar = Scalar::new(dtype, Some(ScalarValue::Primitive(PValue::I32(365))));
196        assert_eq!(format!("{}", scalar.as_extension()), "1971-01-01");
197    }
198
199    #[rstest]
200    #[case::ordinary(DateValue::Milliseconds(86_400_000), "1970-01-02")]
201    #[case::after_year_9999(DateValue::Days(2_932_897), "2932897days")]
202    #[case::beyond_jiff_span(DateValue::Days(10_000_000), "10000000days")]
203    #[case::max_milliseconds(DateValue::Milliseconds(i64::MAX), "9223372036854775807ms")]
204    fn display_date_value(#[case] value: DateValue, #[case] expected: &str) {
205        assert_eq!(value.to_string(), expected);
206    }
207
208    #[test]
209    fn deserialize_empty_metadata_returns_error() {
210        use crate::dtype::extension::ExtVTable;
211
212        let vtable = Date;
213        assert!(vtable.deserialize_metadata(&[]).is_err());
214    }
215
216    #[test]
217    fn deserialize_invalid_tag_returns_error() {
218        use crate::dtype::extension::ExtVTable;
219
220        let vtable = Date;
221        // 0xFF is not a valid TimeUnit tag.
222        assert!(vtable.deserialize_metadata(&[0xFF]).is_err());
223    }
224}