Skip to main content

datafusion_functions_nested/
replace.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`ScalarUDFImpl`] definitions for array_replace, array_replace_n and array_replace_all functions.
6
7use arrow::array::{
8    Array, ArrayRef, AsArray, Capacities, GenericListArray, MutableArrayData,
9    NullBufferBuilder, OffsetSizeTrait, Scalar, new_null_array,
10};
11use arrow::buffer::OffsetBuffer;
12use arrow::datatypes::{DataType, Field, FieldRef};
13use datafusion_common::cast::as_int64_array;
14use datafusion_common::utils::{ListCoercion, offset_span, offset_span_len};
15use datafusion_common::{
16    Result, ScalarValue, exec_err, internal_err, utils::take_function_args,
17};
18use datafusion_expr::{
19    ArrayFunctionArgument, ArrayFunctionSignature, ColumnarValue, Documentation,
20    ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature,
21    Volatility,
22};
23use datafusion_macros::user_doc;
24
25use crate::utils::{compare_element_to_list, list_inner_field, list_type_with_element};
26
27use std::sync::Arc;
28
29// Create static instances of ScalarUDFs for each function
30make_udf_expr_and_func!(ArrayReplace,
31    array_replace,
32    array from to,
33    "replaces the first occurrence of the specified element with another specified element.",
34    array_replace_udf
35);
36make_udf_expr_and_func!(ArrayReplaceN,
37    array_replace_n,
38    array from to max,
39    "replaces the first `max` occurrences of the specified element with another specified element.",
40    array_replace_n_udf
41);
42make_udf_expr_and_func!(ArrayReplaceAll,
43    array_replace_all,
44    array from to,
45    "replaces all occurrences of the specified element with another specified element.",
46    array_replace_all_udf
47);
48
49#[user_doc(
50    doc_section(label = "Array Functions"),
51    description = "Replaces the first occurrence of the specified element with another specified element.",
52    syntax_example = "array_replace(array, from, to)",
53    sql_example = r#"```sql
54> select array_replace([1, 2, 2, 3, 2, 1, 4], 2, 5);
55+--------------------------------------------------------+
56| array_replace(List([1,2,2,3,2,1,4]),Int64(2),Int64(5)) |
57+--------------------------------------------------------+
58| [1, 5, 2, 3, 2, 1, 4]                                  |
59+--------------------------------------------------------+
60```"#,
61    argument(
62        name = "array",
63        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
64    ),
65    argument(name = "from", description = "Initial element."),
66    argument(name = "to", description = "Final element.")
67)]
68#[derive(Debug, PartialEq, Eq, Hash)]
69pub struct ArrayReplace {
70    signature: Signature,
71    aliases: Vec<String>,
72}
73
74impl Default for ArrayReplace {
75    fn default() -> Self {
76        Self::new()
77    }
78}
79
80impl ArrayReplace {
81    pub fn new() -> Self {
82        Self {
83            signature: Signature {
84                type_signature: TypeSignature::ArraySignature(
85                    ArrayFunctionSignature::Array {
86                        arguments: vec![
87                            ArrayFunctionArgument::Array,
88                            ArrayFunctionArgument::Element,
89                            ArrayFunctionArgument::Element,
90                        ],
91                        array_coercion: Some(ListCoercion::FixedSizedListToList),
92                    },
93                ),
94                volatility: Volatility::Immutable,
95                parameter_names: None,
96            },
97            aliases: vec![String::from("list_replace")],
98        }
99    }
100}
101
102impl ScalarUDFImpl for ArrayReplace {
103    fn name(&self) -> &str {
104        "array_replace"
105    }
106
107    fn signature(&self) -> &Signature {
108        &self.signature
109    }
110
111    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
112        internal_err!("return_field_from_args should be used instead")
113    }
114
115    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
116        replace_return_field(self.name(), args.arg_fields)
117    }
118
119    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
120        let return_type = args.return_field.data_type().clone();
121        let [list_arg, from_arg, to_arg] = take_function_args(self.name(), &args.args)?;
122        let num_rows = args.number_rows;
123        let list_array = list_arg.to_array(num_rows)?;
124        match (from_arg, to_arg) {
125            (ColumnarValue::Scalar(scalar_from), ColumnarValue::Scalar(scalar_to)) => {
126                let result = array_replace_with_scalar_args(
127                    self.name(),
128                    &list_array,
129                    scalar_from,
130                    scalar_to,
131                    1i64,
132                    &return_type,
133                )?;
134                Ok(ColumnarValue::Array(result))
135            }
136            (from_arg, to_arg) => {
137                let from_array = from_arg.to_array(num_rows)?;
138                let to_array = to_arg.to_array(num_rows)?;
139                let result = array_replace_internal(
140                    self.name(),
141                    &list_array,
142                    &from_array,
143                    &to_array,
144                    &[Some(1)],
145                    &return_type,
146                )?;
147                Ok(ColumnarValue::Array(result))
148            }
149        }
150    }
151
152    fn aliases(&self) -> &[String] {
153        &self.aliases
154    }
155
156    fn documentation(&self) -> Option<&Documentation> {
157        self.doc()
158    }
159}
160
161#[user_doc(
162    doc_section(label = "Array Functions"),
163    description = "Replaces the first `max` occurrences of the specified element with another specified element.",
164    syntax_example = "array_replace_n(array, from, to, max)",
165    sql_example = r#"```sql
166> select array_replace_n([1, 2, 2, 3, 2, 1, 4], 2, 5, 2);
167+-------------------------------------------------------------------+
168| array_replace_n(List([1,2,2,3,2,1,4]),Int64(2),Int64(5),Int64(2)) |
169+-------------------------------------------------------------------+
170| [1, 5, 5, 3, 2, 1, 4]                                             |
171+-------------------------------------------------------------------+
172```"#,
173    argument(
174        name = "array",
175        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
176    ),
177    argument(name = "from", description = "Initial element."),
178    argument(name = "to", description = "Final element."),
179    argument(name = "max", description = "Number of first occurrences to replace.")
180)]
181#[derive(Debug, PartialEq, Eq, Hash)]
182pub(super) struct ArrayReplaceN {
183    signature: Signature,
184    aliases: Vec<String>,
185}
186
187impl ArrayReplaceN {
188    pub fn new() -> Self {
189        Self {
190            signature: Signature {
191                type_signature: TypeSignature::ArraySignature(
192                    ArrayFunctionSignature::Array {
193                        arguments: vec![
194                            ArrayFunctionArgument::Array,
195                            ArrayFunctionArgument::Element,
196                            ArrayFunctionArgument::Element,
197                            ArrayFunctionArgument::Index,
198                        ],
199                        array_coercion: Some(ListCoercion::FixedSizedListToList),
200                    },
201                ),
202                volatility: Volatility::Immutable,
203                parameter_names: None,
204            },
205            aliases: vec![String::from("list_replace_n")],
206        }
207    }
208}
209
210impl ScalarUDFImpl for ArrayReplaceN {
211    fn name(&self) -> &str {
212        "array_replace_n"
213    }
214
215    fn signature(&self) -> &Signature {
216        &self.signature
217    }
218
219    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
220        internal_err!("return_field_from_args should be used instead")
221    }
222
223    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
224        replace_return_field(self.name(), args.arg_fields)
225    }
226
227    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
228        let return_type = args.return_field.data_type().clone();
229        let [list_arg, from_arg, to_arg, max_arg] =
230            take_function_args(self.name(), &args.args)?;
231        let num_rows = args.number_rows;
232        let list_array = list_arg.to_array(num_rows)?;
233        match (from_arg, to_arg, max_arg) {
234            (
235                ColumnarValue::Scalar(scalar_from),
236                ColumnarValue::Scalar(scalar_to),
237                ColumnarValue::Scalar(scalar_max),
238            ) => {
239                let ScalarValue::Int64(Some(n)) = scalar_max else {
240                    return Ok(ColumnarValue::Array(new_null_array(
241                        &return_type,
242                        num_rows,
243                    )));
244                };
245                let result = array_replace_with_scalar_args(
246                    self.name(),
247                    &list_array,
248                    scalar_from,
249                    scalar_to,
250                    *n,
251                    &return_type,
252                )?;
253                Ok(ColumnarValue::Array(result))
254            }
255            (from_arg, to_arg, max_arg) => {
256                let from_array = from_arg.to_array(num_rows)?;
257                let to_array = to_arg.to_array(num_rows)?;
258                let max_array = max_arg.to_array(num_rows)?;
259                let result = array_replace_n_inner(
260                    self.name(),
261                    &list_array,
262                    &from_array,
263                    &to_array,
264                    &max_array,
265                    &return_type,
266                )?;
267                Ok(ColumnarValue::Array(result))
268            }
269        }
270    }
271
272    fn aliases(&self) -> &[String] {
273        &self.aliases
274    }
275
276    fn documentation(&self) -> Option<&Documentation> {
277        self.doc()
278    }
279}
280
281#[user_doc(
282    doc_section(label = "Array Functions"),
283    description = "Replaces all occurrences of the specified element with another specified element.",
284    syntax_example = "array_replace_all(array, from, to)",
285    sql_example = r#"```sql
286> select array_replace_all([1, 2, 2, 3, 2, 1, 4], 2, 5);
287+------------------------------------------------------------+
288| array_replace_all(List([1,2,2,3,2,1,4]),Int64(2),Int64(5)) |
289+------------------------------------------------------------+
290| [1, 5, 5, 3, 5, 1, 4]                                      |
291+------------------------------------------------------------+
292```"#,
293    argument(
294        name = "array",
295        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
296    ),
297    argument(name = "from", description = "Initial element."),
298    argument(name = "to", description = "Final element.")
299)]
300#[derive(Debug, PartialEq, Eq, Hash)]
301pub(super) struct ArrayReplaceAll {
302    signature: Signature,
303    aliases: Vec<String>,
304}
305
306impl ArrayReplaceAll {
307    pub fn new() -> Self {
308        Self {
309            signature: Signature {
310                type_signature: TypeSignature::ArraySignature(
311                    ArrayFunctionSignature::Array {
312                        arguments: vec![
313                            ArrayFunctionArgument::Array,
314                            ArrayFunctionArgument::Element,
315                            ArrayFunctionArgument::Element,
316                        ],
317                        array_coercion: Some(ListCoercion::FixedSizedListToList),
318                    },
319                ),
320                volatility: Volatility::Immutable,
321                parameter_names: None,
322            },
323            aliases: vec![String::from("list_replace_all")],
324        }
325    }
326}
327
328impl ScalarUDFImpl for ArrayReplaceAll {
329    fn name(&self) -> &str {
330        "array_replace_all"
331    }
332
333    fn signature(&self) -> &Signature {
334        &self.signature
335    }
336
337    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
338        internal_err!("return_field_from_args should be used instead")
339    }
340
341    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
342        replace_return_field(self.name(), args.arg_fields)
343    }
344
345    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
346        let return_type = args.return_field.data_type().clone();
347        let [list_arg, from_arg, to_arg] = take_function_args(self.name(), &args.args)?;
348        let num_rows = args.number_rows;
349        let list_array = list_arg.to_array(num_rows)?;
350        match (from_arg, to_arg) {
351            (ColumnarValue::Scalar(scalar_from), ColumnarValue::Scalar(scalar_to)) => {
352                let result = array_replace_with_scalar_args(
353                    self.name(),
354                    &list_array,
355                    scalar_from,
356                    scalar_to,
357                    i64::MAX,
358                    &return_type,
359                )?;
360                Ok(ColumnarValue::Array(result))
361            }
362            (from_arg, to_arg) => {
363                let from_array = from_arg.to_array(num_rows)?;
364                let to_array = to_arg.to_array(num_rows)?;
365                let result = array_replace_internal(
366                    self.name(),
367                    &list_array,
368                    &from_array,
369                    &to_array,
370                    &[Some(i64::MAX)],
371                    &return_type,
372                )?;
373                Ok(ColumnarValue::Array(result))
374            }
375        }
376    }
377
378    fn aliases(&self) -> &[String] {
379        &self.aliases
380    }
381
382    fn documentation(&self) -> Option<&Documentation> {
383        self.doc()
384    }
385}
386
387/// Return field shared by `array_replace`, `array_replace_n` and
388/// `array_replace_all`: the input list type, except that its inner field is
389/// nullable whenever the replacement element may be null.
390fn replace_return_field(name: &str, arg_fields: &[FieldRef]) -> Result<FieldRef> {
391    // `array` is at index 0 and `to` at index 2 for all three functions.
392    // `from` never contributes values to the output, so `to` is the only
393    // argument besides `array` that can affect the output's type.
394    let [array_field, _from_field, to_field, ..] = arg_fields else {
395        return exec_err!(
396            "{name} expects at least 3 arguments, got {}",
397            arg_fields.len()
398        );
399    };
400    let data_type =
401        list_type_with_element(array_field.data_type(), to_field.is_nullable());
402    Ok(Arc::new(Field::new(name, data_type, true)))
403}
404
405/// For each element of `list_array[i]`, replaces up to `arr_n[i]`  occurrences
406/// of `from_array[i]`, `to_array[i]`.
407///
408/// The type of each **element** in `list_array` must be the same as the type of
409/// `from_array` and `to_array`. This function also handles nested arrays
410/// (\[`ListArray`\] of \[`ListArray`\]s)
411///
412/// For example, when called to replace a list array (where each element is a
413/// list of int32s, the second and third argument are int32 arrays, and the
414/// fourth argument is the number of occurrences to replace
415///
416/// ```text
417/// general_replace(
418///   [1, 2, 3, 2], 2, 10, 1    ==> [1, 10, 3, 2]   (only the first 2 is replaced)
419///   [4, 5, 6, 5], 5, 20, 2    ==> [4, 20, 6, 20]  (both 5s are replaced)
420/// )
421/// ```
422fn general_replace<O: OffsetSizeTrait>(
423    list_array: &GenericListArray<O>,
424    from_array: &ArrayRef,
425    to_array: &ArrayRef,
426    arr_n: &[Option<i64>],
427    field: FieldRef,
428) -> Result<ArrayRef> {
429    // Build up the offsets for the final output array
430    let mut offsets: Vec<O> = Vec::with_capacity(list_array.len() + 1);
431    offsets.push(O::usize_as(0));
432    let values = list_array.values();
433    let original_data = values.to_data();
434    let to_data = to_array.to_data();
435    let capacity = Capacities::Array(offset_span_len(list_array.offsets()));
436
437    // First array is the original array, second array is the element to replace with.
438    let mut mutable = MutableArrayData::with_capacities(
439        vec![&original_data, &to_data],
440        false,
441        capacity,
442    );
443
444    let mut valid = NullBufferBuilder::new(list_array.len());
445
446    for (row_index, offset_window) in list_array.offsets().windows(2).enumerate() {
447        if list_array.is_null(row_index) {
448            offsets.push(offsets[row_index]);
449            valid.append_null();
450            continue;
451        }
452
453        let n = if arr_n.len() == 1 {
454            arr_n[0]
455        } else {
456            arr_n[row_index]
457        };
458        let Some(n) = n else {
459            offsets.push(offsets[row_index]);
460            valid.append_null();
461            continue;
462        };
463
464        let start = offset_window[0];
465        let end = offset_window[1];
466
467        let list_array_row = list_array.value(row_index);
468
469        // Compute all positions in list_row_array (that is itself an
470        // array) that are equal to `from_array_row`
471        let eq_array =
472            compare_element_to_list(&list_array_row, &from_array, row_index, true)?;
473
474        let original_idx = O::usize_as(0);
475        let replace_idx = O::usize_as(1);
476        let mut counter = 0;
477
478        // All elements are false, no need to replace, just copy original data
479        if n <= 0 || !eq_array.has_true() {
480            mutable.try_extend(
481                original_idx.to_usize().unwrap(),
482                start.to_usize().unwrap(),
483                end.to_usize().unwrap(),
484            )?;
485            offsets.push(offsets[row_index] + (end - start));
486            valid.append_non_null();
487            continue;
488        }
489
490        let mut pending_retain: Option<O> = None;
491        for (i, to_replace) in eq_array.iter().enumerate() {
492            let i = O::usize_as(i);
493            if to_replace == Some(true) && counter < n {
494                // Flush any pending retain run before emitting the replacement.
495                if let Some(rs) = pending_retain.take() {
496                    mutable.try_extend(
497                        original_idx.to_usize().unwrap(),
498                        (start + rs).to_usize().unwrap(),
499                        (start + i).to_usize().unwrap(),
500                    )?;
501                }
502                mutable.try_extend(
503                    replace_idx.to_usize().unwrap(),
504                    row_index,
505                    row_index + 1,
506                )?;
507                counter += 1;
508                if counter == n {
509                    // copy original data for any matches past n
510                    mutable.try_extend(
511                        original_idx.to_usize().unwrap(),
512                        (start + i).to_usize().unwrap() + 1,
513                        end.to_usize().unwrap(),
514                    )?;
515                    break;
516                }
517            } else if pending_retain.is_none() {
518                pending_retain = Some(i);
519            }
520        }
521
522        // Flush trailing retain run when we exited the loop without ever
523        // hitting `counter == n` (i.e. fewer than `n` matches in this row).
524        if counter < n
525            && let Some(rs) = pending_retain
526        {
527            mutable.try_extend(
528                original_idx.to_usize().unwrap(),
529                (start + rs).to_usize().unwrap(),
530                end.to_usize().unwrap(),
531            )?;
532        }
533
534        offsets.push(offsets[row_index] + (end - start));
535        valid.append_non_null();
536    }
537
538    let data = mutable.freeze();
539
540    Ok(Arc::new(GenericListArray::<O>::try_new(
541        field,
542        OffsetBuffer::<O>::new(offsets.into()),
543        arrow::array::make_array(data),
544        valid.finish(),
545    )?))
546}
547
548/// Replaces up to `max_replacements` occurrences of `needle` with the single
549/// element in `to_array` for each row in `list_array`.
550///
551/// This is a specialized fast path for the all-scalar case that uses a single
552/// bulk `not_distinct` comparison over only the visible values range, then
553/// iterates match positions via `set_indices` instead of scanning every bit.
554fn general_replace_with_scalar<O: OffsetSizeTrait>(
555    list_array: &GenericListArray<O>,
556    needle: &Scalar<ArrayRef>,
557    scalar_to: &ScalarValue,
558    max_replacements: i64,
559    field: FieldRef,
560) -> Result<ArrayRef> {
561    // No replacement needed, but the output still has to carry the promised
562    // field, which may be more nullable than the input's.
563    if max_replacements <= 0 {
564        return Ok(Arc::new(GenericListArray::<O>::try_new(
565            field,
566            list_array.offsets().clone(),
567            Arc::clone(list_array.values()),
568            list_array.nulls().cloned(),
569        )?));
570    }
571
572    let (first_offset, values_len) = offset_span(list_array.offsets());
573    let visible_values = list_array.values().slice(first_offset, values_len);
574
575    let to_array = scalar_to.to_array_of_size(1)?;
576    let original_data = visible_values.to_data();
577    let to_data = to_array.to_data();
578    let capacity = Capacities::Array(original_data.len());
579
580    let mut mutable = MutableArrayData::with_capacities(
581        vec![&original_data, &to_data],
582        false,
583        capacity,
584    );
585
586    let mut offsets = Vec::<O>::with_capacity(list_array.len() + 1);
587    offsets.push(O::zero());
588
589    // Single bulk comparison over the visible values only.
590    let match_bitmap = arrow_ord::cmp::not_distinct(&visible_values, needle)?;
591    let match_bits = match_bitmap.values();
592
593    for (row_index, offset_window) in list_array.offsets().windows(2).enumerate() {
594        // Offsets relative to visible_values (subtract first_offset).
595        let start = offset_window[0].to_usize().unwrap() - first_offset;
596        let end = offset_window[1].to_usize().unwrap() - first_offset;
597        let row_len = end - start;
598
599        if list_array.is_null(row_index) {
600            offsets.push(offsets[row_index]);
601            continue;
602        }
603
604        // Slice the match bits to this row and iterate only over true positions.
605        let row_bits = match_bits.slice(start, row_len);
606        let mut match_positions = row_bits
607            .set_indices()
608            .take(max_replacements as usize)
609            .peekable();
610        if match_positions.peek().is_none() {
611            mutable.try_extend(0, start, end)?;
612            offsets.push(offsets[row_index] + O::usize_as(row_len));
613            continue;
614        }
615
616        // Iterate only over the positions that match using set_indices,
617        // which is more efficient than scanning every bit because the number
618        // of matches is typically much smaller than the total array size.
619        let mut prev_end = 0usize;
620        for match_pos in match_positions {
621            // Retain elements before this match.
622            if match_pos > prev_end {
623                mutable.try_extend(0, start + prev_end, start + match_pos)?;
624            }
625            // Emit the replacement element.
626            mutable.try_extend(1, 0, 1)?;
627            prev_end = match_pos + 1;
628        }
629
630        // Copy remaining elements after the last replacement.
631        if prev_end < row_len {
632            mutable.try_extend(0, start + prev_end, end)?;
633        }
634
635        offsets.push(offsets[row_index] + O::usize_as(row_len));
636    }
637
638    let data = mutable.freeze();
639
640    Ok(Arc::new(GenericListArray::<O>::try_new(
641        field,
642        OffsetBuffer::new(offsets.into()),
643        arrow::array::make_array(data),
644        list_array.nulls().cloned(),
645    )?))
646}
647
648/// Fast path for `array_replace` when all arguments are scalars.
649///
650/// Uses a single bulk `not_distinct` comparison instead of per-row comparisons.
651fn array_replace_with_scalar_args(
652    name: &str,
653    list_array: &ArrayRef,
654    scalar_from: &ScalarValue,
655    scalar_to: &ScalarValue,
656    max_replacements: i64,
657    return_type: &DataType,
658) -> Result<ArrayRef> {
659    // `not_distinct` doesn't support nested types, fall back to the generic array path.
660    if scalar_from.data_type().is_nested() {
661        let num_rows = list_array.len();
662        let from_array = scalar_from.to_array_of_size(num_rows)?;
663        let to_array = scalar_to.to_array_of_size(num_rows)?;
664        return array_replace_internal(
665            name,
666            list_array,
667            &from_array,
668            &to_array,
669            &vec![Some(max_replacements); num_rows],
670            return_type,
671        );
672    }
673
674    let needle = Scalar::new(scalar_from.to_array_of_size(1)?);
675    match list_array.data_type() {
676        DataType::List(_) => general_replace_with_scalar::<i32>(
677            list_array.as_list::<i32>(),
678            &needle,
679            scalar_to,
680            max_replacements,
681            list_inner_field(name, return_type)?,
682        ),
683        DataType::LargeList(_) => general_replace_with_scalar::<i64>(
684            list_array.as_list::<i64>(),
685            &needle,
686            scalar_to,
687            max_replacements,
688            list_inner_field(name, return_type)?,
689        ),
690        DataType::Null => Ok(new_null_array(return_type, list_array.len())),
691        array_type => exec_err!("{name} does not support type '{array_type}'."),
692    }
693}
694
695fn array_replace_internal(
696    name: &str,
697    array: &ArrayRef,
698    from: &ArrayRef,
699    to: &ArrayRef,
700    arr_n: &[Option<i64>],
701    return_type: &DataType,
702) -> Result<ArrayRef> {
703    match array.data_type() {
704        DataType::List(_) => general_replace::<i32>(
705            array.as_list::<i32>(),
706            from,
707            to,
708            arr_n,
709            list_inner_field(name, return_type)?,
710        ),
711        DataType::LargeList(_) => general_replace::<i64>(
712            array.as_list::<i64>(),
713            from,
714            to,
715            arr_n,
716            list_inner_field(name, return_type)?,
717        ),
718        DataType::Null => Ok(new_null_array(return_type, array.len())),
719        array_type => exec_err!("{name} does not support type '{array_type}'."),
720    }
721}
722
723fn array_replace_n_inner(
724    name: &str,
725    array: &ArrayRef,
726    from: &ArrayRef,
727    to: &ArrayRef,
728    max: &ArrayRef,
729    return_type: &DataType,
730) -> Result<ArrayRef> {
731    let arr_n = as_int64_array(max)?.iter().collect::<Vec<_>>();
732    array_replace_internal(name, array, from, to, &arr_n, return_type)
733}
734
735#[cfg(test)]
736mod tests {
737    use super::{ArrayReplaceN, array_replace_n_inner};
738    use arrow::array::{ArrayRef, AsArray, Int32Array, Int64Array, ListArray};
739    use arrow::buffer::{NullBuffer, ScalarBuffer};
740    use arrow::datatypes::{DataType, Field, Int32Type};
741    use datafusion_common::{Result, ScalarValue, config::ConfigOptions};
742    use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
743    use std::sync::Arc;
744
745    #[test]
746    fn test_array_replace_n_null_max_returns_null() -> Result<()> {
747        let array: ArrayRef =
748            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
749                Some(vec![Some(1), Some(2), Some(3)]),
750                Some(vec![Some(4), Some(2)]),
751            ]));
752        let from: ArrayRef = Arc::new(Int32Array::from(vec![2, 2]));
753        let to: ArrayRef = Arc::new(Int32Array::from(vec![9, 9]));
754        let max: ArrayRef = Arc::new(Int64Array::new(
755            ScalarBuffer::from(vec![1, 1]),
756            Some(NullBuffer::from(vec![true, false])),
757        ));
758
759        let result = array_replace_n_inner(
760            "array_replace_n",
761            &array,
762            &from,
763            &to,
764            &max,
765            array.data_type(),
766        )?;
767        let expected = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
768            Some(vec![Some(1), Some(9), Some(3)]),
769            None,
770        ]);
771
772        assert_eq!(result.as_list::<i32>(), &expected);
773
774        Ok(())
775    }
776
777    #[test]
778    fn test_array_replace_n_scalar_null_max_returns_null() -> Result<()> {
779        let array: ArrayRef =
780            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
781                Some(vec![Some(1), Some(2), Some(3)]),
782                Some(vec![Some(4), Some(2)]),
783            ]));
784        let array_field = Arc::new(Field::new("array", array.data_type().clone(), true));
785
786        let result = ArrayReplaceN::new().invoke_with_args(ScalarFunctionArgs {
787            args: vec![
788                ColumnarValue::Array(Arc::clone(&array)),
789                ColumnarValue::Scalar(ScalarValue::Int32(Some(2))),
790                ColumnarValue::Scalar(ScalarValue::Int32(Some(9))),
791                ColumnarValue::Scalar(ScalarValue::Int64(None)),
792            ],
793            arg_fields: vec![
794                Arc::clone(&array_field),
795                Arc::new(Field::new("from", DataType::Int32, false)),
796                Arc::new(Field::new("to", DataType::Int32, false)),
797                Arc::new(Field::new("max", DataType::Int64, true)),
798            ],
799            number_rows: array.len(),
800            return_field: Arc::clone(&array_field),
801            config_options: Arc::new(ConfigOptions::default()),
802        })?;
803
804        let result = result.into_array(array.len())?;
805        let expected = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
806            Option::<Vec<Option<i32>>>::None,
807            Option::<Vec<Option<i32>>>::None,
808        ]);
809
810        assert_eq!(result.as_list::<i32>(), &expected);
811
812        Ok(())
813    }
814
815    #[test]
816    fn test_sliced_capacity() -> Result<()> {
817        crate::utils::tests::check_sliced_list_behavior(|input| {
818            let from: ArrayRef =
819                Arc::new(arrow::array::Float64Array::from(vec![3.0; input.len()]));
820            let to: ArrayRef =
821                Arc::new(arrow::array::Float64Array::from(vec![7.0; input.len()]));
822            super::array_replace_internal(
823                "array_replace",
824                input,
825                &from,
826                &to,
827                &vec![Some(1); input.len()],
828                input.data_type(),
829            )
830        })
831    }
832}