1use crate::utils::make_scalar_function;
8use arrow::array::{
9 Array, ArrayRef, GenericListArray, OffsetSizeTrait, UInt32Array, UInt64Array,
10 new_empty_array, new_null_array,
11};
12use arrow::buffer::{NullBuffer, OffsetBuffer};
13use arrow::compute::{concat, take};
14use arrow::datatypes::DataType::{LargeList, List, Null};
15use arrow::datatypes::{DataType, Field, FieldRef};
16use arrow::row::{RowConverter, SortField};
17use datafusion_common::cast::{as_large_list_array, as_list_array};
18use datafusion_common::float_semantics::normalize_floats;
19use datafusion_common::utils::{ListCoercion, offset_span};
20use datafusion_common::{
21 Result, assert_eq_or_internal_err, exec_err, internal_err, utils::take_function_args,
22};
23use datafusion_expr::{
24 ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
25 Volatility,
26};
27use datafusion_macros::user_doc;
28use hashbrown::HashSet;
29use std::fmt::{Display, Formatter};
30use std::sync::Arc;
31
32make_udf_expr_and_func!(
34 ArrayUnion,
35 array_union,
36 array1 array2,
37 "returns an array of the elements in the union of array1 and array2 without duplicates.",
38 array_union_udf
39);
40
41make_udf_expr_and_func!(
42 ArrayIntersect,
43 array_intersect,
44 first_array second_array,
45 "returns an array of the elements in the intersection of array1 and array2.",
46 array_intersect_udf
47);
48
49make_udf_expr_and_func!(
50 ArrayDistinct,
51 array_distinct,
52 array,
53 "returns distinct values from the array after removing duplicates.",
54 array_distinct_udf
55);
56
57#[user_doc(
58 doc_section(label = "Array Functions"),
59 description = "Returns an array of elements that are present in both arrays (all elements from both arrays) without duplicates.",
60 syntax_example = "array_union(array1, array2)",
61 sql_example = r#"```sql
62> select array_union([1, 2, 3, 4], [5, 6, 3, 4]);
63+----------------------------------------------------+
64| array_union([1, 2, 3, 4], [5, 6, 3, 4]); |
65+----------------------------------------------------+
66| [1, 2, 3, 4, 5, 6] |
67+----------------------------------------------------+
68> select array_union([1, 2, 3, 4], [5, 6, 7, 8]);
69+----------------------------------------------------+
70| array_union([1, 2, 3, 4], [5, 6, 7, 8]); |
71+----------------------------------------------------+
72| [1, 2, 3, 4, 5, 6, 7, 8] |
73+----------------------------------------------------+
74```"#,
75 argument(
76 name = "array1",
77 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
78 ),
79 argument(
80 name = "array2",
81 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
82 )
83)]
84#[derive(Debug, PartialEq, Eq, Hash)]
85pub struct ArrayUnion {
86 signature: Signature,
87 aliases: Vec<String>,
88}
89
90impl Default for ArrayUnion {
91 fn default() -> Self {
92 Self::new()
93 }
94}
95
96impl ArrayUnion {
97 pub fn new() -> Self {
98 Self {
99 signature: Signature::arrays(
100 2,
101 Some(ListCoercion::FixedSizedListToList),
102 Volatility::Immutable,
103 ),
104 aliases: vec![String::from("list_union")],
105 }
106 }
107}
108
109impl ScalarUDFImpl for ArrayUnion {
110 fn name(&self) -> &str {
111 "array_union"
112 }
113
114 fn signature(&self) -> &Signature {
115 &self.signature
116 }
117
118 fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
119 let [array1, array2] = take_function_args(self.name(), arg_types)?;
120 match (array1, array2) {
121 (Null, Null) => Ok(DataType::new_list(Null, true)),
122 (Null, dt) | (dt, Null) => Ok(dt.clone()),
123 (dt, _) => Ok(dt.clone()),
124 }
125 }
126
127 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
128 make_scalar_function(array_union_inner)(&args.args)
129 }
130
131 fn aliases(&self) -> &[String] {
132 &self.aliases
133 }
134
135 fn documentation(&self) -> Option<&Documentation> {
136 self.doc()
137 }
138}
139
140#[user_doc(
141 doc_section(label = "Array Functions"),
142 description = "Returns an array of elements in the intersection of array1 and array2.",
143 syntax_example = "array_intersect(array1, array2)",
144 sql_example = r#"```sql
145> select array_intersect([1, 2, 3, 4], [5, 6, 3, 4]);
146+----------------------------------------------------+
147| array_intersect([1, 2, 3, 4], [5, 6, 3, 4]); |
148+----------------------------------------------------+
149| [3, 4] |
150+----------------------------------------------------+
151> select array_intersect([1, 2, 3, 4], [5, 6, 7, 8]);
152+----------------------------------------------------+
153| array_intersect([1, 2, 3, 4], [5, 6, 7, 8]); |
154+----------------------------------------------------+
155| [] |
156+----------------------------------------------------+
157```"#,
158 argument(
159 name = "array1",
160 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
161 ),
162 argument(
163 name = "array2",
164 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
165 )
166)]
167#[derive(Debug, PartialEq, Eq, Hash)]
168pub struct ArrayIntersect {
169 signature: Signature,
170 aliases: Vec<String>,
171}
172
173impl Default for ArrayIntersect {
174 fn default() -> Self {
175 Self::new()
176 }
177}
178
179impl ArrayIntersect {
180 pub fn new() -> Self {
181 Self {
182 signature: Signature::arrays(
183 2,
184 Some(ListCoercion::FixedSizedListToList),
185 Volatility::Immutable,
186 ),
187 aliases: vec![String::from("list_intersect")],
188 }
189 }
190}
191
192impl ScalarUDFImpl for ArrayIntersect {
193 fn name(&self) -> &str {
194 "array_intersect"
195 }
196
197 fn signature(&self) -> &Signature {
198 &self.signature
199 }
200
201 fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
202 let [array1, array2] = take_function_args(self.name(), arg_types)?;
203 match (array1, array2) {
204 (Null, Null) => Ok(DataType::new_list(Null, true)),
205 (Null, dt) | (dt, Null) => Ok(dt.clone()),
206 (dt, _) => Ok(dt.clone()),
207 }
208 }
209
210 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
211 make_scalar_function(array_intersect_inner)(&args.args)
212 }
213
214 fn aliases(&self) -> &[String] {
215 &self.aliases
216 }
217
218 fn documentation(&self) -> Option<&Documentation> {
219 self.doc()
220 }
221}
222
223#[user_doc(
224 doc_section(label = "Array Functions"),
225 description = "Returns distinct values from the array after removing duplicates, in the order they first appear.",
226 syntax_example = "array_distinct(array)",
227 sql_example = r#"```sql
228> select array_distinct([1, 3, 2, 3, 1, 2, 4]);
229+---------------------------------------+
230| array_distinct(List([1,3,2,3,1,2,4])) |
231+---------------------------------------+
232| [1, 3, 2, 4] |
233+---------------------------------------+
234```"#,
235 argument(
236 name = "array",
237 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
238 )
239)]
240#[derive(Debug, PartialEq, Eq, Hash)]
241pub struct ArrayDistinct {
242 signature: Signature,
243 aliases: Vec<String>,
244}
245
246impl ArrayDistinct {
247 pub fn new() -> Self {
248 Self {
249 signature: Signature::array(Volatility::Immutable),
250 aliases: vec!["list_distinct".to_string()],
251 }
252 }
253}
254
255impl Default for ArrayDistinct {
256 fn default() -> Self {
257 Self::new()
258 }
259}
260
261impl ScalarUDFImpl for ArrayDistinct {
262 fn name(&self) -> &str {
263 "array_distinct"
264 }
265
266 fn signature(&self) -> &Signature {
267 &self.signature
268 }
269
270 fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
271 Ok(arg_types[0].clone())
272 }
273
274 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
275 make_scalar_function(array_distinct_inner)(&args.args)
276 }
277
278 fn aliases(&self) -> &[String] {
279 &self.aliases
280 }
281
282 fn documentation(&self) -> Option<&Documentation> {
283 self.doc()
284 }
285}
286
287fn array_distinct_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
290 let [array] = take_function_args("array_distinct", args)?;
291 match array.data_type() {
292 Null => Ok(Arc::clone(array)),
293 List(field) => {
294 let array = as_list_array(&array)?;
295 general_array_distinct(array, field)
296 }
297 LargeList(field) => {
298 let array = as_large_list_array(&array)?;
299 general_array_distinct(array, field)
300 }
301 arg_type => exec_err!("array_distinct does not support type {arg_type}"),
302 }
303}
304
305#[derive(Debug, PartialEq, Copy, Clone)]
306enum SetOp {
307 Union,
308 Intersect,
309}
310
311impl Display for SetOp {
312 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
313 match self {
314 SetOp::Union => write!(f, "array_union"),
315 SetOp::Intersect => write!(f, "array_intersect"),
316 }
317 }
318}
319
320pub(crate) fn normalize_visible_values<OffsetSize: OffsetSizeTrait>(
321 array: &GenericListArray<OffsetSize>,
322) -> ArrayRef {
323 let (first, len) = offset_span(array.offsets());
324 if first == 0 && len == array.values().len() {
325 normalize_floats(array.values())
326 } else {
327 normalize_floats(&array.values().slice(first, len))
328 }
329}
330
331fn generic_set_lists<OffsetSize: OffsetSizeTrait>(
332 l: &GenericListArray<OffsetSize>,
333 r: &GenericListArray<OffsetSize>,
334 set_op: SetOp,
335) -> Result<ArrayRef> {
336 if l.is_empty() || l.value_type().is_null() {
337 let field = Arc::new(Field::new_list_field(r.value_type(), true));
338 return general_array_distinct::<OffsetSize>(r, &field);
339 } else if r.is_empty() || r.value_type().is_null() {
340 let field = Arc::new(Field::new_list_field(l.value_type(), true));
341 return general_array_distinct::<OffsetSize>(l, &field);
342 }
343
344 assert_eq_or_internal_err!(
345 l.value_type(),
346 r.value_type(),
347 "{set_op:?} is not implemented for '{l:?}' and '{r:?}'"
348 );
349
350 let converter = RowConverter::new(vec![SortField::new(l.value_type())])?;
351
352 let l_values_norm = normalize_visible_values(l);
356 let r_values_norm = normalize_visible_values(r);
357
358 let rows_l = converter.convert_columns(&[Arc::clone(&l_values_norm)])?;
359 let rows_r = converter.convert_columns(&[Arc::clone(&r_values_norm)])?;
360
361 let combined_values = concat(&[l_values_norm.as_ref(), r_values_norm.as_ref()])?;
365 let r_offset = l_values_norm.len();
366
367 match set_op {
368 SetOp::Union => generic_set_loop::<OffsetSize, true>(
369 l,
370 r,
371 &rows_l,
372 &rows_r,
373 &combined_values,
374 r_offset,
375 ),
376 SetOp::Intersect => generic_set_loop::<OffsetSize, false>(
377 l,
378 r,
379 &rows_l,
380 &rows_r,
381 &combined_values,
382 r_offset,
383 ),
384 }
385}
386
387fn generic_set_loop<OffsetSize: OffsetSizeTrait, const IS_UNION: bool>(
390 l: &GenericListArray<OffsetSize>,
391 r: &GenericListArray<OffsetSize>,
392 rows_l: &arrow::row::Rows,
393 rows_r: &arrow::row::Rows,
394 combined_values: &ArrayRef,
395 r_offset: usize,
396) -> Result<ArrayRef> {
397 let l_offsets = l.value_offsets();
398 let r_offsets = r.value_offsets();
399 let l_first = l.offsets()[0].as_usize();
400 let r_first = r.offsets()[0].as_usize();
401
402 let mut result_offsets = Vec::with_capacity(l.len() + 1);
403 result_offsets.push(OffsetSize::usize_as(0));
404 let initial_capacity = if IS_UNION {
405 rows_l.num_rows()
407 } else {
408 rows_l.num_rows().min(rows_r.num_rows())
410 };
411
412 let mut indices: Vec<usize> = Vec::with_capacity(initial_capacity);
413
414 let mut seen = HashSet::new();
416 let mut lookup_set = HashSet::new();
417 for i in 0..l.len() {
418 let last_offset = *result_offsets.last().unwrap();
419
420 if l.is_null(i) || r.is_null(i) {
421 result_offsets.push(last_offset);
422 continue;
423 }
424
425 let l_start = l_offsets[i].as_usize() - l_first;
426 let l_end = l_offsets[i + 1].as_usize() - l_first;
427 let r_start = r_offsets[i].as_usize() - r_first;
428 let r_end = r_offsets[i + 1].as_usize() - r_first;
429
430 seen.clear();
431
432 if IS_UNION {
433 for idx in l_start..l_end {
434 let row = rows_l.row(idx);
435 if seen.insert(row) {
436 indices.push(idx);
437 }
438 }
439 for idx in r_start..r_end {
440 let row = rows_r.row(idx);
441 if seen.insert(row) {
442 indices.push(idx + r_offset);
443 }
444 }
445 } else {
446 let l_len = l_end - l_start;
447 let r_len = r_end - r_start;
448
449 let (lookup_rows, lookup_range, probe_rows, probe_range, probe_offset) =
452 if l_len < r_len {
453 (rows_l, l_start..l_end, rows_r, r_start..r_end, r_offset)
454 } else {
455 (rows_r, r_start..r_end, rows_l, l_start..l_end, 0)
456 };
457 lookup_set.clear();
458 lookup_set.reserve(lookup_range.len());
459
460 for idx in lookup_range {
462 lookup_set.insert(lookup_rows.row(idx));
463 }
464
465 for idx in probe_range {
467 let row = probe_rows.row(idx);
468 if lookup_set.contains(&row) && seen.insert(row) {
469 indices.push(idx + probe_offset);
470 }
471 }
472 }
473 result_offsets.push(last_offset + OffsetSize::usize_as(seen.len()));
474 }
475
476 let final_values = if indices.is_empty() {
479 new_empty_array(&l.value_type())
480 } else if OffsetSize::IS_LARGE {
481 let indices =
482 UInt64Array::from(indices.into_iter().map(|i| i as u64).collect::<Vec<_>>());
483 take(combined_values.as_ref(), &indices, None)?
484 } else {
485 let indices =
486 UInt32Array::from(indices.into_iter().map(|i| i as u32).collect::<Vec<_>>());
487 take(combined_values.as_ref(), &indices, None)?
488 };
489
490 let arr = GenericListArray::<OffsetSize>::try_new(
491 Arc::clone(l.value_field()),
492 OffsetBuffer::new(result_offsets.into()),
493 final_values,
494 NullBuffer::union(l.nulls(), r.nulls()),
495 )?;
496 Ok(Arc::new(arr))
497}
498
499fn general_set_op(
500 array1: &ArrayRef,
501 array2: &ArrayRef,
502 set_op: SetOp,
503) -> Result<ArrayRef> {
504 let len = array1.len();
505 match (array1.data_type(), array2.data_type()) {
506 (Null, Null) => Ok(new_null_array(&DataType::new_list(Null, true), len)),
507 (Null, dt @ List(_))
508 | (Null, dt @ LargeList(_))
509 | (dt @ List(_), Null)
510 | (dt @ LargeList(_), Null) => Ok(new_null_array(dt, len)),
511 (List(_), List(_)) => {
512 let array1 = as_list_array(&array1)?;
513 let array2 = as_list_array(&array2)?;
514 generic_set_lists::<i32>(array1, array2, set_op)
515 }
516 (LargeList(_), LargeList(_)) => {
517 let array1 = as_large_list_array(&array1)?;
518 let array2 = as_large_list_array(&array2)?;
519 generic_set_lists::<i64>(array1, array2, set_op)
520 }
521 (data_type1, data_type2) => {
522 internal_err!(
523 "{set_op} does not support types '{data_type1:?}' and '{data_type2:?}'"
524 )
525 }
526 }
527}
528
529fn array_union_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
530 let [array1, array2] = take_function_args("array_union", args)?;
531 general_set_op(array1, array2, SetOp::Union)
532}
533
534fn array_intersect_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
535 let [array1, array2] = take_function_args("array_intersect", args)?;
536 general_set_op(array1, array2, SetOp::Intersect)
537}
538
539fn general_array_distinct<OffsetSize: OffsetSizeTrait>(
540 array: &GenericListArray<OffsetSize>,
541 field: &FieldRef,
542) -> Result<ArrayRef> {
543 if array.is_empty() {
544 return Ok(Arc::new(array.clone()) as ArrayRef);
545 }
546 let value_offsets = array.value_offsets();
547 let dt = array.value_type();
548 let mut offsets = Vec::with_capacity(array.len() + 1);
549 offsets.push(OffsetSize::usize_as(0));
550
551 let converter = RowConverter::new(vec![SortField::new(dt.clone())])?;
552
553 let first_offset = value_offsets[0].as_usize();
557 let values_norm = normalize_visible_values(array);
558 let rows = converter.convert_columns(&[Arc::clone(&values_norm)])?;
559
560 let mut indices: Vec<usize> = Vec::with_capacity(rows.num_rows());
561 let mut seen = HashSet::new();
562 for i in 0..array.len() {
563 let last_offset = *offsets.last().unwrap();
564
565 if array.is_null(i) {
567 offsets.push(last_offset);
568 continue;
569 }
570
571 let start = value_offsets[i].as_usize() - first_offset;
572 let end = value_offsets[i + 1].as_usize() - first_offset;
573 seen.clear();
574 seen.reserve(end - start);
575
576 for idx in start..end {
578 let row = rows.row(idx);
579 if seen.insert(row) {
580 indices.push(idx);
581 }
582 }
583 offsets.push(last_offset + OffsetSize::usize_as(seen.len()));
584 }
585
586 let final_values = if indices.is_empty() {
590 new_empty_array(&dt)
591 } else if OffsetSize::IS_LARGE {
592 let indices =
593 UInt64Array::from(indices.into_iter().map(|i| i as u64).collect::<Vec<_>>());
594 take(values_norm.as_ref(), &indices, None)?
595 } else {
596 let indices =
597 UInt32Array::from(indices.into_iter().map(|i| i as u32).collect::<Vec<_>>());
598 take(values_norm.as_ref(), &indices, None)?
599 };
600
601 Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
602 Arc::clone(field),
603 OffsetBuffer::new(offsets.into()),
604 final_values,
605 array.nulls().cloned(),
607 )?))
608}
609
610#[cfg(test)]
611mod tests {
612 use std::sync::Arc;
613
614 use arrow::{
615 array::{Array, AsArray, Int32Array, LargeListArray, ListArray},
616 buffer::OffsetBuffer,
617 datatypes::{DataType, Field, Float64Type, Int32Type},
618 };
619 use datafusion_common::{DataFusionError, Result, config::ConfigOptions};
620 use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
621
622 use crate::set_ops::{
623 ArrayDistinct, ArrayIntersect, ArrayUnion, SetOp, array_distinct_udf,
624 general_array_distinct, generic_set_lists,
625 };
626
627 fn make_sliced_pair() -> (ListArray, ListArray, Arc<Field>) {
633 let l = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
634 Some(vec![Some(1), Some(2)]),
635 Some(vec![Some(3), Some(4)]),
636 Some(vec![Some(5), Some(6)]),
637 Some(vec![Some(7), Some(8)]),
638 ]);
639 let r = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
640 Some(vec![Some(1), Some(3)]),
641 Some(vec![Some(3), Some(5)]),
642 Some(vec![Some(5), Some(7)]),
643 Some(vec![Some(7), Some(1)]),
644 ]);
645 let field = Arc::new(Field::new("item", l.data_type().clone(), true));
646 (l.slice(1, 2), r.slice(1, 2), field)
647 }
648
649 fn collect_i32_list(list: &ListArray) -> Vec<Vec<i32>> {
650 (0..list.len())
651 .map(|i| {
652 let arr = list.value(i);
653 arr.as_any()
654 .downcast_ref::<Int32Array>()
655 .unwrap()
656 .values()
657 .to_vec()
658 })
659 .collect()
660 }
661
662 fn collect_f64_bits<OffsetSize: arrow::array::OffsetSizeTrait>(
663 list: &arrow::array::GenericListArray<OffsetSize>,
664 row: usize,
665 ) -> Vec<Option<u64>> {
666 list.value(row)
667 .as_primitive::<Float64Type>()
668 .iter()
669 .map(|value| value.map(f64::to_bits))
670 .collect()
671 }
672
673 #[test]
674 fn test_array_union_sliced_lists() -> Result<()> {
675 let (l, r, field) = make_sliced_pair();
676
677 let result = ArrayUnion::new().invoke_with_args(ScalarFunctionArgs {
678 args: vec![
679 ColumnarValue::Array(Arc::new(l)),
680 ColumnarValue::Array(Arc::new(r)),
681 ],
682 arg_fields: vec![Arc::clone(&field), Arc::clone(&field)],
683 number_rows: 2,
684 return_field: Arc::clone(&field),
685 config_options: Arc::new(ConfigOptions::default()),
686 })?;
687
688 let output = result.into_array(2)?;
689 let output = output.as_list::<i32>();
690 let rows = collect_i32_list(output);
691
692 assert_eq!(rows[0], vec![3, 4, 5]);
694 assert_eq!(rows[1], vec![5, 6, 7]);
696 Ok(())
697 }
698
699 #[test]
700 fn test_array_intersect_sliced_lists() -> Result<()> {
701 let (l, r, field) = make_sliced_pair();
702
703 let result = ArrayIntersect::new().invoke_with_args(ScalarFunctionArgs {
704 args: vec![
705 ColumnarValue::Array(Arc::new(l)),
706 ColumnarValue::Array(Arc::new(r)),
707 ],
708 arg_fields: vec![Arc::clone(&field), Arc::clone(&field)],
709 number_rows: 2,
710 return_field: Arc::clone(&field),
711 config_options: Arc::new(ConfigOptions::default()),
712 })?;
713
714 let output = result.into_array(2)?;
715 let output = output.as_list::<i32>();
716 let rows = collect_i32_list(output);
717
718 assert_eq!(rows[0], vec![3]);
720 assert_eq!(rows[1], vec![5]);
722 Ok(())
723 }
724
725 #[test]
726 fn test_array_distinct_sliced_list() -> Result<()> {
727 let list = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
729 Some(vec![Some(1), Some(1)]),
730 Some(vec![Some(3), Some(3), Some(4)]),
731 Some(vec![Some(5), Some(5), Some(6)]),
732 Some(vec![Some(7), Some(7)]),
733 ]);
734 let sliced = list.slice(1, 2);
735 let field = Arc::new(Field::new("item", sliced.data_type().clone(), true));
736
737 let result = ArrayDistinct::new().invoke_with_args(ScalarFunctionArgs {
738 args: vec![ColumnarValue::Array(Arc::new(sliced))],
739 arg_fields: vec![Arc::clone(&field)],
740 number_rows: 2,
741 return_field: field,
742 config_options: Arc::new(ConfigOptions::default()),
743 })?;
744
745 let output = result.into_array(2)?;
746 let output = output.as_list::<i32>();
747 let rows = collect_i32_list(output);
748
749 assert_eq!(rows[0], vec![3, 4]);
751 assert_eq!(rows[1], vec![5, 6]);
753 Ok(())
754 }
755
756 #[test]
757 fn test_sliced_float_set_ops_preserve_semantics() -> Result<()> {
758 let nan = f64::from_bits(0x7ff8_0000_0000_0042);
759 let l = ListArray::from_iter_primitive::<Float64Type, _, _>(vec![
760 Some(vec![Some(99.0)]),
761 Some(vec![
762 Some(-0.0),
763 Some(0.0),
764 Some(1.0),
765 Some(nan),
766 Some(nan),
767 None,
768 None,
769 ]),
770 None,
771 Some(vec![Some(-99.0)]),
772 ])
773 .slice(1, 2);
774 let r = ListArray::from_iter_primitive::<Float64Type, _, _>(vec![
775 Some(vec![Some(98.0)]),
776 Some(vec![Some(0.0), Some(2.0), Some(nan), None]),
777 Some(vec![Some(1.0)]),
778 Some(vec![Some(-98.0)]),
779 ])
780 .slice(1, 2);
781 let distinct = general_array_distinct::<i32>(&l, l.value_field())?;
782 let distinct = distinct.as_list::<i32>();
783 assert_eq!(
784 collect_f64_bits(distinct, 0),
785 vec![
786 Some(0.0_f64.to_bits()),
787 Some(1.0_f64.to_bits()),
788 Some(nan.to_bits()),
789 None,
790 ]
791 );
792 assert!(distinct.is_null(1));
793
794 let union = generic_set_lists::<i32>(&l, &r, SetOp::Union)?;
795 let union = union.as_list::<i32>();
796 assert_eq!(
797 collect_f64_bits(union, 0),
798 vec![
799 Some(0.0_f64.to_bits()),
800 Some(1.0_f64.to_bits()),
801 Some(nan.to_bits()),
802 None,
803 Some(2.0_f64.to_bits()),
804 ]
805 );
806 assert!(union.is_null(1));
807
808 let intersect = generic_set_lists::<i32>(&l, &r, SetOp::Intersect)?;
809 let intersect = intersect.as_list::<i32>();
810 assert_eq!(
811 collect_f64_bits(intersect, 0),
812 vec![Some(0.0_f64.to_bits()), Some(nan.to_bits()), None]
813 );
814 assert!(intersect.is_null(1));
815 Ok(())
816 }
817
818 #[test]
819 fn test_array_distinct_sliced_float_large_list() -> Result<()> {
820 let list = LargeListArray::from_iter_primitive::<Float64Type, _, _>(vec![
821 Some(vec![Some(99.0)]),
822 Some(vec![Some(-0.0), Some(0.0), Some(1.0), None, None]),
823 Some(vec![Some(-99.0)]),
824 ]);
825 let sliced = list.slice(1, 1);
826 let result = general_array_distinct::<i64>(&sliced, sliced.value_field())?;
827 let result = result.as_list::<i64>();
828 assert_eq!(
829 collect_f64_bits(result, 0),
830 vec![Some(0.0_f64.to_bits()), Some(1.0_f64.to_bits()), None]
831 );
832 Ok(())
833 }
834
835 #[test]
836 fn test_array_distinct_sliced_empty_float_list() -> Result<()> {
837 let list = ListArray::from_iter_primitive::<Float64Type, _, _>(vec![
838 Some(vec![Some(-0.0), Some(99.0)]),
839 Some(Vec::<Option<f64>>::new()),
840 Some(vec![Some(-0.0), Some(0.0)]),
841 ]);
842 let sliced = list.slice(1, 1);
843 let result = general_array_distinct::<i32>(&sliced, sliced.value_field())?;
844 let result = result.as_list::<i32>();
845 assert_eq!(result.len(), 1);
846 assert_eq!(result.value_length(0), 0);
847 Ok(())
848 }
849
850 #[test]
851 fn test_array_distinct_inner_nullability_result_type_match_return_type()
852 -> Result<(), DataFusionError> {
853 let udf = array_distinct_udf();
854
855 for inner_nullable in [true, false] {
856 let inner_field = Field::new_list_field(DataType::Int32, inner_nullable);
857 let input_field =
858 Field::new_list("input", Arc::new(inner_field.clone()), true);
859
860 let input_array = ListArray::new(
862 inner_field.into(),
863 OffsetBuffer::new(vec![0, 3].into()),
864 Arc::new(Int32Array::new(vec![1, 1, 2].into(), None)),
865 None,
866 );
867
868 let input_array = ColumnarValue::Array(Arc::new(input_array));
869
870 let result = udf.invoke_with_args(ScalarFunctionArgs {
871 args: vec![input_array],
872 arg_fields: vec![input_field.clone().into()],
873 number_rows: 1,
874 return_field: input_field.clone().into(),
875 config_options: Arc::new(ConfigOptions::default()),
876 })?;
877
878 assert_eq!(
879 result.data_type(),
880 udf.return_type(&[input_field.data_type().clone()])?
881 );
882 }
883 Ok(())
884 }
885}