Skip to main content

datafusion_functions_nested/
length.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_length function.
6
7use crate::utils::make_scalar_function;
8use arrow::array::{
9    Array, ArrayRef, FixedSizeListArray, Int64Array, LargeListArray, ListArray,
10    UInt64Array,
11};
12use arrow::datatypes::{
13    DataType,
14    DataType::{FixedSizeList, LargeList, List, UInt64},
15};
16use datafusion_common::cast::{
17    as_fixed_size_list_array, as_int64_array, as_large_list_array, as_list_array,
18};
19use datafusion_common::{Result, ScalarValue, exec_err};
20use datafusion_expr::{
21    ArrayFunctionArgument, ArrayFunctionSignature, ColumnarValue, Documentation,
22    ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature, Volatility,
23};
24use datafusion_functions::downcast_arg;
25use datafusion_macros::user_doc;
26use std::sync::Arc;
27
28make_udf_expr_and_func!(
29    ArrayLength,
30    array_length,
31    array,
32    "returns the length of the array dimension.",
33    array_length_udf
34);
35
36#[user_doc(
37    doc_section(label = "Array Functions"),
38    description = "Returns the length of the array dimension.",
39    syntax_example = "array_length(array[, dimension])",
40    sql_example = r#"```sql
41> select array_length([1, 2, 3, 4, 5], 1);
42+-------------------------------------------+
43| array_length(List([1,2,3,4,5]), 1)        |
44+-------------------------------------------+
45| 5                                         |
46+-------------------------------------------+
47```"#,
48    argument(
49        name = "array",
50        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
51    ),
52    argument(name = "dimension", description = "Array dimension. Default is 1")
53)]
54#[derive(Debug, PartialEq, Eq, Hash)]
55pub struct ArrayLength {
56    signature: Signature,
57    aliases: Vec<String>,
58}
59
60impl Default for ArrayLength {
61    fn default() -> Self {
62        Self::new()
63    }
64}
65
66impl ArrayLength {
67    pub fn new() -> Self {
68        Self {
69            signature: Signature::one_of(
70                vec![
71                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
72                        arguments: vec![ArrayFunctionArgument::Array],
73                        array_coercion: None,
74                    }),
75                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
76                        arguments: vec![
77                            ArrayFunctionArgument::Array,
78                            ArrayFunctionArgument::Index,
79                        ],
80                        array_coercion: None,
81                    }),
82                ],
83                Volatility::Immutable,
84            ),
85            aliases: vec![String::from("list_length")],
86        }
87    }
88}
89
90impl ScalarUDFImpl for ArrayLength {
91    fn name(&self) -> &str {
92        "array_length"
93    }
94
95    fn signature(&self) -> &Signature {
96        &self.signature
97    }
98
99    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
100        Ok(UInt64)
101    }
102
103    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
104        // An explicit scalar dimension of one uses the same fast path as an
105        // omitted dimension.
106        let args = match args.args.as_slice() {
107            [_, ColumnarValue::Scalar(ScalarValue::Int64(Some(1)))] => &args.args[..1],
108            args => args,
109        };
110        make_scalar_function(array_length_inner)(args)
111    }
112
113    fn aliases(&self) -> &[String] {
114        &self.aliases
115    }
116
117    fn documentation(&self) -> Option<&Documentation> {
118        self.doc()
119    }
120}
121
122fn array_length_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
123    match args {
124        [array] => first_dimension_length(array),
125        [array, dimension] => nth_dimension_length(array, as_int64_array(dimension)?),
126        _ => exec_err!("array_length expects one or two arguments"),
127    }
128}
129
130/// Returns each row's length along the first dimension.
131///
132/// The first dimension counts a row's immediate elements, whatever their
133/// type, so the lengths come straight from the offsets or the fixed width
134/// without slicing out any row.
135fn first_dimension_length(array: &ArrayRef) -> Result<ArrayRef> {
136    let lengths: Vec<u64> = match array.data_type() {
137        List(_) => as_list_array(array)?
138            .offsets()
139            .lengths()
140            .map(|len| len as u64)
141            .collect(),
142        LargeList(_) => as_large_list_array(array)?
143            .offsets()
144            .lengths()
145            .map(|len| len as u64)
146            .collect(),
147        FixedSizeList(_, size) => vec![*size as u64; array.len()],
148        array_type => {
149            return exec_err!("array_length does not support type '{array_type}'");
150        }
151    };
152    Ok(Arc::new(UInt64Array::new(
153        lengths.into(),
154        array.nulls().cloned(),
155    )))
156}
157
158/// Returns each row's length along the dimension given for that row.
159fn nth_dimension_length(array: &ArrayRef, dimension: &Int64Array) -> Result<ArrayRef> {
160    match array.data_type() {
161        List(_) => lengths_at_dimension(as_list_array(array)?.iter(), dimension),
162        LargeList(_) => {
163            lengths_at_dimension(as_large_list_array(array)?.iter(), dimension)
164        }
165        FixedSizeList(..) => {
166            lengths_at_dimension(as_fixed_size_list_array(array)?.iter(), dimension)
167        }
168        array_type => exec_err!("array_length does not support type '{array_type}'"),
169    }
170}
171
172fn lengths_at_dimension(
173    rows: impl Iterator<Item = Option<ArrayRef>>,
174    dimension: &Int64Array,
175) -> Result<ArrayRef> {
176    let result = rows
177        .zip(dimension.iter())
178        .map(|(row, dim)| compute_array_length(row, dim))
179        .collect::<Result<UInt64Array>>()?;
180    Ok(Arc::new(result))
181}
182
183/// Returns the length of a concrete array dimension
184fn compute_array_length(
185    arr: Option<ArrayRef>,
186    dimension: Option<i64>,
187) -> Result<Option<u64>> {
188    let mut current_dimension: i64 = 1;
189    let Some(mut value) = arr else {
190        return Ok(None);
191    };
192    let dimension = match dimension {
193        Some(value) => {
194            if value < 1 {
195                return Ok(None);
196            }
197
198            value
199        }
200        None => return Ok(None),
201    };
202
203    loop {
204        if current_dimension == dimension {
205            return Ok(Some(value.len() as u64));
206        }
207
208        match value.data_type() {
209            List(..) => {
210                value = downcast_arg!(value, ListArray).value(0);
211                current_dimension += 1;
212            }
213            LargeList(..) => {
214                value = downcast_arg!(value, LargeListArray).value(0);
215                current_dimension += 1;
216            }
217            FixedSizeList(_, _) => {
218                value = downcast_arg!(value, FixedSizeListArray).value(0);
219                current_dimension += 1;
220            }
221            _ => return Ok(None),
222        }
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229    use arrow::array::{GenericListArray, Int32Array, OffsetSizeTrait};
230    use arrow::buffer::{NullBuffer, OffsetBuffer};
231    use arrow::datatypes::Field;
232    use datafusion_common::config::ConfigOptions;
233
234    fn check_slices(array: &dyn Array, expected: &UInt64Array) -> Result<()> {
235        let udf = ArrayLength::new();
236        for (offset, len) in [(0, 4), (1, 3), (2, 0)] {
237            let array = array.slice(offset, len);
238            for explicit_dimension in [false, true] {
239                let mut args = vec![ColumnarValue::Array(Arc::clone(&array))];
240                if explicit_dimension {
241                    args.push(ColumnarValue::Scalar(ScalarValue::Int64(Some(1))));
242                }
243                let arg_fields = args
244                    .iter()
245                    .map(|arg| Arc::new(Field::new("arg", arg.data_type(), true)))
246                    .collect();
247                let result = udf.invoke_with_args(ScalarFunctionArgs {
248                    args,
249                    arg_fields,
250                    number_rows: len,
251                    return_field: Arc::new(Field::new("length", UInt64, true)),
252                    config_options: Arc::new(ConfigOptions::default()),
253                })?;
254                let ColumnarValue::Array(result) = result else {
255                    panic!("expected an array result");
256                };
257                assert_eq!(result.as_ref(), &expected.slice(offset, len));
258            }
259        }
260        Ok(())
261    }
262
263    #[test]
264    fn array_length_list_offsets() -> Result<()> {
265        fn check<O: OffsetSizeTrait>() -> Result<()> {
266            let values = Arc::new(Int32Array::new_null(5));
267            let array = GenericListArray::<O>::new(
268                Arc::new(Field::new_list_field(DataType::Int32, true)),
269                OffsetBuffer::from_lengths([1, 2, 0, 2]),
270                values,
271                Some(NullBuffer::from(vec![true, true, true, false])),
272            );
273            check_slices(
274                &array,
275                &UInt64Array::from(vec![Some(1), Some(2), Some(0), None]),
276            )
277        }
278        check::<i32>()?;
279        check::<i64>()
280    }
281
282    #[test]
283    fn array_length_fixed_size_lists() -> Result<()> {
284        for width in [0, 2] {
285            let array = FixedSizeListArray::try_new_with_length(
286                Arc::new(Field::new_list_field(DataType::Int32, true)),
287                width,
288                Arc::new(Int32Array::new_null(4 * width as usize)),
289                Some(NullBuffer::from(vec![true, true, false, true])),
290                4,
291            )?;
292            check_slices(
293                &array,
294                &UInt64Array::from(vec![
295                    Some(width as u64),
296                    Some(width as u64),
297                    None,
298                    Some(width as u64),
299                ]),
300            )?;
301        }
302        Ok(())
303    }
304}