Skip to main content

datafusion_functions_nested/
repeat.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_repeat function.
6
7use crate::utils::make_scalar_function;
8use arrow::array::{
9    Array, ArrayRef, BooleanBufferBuilder, GenericListArray, Int64Array, OffsetSizeTrait,
10    UInt64Array,
11};
12use arrow::buffer::{NullBuffer, OffsetBuffer};
13use arrow::compute;
14use arrow::datatypes::DataType;
15use arrow::datatypes::{
16    DataType::{LargeList, List},
17    Field,
18};
19use datafusion_common::cast::{as_int64_array, as_large_list_array, as_list_array};
20use datafusion_common::types::{NativeType, logical_int64};
21use datafusion_common::{Result, exec_datafusion_err};
22use datafusion_expr::{
23    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
24    Volatility,
25};
26use datafusion_expr_common::signature::{Coercion, TypeSignatureClass};
27use datafusion_expr_common::sort_properties::ExprProperties;
28use datafusion_macros::user_doc;
29use std::mem::size_of;
30use std::sync::Arc;
31
32const ARRAY_REPEAT_LENGTH_EXCEEDED: &str =
33    "array_repeat: requested length exceeds maximum array size";
34
35make_udf_expr_and_func!(
36    ArrayRepeat,
37    array_repeat,
38    element count, // arg name
39    "returns an array containing element `count` times.", // doc
40    array_repeat_udf // internal function name
41);
42
43#[user_doc(
44    doc_section(label = "Array Functions"),
45    description = "Returns an array containing element `count` times.",
46    syntax_example = "array_repeat(element, count)",
47    sql_example = r#"```sql
48> select array_repeat(1, 3);
49+---------------------------------+
50| array_repeat(Int64(1),Int64(3)) |
51+---------------------------------+
52| [1, 1, 1]                       |
53+---------------------------------+
54> select array_repeat([1, 2], 2);
55+------------------------------------+
56| array_repeat(List([1,2]),Int64(2)) |
57+------------------------------------+
58| [[1, 2], [1, 2]]                   |
59+------------------------------------+
60```"#,
61    argument(
62        name = "element",
63        description = "Element expression. Can be a constant, column, or function, and any combination of array operators."
64    ),
65    argument(
66        name = "count",
67        description = "Value of how many times to repeat the element."
68    )
69)]
70#[derive(Debug, PartialEq, Eq, Hash)]
71pub struct ArrayRepeat {
72    signature: Signature,
73    aliases: Vec<String>,
74}
75
76impl Default for ArrayRepeat {
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82impl ArrayRepeat {
83    pub fn new() -> Self {
84        Self {
85            signature: Signature::coercible(
86                vec![
87                    Coercion::new_exact(TypeSignatureClass::Any),
88                    Coercion::new_implicit(
89                        TypeSignatureClass::Native(logical_int64()),
90                        vec![TypeSignatureClass::Integer],
91                        NativeType::Int64,
92                    ),
93                ],
94                Volatility::Immutable,
95            ),
96            aliases: vec![String::from("list_repeat")],
97        }
98    }
99}
100
101impl ScalarUDFImpl for ArrayRepeat {
102    fn name(&self) -> &str {
103        "array_repeat"
104    }
105
106    fn signature(&self) -> &Signature {
107        &self.signature
108    }
109
110    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
111        let element_type = &arg_types[0];
112        match element_type {
113            LargeList(_) => Ok(LargeList(Arc::new(Field::new_list_field(
114                element_type.clone(),
115                true,
116            )))),
117            _ => Ok(List(Arc::new(Field::new_list_field(
118                element_type.clone(),
119                true,
120            )))),
121        }
122    }
123
124    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
125        make_scalar_function(array_repeat_inner)(&args.args)
126    }
127
128    fn strictly_order_preserving(&self, _inputs: &[ExprProperties]) -> Result<bool> {
129        // this is not strictly order preserving
130        // since array_repeat(NULL, 2) = [NULL, NULL] and not NULL
131        Ok(false)
132    }
133
134    fn aliases(&self) -> &[String] {
135        &self.aliases
136    }
137
138    fn documentation(&self) -> Option<&Documentation> {
139        self.doc()
140    }
141}
142
143fn array_repeat_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
144    let element = &args[0];
145    let count_array = as_int64_array(&args[1])?;
146
147    match element.data_type() {
148        List(_) => {
149            let list_array = as_list_array(element)?;
150            general_list_repeat::<i32>(list_array, count_array)
151        }
152        LargeList(_) => {
153            let list_array = as_large_list_array(element)?;
154            general_list_repeat::<i64>(list_array, count_array)
155        }
156        _ => general_repeat::<i32>(element, count_array),
157    }
158}
159
160/// For each element of `array[i]` repeat `count_array[i]` times.
161///
162/// Assumption for the input:
163///     1. `count[i] >= 0`
164///     2. `array.len() == count_array.len()`
165///
166/// For example,
167/// ```text
168/// array_repeat(
169///     [1, 2, 3], [2, 0, 1] => [[1, 1], [], [3]]
170/// )
171/// ```
172fn general_repeat<O: OffsetSizeTrait>(
173    array: &ArrayRef,
174    count_array: &Int64Array,
175) -> Result<ArrayRef> {
176    let total_repeated_values =
177        (0..count_array.len()).try_fold(0usize, |total, idx| {
178            total
179                .checked_add(repeat_count(count_array, idx).unwrap_or_default())
180                .ok_or_else(|| {
181                    exec_datafusion_err!(
182                        "array_repeat: total repeated values overflowed usize"
183                    )
184                })
185        })?;
186    ensure_repeated_values_fit::<O>(total_repeated_values)?;
187    let (offsets, _) = build_repeat_offsets::<O>(count_array)?;
188
189    let mut take_indices = Vec::with_capacity(total_repeated_values);
190
191    for idx in 0..count_array.len() {
192        let Some(count) = repeat_count(count_array, idx) else {
193            continue;
194        };
195        take_indices.extend(std::iter::repeat_n(idx as u64, count));
196    }
197
198    // Build the flattened values
199    let repeated_values = compute::take(
200        array.as_ref(),
201        &UInt64Array::from_iter_values(take_indices),
202        None,
203    )?;
204
205    // Construct final ListArray
206    Ok(Arc::new(GenericListArray::<O>::try_new(
207        Arc::new(Field::new_list_field(array.data_type().to_owned(), true)),
208        OffsetBuffer::new(offsets.into()),
209        repeated_values,
210        count_array.nulls().cloned(),
211    )?))
212}
213
214/// Handle List version of `general_repeat`
215///
216/// For each element of `list_array[i]` repeat `count_array[i]` times.
217///
218/// For example,
219/// ```text
220/// array_repeat(
221///     [[1, 2, 3], [4, 5], [6]], [2, 0, 1] => [[[1, 2, 3], [1, 2, 3]], [], [[6]]]
222/// )
223/// ```
224fn general_list_repeat<O: OffsetSizeTrait>(
225    list_array: &GenericListArray<O>,
226    count_array: &Int64Array,
227) -> Result<ArrayRef> {
228    let list_offsets = list_array.value_offsets();
229    let (outer_offsets, outer_total) = build_repeat_offsets::<O>(count_array)?;
230
231    // calculate capacities for pre-allocation
232    let mut inner_total = 0usize;
233    for i in 0..count_array.len() {
234        let Some(count) = repeat_count(count_array, i) else {
235            continue;
236        };
237        if count > 0 && list_array.is_valid(i) {
238            let len = list_offsets[i + 1].to_usize().unwrap()
239                - list_offsets[i].to_usize().unwrap();
240            inner_total =
241                checked_repeat_len_add(inner_total, checked_repeat_len_mul(len, count)?)?;
242            ensure_repeated_values_fit::<O>(inner_total)?;
243        }
244    }
245
246    // Build inner structures
247    let inner_offsets_capacity = checked_offset_slots_capacity::<O>(outer_total)?;
248    let mut inner_offsets = Vec::with_capacity(inner_offsets_capacity);
249    let mut take_indices = Vec::with_capacity(inner_total);
250    let mut inner_nulls = BooleanBufferBuilder::new(outer_total);
251    let mut inner_running = 0usize;
252    inner_offsets.push(O::zero());
253
254    for row_idx in 0..count_array.len() {
255        let Some(count) = repeat_count(count_array, row_idx) else {
256            continue;
257        };
258        let list_is_valid = list_array.is_valid(row_idx);
259        // A NULL list slot may still have a non-empty offset range; treat the
260        // range as empty to keep the inner offsets and taken values in step.
261        let (start, end) = if list_is_valid {
262            (
263                list_offsets[row_idx].to_usize().unwrap(),
264                list_offsets[row_idx + 1].to_usize().unwrap(),
265            )
266        } else {
267            (0, 0)
268        };
269        let row_len = end - start;
270
271        for _ in 0..count {
272            inner_running = checked_repeat_len_add(inner_running, row_len)?;
273            ensure_repeated_values_fit::<O>(inner_running)?;
274            let offset = checked_repeat_offset::<O>(inner_running)?;
275            inner_offsets.push(offset);
276            inner_nulls.append(list_is_valid);
277            take_indices.extend(start as u64..end as u64);
278        }
279    }
280
281    // Build inner ListArray
282    let inner_values = compute::take(
283        list_array.values().as_ref(),
284        &UInt64Array::from_iter_values(take_indices),
285        None,
286    )?;
287    let inner_list = GenericListArray::<O>::try_new(
288        Arc::clone(list_array.value_field()),
289        OffsetBuffer::new(inner_offsets.into()),
290        inner_values,
291        Some(NullBuffer::new(inner_nulls.finish())),
292    )?;
293
294    Ok(Arc::new(GenericListArray::<O>::try_new(
295        Arc::new(Field::new_list_field(
296            list_array.data_type().to_owned(),
297            true,
298        )),
299        OffsetBuffer::new(outer_offsets.into()),
300        Arc::new(inner_list),
301        count_array.nulls().cloned(),
302    )?))
303}
304
305fn build_repeat_offsets<O: OffsetSizeTrait>(
306    count_array: &Int64Array,
307) -> Result<(Vec<O>, usize)> {
308    let offsets_capacity = checked_offset_slots_capacity::<O>(count_array.len())?;
309    let mut offsets = Vec::with_capacity(offsets_capacity);
310    offsets.push(O::zero());
311    let mut running_offset = 0usize;
312
313    for idx in 0..count_array.len() {
314        let Some(count) = repeat_count(count_array, idx) else {
315            offsets.push(*offsets.last().unwrap());
316            continue;
317        };
318        running_offset = checked_repeat_len_add(running_offset, count)?;
319        ensure_repeated_values_fit::<O>(running_offset)?;
320        let offset = checked_repeat_offset::<O>(running_offset)?;
321        offsets.push(offset);
322    }
323
324    Ok((offsets, running_offset))
325}
326
327fn checked_repeat_len_add(lhs: usize, rhs: usize) -> Result<usize> {
328    lhs.checked_add(rhs)
329        .ok_or_else(|| exec_datafusion_err!("{}", ARRAY_REPEAT_LENGTH_EXCEEDED))
330}
331
332fn checked_repeat_len_mul(lhs: usize, rhs: usize) -> Result<usize> {
333    lhs.checked_mul(rhs)
334        .ok_or_else(|| exec_datafusion_err!("{}", ARRAY_REPEAT_LENGTH_EXCEEDED))
335}
336
337fn ensure_repeated_values_fit<O: OffsetSizeTrait>(len: usize) -> Result<()> {
338    ensure_vec_capacity::<u64>(len)?;
339    checked_repeat_offset::<O>(len)?;
340
341    Ok(())
342}
343
344fn ensure_vec_capacity<T>(len: usize) -> Result<()> {
345    if len > max_vec_elements::<T>() {
346        return Err(exec_datafusion_err!("{}", ARRAY_REPEAT_LENGTH_EXCEEDED));
347    }
348
349    Ok(())
350}
351
352fn checked_offset_slots_capacity<O>(len: usize) -> Result<usize> {
353    let capacity = checked_repeat_len_add(len, 1)?;
354    ensure_vec_capacity::<O>(capacity)?;
355
356    Ok(capacity)
357}
358
359fn checked_repeat_offset<O: OffsetSizeTrait>(offset: usize) -> Result<O> {
360    O::from_usize(offset).ok_or_else(|| {
361        exec_datafusion_err!(
362            "array_repeat: offset {offset} exceeds the maximum value for offset type"
363        )
364    })
365}
366
367fn max_vec_elements<T>() -> usize {
368    let element_size = size_of::<T>();
369    (isize::MAX as usize)
370        .checked_div(element_size)
371        .unwrap_or(usize::MAX)
372}
373
374/// Helper function to get count from count_array at given index.
375/// Returns `None` for NULL values and `Some(0)` for non-positive counts.
376#[inline]
377fn repeat_count(count_array: &Int64Array, idx: usize) -> Option<usize> {
378    if count_array.is_null(idx) {
379        None
380    } else {
381        let c = count_array.value(idx);
382        Some(if c > 0 { c as usize } else { 0 })
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::{array_repeat_inner, general_list_repeat, general_repeat};
389    use arrow::array::{Array, ArrayRef, AsArray, Int32Array, Int64Array, ListArray};
390    use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
391    use arrow::datatypes::{DataType, Field, Int32Type};
392    use datafusion_common::Result;
393    use std::sync::Arc;
394
395    #[test]
396    fn test_array_repeat_null_count_stays_null() -> Result<()> {
397        let array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
398        let counts = Int64Array::new(
399            ScalarBuffer::from(vec![2, 1, 1]),
400            Some(NullBuffer::from(vec![true, false, true])),
401        );
402
403        let result = general_repeat::<i32>(&array, &counts)?;
404        let expected = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
405            Some(vec![Some(1), Some(1)]),
406            None,
407            Some(vec![Some(3)]),
408        ]);
409
410        assert_eq!(result.as_list::<i32>(), &expected);
411
412        Ok(())
413    }
414
415    #[test]
416    fn test_array_repeat_nested_null_count_stays_null() -> Result<()> {
417        let list_array = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
418            Some(vec![Some(1), Some(2)]),
419            Some(vec![Some(3), Some(4)]),
420            Some(vec![Some(5)]),
421        ]);
422        let counts = Int64Array::new(
423            ScalarBuffer::from(vec![2, 1, 1]),
424            Some(NullBuffer::from(vec![true, false, true])),
425        );
426
427        let result = general_list_repeat::<i32>(&list_array, &counts)?;
428        let repeated_values = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
429            Some(vec![Some(1), Some(2)]),
430            Some(vec![Some(1), Some(2)]),
431            Some(vec![Some(5)]),
432        ]);
433        let expected = ListArray::new(
434            Arc::new(Field::new_list_field(
435                repeated_values.data_type().clone(),
436                true,
437            )),
438            OffsetBuffer::new(ScalarBuffer::from(vec![0, 2, 2, 3])),
439            Arc::new(repeated_values),
440            Some(NullBuffer::from(vec![true, false, true])),
441        );
442
443        assert_eq!(result.as_list::<i32>(), &expected);
444
445        Ok(())
446    }
447
448    #[test]
449    fn test_array_repeat_nested_null_list_with_nonempty_range() -> Result<()> {
450        // A NULL list slot might still have a non-empty offset range
451        // https://github.com/apache/datafusion/issues/25223
452        let values = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
453        let list_array = ListArray::new(
454            Arc::new(Field::new_list_field(DataType::Int32, true)),
455            OffsetBuffer::new(ScalarBuffer::from(vec![0, 3, 6])),
456            Arc::new(values),
457            Some(NullBuffer::from(vec![false, true])),
458        );
459        let counts = Int64Array::from(vec![2, 2]);
460
461        let result = general_list_repeat::<i32>(&list_array, &counts)?;
462        let repeated_values = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
463            None,
464            None,
465            Some(vec![Some(4), Some(5), Some(6)]),
466            Some(vec![Some(4), Some(5), Some(6)]),
467        ]);
468        let expected = ListArray::new(
469            Arc::new(Field::new_list_field(
470                repeated_values.data_type().clone(),
471                true,
472            )),
473            OffsetBuffer::new(ScalarBuffer::from(vec![0, 2, 4])),
474            Arc::new(repeated_values),
475            None,
476        );
477
478        assert_eq!(result.as_list::<i32>(), &expected);
479
480        Ok(())
481    }
482
483    #[test]
484    fn scalar_count_exceeding_max_array_size_returns_error() {
485        let element: ArrayRef = Arc::new(Int64Array::from(vec![1]));
486        let count: ArrayRef = Arc::new(Int64Array::from(vec![i64::MAX]));
487
488        let err = array_repeat_inner(&[element, count]).unwrap_err();
489        assert!(
490            err.to_string().starts_with(
491                "Execution error: array_repeat: requested length exceeds maximum array size"
492            ),
493            "unexpected error: {err}"
494        );
495    }
496
497    #[test]
498    fn scalar_count_exceeding_list_offset_limit_returns_error() {
499        let element: ArrayRef = Arc::new(Int64Array::from(vec![1]));
500        let count: ArrayRef = Arc::new(Int64Array::from(vec![i32::MAX as i64 + 1]));
501
502        let err = array_repeat_inner(&[element, count]).unwrap_err();
503        assert!(
504            err.to_string().starts_with(
505                "Execution error: array_repeat: offset 2147483648 exceeds the maximum value for offset type"
506            ),
507            "unexpected error: {err}"
508        );
509    }
510}