Skip to main content

datafusion_functions_nested/
resize.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_resize function.
6
7use crate::utils::make_scalar_function;
8use arrow::array::{
9    Array, ArrayRef, Capacities, GenericListArray, Int64Array, MutableArrayData,
10    NullBufferBuilder, OffsetSizeTrait, new_null_array,
11};
12use arrow::buffer::OffsetBuffer;
13use arrow::datatypes::DataType;
14use arrow::datatypes::DataType::{LargeList, List};
15use arrow::datatypes::Field;
16use datafusion_common::cast::{as_int64_array, as_large_list_array, as_list_array};
17use datafusion_common::utils::ListCoercion;
18use datafusion_common::{
19    Result, ScalarValue, assert_or_internal_err, exec_datafusion_err, exec_err,
20    internal_datafusion_err,
21};
22use datafusion_expr::{
23    ArrayFunctionArgument, ArrayFunctionSignature, ColumnarValue, Documentation,
24    ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature, Volatility,
25};
26use datafusion_macros::user_doc;
27use std::sync::Arc;
28
29make_udf_expr_and_func!(
30    ArrayResize,
31    array_resize,
32    array size value,
33    "returns an array with the specified size filled with the given value.",
34    array_resize_udf
35);
36
37#[user_doc(
38    doc_section(label = "Array Functions"),
39    description = "Resizes the list to contain size elements.",
40    syntax_example = "array_resize(array, size[, value])",
41    sql_example = r#"```sql
42> select array_resize([1, 2, 3], 5, 0);
43+-------------------------------------+
44| array_resize(List([1,2,3],5,0))     |
45+-------------------------------------+
46| [1, 2, 3, 0, 0]                     |
47+-------------------------------------+
48```"#,
49    argument(
50        name = "array",
51        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
52    ),
53    argument(name = "size", description = "New size of given array."),
54    argument(
55        name = "value",
56        description = "If expanding the array, defines the values to fill in. Defaults to null."
57    )
58)]
59#[derive(Debug, PartialEq, Eq, Hash)]
60pub struct ArrayResize {
61    signature: Signature,
62    aliases: Vec<String>,
63}
64
65impl Default for ArrayResize {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71impl ArrayResize {
72    pub fn new() -> Self {
73        Self {
74            signature: Signature::one_of(
75                vec![
76                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
77                        arguments: vec![
78                            ArrayFunctionArgument::Array,
79                            ArrayFunctionArgument::Index,
80                        ],
81                        array_coercion: Some(ListCoercion::FixedSizedListToList),
82                    }),
83                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
84                        arguments: vec![
85                            ArrayFunctionArgument::Array,
86                            ArrayFunctionArgument::Index,
87                            ArrayFunctionArgument::Element,
88                        ],
89                        array_coercion: Some(ListCoercion::FixedSizedListToList),
90                    }),
91                ],
92                Volatility::Immutable,
93            ),
94            aliases: vec!["list_resize".to_string()],
95        }
96    }
97}
98
99impl ScalarUDFImpl for ArrayResize {
100    fn name(&self) -> &str {
101        "array_resize"
102    }
103
104    fn signature(&self) -> &Signature {
105        &self.signature
106    }
107
108    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
109        match &arg_types[0] {
110            List(field) => Ok(List(Arc::clone(field))),
111            LargeList(field) => Ok(LargeList(Arc::clone(field))),
112            DataType::Null => {
113                Ok(List(Arc::new(Field::new_list_field(DataType::Int64, true))))
114            }
115            _ => exec_err!(
116                "Not reachable, data_type should be List, LargeList or FixedSizeList"
117            ),
118        }
119    }
120
121    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
122        make_scalar_function(array_resize_inner)(&args.args)
123    }
124
125    fn aliases(&self) -> &[String] {
126        &self.aliases
127    }
128
129    fn documentation(&self) -> Option<&Documentation> {
130        self.doc()
131    }
132}
133
134fn array_resize_inner(arg: &[ArrayRef]) -> Result<ArrayRef> {
135    if arg.len() < 2 || arg.len() > 3 {
136        return exec_err!("array_resize needs two or three arguments");
137    }
138
139    let array = &arg[0];
140
141    // Checks if entire array is null
142    if array.logical_null_count() == array.len() {
143        let return_type = match array.data_type() {
144            List(field) => List(Arc::clone(field)),
145            LargeList(field) => LargeList(Arc::clone(field)),
146            _ => {
147                return exec_err!(
148                    "array_resize does not support type '{:?}'.",
149                    array.data_type()
150                );
151            }
152        };
153        return Ok(new_null_array(&return_type, array.len()));
154    }
155
156    let new_len = as_int64_array(&arg[1])?;
157    let new_element = if arg.len() == 3 {
158        Some(Arc::clone(&arg[2]))
159    } else {
160        None
161    };
162
163    match &arg[0].data_type() {
164        List(_) => {
165            let array = as_list_array(&arg[0])?;
166            general_list_resize::<i32>(array, new_len, new_element)
167        }
168        LargeList(_) => {
169            let array = as_large_list_array(&arg[0])?;
170            general_list_resize::<i64>(array, new_len, new_element)
171        }
172        array_type => exec_err!("array_resize does not support type '{array_type}'."),
173    }
174}
175
176fn resize_count(count_array: &Int64Array, idx: usize) -> Result<usize> {
177    let c = count_array.value(idx);
178    usize::try_from(c).map_err(|_| {
179        exec_datafusion_err!("array_resize: size must not be negative, got {c}")
180    })
181}
182
183/// array_resize keep the original array and append the default element to the end
184fn general_list_resize<O: OffsetSizeTrait + TryInto<i64>>(
185    array: &GenericListArray<O>,
186    count_array: &Int64Array,
187    default_element: Option<ArrayRef>,
188) -> Result<ArrayRef> {
189    let data_type = array.value_type();
190
191    let values = array.values();
192    let original_data = values.to_data();
193
194    // Track the largest per-row growth so the uniform-fill fast path can
195    // materialize one reusable fill buffer of the required size.
196    let mut max_extra: usize = 0;
197    let mut output_values_len: usize = 0;
198    for (row_index, offset_window) in array.offsets().windows(2).enumerate() {
199        if array.is_null(row_index) || count_array.is_null(row_index) {
200            continue;
201        }
202        let target_count = resize_count(count_array, row_index)?;
203        output_values_len =
204            output_values_len.checked_add(target_count).ok_or_else(|| {
205                internal_datafusion_err!("array_resize: output size overflow")
206            })?;
207        let current_len = (offset_window[1] - offset_window[0]).to_usize().unwrap();
208        if target_count > current_len {
209            max_extra = max_extra.max(target_count - current_len);
210        }
211    }
212
213    if output_values_len > max_resize_values(&data_type)
214        || O::from_usize(output_values_len).is_none()
215    {
216        return exec_err!(
217            "array_resize: resulting array of {output_values_len} elements exceeds the maximum array size"
218        );
219    }
220
221    // The fast path is valid when at least one row grows and every row would
222    // use the same fill value.
223    let use_bulk_fill = max_extra > 0
224        && match &default_element {
225            None => true,
226            Some(fill_array) => {
227                let len = fill_array.len();
228                let null_count = fill_array.logical_null_count();
229
230                len <= 1
231                    || null_count == len
232                    || (null_count == 0 && {
233                        let first = fill_array.slice(0, 1);
234                        (1..len)
235                            .all(|i| fill_array.slice(i, 1).as_ref() == first.as_ref())
236                    })
237            }
238        };
239
240    if use_bulk_fill {
241        // Fast path: materialize one reusable fill buffer for all grown rows.
242        let fill_scalar = match &default_element {
243            None => ScalarValue::try_from(&data_type)?,
244            Some(fill_array) if fill_array.logical_null_count() == fill_array.len() => {
245                ScalarValue::try_from(&data_type)?
246            }
247            Some(fill_array) => ScalarValue::try_from_array(fill_array.as_ref(), 0)?,
248        };
249        let fill_values = fill_scalar.to_array_of_size(max_extra)?;
250        let default_value_data = fill_values.to_data();
251        build_resized_list(
252            array,
253            count_array,
254            &original_data,
255            Some(&default_value_data),
256            output_values_len,
257            |mutable, _, extra_count| Ok(mutable.try_extend(1, 0, extra_count)?),
258        )
259    } else {
260        // Handle batches with no growth or with different fill values per row.
261        // Growing rows repeat the fill value from their corresponding input slot.
262        // Growth without a fill argument always takes the bulk path above, so
263        // `default_element` is present whenever a row grows here.
264        let default_value_data = if max_extra > 0 {
265            default_element.map(|fill_values| fill_values.to_data())
266        } else {
267            None
268        };
269        build_resized_list(
270            array,
271            count_array,
272            &original_data,
273            default_value_data.as_ref(),
274            output_values_len,
275            |mutable, row_index, extra_count| {
276                for _ in 0..extra_count {
277                    mutable.try_extend(1, row_index, row_index + 1)?;
278                }
279                Ok(())
280            },
281        )
282    }
283}
284
285/// Copies the retained prefix of each row from `original_data` (source 0) and
286/// calls `append_fill_values(mutable, row_index, extra_count)` for each row
287/// that grows. `default_value_data` is registered as source 1 for that
288/// callback to read; it may be `None` only when no row grows.
289fn build_resized_list<O, F>(
290    array: &GenericListArray<O>,
291    count_array: &Int64Array,
292    original_data: &arrow::array::ArrayData,
293    default_value_data: Option<&arrow::array::ArrayData>,
294    output_values_len: usize,
295    mut append_fill_values: F,
296) -> Result<ArrayRef>
297where
298    O: OffsetSizeTrait + TryInto<i64>,
299    F: FnMut(&mut MutableArrayData, usize, usize) -> Result<()>,
300{
301    let capacity = Capacities::Array(output_values_len);
302    let mut offsets = Vec::with_capacity(array.len() + 1);
303    offsets.push(O::usize_as(0));
304    let sources = match default_value_data {
305        Some(default_value_data) => vec![original_data, default_value_data],
306        None => vec![original_data],
307    };
308    let mut mutable = MutableArrayData::with_capacities(sources, false, capacity);
309    let mut null_builder = NullBufferBuilder::new(array.len());
310
311    for (row_index, offset_window) in array.offsets().windows(2).enumerate() {
312        if array.is_null(row_index) || count_array.is_null(row_index) {
313            null_builder.append_null();
314            offsets.push(offsets[row_index]);
315            continue;
316        }
317        null_builder.append_non_null();
318
319        let count = resize_count(count_array, row_index)?;
320        let count = O::usize_as(count);
321        let start = offset_window[0];
322        if start + count > offset_window[1] {
323            assert_or_internal_err!(
324                default_value_data.is_some(),
325                "fill values are required when growing a list"
326            );
327            let extra_count = (start + count - offset_window[1]).to_usize().unwrap();
328            let end = offset_window[1];
329            mutable.try_extend(0, start.to_usize().unwrap(), end.to_usize().unwrap())?;
330            append_fill_values(&mut mutable, row_index, extra_count)?;
331        } else {
332            let end = start + count;
333            mutable.try_extend(0, start.to_usize().unwrap(), end.to_usize().unwrap())?;
334        }
335        offsets.push(offsets[row_index] + count);
336    }
337
338    let data = mutable.freeze();
339
340    Ok(Arc::new(GenericListArray::<O>::try_new(
341        Arc::clone(array.value_field()),
342        OffsetBuffer::<O>::new(offsets.into()),
343        arrow::array::make_array(data),
344        null_builder.finish(),
345    )?))
346}
347
348/// Largest element count whose eager value buffer stays within `isize::MAX`
349/// bytes, so `array_resize` rejects oversized results instead of panicking.
350/// Only primitive and `FixedSizeBinary` leaves are byte-exact.
351fn max_resize_values(value_type: &DataType) -> usize {
352    let element_width = match value_type {
353        DataType::FixedSizeBinary(size) if *size > 0 => *size as usize,
354        _ => value_type.primitive_width().unwrap_or(size_of::<u128>()),
355    };
356
357    (isize::MAX as usize) / element_width.max(1)
358}
359
360#[cfg(test)]
361mod tests {
362    use super::array_resize_inner;
363    use arrow::array::{
364        ArrayRef, AsArray, FixedSizeBinaryArray, GenericListArray, Int32Array,
365        Int64Array, LargeListArray, ListArray, OffsetSizeTrait,
366    };
367    use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
368    use arrow::datatypes::{DataType, Field, Int32Type, Int64Type};
369    use datafusion_common::Result;
370    use std::sync::Arc;
371
372    #[test]
373    fn test_array_resize_sliced_no_growth() -> Result<()> {
374        fn check<O: OffsetSizeTrait>() -> Result<()> {
375            let array =
376                GenericListArray::<O>::from_iter_primitive::<Int32Type, _, _>(vec![
377                    Some(vec![Some(90), Some(91), Some(92)]),
378                    Some(vec![Some(1), None, Some(3)]),
379                    Some(vec![Some(4), Some(5)]),
380                    Some(vec![Some(6)]),
381                    Some(vec![]),
382                    None,
383                    Some(vec![Some(7), Some(8)]),
384                    Some(vec![Some(93), Some(94), Some(95)]),
385                ]);
386            // Retain the full child array, with unused values before and after
387            // the visible rows. None of the valid rows needs a fill value.
388            let array: ArrayRef = Arc::new(array.slice(1, 6));
389            let size: ArrayRef = Arc::new(Int64Array::from(vec![
390                Some(2),
391                Some(2),
392                Some(0),
393                Some(0),
394                // The list in this row is NULL, so the size is ignored.
395                Some(20),
396                None,
397            ]));
398
399            let expected =
400                GenericListArray::<O>::from_iter_primitive::<Int32Type, _, _>(vec![
401                    Some(vec![Some(1), None]),
402                    Some(vec![Some(4), Some(5)]),
403                    Some(vec![]),
404                    Some(vec![]),
405                    None,
406                    None,
407                ]);
408            // The result is the same with or without a fill argument, because
409            // no row reads a fill value.
410            let fill: ArrayRef = Arc::new(Int32Array::from(vec![10, 20, 30, 40, 50, 60]));
411            for args in [
412                vec![Arc::clone(&array), Arc::clone(&size)],
413                vec![array, size, fill],
414            ] {
415                let result = array_resize_inner(&args)?;
416                assert_eq!(result.as_list::<O>(), &expected);
417            }
418
419            Ok(())
420        }
421        check::<i32>()?;
422        check::<i64>()
423    }
424
425    #[test]
426    fn test_array_resize_null_size_returns_null() -> Result<()> {
427        let array: ArrayRef =
428            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
429                Some(vec![Some(1), Some(2), Some(3)]),
430                Some(vec![Some(4), Some(5)]),
431            ]));
432        let size: ArrayRef = Arc::new(Int64Array::new(
433            ScalarBuffer::from(vec![2, 1]),
434            Some(NullBuffer::from(vec![true, false])),
435        ));
436
437        let result = array_resize_inner(&[array, size])?;
438        let expected = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
439            Some(vec![Some(1), Some(2)]),
440            None,
441        ]);
442
443        assert_eq!(result.as_list::<i32>(), &expected);
444
445        Ok(())
446    }
447
448    #[test]
449    fn test_array_resize_large_size_errors_without_panicking() {
450        let array: ArrayRef =
451            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(vec![
452                Some(vec![Some(1)]),
453            ]));
454        let size: ArrayRef = Arc::new(Int64Array::from(vec![i64::MAX]));
455        let fill: ArrayRef = Arc::new(Int64Array::from(vec![0]));
456
457        let err = array_resize_inner(&[array, size, fill]).unwrap_err();
458        assert!(
459            err.to_string().contains("exceeds the maximum array size"),
460            "unexpected error: {err}"
461        );
462    }
463
464    #[test]
465    fn test_array_resize_fixed_size_binary_large_size_errors_without_panicking() {
466        let values =
467            FixedSizeBinaryArray::try_from_iter(vec![vec![0u8; 32]].into_iter()).unwrap();
468        let elem_field =
469            Arc::new(Field::new_list_field(DataType::FixedSizeBinary(32), true));
470        let offsets = OffsetBuffer::<i64>::new(vec![0i64, 1].into());
471        let array: ArrayRef = Arc::new(LargeListArray::new(
472            elem_field,
473            offsets,
474            Arc::new(values) as ArrayRef,
475            None,
476        ));
477        // Passes the width-16 bound (isize::MAX / 16) but overflows at width 32.
478        let size: ArrayRef = Arc::new(Int64Array::from(vec![400_000_000_000_000_000i64]));
479
480        let err = array_resize_inner(&[array, size]).unwrap_err();
481        assert!(
482            err.to_string().contains("exceeds the maximum array size"),
483            "unexpected error: {err}"
484        );
485    }
486
487    #[test]
488    fn test_array_resize_accumulates_values_across_rows() {
489        // Each row's target (6e17) is individually under the width-8 cap
490        // (isize::MAX / 8), but their sum (1.2e18) exceeds it, so the guard
491        // must reject based on the accumulated total rather than per row.
492        let values = Int64Array::from(vec![1, 2]);
493        let offsets = OffsetBuffer::<i64>::new(vec![0i64, 1, 2].into());
494        let elem_field = Arc::new(Field::new_list_field(DataType::Int64, true));
495        let array: ArrayRef = Arc::new(LargeListArray::new(
496            elem_field,
497            offsets,
498            Arc::new(values) as ArrayRef,
499            None,
500        ));
501        let size: ArrayRef = Arc::new(Int64Array::from(vec![
502            600_000_000_000_000_000i64,
503            600_000_000_000_000_000i64,
504        ]));
505
506        let err = array_resize_inner(&[array, size]).unwrap_err();
507        assert!(
508            err.to_string().contains("1200000000000000000"),
509            "expected accumulated total in error: {err}"
510        );
511        assert!(
512            err.to_string().contains("exceeds the maximum array size"),
513            "unexpected error: {err}"
514        );
515    }
516}