datafusion-functions-nested 56.0.0

Nested Type Function packages for the DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! [`ScalarUDFImpl`] definitions for array_resize function.

use crate::utils::make_scalar_function;
use arrow::array::{
    Array, ArrayRef, Capacities, GenericListArray, Int64Array, MutableArrayData,
    NullBufferBuilder, OffsetSizeTrait, new_null_array,
};
use arrow::buffer::OffsetBuffer;
use arrow::datatypes::DataType;
use arrow::datatypes::DataType::{LargeList, List};
use arrow::datatypes::Field;
use datafusion_common::cast::{as_int64_array, as_large_list_array, as_list_array};
use datafusion_common::utils::ListCoercion;
use datafusion_common::{
    Result, ScalarValue, assert_or_internal_err, exec_datafusion_err, exec_err,
    internal_datafusion_err,
};
use datafusion_expr::{
    ArrayFunctionArgument, ArrayFunctionSignature, ColumnarValue, Documentation,
    ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature, Volatility,
};
use datafusion_macros::user_doc;
use std::sync::Arc;

make_udf_expr_and_func!(
    ArrayResize,
    array_resize,
    array size value,
    "returns an array with the specified size filled with the given value.",
    array_resize_udf
);

#[user_doc(
    doc_section(label = "Array Functions"),
    description = "Resizes the list to contain size elements.",
    syntax_example = "array_resize(array, size[, value])",
    sql_example = r#"```sql
> select array_resize([1, 2, 3], 5, 0);
+-------------------------------------+
| array_resize(List([1,2,3],5,0))     |
+-------------------------------------+
| [1, 2, 3, 0, 0]                     |
+-------------------------------------+
```"#,
    argument(
        name = "array",
        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
    ),
    argument(name = "size", description = "New size of given array."),
    argument(
        name = "value",
        description = "If expanding the array, defines the values to fill in. Defaults to null."
    )
)]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct ArrayResize {
    signature: Signature,
    aliases: Vec<String>,
}

impl Default for ArrayResize {
    fn default() -> Self {
        Self::new()
    }
}

impl ArrayResize {
    pub fn new() -> Self {
        Self {
            signature: Signature::one_of(
                vec![
                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
                        arguments: vec![
                            ArrayFunctionArgument::Array,
                            ArrayFunctionArgument::Index,
                        ],
                        array_coercion: Some(ListCoercion::FixedSizedListToList),
                    }),
                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
                        arguments: vec![
                            ArrayFunctionArgument::Array,
                            ArrayFunctionArgument::Index,
                            ArrayFunctionArgument::Element,
                        ],
                        array_coercion: Some(ListCoercion::FixedSizedListToList),
                    }),
                ],
                Volatility::Immutable,
            ),
            aliases: vec!["list_resize".to_string()],
        }
    }
}

impl ScalarUDFImpl for ArrayResize {
    fn name(&self) -> &str {
        "array_resize"
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
        match &arg_types[0] {
            List(field) => Ok(List(Arc::clone(field))),
            LargeList(field) => Ok(LargeList(Arc::clone(field))),
            DataType::Null => {
                Ok(List(Arc::new(Field::new_list_field(DataType::Int64, true))))
            }
            _ => exec_err!(
                "Not reachable, data_type should be List, LargeList or FixedSizeList"
            ),
        }
    }

    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
        make_scalar_function(array_resize_inner)(&args.args)
    }

    fn aliases(&self) -> &[String] {
        &self.aliases
    }

    fn documentation(&self) -> Option<&Documentation> {
        self.doc()
    }
}

fn array_resize_inner(arg: &[ArrayRef]) -> Result<ArrayRef> {
    if arg.len() < 2 || arg.len() > 3 {
        return exec_err!("array_resize needs two or three arguments");
    }

    let array = &arg[0];

    // Checks if entire array is null
    if array.logical_null_count() == array.len() {
        let return_type = match array.data_type() {
            List(field) => List(Arc::clone(field)),
            LargeList(field) => LargeList(Arc::clone(field)),
            _ => {
                return exec_err!(
                    "array_resize does not support type '{:?}'.",
                    array.data_type()
                );
            }
        };
        return Ok(new_null_array(&return_type, array.len()));
    }

    let new_len = as_int64_array(&arg[1])?;
    let new_element = if arg.len() == 3 {
        Some(Arc::clone(&arg[2]))
    } else {
        None
    };

    match &arg[0].data_type() {
        List(_) => {
            let array = as_list_array(&arg[0])?;
            general_list_resize::<i32>(array, new_len, new_element)
        }
        LargeList(_) => {
            let array = as_large_list_array(&arg[0])?;
            general_list_resize::<i64>(array, new_len, new_element)
        }
        array_type => exec_err!("array_resize does not support type '{array_type}'."),
    }
}

fn resize_count(count_array: &Int64Array, idx: usize) -> Result<usize> {
    let c = count_array.value(idx);
    usize::try_from(c).map_err(|_| {
        exec_datafusion_err!("array_resize: size must not be negative, got {c}")
    })
}

/// array_resize keep the original array and append the default element to the end
fn general_list_resize<O: OffsetSizeTrait + TryInto<i64>>(
    array: &GenericListArray<O>,
    count_array: &Int64Array,
    default_element: Option<ArrayRef>,
) -> Result<ArrayRef> {
    let data_type = array.value_type();

    let values = array.values();
    let original_data = values.to_data();

    // Track the largest per-row growth so the uniform-fill fast path can
    // materialize one reusable fill buffer of the required size.
    let mut max_extra: usize = 0;
    let mut output_values_len: usize = 0;
    for (row_index, offset_window) in array.offsets().windows(2).enumerate() {
        if array.is_null(row_index) || count_array.is_null(row_index) {
            continue;
        }
        let target_count = resize_count(count_array, row_index)?;
        output_values_len =
            output_values_len.checked_add(target_count).ok_or_else(|| {
                internal_datafusion_err!("array_resize: output size overflow")
            })?;
        let current_len = (offset_window[1] - offset_window[0]).to_usize().unwrap();
        if target_count > current_len {
            max_extra = max_extra.max(target_count - current_len);
        }
    }

    if output_values_len > max_resize_values(&data_type)
        || O::from_usize(output_values_len).is_none()
    {
        return exec_err!(
            "array_resize: resulting array of {output_values_len} elements exceeds the maximum array size"
        );
    }

    // The fast path is valid when at least one row grows and every row would
    // use the same fill value.
    let use_bulk_fill = max_extra > 0
        && match &default_element {
            None => true,
            Some(fill_array) => {
                let len = fill_array.len();
                let null_count = fill_array.logical_null_count();

                len <= 1
                    || null_count == len
                    || (null_count == 0 && {
                        let first = fill_array.slice(0, 1);
                        (1..len)
                            .all(|i| fill_array.slice(i, 1).as_ref() == first.as_ref())
                    })
            }
        };

    if use_bulk_fill {
        // Fast path: materialize one reusable fill buffer for all grown rows.
        let fill_scalar = match &default_element {
            None => ScalarValue::try_from(&data_type)?,
            Some(fill_array) if fill_array.logical_null_count() == fill_array.len() => {
                ScalarValue::try_from(&data_type)?
            }
            Some(fill_array) => ScalarValue::try_from_array(fill_array.as_ref(), 0)?,
        };
        let fill_values = fill_scalar.to_array_of_size(max_extra)?;
        let default_value_data = fill_values.to_data();
        build_resized_list(
            array,
            count_array,
            &original_data,
            Some(&default_value_data),
            output_values_len,
            |mutable, _, extra_count| Ok(mutable.try_extend(1, 0, extra_count)?),
        )
    } else {
        // Handle batches with no growth or with different fill values per row.
        // Growing rows repeat the fill value from their corresponding input slot.
        // Growth without a fill argument always takes the bulk path above, so
        // `default_element` is present whenever a row grows here.
        let default_value_data = if max_extra > 0 {
            default_element.map(|fill_values| fill_values.to_data())
        } else {
            None
        };
        build_resized_list(
            array,
            count_array,
            &original_data,
            default_value_data.as_ref(),
            output_values_len,
            |mutable, row_index, extra_count| {
                for _ in 0..extra_count {
                    mutable.try_extend(1, row_index, row_index + 1)?;
                }
                Ok(())
            },
        )
    }
}

/// Copies the retained prefix of each row from `original_data` (source 0) and
/// calls `append_fill_values(mutable, row_index, extra_count)` for each row
/// that grows. `default_value_data` is registered as source 1 for that
/// callback to read; it may be `None` only when no row grows.
fn build_resized_list<O, F>(
    array: &GenericListArray<O>,
    count_array: &Int64Array,
    original_data: &arrow::array::ArrayData,
    default_value_data: Option<&arrow::array::ArrayData>,
    output_values_len: usize,
    mut append_fill_values: F,
) -> Result<ArrayRef>
where
    O: OffsetSizeTrait + TryInto<i64>,
    F: FnMut(&mut MutableArrayData, usize, usize) -> Result<()>,
{
    let capacity = Capacities::Array(output_values_len);
    let mut offsets = Vec::with_capacity(array.len() + 1);
    offsets.push(O::usize_as(0));
    let sources = match default_value_data {
        Some(default_value_data) => vec![original_data, default_value_data],
        None => vec![original_data],
    };
    let mut mutable = MutableArrayData::with_capacities(sources, false, capacity);
    let mut null_builder = NullBufferBuilder::new(array.len());

    for (row_index, offset_window) in array.offsets().windows(2).enumerate() {
        if array.is_null(row_index) || count_array.is_null(row_index) {
            null_builder.append_null();
            offsets.push(offsets[row_index]);
            continue;
        }
        null_builder.append_non_null();

        let count = resize_count(count_array, row_index)?;
        let count = O::usize_as(count);
        let start = offset_window[0];
        if start + count > offset_window[1] {
            assert_or_internal_err!(
                default_value_data.is_some(),
                "fill values are required when growing a list"
            );
            let extra_count = (start + count - offset_window[1]).to_usize().unwrap();
            let end = offset_window[1];
            mutable.try_extend(0, start.to_usize().unwrap(), end.to_usize().unwrap())?;
            append_fill_values(&mut mutable, row_index, extra_count)?;
        } else {
            let end = start + count;
            mutable.try_extend(0, start.to_usize().unwrap(), end.to_usize().unwrap())?;
        }
        offsets.push(offsets[row_index] + count);
    }

    let data = mutable.freeze();

    Ok(Arc::new(GenericListArray::<O>::try_new(
        Arc::clone(array.value_field()),
        OffsetBuffer::<O>::new(offsets.into()),
        arrow::array::make_array(data),
        null_builder.finish(),
    )?))
}

/// Largest element count whose eager value buffer stays within `isize::MAX`
/// bytes, so `array_resize` rejects oversized results instead of panicking.
/// Only primitive and `FixedSizeBinary` leaves are byte-exact.
fn max_resize_values(value_type: &DataType) -> usize {
    let element_width = match value_type {
        DataType::FixedSizeBinary(size) if *size > 0 => *size as usize,
        _ => value_type.primitive_width().unwrap_or(size_of::<u128>()),
    };

    (isize::MAX as usize) / element_width.max(1)
}

#[cfg(test)]
mod tests {
    use super::array_resize_inner;
    use arrow::array::{
        ArrayRef, AsArray, FixedSizeBinaryArray, GenericListArray, Int32Array,
        Int64Array, LargeListArray, ListArray, OffsetSizeTrait,
    };
    use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
    use arrow::datatypes::{DataType, Field, Int32Type, Int64Type};
    use datafusion_common::Result;
    use std::sync::Arc;

    #[test]
    fn test_array_resize_sliced_no_growth() -> Result<()> {
        fn check<O: OffsetSizeTrait>() -> Result<()> {
            let array =
                GenericListArray::<O>::from_iter_primitive::<Int32Type, _, _>(vec![
                    Some(vec![Some(90), Some(91), Some(92)]),
                    Some(vec![Some(1), None, Some(3)]),
                    Some(vec![Some(4), Some(5)]),
                    Some(vec![Some(6)]),
                    Some(vec![]),
                    None,
                    Some(vec![Some(7), Some(8)]),
                    Some(vec![Some(93), Some(94), Some(95)]),
                ]);
            // Retain the full child array, with unused values before and after
            // the visible rows. None of the valid rows needs a fill value.
            let array: ArrayRef = Arc::new(array.slice(1, 6));
            let size: ArrayRef = Arc::new(Int64Array::from(vec![
                Some(2),
                Some(2),
                Some(0),
                Some(0),
                // The list in this row is NULL, so the size is ignored.
                Some(20),
                None,
            ]));

            let expected =
                GenericListArray::<O>::from_iter_primitive::<Int32Type, _, _>(vec![
                    Some(vec![Some(1), None]),
                    Some(vec![Some(4), Some(5)]),
                    Some(vec![]),
                    Some(vec![]),
                    None,
                    None,
                ]);
            // The result is the same with or without a fill argument, because
            // no row reads a fill value.
            let fill: ArrayRef = Arc::new(Int32Array::from(vec![10, 20, 30, 40, 50, 60]));
            for args in [
                vec![Arc::clone(&array), Arc::clone(&size)],
                vec![array, size, fill],
            ] {
                let result = array_resize_inner(&args)?;
                assert_eq!(result.as_list::<O>(), &expected);
            }

            Ok(())
        }
        check::<i32>()?;
        check::<i64>()
    }

    #[test]
    fn test_array_resize_null_size_returns_null() -> Result<()> {
        let array: ArrayRef =
            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
                Some(vec![Some(1), Some(2), Some(3)]),
                Some(vec![Some(4), Some(5)]),
            ]));
        let size: ArrayRef = Arc::new(Int64Array::new(
            ScalarBuffer::from(vec![2, 1]),
            Some(NullBuffer::from(vec![true, false])),
        ));

        let result = array_resize_inner(&[array, size])?;
        let expected = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
            Some(vec![Some(1), Some(2)]),
            None,
        ]);

        assert_eq!(result.as_list::<i32>(), &expected);

        Ok(())
    }

    #[test]
    fn test_array_resize_large_size_errors_without_panicking() {
        let array: ArrayRef =
            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(vec![
                Some(vec![Some(1)]),
            ]));
        let size: ArrayRef = Arc::new(Int64Array::from(vec![i64::MAX]));
        let fill: ArrayRef = Arc::new(Int64Array::from(vec![0]));

        let err = array_resize_inner(&[array, size, fill]).unwrap_err();
        assert!(
            err.to_string().contains("exceeds the maximum array size"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_array_resize_fixed_size_binary_large_size_errors_without_panicking() {
        let values =
            FixedSizeBinaryArray::try_from_iter(vec![vec![0u8; 32]].into_iter()).unwrap();
        let elem_field =
            Arc::new(Field::new_list_field(DataType::FixedSizeBinary(32), true));
        let offsets = OffsetBuffer::<i64>::new(vec![0i64, 1].into());
        let array: ArrayRef = Arc::new(LargeListArray::new(
            elem_field,
            offsets,
            Arc::new(values) as ArrayRef,
            None,
        ));
        // Passes the width-16 bound (isize::MAX / 16) but overflows at width 32.
        let size: ArrayRef = Arc::new(Int64Array::from(vec![400_000_000_000_000_000i64]));

        let err = array_resize_inner(&[array, size]).unwrap_err();
        assert!(
            err.to_string().contains("exceeds the maximum array size"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_array_resize_accumulates_values_across_rows() {
        // Each row's target (6e17) is individually under the width-8 cap
        // (isize::MAX / 8), but their sum (1.2e18) exceeds it, so the guard
        // must reject based on the accumulated total rather than per row.
        let values = Int64Array::from(vec![1, 2]);
        let offsets = OffsetBuffer::<i64>::new(vec![0i64, 1, 2].into());
        let elem_field = Arc::new(Field::new_list_field(DataType::Int64, true));
        let array: ArrayRef = Arc::new(LargeListArray::new(
            elem_field,
            offsets,
            Arc::new(values) as ArrayRef,
            None,
        ));
        let size: ArrayRef = Arc::new(Int64Array::from(vec![
            600_000_000_000_000_000i64,
            600_000_000_000_000_000i64,
        ]));

        let err = array_resize_inner(&[array, size]).unwrap_err();
        assert!(
            err.to_string().contains("1200000000000000000"),
            "expected accumulated total in error: {err}"
        );
        assert!(
            err.to_string().contains("exceeds the maximum array size"),
            "unexpected error: {err}"
        );
    }
}