vortex_functions/
convert_time_zone.rs1use std::fmt;
11use std::sync::Arc;
12
13use prost::Message;
14use vortex_array::ArrayRef;
15use vortex_array::ExecutionCtx;
16use vortex_array::IntoArray;
17use vortex_array::arrays::ConstantArray;
18use vortex_array::arrays::ExtensionArray;
19use vortex_array::arrays::extension::ExtensionArrayExt;
20use vortex_array::dtype::DType;
21use vortex_array::extension::datetime::Timestamp;
22use vortex_array::extension::datetime::TimestampOptions;
23use vortex_array::proto::expr as pb;
24use vortex_array::scalar::Scalar;
25use vortex_array::scalar_fn::Arity;
26use vortex_array::scalar_fn::ChildName;
27use vortex_array::scalar_fn::ExecutionArgs;
28use vortex_array::scalar_fn::ScalarFnId;
29use vortex_array::scalar_fn::ScalarFnVTable;
30use vortex_error::VortexResult;
31use vortex_error::vortex_bail;
32use vortex_error::vortex_panic;
33use vortex_session::VortexSession;
34use vortex_session::registry::CachedId;
35
36#[derive(Clone, Debug, PartialEq, Eq, Hash)]
38pub struct ConvertTimeZoneOptions {
39 pub time_zone: Arc<str>,
41}
42
43impl fmt::Display for ConvertTimeZoneOptions {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 write!(f, "tz={}", self.time_zone)
46 }
47}
48
49#[derive(Clone)]
53pub struct ConvertTimeZone;
54
55impl ScalarFnVTable for ConvertTimeZone {
56 type Options = ConvertTimeZoneOptions;
57
58 fn id(&self) -> ScalarFnId {
59 static ID: CachedId = CachedId::new("vortex.convert_time_zone");
60 *ID
61 }
62
63 fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
64 Ok(Some(
65 pb::ConvertTimeZoneOpts {
66 time_zone: options.time_zone.to_string(),
67 }
68 .encode_to_vec(),
69 ))
70 }
71
72 fn deserialize(
73 &self,
74 metadata: &[u8],
75 _session: &VortexSession,
76 ) -> VortexResult<Self::Options> {
77 let options = pb::ConvertTimeZoneOpts::decode(metadata)?;
78 Ok(ConvertTimeZoneOptions {
79 time_zone: Arc::from(options.time_zone),
80 })
81 }
82
83 fn arity(&self, _options: &Self::Options) -> Arity {
84 Arity::Exact(1)
85 }
86
87 fn child_name(&self, _options: &Self::Options, _child_idx: usize) -> ChildName {
88 ChildName::from("input")
89 }
90
91 fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
92 let input = &arg_dtypes[0];
93 let Some(TimestampOptions { unit, tz: Some(_) }) = input
94 .as_extension_opt()
95 .and_then(|ext| ext.metadata_opt::<Timestamp>())
96 else {
97 vortex_bail!("Expected a timestamp with a time zone, got {input}");
98 };
99
100 let target = Timestamp::try_new_with_tz(
101 *unit,
102 Some(Arc::clone(&options.time_zone)),
103 input.nullability(),
104 )?;
105 Ok(DType::Extension(target.erased()))
106 }
107
108 fn execute(
109 &self,
110 options: &Self::Options,
111 args: &dyn ExecutionArgs,
112 ctx: &mut ExecutionCtx,
113 ) -> VortexResult<ArrayRef> {
114 let input = args.get(0)?;
115 let DType::Extension(target) =
116 self.return_dtype(options, std::slice::from_ref(input.dtype()))?
117 else {
118 vortex_panic!("`return_dtype` returns a timestamp dtype");
119 };
120
121 if let Some(scalar) = input.as_constant() {
123 let output =
124 Scalar::try_extension_ref(target, scalar.as_extension().to_storage_scalar())?;
125 return Ok(ConstantArray::new(output, input.len()).into_array());
126 }
127
128 let input = input.execute::<ExtensionArray>(ctx)?;
129 Ok(ExtensionArray::try_new(target, input.storage_array().clone())?.into_array())
130 }
131
132 fn is_strict(&self, _options: &Self::Options) -> bool {
133 true
134 }
135
136 fn is_infallible(&self, _options: &Self::Options) -> bool {
137 true
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use vortex_array::IntoArray;
145 use vortex_array::VortexSessionExecute;
146 use vortex_array::arrays::Dict;
147 use vortex_array::arrays::DictArray;
148 use vortex_array::arrays::ExtensionArray;
149 use vortex_array::arrays::PrimitiveArray;
150 use vortex_array::assert_arrays_eq;
151 use vortex_array::dtype::Nullability;
152 use vortex_array::dtype::extension::ExtDTypeRef;
153 use vortex_array::extension::datetime::TimeUnit;
154 use vortex_array::extension::datetime::Timestamp;
155 use vortex_array::test_harness::ExpectedOutcome;
156 use vortex_array::test_harness::assert_execution_paths;
157 use vortex_buffer::buffer;
158 use vortex_error::VortexResult;
159 use vortex_expr::ArrayExprExt;
160 use vortex_expr::Expression;
161 use vortex_expr::proto::ExprSerializeProtoExt;
162 use vortex_expr::root;
163 use vortex_session::VortexSession;
164
165 use crate::expr::convert_time_zone;
166
167 fn zoned(zone: &str, nullability: Nullability) -> ExtDTypeRef {
168 Timestamp::new_with_tz(TimeUnit::Seconds, Some(zone.into()), nullability).erased()
169 }
170
171 #[test]
172 fn test_convert_time_zone_keeps_instants() -> VortexResult<()> {
173 let input = ExtensionArray::try_new(
174 zoned("America/New_York", Nullability::Nullable),
175 PrimitiveArray::from_option_iter([Some(0i64), None, Some(1_710_054_000)]).into_array(),
176 )?;
177 let expected = ExtensionArray::try_new(
178 zoned("UTC", Nullability::Nullable),
179 PrimitiveArray::from_option_iter([Some(0i64), None, Some(1_710_054_000)]).into_array(),
180 )?;
181 let session = VortexSession::empty();
182 crate::initialize(&session);
183 let operation = convert_time_zone(root(), "UTC");
184 let restored = Expression::from_proto(&operation.serialize_proto()?, &session)?;
185
186 assert_execution_paths(
187 &[input.into_array()],
188 |inputs| inputs[0].clone().apply(&restored),
189 ExpectedOutcome::Array(expected.into_array()),
190 &mut session.create_execution_ctx(),
191 );
192 Ok(())
193 }
194
195 #[test]
196 fn test_convert_time_zone_pushes_into_dictionary_values() -> VortexResult<()> {
197 let input = DictArray::try_new(
199 PrimitiveArray::from_option_iter([Some(0u8), None, Some(0)]).into_array(),
200 ExtensionArray::try_new(
201 zoned("America/New_York", Nullability::NonNullable),
202 buffer![0i64, 1].into_array(),
203 )?
204 .into_array(),
205 )?;
206 let mut ctx = VortexSession::empty().create_execution_ctx();
207
208 let result = input
209 .into_array()
210 .apply(&convert_time_zone(root(), "UTC"))?
211 .execute_until::<Dict>(&mut ctx)?;
212
213 assert!(result.is::<Dict>());
214 let expected = ExtensionArray::try_new(
215 zoned("UTC", Nullability::Nullable),
216 PrimitiveArray::from_option_iter([Some(0i64), None, Some(0)]).into_array(),
217 )?;
218 assert_arrays_eq!(result, expected.into_array(), &mut ctx);
219 Ok(())
220 }
221}