Skip to main content

datafusion_functions_nested/
make_array.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 `make_array` function.
6
7use std::sync::Arc;
8use std::vec;
9
10use crate::utils::make_scalar_function;
11use arrow::array::{
12    Array, ArrayData, ArrayRef, Capacities, GenericListArray, MutableArrayData,
13    NullArray, OffsetSizeTrait, new_null_array,
14};
15use arrow::buffer::OffsetBuffer;
16use arrow::datatypes::DataType;
17use arrow::datatypes::{DataType::Null, Field};
18use datafusion_common::utils::SingleRowListArrayBuilder;
19use datafusion_common::{Result, plan_err};
20use datafusion_expr::binary::{
21    try_type_union_resolution_with_struct, type_union_resolution,
22};
23use datafusion_expr::{
24    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
25    Volatility,
26};
27use datafusion_expr_common::sort_properties::ExprProperties;
28use datafusion_macros::user_doc;
29use itertools::Itertools as _;
30
31make_udf_expr_and_func!(
32    MakeArray,
33    make_array,
34    "Returns an Arrow array using the specified input expressions.",
35    make_array_udf
36);
37
38#[user_doc(
39    doc_section(label = "Array Functions"),
40    description = "Returns an array using the specified input expressions.",
41    syntax_example = "make_array([expression1, ..., expression_n])",
42    sql_example = r#"```sql
43> select make_array(1, 2, 3, 4, 5);
44+----------------------------------------------------------+
45| make_array(Int64(1),Int64(2),Int64(3),Int64(4),Int64(5)) |
46+----------------------------------------------------------+
47| [1, 2, 3, 4, 5]                                          |
48+----------------------------------------------------------+
49```"#,
50    argument(
51        name = "expression_n",
52        description = "Expression to include in the output array. Can be a constant, column, or function, and any combination of arithmetic or string operators."
53    )
54)]
55#[derive(Debug, PartialEq, Eq, Hash)]
56pub struct MakeArray {
57    signature: Signature,
58    aliases: Vec<String>,
59}
60
61impl Default for MakeArray {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl MakeArray {
68    pub fn new() -> Self {
69        Self {
70            signature: Signature::user_defined(Volatility::Immutable),
71            aliases: vec![String::from("make_list")],
72        }
73    }
74}
75
76impl ScalarUDFImpl for MakeArray {
77    fn name(&self) -> &str {
78        "make_array"
79    }
80
81    fn signature(&self) -> &Signature {
82        &self.signature
83    }
84
85    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
86        let element_type = if arg_types.is_empty() {
87            Null
88        } else {
89            // At this point, all the type in array should be coerced to the same one.
90            arg_types[0].to_owned()
91        };
92
93        Ok(DataType::new_list(element_type, true))
94    }
95
96    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
97        make_scalar_function(make_array_inner)(&args.args)
98    }
99
100    fn aliases(&self) -> &[String] {
101        &self.aliases
102    }
103
104    fn strictly_order_preserving(&self, _inputs: &[ExprProperties]) -> Result<bool> {
105        // Not strictly order preserving since null input does not correspond to null output
106        Ok(false)
107    }
108
109    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
110        if arg_types.is_empty() {
111            Ok(vec![])
112        } else {
113            coerce_types_inner(arg_types, self.name())
114        }
115    }
116
117    fn documentation(&self) -> Option<&Documentation> {
118        self.doc()
119    }
120}
121
122/// `make_array_inner` is the implementation of the `make_array` function.
123/// Constructs an array using the input `data` as `ArrayRef`.
124/// Returns a reference-counted `Array` instance result.
125pub(crate) fn make_array_inner(arrays: &[ArrayRef]) -> Result<ArrayRef> {
126    let data_type = arrays.iter().find_map(|arg| {
127        let arg_type = arg.data_type();
128        (!arg_type.is_null()).then_some(arg_type)
129    });
130
131    let data_type = data_type.unwrap_or(&Null);
132    array_array::<i32>(arrays, data_type.clone(), Field::LIST_FIELD_DEFAULT_NAME)
133}
134
135/// Convert zero or more [`ArrayRef`] of the same type into a
136/// `ListArray` or 'LargeListArray' depending on the offset size.
137///
138/// Returns empty `ListArray` if input has zero array.
139///
140/// # Example (non nested)
141///
142/// Calling `array(col1, col2)` where col1 and col2 are non nested
143/// would return a single new `ListArray`, where each row was a list
144/// of 2 elements:
145///
146/// ```text
147/// ┌─────────┐   ┌─────────┐           ┌──────────────┐
148/// │ ┌─────┐ │   │ ┌─────┐ │           │ ┌──────────┐ │
149/// │ │  A  │ │   │ │  X  │ │           │ │  [A, X]  │ │
150/// │ ├─────┤ │   │ ├─────┤ │           │ ├──────────┤ │
151/// │ │NULL │ │   │ │  Y  │ │──────────▶│ │[NULL, Y] │ │
152/// │ ├─────┤ │   │ ├─────┤ │           │ ├──────────┤ │
153/// │ │  C  │ │   │ │  Z  │ │           │ │  [C, Z]  │ │
154/// │ └─────┘ │   │ └─────┘ │           │ └──────────┘ │
155/// └─────────┘   └─────────┘           └──────────────┘
156///   col1           col2                    output
157/// ```
158///
159/// # Example (nested)
160///
161/// Calling `array(col1, col2)` where col1 and col2 are lists
162/// would return a single new `ListArray`, where each row was a list
163/// of the corresponding elements of col1 and col2.
164///
165/// ``` text
166/// ┌──────────────┐   ┌──────────────┐        ┌─────────────────────────────┐
167/// │ ┌──────────┐ │   │ ┌──────────┐ │        │ ┌────────────────────────┐  │
168/// │ │  [A, X]  │ │   │ │    []    │ │        │ │    [[A, X], []]        │  │
169/// │ ├──────────┤ │   │ ├──────────┤ │        │ ├────────────────────────┤  │
170/// │ │[NULL, Y] │ │   │ │[Q, R, S] │ │───────▶│ │ [[NULL, Y], [Q, R, S]] │  │
171/// │ ├──────────┤ │   │ ├──────────┤ │        │ ├────────────────────────│  │
172/// │ │  [C, Z]  │ │   │ │   NULL   │ │        │ │    [[C, Z], NULL]      │  │
173/// │ └──────────┘ │   │ └──────────┘ │        │ └────────────────────────┘  │
174/// └──────────────┘   └──────────────┘        └─────────────────────────────┘
175///      col1               col2                         output
176/// ```
177///
178/// # Public Only for Internal Use:
179/// `datafusion-spark` uses this helper to construct arrays with its element field
180/// name. This implementation detail is not part of the supported public API.
181#[doc(hidden)]
182pub fn array_array<O: OffsetSizeTrait>(
183    args: &[ArrayRef],
184    data_type: DataType,
185    field_name: &str,
186) -> Result<ArrayRef> {
187    if args.is_empty() {
188        // If input is empty, combined output is an empty array with `Null` data type
189        let array = new_null_array(&Null, 0);
190        return Ok(Arc::new(
191            SingleRowListArrayBuilder::new(array).build_list_array(),
192        ));
193    }
194
195    let mut data = Vec::with_capacity(args.len());
196    let mut total_len = 0;
197    for arg in args {
198        let arg_data = if arg.as_any().is::<NullArray>() {
199            ArrayData::new_empty(&data_type)
200        } else {
201            arg.to_data()
202        };
203        total_len += arg_data.len();
204        data.push(arg_data);
205    }
206
207    let mut offsets: Vec<O> = Vec::with_capacity(total_len);
208    offsets.push(O::usize_as(0));
209
210    let capacity = Capacities::Array(total_len);
211    let data_ref = data.iter().collect::<Vec<_>>();
212    let mut mutable = MutableArrayData::with_capacities(data_ref, true, capacity);
213
214    let num_rows = args[0].len();
215    for row_idx in 0..num_rows {
216        for (arr_idx, arg) in args.iter().enumerate() {
217            if !arg.as_any().is::<NullArray>()
218                && !arg.is_null(row_idx)
219                && arg.is_valid(row_idx)
220            {
221                mutable.try_extend(arr_idx, row_idx, row_idx + 1)?;
222            } else {
223                mutable.try_extend_nulls(1)?;
224            }
225        }
226        offsets.push(O::usize_as(mutable.len()));
227    }
228    let data = mutable.freeze();
229
230    Ok(Arc::new(GenericListArray::<O>::try_new(
231        Arc::new(Field::new(field_name, data_type, true)),
232        OffsetBuffer::new(offsets.into()),
233        arrow::array::make_array(data),
234        None,
235    )?))
236}
237
238pub fn coerce_types_inner(arg_types: &[DataType], name: &str) -> Result<Vec<DataType>> {
239    if let Ok(unified) = try_type_union_resolution_with_struct(arg_types) {
240        return Ok(unified);
241    }
242
243    if let Some(unified) = type_union_resolution(arg_types) {
244        Ok(vec![unified; arg_types.len()])
245    } else {
246        plan_err!(
247            "Failed to unify argument types of {}: [{}]",
248            name,
249            arg_types.iter().join(", ")
250        )
251    }
252}