datafusion_functions_nested/
make_array.rs1use 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 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 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
122pub(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#[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 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}