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/// Check that a count of `unit` lies within one day, as every [`Time`] value must.
50///
51/// An array does not check the values of its rows, so a conversion that reads or produces a time
52/// of day checks each count itself.
53pub fn check_time_of_day(value: i64, unit: TimeUnit) -> VortexResult<()> {
54    vortex_ensure!(
55        (0..unit.units_per_day()).contains(&value),
56        "Expected a time of day in {unit}, got {value}"
57    );
58    Ok(())
59}
60
61/// Unpacked value of a [`Time`] extension scalar.
62pub enum TimeValue {
63    /// Seconds since midnight.
64    Seconds(i32),
65    /// Milliseconds since midnight.
66    Milliseconds(i32),
67    /// Microseconds since midnight.
68    Microseconds(i64),
69    /// Nanoseconds since midnight.
70    Nanoseconds(i64),
71}
72
73impl fmt::Display for TimeValue {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        let min = jiff::civil::Time::MIN;
76
77        let time = match self {
78            TimeValue::Seconds(s) => min + Span::new().seconds(*s),
79            TimeValue::Milliseconds(ms) => min + Span::new().milliseconds(*ms),
80            TimeValue::Microseconds(us) => min + Span::new().microseconds(*us),
81            TimeValue::Nanoseconds(ns) => min + Span::new().nanoseconds(*ns),
82        };
83
84        write!(f, "{}", time)
85    }
86}
87
88impl ExtVTable for Time {
89    type Metadata = TimeUnit;
90    type StoredMetadata = Self::Metadata;
91
92    type NativeValue<'a> = TimeValue;
93
94    fn id(&self) -> ExtId {
95        static ID: CachedId = CachedId::new("vortex.time");
96        *ID
97    }
98
99    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
100        Ok(vec![u8::from(*metadata)])
101    }
102
103    fn deserialize_metadata(&self, data: &[u8]) -> VortexResult<Self::StoredMetadata> {
104        vortex_ensure!(!data.is_empty(), "Time metadata must not be empty");
105        let tag = data[0];
106        TimeUnit::try_from(tag)
107    }
108
109    fn metadata_from_storage(
110        &self,
111        stored_metadata: Self::StoredMetadata,
112        _storage_dtype: &DType,
113    ) -> VortexResult<Self::Metadata> {
114        Ok(stored_metadata)
115    }
116
117    fn storage_dtype(metadata: &Self::Metadata) -> DType {
118        let ptype = time_ptype(metadata).vortex_expect("Time::validate_metadata rejects days");
119        DType::Primitive(ptype, Nullability::NonNullable)
120    }
121
122    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
123        vortex_ensure!(
124            time_ptype(metadata).is_some(),
125            "Time time unit must be finer than days, got {metadata}"
126        );
127
128        Ok(())
129    }
130
131    fn unpack_native<'a>(
132        ext_dtype: &'a ExtDType<Self>,
133        storage_value: &'a ScalarValue,
134    ) -> VortexResult<Self::NativeValue<'a>> {
135        let length_of_time = storage_value.as_primitive().cast::<i64>()?;
136
137        let (span, value) = match *ext_dtype.metadata() {
138            TimeUnit::Seconds => {
139                let v = i32::try_from(length_of_time)
140                    .map_err(|e| vortex_err!("Time seconds value out of i32 range: {e}"))?;
141                (Span::new().try_seconds(v)?, TimeValue::Seconds(v))
142            }
143            TimeUnit::Milliseconds => {
144                let v = i32::try_from(length_of_time)
145                    .map_err(|e| vortex_err!("Time milliseconds value out of i32 range: {e}"))?;
146                (Span::new().try_milliseconds(v)?, TimeValue::Milliseconds(v))
147            }
148            TimeUnit::Microseconds => (
149                Span::new().try_microseconds(length_of_time)?,
150                TimeValue::Microseconds(length_of_time),
151            ),
152            TimeUnit::Nanoseconds => (
153                Span::new().try_nanoseconds(length_of_time)?,
154                TimeValue::Nanoseconds(length_of_time),
155            ),
156            d @ TimeUnit::Days => {
157                vortex_bail!("Time type does not support time unit {d}")
158            }
159        };
160
161        // Validate the storage value is within the valid range for Time.
162        jiff::civil::Time::MIN
163            .checked_add(span)
164            .map_err(|e| vortex_err!("Invalid time scalar: {}", e))?;
165
166        Ok(value)
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use rstest::rstest;
173    use vortex_error::VortexResult;
174
175    use crate::dtype::DType;
176    use crate::dtype::Nullability::Nullable;
177    use crate::dtype::extension::ExtDTypePlugin;
178    use crate::extension::datetime::Time;
179    use crate::extension::datetime::TimeUnit;
180    use crate::scalar::PValue;
181    use crate::scalar::Scalar;
182    use crate::scalar::ScalarValue;
183
184    #[rstest]
185    #[case::microseconds(TimeUnit::Microseconds, i64::MAX)]
186    #[case::nanoseconds(TimeUnit::Nanoseconds, i64::MIN)]
187    fn test_reject_time_span_out_of_range(#[case] unit: TimeUnit, #[case] value: i64) {
188        let dtype = DType::Extension(Time::new(unit, Nullable).erased());
189        assert!(Scalar::try_new(dtype, Some(ScalarValue::from(value))).is_err());
190    }
191
192    #[test]
193    fn test_read_rejects_non_primitive_storage() {
194        let result = Time.deserialize(&[u8::from(TimeUnit::Seconds)], DType::Utf8(Nullable));
195        assert!(result.is_err_and(|error| {
196            error
197                .to_string()
198                .contains("vortex.time storage must be i32?, got utf8?")
199        }));
200    }
201
202    #[test]
203    fn validate_time_scalar() -> VortexResult<()> {
204        // 3661 seconds = 1 hour, 1 minute, 1 second.
205        let dtype = DType::Extension(Time::new(TimeUnit::Seconds, Nullable).erased());
206        Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I32(3661))))?;
207
208        Ok(())
209    }
210
211    #[test]
212    fn reject_time_out_of_range() {
213        // 86400 seconds = exactly 24 hours, which exceeds the valid `jiff::civil::Time` range.
214        let dtype = DType::Extension(Time::new(TimeUnit::Seconds, Nullable).erased());
215        let result = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I32(86400))));
216        assert!(result.is_err());
217    }
218
219    #[test]
220    fn display_time_scalar() {
221        let dtype = DType::Extension(Time::new(TimeUnit::Seconds, Nullable).erased());
222
223        let scalar = Scalar::new(
224            dtype.clone(),
225            Some(ScalarValue::Primitive(PValue::I32(3661))),
226        );
227        assert_eq!(format!("{}", scalar.as_extension()), "01:01:01");
228
229        let scalar = Scalar::new(dtype, Some(ScalarValue::Primitive(PValue::I32(0))));
230        assert_eq!(format!("{}", scalar.as_extension()), "00:00:00");
231    }
232
233    #[test]
234    fn deserialize_empty_metadata_returns_error() {
235        use crate::dtype::extension::ExtVTable;
236
237        let vtable = Time;
238        assert!(vtable.deserialize_metadata(&[]).is_err());
239    }
240
241    #[test]
242    fn deserialize_invalid_tag_returns_error() {
243        use crate::dtype::extension::ExtVTable;
244
245        let vtable = Time;
246        // 0xFF is not a valid TimeUnit tag.
247        assert!(vtable.deserialize_metadata(&[0xFF]).is_err());
248    }
249}