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(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(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(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 ext_dtype: &'a ExtDType<Self>,
211 storage_value: &'a ScalarValue,
212 ) -> VortexResult<Self::NativeValue<'a>> {
213 let metadata = ext_dtype.metadata();
214 let ts_value = storage_value.as_primitive().cast::<i64>()?;
215 let tz = metadata.tz.as_ref();
216
217 let (span, value) = match metadata.unit {
218 TimeUnit::Nanoseconds => (
219 Span::new().nanoseconds(ts_value),
220 TimestampValue::Nanoseconds(ts_value, tz),
221 ),
222 TimeUnit::Microseconds => (
223 Span::new().microseconds(ts_value),
224 TimestampValue::Microseconds(ts_value, tz),
225 ),
226 TimeUnit::Milliseconds => (
227 Span::new().milliseconds(ts_value),
228 TimestampValue::Milliseconds(ts_value, tz),
229 ),
230 TimeUnit::Seconds => (
231 Span::new().seconds(ts_value),
232 TimestampValue::Seconds(ts_value, tz),
233 ),
234 TimeUnit::Days => vortex_bail!("Timestamp does not support Days time unit"),
235 };
236
237 let ts = jiff::Timestamp::UNIX_EPOCH
239 .checked_add(span)
240 .map_err(|e| vortex_err!("Invalid timestamp scalar: {}", e))?;
241
242 if let Some(tz) = tz {
243 ts.in_tz(tz.as_ref())
244 .map_err(|e| vortex_err!("Invalid timezone for timestamp scalar: {}", e))?;
245 }
246
247 Ok(value)
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use std::sync::Arc;
254
255 use vortex_error::VortexResult;
256
257 use crate::dtype::DType;
258 use crate::dtype::Nullability::Nullable;
259 use crate::extension::datetime::TimeUnit;
260 use crate::extension::datetime::Timestamp;
261 use crate::scalar::PValue;
262 use crate::scalar::Scalar;
263 use crate::scalar::ScalarValue;
264
265 #[test]
266 fn validate_timestamp_scalar() -> VortexResult<()> {
267 let dtype = DType::Extension(Timestamp::new(TimeUnit::Seconds, Nullable).erased());
268 Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(0))))?;
269
270 Ok(())
271 }
272
273 #[cfg_attr(miri, ignore)]
274 #[test]
275 fn reject_timestamp_with_invalid_timezone() {
276 let dtype = DType::Extension(
277 Timestamp::new_with_tz(
278 TimeUnit::Seconds,
279 Some(Arc::from("Not/A/Timezone")),
280 Nullable,
281 )
282 .erased(),
283 );
284 let result = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
285 assert!(result.is_err());
286 }
287
288 #[cfg_attr(miri, ignore)]
289 #[test]
290 fn display_timestamp_scalar() {
291 let local_dtype = DType::Extension(Timestamp::new(TimeUnit::Seconds, Nullable).erased());
293 let scalar = Scalar::new(local_dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
294 assert_eq!(format!("{}", scalar.as_extension()), "1970-01-01T00:00:00Z");
295
296 let zoned_dtype = DType::Extension(
298 Timestamp::new_with_tz(
299 TimeUnit::Seconds,
300 Some(Arc::from("America/New_York")),
301 Nullable,
302 )
303 .erased(),
304 );
305 let scalar = Scalar::new(zoned_dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
306 assert_eq!(
307 format!("{}", scalar.as_extension()),
308 "1969-12-31T19:00:00-05:00[America/New_York]"
309 );
310 }
311
312 #[test]
313 fn least_supertype_timestamp_units() {
314 use crate::dtype::Nullability::NonNullable;
315
316 let secs = DType::Extension(Timestamp::new(TimeUnit::Seconds, NonNullable).erased());
317 let ns = DType::Extension(Timestamp::new(TimeUnit::Nanoseconds, NonNullable).erased());
318 let expected =
319 DType::Extension(Timestamp::new(TimeUnit::Nanoseconds, NonNullable).erased());
320 assert_eq!(secs.least_supertype(&ns).unwrap(), expected);
321 assert_eq!(ns.least_supertype(&secs).unwrap(), expected);
322 }
323
324 #[test]
325 fn least_supertype_timestamp_tz_mismatch() {
326 use crate::dtype::Nullability::NonNullable;
327
328 let utc = DType::Extension(
329 Timestamp::new_with_tz(TimeUnit::Seconds, Some(Arc::from("UTC")), NonNullable).erased(),
330 );
331 let none = DType::Extension(Timestamp::new(TimeUnit::Seconds, NonNullable).erased());
332 assert!(utc.least_supertype(&none).is_none());
333 }
334
335 #[test]
336 fn least_supertype_timestamp_same_tz() {
337 use crate::dtype::Nullability::NonNullable;
338
339 let utc_s = DType::Extension(
340 Timestamp::new_with_tz(TimeUnit::Seconds, Some(Arc::from("UTC")), NonNullable).erased(),
341 );
342 let utc_ns = DType::Extension(
343 Timestamp::new_with_tz(TimeUnit::Nanoseconds, Some(Arc::from("UTC")), NonNullable)
344 .erased(),
345 );
346 let expected = DType::Extension(
347 Timestamp::new_with_tz(TimeUnit::Nanoseconds, Some(Arc::from("UTC")), NonNullable)
348 .erased(),
349 );
350 assert_eq!(utc_s.least_supertype(&utc_ns).unwrap(), expected);
351 }
352
353 #[test]
354 fn can_coerce_from_timestamp_tz() {
355 use crate::dtype::Nullability::NonNullable;
356
357 let utc = DType::Extension(
358 Timestamp::new_with_tz(TimeUnit::Nanoseconds, Some(Arc::from("UTC")), NonNullable)
359 .erased(),
360 );
361 let utc_s = DType::Extension(
362 Timestamp::new_with_tz(TimeUnit::Seconds, Some(Arc::from("UTC")), NonNullable).erased(),
363 );
364 let none = DType::Extension(Timestamp::new(TimeUnit::Nanoseconds, NonNullable).erased());
365 assert!(utc.can_coerce_from(&utc_s));
366 assert!(!utc.can_coerce_from(&none));
367 }
368}