1use crate::utils;
8use arrow::array::{
9 Array, ArrayRef, Capacities, GenericListArray, MutableArrayData, NullBufferBuilder,
10 OffsetSizeTrait, Scalar, cast::AsArray, make_array, new_null_array,
11};
12use arrow::buffer::OffsetBuffer;
13use arrow::datatypes::{DataType, FieldRef};
14use datafusion_common::cast::as_int64_array;
15use datafusion_common::utils::{ListCoercion, offset_span, offset_span_len};
16use datafusion_common::{
17 Result, ScalarValue, exec_err, internal_err, utils::take_function_args,
18};
19use datafusion_expr::{
20 ArrayFunctionArgument, ArrayFunctionSignature, ColumnarValue, Documentation,
21 ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature, Volatility,
22};
23use datafusion_macros::user_doc;
24use std::sync::Arc;
25
26make_udf_expr_and_func!(
27 ArrayRemove,
28 array_remove,
29 array element,
30 "removes the first element from the array equal to the given value. NULL elements already in the array are preserved when removing a non-NULL value. If `element` evaluates to NULL, the result is NULL rather than removing NULL entries.",
31 array_remove_udf
32);
33
34#[user_doc(
35 doc_section(label = "Array Functions"),
36 description = "Removes the first element from the array equal to the given value. NULL elements already in the array are preserved when removing a non-NULL value. If `element` evaluates to NULL, the result is NULL rather than removing NULL entries.",
37 syntax_example = "array_remove(array, element)",
38 sql_example = r#"```sql
39> select array_remove([1, 2, 2, 3, 2, 1, 4], 2);
40+----------------------------------------------+
41| array_remove(List([1,2,2,3,2,1,4]),Int64(2)) |
42+----------------------------------------------+
43| [1, 2, 3, 2, 1, 4] |
44+----------------------------------------------+
45
46> select array_remove([1, 2, NULL, 2, 4], 2);
47+---------------------------------------------+
48| array_remove(List([1,2,NULL,2,4]),Int64(2)) |
49+---------------------------------------------+
50| [1, NULL, 2, 4] |
51+---------------------------------------------+
52```"#,
53 argument(
54 name = "array",
55 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
56 ),
57 argument(
58 name = "element",
59 description = "Element to be removed from the array."
60 )
61)]
62#[derive(Debug, PartialEq, Eq, Hash)]
63pub struct ArrayRemove {
64 signature: Signature,
65 aliases: Vec<String>,
66}
67
68impl Default for ArrayRemove {
69 fn default() -> Self {
70 Self::new()
71 }
72}
73
74impl ArrayRemove {
75 pub fn new() -> Self {
76 Self {
77 signature: Signature::array_and_element(Volatility::Immutable),
78 aliases: vec!["list_remove".to_string()],
79 }
80 }
81}
82
83impl ScalarUDFImpl for ArrayRemove {
84 fn name(&self) -> &str {
85 "array_remove"
86 }
87
88 fn signature(&self) -> &Signature {
89 &self.signature
90 }
91
92 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
93 internal_err!("return_field_from_args should be used instead")
94 }
95
96 fn return_field_from_args(
97 &self,
98 args: datafusion_expr::ReturnFieldArgs,
99 ) -> Result<FieldRef> {
100 let array_field = args.arg_fields[0].as_ref().clone();
101 let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
102 Ok(Arc::new(array_field.with_nullable(nullable)))
103 }
104
105 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
106 let [list_arg, element_arg] = take_function_args(self.name(), &args.args)?;
107 let num_rows = args.number_rows;
108 let list_array = list_arg.to_array(num_rows)?;
109 match element_arg {
110 ColumnarValue::Scalar(scalar_element)
111 if !scalar_element.is_null()
112 && !scalar_element.data_type().is_nested() =>
113 {
114 let result =
115 array_remove_with_scalar_args(&list_array, scalar_element, 1i64)?;
116 Ok(ColumnarValue::Array(result))
117 }
118 element_arg => {
119 let element_array = element_arg.to_array(num_rows)?;
120 let result =
121 array_remove_internal(&list_array, &element_array, &[Some(1)])?;
122 Ok(ColumnarValue::Array(result))
123 }
124 }
125 }
126
127 fn aliases(&self) -> &[String] {
128 &self.aliases
129 }
130
131 fn documentation(&self) -> Option<&Documentation> {
132 self.doc()
133 }
134}
135
136make_udf_expr_and_func!(
137 ArrayRemoveN,
138 array_remove_n,
139 array element max,
140 "removes the first `max` elements from the array equal to the given value. NULL elements already in the array are preserved when removing a non-NULL value. If `element` evaluates to NULL, the result is NULL rather than removing NULL entries.",
141 array_remove_n_udf
142);
143
144#[user_doc(
145 doc_section(label = "Array Functions"),
146 description = "Removes the first `max` elements from the array equal to the given value. NULL elements already in the array are preserved when removing a non-NULL value. If `element` evaluates to NULL, the result is NULL rather than removing NULL entries.",
147 syntax_example = "array_remove_n(array, element, max)",
148 sql_example = r#"```sql
149> select array_remove_n([1, 2, 2, 3, 2, 1, 4], 2, 2);
150+---------------------------------------------------------+
151| array_remove_n(List([1,2,2,3,2,1,4]),Int64(2),Int64(2)) |
152+---------------------------------------------------------+
153| [1, 3, 2, 1, 4] |
154+---------------------------------------------------------+
155
156> select array_remove_n([1, 2, NULL, 2, 4], 2, 2);
157+--------------------------------------------------------+
158| array_remove_n(List([1,2,NULL,2,4]),Int64(2),Int64(2)) |
159+--------------------------------------------------------+
160| [1, NULL, 4] |
161+--------------------------------------------------------+
162```"#,
163 argument(
164 name = "array",
165 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
166 ),
167 argument(
168 name = "element",
169 description = "Element to be removed from the array."
170 ),
171 argument(name = "max", description = "Number of first occurrences to remove.")
172)]
173#[derive(Debug, PartialEq, Eq, Hash)]
174pub struct ArrayRemoveN {
175 signature: Signature,
176 aliases: Vec<String>,
177}
178
179impl Default for ArrayRemoveN {
180 fn default() -> Self {
181 Self::new()
182 }
183}
184
185impl ArrayRemoveN {
186 pub fn new() -> Self {
187 Self {
188 signature: Signature::new(
189 TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
190 arguments: vec![
191 ArrayFunctionArgument::Array,
192 ArrayFunctionArgument::Element,
193 ArrayFunctionArgument::Index,
194 ],
195 array_coercion: Some(ListCoercion::FixedSizedListToList),
196 }),
197 Volatility::Immutable,
198 ),
199 aliases: vec!["list_remove_n".to_string()],
200 }
201 }
202}
203
204impl ScalarUDFImpl for ArrayRemoveN {
205 fn name(&self) -> &str {
206 "array_remove_n"
207 }
208
209 fn signature(&self) -> &Signature {
210 &self.signature
211 }
212
213 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
214 internal_err!("return_field_from_args should be used instead")
215 }
216
217 fn return_field_from_args(
218 &self,
219 args: datafusion_expr::ReturnFieldArgs,
220 ) -> Result<FieldRef> {
221 let array_field = args.arg_fields[0].as_ref().clone();
222 let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
223 Ok(Arc::new(array_field.with_nullable(nullable)))
224 }
225
226 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
227 let [list_arg, element_arg, max_arg] =
228 take_function_args(self.name(), &args.args)?;
229 let num_rows = args.number_rows;
230 let list_array = list_arg.to_array(num_rows)?;
231 match (element_arg, max_arg) {
232 (
233 ColumnarValue::Scalar(scalar_element),
234 ColumnarValue::Scalar(scalar_max),
235 ) if !scalar_element.is_null() && !scalar_element.data_type().is_nested() => {
236 let ScalarValue::Int64(Some(n)) = scalar_max else {
237 return Ok(ColumnarValue::Array(new_null_array(
238 list_array.data_type(),
239 num_rows,
240 )));
241 };
242 let result =
243 array_remove_with_scalar_args(&list_array, scalar_element, *n)?;
244 Ok(ColumnarValue::Array(result))
245 }
246 (element_arg, max_arg) => {
247 let element_array = element_arg.to_array(num_rows)?;
248 let max_array = max_arg.to_array(num_rows)?;
249 let arr_n = as_int64_array(&max_array)?.iter().collect::<Vec<_>>();
250 let result = array_remove_internal(&list_array, &element_array, &arr_n)?;
251 Ok(ColumnarValue::Array(result))
252 }
253 }
254 }
255
256 fn aliases(&self) -> &[String] {
257 &self.aliases
258 }
259
260 fn documentation(&self) -> Option<&Documentation> {
261 self.doc()
262 }
263}
264
265make_udf_expr_and_func!(
266 ArrayRemoveAll,
267 array_remove_all,
268 array element,
269 "removes all elements from the array equal to the given value. NULL elements already in the array are preserved when removing a non-NULL value. If `element` evaluates to NULL, the result is NULL rather than removing NULL entries.",
270 array_remove_all_udf
271);
272
273#[user_doc(
274 doc_section(label = "Array Functions"),
275 description = "Removes all elements from the array equal to the given value. NULL elements already in the array are preserved when removing a non-NULL value. If `element` evaluates to NULL, the result is NULL rather than removing NULL entries.",
276 syntax_example = "array_remove_all(array, element)",
277 sql_example = r#"```sql
278> select array_remove_all([1, 2, 2, 3, 2, 1, 4], 2);
279+--------------------------------------------------+
280| array_remove_all(List([1,2,2,3,2,1,4]),Int64(2)) |
281+--------------------------------------------------+
282| [1, 3, 1, 4] |
283+--------------------------------------------------+
284
285> select array_remove_all([1, 2, NULL, 2, 4], 2);
286+-------------------------------------------------+
287| array_remove_all(List([1,2,NULL,2,4]),Int64(2)) |
288+-------------------------------------------------+
289| [1, NULL, 4] |
290+-------------------------------------------------+
291```"#,
292 argument(
293 name = "array",
294 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
295 ),
296 argument(
297 name = "element",
298 description = "Element to be removed from the array."
299 )
300)]
301#[derive(Debug, PartialEq, Eq, Hash)]
302pub struct ArrayRemoveAll {
303 signature: Signature,
304 aliases: Vec<String>,
305}
306
307impl Default for ArrayRemoveAll {
308 fn default() -> Self {
309 Self::new()
310 }
311}
312
313impl ArrayRemoveAll {
314 pub fn new() -> Self {
315 Self {
316 signature: Signature::array_and_element(Volatility::Immutable),
317 aliases: vec!["list_remove_all".to_string()],
318 }
319 }
320}
321
322impl ScalarUDFImpl for ArrayRemoveAll {
323 fn name(&self) -> &str {
324 "array_remove_all"
325 }
326
327 fn signature(&self) -> &Signature {
328 &self.signature
329 }
330
331 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
332 internal_err!("return_field_from_args should be used instead")
333 }
334
335 fn return_field_from_args(
336 &self,
337 args: datafusion_expr::ReturnFieldArgs,
338 ) -> Result<FieldRef> {
339 let array_field = args.arg_fields[0].as_ref().clone();
340 let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
341 Ok(Arc::new(array_field.with_nullable(nullable)))
342 }
343
344 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
345 let [list_arg, element_arg] = take_function_args(self.name(), &args.args)?;
346 let num_rows = args.number_rows;
347 let list_array = list_arg.to_array(num_rows)?;
348 match element_arg {
349 ColumnarValue::Scalar(scalar_element)
350 if !scalar_element.is_null()
351 && !scalar_element.data_type().is_nested() =>
352 {
353 let result =
354 array_remove_with_scalar_args(&list_array, scalar_element, i64::MAX)?;
355 Ok(ColumnarValue::Array(result))
356 }
357 element_arg => {
358 let element_array = element_arg.to_array(num_rows)?;
359 let result = array_remove_internal(
360 &list_array,
361 &element_array,
362 &[Some(i64::MAX)],
363 )?;
364 Ok(ColumnarValue::Array(result))
365 }
366 }
367 }
368
369 fn aliases(&self) -> &[String] {
370 &self.aliases
371 }
372
373 fn documentation(&self) -> Option<&Documentation> {
374 self.doc()
375 }
376}
377
378fn array_remove_internal(
379 array: &ArrayRef,
380 element_array: &ArrayRef,
381 arr_n: &[Option<i64>],
382) -> Result<ArrayRef> {
383 match array.data_type() {
384 DataType::List(_) => {
385 let list_array = array.as_list::<i32>();
386 general_remove::<i32>(list_array, element_array, arr_n)
387 }
388 DataType::LargeList(_) => {
389 let list_array = array.as_list::<i64>();
390 general_remove::<i64>(list_array, element_array, arr_n)
391 }
392 DataType::Null => Ok(new_null_array(array.data_type(), array.len())),
393 array_type => {
394 exec_err!("array_remove_all does not support type '{array_type}'.")
395 }
396 }
397}
398
399fn array_remove_with_scalar_args(
402 array: &ArrayRef,
403 scalar_needle: &ScalarValue,
404 max_removals: i64,
405) -> Result<ArrayRef> {
406 match array.data_type() {
407 DataType::List(_) => {
408 let list_array = array.as_list::<i32>();
409 general_remove_with_scalar::<i32>(list_array, scalar_needle, max_removals)
410 }
411 DataType::LargeList(_) => {
412 let list_array = array.as_list::<i64>();
413 general_remove_with_scalar::<i64>(list_array, scalar_needle, max_removals)
414 }
415 DataType::Null => Ok(new_null_array(array.data_type(), array.len())),
416 array_type => exec_err!(
417 "array_remove/array_remove_n/array_remove_all does not support type '{array_type}'."
418 ),
419 }
420}
421
422fn general_remove<OffsetSize: OffsetSizeTrait>(
440 list_array: &GenericListArray<OffsetSize>,
441 element_array: &ArrayRef,
442 arr_n: &[Option<i64>],
443) -> Result<ArrayRef> {
444 let original_data = list_array.values().to_data();
445 let mut offsets = Vec::<OffsetSize>::with_capacity(list_array.len() + 1);
447 offsets.push(OffsetSize::zero());
448
449 let mut mutable = MutableArrayData::with_capacities(
450 vec![&original_data],
451 false,
452 Capacities::Array(offset_span_len(list_array.offsets())),
453 );
454 let mut valid = NullBufferBuilder::new(list_array.len());
455
456 for (row_index, offset_window) in list_array.offsets().windows(2).enumerate() {
457 if list_array.is_null(row_index) || element_array.is_null(row_index) {
458 offsets.push(offsets[row_index]);
459 valid.append_null();
460 continue;
461 }
462
463 let n = if arr_n.len() == 1 {
464 arr_n[0]
465 } else {
466 arr_n[row_index]
467 };
468 let Some(n) = n else {
469 offsets.push(offsets[row_index]);
470 valid.append_null();
471 continue;
472 };
473
474 let start = offset_window[0].to_usize().unwrap();
475 let end = offset_window[1].to_usize().unwrap();
476
477 let eq_array = utils::compare_element_to_list(
479 &list_array.value(row_index),
480 element_array,
481 row_index,
482 false,
483 )?;
484
485 let num_to_remove = eq_array.false_count();
486
487 if num_to_remove == 0 {
489 mutable.try_extend(0, start, end)?;
490 offsets.push(offsets[row_index] + OffsetSize::usize_as(end - start));
491 valid.append_non_null();
492 continue;
493 }
494
495 let max_removals = n.min(num_to_remove as i64);
497 let mut removed = 0i64;
498 let mut copied = 0usize;
499 let mut pending_batch_to_retain: Option<usize> = None;
501 for (i, keep) in eq_array.iter().enumerate() {
502 if keep == Some(false) && removed < max_removals {
503 if let Some(bs) = pending_batch_to_retain {
505 mutable.try_extend(0, start + bs, start + i)?;
506 copied += i - bs;
507 pending_batch_to_retain = None;
508 }
509 removed += 1;
510 } else if pending_batch_to_retain.is_none() {
511 pending_batch_to_retain = Some(i);
512 }
513 }
514
515 if let Some(bs) = pending_batch_to_retain {
517 mutable.try_extend(0, start + bs, start + eq_array.len())?;
518 copied += eq_array.len() - bs;
519 }
520
521 offsets.push(offsets[row_index] + OffsetSize::usize_as(copied));
522 valid.append_non_null();
523 }
524
525 let new_values = make_array(mutable.freeze());
526 Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
527 Arc::clone(list_array.value_field()),
528 OffsetBuffer::new(offsets.into()),
529 new_values,
530 valid.finish(),
531 )?))
532}
533
534fn general_remove_with_scalar<OffsetSize: OffsetSizeTrait>(
540 list_array: &GenericListArray<OffsetSize>,
541 scalar_needle: &ScalarValue,
542 max_removals: i64,
543) -> Result<ArrayRef> {
544 if max_removals <= 0 {
545 return Ok(Arc::new(list_array.clone()));
546 }
547
548 let list_offsets = list_array.offsets();
549 let (first_offset, values_range_len) = offset_span(list_offsets);
550 let values_slice = list_array.values().slice(first_offset, values_range_len);
551 let original_data = values_slice.to_data();
552 let mut offsets = Vec::<OffsetSize>::with_capacity(list_array.len() + 1);
553 offsets.push(OffsetSize::zero());
554
555 let mut mutable = MutableArrayData::with_capacities(
556 vec![&original_data],
557 false,
558 Capacities::Array(original_data.len()),
559 );
560 let nulls = list_array.nulls().cloned();
561 let needle = scalar_needle.to_array_of_size(1)?;
562 let remove_mask = arrow_ord::cmp::not_distinct(&values_slice, &Scalar::new(needle))?;
563 let remove_bits = remove_mask.values();
564
565 for (row_index, offset_window) in list_offsets.windows(2).enumerate() {
566 if nulls.as_ref().is_some_and(|nulls| nulls.is_null(row_index)) {
567 offsets.push(offsets[row_index]);
568 continue;
569 }
570
571 let start = offset_window[0].to_usize().unwrap() - first_offset;
572 let end = offset_window[1].to_usize().unwrap() - first_offset;
573 let row_len = end - start;
574
575 let row_remove_bits = remove_bits.slice(start, row_len);
576 let num_to_remove = row_remove_bits.count_set_bits();
577
578 if num_to_remove == 0 {
579 mutable.try_extend(0, start, end)?;
580 offsets.push(offsets[row_index] + OffsetSize::usize_as(row_len));
581 continue;
582 }
583
584 let removals_to_apply = max_removals.min(num_to_remove as i64) as usize;
585
586 let mut removed = 0usize;
590 let mut copied = 0usize;
591 let mut prev_end = start;
592 for remove_pos in row_remove_bits.set_indices() {
593 let abs_pos = start + remove_pos;
594 if abs_pos > prev_end {
595 mutable.try_extend(0, prev_end, abs_pos)?;
596 copied += abs_pos - prev_end;
597 }
598 prev_end = abs_pos + 1;
599 removed += 1;
600 if removed == removals_to_apply {
601 break;
602 }
603 }
604 if prev_end < end {
606 mutable.try_extend(0, prev_end, end)?;
607 copied += end - prev_end;
608 }
609
610 offsets.push(offsets[row_index] + OffsetSize::usize_as(copied));
611 }
612
613 let new_values = make_array(mutable.freeze());
614 Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
615 Arc::clone(list_array.value_field()),
616 OffsetBuffer::new(offsets.into()),
617 new_values,
618 nulls,
619 )?))
620}
621
622#[cfg(test)]
623mod tests {
624 use crate::remove::{ArrayRemove, ArrayRemoveAll, ArrayRemoveN};
625 use arrow::array::{
626 Array, ArrayRef, AsArray, GenericListArray, Int32Array, Int64Array, ListArray,
627 OffsetSizeTrait,
628 };
629 use arrow::buffer::{NullBuffer, ScalarBuffer};
630 use arrow::datatypes::{DataType, Field, Int32Type};
631 use datafusion_common::ScalarValue;
632 use datafusion_expr::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl};
633 use datafusion_expr_common::columnar_value::ColumnarValue;
634 use std::ops::Deref;
635 use std::sync::Arc;
636
637 #[test]
638 fn test_array_remove_nullability() {
639 for nullability in [true, false] {
640 for item_nullability in [true, false] {
641 for element_nullability in [true, false] {
642 let input_field = Arc::new(Field::new(
643 "num",
644 DataType::new_list(DataType::Int32, item_nullability),
645 nullability,
646 ));
647 let args_fields = vec![
648 Arc::clone(&input_field),
649 Arc::new(Field::new("a", DataType::Int32, element_nullability)),
650 ];
651 let scalar_args = vec![None, Some(&ScalarValue::Int32(Some(1)))];
652
653 let result = ArrayRemove::new()
654 .return_field_from_args(ReturnFieldArgs {
655 arg_fields: &args_fields,
656 scalar_arguments: &scalar_args,
657 })
658 .unwrap();
659
660 let expected = Arc::new(
661 input_field
662 .as_ref()
663 .clone()
664 .with_nullable(nullability || element_nullability),
665 );
666
667 assert_eq!(result, expected);
668 }
669 }
670 }
671 }
672
673 #[test]
674 fn test_array_remove_n_nullability() {
675 for nullability in [true, false] {
676 for item_nullability in [true, false] {
677 for element_nullability in [true, false] {
678 for count_nullability in [true, false] {
679 let input_field = Arc::new(Field::new(
680 "num",
681 DataType::new_list(DataType::Int32, item_nullability),
682 nullability,
683 ));
684 let args_fields = vec![
685 Arc::clone(&input_field),
686 Arc::new(Field::new(
687 "a",
688 DataType::Int32,
689 element_nullability,
690 )),
691 Arc::new(Field::new("b", DataType::Int64, count_nullability)),
692 ];
693 let scalar_args = vec![
694 None,
695 Some(&ScalarValue::Int32(Some(1))),
696 Some(&ScalarValue::Int64(Some(1))),
697 ];
698
699 let result = ArrayRemoveN::new()
700 .return_field_from_args(ReturnFieldArgs {
701 arg_fields: &args_fields,
702 scalar_arguments: &scalar_args,
703 })
704 .unwrap();
705
706 let expected_nullable =
707 nullability || element_nullability || count_nullability;
708 let expected = Arc::new(
709 input_field
710 .as_ref()
711 .clone()
712 .with_nullable(expected_nullable),
713 );
714
715 assert_eq!(result, expected);
716 }
717 }
718 }
719 }
720 }
721
722 #[test]
723 fn test_array_remove_all_nullability() {
724 for nullability in [true, false] {
725 for item_nullability in [true, false] {
726 for element_nullability in [true, false] {
727 let input_field = Arc::new(Field::new(
728 "num",
729 DataType::new_list(DataType::Int32, item_nullability),
730 nullability,
731 ));
732 let args_fields = vec![
733 Arc::clone(&input_field),
734 Arc::new(Field::new("a", DataType::Int32, element_nullability)),
735 ];
736 let scalar_args = vec![None, Some(&ScalarValue::Int32(Some(1)))];
737 let result = ArrayRemoveAll::new()
738 .return_field_from_args(ReturnFieldArgs {
739 arg_fields: &args_fields,
740 scalar_arguments: &scalar_args,
741 })
742 .unwrap();
743
744 let expected = Arc::new(
745 input_field
746 .as_ref()
747 .clone()
748 .with_nullable(nullability || element_nullability),
749 );
750
751 assert_eq!(result, expected);
752 }
753 }
754 }
755 }
756
757 fn ensure_field_nullability<O: OffsetSizeTrait>(
758 field_nullable: bool,
759 list: GenericListArray<O>,
760 ) -> GenericListArray<O> {
761 let (field, offsets, values, nulls) = list.into_parts();
762
763 if field.is_nullable() == field_nullable {
764 return GenericListArray::new(field, offsets, values, nulls);
765 }
766 if !field_nullable {
767 assert_eq!(nulls, None);
768 }
769
770 let field = Arc::new(field.deref().clone().with_nullable(field_nullable));
771
772 GenericListArray::new(field, offsets, values, nulls)
773 }
774
775 #[test]
776 fn test_array_remove_non_nullable() {
777 let input_list = Arc::new(ensure_field_nullability(
778 false,
779 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
780 Some(([1, 2, 2, 3, 2, 1, 4]).iter().copied().map(Some)),
781 Some(([42, 2, 55, 63, 2]).iter().copied().map(Some)),
782 ]),
783 ));
784 let expected_list = ensure_field_nullability(
785 false,
786 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
787 Some(([1, 2, 3, 2, 1, 4]).iter().copied().map(Some)),
788 Some(([42, 55, 63, 2]).iter().copied().map(Some)),
789 ]),
790 );
791
792 let element_to_remove = ScalarValue::Int32(Some(2));
793
794 assert_array_remove(input_list, expected_list, element_to_remove);
795 }
796
797 #[test]
798 fn test_array_remove_nullable() {
799 let input_list = Arc::new(ensure_field_nullability(
800 true,
801 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
802 Some(vec![
803 Some(1),
804 Some(2),
805 Some(2),
806 Some(3),
807 None,
808 Some(1),
809 Some(4),
810 ]),
811 Some(vec![Some(42), Some(2), None, Some(63), Some(2)]),
812 ]),
813 ));
814 let expected_list = ensure_field_nullability(
815 true,
816 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
817 Some(vec![Some(1), Some(2), Some(3), None, Some(1), Some(4)]),
818 Some(vec![Some(42), None, Some(63), Some(2)]),
819 ]),
820 );
821
822 let element_to_remove = ScalarValue::Int32(Some(2));
823
824 assert_array_remove(input_list, expected_list, element_to_remove);
825 }
826
827 fn assert_array_remove(
828 input_list: ArrayRef,
829 expected_list: GenericListArray<i32>,
830 element_to_remove: ScalarValue,
831 ) {
832 assert_eq!(input_list.data_type(), expected_list.data_type());
833 assert_eq!(expected_list.value_type(), element_to_remove.data_type());
834 let input_list_len = input_list.len();
835 let input_list_data_type = input_list.data_type().clone();
836
837 let udf = ArrayRemove::new();
838 let args_fields = vec![
839 Arc::new(Field::new("num", input_list.data_type().clone(), false)),
840 Arc::new(Field::new(
841 "el",
842 element_to_remove.data_type(),
843 element_to_remove.is_null(),
844 )),
845 ];
846 let scalar_args = vec![None, Some(&element_to_remove)];
847
848 let return_field = udf
849 .return_field_from_args(ReturnFieldArgs {
850 arg_fields: &args_fields,
851 scalar_arguments: &scalar_args,
852 })
853 .unwrap();
854
855 let result = udf
856 .invoke_with_args(ScalarFunctionArgs {
857 args: vec![
858 ColumnarValue::Array(input_list),
859 ColumnarValue::Scalar(element_to_remove),
860 ],
861 arg_fields: args_fields,
862 number_rows: input_list_len,
863 return_field,
864 config_options: Arc::new(Default::default()),
865 })
866 .unwrap();
867
868 assert_eq!(result.data_type(), input_list_data_type);
869 match result {
870 ColumnarValue::Array(array) => {
871 let result_list = array.as_list::<i32>();
872 assert_eq!(result_list, &expected_list);
873 }
874 _ => panic!("Expected ColumnarValue::Array"),
875 }
876 }
877
878 #[test]
879 fn test_array_remove_n_non_nullable() {
880 let input_list = Arc::new(ensure_field_nullability(
881 false,
882 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
883 Some(([1, 2, 2, 3, 2, 1, 4]).iter().copied().map(Some)),
884 Some(([42, 2, 55, 63, 2]).iter().copied().map(Some)),
885 ]),
886 ));
887 let expected_list = ensure_field_nullability(
888 false,
889 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
890 Some(([1, 3, 2, 1, 4]).iter().copied().map(Some)),
891 Some(([42, 55, 63]).iter().copied().map(Some)),
892 ]),
893 );
894
895 let element_to_remove = ScalarValue::Int32(Some(2));
896
897 assert_array_remove_n(input_list, expected_list, element_to_remove, 2);
898 }
899
900 #[test]
901 fn test_array_remove_n_nullable() {
902 let input_list = Arc::new(ensure_field_nullability(
903 true,
904 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
905 Some(vec![
906 Some(1),
907 Some(2),
908 Some(2),
909 Some(3),
910 None,
911 Some(1),
912 Some(4),
913 ]),
914 Some(vec![Some(42), Some(2), None, Some(63), Some(2)]),
915 ]),
916 ));
917 let expected_list = ensure_field_nullability(
918 true,
919 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
920 Some(vec![Some(1), Some(3), None, Some(1), Some(4)]),
921 Some(vec![Some(42), None, Some(63)]),
922 ]),
923 );
924
925 let element_to_remove = ScalarValue::Int32(Some(2));
926
927 assert_array_remove_n(input_list, expected_list, element_to_remove, 2);
928 }
929
930 #[test]
931 fn test_array_remove_n_null_count_returns_null() {
932 let array: ArrayRef =
933 Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
934 Some(vec![Some(1), Some(2), Some(2)]),
935 Some(vec![Some(4), Some(2)]),
936 ]));
937 let element: ArrayRef = Arc::new(Int32Array::from(vec![2, 2]));
938 let max: ArrayRef = Arc::new(Int64Array::new(
939 ScalarBuffer::from(vec![1, 1]),
940 Some(NullBuffer::from(vec![true, false])),
941 ));
942
943 let udf = ArrayRemoveN::new();
944 let args_fields = vec![
945 Arc::new(Field::new("num", array.data_type().clone(), false)),
946 Arc::new(Field::new("el", DataType::Int32, false)),
947 Arc::new(Field::new("count", DataType::Int64, true)),
948 ];
949 let scalar_args = vec![None, None, None];
950 let return_field = udf
951 .return_field_from_args(ReturnFieldArgs {
952 arg_fields: &args_fields,
953 scalar_arguments: &scalar_args,
954 })
955 .unwrap();
956 let result = udf
957 .invoke_with_args(ScalarFunctionArgs {
958 args: vec![
959 ColumnarValue::Array(array),
960 ColumnarValue::Array(element),
961 ColumnarValue::Array(max),
962 ],
963 arg_fields: args_fields,
964 number_rows: 2,
965 return_field,
966 config_options: Arc::new(Default::default()),
967 })
968 .unwrap();
969 let expected = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
970 Some(vec![Some(1), Some(2)]),
971 None,
972 ]);
973
974 match result {
975 ColumnarValue::Array(array) => {
976 assert_eq!(array.as_list::<i32>(), &expected);
977 }
978 _ => panic!("Expected ColumnarValue::Array"),
979 }
980 }
981
982 fn assert_array_remove_n(
983 input_list: ArrayRef,
984 expected_list: GenericListArray<i32>,
985 element_to_remove: ScalarValue,
986 n: i64,
987 ) {
988 assert_eq!(input_list.data_type(), expected_list.data_type());
989 assert_eq!(expected_list.value_type(), element_to_remove.data_type());
990 let input_list_len = input_list.len();
991 let input_list_data_type = input_list.data_type().clone();
992
993 let count_scalar = ScalarValue::Int64(Some(n));
994
995 let udf = ArrayRemoveN::new();
996 let args_fields = vec![
997 Arc::new(Field::new("num", input_list.data_type().clone(), false)),
998 Arc::new(Field::new(
999 "el",
1000 element_to_remove.data_type(),
1001 element_to_remove.is_null(),
1002 )),
1003 Arc::new(Field::new("count", DataType::Int64, false)),
1004 ];
1005 let scalar_args = vec![None, Some(&element_to_remove), Some(&count_scalar)];
1006
1007 let return_field = udf
1008 .return_field_from_args(ReturnFieldArgs {
1009 arg_fields: &args_fields,
1010 scalar_arguments: &scalar_args,
1011 })
1012 .unwrap();
1013
1014 let result = udf
1015 .invoke_with_args(ScalarFunctionArgs {
1016 args: vec![
1017 ColumnarValue::Array(input_list),
1018 ColumnarValue::Scalar(element_to_remove),
1019 ColumnarValue::Scalar(count_scalar),
1020 ],
1021 arg_fields: args_fields,
1022 number_rows: input_list_len,
1023 return_field,
1024 config_options: Arc::new(Default::default()),
1025 })
1026 .unwrap();
1027
1028 assert_eq!(result.data_type(), input_list_data_type);
1029 match result {
1030 ColumnarValue::Array(array) => {
1031 let result_list = array.as_list::<i32>();
1032 assert_eq!(result_list, &expected_list);
1033 }
1034 _ => panic!("Expected ColumnarValue::Array"),
1035 }
1036 }
1037
1038 #[test]
1039 fn test_array_remove_all_non_nullable() {
1040 let input_list = Arc::new(ensure_field_nullability(
1041 false,
1042 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1043 Some(([1, 2, 2, 3, 2, 1, 4]).iter().copied().map(Some)),
1044 Some(([42, 2, 55, 63, 2]).iter().copied().map(Some)),
1045 ]),
1046 ));
1047 let expected_list = ensure_field_nullability(
1048 false,
1049 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1050 Some(([1, 3, 1, 4]).iter().copied().map(Some)),
1051 Some(([42, 55, 63]).iter().copied().map(Some)),
1052 ]),
1053 );
1054
1055 let element_to_remove = ScalarValue::Int32(Some(2));
1056
1057 assert_array_remove_all(input_list, expected_list, element_to_remove);
1058 }
1059
1060 #[test]
1061 fn test_array_remove_all_nullable() {
1062 let input_list = Arc::new(ensure_field_nullability(
1063 true,
1064 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1065 Some(vec![
1066 Some(1),
1067 Some(2),
1068 Some(2),
1069 Some(3),
1070 None,
1071 Some(1),
1072 Some(4),
1073 ]),
1074 Some(vec![Some(42), Some(2), None, Some(63), Some(2)]),
1075 ]),
1076 ));
1077 let expected_list = ensure_field_nullability(
1078 true,
1079 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1080 Some(vec![Some(1), Some(3), None, Some(1), Some(4)]),
1081 Some(vec![Some(42), None, Some(63)]),
1082 ]),
1083 );
1084
1085 let element_to_remove = ScalarValue::Int32(Some(2));
1086
1087 assert_array_remove_all(input_list, expected_list, element_to_remove);
1088 }
1089
1090 fn assert_array_remove_all(
1091 input_list: ArrayRef,
1092 expected_list: GenericListArray<i32>,
1093 element_to_remove: ScalarValue,
1094 ) {
1095 assert_eq!(input_list.data_type(), expected_list.data_type());
1096 assert_eq!(expected_list.value_type(), element_to_remove.data_type());
1097 let input_list_len = input_list.len();
1098 let input_list_data_type = input_list.data_type().clone();
1099
1100 let udf = ArrayRemoveAll::new();
1101 let args_fields = vec![
1102 Arc::new(Field::new("num", input_list.data_type().clone(), false)),
1103 Arc::new(Field::new(
1104 "el",
1105 element_to_remove.data_type(),
1106 element_to_remove.is_null(),
1107 )),
1108 ];
1109 let scalar_args = vec![None, Some(&element_to_remove)];
1110
1111 let return_field = udf
1112 .return_field_from_args(ReturnFieldArgs {
1113 arg_fields: &args_fields,
1114 scalar_arguments: &scalar_args,
1115 })
1116 .unwrap();
1117
1118 let result = udf
1119 .invoke_with_args(ScalarFunctionArgs {
1120 args: vec![
1121 ColumnarValue::Array(input_list),
1122 ColumnarValue::Scalar(element_to_remove),
1123 ],
1124 arg_fields: args_fields,
1125 number_rows: input_list_len,
1126 return_field,
1127 config_options: Arc::new(Default::default()),
1128 })
1129 .unwrap();
1130
1131 assert_eq!(result.data_type(), input_list_data_type);
1132 match result {
1133 ColumnarValue::Array(array) => {
1134 let result_list = array.as_list::<i32>();
1135 assert_eq!(result_list, &expected_list);
1136 }
1137 _ => panic!("Expected ColumnarValue::Array"),
1138 }
1139 }
1140
1141 #[test]
1142 fn test_sliced_capacity() -> datafusion_common::Result<()> {
1143 crate::utils::tests::check_sliced_list_behavior(|input| {
1144 let element: ArrayRef =
1145 Arc::new(arrow::array::Float64Array::from(vec![3.0; input.len()]));
1146 super::array_remove_internal(input, &element, &vec![Some(1); input.len()])
1147 })
1148 }
1149}