Skip to main content

vortex_array/arrays/datetime/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Typed wrappers for temporal extension arrays.
5//!
6//! [`TemporalData`] gives date, time, and timestamp arrays a shared storage interface. The extension
7//! dtype retains each type's unit and metadata while the underlying array stores numeric values.
8
9use std::sync::Arc;
10
11use vortex_error::VortexError;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_err;
14
15use crate::ArrayRef;
16use crate::IntoArray;
17use crate::arrays::Extension;
18use crate::arrays::ExtensionArray;
19use crate::arrays::extension::ExtensionArrayExt;
20use crate::dtype::DType;
21use crate::dtype::extension::ExtDTypeRef;
22use crate::extension::datetime::AnyTemporal;
23use crate::extension::datetime::Date;
24use crate::extension::datetime::Duration;
25use crate::extension::datetime::TemporalMetadata;
26use crate::extension::datetime::Time;
27use crate::extension::datetime::TimeUnit;
28use crate::extension::datetime::Timestamp;
29
30/// An array wrapper for primitive values that have an associated temporal meaning.
31///
32/// This is a wrapper around ExtensionArrays containing numeric types, each of which corresponds to
33/// either a timestamp or julian date (both referenced to UNIX epoch), OR a time since midnight.
34///
35/// ## Arrow compatibility
36///
37/// TemporalData can be created from Arrow arrays containing the following datatypes:
38/// * `Time32`
39/// * `Time64`
40/// * `Timestamp`
41/// * `Date32`
42/// * `Date64`
43///
44/// Anything that can be constructed and held in a `TemporalData` can also be zero-copy converted
45/// back to the relevant Arrow datatype.
46#[derive(Clone, Debug)]
47pub struct TemporalData {
48    /// The underlying Vortex extension array holding all the numeric values.
49    ext: ExtensionArray,
50}
51
52/// Type alias for backward compatibility.
53pub type TemporalArray = TemporalData;
54
55impl TemporalData {
56    /// Create a new `TemporalData` holding either i32 day offsets, or i64 millisecond offsets
57    /// that are evenly divisible by the number of 86,400,000.
58    ///
59    /// This is equivalent to the data described by either of the `Date32` or `Date64` data types
60    /// from Arrow.
61    ///
62    /// # Panics
63    ///
64    /// If the time unit is milliseconds, and the array is not of primitive I64 type, it panics.
65    ///
66    /// If the time unit is days, and the array is not of primitive I32 type, it panics.
67    ///
68    /// If any other time unit is provided, it panics.
69    pub fn new_date(array: ArrayRef, time_unit: TimeUnit) -> Self {
70        Self {
71            ext: ExtensionArray::new(
72                Date::new(time_unit, array.dtype().nullability()).erased(),
73                array,
74            ),
75        }
76    }
77
78    /// Create a new `TemporalData` holding one of the following values:
79    ///
80    /// * `i32` values representing seconds since midnight
81    /// * `i32` values representing milliseconds since midnight
82    /// * `i64` values representing microseconds since midnight
83    /// * `i64` values representing nanoseconds since midnight
84    ///
85    /// Note, this is equivalent to the set of values represented by the Time32 or Time64 types
86    /// from Arrow.
87    ///
88    /// # Panics
89    ///
90    /// If the time unit is seconds, and the array is not of primitive I32 type, it panics.
91    ///
92    /// If the time unit is milliseconds, and the array is not of primitive I32 type, it panics.
93    ///
94    /// If the time unit is microseconds, and the array is not of primitive I64 type, it panics.
95    ///
96    /// If the time unit is nanoseconds, and the array is not of primitive I64 type, it panics.
97    pub fn new_time(array: ArrayRef, time_unit: TimeUnit) -> Self {
98        Self {
99            ext: ExtensionArray::new(
100                Time::new(time_unit, array.dtype().nullability()).erased(),
101                array,
102            ),
103        }
104    }
105
106    /// Creates a timestamp array with the given unit and optional time zone.
107    ///
108    /// # Panics
109    ///
110    /// Panics if `array` does not have primitive i64 storage, or if
111    /// [`Timestamp::try_new_with_tz`] rejects the unit or time zone.
112    pub fn new_timestamp(
113        array: ArrayRef,
114        time_unit: TimeUnit,
115        time_zone: Option<Arc<str>>,
116    ) -> Self {
117        Self {
118            ext: ExtensionArray::new(
119                Timestamp::new_with_tz(time_unit, time_zone, array.dtype().nullability()).erased(),
120                array,
121            ),
122        }
123    }
124
125    /// Creates a duration array with the given time unit.
126    ///
127    /// # Panics
128    ///
129    /// Panics if `array` does not have primitive `i64` storage, or if [`Duration::try_new`]
130    /// rejects the unit.
131    pub fn new_duration(array: ArrayRef, time_unit: TimeUnit) -> Self {
132        Self {
133            ext: ExtensionArray::new(
134                Duration::new(time_unit, array.dtype().nullability()).erased(),
135                array,
136            ),
137        }
138    }
139}
140
141impl TemporalData {
142    /// Access the underlying temporal values in the underlying ExtensionArray storage.
143    ///
144    /// These values are to be interpreted based on the time unit and optional time-zone stored
145    /// in the TemporalMetadata.
146    pub fn temporal_values(&self) -> &ArrayRef {
147        self.ext.storage_array()
148    }
149
150    /// Retrieve the temporal metadata.
151    ///
152    /// The metadata is used to provide semantic meaning to the temporal values Array, for example
153    /// to understand the granularity of the samples and if they have an associated timezone.
154    pub fn temporal_metadata(&self) -> TemporalMetadata<'_> {
155        self.ext.dtype().as_extension().metadata::<AnyTemporal>()
156    }
157
158    /// Retrieve the extension DType associated with the underlying array.
159    pub fn ext_dtype(&self) -> ExtDTypeRef {
160        self.ext.ext_dtype().clone()
161    }
162
163    /// Retrieve the DType of the array. This will be a `DType::Extension` variant.
164    pub fn dtype(&self) -> &DType {
165        self.ext.dtype()
166    }
167}
168
169impl From<TemporalData> for ArrayRef {
170    fn from(value: TemporalData) -> Self {
171        value.ext.into_array()
172    }
173}
174
175impl IntoArray for TemporalData {
176    fn into_array(self) -> ArrayRef {
177        self.into()
178    }
179}
180
181impl TryFrom<ArrayRef> for TemporalData {
182    type Error = VortexError;
183
184    /// Try to specialize a generic Vortex array as a TemporalData.
185    ///
186    /// # Errors
187    ///
188    /// If the provided Array does not have `vortex.ext` encoding, an error will be returned.
189    ///
190    /// If the provided Array does not have recognized ExtMetadata corresponding to one of the known
191    /// `TemporalMetadata` variants, an error is returned.
192    fn try_from(value: ArrayRef) -> Result<Self, Self::Error> {
193        let ext = value
194            .as_opt::<Extension>()
195            .ok_or_else(|| vortex_err!("array must be an ExtensionArray"))?;
196        if !ext.ext_dtype().is::<AnyTemporal>() {
197            vortex_bail!(
198                "array extension dtype {} is not a temporal type",
199                ext.ext_dtype()
200            );
201        }
202        Ok(Self {
203            ext: ext.into_owned(),
204        })
205    }
206}
207
208// Conversions to/from ExtensionArray
209impl From<&TemporalData> for ExtensionArray {
210    fn from(value: &TemporalData) -> Self {
211        value.ext.clone()
212    }
213}
214
215impl From<TemporalData> for ExtensionArray {
216    fn from(value: TemporalData) -> Self {
217        value.ext
218    }
219}
220
221impl TryFrom<ExtensionArray> for TemporalData {
222    type Error = VortexError;
223
224    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
225        if !ext.ext_dtype().is::<AnyTemporal>() {
226            vortex_bail!(
227                "array extension dtype {} is not a temporal type",
228                ext.ext_dtype()
229            );
230        }
231        Ok(Self { ext })
232    }
233}
234
235#[cfg(test)]
236mod tests;