1use std::fmt::Display;
5use std::fmt::Formatter;
6use std::hash::Hash;
7use std::sync::Arc;
8
9use itertools::Itertools as _;
10use vortex_array::ArrayRef;
11use vortex_array::ExecutionCtx;
12use vortex_array::IntoArray as _;
13use vortex_array::arrays::StructArray;
14use vortex_array::arrays::struct_::StructArrayExt;
15use vortex_array::dtype::DType;
16use vortex_array::dtype::FieldNames;
17use vortex_array::dtype::Nullability;
18use vortex_array::dtype::StructFields;
19use vortex_array::scalar_fn::Arity;
20use vortex_array::scalar_fn::ChildName;
21use vortex_array::scalar_fn::ExecutionArgs;
22use vortex_array::scalar_fn::ReduceNode;
23use vortex_array::scalar_fn::ScalarFnId;
24use vortex_array::scalar_fn::ScalarFnVTable;
25use vortex_array::scalar_fn::ScalarFnVTableExt;
26use vortex_array::scalar_fn::builtin::get_item::GetItem;
27use vortex_array::scalar_fn::builtin::pack::Pack;
28use vortex_array::scalar_fn::builtin::pack::PackOptions;
29use vortex_array::validity::Validity;
30use vortex_error::VortexExpect;
31use vortex_error::VortexResult;
32use vortex_error::vortex_bail;
33use vortex_session::VortexSession;
34use vortex_session::registry::CachedId;
35use vortex_utils::aliases::hash_set::HashSet;
36
37#[derive(Clone)]
44pub struct Merge;
45
46impl ScalarFnVTable for Merge {
47 type Options = DuplicateHandling;
48
49 fn id(&self) -> ScalarFnId {
50 static ID: CachedId = CachedId::new("vortex.merge");
51 *ID
52 }
53
54 fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
55 Ok(Some(match instance {
56 DuplicateHandling::RightMost => vec![0x00],
57 DuplicateHandling::Error => vec![0x01],
58 }))
59 }
60
61 fn deserialize(
62 &self,
63 _metadata: &[u8],
64 _session: &VortexSession,
65 ) -> VortexResult<Self::Options> {
66 let instance = match _metadata {
67 [0x00] => DuplicateHandling::RightMost,
68 [0x01] => DuplicateHandling::Error,
69 _ => {
70 vortex_bail!("invalid metadata for Merge expression");
71 }
72 };
73 Ok(instance)
74 }
75
76 fn arity(&self, _options: &Self::Options) -> Arity {
77 Arity::Variadic { min: 0, max: None }
78 }
79
80 fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
81 ChildName::from(Arc::from(format!("{}", child_idx)))
82 }
83
84 fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
85 let mut field_names = Vec::new();
86 let mut arrays = Vec::new();
87 let mut merge_nullability = Nullability::NonNullable;
88 let mut duplicate_names = HashSet::<_>::new();
89
90 for dtype in arg_dtypes {
91 let Some(fields) = dtype.as_struct_fields_opt() else {
92 vortex_bail!("merge expects struct input");
93 };
94 if dtype.is_nullable() {
95 vortex_bail!("merge expects non-nullable input");
96 }
97
98 merge_nullability |= dtype.nullability();
99
100 for (field_name, field_dtype) in fields.names().iter().zip_eq(fields.fields()) {
101 if let Some(idx) = field_names.iter().position(|name| name == field_name) {
102 duplicate_names.insert(field_name.clone());
103 arrays[idx] = field_dtype;
104 } else {
105 field_names.push(field_name.clone());
106 arrays.push(field_dtype);
107 }
108 }
109 }
110
111 if options == &DuplicateHandling::Error && !duplicate_names.is_empty() {
112 vortex_bail!(
113 "merge: duplicate fields in children: {}",
114 duplicate_names.into_iter().format(", ")
115 )
116 }
117
118 Ok(DType::Struct(
119 StructFields::new(FieldNames::from(field_names), arrays),
120 merge_nullability,
121 ))
122 }
123
124 fn execute(
125 &self,
126 options: &Self::Options,
127 args: &dyn ExecutionArgs,
128 ctx: &mut ExecutionCtx,
129 ) -> VortexResult<ArrayRef> {
130 let mut field_names = Vec::new();
132 let mut arrays = Vec::new();
133 let mut duplicate_names = HashSet::<_>::new();
134
135 for i in 0..args.num_inputs() {
136 let array = args.get(i)?.execute::<StructArray>(ctx)?;
137 if array.dtype().is_nullable() {
138 vortex_bail!("merge expects non-nullable input");
139 }
140
141 for (field_name, field_array) in array
142 .names()
143 .iter()
144 .zip_eq(array.iter_unmasked_fields().cloned())
145 {
146 if let Some(idx) = field_names.iter().position(|name| name == field_name) {
148 duplicate_names.insert(field_name.clone());
149 arrays[idx] = field_array;
150 } else {
151 field_names.push(field_name.clone());
152 arrays.push(field_array);
153 }
154 }
155 }
156
157 if options == &DuplicateHandling::Error && !duplicate_names.is_empty() {
158 vortex_bail!(
159 "merge: duplicate fields in children: {}",
160 duplicate_names.into_iter().format(", ")
161 )
162 }
163
164 let validity = Validity::NonNullable;
166 let len = args.row_count();
167 Ok(
168 StructArray::try_new(FieldNames::from(field_names), arrays, len, validity)?
169 .into_array(),
170 )
171 }
172
173 fn reduce<T: ReduceNode>(&self, options: &Self::Options, node: &T) -> VortexResult<Option<T>> {
174 let mut names = Vec::with_capacity(node.child_count() * 2);
175 let mut fields: Vec<T> = Vec::with_capacity(node.child_count() * 2);
176 let mut duplicate_names = HashSet::<_>::new();
177
178 for child in (0..node.child_count()).map(|i| node.child(i)) {
179 let child_dtype = child.node_dtype()?;
180 if !child_dtype.is_struct() || child_dtype.is_nullable() {
181 vortex_bail!(
182 "Merge child must return a non-nullable struct dtype, got {}",
183 child_dtype
184 )
185 }
186
187 let child_dtype = child_dtype
188 .as_struct_fields_opt()
189 .vortex_expect("expected struct");
190
191 for name in child_dtype.names().iter() {
192 let field = GetItem::apply_now(&child, name)?;
197
198 if let Some(idx) = names.iter().position(|n| n == name) {
199 duplicate_names.insert(name.clone());
200 fields[idx] = field;
201 } else {
202 names.push(name.clone());
203 fields.push(field);
204 }
205 }
206
207 if options == &DuplicateHandling::Error && !duplicate_names.is_empty() {
208 vortex_bail!(
209 "merge: duplicate fields in children: {}",
210 duplicate_names.into_iter().format(", ")
211 )
212 }
213 }
214
215 let pack_expr = node.new_node(
216 Pack.bind(PackOptions {
217 names: FieldNames::from(names),
218 nullability: node.node_dtype()?.nullability(),
219 }),
220 &fields,
221 )?;
222
223 Ok(Some(pack_expr))
224 }
225
226 fn is_strict(&self, _options: &Self::Options) -> bool {
227 true
228 }
229
230 fn is_infallible(&self, instance: &Self::Options) -> bool {
231 !matches!(instance, DuplicateHandling::Error)
232 }
233}
234
235#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
237pub enum DuplicateHandling {
238 RightMost,
240 #[default]
242 Error,
243}
244
245impl Display for DuplicateHandling {
246 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
247 match self {
248 DuplicateHandling::RightMost => write!(f, "RightMost"),
249 DuplicateHandling::Error => write!(f, "Error"),
250 }
251 }
252}
253
254#[cfg(test)]
255mod tests {
256 use std::sync::LazyLock;
257
258 use vortex_array::ArrayRef;
259 use vortex_array::IntoArray;
260 use vortex_array::VortexSessionExecute;
261 use vortex_array::arrays::PrimitiveArray;
262 use vortex_array::arrays::struct_::StructArrayExt;
263 use vortex_array::assert_arrays_eq;
264 use vortex_array::dtype::DType;
265 use vortex_array::dtype::Nullability::NonNullable;
266 use vortex_array::dtype::PType::I32;
267 use vortex_array::dtype::PType::I64;
268 use vortex_array::dtype::PType::U32;
269 use vortex_array::dtype::PType::U64;
270 use vortex_array::scalar_fn::builtin::pack::Pack;
271 use vortex_buffer::buffer;
272 use vortex_error::VortexResult;
273 use vortex_error::vortex_bail;
274 use vortex_expr::ArrayExprExt;
275 use vortex_expr::Expression;
276 use vortex_expr::get_item;
277 use vortex_expr::root;
278 use vortex_session::VortexSession;
279
280 use crate::expr::merge;
281 use crate::expr::merge_opts;
282 use crate::merge::DuplicateHandling;
283 use crate::merge::StructArray;
284
285 static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
286 let session = VortexSession::empty();
287
288 vortex_array::initialize(&session);
289
290 crate::initialize(&session);
291
292 session
293 });
294
295 fn field_array(array: &ArrayRef, field_path: &[&str]) -> VortexResult<ArrayRef> {
296 let mut ctx = SESSION.create_execution_ctx();
297 let mut field_path = field_path.iter();
298
299 let Some(field) = field_path.next() else {
300 vortex_bail!("empty field path");
301 };
302
303 let mut array = array
304 .clone()
305 .execute::<StructArray>(&mut ctx)?
306 .unmasked_field_by_name(field)?
307 .clone();
308 for field in field_path {
309 let next = array
310 .clone()
311 .execute::<StructArray>(&mut ctx)?
312 .unmasked_field_by_name(field)?
313 .clone();
314 array = next;
315 }
316 Ok(array)
317 }
318
319 #[test]
320 pub fn test_merge_right_most() {
321 let mut ctx = SESSION.create_execution_ctx();
322 let expr = merge_opts(
323 vec![
324 get_item("0", root()),
325 get_item("1", root()),
326 get_item("2", root()),
327 ],
328 DuplicateHandling::RightMost,
329 );
330
331 let test_array = StructArray::from_fields(&[
332 (
333 "0",
334 StructArray::from_fields(&[
335 ("a", buffer![0, 0, 0].into_array()),
336 ("b", buffer![1, 1, 1].into_array()),
337 ])
338 .unwrap()
339 .into_array(),
340 ),
341 (
342 "1",
343 StructArray::from_fields(&[
344 ("b", buffer![2, 2, 2].into_array()),
345 ("c", buffer![3, 3, 3].into_array()),
346 ])
347 .unwrap()
348 .into_array(),
349 ),
350 (
351 "2",
352 StructArray::from_fields(&[
353 ("d", buffer![4, 4, 4].into_array()),
354 ("e", buffer![5, 5, 5].into_array()),
355 ])
356 .unwrap()
357 .into_array(),
358 ),
359 ])
360 .unwrap()
361 .into_array();
362 let actual_array = test_array.apply(&expr).unwrap();
363
364 assert_eq!(
365 actual_array.dtype().as_struct_fields().names(),
366 ["a", "b", "c", "d", "e"]
367 );
368
369 assert_arrays_eq!(
370 field_array(&actual_array, &["a"]).unwrap(),
371 PrimitiveArray::from_iter([0i32, 0, 0]),
372 &mut ctx
373 );
374 assert_arrays_eq!(
375 field_array(&actual_array, &["b"]).unwrap(),
376 PrimitiveArray::from_iter([2i32, 2, 2]),
377 &mut ctx
378 );
379 assert_arrays_eq!(
380 field_array(&actual_array, &["c"]).unwrap(),
381 PrimitiveArray::from_iter([3i32, 3, 3]),
382 &mut ctx
383 );
384 assert_arrays_eq!(
385 field_array(&actual_array, &["d"]).unwrap(),
386 PrimitiveArray::from_iter([4i32, 4, 4]),
387 &mut ctx
388 );
389 assert_arrays_eq!(
390 field_array(&actual_array, &["e"]).unwrap(),
391 PrimitiveArray::from_iter([5i32, 5, 5]),
392 &mut ctx
393 );
394 }
395
396 #[test]
397 #[should_panic(expected = "merge: duplicate fields in children")]
398 pub fn test_merge_error_on_dupe_return_dtype() {
399 let expr = merge_opts(
400 vec![get_item("0", root()), get_item("1", root())],
401 DuplicateHandling::Error,
402 );
403 let test_array = StructArray::try_from_iter([
404 (
405 "0",
406 StructArray::try_from_iter([("a", buffer![1]), ("b", buffer![1])]).unwrap(),
407 ),
408 (
409 "1",
410 StructArray::try_from_iter([("c", buffer![1]), ("b", buffer![1])]).unwrap(),
411 ),
412 ])
413 .unwrap()
414 .into_array();
415
416 expr.return_dtype(test_array.dtype()).unwrap();
417 }
418
419 #[test]
420 #[should_panic(expected = "merge: duplicate fields in children")]
421 pub fn test_merge_error_on_dupe_evaluate() {
422 let expr = merge_opts(
423 vec![get_item("0", root()), get_item("1", root())],
424 DuplicateHandling::Error,
425 );
426 let test_array = StructArray::try_from_iter([
427 (
428 "0",
429 StructArray::try_from_iter([("a", buffer![1]), ("b", buffer![1])]).unwrap(),
430 ),
431 (
432 "1",
433 StructArray::try_from_iter([("c", buffer![1]), ("b", buffer![1])]).unwrap(),
434 ),
435 ])
436 .unwrap()
437 .into_array();
438
439 test_array.apply(&expr).unwrap();
440 }
441
442 #[test]
443 pub fn test_empty_merge() {
444 let expr = merge(Vec::<Expression>::new());
445
446 let test_array = StructArray::from_fields(&[("a", buffer![0, 1, 2].into_array())])
447 .unwrap()
448 .into_array();
449 let actual_array = test_array.clone().apply(&expr).unwrap();
450 assert_eq!(actual_array.len(), test_array.len());
451 let expected = StructArray::try_new(
452 Default::default(),
453 vec![],
454 3,
455 vortex_array::validity::Validity::NonNullable,
456 )
457 .unwrap();
458 assert_arrays_eq!(actual_array, expected, &mut SESSION.create_execution_ctx());
459 }
460
461 #[test]
462 pub fn test_nested_merge() {
463 let expr = merge_opts(
466 vec![get_item("0", root()), get_item("1", root())],
467 DuplicateHandling::RightMost,
468 );
469
470 let test_array = StructArray::from_fields(&[
471 (
472 "0",
473 StructArray::from_fields(&[(
474 "a",
475 StructArray::from_fields(&[
476 ("x", buffer![0, 0, 0].into_array()),
477 ("y", buffer![1, 1, 1].into_array()),
478 ])
479 .unwrap()
480 .into_array(),
481 )])
482 .unwrap()
483 .into_array(),
484 ),
485 (
486 "1",
487 StructArray::from_fields(&[(
488 "a",
489 StructArray::from_fields(&[("x", buffer![0, 0, 0].into_array())])
490 .unwrap()
491 .into_array(),
492 )])
493 .unwrap()
494 .into_array(),
495 ),
496 ])
497 .unwrap()
498 .into_array();
499 let mut ctx = SESSION.create_execution_ctx();
500 let actual_array = test_array
501 .apply(&expr)
502 .unwrap()
503 .execute::<StructArray>(&mut ctx)
504 .unwrap();
505
506 let inner_struct = actual_array.unmasked_field_by_name("a").unwrap();
507 assert_eq!(
508 inner_struct
509 .dtype()
510 .as_struct_fields()
511 .names()
512 .iter()
513 .map(|name| name.as_ref())
514 .collect::<Vec<_>>(),
515 vec!["x"]
516 );
517 assert_arrays_eq!(
518 inner_struct,
519 StructArray::from_fields(&[("x", buffer![0i32, 0, 0].into_array())]).unwrap(),
520 &mut ctx
521 );
522 }
523
524 #[test]
525 pub fn test_merge_order() {
526 let mut ctx = SESSION.create_execution_ctx();
527 let expr = merge(vec![get_item("0", root()), get_item("1", root())]);
528
529 let test_array = StructArray::from_fields(&[
530 (
531 "0",
532 StructArray::from_fields(&[
533 ("a", buffer![0, 0, 0].into_array()),
534 ("c", buffer![1, 1, 1].into_array()),
535 ])
536 .unwrap()
537 .into_array(),
538 ),
539 (
540 "1",
541 StructArray::from_fields(&[
542 ("b", buffer![2, 2, 2].into_array()),
543 ("d", buffer![3, 3, 3].into_array()),
544 ])
545 .unwrap()
546 .into_array(),
547 ),
548 ])
549 .unwrap()
550 .into_array();
551 let actual_array = test_array.apply(&expr).unwrap();
552
553 assert_eq!(
554 actual_array.dtype().as_struct_fields().names(),
555 ["a", "c", "b", "d"]
556 );
557 let expected = StructArray::from_fields(&[
558 ("a", buffer![0i32, 0, 0].into_array()),
559 ("c", buffer![1i32, 1, 1].into_array()),
560 ("b", buffer![2i32, 2, 2].into_array()),
561 ("d", buffer![3i32, 3, 3].into_array()),
562 ])
563 .unwrap();
564 assert_arrays_eq!(actual_array, expected, &mut ctx);
565 }
566
567 #[test]
568 pub fn test_display() {
569 let expr = merge([get_item("struct1", root()), get_item("struct2", root())]);
570 assert_eq!(
571 expr.to_string(),
572 "vortex.merge($.struct1, $.struct2, opts=Error)"
573 );
574
575 let expr2 = merge(vec![get_item("a", root())]);
576 assert_eq!(expr2.to_string(), "vortex.merge($.a, opts=Error)");
577 }
578
579 #[test]
580 fn test_remove_merge() {
581 let dtype = DType::struct_(
582 [
583 ("0", DType::struct_([("a", I32), ("b", I64)], NonNullable)),
584 ("1", DType::struct_([("b", U32), ("c", U64)], NonNullable)),
585 ],
586 NonNullable,
587 );
588
589 let e = merge_opts(
590 [get_item("0", root()), get_item("1", root())],
591 DuplicateHandling::RightMost,
592 );
593
594 let result = e.bind(&dtype).unwrap().optimize().unwrap();
595
596 assert!(result.is::<Pack>());
597 assert_eq!(
598 result.dtype(),
599 &DType::struct_([("a", I32), ("b", U32), ("c", U64)], NonNullable)
600 );
601 }
602}