Skip to main content

vortex_array/extension/datetime/
timestamp.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Temporal extension data types.
5
6use std::fmt;
7use std::sync::Arc;
8
9use jiff::fmt::temporal::DateTimeParser;
10use jiff::tz::TimeZone;
11use vortex_error::VortexExpect;
12use vortex_error::VortexResult;
13use vortex_error::vortex_bail;
14use vortex_error::vortex_ensure;
15use vortex_error::vortex_err;
16use vortex_error::vortex_panic;
17use vortex_session::registry::CachedId;
18
19use crate::dtype::DType;
20use crate::dtype::Nullability;
21use crate::dtype::PType;
22use crate::dtype::extension::ExtDType;
23use crate::dtype::extension::ExtId;
24use crate::dtype::extension::ExtVTable;
25use crate::extension::datetime::TimeUnit;
26use crate::scalar::ScalarValue;
27
28/// A timestamp stored as an `i64` count of seconds, milliseconds, microseconds, or nanoseconds.
29///
30/// Every storage value is valid. Formatting falls back to the raw count when jiff cannot format it.
31#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
32pub struct Timestamp;
33
34impl Timestamp {
35    /// Creates a timestamp dtype with the given time unit and nullability.
36    ///
37    /// # Panics
38    ///
39    /// Panics if `time_unit` is [`TimeUnit::Days`].
40    pub fn new(time_unit: TimeUnit, nullability: Nullability) -> ExtDType<Self> {
41        Self::new_with_tz(time_unit, None, nullability)
42    }
43
44    /// Creates a timestamp dtype with the given time unit, time zone, and nullability.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error for [`TimeUnit::Days`] or an unresolved time zone. IANA names and fixed
49    /// UTC offsets are accepted.
50    pub fn try_new_with_tz(
51        time_unit: TimeUnit,
52        timezone: Option<Arc<str>>,
53        nullability: Nullability,
54    ) -> VortexResult<ExtDType<Self>> {
55        ExtDType::try_new(
56            TimestampOptions {
57                unit: time_unit,
58                tz: timezone,
59            },
60            nullability,
61        )
62    }
63
64    /// Creates a timestamp dtype with the given time unit, time zone, and nullability.
65    ///
66    /// # Panics
67    ///
68    /// Panics if [`Self::try_new_with_tz`] rejects the unit or time zone.
69    pub fn new_with_tz(
70        time_unit: TimeUnit,
71        timezone: Option<Arc<str>>,
72        nullability: Nullability,
73    ) -> ExtDType<Self> {
74        Self::try_new_with_tz(time_unit, timezone, nullability)
75            .vortex_expect("timestamp unit and time zone must be valid")
76    }
77
78    /// Creates a timestamp dtype with the given options and nullability.
79    ///
80    /// # Panics
81    ///
82    /// Panics if [`Self::try_new_with_tz`] rejects the unit or time zone.
83    pub fn new_with_options(options: TimestampOptions, nullability: Nullability) -> ExtDType<Self> {
84        Self::new_with_tz(options.unit, options.tz, nullability)
85    }
86}
87
88/// Options for the Timestamp DType.
89#[derive(Clone, Debug, PartialEq, Eq, Hash)]
90pub struct TimestampOptions {
91    /// The time unit of the timestamp.
92    pub unit: TimeUnit,
93    /// The timezone of the timestamp, if any.
94    pub tz: Option<Arc<str>>,
95}
96
97impl fmt::Display for TimestampOptions {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match &self.tz {
100            Some(tz) => write!(f, "{}, tz={}", self.unit, tz),
101            None => write!(f, "{}", self.unit),
102        }
103    }
104}
105
106/// Resolve an Arrow timestamp timezone, accepting IANA names and fixed offsets.
107pub fn resolve_time_zone(name: Option<&str>) -> VortexResult<TimeZone> {
108    Ok(match name {
109        Some(name) if name.starts_with('+') || name.starts_with('-') => {
110            DateTimeParser::new().parse_time_zone(name)?
111        }
112        Some(name) => TimeZone::get(name)?,
113        None => TimeZone::UTC,
114    })
115}
116
117/// Unpacked value of a [`Timestamp`] extension scalar.
118///
119/// Each variant carries the raw storage value and an optional timezone.
120pub enum TimestampValue<'a> {
121    /// Seconds since the Unix epoch.
122    Seconds(i64, Option<&'a Arc<str>>),
123    /// Milliseconds since the Unix epoch.
124    Milliseconds(i64, Option<&'a Arc<str>>),
125    /// Microseconds since the Unix epoch.
126    Microseconds(i64, Option<&'a Arc<str>>),
127    /// Nanoseconds since the Unix epoch.
128    Nanoseconds(i64, Option<&'a Arc<str>>),
129}
130
131impl fmt::Display for TimestampValue<'_> {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        let (unit, value, tz) = match *self {
134            TimestampValue::Seconds(v, tz) => (TimeUnit::Seconds, v, tz),
135            TimestampValue::Milliseconds(v, tz) => (TimeUnit::Milliseconds, v, tz),
136            TimestampValue::Microseconds(v, tz) => (TimeUnit::Microseconds, v, tz),
137            TimestampValue::Nanoseconds(v, tz) => (TimeUnit::Nanoseconds, v, tz),
138        };
139
140        // jiff cannot format every storage value, including the last 26 hours of year 9999.
141        let Ok(ts) = unit
142            .to_jiff_span(value)
143            .and_then(|span| Ok(jiff::Timestamp::UNIX_EPOCH.checked_add(span)?))
144        else {
145            return write!(f, "{value}{unit}");
146        };
147
148        match tz {
149            None => write!(f, "{ts}"),
150            Some(tz) => {
151                let zone = resolve_time_zone(Some(tz)).vortex_expect("unknown timezone");
152                let adjusted_ts = ts.to_zoned_datetime(zone);
153                write!(f, "{adjusted_ts}",)
154            }
155        }
156    }
157}
158
159impl ExtVTable for Timestamp {
160    type Metadata = TimestampOptions;
161    type StoredMetadata = Self::Metadata;
162
163    type NativeValue<'a> = TimestampValue<'a>;
164
165    fn id(&self) -> ExtId {
166        static ID: CachedId = CachedId::new("vortex.timestamp");
167        *ID
168    }
169
170    // NOTE(ngates): unfortunately we're stuck with this hand-rolled serialization format for
171    //  backwards compatibility.
172    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
173        let mut bytes = Vec::with_capacity(4);
174        let unit_tag: u8 = metadata.unit.into();
175
176        bytes.push(unit_tag);
177
178        // Encode time_zone as u16 length followed by utf8 bytes.
179        match &metadata.tz {
180            None => bytes.extend_from_slice(0u16.to_le_bytes().as_slice()),
181            Some(tz) => {
182                let tz_bytes = tz.as_bytes();
183                let tz_len = u16::try_from(tz_bytes.len())
184                    .unwrap_or_else(|err| vortex_panic!("tz did not fit in u16: {}", err));
185                bytes.extend_from_slice(tz_len.to_le_bytes().as_slice());
186                bytes.extend_from_slice(tz_bytes);
187            }
188        }
189
190        Ok(bytes)
191    }
192
193    fn deserialize_metadata(&self, data: &[u8]) -> VortexResult<Self::StoredMetadata> {
194        vortex_ensure!(
195            data.len() >= 3,
196            "Timestamp metadata must have at least 3 bytes, got {}",
197            data.len()
198        );
199
200        let tag = data[0];
201        let time_unit = TimeUnit::try_from(tag)?;
202        let tz_len_bytes: [u8; 2] = data[1..3]
203            .try_into()
204            .ok()
205            .vortex_expect("Verified to have two bytes");
206        let tz_len = u16::from_le_bytes(tz_len_bytes) as usize;
207        if tz_len == 0 {
208            return Ok(TimestampOptions {
209                unit: time_unit,
210                tz: None,
211            });
212        }
213
214        // Attempt to load from len-prefixed bytes
215        vortex_ensure!(
216            data.len() >= 3 + tz_len,
217            "Timestamp metadata is truncated: declared timezone length {} but only {} bytes available",
218            tz_len,
219            data.len() - 3
220        );
221        let tz_bytes = &data[3..3 + tz_len];
222        let tz: Arc<str> = str::from_utf8(tz_bytes)
223            .map_err(|e| vortex_err!("timezone is not valid utf8 string: {e}"))?
224            .to_string()
225            .into();
226        Ok(TimestampOptions {
227            unit: time_unit,
228            tz: Some(tz),
229        })
230    }
231
232    fn metadata_from_storage(
233        &self,
234        stored_metadata: Self::StoredMetadata,
235        _storage_dtype: &DType,
236    ) -> VortexResult<Self::Metadata> {
237        Ok(stored_metadata)
238    }
239
240    fn storage_dtype(_metadata: &Self::Metadata) -> DType {
241        DType::Primitive(PType::I64, Nullability::NonNullable)
242    }
243
244    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
245        vortex_ensure!(
246            metadata.unit != TimeUnit::Days,
247            "Timestamp time unit must be finer than days, got {:?}",
248            metadata.unit
249        );
250        resolve_time_zone(metadata.tz.as_deref())?;
251
252        Ok(())
253    }
254
255    fn unpack_native<'a>(
256        ext_dtype: &'a ExtDType<Self>,
257        storage_value: &'a ScalarValue,
258    ) -> VortexResult<Self::NativeValue<'a>> {
259        let metadata = ext_dtype.metadata();
260        let ts_value = storage_value.as_primitive().cast::<i64>()?;
261        let tz = metadata.tz.as_ref();
262
263        Ok(match metadata.unit {
264            TimeUnit::Nanoseconds => TimestampValue::Nanoseconds(ts_value, tz),
265            TimeUnit::Microseconds => TimestampValue::Microseconds(ts_value, tz),
266            TimeUnit::Milliseconds => TimestampValue::Milliseconds(ts_value, tz),
267            TimeUnit::Seconds => TimestampValue::Seconds(ts_value, tz),
268            TimeUnit::Days => vortex_bail!("Timestamp does not support Days time unit"),
269        })
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use std::sync::Arc;
276
277    use rstest::rstest;
278    use vortex_error::VortexResult;
279
280    use crate::dtype::DType;
281    use crate::dtype::Nullability::Nullable;
282    use crate::extension::datetime::TimeUnit;
283    use crate::extension::datetime::Timestamp;
284    use crate::scalar::PValue;
285    use crate::scalar::Scalar;
286    use crate::scalar::ScalarValue;
287
288    #[test]
289    fn validate_timestamp_scalar() -> VortexResult<()> {
290        let dtype = DType::Extension(Timestamp::new(TimeUnit::Seconds, Nullable).erased());
291        Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(0))))?;
292
293        Ok(())
294    }
295
296    #[cfg_attr(miri, ignore)]
297    #[rstest]
298    #[case::end_of_9999(
299        TimeUnit::Microseconds,
300        253_402_214_400_000_000,
301        "253402214400000000µs"
302    )]
303    #[case::start_of_neg_9999(TimeUnit::Seconds, -377_705_116_800, "-377705116800s")]
304    #[case::max(TimeUnit::Microseconds, i64::MAX, "9223372036854775807µs")]
305    fn test_accept_timestamp_beyond_jiff_range(
306        #[case] unit: TimeUnit,
307        #[case] value: i64,
308        #[case] expected: &str,
309        #[values(None, Some(Arc::from("UTC")))] timezone: Option<Arc<str>>,
310    ) -> VortexResult<()> {
311        let dtype = DType::Extension(Timestamp::new_with_tz(unit, timezone, Nullable).erased());
312        let scalar = Scalar::try_new(dtype, Some(ScalarValue::from(value)))?;
313        assert_eq!(scalar.as_extension().to_string(), expected);
314
315        Ok(())
316    }
317
318    #[cfg_attr(miri, ignore)]
319    #[rstest]
320    #[case("+01:00", "1970-01-01T01:00:00+01:00[+01:00]")]
321    #[case("-05:30", "1969-12-31T18:30:00-05:30[-05:30]")]
322    fn display_fixed_offset_timestamp(
323        #[case] timezone: &str,
324        #[case] expected: &str,
325    ) -> VortexResult<()> {
326        let dtype = DType::Extension(
327            Timestamp::new_with_tz(TimeUnit::Seconds, Some(timezone.into()), Nullable).erased(),
328        );
329        let scalar = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(0))))?;
330        assert_eq!(format!("{}", scalar.as_extension()), expected);
331        Ok(())
332    }
333
334    #[cfg_attr(miri, ignore)]
335    #[test]
336    fn reject_timestamp_with_invalid_timezone() {
337        assert!(
338            Timestamp::try_new_with_tz(
339                TimeUnit::Seconds,
340                Some(Arc::from("Not/A/Timezone")),
341                Nullable,
342            )
343            .is_err()
344        );
345    }
346
347    #[test]
348    fn test_reject_timestamp_days() {
349        assert!(Timestamp::try_new_with_tz(TimeUnit::Days, None, Nullable).is_err());
350    }
351
352    #[rstest]
353    #[case::seconds(TimeUnit::Seconds, i64::MAX)]
354    #[case::milliseconds(TimeUnit::Milliseconds, i64::MAX)]
355    #[case::microseconds(TimeUnit::Microseconds, i64::MAX)]
356    #[case::nanoseconds(TimeUnit::Nanoseconds, i64::MIN)]
357    fn test_accept_timestamp_storage_extremes(
358        #[case] unit: TimeUnit,
359        #[case] value: i64,
360    ) -> VortexResult<()> {
361        let dtype = DType::Extension(Timestamp::new(unit, Nullable).erased());
362        Scalar::try_new(dtype, Some(ScalarValue::from(value)))?;
363
364        Ok(())
365    }
366
367    #[cfg_attr(miri, ignore)]
368    #[test]
369    fn display_timestamp_scalar() {
370        // Local (no timezone) timestamp.
371        let local_dtype = DType::Extension(Timestamp::new(TimeUnit::Seconds, Nullable).erased());
372        let scalar = Scalar::new(local_dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
373        assert_eq!(format!("{}", scalar.as_extension()), "1970-01-01T00:00:00Z");
374
375        // Zoned timestamp.
376        let zoned_dtype = DType::Extension(
377            Timestamp::new_with_tz(
378                TimeUnit::Seconds,
379                Some(Arc::from("America/New_York")),
380                Nullable,
381            )
382            .erased(),
383        );
384        let scalar = Scalar::new(zoned_dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
385        assert_eq!(
386            format!("{}", scalar.as_extension()),
387            "1969-12-31T19:00:00-05:00[America/New_York]"
388        );
389    }
390
391    #[test]
392    fn deserialize_empty_metadata_returns_error() {
393        use crate::dtype::extension::ExtVTable;
394
395        let vtable = Timestamp;
396        assert!(vtable.deserialize_metadata(&[]).is_err());
397    }
398
399    #[test]
400    fn deserialize_too_short_metadata_returns_error() {
401        use crate::dtype::extension::ExtVTable;
402
403        let vtable = Timestamp;
404        // Only 2 bytes - too short for the required 3-byte header.
405        assert!(vtable.deserialize_metadata(&[0x00, 0x01]).is_err());
406    }
407
408    #[test]
409    fn deserialize_truncated_timezone_returns_error() {
410        use crate::dtype::extension::ExtVTable;
411
412        let vtable = Timestamp;
413        // Valid tag (0x00 = Nanoseconds), tz_len = 10 (little-endian: [0x0A, 0x00]),
414        // but only 3 bytes of timezone data instead of the declared 10.
415        let data = [0x00u8, 0x0A, 0x00, b'U', b'T', b'C'];
416        assert!(vtable.deserialize_metadata(&data).is_err());
417    }
418}