vortex_array/extension/datetime/
timestamp.rs1use std::fmt;
7use std::sync::Arc;
8
9use jiff::Span;
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_err;
15use vortex_error::vortex_panic;
16
17use crate::dtype::DType;
18use crate::dtype::Nullability;
19use crate::dtype::PType;
20use crate::dtype::extension::ExtDType;
21use crate::dtype::extension::ExtId;
22use crate::dtype::extension::ExtVTable;
23use crate::extension::datetime::TimeUnit;
24use crate::scalar::ScalarValue;
25
26#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
28pub struct Timestamp;
29
30impl Timestamp {
31 pub fn new(time_unit: TimeUnit, nullability: Nullability) -> ExtDType<Self> {
33 Self::new_with_tz(time_unit, None, nullability)
34 }
35
36 pub fn new_with_tz(
38 time_unit: TimeUnit,
39 timezone: Option<Arc<str>>,
40 nullability: Nullability,
41 ) -> ExtDType<Self> {
42 ExtDType::try_new(
43 TimestampOptions {
44 unit: time_unit,
45 tz: timezone,
46 },
47 DType::Primitive(PType::I64, nullability),
48 )
49 .vortex_expect("failed to create timestamp dtype")
50 }
51
52 pub fn new_with_options(options: TimestampOptions, nullability: Nullability) -> ExtDType<Self> {
54 ExtDType::try_new(options, DType::Primitive(PType::I64, nullability))
55 .vortex_expect("failed to create timestamp dtype")
56 }
57}
58
59#[derive(Clone, Debug, PartialEq, Eq, Hash)]
61pub struct TimestampOptions {
62 pub unit: TimeUnit,
64 pub tz: Option<Arc<str>>,
66}
67
68impl fmt::Display for TimestampOptions {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 match &self.tz {
71 Some(tz) => write!(f, "{}, tz={}", self.unit, tz),
72 None => write!(f, "{}", self.unit),
73 }
74 }
75}
76
77pub enum TimestampValue<'a> {
81 Seconds(i64, Option<&'a Arc<str>>),
83 Milliseconds(i64, Option<&'a Arc<str>>),
85 Microseconds(i64, Option<&'a Arc<str>>),
87 Nanoseconds(i64, Option<&'a Arc<str>>),
89}
90
91impl fmt::Display for TimestampValue<'_> {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 let (span, tz) = match self {
94 TimestampValue::Seconds(v, tz) => (Span::new().seconds(*v), *tz),
95 TimestampValue::Milliseconds(v, tz) => (Span::new().milliseconds(*v), *tz),
96 TimestampValue::Microseconds(v, tz) => (Span::new().microseconds(*v), *tz),
97 TimestampValue::Nanoseconds(v, tz) => (Span::new().nanoseconds(*v), *tz),
98 };
99 let ts = jiff::Timestamp::UNIX_EPOCH + span;
100
101 match tz {
102 None => write!(f, "{ts}"),
103 Some(tz) => {
104 let adjusted_ts = ts.in_tz(tz.as_ref()).vortex_expect("unknown timezone");
105 write!(f, "{adjusted_ts}",)
106 }
107 }
108 }
109}
110
111impl ExtVTable for Timestamp {
112 type Metadata = TimestampOptions;
113
114 type NativeValue<'a> = TimestampValue<'a>;
115
116 fn id(&self) -> ExtId {
117 ExtId::new_ref("vortex.timestamp")
118 }
119
120 fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
123 let mut bytes = Vec::with_capacity(4);
124 let unit_tag: u8 = metadata.unit.into();
125
126 bytes.push(unit_tag);
127
128 match &metadata.tz {
130 None => bytes.extend_from_slice(0u16.to_le_bytes().as_slice()),
131 Some(tz) => {
132 let tz_bytes = tz.as_bytes();
133 let tz_len = u16::try_from(tz_bytes.len())
134 .unwrap_or_else(|err| vortex_panic!("tz did not fit in u16: {}", err));
135 bytes.extend_from_slice(tz_len.to_le_bytes().as_slice());
136 bytes.extend_from_slice(tz_bytes);
137 }
138 }
139
140 Ok(bytes)
141 }
142
143 fn deserialize_metadata(&self, data: &[u8]) -> VortexResult<Self::Metadata> {
144 vortex_ensure!(data.len() >= 3);
145
146 let tag = data[0];
147 let time_unit = TimeUnit::try_from(tag)?;
148 let tz_len_bytes: [u8; 2] = data[1..3]
149 .try_into()
150 .ok()
151 .vortex_expect("Verified to have two bytes");
152 let tz_len = u16::from_le_bytes(tz_len_bytes) as usize;
153 if tz_len == 0 {
154 return Ok(TimestampOptions {
155 unit: time_unit,
156 tz: None,
157 });
158 }
159
160 let tz_bytes = &data[3..][..tz_len];
162 let tz: Arc<str> = str::from_utf8(tz_bytes)
163 .map_err(|e| vortex_err!("timezone is not valid utf8 string: {e}"))?
164 .to_string()
165 .into();
166 Ok(TimestampOptions {
167 unit: time_unit,
168 tz: Some(tz),
169 })
170 }
171
172 fn can_coerce_from(&self, ext_dtype: &ExtDType<Self>, other: &DType) -> bool {
173 let DType::Extension(other_ext) = other else {
174 return false;
175 };
176 let Some(other_opts) = other_ext.metadata_opt::<Timestamp>() else {
177 return false;
178 };
179 let our_opts = ext_dtype.metadata();
180 our_opts.tz == other_opts.tz
181 && our_opts.unit <= other_opts.unit
182 && (ext_dtype.storage_dtype().is_nullable() || !other.is_nullable())
183 }
184
185 fn least_supertype(&self, ext_dtype: &ExtDType<Self>, other: &DType) -> Option<DType> {
186 let DType::Extension(other_ext) = other else {
187 return None;
188 };
189 let other_opts = other_ext.metadata_opt::<Timestamp>()?;
190 let our_opts = ext_dtype.metadata();
191 if our_opts.tz != other_opts.tz {
192 return None;
193 }
194 let finest = our_opts.unit.min(other_opts.unit);
195 let union_null = ext_dtype.storage_dtype().nullability() | other.nullability();
196 Some(DType::Extension(
197 Timestamp::new_with_tz(finest, our_opts.tz.clone(), union_null).erased(),
198 ))
199 }
200
201 fn validate_dtype(&self, ext_dtype: &ExtDType<Self>) -> VortexResult<()> {
202 vortex_ensure!(
203 matches!(ext_dtype.storage_dtype(), DType::Primitive(PType::I64, _)),
204 "Timestamp storage dtype must be i64"
205 );
206 Ok(())
207 }
208
209 fn unpack_native<'a>(
210 &self,
211 ext_dtype: &'a ExtDType<Self>,
212 storage_value: &'a ScalarValue,
213 ) -> VortexResult<Self::NativeValue<'a>> {
214 let metadata = ext_dtype.metadata();
215 let ts_value = storage_value.as_primitive().cast::<i64>()?;
216 let tz = metadata.tz.as_ref();
217
218 let (span, value) = match metadata.unit {
219 TimeUnit::Nanoseconds => (
220 Span::new().nanoseconds(ts_value),
221 TimestampValue::Nanoseconds(ts_value, tz),
222 ),
223 TimeUnit::Microseconds => (
224 Span::new().microseconds(ts_value),
225 TimestampValue::Microseconds(ts_value, tz),
226 ),
227 TimeUnit::Milliseconds => (
228 Span::new().milliseconds(ts_value),
229 TimestampValue::Milliseconds(ts_value, tz),
230 ),
231 TimeUnit::Seconds => (
232 Span::new().seconds(ts_value),
233 TimestampValue::Seconds(ts_value, tz),
234 ),
235 TimeUnit::Days => vortex_bail!("Timestamp does not support Days time unit"),
236 };
237
238 let ts = jiff::Timestamp::UNIX_EPOCH
240 .checked_add(span)
241 .map_err(|e| vortex_err!("Invalid timestamp scalar: {}", e))?;
242
243 if let Some(tz) = tz {
244 ts.in_tz(tz.as_ref())
245 .map_err(|e| vortex_err!("Invalid timezone for timestamp scalar: {}", e))?;
246 }
247
248 Ok(value)
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use std::sync::Arc;
255
256 use vortex_error::VortexResult;
257
258 use crate::dtype::DType;
259 use crate::dtype::Nullability::Nullable;
260 use crate::extension::datetime::TimeUnit;
261 use crate::extension::datetime::Timestamp;
262 use crate::scalar::PValue;
263 use crate::scalar::Scalar;
264 use crate::scalar::ScalarValue;
265
266 #[test]
267 fn validate_timestamp_scalar() -> VortexResult<()> {
268 let dtype = DType::Extension(Timestamp::new(TimeUnit::Seconds, Nullable).erased());
269 Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(0))))?;
270
271 Ok(())
272 }
273
274 #[cfg_attr(miri, ignore)]
275 #[test]
276 fn reject_timestamp_with_invalid_timezone() {
277 let dtype = DType::Extension(
278 Timestamp::new_with_tz(
279 TimeUnit::Seconds,
280 Some(Arc::from("Not/A/Timezone")),
281 Nullable,
282 )
283 .erased(),
284 );
285 let result = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
286 assert!(result.is_err());
287 }
288
289 #[cfg_attr(miri, ignore)]
290 #[test]
291 fn display_timestamp_scalar() {
292 let local_dtype = DType::Extension(Timestamp::new(TimeUnit::Seconds, Nullable).erased());
294 let scalar = Scalar::new(local_dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
295 assert_eq!(format!("{}", scalar.as_extension()), "1970-01-01T00:00:00Z");
296
297 let zoned_dtype = DType::Extension(
299 Timestamp::new_with_tz(
300 TimeUnit::Seconds,
301 Some(Arc::from("America/New_York")),
302 Nullable,
303 )
304 .erased(),
305 );
306 let scalar = Scalar::new(zoned_dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
307 assert_eq!(
308 format!("{}", scalar.as_extension()),
309 "1969-12-31T19:00:00-05:00[America/New_York]"
310 );
311 }
312
313 #[test]
314 fn least_supertype_timestamp_units() {
315 use crate::dtype::Nullability::NonNullable;
316
317 let secs = DType::Extension(Timestamp::new(TimeUnit::Seconds, NonNullable).erased());
318 let ns = DType::Extension(Timestamp::new(TimeUnit::Nanoseconds, NonNullable).erased());
319 let expected =
320 DType::Extension(Timestamp::new(TimeUnit::Nanoseconds, NonNullable).erased());
321 assert_eq!(secs.least_supertype(&ns).unwrap(), expected);
322 assert_eq!(ns.least_supertype(&secs).unwrap(), expected);
323 }
324
325 #[test]
326 fn least_supertype_timestamp_tz_mismatch() {
327 use crate::dtype::Nullability::NonNullable;
328
329 let utc = DType::Extension(
330 Timestamp::new_with_tz(TimeUnit::Seconds, Some(Arc::from("UTC")), NonNullable).erased(),
331 );
332 let none = DType::Extension(Timestamp::new(TimeUnit::Seconds, NonNullable).erased());
333 assert!(utc.least_supertype(&none).is_none());
334 }
335
336 #[test]
337 fn least_supertype_timestamp_same_tz() {
338 use crate::dtype::Nullability::NonNullable;
339
340 let utc_s = DType::Extension(
341 Timestamp::new_with_tz(TimeUnit::Seconds, Some(Arc::from("UTC")), NonNullable).erased(),
342 );
343 let utc_ns = DType::Extension(
344 Timestamp::new_with_tz(TimeUnit::Nanoseconds, Some(Arc::from("UTC")), NonNullable)
345 .erased(),
346 );
347 let expected = DType::Extension(
348 Timestamp::new_with_tz(TimeUnit::Nanoseconds, Some(Arc::from("UTC")), NonNullable)
349 .erased(),
350 );
351 assert_eq!(utc_s.least_supertype(&utc_ns).unwrap(), expected);
352 }
353
354 #[test]
355 fn can_coerce_from_timestamp_tz() {
356 use crate::dtype::Nullability::NonNullable;
357
358 let utc = DType::Extension(
359 Timestamp::new_with_tz(TimeUnit::Nanoseconds, Some(Arc::from("UTC")), NonNullable)
360 .erased(),
361 );
362 let utc_s = DType::Extension(
363 Timestamp::new_with_tz(TimeUnit::Seconds, Some(Arc::from("UTC")), NonNullable).erased(),
364 );
365 let none = DType::Extension(Timestamp::new(TimeUnit::Nanoseconds, NonNullable).erased());
366 assert!(utc.can_coerce_from(&utc_s));
367 assert!(!utc.can_coerce_from(&none));
368 }
369}