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(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 can_coerce_from(ext_dtype: &ExtDType<Self>, other: &DType) -> bool {
110 let DType::Extension(other_ext) = other else {
111 return false;
112 };
113 let Some(other_unit) = other_ext.metadata_opt::<Date>() else {
114 return false;
115 };
116 let our_unit = ext_dtype.metadata();
117 our_unit <= other_unit && (ext_dtype.storage_dtype().is_nullable() || !other.is_nullable())
119 }
120
121 fn least_supertype(ext_dtype: &ExtDType<Self>, other: &DType) -> Option<DType> {
122 let DType::Extension(other_ext) = other else {
123 return None;
124 };
125 let other_unit = other_ext.metadata_opt::<Date>()?;
126 let our_unit = ext_dtype.metadata();
127 let finest = (*our_unit).min(*other_unit);
128 let union_null = ext_dtype.storage_dtype().nullability() | other.nullability();
129 Some(DType::Extension(Date::new(finest, union_null).erased()))
130 }
131
132 fn unpack_native<'a>(
133 ext_dtype: &'a ExtDType<Self>,
134 storage_value: &'a ScalarValue,
135 ) -> VortexResult<Self::NativeValue<'a>> {
136 let metadata = ext_dtype.metadata();
137 match metadata {
138 TimeUnit::Milliseconds => Ok(DateValue::Milliseconds(
139 storage_value.as_primitive().cast::<i64>()?,
140 )),
141 TimeUnit::Days => Ok(DateValue::Days(storage_value.as_primitive().cast::<i32>()?)),
142 _ => vortex_bail!("Date type does not support time unit {}", metadata),
143 }
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use vortex_error::VortexResult;
150
151 use crate::dtype::DType;
152 use crate::dtype::Nullability::Nullable;
153 use crate::extension::datetime::Date;
154 use crate::extension::datetime::TimeUnit;
155 use crate::scalar::PValue;
156 use crate::scalar::Scalar;
157 use crate::scalar::ScalarValue;
158
159 #[test]
160 fn validate_date_scalar() -> VortexResult<()> {
161 let days_dtype = DType::Extension(Date::new(TimeUnit::Days, Nullable).erased());
162 Scalar::try_new(days_dtype, Some(ScalarValue::Primitive(PValue::I32(0))))?;
163
164 let ms_dtype = DType::Extension(Date::new(TimeUnit::Milliseconds, Nullable).erased());
165 Scalar::try_new(
166 ms_dtype,
167 Some(ScalarValue::Primitive(PValue::I64(86_400_000))),
168 )?;
169
170 Ok(())
171 }
172
173 #[test]
174 fn reject_date_with_overflowing_value() {
175 let dtype = DType::Extension(Date::new(TimeUnit::Days, Nullable).erased());
177 let result = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(i64::MAX))));
178 assert!(result.is_err());
179 }
180
181 #[test]
182 fn display_date_scalar() {
183 let dtype = DType::Extension(Date::new(TimeUnit::Days, Nullable).erased());
184
185 let scalar = Scalar::new(dtype.clone(), Some(ScalarValue::Primitive(PValue::I32(0))));
186 assert_eq!(format!("{}", scalar.as_extension()), "1970-01-01");
187
188 let scalar = Scalar::new(dtype, Some(ScalarValue::Primitive(PValue::I32(365))));
189 assert_eq!(format!("{}", scalar.as_extension()), "1971-01-01");
190 }
191
192 #[test]
193 fn least_supertype_date_units() {
194 use crate::dtype::Nullability::NonNullable;
195
196 let days = DType::Extension(Date::new(TimeUnit::Days, NonNullable).erased());
197 let ms = DType::Extension(Date::new(TimeUnit::Milliseconds, NonNullable).erased());
198 let expected = DType::Extension(Date::new(TimeUnit::Milliseconds, NonNullable).erased());
199 assert_eq!(days.least_supertype(&ms).unwrap(), expected);
200 assert_eq!(ms.least_supertype(&days).unwrap(), expected);
201 }
202
203 #[test]
204 fn can_coerce_from_date() {
205 use crate::dtype::Nullability::NonNullable;
206
207 let days = DType::Extension(Date::new(TimeUnit::Days, NonNullable).erased());
208 let ms = DType::Extension(Date::new(TimeUnit::Milliseconds, NonNullable).erased());
209 assert!(ms.can_coerce_from(&days));
210 assert!(!days.can_coerce_from(&ms));
211 }
212}