Skip to main content

datafusion_functions_nested/
concat.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_append`, `array_prepend` and `array_concat` functions.
6
7use std::sync::Arc;
8
9use crate::make_array::make_array_inner;
10use crate::utils::{
11    align_array_dimensions, check_datatypes, list_inner_field, list_type_with_element,
12    make_scalar_function,
13};
14use arrow::array::{
15    Array, ArrayData, ArrayRef, Capacities, GenericListArray, MutableArrayData,
16    OffsetSizeTrait,
17};
18use arrow::buffer::{NullBuffer, OffsetBuffer};
19use arrow::datatypes::{DataType, Field, FieldRef};
20use datafusion_common::Result;
21use datafusion_common::utils::{
22    base_type, coerced_fixed_size_list_to_list, offset_span_len,
23};
24use datafusion_common::{
25    cast::as_generic_list_array,
26    exec_err, internal_err, plan_err,
27    utils::{list_ndims, take_function_args},
28};
29use datafusion_expr::binary::type_union_resolution;
30use datafusion_expr::{
31    ColumnarValue, Documentation, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl,
32    Signature, Volatility,
33};
34use datafusion_macros::user_doc;
35use itertools::Itertools;
36
37make_udf_expr_and_func!(
38    ArrayAppend,
39    array_append,
40    array element,                                // arg name
41    "appends an element to the end of an array.", // doc
42    array_append_udf                              // internal function name
43);
44
45#[user_doc(
46    doc_section(label = "Array Functions"),
47    description = "Appends an element to the end of an array.",
48    syntax_example = "array_append(array, element)",
49    sql_example = r#"```sql
50> select array_append([1, 2, 3], 4);
51+--------------------------------------+
52| array_append(List([1,2,3]),Int64(4)) |
53+--------------------------------------+
54| [1, 2, 3, 4]                         |
55+--------------------------------------+
56```"#,
57    argument(
58        name = "array",
59        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
60    ),
61    argument(name = "element", description = "Element to append to the array.")
62)]
63#[derive(Debug, PartialEq, Eq, Hash)]
64pub struct ArrayAppend {
65    signature: Signature,
66    aliases: Vec<String>,
67}
68
69impl Default for ArrayAppend {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl ArrayAppend {
76    pub fn new() -> Self {
77        Self {
78            signature: Signature::array_and_element(Volatility::Immutable),
79            aliases: vec![
80                String::from("list_append"),
81                String::from("array_push_back"),
82                String::from("list_push_back"),
83            ],
84        }
85    }
86}
87
88impl ScalarUDFImpl for ArrayAppend {
89    fn name(&self) -> &str {
90        "array_append"
91    }
92
93    fn signature(&self) -> &Signature {
94        &self.signature
95    }
96
97    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
98        internal_err!("return_field_from_args should be used instead")
99    }
100
101    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
102        let [array_field, element_field] =
103            take_function_args(self.name(), args.arg_fields)?;
104        let data_type = append_prepend_return_type(
105            array_field.data_type(),
106            element_field.data_type(),
107            element_field.is_nullable(),
108        );
109        Ok(Arc::new(Field::new(self.name(), data_type, true)))
110    }
111
112    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
113        let return_type = args.return_field.data_type().clone();
114        make_scalar_function(|args: &[ArrayRef]| array_append_inner(args, &return_type))(
115            &args.args,
116        )
117    }
118
119    fn aliases(&self) -> &[String] {
120        &self.aliases
121    }
122
123    fn documentation(&self) -> Option<&Documentation> {
124        self.doc()
125    }
126}
127
128make_udf_expr_and_func!(
129    ArrayPrepend,
130    array_prepend,
131    element array,
132    "Prepends an element to the beginning of an array.",
133    array_prepend_udf
134);
135
136#[user_doc(
137    doc_section(label = "Array Functions"),
138    description = "Prepends an element to the beginning of an array.",
139    syntax_example = "array_prepend(element, array)",
140    sql_example = r#"```sql
141> select array_prepend(1, [2, 3, 4]);
142+---------------------------------------+
143| array_prepend(Int64(1),List([2,3,4])) |
144+---------------------------------------+
145| [1, 2, 3, 4]                          |
146+---------------------------------------+
147```"#,
148    argument(
149        name = "array",
150        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
151    ),
152    argument(name = "element", description = "Element to prepend to the array.")
153)]
154#[derive(Debug, PartialEq, Eq, Hash)]
155pub struct ArrayPrepend {
156    signature: Signature,
157    aliases: Vec<String>,
158}
159
160impl Default for ArrayPrepend {
161    fn default() -> Self {
162        Self::new()
163    }
164}
165
166impl ArrayPrepend {
167    pub fn new() -> Self {
168        Self {
169            signature: Signature::element_and_array(Volatility::Immutable),
170            aliases: vec![
171                String::from("list_prepend"),
172                String::from("array_push_front"),
173                String::from("list_push_front"),
174            ],
175        }
176    }
177}
178
179impl ScalarUDFImpl for ArrayPrepend {
180    fn name(&self) -> &str {
181        "array_prepend"
182    }
183
184    fn signature(&self) -> &Signature {
185        &self.signature
186    }
187
188    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
189        internal_err!("return_field_from_args should be used instead")
190    }
191
192    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
193        let [element_field, array_field] =
194            take_function_args(self.name(), args.arg_fields)?;
195        let data_type = append_prepend_return_type(
196            array_field.data_type(),
197            element_field.data_type(),
198            element_field.is_nullable(),
199        );
200        Ok(Arc::new(Field::new(self.name(), data_type, true)))
201    }
202
203    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
204        let return_type = args.return_field.data_type().clone();
205        make_scalar_function(|args: &[ArrayRef]| array_prepend_inner(args, &return_type))(
206            &args.args,
207        )
208    }
209
210    fn aliases(&self) -> &[String] {
211        &self.aliases
212    }
213
214    fn documentation(&self) -> Option<&Documentation> {
215        self.doc()
216    }
217}
218
219make_udf_expr_and_func!(
220    ArrayConcat,
221    array_concat,
222    "Concatenates arrays.",
223    array_concat_udf
224);
225
226#[user_doc(
227    doc_section(label = "Array Functions"),
228    description = "Concatenates arrays.",
229    syntax_example = "array_concat(array[, ..., array_n])",
230    sql_example = r#"```sql
231> select array_concat([1, 2], [3, 4], [5, 6]);
232+---------------------------------------------------+
233| array_concat(List([1,2]),List([3,4]),List([5,6])) |
234+---------------------------------------------------+
235| [1, 2, 3, 4, 5, 6]                                |
236+---------------------------------------------------+
237```"#,
238    argument(
239        name = "array",
240        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
241    ),
242    argument(
243        name = "array_n",
244        description = "Subsequent array column or literal array to concatenate."
245    )
246)]
247#[derive(Debug, PartialEq, Eq, Hash)]
248pub struct ArrayConcat {
249    signature: Signature,
250    aliases: Vec<String>,
251}
252
253impl Default for ArrayConcat {
254    fn default() -> Self {
255        Self::new()
256    }
257}
258
259impl ArrayConcat {
260    pub fn new() -> Self {
261        Self {
262            signature: Signature::user_defined(Volatility::Immutable),
263            aliases: vec![
264                String::from("array_cat"),
265                String::from("list_concat"),
266                String::from("list_cat"),
267            ],
268        }
269    }
270}
271
272impl ScalarUDFImpl for ArrayConcat {
273    fn name(&self) -> &str {
274        "array_concat"
275    }
276
277    fn signature(&self) -> &Signature {
278        &self.signature
279    }
280
281    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
282        array_concat_return_type(self.name(), arg_types)
283    }
284
285    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
286        let return_type = args.return_field.data_type().clone();
287        make_scalar_function(|args: &[ArrayRef]| {
288            array_concat_with_return_type(args, &return_type)
289        })(&args.args)
290    }
291
292    fn aliases(&self) -> &[String] {
293        &self.aliases
294    }
295
296    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
297        let return_type = self.return_type(arg_types)?;
298        let return_ndims = list_ndims(&return_type);
299
300        Ok(arg_types
301            .iter()
302            .map(|arg_type| {
303                let arg_ndims = list_ndims(arg_type);
304                if arg_ndims == 0 {
305                    return_type.clone()
306                } else {
307                    peel_list_type(&return_type, return_ndims - arg_ndims)
308                }
309            })
310            .collect())
311    }
312
313    fn documentation(&self) -> Option<&Documentation> {
314        self.doc()
315    }
316}
317
318fn array_concat_return_type(name: &str, arg_types: &[DataType]) -> Result<DataType> {
319    let mut max_dims = 0;
320    let wrap_with_large_list = arg_types
321        .iter()
322        .any(|arg_type| matches!(arg_type, DataType::LargeList(_)));
323    let mut aligned_types = Vec::with_capacity(arg_types.len());
324
325    for arg_type in arg_types {
326        match arg_type {
327            DataType::Null
328            | DataType::List(_)
329            | DataType::FixedSizeList(..)
330            | DataType::LargeList(_) => (),
331            arg_type => {
332                return plan_err!("{name} does not support type {arg_type}");
333            }
334        }
335
336        max_dims = max_dims.max(list_ndims(arg_type));
337    }
338
339    if max_dims == 0 {
340        return Ok(DataType::Null);
341    }
342
343    if max_dims == 1 {
344        let element_types: Vec<DataType> = arg_types.iter().map(base_type).collect();
345        let Some(element_type) = type_union_resolution(&element_types) else {
346            return plan_err!(
347                "Failed to unify argument types of {name}: [{}]",
348                arg_types.iter().join(", ")
349            );
350        };
351        return Ok(if wrap_with_large_list {
352            DataType::new_large_list(element_type, true)
353        } else {
354            DataType::new_list(element_type, true)
355        });
356    }
357
358    for arg_type in arg_types {
359        aligned_types.push(align_type_dimensions(
360            arg_type,
361            max_dims,
362            wrap_with_large_list,
363        ));
364    }
365
366    if let Some(return_type) = type_union_resolution(&aligned_types) {
367        Ok(return_type)
368    } else {
369        plan_err!(
370            "Failed to unify argument types of {name}: [{}]",
371            arg_types.iter().join(", ")
372        )
373    }
374}
375
376fn align_type_dimensions(
377    data_type: &DataType,
378    max_dims: u64,
379    wrap_with_large_list: bool,
380) -> DataType {
381    let mut aligned_type = coerced_fixed_size_list_to_list(data_type);
382
383    for _ in list_ndims(data_type)..max_dims {
384        aligned_type = if wrap_with_large_list {
385            DataType::new_large_list(aligned_type, true)
386        } else {
387            DataType::new_list(aligned_type, true)
388        };
389    }
390
391    aligned_type
392}
393
394fn peel_list_type(data_type: &DataType, levels: u64) -> DataType {
395    let mut peeled_type = data_type.clone();
396
397    for _ in 0..levels {
398        peeled_type = match peeled_type {
399            DataType::List(field)
400            | DataType::LargeList(field)
401            | DataType::FixedSizeList(field, _) => field.data_type().clone(),
402            other => other,
403        };
404    }
405
406    peeled_type
407}
408
409pub fn array_concat_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
410    let arg_types: Vec<DataType> =
411        args.iter().map(|arg| arg.data_type().clone()).collect();
412    let return_type = array_concat_return_type("array_concat", &arg_types)?;
413    array_concat_with_return_type(args, &return_type)
414}
415
416fn array_concat_with_return_type(
417    args: &[ArrayRef],
418    return_type: &DataType,
419) -> Result<ArrayRef> {
420    if args.is_empty() {
421        return exec_err!("array_concat expects at least one argument");
422    }
423
424    let mut all_null = true;
425    for arg in args {
426        if arg.data_type() == &DataType::Null {
427            continue;
428        }
429        if arg.null_count() < arg.len() {
430            all_null = false;
431        }
432    }
433
434    if all_null {
435        Ok(arrow::array::make_array(ArrayData::new_null(
436            return_type,
437            args[0].len(),
438        )))
439    } else {
440        let field = list_inner_field("array_concat", return_type)?;
441        match return_type {
442            DataType::List(_) => concat_internal::<i32>(args, Some(&field)),
443            DataType::LargeList(_) => concat_internal::<i64>(args, Some(&field)),
444            arg_type => exec_err!("array_concat does not support type {arg_type}"),
445        }
446    }
447}
448
449/// Return type shared by `array_append` and `array_prepend`: the input list
450/// type, except that its inner field is nullable whenever the appended or
451/// prepended element may be null.
452fn append_prepend_return_type(
453    array_type: &DataType,
454    element_type: &DataType,
455    element_nullable: bool,
456) -> DataType {
457    if array_type.is_null() {
458        DataType::new_list(element_type.clone(), true)
459    } else {
460        list_type_with_element(array_type, element_nullable)
461    }
462}
463
464/// Concatenates the list arrays in `args` row-wise.
465///
466/// `field` is the list field the output must carry. `array_concat` passes the
467/// inner field of its planned return type, and `array_append` / `array_prepend`
468/// pass their input's field. `None` derives the field from the aligned inputs.
469fn concat_internal<O: OffsetSizeTrait>(
470    args: &[ArrayRef],
471    field: Option<&FieldRef>,
472) -> Result<ArrayRef> {
473    let args = align_array_dimensions::<O>(args.to_vec())?;
474
475    let list_arrays = args
476        .iter()
477        .map(|arg| as_generic_list_array::<O>(arg))
478        .collect::<Result<Vec<_>>>()?;
479    let row_count = list_arrays[0].len();
480
481    // Extract underlying values ArrayData from each list array for MutableArrayData.
482    let values_data: Vec<ArrayData> =
483        list_arrays.iter().map(|la| la.values().to_data()).collect();
484    let values_data_refs: Vec<&ArrayData> = values_data.iter().collect();
485
486    // Only reserve for values covered by the visible rows of each input.
487    let total_capacity: usize = list_arrays
488        .iter()
489        .map(|array| offset_span_len(array.offsets()))
490        .sum();
491
492    let mut mutable = MutableArrayData::with_capacities(
493        values_data_refs,
494        false,
495        Capacities::Array(total_capacity),
496    );
497    let mut offsets: Vec<O> = Vec::with_capacity(row_count + 1);
498    offsets.push(O::zero());
499
500    // Compute the output null buffer: a row is null only if null in ALL input
501    // arrays. This is the bitwise OR of validity bits (valid if valid in ANY
502    // input). If any array has no null buffer (all valid), no output row can be
503    // null.
504    let nulls = list_arrays
505        .iter()
506        .filter_map(|la| la.nulls())
507        .collect::<Vec<_>>();
508    let valid = if nulls.len() == list_arrays.len() {
509        nulls
510            .iter()
511            .map(|n| n.inner().clone())
512            .reduce(|a, b| &a | &b)
513            .map(NullBuffer::new)
514    } else {
515        None
516    };
517
518    for row_idx in 0..row_count {
519        for (arr_idx, list_array) in list_arrays.iter().enumerate() {
520            if list_array.is_null(row_idx) {
521                continue;
522            }
523            let start = list_array.offsets()[row_idx].to_usize().unwrap();
524            let end = list_array.offsets()[row_idx + 1].to_usize().unwrap();
525            if start < end {
526                mutable.try_extend(arr_idx, start, end)?;
527            }
528        }
529        offsets.push(O::usize_as(mutable.len()));
530    }
531
532    let field = match field {
533        Some(field) => Arc::clone(field),
534        None => Arc::new(Field::new_list_field(list_arrays[0].value_type(), true)),
535    };
536    let data = mutable.freeze();
537
538    Ok(Arc::new(GenericListArray::<O>::try_new(
539        field,
540        OffsetBuffer::new(offsets.into()),
541        arrow::array::make_array(data),
542        valid,
543    )?))
544}
545
546// Kernel functions
547
548fn array_append_inner(args: &[ArrayRef], return_type: &DataType) -> Result<ArrayRef> {
549    let [array, values] = take_function_args("array_append", args)?;
550    match array.data_type() {
551        DataType::Null => make_array_inner(&[Arc::clone(values)]),
552        DataType::List(_) => general_append_and_prepend::<i32>(args, true, return_type),
553        DataType::LargeList(_) => {
554            general_append_and_prepend::<i64>(args, true, return_type)
555        }
556        arg_type => exec_err!("array_append does not support type {arg_type}"),
557    }
558}
559
560fn array_prepend_inner(args: &[ArrayRef], return_type: &DataType) -> Result<ArrayRef> {
561    let [values, array] = take_function_args("array_prepend", args)?;
562    match array.data_type() {
563        DataType::Null => make_array_inner(&[Arc::clone(values)]),
564        DataType::List(_) => general_append_and_prepend::<i32>(args, false, return_type),
565        DataType::LargeList(_) => {
566            general_append_and_prepend::<i64>(args, false, return_type)
567        }
568        arg_type => exec_err!("array_prepend does not support type {arg_type}"),
569    }
570}
571
572fn general_append_and_prepend<O: OffsetSizeTrait>(
573    args: &[ArrayRef],
574    is_append: bool,
575    return_type: &DataType,
576) -> Result<ArrayRef>
577where
578    i64: TryInto<O>,
579{
580    let (list_array, element_array) = if is_append {
581        let list_array = as_generic_list_array::<O>(&args[0])?;
582        let element_array = &args[1];
583        check_datatypes("array_append", &[element_array, list_array.values()])?;
584        (list_array, element_array)
585    } else {
586        let list_array = as_generic_list_array::<O>(&args[1])?;
587        let element_array = &args[0];
588        check_datatypes("array_prepend", &[list_array.values(), element_array])?;
589        (list_array, element_array)
590    };
591
592    let name = if is_append {
593        "array_append"
594    } else {
595        "array_prepend"
596    };
597    let field = list_inner_field(name, return_type)?;
598
599    let res = match list_array.value_type() {
600        DataType::List(_) | DataType::LargeList(_) => {
601            concat_internal::<O>(args, Some(&field))?
602        }
603        _ => {
604            return generic_append_and_prepend::<O>(
605                list_array,
606                element_array,
607                field,
608                is_append,
609            );
610        }
611    };
612
613    Ok(res)
614}
615
616/// Appends or prepends elements to a ListArray.
617///
618/// This function takes a ListArray, an ArrayRef, a FieldRef, and a boolean flag
619/// indicating whether to append or prepend the elements. It returns a `Result<ArrayRef>`
620/// representing the resulting ListArray after the operation. A NULL list is
621/// treated as an empty list, so its result holds only the element.
622///
623/// # Arguments
624///
625/// * `list_array` - A reference to the ListArray to which elements will be appended/prepended.
626/// * `element_array` - A reference to the Array containing elements to be appended/prepended.
627/// * `field` - The list field the output must carry, taken from the promised return type.
628/// * `is_append` - A boolean flag indicating whether to append (`true`) or prepend (`false`) elements.
629///
630/// # Examples
631///
632/// ```text
633/// generic_append_and_prepend(
634///     [1, 2, 3], 4, append => [1, 2, 3, 4]
635///     5, [6, 7, 8], prepend => [5, 6, 7, 8]
636///     NULL, 4, append => [4]
637/// )
638/// ```
639fn generic_append_and_prepend<O: OffsetSizeTrait>(
640    list_array: &GenericListArray<O>,
641    element_array: &ArrayRef,
642    field: FieldRef,
643    is_append: bool,
644) -> Result<ArrayRef>
645where
646    i64: TryInto<O>,
647{
648    let mut offsets = Vec::with_capacity(list_array.len() + 1);
649    offsets.push(O::usize_as(0));
650    let values = list_array.values();
651    let original_data = values.to_data();
652    let element_data = element_array.to_data();
653    let capacity =
654        Capacities::Array(offset_span_len(list_array.offsets()) + element_array.len());
655
656    let mut mutable = MutableArrayData::with_capacities(
657        vec![&original_data, &element_data],
658        false,
659        capacity,
660    );
661
662    let values_index = 0;
663    let element_index = 1;
664
665    for (row_index, offset_window) in list_array.offsets().windows(2).enumerate() {
666        let (start, end) = if list_array.is_null(row_index) {
667            (0, 0)
668        } else {
669            (
670                offset_window[0].to_usize().unwrap(),
671                offset_window[1].to_usize().unwrap(),
672            )
673        };
674        if is_append {
675            mutable.try_extend(values_index, start, end)?;
676            mutable.try_extend(element_index, row_index, row_index + 1)?;
677        } else {
678            mutable.try_extend(element_index, row_index, row_index + 1)?;
679            mutable.try_extend(values_index, start, end)?;
680        }
681        offsets.push(offsets[row_index] + O::usize_as(end - start + 1));
682    }
683
684    let data = mutable.freeze();
685
686    Ok(Arc::new(GenericListArray::<O>::try_new(
687        field,
688        OffsetBuffer::new(offsets.into()),
689        arrow::array::make_array(data),
690        None,
691    )?))
692}
693
694#[cfg(test)]
695mod tests {
696    use super::*;
697
698    #[test]
699    fn test_concat_sliced_capacity() -> Result<()> {
700        crate::utils::tests::check_sliced_list_behavior(|input| {
701            array_concat_inner(&[Arc::clone(input), Arc::clone(input)])
702        })
703    }
704
705    #[test]
706    fn test_append_sliced_capacity() -> Result<()> {
707        crate::utils::tests::check_sliced_list_behavior(|input| {
708            array_append_inner(
709                &[
710                    Arc::clone(input),
711                    Arc::new(arrow::array::Float64Array::from(vec![3.0; input.len()])),
712                ],
713                input.data_type(),
714            )
715        })
716    }
717}