1use std::fmt::Display;
5use std::hash::Hash;
6
7use itertools::Itertools as _;
8use vortex_array::arrays::StructArray;
9use vortex_array::validity::Validity;
10use vortex_array::{Array, ArrayRef, DeserializeMetadata, EmptyMetadata, IntoArray, ToCanonical};
11use vortex_dtype::{DType, FieldNames, Nullability, StructFields};
12use vortex_error::{VortexExpect as _, VortexResult, vortex_bail};
13
14use crate::{AnalysisExpr, ExprEncodingRef, ExprId, ExprRef, IntoExpr, Scope, VTable, vtable};
15
16vtable!(Merge);
17
18#[allow(clippy::derived_hash_with_manual_eq)]
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26pub struct MergeExpr {
27 values: Vec<ExprRef>,
28 nullability: Nullability,
29}
30
31pub struct MergeExprEncoding;
32
33impl VTable for MergeVTable {
34 type Expr = MergeExpr;
35 type Encoding = MergeExprEncoding;
36 type Metadata = EmptyMetadata;
37
38 fn id(_encoding: &Self::Encoding) -> ExprId {
39 ExprId::new_ref("merge")
40 }
41
42 fn encoding(_expr: &Self::Expr) -> ExprEncodingRef {
43 ExprEncodingRef::new_ref(MergeExprEncoding.as_ref())
44 }
45
46 fn metadata(_expr: &Self::Expr) -> Option<Self::Metadata> {
47 Some(EmptyMetadata)
48 }
49
50 fn children(expr: &Self::Expr) -> Vec<&ExprRef> {
51 expr.values.iter().collect()
52 }
53
54 fn with_children(expr: &Self::Expr, children: Vec<ExprRef>) -> VortexResult<Self::Expr> {
55 Ok(MergeExpr {
56 values: children,
57 nullability: expr.nullability,
58 })
59 }
60
61 fn build(
62 _encoding: &Self::Encoding,
63 _metadata: &<Self::Metadata as DeserializeMetadata>::Output,
64 children: Vec<ExprRef>,
65 ) -> VortexResult<Self::Expr> {
66 if children.is_empty() {
67 vortex_bail!(
68 "Merge expression must have at least one child, got: {:?}",
69 children
70 );
71 }
72 Ok(MergeExpr {
73 values: children,
74 nullability: Nullability::NonNullable, })
76 }
77
78 fn evaluate(expr: &Self::Expr, scope: &Scope) -> VortexResult<ArrayRef> {
79 let len = scope.len();
80 let value_arrays = expr
81 .values
82 .iter()
83 .map(|value_expr| value_expr.unchecked_evaluate(scope))
84 .process_results(|it| it.collect::<Vec<_>>())?;
85
86 let mut field_names = Vec::new();
88 let mut arrays = Vec::new();
89
90 for value_array in value_arrays.iter() {
91 if value_array.dtype().is_nullable() {
93 todo!("merge nullable structs");
94 }
95 if !value_array.dtype().is_struct() {
96 vortex_bail!("merge expects non-nullable struct input");
97 }
98
99 let struct_array = value_array.to_struct()?;
100
101 for (i, field_name) in struct_array.names().iter().enumerate() {
102 let array = struct_array.fields()[i].clone();
103
104 if let Some(idx) = field_names.iter().position(|name| name == field_name) {
106 arrays[idx] = array;
107 } else {
108 field_names.push(field_name.clone());
109 arrays.push(array);
110 }
111 }
112 }
113
114 let validity = match expr.nullability {
115 Nullability::NonNullable => Validity::NonNullable,
116 Nullability::Nullable => Validity::AllValid,
117 };
118 Ok(
119 StructArray::try_new(FieldNames::from(field_names), arrays, len, validity)?
120 .into_array(),
121 )
122 }
123
124 fn return_dtype(expr: &Self::Expr, scope: &DType) -> VortexResult<DType> {
125 let mut field_names = Vec::new();
126 let mut arrays = Vec::new();
127
128 for value in expr.values.iter() {
129 let dtype = value.return_dtype(scope)?;
130 if !dtype.is_struct() {
131 vortex_bail!("merge expects non-nullable struct input");
132 }
133
134 let struct_dtype = dtype
135 .as_struct()
136 .vortex_expect("merge expects struct input");
137
138 for i in 0..struct_dtype.nfields() {
139 let field_name = struct_dtype.field_name(i).vortex_expect("never OOB");
140 let field_dtype = struct_dtype.field_by_index(i).vortex_expect("never OOB");
141 if let Some(idx) = field_names.iter().position(|name| name == field_name) {
142 arrays[idx] = field_dtype;
143 } else {
144 field_names.push(field_name.clone());
145 arrays.push(field_dtype);
146 }
147 }
148 }
149
150 Ok(DType::Struct(
151 StructFields::new(FieldNames::from(field_names), arrays),
152 expr.nullability,
153 ))
154 }
155}
156
157impl MergeExpr {
158 pub fn new(values: Vec<ExprRef>, nullability: Nullability) -> Self {
159 MergeExpr {
160 values,
161 nullability,
162 }
163 }
164
165 pub fn new_expr(values: Vec<ExprRef>, nullability: Nullability) -> ExprRef {
166 Self::new(values, nullability).into_expr()
167 }
168
169 pub fn nullability(&self) -> Nullability {
170 self.nullability
171 }
172}
173
174pub fn merge(
185 elements: impl IntoIterator<Item = impl Into<ExprRef>>,
186 nullability: Nullability,
187) -> ExprRef {
188 let values = elements.into_iter().map(|value| value.into()).collect_vec();
189 MergeExpr::new(values, nullability).into_expr()
190}
191
192impl Display for MergeExpr {
193 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194 write!(
195 f,
196 "merge({}){}",
197 self.values.iter().format(", "),
198 self.nullability
199 )
200 }
201}
202
203impl AnalysisExpr for MergeExpr {}
204
205#[cfg(test)]
206mod tests {
207 use vortex_array::arrays::{PrimitiveArray, StructArray};
208 use vortex_array::{Array, IntoArray, ToCanonical};
209 use vortex_buffer::buffer;
210 use vortex_dtype::Nullability;
211 use vortex_error::{VortexResult, vortex_bail};
212
213 use crate::{MergeExpr, Scope, get_item, root};
214
215 fn primitive_field(array: &dyn Array, field_path: &[&str]) -> VortexResult<PrimitiveArray> {
216 let mut field_path = field_path.iter();
217
218 let Some(field) = field_path.next() else {
219 vortex_bail!("empty field path");
220 };
221
222 let mut array = array.to_struct()?.field_by_name(field)?.clone();
223 for field in field_path {
224 array = array.to_struct()?.field_by_name(field)?.clone();
225 }
226 array.to_primitive()
227 }
228
229 #[test]
230 pub fn test_merge() {
231 let expr = MergeExpr::new(
232 vec![
233 get_item("0", root()),
234 get_item("1", root()),
235 get_item("2", root()),
236 ],
237 Nullability::NonNullable,
238 );
239
240 let test_array = StructArray::from_fields(&[
241 (
242 "0",
243 StructArray::from_fields(&[
244 ("a", buffer![0, 0, 0].into_array()),
245 ("b", buffer![1, 1, 1].into_array()),
246 ])
247 .unwrap()
248 .into_array(),
249 ),
250 (
251 "1",
252 StructArray::from_fields(&[
253 ("b", buffer![2, 2, 2].into_array()),
254 ("c", buffer![3, 3, 3].into_array()),
255 ])
256 .unwrap()
257 .into_array(),
258 ),
259 (
260 "2",
261 StructArray::from_fields(&[
262 ("d", buffer![4, 4, 4].into_array()),
263 ("e", buffer![5, 5, 5].into_array()),
264 ])
265 .unwrap()
266 .into_array(),
267 ),
268 ])
269 .unwrap()
270 .into_array();
271 let actual_array = expr.evaluate(&Scope::new(test_array)).unwrap();
272
273 assert_eq!(
274 actual_array.as_struct_typed().names(),
275 ["a", "b", "c", "d", "e"]
276 );
277
278 assert_eq!(
279 primitive_field(&actual_array, &["a"])
280 .unwrap()
281 .as_slice::<i32>(),
282 [0, 0, 0]
283 );
284 assert_eq!(
285 primitive_field(&actual_array, &["b"])
286 .unwrap()
287 .as_slice::<i32>(),
288 [2, 2, 2]
289 );
290 assert_eq!(
291 primitive_field(&actual_array, &["c"])
292 .unwrap()
293 .as_slice::<i32>(),
294 [3, 3, 3]
295 );
296 assert_eq!(
297 primitive_field(&actual_array, &["d"])
298 .unwrap()
299 .as_slice::<i32>(),
300 [4, 4, 4]
301 );
302 assert_eq!(
303 primitive_field(&actual_array, &["e"])
304 .unwrap()
305 .as_slice::<i32>(),
306 [5, 5, 5]
307 );
308 }
309
310 #[test]
311 pub fn test_empty_merge() {
312 let expr = MergeExpr::new(Vec::new(), Nullability::NonNullable);
313
314 let test_array = StructArray::from_fields(&[("a", buffer![0, 1, 2].into_array())])
315 .unwrap()
316 .into_array();
317 let actual_array = expr.evaluate(&Scope::new(test_array.clone())).unwrap();
318 assert_eq!(actual_array.len(), test_array.len());
319 assert_eq!(actual_array.as_struct_typed().nfields(), 0);
320 }
321
322 #[test]
323 pub fn test_nested_merge() {
324 let expr = MergeExpr::new(
327 vec![get_item("0", root()), get_item("1", root())],
328 Nullability::NonNullable,
329 );
330
331 let test_array = StructArray::from_fields(&[
332 (
333 "0",
334 StructArray::from_fields(&[(
335 "a",
336 StructArray::from_fields(&[
337 ("x", buffer![0, 0, 0].into_array()),
338 ("y", buffer![1, 1, 1].into_array()),
339 ])
340 .unwrap()
341 .into_array(),
342 )])
343 .unwrap()
344 .into_array(),
345 ),
346 (
347 "1",
348 StructArray::from_fields(&[(
349 "a",
350 StructArray::from_fields(&[("x", buffer![0, 0, 0].into_array())])
351 .unwrap()
352 .into_array(),
353 )])
354 .unwrap()
355 .into_array(),
356 ),
357 ])
358 .unwrap()
359 .into_array();
360 let actual_array = expr
361 .evaluate(&Scope::new(test_array.clone()))
362 .unwrap()
363 .to_struct()
364 .unwrap();
365
366 assert_eq!(
367 actual_array
368 .field_by_name("a")
369 .unwrap()
370 .to_struct()
371 .unwrap()
372 .names()
373 .iter()
374 .map(|name| name.as_ref())
375 .collect::<Vec<_>>(),
376 vec!["x"]
377 );
378 }
379
380 #[test]
381 pub fn test_merge_order() {
382 let expr = MergeExpr::new(
383 vec![get_item("0", root()), get_item("1", root())],
384 Nullability::NonNullable,
385 );
386
387 let test_array = StructArray::from_fields(&[
388 (
389 "0",
390 StructArray::from_fields(&[
391 ("a", buffer![0, 0, 0].into_array()),
392 ("c", buffer![1, 1, 1].into_array()),
393 ])
394 .unwrap()
395 .into_array(),
396 ),
397 (
398 "1",
399 StructArray::from_fields(&[
400 ("b", buffer![2, 2, 2].into_array()),
401 ("d", buffer![3, 3, 3].into_array()),
402 ])
403 .unwrap()
404 .into_array(),
405 ),
406 ])
407 .unwrap()
408 .into_array();
409 let actual_array = expr
410 .evaluate(&Scope::new(test_array.clone()))
411 .unwrap()
412 .to_struct()
413 .unwrap();
414
415 assert_eq!(actual_array.names(), ["a", "c", "b", "d"]);
416 }
417
418 #[test]
419 pub fn test_merge_nullable() {
420 let expr = MergeExpr::new(vec![get_item("0", root())], Nullability::Nullable);
421
422 let test_array = StructArray::from_fields(&[(
423 "0",
424 StructArray::from_fields(&[
425 ("a", buffer![0, 0, 0].into_array()),
426 ("b", buffer![1, 1, 1].into_array()),
427 ])
428 .unwrap()
429 .into_array(),
430 )])
431 .unwrap()
432 .into_array();
433 let actual_array = expr.evaluate(&Scope::new(test_array.clone())).unwrap();
434 assert!(actual_array.dtype().is_nullable());
435 }
436}