vortex_array/extension/datetime/
date.rs1use 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;
12
13use crate::dtype::DType;
14use crate::dtype::Nullability;
15use crate::dtype::PType;
16use crate::dtype::extension::ExtDType;
17use crate::dtype::extension::ExtId;
18use crate::dtype::extension::ExtVTable;
19use crate::extension::datetime::TimeUnit;
20use crate::scalar::ScalarValue;
21
22const EPOCH: jiff::civil::Date = jiff::civil::Date::constant(1970, 1, 1);
24
25#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
27pub struct Date;
28
29fn date_ptype(time_unit: &TimeUnit) -> Option<PType> {
30 match time_unit {
31 TimeUnit::Nanoseconds => None,
32 TimeUnit::Microseconds => None,
33 TimeUnit::Milliseconds => Some(PType::I64),
34 TimeUnit::Seconds => None,
35 TimeUnit::Days => Some(PType::I32),
36 }
37}
38
39impl Date {
40 pub fn try_new(time_unit: TimeUnit, nullability: Nullability) -> VortexResult<ExtDType<Self>> {
44 let ptype = date_ptype(&time_unit)
45 .ok_or_else(|| vortex_err!("Date type does not support time unit {}", time_unit))?;
46 ExtDType::try_new(time_unit, DType::Primitive(ptype, nullability))
47 }
48
49 pub fn new(time_unit: TimeUnit, nullability: Nullability) -> ExtDType<Self> {
55 Self::try_new(time_unit, nullability).vortex_expect("failed to create date dtype")
56 }
57}
58
59pub enum DateValue {
61 Days(i32),
63 Milliseconds(i64),
65}
66
67impl fmt::Display for DateValue {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 let date = match self {
70 DateValue::Days(days) => EPOCH + Span::new().days(*days),
71 DateValue::Milliseconds(ms) => EPOCH + Span::new().milliseconds(*ms),
72 };
73 write!(f, "{}", date)
74 }
75}
76
77impl ExtVTable for Date {
78 type Metadata = TimeUnit;
79 type NativeValue<'a> = DateValue;
80
81 fn id(&self) -> ExtId {
82 ExtId::new_ref("vortex.date")
83 }
84
85 fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
86 Ok(vec![u8::from(*metadata)])
87 }
88
89 fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::Metadata> {
90 let tag = metadata[0];
91 TimeUnit::try_from(tag)
92 }
93
94 fn validate_dtype(&self, ext_dtype: &ExtDType<Self>) -> VortexResult<()> {
95 let metadata = ext_dtype.metadata();
96 let ptype = date_ptype(metadata)
97 .ok_or_else(|| vortex_err!("Date type does not support time unit {}", metadata))?;
98
99 vortex_ensure!(
100 ext_dtype.storage_dtype().as_ptype() == ptype,
101 "Date storage dtype for {} must be {}",
102 metadata,
103 ptype
104 );
105
106 Ok(())
107 }
108
109 fn unpack_native(
110 &self,
111 ext_dtype: &ExtDType<Self>,
112 storage_value: &ScalarValue,
113 ) -> VortexResult<Self::NativeValue<'_>> {
114 let metadata = ext_dtype.metadata();
115 match metadata {
116 TimeUnit::Milliseconds => Ok(DateValue::Milliseconds(
117 storage_value.as_primitive().cast::<i64>()?,
118 )),
119 TimeUnit::Days => Ok(DateValue::Days(storage_value.as_primitive().cast::<i32>()?)),
120 _ => vortex_bail!("Date type does not support time unit {}", metadata),
121 }
122 }
123}
124
125#[cfg(test)]
126mod tests {
127 use vortex_error::VortexResult;
128
129 use crate::dtype::DType;
130 use crate::dtype::Nullability::Nullable;
131 use crate::extension::datetime::Date;
132 use crate::extension::datetime::TimeUnit;
133 use crate::scalar::PValue;
134 use crate::scalar::Scalar;
135 use crate::scalar::ScalarValue;
136
137 #[test]
138 fn validate_date_scalar() -> VortexResult<()> {
139 let days_dtype = DType::Extension(Date::new(TimeUnit::Days, Nullable).erased());
140 Scalar::try_new(days_dtype, Some(ScalarValue::Primitive(PValue::I32(0))))?;
141
142 let ms_dtype = DType::Extension(Date::new(TimeUnit::Milliseconds, Nullable).erased());
143 Scalar::try_new(
144 ms_dtype,
145 Some(ScalarValue::Primitive(PValue::I64(86_400_000))),
146 )?;
147
148 Ok(())
149 }
150
151 #[test]
152 fn reject_date_with_overflowing_value() {
153 let dtype = DType::Extension(Date::new(TimeUnit::Days, Nullable).erased());
155 let result = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(i64::MAX))));
156 assert!(result.is_err());
157 }
158
159 #[test]
160 fn display_date_scalar() {
161 let dtype = DType::Extension(Date::new(TimeUnit::Days, Nullable).erased());
162
163 let scalar = Scalar::new(dtype.clone(), Some(ScalarValue::Primitive(PValue::I32(0))));
164 assert_eq!(format!("{}", scalar.as_extension()), "1970-01-01");
165
166 let scalar = Scalar::new(dtype, Some(ScalarValue::Primitive(PValue::I32(365))));
167 assert_eq!(format!("{}", scalar.as_extension()), "1971-01-01");
168 }
169}