1use std::fmt;
7use std::sync::Arc;
8
9use jiff::Timestamp as JiffTimestamp;
10use jiff::tz::AmbiguousOffset;
11use jiff::tz::TimeZone;
12use prost::Message;
13use vortex_array::ArrayRef;
14use vortex_array::ExecutionCtx;
15use vortex_array::IntoArray;
16use vortex_array::arrays::ConstantArray;
17use vortex_array::arrays::ExtensionArray;
18use vortex_array::arrays::PrimitiveArray;
19use vortex_array::arrays::VarBinViewArray;
20use vortex_array::arrays::extension::ExtensionArrayExt;
21use vortex_array::dtype::DType;
22use vortex_array::dtype::Nullability;
23use vortex_array::dtype::PType;
24use vortex_array::extension::datetime::TimeUnit;
25use vortex_array::extension::datetime::Timestamp;
26use vortex_array::extension::datetime::TimestampOptions;
27use vortex_array::extension::datetime::resolve_time_zone as resolve_zone;
28use vortex_array::proto::expr as pb;
29use vortex_array::scalar::Scalar;
30use vortex_array::scalar_fn::Arity;
31use vortex_array::scalar_fn::ChildName;
32use vortex_array::scalar_fn::ExecutionArgs;
33use vortex_array::scalar_fn::ReduceNode;
34use vortex_array::scalar_fn::ScalarFnId;
35use vortex_array::scalar_fn::ScalarFnVTable;
36use vortex_array::validity::Validity;
37use vortex_buffer::BitBufferMut;
38use vortex_buffer::BufferMut;
39use vortex_error::VortexError;
40use vortex_error::VortexResult;
41use vortex_error::vortex_bail;
42use vortex_error::vortex_err;
43use vortex_session::VortexSession;
44use vortex_session::registry::CachedId;
45
46#[derive(Clone, Debug, PartialEq, Eq, Hash)]
48pub struct ReplaceTimeZoneOptions {
49 pub time_zone: Option<Arc<str>>,
51 pub null_on_non_existent: bool,
53}
54
55impl fmt::Display for ReplaceTimeZoneOptions {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 match &self.time_zone {
58 Some(tz) => write!(f, "tz={tz}")?,
59 None => write!(f, "tz=none")?,
60 }
61 write!(f, ", null_on_non_existent={}", self.null_on_non_existent)
62 }
63}
64
65#[derive(Clone)]
69pub struct ReplaceTimeZone;
70
71impl ScalarFnVTable for ReplaceTimeZone {
72 type Options = ReplaceTimeZoneOptions;
73
74 fn id(&self) -> ScalarFnId {
75 static ID: CachedId = CachedId::new("vortex.replace_time_zone");
76 *ID
77 }
78
79 fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
80 Ok(Some(
81 pb::ReplaceTimeZoneOpts {
82 time_zone: options.time_zone.as_ref().map(ToString::to_string),
83 null_on_non_existent: options.null_on_non_existent,
84 }
85 .encode_to_vec(),
86 ))
87 }
88
89 fn deserialize(
90 &self,
91 metadata: &[u8],
92 _session: &VortexSession,
93 ) -> VortexResult<Self::Options> {
94 let options = pb::ReplaceTimeZoneOpts::decode(metadata)?;
95 Ok(ReplaceTimeZoneOptions {
96 time_zone: options.time_zone.map(Arc::from),
97 null_on_non_existent: options.null_on_non_existent,
98 })
99 }
100
101 fn arity(&self, _options: &Self::Options) -> Arity {
102 Arity::Exact(2)
103 }
104
105 fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
106 match child_idx {
107 0 => ChildName::from("input"),
108 1 => ChildName::from("ambiguous"),
109 _ => unreachable!("Invalid child index {child_idx} for replace_time_zone()"),
110 }
111 }
112
113 fn simplify<T: ReduceNode>(
114 &self,
115 options: &Self::Options,
116 node: &T,
117 ) -> VortexResult<Option<T>> {
118 let (value, policy) = (node.child(0), node.child(1));
119 let (Some(value), Some(policy)) = (value.as_constant(), policy.as_constant()) else {
120 return Ok(None);
121 };
122 Ok(replace_scalar(options, value, policy)
125 .ok()
126 .map(|scalar| node.new_constant(scalar)))
127 }
128
129 fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
130 let input = timestamp_options(&arg_dtypes[0])?;
131 if input.unit == TimeUnit::Days {
132 vortex_bail!("Timestamp cannot use day units");
133 }
134 if !matches!(arg_dtypes[1], DType::Utf8(_) | DType::Null) {
135 vortex_bail!(
136 "replace_time_zone() requires a UTF-8 ambiguity policy, got {}",
137 arg_dtypes[1]
138 );
139 }
140 resolve_zone(options.time_zone.as_deref())?;
141 Ok(DType::Extension(
143 Timestamp::new_with_tz(input.unit, options.time_zone.clone(), Nullability::Nullable)
144 .erased(),
145 ))
146 }
147
148 fn execute(
149 &self,
150 options: &Self::Options,
151 args: &dyn ExecutionArgs,
152 ctx: &mut ExecutionCtx,
153 ) -> VortexResult<ArrayRef> {
154 let input = args.get(0)?;
155 let ambiguous = args.get(1)?;
156 let dtype =
157 self.return_dtype(options, &[input.dtype().clone(), ambiguous.dtype().clone()])?;
158 let metadata = timestamp_options(input.dtype())?.clone();
159 let source = resolve_zone(metadata.tz.as_deref())?;
160 let target = resolve_zone(options.time_zone.as_deref())?;
161 let convert = |value, policy: &str| {
162 replace(
163 value,
164 metadata.unit,
165 &source,
166 &target,
167 policy,
168 options.null_on_non_existent,
169 )
170 };
171
172 if let (Some(value), Some(policy)) = (input.as_constant(), ambiguous.as_constant()) {
173 let scalar = replace_scalar(options, value, policy)?;
174 return Ok(ConstantArray::new(scalar, args.row_count()).into_array());
175 }
176
177 if matches!(ambiguous.dtype(), DType::Null) {
178 return Ok(ConstantArray::new(Scalar::null(dtype), args.row_count()).into_array());
179 }
180 let input = input.execute::<ExtensionArray>(ctx)?;
181 let storage = input
182 .storage_array()
183 .clone()
184 .execute::<PrimitiveArray>(ctx)?;
185 let values = storage.to_buffer::<i64>();
186 let valid = storage.validity()?.execute_mask(values.len(), ctx)?;
187 let policies = ambiguous.execute::<VarBinViewArray>(ctx)?;
188 let policies_valid = policies.validity()?.execute_mask(values.len(), ctx)?;
189 let mut output = BufferMut::<i64>::with_capacity(values.len());
190 let mut output_valid = BitBufferMut::with_capacity(values.len());
191 for (i, ((value, valid), policy_valid)) in values
192 .iter()
193 .zip(valid.iter())
194 .zip(policies_valid.iter())
195 .enumerate()
196 {
197 let replaced = if valid && policy_valid {
198 let bytes = policies.bytes_at(i);
199 let policy = unsafe { std::str::from_utf8_unchecked(&bytes) };
201 convert(*value, policy)?
202 } else {
203 None
204 };
205 output.push(replaced.unwrap_or_default());
206 output_valid.append(replaced.is_some());
207 }
208 let DType::Extension(ext) = dtype else {
209 unreachable!()
210 };
211 let storage = PrimitiveArray::new(
212 output.freeze(),
213 Validity::from_bit_buffer(output_valid.freeze(), Nullability::Nullable),
214 )
215 .into_array();
216 Ok(ExtensionArray::new(ext, storage).into_array())
217 }
218}
219
220fn replace_scalar(
222 options: &ReplaceTimeZoneOptions,
223 value: &Scalar,
224 policy: &Scalar,
225) -> VortexResult<Scalar> {
226 let DType::Extension(ext) =
227 ReplaceTimeZone.return_dtype(options, &[value.dtype().clone(), policy.dtype().clone()])?
228 else {
229 unreachable!("replace_time_zone() returns a timestamp")
230 };
231 let metadata = timestamp_options(value.dtype())?;
232 let result = if value.is_null() || policy.is_null() {
233 None
234 } else {
235 let storage = value.as_extension().to_storage_scalar();
236 let policy = policy
237 .as_utf8()
238 .value()
239 .ok_or_else(|| vortex_err!("Missing ambiguity policy"))?;
240 replace(
241 i64::try_from(&storage)?,
242 metadata.unit,
243 &resolve_zone(metadata.tz.as_deref())?,
244 &resolve_zone(options.time_zone.as_deref())?,
245 policy.as_str(),
246 options.null_on_non_existent,
247 )?
248 };
249 let storage = result.map_or_else(
250 || Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable)),
251 |v| Scalar::primitive(v, Nullability::Nullable),
252 );
253 Scalar::try_extension_ref(ext, storage)
254}
255
256fn timestamp_options(dtype: &DType) -> VortexResult<&TimestampOptions> {
257 if let DType::Extension(ext) = dtype
258 && let Some(options) = ext.metadata_opt::<Timestamp>()
259 {
260 return Ok(options);
261 }
262 vortex_bail!("replace_time_zone() requires Timestamp, got {dtype}")
263}
264
265fn replace(
266 value: i64,
267 unit: TimeUnit,
268 source: &TimeZone,
269 target: &TimeZone,
270 policy: &str,
271 null_on_non_existent: bool,
272) -> VortexResult<Option<i64>> {
273 if !matches!(policy, "raise" | "earliest" | "latest" | "null") {
274 vortex_bail!(
275 "Invalid ambiguity policy {policy:?}: expected raise, earliest, latest, or null"
276 );
277 }
278 let timestamp = match unit {
280 TimeUnit::Seconds => JiffTimestamp::from_second(value),
281 TimeUnit::Milliseconds => JiffTimestamp::from_millisecond(value),
282 TimeUnit::Microseconds => JiffTimestamp::from_microsecond(value),
283 TimeUnit::Nanoseconds => JiffTimestamp::from_nanosecond(i128::from(value)),
284 TimeUnit::Days => vortex_bail!("Timestamp cannot use day units"),
285 }
286 .map_err(|error| {
287 VortexError::from(error)
288 .with_context(format!("replace_time_zone() cannot convert {value}{unit}"))
289 })?;
290 if source == target && policy == "raise" {
292 return Ok(Some(value));
293 }
294 let wall_time = source.to_datetime(timestamp);
295 let ambiguous = target.to_ambiguous_timestamp(wall_time);
296 let timestamp = match ambiguous.offset() {
297 AmbiguousOffset::Unambiguous { .. } => ambiguous.unambiguous()?,
298 AmbiguousOffset::Gap { .. } if null_on_non_existent => return Ok(None),
299 AmbiguousOffset::Gap { .. } => ambiguous.unambiguous()?,
300 AmbiguousOffset::Fold { .. } => match policy {
301 "earliest" => ambiguous.earlier()?,
302 "latest" => ambiguous.later()?,
303 "null" => return Ok(None),
304 _ => ambiguous.unambiguous()?,
305 },
306 };
307 Ok(Some(match unit {
308 TimeUnit::Seconds => timestamp.as_second(),
309 TimeUnit::Milliseconds => timestamp.as_millisecond(),
310 TimeUnit::Microseconds => timestamp.as_microsecond(),
311 TimeUnit::Nanoseconds => i64::try_from(timestamp.as_nanosecond())
312 .map_err(|e| vortex_err!("Timestamp overflow: {e}"))?,
313 TimeUnit::Days => unreachable!(),
314 }))
315}
316
317#[cfg(test)]
318mod tests {
319 use std::error::Error;
320 use std::sync::LazyLock;
321
322 use rstest::rstest;
323 use vortex_array::Canonical;
324 use vortex_array::IntoArray;
325 use vortex_array::VortexSessionExecute;
326 use vortex_array::arrays::ExtensionArray;
327 use vortex_array::arrays::PrimitiveArray;
328 use vortex_array::arrays::StructArray;
329 use vortex_array::arrays::VarBinViewArray;
330 use vortex_array::assert_arrays_eq;
331 use vortex_array::dtype::DType;
332 use vortex_array::dtype::Nullability;
333 use vortex_array::dtype::StructFields;
334 use vortex_array::extension::datetime::TimeUnit;
335 use vortex_array::extension::datetime::Timestamp;
336 use vortex_array::scalar::Scalar;
337 use vortex_array::scalar_fn::ScalarFnVTable;
338 use vortex_array::scalar_fn::builtin::literal::Literal;
339 use vortex_error::VortexResult;
340 use vortex_error::vortex_err;
341 use vortex_expr::ArrayExprExt;
342 use vortex_expr::get_item;
343 use vortex_expr::lit;
344 use vortex_expr::root;
345 use vortex_session::VortexSession;
346
347 use super::ReplaceTimeZone;
348 use super::ReplaceTimeZoneOptions;
349 use super::replace;
350 use super::resolve_zone;
351 use crate::expr::replace_time_zone;
352
353 static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
354 let session = VortexSession::empty();
355
356 vortex_array::initialize(&session);
357
358 crate::initialize(&session);
359
360 session
361 });
362
363 #[rstest]
364 #[case(TimeUnit::Seconds, 1)]
365 #[case(TimeUnit::Milliseconds, 1_000)]
366 #[case(TimeUnit::Microseconds, 1_000_000)]
367 #[case(TimeUnit::Nanoseconds, 1_000_000_000)]
368 fn preserves_units_and_fractional_values(
369 #[case] unit: TimeUnit,
370 #[case] scale: i64,
371 ) -> VortexResult<()> {
372 let utc = resolve_zone(None)?;
373 let new_york = resolve_zone(Some("America/New_York"))?;
374 let value = 1_705_320_000 * scale + scale / 2;
375 assert_eq!(
376 replace(value, unit, &utc, &new_york, "raise", false)?,
377 Some(value + 18_000 * scale)
378 );
379 assert_eq!(
380 replace(
381 value + 18_000 * scale,
382 unit,
383 &new_york,
384 &utc,
385 "raise",
386 false
387 )?,
388 Some(value)
389 );
390 Ok(())
391 }
392
393 #[test]
394 fn resolves_folds_and_gaps_separately() -> VortexResult<()> {
395 let utc = resolve_zone(None)?;
396 let new_york = resolve_zone(Some("America/New_York"))?;
397 let fold = "2024-11-03T01:30:00Z"
398 .parse::<jiff::Timestamp>()?
399 .as_second();
400 let gap = "2024-03-10T02:30:00Z"
401 .parse::<jiff::Timestamp>()?
402 .as_second();
403 let convert = |value, policy, null_on_non_existent| {
404 replace(
405 value,
406 TimeUnit::Seconds,
407 &utc,
408 &new_york,
409 policy,
410 null_on_non_existent,
411 )
412 };
413 assert_eq!(convert(fold, "earliest", false)?, Some(fold + 14_400));
414 assert_eq!(convert(fold, "latest", false)?, Some(fold + 18_000));
415 assert_eq!(convert(fold, "null", false)?, None);
416 assert!(convert(fold, "raise", false).is_err());
417 assert_eq!(convert(gap, "raise", true)?, None);
418 assert!(convert(gap, "earliest", false).is_err());
420 Ok(())
421 }
422
423 #[test]
424 fn rejects_invalid_policy_and_timestamp_overflow() -> VortexResult<()> {
425 let utc = resolve_zone(None)?;
426 assert!(replace(0, TimeUnit::Seconds, &utc, &utc, "invalid", false).is_err());
427 let new_york = resolve_zone(Some("America/New_York"))?;
428 assert!(
429 replace(
430 i64::MAX,
431 TimeUnit::Nanoseconds,
432 &utc,
433 &new_york,
434 "raise",
435 false
436 )
437 .is_err()
438 );
439 assert!(resolve_zone(Some("Not/A/Timezone")).is_err());
440 assert!(resolve_zone(Some("+99:00")).is_err());
441 assert!(resolve_zone(Some("-05:60")).is_err());
442 Ok(())
443 }
444
445 #[rstest]
446 #[case(None, false)]
447 #[case(Some("America/New_York"), true)]
448 fn options_round_trip(
449 #[case] time_zone: Option<&str>,
450 #[case] null_on_non_existent: bool,
451 ) -> VortexResult<()> {
452 let options = ReplaceTimeZoneOptions {
453 time_zone: time_zone.map(Into::into),
454 null_on_non_existent,
455 };
456 let metadata = ReplaceTimeZone.serialize(&options)?.unwrap();
457 assert_eq!(ReplaceTimeZone.deserialize(&metadata, &SESSION)?, options);
458 Ok(())
459 }
460
461 #[rstest]
462 #[case(None, Some("UTC"), 0)]
463 #[case(Some("+01:00"), None, 3_600)]
464 #[case(Some("-05:30"), None, -19_800)]
465 #[case(None, Some("+05:30"), -19_800)]
466 #[case(Some("+01:00"), Some("-05:30"), 23_400)]
467 fn simplify_folds_literal_input(
468 #[case] source: Option<&str>,
469 #[case] target: Option<&str>,
470 #[case] offset_seconds: i64,
471 ) -> VortexResult<()> {
472 let timestamp = |tz: Option<&str>| {
473 Timestamp::new_with_tz(
474 TimeUnit::Microseconds,
475 tz.map(Into::into),
476 Nullability::Nullable,
477 )
478 .erased()
479 };
480 let micros = Scalar::primitive(1_704_153_600_000_000i64, Nullability::Nullable);
481 let expr = replace_time_zone(
482 lit(Scalar::extension_ref(timestamp(source), micros)),
483 lit("earliest"),
484 ReplaceTimeZoneOptions {
485 time_zone: target.map(Into::into),
486 null_on_non_existent: false,
487 },
488 );
489 let scope = DType::Struct(StructFields::empty(), Nullability::NonNullable);
490 let optimized = expr.bind(&scope)?.optimize()?;
491
492 let scalar = optimized
494 .as_opt::<Literal>()
495 .ok_or_else(|| vortex_err!("expected a bare literal, got {optimized}"))?;
496 assert_eq!(
497 scalar,
498 &Scalar::extension_ref(
499 timestamp(target),
500 Scalar::primitive(
501 1_704_153_600_000_000i64 + offset_seconds * 1_000_000,
502 Nullability::Nullable,
503 ),
504 )
505 );
506 assert_eq!(scalar.dtype(), &DType::Extension(timestamp(target)));
507 Ok(())
508 }
509
510 #[test]
511 fn applies_per_row_policies_and_nulls() -> VortexResult<()> {
512 let timestamp = |tz: Option<&str>| {
513 Timestamp::new_with_tz(
514 TimeUnit::Microseconds,
515 tz.map(Into::into),
516 Nullability::Nullable,
517 )
518 .erased()
519 };
520 let fold = 1_730_597_400_000_000i64;
522 let hour = 3_600_000_000i64;
523 let input = ExtensionArray::new(
524 timestamp(None),
525 PrimitiveArray::from_option_iter([
526 Some(fold),
527 Some(fold),
528 Some(fold),
529 Some(fold),
530 None,
531 ])
532 .into_array(),
533 );
534 let policies = VarBinViewArray::from_iter_nullable_str([
535 Some("earliest"),
536 Some("latest"),
537 Some("null"),
538 None,
539 Some("raise"),
540 ]);
541 let array =
542 StructArray::from_fields(&[("t", input.into_array()), ("p", policies.into_array())])?
543 .into_array();
544 let result = array.apply(&replace_time_zone(
545 get_item("t", root()),
546 get_item("p", root()),
547 ReplaceTimeZoneOptions {
548 time_zone: Some("America/New_York".into()),
549 null_on_non_existent: false,
550 },
551 ))?;
552
553 let expected = ExtensionArray::new(
554 timestamp(Some("America/New_York")),
555 PrimitiveArray::from_option_iter([
556 Some(fold + 4 * hour),
557 Some(fold + 5 * hour),
558 None,
559 None,
560 None,
561 ])
562 .into_array(),
563 );
564 let mut ctx = SESSION.create_execution_ctx();
565 assert_arrays_eq!(result, expected, &mut ctx);
566 Ok(())
567 }
568
569 #[rstest]
570 #[case::end_of_9999(TimeUnit::Microseconds, 253_402_214_400_000_000)]
571 #[case::storage_min(TimeUnit::Seconds, i64::MIN)]
572 fn rejects_timestamps_beyond_jiff_range(
573 #[case] unit: TimeUnit,
574 #[case] value: i64,
575 #[values(None, Some("America/New_York"))] target: Option<&str>,
576 ) -> VortexResult<()> {
577 let input = ExtensionArray::new(
578 Timestamp::new(unit, Nullability::Nullable).erased(),
579 PrimitiveArray::from_option_iter([Some(0i64), Some(value)]).into_array(),
580 );
581 let expr = replace_time_zone(
582 root(),
583 lit("raise"),
584 ReplaceTimeZoneOptions {
585 time_zone: target.map(Into::into),
586 null_on_non_existent: false,
587 },
588 );
589 let mut ctx = SESSION.create_execution_ctx();
590 let result = input
591 .into_array()
592 .apply(&expr)
593 .and_then(|array| array.execute::<Canonical>(&mut ctx));
594 let error = result.unwrap_err();
595 assert!(error.to_string().contains("cannot convert"), "{error}");
596 assert!(
597 error
598 .source()
599 .is_some_and(|source| source.is::<jiff::Error>())
600 );
601
602 let control = ExtensionArray::new(
603 Timestamp::new(unit, Nullability::Nullable).erased(),
604 PrimitiveArray::from_option_iter([Some(0i64)]).into_array(),
605 );
606 control
607 .into_array()
608 .apply(&expr)?
609 .execute::<Canonical>(&mut ctx)?;
610
611 Ok(())
612 }
613}