1use std::fmt;
7use std::sync::Arc;
8
9use jiff::fmt::temporal::DateTimeParser;
10use jiff::tz::TimeZone;
11use vortex_error::VortexExpect;
12use vortex_error::VortexResult;
13use vortex_error::vortex_bail;
14use vortex_error::vortex_ensure;
15use vortex_error::vortex_err;
16use vortex_error::vortex_panic;
17use vortex_session::registry::CachedId;
18
19use crate::dtype::DType;
20use crate::dtype::Nullability;
21use crate::dtype::PType;
22use crate::dtype::extension::ExtDType;
23use crate::dtype::extension::ExtId;
24use crate::dtype::extension::ExtVTable;
25use crate::extension::datetime::TimeUnit;
26use crate::scalar::ScalarValue;
27
28#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
32pub struct Timestamp;
33
34impl Timestamp {
35 pub fn new(time_unit: TimeUnit, nullability: Nullability) -> ExtDType<Self> {
41 Self::new_with_tz(time_unit, None, nullability)
42 }
43
44 pub fn try_new_with_tz(
51 time_unit: TimeUnit,
52 timezone: Option<Arc<str>>,
53 nullability: Nullability,
54 ) -> VortexResult<ExtDType<Self>> {
55 ExtDType::try_new(
56 TimestampOptions {
57 unit: time_unit,
58 tz: timezone,
59 },
60 nullability,
61 )
62 }
63
64 pub fn new_with_tz(
70 time_unit: TimeUnit,
71 timezone: Option<Arc<str>>,
72 nullability: Nullability,
73 ) -> ExtDType<Self> {
74 Self::try_new_with_tz(time_unit, timezone, nullability)
75 .vortex_expect("timestamp unit and time zone must be valid")
76 }
77
78 pub fn new_with_options(options: TimestampOptions, nullability: Nullability) -> ExtDType<Self> {
84 Self::new_with_tz(options.unit, options.tz, nullability)
85 }
86}
87
88#[derive(Clone, Debug, PartialEq, Eq, Hash)]
90pub struct TimestampOptions {
91 pub unit: TimeUnit,
93 pub tz: Option<Arc<str>>,
95}
96
97impl fmt::Display for TimestampOptions {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 match &self.tz {
100 Some(tz) => write!(f, "{}, tz={}", self.unit, tz),
101 None => write!(f, "{}", self.unit),
102 }
103 }
104}
105
106pub fn resolve_time_zone(name: Option<&str>) -> VortexResult<TimeZone> {
108 Ok(match name {
109 Some(name) if name.starts_with('+') || name.starts_with('-') => {
110 DateTimeParser::new().parse_time_zone(name)?
111 }
112 Some(name) => TimeZone::get(name)?,
113 None => TimeZone::UTC,
114 })
115}
116
117pub fn local_count(value: i64, unit: TimeUnit, zone: Option<&TimeZone>) -> VortexResult<i128> {
125 let Some(zone) = zone else {
126 return Ok(i128::from(value));
127 };
128
129 let units_per_second = TimeUnit::Seconds.nanos_per_unit() / unit.nanos_per_unit();
130 let offset = if let Ok(offset) = zone.to_fixed_offset() {
131 offset
132 } else {
133 let second = value.div_euclid(units_per_second);
134 let nanos = value.rem_euclid(units_per_second) * unit.nanos_per_unit();
135 zone.to_offset(jiff::Timestamp::new(second, i32::try_from(nanos)?)?)
136 };
137
138 Ok(i128::from(value) + i128::from(offset.seconds()) * i128::from(units_per_second))
139}
140
141pub enum TimestampValue<'a> {
145 Seconds(i64, Option<&'a Arc<str>>),
147 Milliseconds(i64, Option<&'a Arc<str>>),
149 Microseconds(i64, Option<&'a Arc<str>>),
151 Nanoseconds(i64, Option<&'a Arc<str>>),
153}
154
155impl fmt::Display for TimestampValue<'_> {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 let (unit, value, tz) = match *self {
158 TimestampValue::Seconds(v, tz) => (TimeUnit::Seconds, v, tz),
159 TimestampValue::Milliseconds(v, tz) => (TimeUnit::Milliseconds, v, tz),
160 TimestampValue::Microseconds(v, tz) => (TimeUnit::Microseconds, v, tz),
161 TimestampValue::Nanoseconds(v, tz) => (TimeUnit::Nanoseconds, v, tz),
162 };
163
164 let Ok(ts) = unit
166 .to_jiff_span(value)
167 .and_then(|span| Ok(jiff::Timestamp::UNIX_EPOCH.checked_add(span)?))
168 else {
169 return write!(f, "{value}{unit}");
170 };
171
172 match tz {
173 None => write!(f, "{ts}"),
174 Some(tz) => {
175 let zone = resolve_time_zone(Some(tz)).vortex_expect("unknown timezone");
176 let adjusted_ts = ts.to_zoned_datetime(zone);
177 write!(f, "{adjusted_ts}",)
178 }
179 }
180 }
181}
182
183impl ExtVTable for Timestamp {
184 type Metadata = TimestampOptions;
185 type StoredMetadata = Self::Metadata;
186
187 type NativeValue<'a> = TimestampValue<'a>;
188
189 fn id(&self) -> ExtId {
190 static ID: CachedId = CachedId::new("vortex.timestamp");
191 *ID
192 }
193
194 fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
197 let mut bytes = Vec::with_capacity(4);
198 let unit_tag: u8 = metadata.unit.into();
199
200 bytes.push(unit_tag);
201
202 match &metadata.tz {
204 None => bytes.extend_from_slice(0u16.to_le_bytes().as_slice()),
205 Some(tz) => {
206 let tz_bytes = tz.as_bytes();
207 let tz_len = u16::try_from(tz_bytes.len())
208 .unwrap_or_else(|err| vortex_panic!("tz did not fit in u16: {}", err));
209 bytes.extend_from_slice(tz_len.to_le_bytes().as_slice());
210 bytes.extend_from_slice(tz_bytes);
211 }
212 }
213
214 Ok(bytes)
215 }
216
217 fn deserialize_metadata(&self, data: &[u8]) -> VortexResult<Self::StoredMetadata> {
218 vortex_ensure!(
219 data.len() >= 3,
220 "Timestamp metadata must have at least 3 bytes, got {}",
221 data.len()
222 );
223
224 let tag = data[0];
225 let time_unit = TimeUnit::try_from(tag)?;
226 let tz_len_bytes: [u8; 2] = data[1..3]
227 .try_into()
228 .ok()
229 .vortex_expect("Verified to have two bytes");
230 let tz_len = u16::from_le_bytes(tz_len_bytes) as usize;
231 if tz_len == 0 {
232 return Ok(TimestampOptions {
233 unit: time_unit,
234 tz: None,
235 });
236 }
237
238 vortex_ensure!(
240 data.len() >= 3 + tz_len,
241 "Timestamp metadata is truncated: declared timezone length {} but only {} bytes available",
242 tz_len,
243 data.len() - 3
244 );
245 let tz_bytes = &data[3..3 + tz_len];
246 let tz: Arc<str> = str::from_utf8(tz_bytes)
247 .map_err(|e| vortex_err!("timezone is not valid utf8 string: {e}"))?
248 .to_string()
249 .into();
250 Ok(TimestampOptions {
251 unit: time_unit,
252 tz: Some(tz),
253 })
254 }
255
256 fn metadata_from_storage(
257 &self,
258 stored_metadata: Self::StoredMetadata,
259 _storage_dtype: &DType,
260 ) -> VortexResult<Self::Metadata> {
261 Ok(stored_metadata)
262 }
263
264 fn storage_dtype(_metadata: &Self::Metadata) -> DType {
265 DType::Primitive(PType::I64, Nullability::NonNullable)
266 }
267
268 fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
269 vortex_ensure!(
270 metadata.unit != TimeUnit::Days,
271 "Timestamp time unit must be finer than days, got {:?}",
272 metadata.unit
273 );
274 resolve_time_zone(metadata.tz.as_deref())?;
275
276 Ok(())
277 }
278
279 fn unpack_native<'a>(
280 ext_dtype: &'a ExtDType<Self>,
281 storage_value: &'a ScalarValue,
282 ) -> VortexResult<Self::NativeValue<'a>> {
283 let metadata = ext_dtype.metadata();
284 let ts_value = storage_value.as_primitive().cast::<i64>()?;
285 let tz = metadata.tz.as_ref();
286
287 Ok(match metadata.unit {
288 TimeUnit::Nanoseconds => TimestampValue::Nanoseconds(ts_value, tz),
289 TimeUnit::Microseconds => TimestampValue::Microseconds(ts_value, tz),
290 TimeUnit::Milliseconds => TimestampValue::Milliseconds(ts_value, tz),
291 TimeUnit::Seconds => TimestampValue::Seconds(ts_value, tz),
292 TimeUnit::Days => vortex_bail!("Timestamp does not support Days time unit"),
293 })
294 }
295}
296
297#[cfg(test)]
298mod tests {
299 use std::sync::Arc;
300
301 use rstest::rstest;
302 use vortex_error::VortexResult;
303
304 use crate::dtype::DType;
305 use crate::dtype::Nullability::Nullable;
306 use crate::extension::datetime::TimeUnit;
307 use crate::extension::datetime::Timestamp;
308 use crate::scalar::PValue;
309 use crate::scalar::Scalar;
310 use crate::scalar::ScalarValue;
311
312 #[test]
313 fn validate_timestamp_scalar() -> VortexResult<()> {
314 let dtype = DType::Extension(Timestamp::new(TimeUnit::Seconds, Nullable).erased());
315 Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(0))))?;
316
317 Ok(())
318 }
319
320 #[cfg_attr(miri, ignore)]
321 #[rstest]
322 #[case::end_of_9999(
323 TimeUnit::Microseconds,
324 253_402_214_400_000_000,
325 "253402214400000000µs"
326 )]
327 #[case::start_of_neg_9999(TimeUnit::Seconds, -377_705_116_800, "-377705116800s")]
328 #[case::max(TimeUnit::Microseconds, i64::MAX, "9223372036854775807µs")]
329 fn test_accept_timestamp_beyond_jiff_range(
330 #[case] unit: TimeUnit,
331 #[case] value: i64,
332 #[case] expected: &str,
333 #[values(None, Some(Arc::from("UTC")))] timezone: Option<Arc<str>>,
334 ) -> VortexResult<()> {
335 let dtype = DType::Extension(Timestamp::new_with_tz(unit, timezone, Nullable).erased());
336 let scalar = Scalar::try_new(dtype, Some(ScalarValue::from(value)))?;
337 assert_eq!(scalar.as_extension().to_string(), expected);
338
339 Ok(())
340 }
341
342 #[cfg_attr(miri, ignore)]
343 #[rstest]
344 #[case("+01:00", "1970-01-01T01:00:00+01:00[+01:00]")]
345 #[case("-05:30", "1969-12-31T18:30:00-05:30[-05:30]")]
346 fn display_fixed_offset_timestamp(
347 #[case] timezone: &str,
348 #[case] expected: &str,
349 ) -> VortexResult<()> {
350 let dtype = DType::Extension(
351 Timestamp::new_with_tz(TimeUnit::Seconds, Some(timezone.into()), Nullable).erased(),
352 );
353 let scalar = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(0))))?;
354 assert_eq!(format!("{}", scalar.as_extension()), expected);
355 Ok(())
356 }
357
358 #[cfg_attr(miri, ignore)]
359 #[test]
360 fn reject_timestamp_with_invalid_timezone() {
361 assert!(
362 Timestamp::try_new_with_tz(
363 TimeUnit::Seconds,
364 Some(Arc::from("Not/A/Timezone")),
365 Nullable,
366 )
367 .is_err()
368 );
369 }
370
371 #[test]
372 fn test_reject_timestamp_days() {
373 assert!(Timestamp::try_new_with_tz(TimeUnit::Days, None, Nullable).is_err());
374 }
375
376 #[rstest]
377 #[case::seconds(TimeUnit::Seconds, i64::MAX)]
378 #[case::milliseconds(TimeUnit::Milliseconds, i64::MAX)]
379 #[case::microseconds(TimeUnit::Microseconds, i64::MAX)]
380 #[case::nanoseconds(TimeUnit::Nanoseconds, i64::MIN)]
381 fn test_accept_timestamp_storage_extremes(
382 #[case] unit: TimeUnit,
383 #[case] value: i64,
384 ) -> VortexResult<()> {
385 let dtype = DType::Extension(Timestamp::new(unit, Nullable).erased());
386 Scalar::try_new(dtype, Some(ScalarValue::from(value)))?;
387
388 Ok(())
389 }
390
391 #[cfg_attr(miri, ignore)]
392 #[test]
393 fn display_timestamp_scalar() {
394 let local_dtype = DType::Extension(Timestamp::new(TimeUnit::Seconds, Nullable).erased());
396 let scalar = Scalar::new(local_dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
397 assert_eq!(format!("{}", scalar.as_extension()), "1970-01-01T00:00:00Z");
398
399 let zoned_dtype = DType::Extension(
401 Timestamp::new_with_tz(
402 TimeUnit::Seconds,
403 Some(Arc::from("America/New_York")),
404 Nullable,
405 )
406 .erased(),
407 );
408 let scalar = Scalar::new(zoned_dtype, Some(ScalarValue::Primitive(PValue::I64(0))));
409 assert_eq!(
410 format!("{}", scalar.as_extension()),
411 "1969-12-31T19:00:00-05:00[America/New_York]"
412 );
413 }
414
415 #[test]
416 fn deserialize_empty_metadata_returns_error() {
417 use crate::dtype::extension::ExtVTable;
418
419 let vtable = Timestamp;
420 assert!(vtable.deserialize_metadata(&[]).is_err());
421 }
422
423 #[test]
424 fn deserialize_too_short_metadata_returns_error() {
425 use crate::dtype::extension::ExtVTable;
426
427 let vtable = Timestamp;
428 assert!(vtable.deserialize_metadata(&[0x00, 0x01]).is_err());
430 }
431
432 #[test]
433 fn deserialize_truncated_timezone_returns_error() {
434 use crate::dtype::extension::ExtVTable;
435
436 let vtable = Timestamp;
437 let data = [0x00u8, 0x0A, 0x00, b'U', b'T', b'C'];
440 assert!(vtable.deserialize_metadata(&data).is_err());
441 }
442}