Skip to main content

vortex_array/extension/datetime/
time.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt;
5
6use jiff::Span;
7use vortex_error::VortexExpect;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10use vortex_error::vortex_ensure;
11use vortex_error::vortex_err;
12use vortex_session::registry::CachedId;
13
14use crate::dtype::DType;
15use crate::dtype::Nullability;
16use crate::dtype::PType;
17use crate::dtype::extension::ExtDType;
18use crate::dtype::extension::ExtId;
19use crate::dtype::extension::ExtVTable;
20use crate::extension::datetime::TimeUnit;
21use crate::scalar::ScalarValue;
22
23/// Time DType.
24#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
25pub struct Time;
26
27fn time_ptype(time_unit: &TimeUnit) -> Option<PType> {
28    Some(match time_unit {
29        TimeUnit::Nanoseconds | TimeUnit::Microseconds => PType::I64,
30        TimeUnit::Milliseconds | TimeUnit::Seconds => PType::I32,
31        TimeUnit::Days => return None,
32    })
33}
34
35impl Time {
36    /// Creates a new Time extension dtype with the given time unit and nullability.
37    ///
38    /// Note that Days units are not supported for Time.
39    pub fn try_new(time_unit: TimeUnit, nullability: Nullability) -> VortexResult<ExtDType<Self>> {
40        ExtDType::try_new(time_unit, nullability)
41    }
42
43    /// Creates a new Time extension dtype with the given time unit and nullability.
44    pub fn new(time_unit: TimeUnit, nullability: Nullability) -> ExtDType<Self> {
45        Self::try_new(time_unit, nullability).vortex_expect("failed to create time dtype")
46    }
47}
48
49/// Unpacked value of a [`Time`] extension scalar.
50pub enum TimeValue {
51    /// Seconds since midnight.
52    Seconds(i32),
53    /// Milliseconds since midnight.
54    Milliseconds(i32),
55    /// Microseconds since midnight.
56    Microseconds(i64),
57    /// Nanoseconds since midnight.
58    Nanoseconds(i64),
59}
60
61impl fmt::Display for TimeValue {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        let min = jiff::civil::Time::MIN;
64
65        let time = match self {
66            TimeValue::Seconds(s) => min + Span::new().seconds(*s),
67            TimeValue::Milliseconds(ms) => min + Span::new().milliseconds(*ms),
68            TimeValue::Microseconds(us) => min + Span::new().microseconds(*us),
69            TimeValue::Nanoseconds(ns) => min + Span::new().nanoseconds(*ns),
70        };
71
72        write!(f, "{}", time)
73    }
74}
75
76impl ExtVTable for Time {
77    type Metadata = TimeUnit;
78    type StoredMetadata = Self::Metadata;
79
80    type NativeValue<'a> = TimeValue;
81
82    fn id(&self) -> ExtId {
83        static ID: CachedId = CachedId::new("vortex.time");
84        *ID
85    }
86
87    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
88        Ok(vec![u8::from(*metadata)])
89    }
90
91    fn deserialize_metadata(&self, data: &[u8]) -> VortexResult<Self::StoredMetadata> {
92        vortex_ensure!(!data.is_empty(), "Time metadata must not be empty");
93        let tag = data[0];
94        TimeUnit::try_from(tag)
95    }
96
97    fn metadata_from_storage(
98        &self,
99        stored_metadata: Self::StoredMetadata,
100        _storage_dtype: &DType,
101    ) -> VortexResult<Self::Metadata> {
102        Ok(stored_metadata)
103    }
104
105    fn storage_dtype(metadata: &Self::Metadata) -> DType {
106        let ptype = time_ptype(metadata).vortex_expect("Time::validate_metadata rejects days");
107        DType::Primitive(ptype, Nullability::NonNullable)
108    }
109
110    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
111        vortex_ensure!(
112            time_ptype(metadata).is_some(),
113            "Time time unit must be finer than days, got {metadata}"
114        );
115
116        Ok(())
117    }
118
119    fn unpack_native<'a>(
120        ext_dtype: &'a ExtDType<Self>,
121        storage_value: &'a ScalarValue,
122    ) -> VortexResult<Self::NativeValue<'a>> {
123        let length_of_time = storage_value.as_primitive().cast::<i64>()?;
124
125        let (span, value) = match *ext_dtype.metadata() {
126            TimeUnit::Seconds => {
127                let v = i32::try_from(length_of_time)
128                    .map_err(|e| vortex_err!("Time seconds value out of i32 range: {e}"))?;
129                (Span::new().try_seconds(v)?, TimeValue::Seconds(v))
130            }
131            TimeUnit::Milliseconds => {
132                let v = i32::try_from(length_of_time)
133                    .map_err(|e| vortex_err!("Time milliseconds value out of i32 range: {e}"))?;
134                (Span::new().try_milliseconds(v)?, TimeValue::Milliseconds(v))
135            }
136            TimeUnit::Microseconds => (
137                Span::new().try_microseconds(length_of_time)?,
138                TimeValue::Microseconds(length_of_time),
139            ),
140            TimeUnit::Nanoseconds => (
141                Span::new().try_nanoseconds(length_of_time)?,
142                TimeValue::Nanoseconds(length_of_time),
143            ),
144            d @ TimeUnit::Days => {
145                vortex_bail!("Time type does not support time unit {d}")
146            }
147        };
148
149        // Validate the storage value is within the valid range for Time.
150        jiff::civil::Time::MIN
151            .checked_add(span)
152            .map_err(|e| vortex_err!("Invalid time scalar: {}", e))?;
153
154        Ok(value)
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use rstest::rstest;
161    use vortex_error::VortexResult;
162
163    use crate::dtype::DType;
164    use crate::dtype::Nullability::Nullable;
165    use crate::dtype::extension::ExtDTypePlugin;
166    use crate::extension::datetime::Time;
167    use crate::extension::datetime::TimeUnit;
168    use crate::scalar::PValue;
169    use crate::scalar::Scalar;
170    use crate::scalar::ScalarValue;
171
172    #[rstest]
173    #[case::microseconds(TimeUnit::Microseconds, i64::MAX)]
174    #[case::nanoseconds(TimeUnit::Nanoseconds, i64::MIN)]
175    fn test_reject_time_span_out_of_range(#[case] unit: TimeUnit, #[case] value: i64) {
176        let dtype = DType::Extension(Time::new(unit, Nullable).erased());
177        assert!(Scalar::try_new(dtype, Some(ScalarValue::from(value))).is_err());
178    }
179
180    #[test]
181    fn test_read_rejects_non_primitive_storage() {
182        let result = Time.deserialize(&[u8::from(TimeUnit::Seconds)], DType::Utf8(Nullable));
183        assert!(result.is_err_and(|error| {
184            error
185                .to_string()
186                .contains("vortex.time storage must be i32?, got utf8?")
187        }));
188    }
189
190    #[test]
191    fn validate_time_scalar() -> VortexResult<()> {
192        // 3661 seconds = 1 hour, 1 minute, 1 second.
193        let dtype = DType::Extension(Time::new(TimeUnit::Seconds, Nullable).erased());
194        Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I32(3661))))?;
195
196        Ok(())
197    }
198
199    #[test]
200    fn reject_time_out_of_range() {
201        // 86400 seconds = exactly 24 hours, which exceeds the valid `jiff::civil::Time` range.
202        let dtype = DType::Extension(Time::new(TimeUnit::Seconds, Nullable).erased());
203        let result = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I32(86400))));
204        assert!(result.is_err());
205    }
206
207    #[test]
208    fn display_time_scalar() {
209        let dtype = DType::Extension(Time::new(TimeUnit::Seconds, Nullable).erased());
210
211        let scalar = Scalar::new(
212            dtype.clone(),
213            Some(ScalarValue::Primitive(PValue::I32(3661))),
214        );
215        assert_eq!(format!("{}", scalar.as_extension()), "01:01:01");
216
217        let scalar = Scalar::new(dtype, Some(ScalarValue::Primitive(PValue::I32(0))));
218        assert_eq!(format!("{}", scalar.as_extension()), "00:00:00");
219    }
220
221    #[test]
222    fn deserialize_empty_metadata_returns_error() {
223        use crate::dtype::extension::ExtVTable;
224
225        let vtable = Time;
226        assert!(vtable.deserialize_metadata(&[]).is_err());
227    }
228
229    #[test]
230    fn deserialize_invalid_tag_returns_error() {
231        use crate::dtype::extension::ExtVTable;
232
233        let vtable = Time;
234        // 0xFF is not a valid TimeUnit tag.
235        assert!(vtable.deserialize_metadata(&[0xFF]).is_err());
236    }
237}