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