datafusion_functions_nested/
dimension.rs1use arrow::array::{Array, ArrayRef, ListArray, UInt64Array};
8use arrow::datatypes::{
9 DataType,
10 DataType::{FixedSizeList, LargeList, List, Null, UInt64},
11 UInt64Type,
12};
13
14use datafusion_common::cast::{
15 as_fixed_size_list_array, as_large_list_array, as_list_array,
16};
17use datafusion_common::{Result, exec_err, utils::take_function_args};
18
19use crate::utils::{compute_array_dims, make_scalar_function};
20use datafusion_common::utils::list_ndims;
21use datafusion_expr::{
22 ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
23 Volatility,
24};
25use datafusion_macros::user_doc;
26use itertools::Itertools;
27use std::sync::Arc;
28
29make_udf_expr_and_func!(
30 ArrayDims,
31 array_dims,
32 array,
33 "returns an array of the array's dimensions.",
34 array_dims_udf
35);
36
37#[user_doc(
38 doc_section(label = "Array Functions"),
39 description = "Returns an array of the array's dimensions.",
40 syntax_example = "array_dims(array)",
41 sql_example = r#"```sql
42> select array_dims([[1, 2, 3], [4, 5, 6]]);
43+---------------------------------+
44| array_dims(List([1,2,3,4,5,6])) |
45+---------------------------------+
46| [2, 3] |
47+---------------------------------+
48```"#,
49 argument(
50 name = "array",
51 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
52 )
53)]
54#[derive(Debug, PartialEq, Eq, Hash)]
55pub struct ArrayDims {
56 signature: Signature,
57 aliases: Vec<String>,
58}
59
60impl Default for ArrayDims {
61 fn default() -> Self {
62 Self::new()
63 }
64}
65
66impl ArrayDims {
67 pub fn new() -> Self {
68 Self {
69 signature: Signature::arrays(1, None, Volatility::Immutable),
70 aliases: vec!["list_dims".to_string()],
71 }
72 }
73}
74
75impl ScalarUDFImpl for ArrayDims {
76 fn name(&self) -> &str {
77 "array_dims"
78 }
79
80 fn signature(&self) -> &Signature {
81 &self.signature
82 }
83
84 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
85 Ok(DataType::new_list(UInt64, true))
86 }
87
88 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
89 make_scalar_function(array_dims_inner)(&args.args)
90 }
91
92 fn aliases(&self) -> &[String] {
93 &self.aliases
94 }
95
96 fn documentation(&self) -> Option<&Documentation> {
97 self.doc()
98 }
99}
100
101make_udf_expr_and_func!(
102 ArrayNdims,
103 array_ndims,
104 array,
105 "returns the number of dimensions of the array.",
106 array_ndims_udf
107);
108
109#[user_doc(
110 doc_section(label = "Array Functions"),
111 description = "Returns the number of dimensions of the array.",
112 syntax_example = "array_ndims(array)",
113 sql_example = r#"```sql
114> select array_ndims([[1, 2, 3], [4, 5, 6]]);
115+----------------------------------+
116| array_ndims(List([1,2,3,4,5,6])) |
117+----------------------------------+
118| 2 |
119+----------------------------------+
120```"#,
121 argument(
122 name = "array",
123 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
124 )
125)]
126#[derive(Debug, PartialEq, Eq, Hash)]
127pub(super) struct ArrayNdims {
128 signature: Signature,
129 aliases: Vec<String>,
130}
131impl ArrayNdims {
132 pub fn new() -> Self {
133 Self {
134 signature: Signature::arrays(1, None, Volatility::Immutable),
135 aliases: vec![String::from("list_ndims")],
136 }
137 }
138}
139
140impl ScalarUDFImpl for ArrayNdims {
141 fn name(&self) -> &str {
142 "array_ndims"
143 }
144
145 fn signature(&self) -> &Signature {
146 &self.signature
147 }
148
149 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
150 Ok(UInt64)
151 }
152
153 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
154 make_scalar_function(array_ndims_inner)(&args.args)
155 }
156
157 fn aliases(&self) -> &[String] {
158 &self.aliases
159 }
160
161 fn documentation(&self) -> Option<&Documentation> {
162 self.doc()
163 }
164}
165
166fn array_dims_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
167 let [array] = take_function_args("array_dims", args)?;
168 let data: Vec<_> = match array.data_type() {
169 List(_) => as_list_array(&array)?
170 .iter()
171 .map(compute_array_dims)
172 .try_collect()?,
173 LargeList(_) => as_large_list_array(&array)?
174 .iter()
175 .map(compute_array_dims)
176 .try_collect()?,
177 FixedSizeList(..) => as_fixed_size_list_array(&array)?
178 .iter()
179 .map(compute_array_dims)
180 .try_collect()?,
181 arg_type => {
182 return exec_err!("array_dims does not support type {arg_type}");
183 }
184 };
185
186 let result = ListArray::from_iter_primitive::<UInt64Type, _, _>(data);
187 Ok(Arc::new(result))
188}
189
190fn array_ndims_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
191 let [array] = take_function_args("array_ndims", args)?;
192
193 fn general_list_ndims(array: &ArrayRef) -> Result<ArrayRef> {
194 let ndims = list_ndims(array.data_type());
195 let data = vec![ndims; array.len()];
196 let result = UInt64Array::new(data.into(), array.nulls().cloned());
197 Ok(Arc::new(result))
198 }
199
200 match array.data_type() {
201 Null => Ok(Arc::new(UInt64Array::new_null(array.len()))),
202 List(_) | LargeList(_) | FixedSizeList(..) => general_list_ndims(array),
203 arg_type => exec_err!("array_ndims does not support type {arg_type}"),
204 }
205}