Skip to main content

datafusion_functions_nested/
extract.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_element, array_slice, array_pop_front, array_pop_back, and array_any_value functions.
6
7use arrow::array::{
8    Array, ArrayRef, Capacities, GenericListArray, GenericListViewArray, Int64Array,
9    MutableArrayData, NullArray, OffsetSizeTrait,
10};
11use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
12use arrow::datatypes::DataType;
13use arrow::datatypes::DataType::{
14    FixedSizeList, LargeList, LargeListView, List, ListView, Null,
15};
16use datafusion_common::cast::as_large_list_array;
17use datafusion_common::cast::as_list_array;
18use datafusion_common::cast::{
19    as_int64_array, as_large_list_view_array, as_list_view_array,
20};
21use datafusion_common::utils::ListCoercion;
22use datafusion_common::utils::offset_span_len;
23use datafusion_common::{
24    Result, exec_datafusion_err, exec_err, internal_datafusion_err, plan_err,
25    utils::take_function_args,
26};
27use datafusion_expr::{
28    ArrayFunctionArgument, ArrayFunctionSignature, Expr, ScalarFunctionArgs,
29    TypeSignature,
30};
31use datafusion_expr::{
32    ColumnarValue, Documentation, ScalarUDFImpl, Signature, Volatility,
33};
34use datafusion_macros::user_doc;
35use std::sync::Arc;
36
37use crate::utils::make_scalar_function;
38
39// Create static instances of ScalarUDFs for each function
40make_udf_expr_and_func!(
41    ArrayElement,
42    array_element,
43    array element,
44    "extracts the element with the index n from the array.",
45    array_element_udf
46);
47
48create_func!(ArraySlice, array_slice_udf);
49
50make_udf_expr_and_func!(
51    ArrayPopFront,
52    array_pop_front,
53    array,
54    "returns the array without the first element.",
55    array_pop_front_udf
56);
57
58make_udf_expr_and_func!(
59    ArrayPopBack,
60    array_pop_back,
61    array,
62    "returns the array without the last element.",
63    array_pop_back_udf
64);
65
66make_udf_expr_and_func!(
67    ArrayAnyValue,
68    array_any_value,
69    array,
70    "returns the first non-null element in the array.",
71    array_any_value_udf
72);
73
74#[user_doc(
75    doc_section(label = "Array Functions"),
76    description = "Extracts the element with the index n from the array.",
77    syntax_example = "array_element(array, index)",
78    sql_example = r#"```sql
79> select array_element([1, 2, 3, 4], 3);
80+-----------------------------------------+
81| array_element(List([1,2,3,4]),Int64(3)) |
82+-----------------------------------------+
83| 3                                       |
84+-----------------------------------------+
85```"#,
86    argument(
87        name = "array",
88        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
89    ),
90    argument(
91        name = "index",
92        description = "Index to extract the element from the array."
93    )
94)]
95#[derive(Debug, PartialEq, Eq, Hash)]
96pub struct ArrayElement {
97    signature: Signature,
98    aliases: Vec<String>,
99}
100
101impl Default for ArrayElement {
102    fn default() -> Self {
103        Self::new()
104    }
105}
106
107impl ArrayElement {
108    pub fn new() -> Self {
109        Self {
110            signature: Signature::array_and_index(Volatility::Immutable),
111            aliases: vec![
112                String::from("array_extract"),
113                String::from("list_element"),
114                String::from("list_extract"),
115            ],
116        }
117    }
118}
119
120impl ScalarUDFImpl for ArrayElement {
121    fn name(&self) -> &str {
122        "array_element"
123    }
124
125    fn schema_name(&self, args: &[Expr]) -> Result<String> {
126        let args_name = args
127            .iter()
128            .map(|e| e.schema_name().to_string())
129            .collect::<Vec<_>>();
130        if args_name.len() != 2 {
131            return exec_err!("expect 2 args, got {}", args_name.len());
132        }
133
134        Ok(format!("{}[{}]", args_name[0], args_name[1]))
135    }
136
137    fn signature(&self) -> &Signature {
138        &self.signature
139    }
140
141    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
142        match &arg_types[0] {
143            Null => Ok(Null),
144            List(field) | LargeList(field) => Ok(field.data_type().clone()),
145            arg_type => plan_err!("{} does not support type {arg_type}", self.name()),
146        }
147    }
148
149    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
150        make_scalar_function(array_element_inner)(&args.args)
151    }
152
153    fn aliases(&self) -> &[String] {
154        &self.aliases
155    }
156
157    fn documentation(&self) -> Option<&Documentation> {
158        self.doc()
159    }
160}
161
162/// array_element SQL function
163///
164/// There are two arguments for array_element, the first one is the array, the second one is the 1-indexed index.
165/// `array_element(array, index)`
166///
167/// For example:
168/// > array_element(\[1, 2, 3], 2) -> 2
169fn array_element_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
170    let [array, indexes] = take_function_args("array_element", args)?;
171
172    match &array.data_type() {
173        Null => Ok(Arc::new(NullArray::new(array.len()))),
174        List(_) => {
175            let array = as_list_array(&array)?;
176            let indexes = as_int64_array(&indexes)?;
177            general_array_element::<i32>(array, indexes)
178        }
179        LargeList(_) => {
180            let array = as_large_list_array(&array)?;
181            let indexes = as_int64_array(&indexes)?;
182            general_array_element::<i64>(array, indexes)
183        }
184        arg_type => {
185            exec_err!("array_element does not support type {arg_type}")
186        }
187    }
188}
189
190fn general_array_element<O: OffsetSizeTrait>(
191    array: &GenericListArray<O>,
192    indexes: &Int64Array,
193) -> Result<ArrayRef>
194where
195    i64: TryInto<O>,
196{
197    let values = array.values();
198    if values.data_type().is_null() {
199        return Ok(Arc::new(NullArray::new(array.len())));
200    }
201
202    let original_data = values.to_data();
203    let capacity = Capacities::Array(array.len());
204
205    // use_nulls: true, we don't construct List for array_element, so we need explicit nulls.
206    let mut mutable =
207        MutableArrayData::with_capacities(vec![&original_data], true, capacity);
208
209    fn adjusted_array_index<O: OffsetSizeTrait>(index: i64, len: O) -> Result<Option<O>>
210    where
211        i64: TryInto<O>,
212    {
213        let index: O = index.try_into().map_err(|_| {
214            exec_datafusion_err!("array_element got invalid index: {index}")
215        })?;
216        // 0 ~ len - 1
217        let adjusted_zero_index = if index < O::usize_as(0) {
218            index + len
219        } else {
220            index - O::usize_as(1)
221        };
222
223        if O::usize_as(0) <= adjusted_zero_index && adjusted_zero_index < len {
224            Ok(Some(adjusted_zero_index))
225        } else {
226            // Out of bounds
227            Ok(None)
228        }
229    }
230
231    for (row_index, offset_window) in array.offsets().windows(2).enumerate() {
232        let start = offset_window[0];
233        let end = offset_window[1];
234        let len = end - start;
235
236        // array or index is null
237        if array.is_null(row_index) || indexes.is_null(row_index) {
238            mutable.try_extend_nulls(1)?;
239            continue;
240        }
241
242        let index = adjusted_array_index::<O>(indexes.value(row_index), len)?;
243
244        if let Some(index) = index {
245            let start = start.as_usize() + index.as_usize();
246            mutable.try_extend(0, start, start + 1_usize)?;
247        } else {
248            // Index out of bounds
249            mutable.try_extend_nulls(1)?;
250        }
251    }
252
253    let data = mutable.freeze();
254    Ok(arrow::array::make_array(data))
255}
256
257#[doc = "returns a slice of the array."]
258pub fn array_slice(array: Expr, begin: Expr, end: Expr, stride: Option<Expr>) -> Expr {
259    let args = match stride {
260        Some(stride) => vec![array, begin, end, stride],
261        None => vec![array, begin, end],
262    };
263    array_slice_udf().call(args)
264}
265
266#[user_doc(
267    doc_section(label = "Array Functions"),
268    description = "Returns a slice of the array based on 1-indexed start and end positions.",
269    syntax_example = "array_slice(array, begin, end[, stride])",
270    sql_example = r#"```sql
271> select array_slice([1, 2, 3, 4, 5, 6, 7, 8], 3, 6);
272+--------------------------------------------------------+
273| array_slice(List([1,2,3,4,5,6,7,8]),Int64(3),Int64(6)) |
274+--------------------------------------------------------+
275| [3, 4, 5, 6]                                           |
276+--------------------------------------------------------+
277```"#,
278    argument(
279        name = "array",
280        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
281    ),
282    argument(
283        name = "begin",
284        description = "Index of the first element. If negative, it counts backward from the end of the array."
285    ),
286    argument(
287        name = "end",
288        description = "Index of the last element. If negative, it counts backward from the end of the array."
289    ),
290    argument(
291        name = "stride",
292        description = "Stride of the array slice. The default is 1."
293    )
294)]
295#[derive(Debug, PartialEq, Eq, Hash)]
296pub(super) struct ArraySlice {
297    signature: Signature,
298    aliases: Vec<String>,
299}
300
301impl ArraySlice {
302    pub fn new() -> Self {
303        Self {
304            signature: Signature::one_of(
305                vec![
306                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
307                        arguments: vec![
308                            ArrayFunctionArgument::Array,
309                            ArrayFunctionArgument::Index,
310                            ArrayFunctionArgument::Index,
311                        ],
312                        array_coercion: Some(ListCoercion::FixedSizedListToList),
313                    }),
314                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
315                        arguments: vec![
316                            ArrayFunctionArgument::Array,
317                            ArrayFunctionArgument::Index,
318                            ArrayFunctionArgument::Index,
319                            ArrayFunctionArgument::Index,
320                        ],
321                        array_coercion: Some(ListCoercion::FixedSizedListToList),
322                    }),
323                ],
324                Volatility::Immutable,
325            ),
326            aliases: vec![String::from("list_slice")],
327        }
328    }
329}
330
331impl ScalarUDFImpl for ArraySlice {
332    fn schema_name(&self, args: &[Expr]) -> Result<String> {
333        let args_name = args
334            .iter()
335            .map(|e| e.schema_name().to_string())
336            .collect::<Vec<_>>();
337        if let Some((arr, indexes)) = args_name.split_first() {
338            Ok(format!("{arr}[{}]", indexes.join(":")))
339        } else {
340            exec_err!("no argument")
341        }
342    }
343
344    fn name(&self) -> &str {
345        "array_slice"
346    }
347
348    fn signature(&self) -> &Signature {
349        &self.signature
350    }
351
352    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
353        Ok(arg_types[0].clone())
354    }
355
356    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
357        make_scalar_function(array_slice_inner)(&args.args)
358    }
359
360    fn aliases(&self) -> &[String] {
361        &self.aliases
362    }
363
364    fn documentation(&self) -> Option<&Documentation> {
365        self.doc()
366    }
367}
368
369/// array_slice SQL function
370///
371/// We follow the behavior of array_slice in DuckDB
372/// Note that array_slice is 1-indexed. And there are two additional arguments `from` and `to` in array_slice.
373///
374/// > array_slice(array, from, to)
375///
376/// Positive index is treated as the index from the start of the array. If the
377/// `from` index is smaller than 1, it is treated as 1. If the `to` index is larger than the
378/// length of the array, it is treated as the length of the array.
379///
380/// Negative index is treated as the index from the end of the array. If the index
381/// is larger than the length of the array, it is NOT VALID, either in `from` or `to`.
382/// The `to` index is exclusive like python slice syntax.
383///
384/// See test cases in `array.slt` for more details.
385fn array_slice_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
386    let args_len = args.len();
387    if args_len != 3 && args_len != 4 {
388        return exec_err!("array_slice needs three or four arguments");
389    }
390
391    let stride = if args_len == 4 {
392        Some(as_int64_array(&args[3])?)
393    } else {
394        None
395    };
396
397    let from_array = as_int64_array(&args[1])?;
398    let to_array = as_int64_array(&args[2])?;
399
400    let array_data_type = args[0].data_type();
401    match array_data_type {
402        List(_) => {
403            let array = as_list_array(&args[0])?;
404            general_array_slice::<i32>(array, from_array, to_array, stride)
405        }
406        LargeList(_) => {
407            let array = as_large_list_array(&args[0])?;
408            general_array_slice::<i64>(array, from_array, to_array, stride)
409        }
410        ListView(_) => {
411            let array = as_list_view_array(&args[0])?;
412            general_list_view_array_slice::<i32>(array, from_array, to_array, stride)
413        }
414        LargeListView(_) => {
415            let array = as_large_list_view_array(&args[0])?;
416            general_list_view_array_slice::<i64>(array, from_array, to_array, stride)
417        }
418        _ => exec_err!("array_slice does not support type: {}", array_data_type),
419    }
420}
421
422fn adjusted_from_index<O: OffsetSizeTrait>(index: i64, len: O) -> Result<Option<O>>
423where
424    i64: TryInto<O>,
425{
426    // 0 ~ len - 1
427    let adjusted_zero_index = if index < 0 {
428        if let Ok(index) = index.try_into() {
429            // When index < 0 and -index > length, index is clamped to the beginning of the list.
430            // Otherwise, when index < 0, the index is counted from the end of the list.
431            //
432            // Note, we actually test the contrapositive, index < -length, because negating a
433            // negative will panic if the negative is equal to the smallest representable value
434            // while negating a positive is always safe.
435            if index < (O::zero() - O::one()) * len {
436                O::zero()
437            } else {
438                index + len
439            }
440        } else {
441            return exec_err!("array_slice got invalid index: {}", index);
442        }
443    } else {
444        // array_slice(arr, 1, to) is the same as array_slice(arr, 0, to)
445        if let Ok(index) = index.try_into() {
446            std::cmp::max(index - O::usize_as(1), O::usize_as(0))
447        } else {
448            return exec_err!("array_slice got invalid index: {}", index);
449        }
450    };
451
452    if O::usize_as(0) <= adjusted_zero_index && adjusted_zero_index < len {
453        Ok(Some(adjusted_zero_index))
454    } else {
455        // Out of bounds
456        Ok(None)
457    }
458}
459
460fn adjusted_to_index<O: OffsetSizeTrait>(index: i64, len: O) -> Result<Option<O>>
461where
462    i64: TryInto<O>,
463{
464    // 0 ~ len - 1
465    let adjusted_zero_index = if index < 0 {
466        // array_slice in duckdb with negative to_index is python-like, so index itself is exclusive
467        if let Ok(index) = index.try_into() {
468            index + len
469        } else {
470            return exec_err!("array_slice got invalid index: {}", index);
471        }
472    } else {
473        // array_slice(arr, from, len + 1) is the same as array_slice(arr, from, len)
474        if let Ok(index) = index.try_into() {
475            std::cmp::min(index - O::usize_as(1), len - O::usize_as(1))
476        } else {
477            return exec_err!("array_slice got invalid index: {}", index);
478        }
479    };
480
481    if O::usize_as(0) <= adjusted_zero_index && adjusted_zero_index < len {
482        Ok(Some(adjusted_zero_index))
483    } else {
484        // Out of bounds
485        Ok(None)
486    }
487}
488
489/// Internal plan describing how to materialize a single row's slice after
490/// the slice bounds/stride have been normalized. Both list layouts consume
491/// this to drive their copy logic.
492enum SlicePlan<O: OffsetSizeTrait> {
493    /// No values should be produced.
494    Empty,
495    /// A contiguous run starting at `start` (relative to the row) with `len`
496    /// elements can be copied in one go.
497    Contiguous { start: O, len: O },
498    /// Arbitrary positions (already relative to the row), written to the
499    /// caller's index buffer, must be copied in sequence.
500    Indices,
501}
502
503/// Produces a [`SlicePlan`] for the given logical slice parameters.
504fn compute_slice_plan<O: OffsetSizeTrait>(
505    len: O,
506    from_raw: i64,
507    to_raw: i64,
508    stride_raw: Option<i64>,
509    indices: &mut Vec<O>,
510) -> Result<SlicePlan<O>>
511where
512    i64: TryInto<O>,
513{
514    if len == O::usize_as(0) {
515        return Ok(SlicePlan::Empty);
516    }
517
518    let from_index = adjusted_from_index::<O>(from_raw, len)?;
519    let to_index = adjusted_to_index::<O>(to_raw, len)?;
520
521    let (Some(from), Some(to)) = (from_index, to_index) else {
522        return Ok(SlicePlan::Empty);
523    };
524
525    let stride_value = stride_raw.unwrap_or(1);
526    if stride_value == 0 {
527        return exec_err!(
528            "array_slice got invalid stride: {:?}, it cannot be 0",
529            stride_value
530        );
531    }
532
533    if (from < to && stride_value.is_negative())
534        || (from > to && stride_value.is_positive())
535    {
536        return Ok(SlicePlan::Empty);
537    }
538
539    let stride: O = stride_value.try_into().map_err(|_| {
540        internal_datafusion_err!("array_slice got invalid stride: {}", stride_value)
541    })?;
542
543    if from <= to && stride_value.is_positive() {
544        if stride_value == 1 {
545            let len = to - from + O::usize_as(1);
546            Ok(SlicePlan::Contiguous { start: from, len })
547        } else {
548            indices.clear();
549            let mut index = from;
550            while index <= to {
551                indices.push(index);
552                index += stride;
553            }
554            Ok(SlicePlan::Indices)
555        }
556    } else {
557        indices.clear();
558        let mut index = from;
559        while index >= to {
560            indices.push(index);
561            index += stride;
562        }
563        Ok(SlicePlan::Indices)
564    }
565}
566
567/// Combine null bitmaps from all slice inputs into a single mask.
568fn combine_input_nulls(
569    array: &dyn Array,
570    from_array: &Int64Array,
571    to_array: &Int64Array,
572    stride: Option<&Int64Array>,
573) -> Option<NullBuffer> {
574    NullBuffer::union_many([
575        array.nulls(),
576        from_array.nulls(),
577        to_array.nulls(),
578        stride.and_then(|s| s.nulls()),
579    ])
580}
581
582fn general_array_slice<O: OffsetSizeTrait>(
583    array: &GenericListArray<O>,
584    from_array: &Int64Array,
585    to_array: &Int64Array,
586    stride: Option<&Int64Array>,
587) -> Result<ArrayRef>
588where
589    i64: TryInto<O>,
590{
591    let values = array.values();
592    let original_data = values.to_data();
593    let capacity = Capacities::Array(offset_span_len(array.offsets()));
594    // Carry the input's list field through to the output so that the returned
595    // type matches the one promised by `return_type` / `return_field_from_args`,
596    // including the field name, nullability and metadata.
597    let field = Arc::clone(array.value_field());
598
599    // `use_nulls` is false because we never call `try_extend_nulls`: null rows are
600    // emitted as empty slices. Arrow still allocates a validity buffer on its own
601    // if the child array has nulls.
602    let mut mutable =
603        MutableArrayData::with_capacities(vec![&original_data], false, capacity);
604
605    // We have the slice syntax compatible with DuckDB v0.8.1.
606    // The rule `adjusted_from_index` and `adjusted_to_index` follows the rule of array_slice in duckdb.
607
608    let mut offsets = Vec::with_capacity(array.len() + 1);
609    offsets.push(O::usize_as(0));
610    let mut indices = Vec::new();
611
612    let nulls = combine_input_nulls(array, from_array, to_array, stride);
613
614    for (row_index, offset_window) in array.offsets().windows(2).enumerate() {
615        let start = offset_window[0];
616        let end = offset_window[1];
617        let len = end - start;
618
619        // The row is null, so its contents are never observed. Emit an empty
620        // slice rather than a null child element: the input's list field may be
621        // non-nullable, in which case a null child would be invalid.
622        if nulls.as_ref().is_some_and(|n| n.is_null(row_index)) {
623            offsets.push(offsets[row_index]);
624            continue;
625        }
626
627        // Empty arrays always return an empty array.
628        if len == O::usize_as(0) {
629            offsets.push(offsets[row_index]);
630            continue;
631        }
632
633        let slice_plan = compute_slice_plan::<O>(
634            len,
635            from_array.value(row_index),
636            to_array.value(row_index),
637            stride.map(|s| s.value(row_index)),
638            &mut indices,
639        )?;
640
641        match slice_plan {
642            SlicePlan::Empty => offsets.push(offsets[row_index]),
643            SlicePlan::Contiguous {
644                start: rel_start,
645                len: slice_len,
646            } => {
647                let start_index = (start + rel_start).to_usize().unwrap();
648                let end_index = (start + rel_start + slice_len).to_usize().unwrap();
649                mutable.try_extend(0, start_index, end_index)?;
650                offsets.push(offsets[row_index] + slice_len);
651            }
652            SlicePlan::Indices => {
653                let count = indices.len();
654                for &rel_index in &indices {
655                    let absolute_index = (start + rel_index).to_usize().unwrap();
656                    mutable.try_extend(0, absolute_index, absolute_index + 1)?;
657                }
658                offsets.push(offsets[row_index] + O::usize_as(count));
659            }
660        }
661    }
662
663    let data = mutable.freeze();
664
665    Ok(Arc::new(GenericListArray::<O>::try_new(
666        field,
667        OffsetBuffer::<O>::new(offsets.into()),
668        arrow::array::make_array(data),
669        nulls,
670    )?))
671}
672
673fn general_list_view_array_slice<O: OffsetSizeTrait>(
674    array: &GenericListViewArray<O>,
675    from_array: &Int64Array,
676    to_array: &Int64Array,
677    stride: Option<&Int64Array>,
678) -> Result<ArrayRef>
679where
680    i64: TryInto<O>,
681{
682    let values = array.values();
683    let original_data = values.to_data();
684    let capacity = Capacities::Array(original_data.len());
685    let field = Arc::clone(array.value_field());
686
687    // See the note on `use_nulls` in `general_array_slice`.
688    let mut mutable =
689        MutableArrayData::with_capacities(vec![&original_data], false, capacity);
690
691    // We must build `offsets` and `sizes` buffers manually as ListView does not enforce
692    // monotonically increasing offsets.
693    let mut offsets = Vec::with_capacity(array.len());
694    let mut sizes = Vec::with_capacity(array.len());
695    let mut current_offset = O::usize_as(0);
696    let mut indices = Vec::new();
697
698    let nulls = combine_input_nulls(array, from_array, to_array, stride);
699
700    for row_index in 0..array.len() {
701        if nulls.as_ref().is_some_and(|n| n.is_null(row_index)) {
702            offsets.push(current_offset);
703            sizes.push(O::usize_as(0));
704            continue;
705        }
706
707        let len = array.value_size(row_index);
708
709        // Empty arrays always return an empty array.
710        if len == O::usize_as(0) {
711            offsets.push(current_offset);
712            sizes.push(O::usize_as(0));
713            continue;
714        }
715
716        let slice_plan = compute_slice_plan::<O>(
717            len,
718            from_array.value(row_index),
719            to_array.value(row_index),
720            stride.map(|s| s.value(row_index)),
721            &mut indices,
722        )?;
723
724        let start = array.value_offset(row_index);
725        match slice_plan {
726            SlicePlan::Empty => {
727                offsets.push(current_offset);
728                sizes.push(O::usize_as(0));
729            }
730            SlicePlan::Contiguous {
731                start: rel_start,
732                len: slice_len,
733            } => {
734                let start_index = (start + rel_start).to_usize().unwrap();
735                let end_index = (start + rel_start + slice_len).to_usize().unwrap();
736                mutable.try_extend(0, start_index, end_index)?;
737                offsets.push(current_offset);
738                sizes.push(slice_len);
739                current_offset += slice_len;
740            }
741            SlicePlan::Indices => {
742                let count = indices.len();
743                for &rel_index in &indices {
744                    let absolute_index = (start + rel_index).to_usize().unwrap();
745                    mutable.try_extend(0, absolute_index, absolute_index + 1)?;
746                }
747                let length = O::usize_as(count);
748                offsets.push(current_offset);
749                sizes.push(length);
750                current_offset += length;
751            }
752        }
753    }
754
755    let data = mutable.freeze();
756
757    Ok(Arc::new(GenericListViewArray::<O>::try_new(
758        field,
759        ScalarBuffer::from(offsets),
760        ScalarBuffer::from(sizes),
761        arrow::array::make_array(data),
762        nulls,
763    )?))
764}
765
766#[user_doc(
767    doc_section(label = "Array Functions"),
768    description = "Returns the array without the first element.",
769    syntax_example = "array_pop_front(array)",
770    sql_example = r#"```sql
771> select array_pop_front([1, 2, 3]);
772+--------------------------------+
773| array_pop_front(List([1,2,3])) |
774+--------------------------------+
775| [2, 3]                         |
776+--------------------------------+
777```"#,
778    argument(
779        name = "array",
780        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
781    )
782)]
783#[derive(Debug, PartialEq, Eq, Hash)]
784pub(super) struct ArrayPopFront {
785    signature: Signature,
786    aliases: Vec<String>,
787}
788
789impl ArrayPopFront {
790    pub fn new() -> Self {
791        Self {
792            signature: Signature::array(Volatility::Immutable),
793            aliases: vec![String::from("list_pop_front")],
794        }
795    }
796}
797
798impl ScalarUDFImpl for ArrayPopFront {
799    fn name(&self) -> &str {
800        "array_pop_front"
801    }
802
803    fn signature(&self) -> &Signature {
804        &self.signature
805    }
806
807    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
808        Ok(arg_types[0].clone())
809    }
810
811    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
812        make_scalar_function(array_pop_front_inner)(&args.args)
813    }
814
815    fn aliases(&self) -> &[String] {
816        &self.aliases
817    }
818
819    fn documentation(&self) -> Option<&Documentation> {
820        self.doc()
821    }
822}
823
824/// array_pop_front SQL function
825fn array_pop_front_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
826    let array_data_type = args[0].data_type();
827    match array_data_type {
828        List(_) => {
829            let array = as_list_array(&args[0])?;
830            general_pop_front_list::<i32>(array)
831        }
832        LargeList(_) => {
833            let array = as_large_list_array(&args[0])?;
834            general_pop_front_list::<i64>(array)
835        }
836        _ => exec_err!("array_pop_front does not support type: {}", array_data_type),
837    }
838}
839
840fn general_pop_front_list<O: OffsetSizeTrait>(
841    array: &GenericListArray<O>,
842) -> Result<ArrayRef>
843where
844    i64: TryInto<O>,
845{
846    let from_array = Int64Array::from(vec![2; array.len()]);
847    let to_array = Int64Array::from(
848        array
849            .iter()
850            .map(|arr| arr.map_or(0, |arr| arr.len() as i64))
851            .collect::<Vec<i64>>(),
852    );
853    general_array_slice::<O>(array, &from_array, &to_array, None)
854}
855
856#[user_doc(
857    doc_section(label = "Array Functions"),
858    description = "Returns the array without the last element.",
859    syntax_example = "array_pop_back(array)",
860    sql_example = r#"```sql
861> select array_pop_back([1, 2, 3]);
862+-------------------------------+
863| array_pop_back(List([1,2,3])) |
864+-------------------------------+
865| [1, 2]                        |
866+-------------------------------+
867```"#,
868    argument(
869        name = "array",
870        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
871    )
872)]
873#[derive(Debug, PartialEq, Eq, Hash)]
874pub(super) struct ArrayPopBack {
875    signature: Signature,
876    aliases: Vec<String>,
877}
878
879impl ArrayPopBack {
880    pub fn new() -> Self {
881        Self {
882            signature: Signature::array(Volatility::Immutable),
883            aliases: vec![String::from("list_pop_back")],
884        }
885    }
886}
887
888impl ScalarUDFImpl for ArrayPopBack {
889    fn name(&self) -> &str {
890        "array_pop_back"
891    }
892
893    fn signature(&self) -> &Signature {
894        &self.signature
895    }
896
897    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
898        Ok(arg_types[0].clone())
899    }
900
901    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
902        make_scalar_function(array_pop_back_inner)(&args.args)
903    }
904
905    fn aliases(&self) -> &[String] {
906        &self.aliases
907    }
908
909    fn documentation(&self) -> Option<&Documentation> {
910        self.doc()
911    }
912}
913
914/// array_pop_back SQL function
915fn array_pop_back_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
916    let [array] = take_function_args("array_pop_back", args)?;
917
918    match array.data_type() {
919        List(_) => {
920            let array = as_list_array(&array)?;
921            general_pop_back_list::<i32>(array)
922        }
923        LargeList(_) => {
924            let array = as_large_list_array(&array)?;
925            general_pop_back_list::<i64>(array)
926        }
927        _ => exec_err!(
928            "array_pop_back does not support type: {}",
929            array.data_type()
930        ),
931    }
932}
933
934fn general_pop_back_list<O: OffsetSizeTrait>(
935    array: &GenericListArray<O>,
936) -> Result<ArrayRef>
937where
938    i64: TryInto<O>,
939{
940    let from_array = Int64Array::from(vec![1; array.len()]);
941    let to_array = Int64Array::from(
942        array
943            .iter()
944            .map(|arr| arr.map_or(0, |arr| arr.len() as i64 - 1))
945            .collect::<Vec<i64>>(),
946    );
947    general_array_slice::<O>(array, &from_array, &to_array, None)
948}
949
950#[user_doc(
951    doc_section(label = "Array Functions"),
952    description = "Returns the first non-null element in the array. Returns NULL if the array is empty or NULL.",
953    syntax_example = "array_any_value(array)",
954    sql_example = r#"```sql
955> select array_any_value([NULL, 1, 2, 3]);
956+-------------------------------------+
957| array_any_value(List([NULL,1,2,3])) |
958+-------------------------------------+
959| 1                                   |
960+-------------------------------------+
961```"#,
962    argument(
963        name = "array",
964        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
965    )
966)]
967#[derive(Debug, PartialEq, Eq, Hash)]
968pub(super) struct ArrayAnyValue {
969    signature: Signature,
970    aliases: Vec<String>,
971}
972
973impl ArrayAnyValue {
974    pub fn new() -> Self {
975        Self {
976            signature: Signature::array(Volatility::Immutable),
977            aliases: vec![String::from("list_any_value")],
978        }
979    }
980}
981
982impl ScalarUDFImpl for ArrayAnyValue {
983    fn name(&self) -> &str {
984        "array_any_value"
985    }
986    fn signature(&self) -> &Signature {
987        &self.signature
988    }
989    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
990        match &arg_types[0] {
991            List(field) | LargeList(field) | FixedSizeList(field, _) => {
992                Ok(field.data_type().clone())
993            }
994            _ => plan_err!(
995                "array_any_value can only accept List, LargeList or FixedSizeList as the argument"
996            ),
997        }
998    }
999
1000    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
1001        make_scalar_function(array_any_value_inner)(&args.args)
1002    }
1003
1004    fn aliases(&self) -> &[String] {
1005        &self.aliases
1006    }
1007
1008    fn documentation(&self) -> Option<&Documentation> {
1009        self.doc()
1010    }
1011}
1012
1013fn array_any_value_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
1014    let [array] = take_function_args("array_any_value", args)?;
1015
1016    match &array.data_type() {
1017        List(_) => {
1018            let array = as_list_array(&array)?;
1019            general_array_any_value::<i32>(array)
1020        }
1021        LargeList(_) => {
1022            let array = as_large_list_array(&array)?;
1023            general_array_any_value::<i64>(array)
1024        }
1025        data_type => exec_err!("array_any_value does not support type: {data_type}"),
1026    }
1027}
1028
1029fn general_array_any_value<O: OffsetSizeTrait>(
1030    array: &GenericListArray<O>,
1031) -> Result<ArrayRef>
1032where
1033    i64: TryInto<O>,
1034{
1035    let values = array.values();
1036    let original_data = values.to_data();
1037    let capacity = Capacities::Array(array.len());
1038
1039    let mut mutable =
1040        MutableArrayData::with_capacities(vec![&original_data], true, capacity);
1041
1042    for (row_index, offset_window) in array.offsets().windows(2).enumerate() {
1043        let start = offset_window[0];
1044        let end = offset_window[1];
1045
1046        // the list element is null
1047        if array.is_null(row_index) {
1048            mutable.try_extend_nulls(1)?;
1049            continue;
1050        }
1051
1052        // the list element is empty; there is no value to take, so the result
1053        // is NULL.
1054        if start == end {
1055            mutable.try_extend_nulls(1)?;
1056            continue;
1057        }
1058
1059        let row_value = array.value(row_index);
1060        match row_value.nulls() {
1061            Some(row_nulls_buffer) => {
1062                // nulls are present in the array so try to take the first valid element
1063                if let Some(first_non_null_index) =
1064                    row_nulls_buffer.valid_indices().next()
1065                {
1066                    let index = start.as_usize() + first_non_null_index;
1067                    mutable.try_extend(0, index, index + 1)?;
1068                } else {
1069                    // all the elements in the array are null
1070                    mutable.try_extend_nulls(1)?;
1071                }
1072            }
1073            None => {
1074                // no nulls are present in the array so take the first element
1075                let index = start.as_usize();
1076                mutable.try_extend(0, index, index + 1)?;
1077            }
1078        }
1079    }
1080
1081    let data = mutable.freeze();
1082    Ok(arrow::array::make_array(data))
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087    use super::{
1088        array_element_udf, general_array_any_value, general_array_element,
1089        general_list_view_array_slice,
1090    };
1091    use arrow::array::{
1092        Array, ArrayRef, GenericListViewArray, Int32Array, Int64Array, ListViewArray,
1093        cast::AsArray,
1094    };
1095    use arrow::array::{ListArray, RecordBatch};
1096    use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
1097    use arrow::datatypes::{DataType, Field, Int32Type};
1098    use datafusion_common::{Column, DFSchema, Result, assert_batches_eq};
1099    use datafusion_expr::expr::ScalarFunction;
1100    use datafusion_expr::{Expr, ExprSchemable};
1101    use std::collections::HashMap;
1102    use std::sync::Arc;
1103
1104    fn list_view_values(array: &GenericListViewArray<i32>) -> Vec<Vec<i32>> {
1105        (0..array.len())
1106            .map(|i| {
1107                let child = array.value(i);
1108                let values = child.as_any().downcast_ref::<Int32Array>().unwrap();
1109                values.iter().map(|v| v.unwrap()).collect()
1110            })
1111            .collect()
1112    }
1113
1114    // Regression test for https://github.com/apache/datafusion/issues/13755
1115    #[test]
1116    fn test_array_element_return_type_fixed_size_list() {
1117        let fixed_size_list_type = DataType::FixedSizeList(
1118            Field::new("some_arbitrary_test_field", DataType::Int32, false).into(),
1119            13,
1120        );
1121        let array_type = DataType::List(
1122            Field::new_list_field(fixed_size_list_type.clone(), true).into(),
1123        );
1124        let index_type = DataType::Int64;
1125
1126        let schema = DFSchema::from_unqualified_fields(
1127            vec![
1128                Field::new("my_array", array_type.clone(), false),
1129                Field::new("my_index", index_type.clone(), false),
1130            ]
1131            .into(),
1132            HashMap::default(),
1133        )
1134        .unwrap();
1135
1136        let udf = array_element_udf();
1137
1138        // ScalarUDFImpl::return_type
1139        assert_eq!(
1140            udf.return_type(&[array_type.clone(), index_type.clone()])
1141                .unwrap(),
1142            fixed_size_list_type
1143        );
1144
1145        // Via ExprSchemable::get_type (e.g. SimplifyInfo)
1146        let udf_expr = Expr::ScalarFunction(ScalarFunction {
1147            func: array_element_udf(),
1148            args: vec![
1149                Expr::Column(Column::new_unqualified("my_array")),
1150                Expr::Column(Column::new_unqualified("my_index")),
1151            ],
1152        });
1153        assert_eq!(
1154            ExprSchemable::get_type(&udf_expr, &schema).unwrap(),
1155            fixed_size_list_type
1156        );
1157    }
1158
1159    #[test]
1160    fn test_array_element_null_handling() -> Result<()> {
1161        let values = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5]));
1162        let offsets = OffsetBuffer::new(ScalarBuffer::from(vec![0, 3, 4, 5]));
1163        let nulls = NullBuffer::from(vec![true, false, true]);
1164        let field = Arc::new(Field::new("item", DataType::Int32, true));
1165
1166        let list_array = ListArray::new(field, offsets, values, Some(nulls));
1167        let indexes = Int64Array::from(vec![1, 1, 1]);
1168
1169        let result = general_array_element(&list_array, &indexes)?;
1170
1171        let expected = [
1172            "+--------+",
1173            "| result |",
1174            "+--------+",
1175            "| 1      |",
1176            "|        |",
1177            "| 5      |",
1178            "+--------+",
1179        ];
1180
1181        let batch = RecordBatch::try_from_iter([("result", result)])?;
1182
1183        assert_batches_eq!(expected, &[batch]);
1184
1185        Ok(())
1186    }
1187
1188    #[test]
1189    fn test_array_element_null_index_with_non_zero_buffer_returns_null() -> Result<()> {
1190        let list_array = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1191            Some(vec![Some(1), Some(2), Some(3)]),
1192            Some(vec![Some(4)]),
1193            Some(vec![Some(5)]),
1194        ]);
1195        let indexes = Int64Array::new(
1196            ScalarBuffer::from(vec![1, 1, 1]),
1197            Some(NullBuffer::from(vec![true, false, true])),
1198        );
1199
1200        let result = general_array_element(&list_array, &indexes)?;
1201        let expected = Int32Array::from(vec![Some(1), None, Some(5)]);
1202
1203        assert_eq!(result.as_primitive::<Int32Type>(), &expected);
1204
1205        Ok(())
1206    }
1207
1208    #[test]
1209    fn test_array_any_null_handling() -> Result<()> {
1210        let values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5]));
1211        let offsets = OffsetBuffer::new(ScalarBuffer::from(vec![0, 3, 4, 5]));
1212        let nulls = NullBuffer::from(vec![true, false, true]);
1213        let field = Arc::new(Field::new("item", DataType::Int32, true));
1214
1215        let list_array = ListArray::new(field, offsets, values, Some(nulls));
1216
1217        let result = general_array_any_value(&list_array)?;
1218
1219        assert!(!result.is_null(0));
1220        assert!(result.is_null(1));
1221        assert!(!result.is_null(2));
1222
1223        Ok(())
1224    }
1225
1226    #[test]
1227    fn test_array_slice_list_view_basic() -> Result<()> {
1228        let values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5]));
1229        let offsets = ScalarBuffer::from(vec![0, 3]);
1230        let sizes = ScalarBuffer::from(vec![3, 2]);
1231        let field = Arc::new(Field::new("item", DataType::Int32, true));
1232        let array = ListViewArray::new(field, offsets, sizes, values, None);
1233
1234        let from = Int64Array::from(vec![2, 1]);
1235        let to = Int64Array::from(vec![3, 2]);
1236
1237        let result = general_list_view_array_slice::<i32>(
1238            &array,
1239            &from,
1240            &to,
1241            None::<&Int64Array>,
1242        )?;
1243        let result = result.as_ref().as_list_view::<i32>();
1244
1245        assert_eq!(list_view_values(result), vec![vec![2, 3], vec![4, 5]]);
1246        Ok(())
1247    }
1248
1249    #[test]
1250    fn test_array_slice_list_view_non_monotonic_offsets() -> Result<()> {
1251        // First list references the tail of the values buffer, second list references the head.
1252        let values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5]));
1253        let offsets = ScalarBuffer::from(vec![3, 0]);
1254        let sizes = ScalarBuffer::from(vec![2, 3]);
1255        let field = Arc::new(Field::new("item", DataType::Int32, true));
1256        let array = ListViewArray::new(field, offsets, sizes, values, None);
1257
1258        let from = Int64Array::from(vec![1, 1]);
1259        let to = Int64Array::from(vec![2, 2]);
1260
1261        let result = general_list_view_array_slice::<i32>(
1262            &array,
1263            &from,
1264            &to,
1265            None::<&Int64Array>,
1266        )?;
1267        let result = result.as_ref().as_list_view::<i32>();
1268
1269        assert_eq!(list_view_values(result), vec![vec![4, 5], vec![1, 2]]);
1270        Ok(())
1271    }
1272
1273    #[test]
1274    fn test_array_slice_list_view_negative_stride() -> Result<()> {
1275        let values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5]));
1276        let offsets = ScalarBuffer::from(vec![0, 3]);
1277        let sizes = ScalarBuffer::from(vec![3, 2]);
1278        let field = Arc::new(Field::new("item", DataType::Int32, true));
1279        let array = ListViewArray::new(field, offsets, sizes, values, None);
1280
1281        let from = Int64Array::from(vec![3, 2]);
1282        let to = Int64Array::from(vec![1, 1]);
1283        let stride = Int64Array::from(vec![-1, -1]);
1284
1285        let result =
1286            general_list_view_array_slice::<i32>(&array, &from, &to, Some(&stride))?;
1287        let result = result.as_ref().as_list_view::<i32>();
1288
1289        assert_eq!(list_view_values(result), vec![vec![3, 2, 1], vec![5, 4]]);
1290        Ok(())
1291    }
1292
1293    #[test]
1294    fn test_array_slice_list_view_out_of_order() -> Result<()> {
1295        let values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5]));
1296        let offsets = ScalarBuffer::from(vec![3, 1, 0]);
1297        let sizes = ScalarBuffer::from(vec![2, 2, 1]);
1298        let field = Arc::new(Field::new("item", DataType::Int32, true));
1299        let array = ListViewArray::new(field, offsets, sizes, values, None);
1300        assert_eq!(
1301            list_view_values(&array),
1302            vec![vec![4, 5], vec![2, 3], vec![1]]
1303        );
1304
1305        let from = Int64Array::from(vec![2, 2, 2]);
1306        let to = Int64Array::from(vec![1, 1, 1]);
1307        let stride = Int64Array::from(vec![-1, -1, -1]);
1308
1309        let result =
1310            general_list_view_array_slice::<i32>(&array, &from, &to, Some(&stride))?;
1311        let result = result.as_ref().as_list_view::<i32>();
1312
1313        assert_eq!(
1314            list_view_values(result),
1315            vec![vec![5, 4], vec![3, 2], vec![]]
1316        );
1317        Ok(())
1318    }
1319
1320    #[test]
1321    fn test_array_slice_list_view_with_nulls() -> Result<()> {
1322        let values: ArrayRef = Arc::new(Int32Array::from(vec![
1323            Some(1),
1324            None,
1325            Some(3),
1326            Some(4),
1327            Some(5),
1328        ]));
1329        let offsets = ScalarBuffer::from(vec![0, 2, 5]);
1330        let sizes = ScalarBuffer::from(vec![2, 3, 0]);
1331        let field = Arc::new(Field::new("item", DataType::Int32, true));
1332        let array = ListViewArray::new(field, offsets, sizes, values, None);
1333
1334        let from = Int64Array::from(vec![1, 1, 1]);
1335        let to = Int64Array::from(vec![2, 2, 1]);
1336
1337        let result = general_list_view_array_slice::<i32>(&array, &from, &to, None)?;
1338        let result = result.as_ref().as_list_view::<i32>();
1339
1340        let actual: Vec<Vec<Option<i32>>> = (0..result.len())
1341            .map(|i| {
1342                result
1343                    .value(i)
1344                    .as_any()
1345                    .downcast_ref::<Int32Array>()
1346                    .unwrap()
1347                    .iter()
1348                    .collect()
1349            })
1350            .collect();
1351
1352        assert_eq!(
1353            actual,
1354            vec![vec![Some(1), None], vec![Some(3), Some(4)], Vec::new(),]
1355        );
1356
1357        // Test with NULL stride - should return NULL for rows with NULL stride
1358        let stride_with_null = Int64Array::from(vec![Some(1), None, Some(1)]);
1359        let result = general_list_view_array_slice::<i32>(
1360            &array,
1361            &from,
1362            &to,
1363            Some(&stride_with_null),
1364        )?;
1365        let result = result.as_ref().as_list_view::<i32>();
1366
1367        // First row: stride = 1, should return [1, None]
1368        // Second row: stride = NULL, should return NULL
1369        // Third row: stride = 1, empty array should return empty
1370        assert!(!result.is_null(0)); // First row should not be null
1371        assert!(result.is_null(1)); // Second row should be null (stride is NULL)
1372        assert!(!result.is_null(2)); // Third row should not be null
1373
1374        let first_row: Vec<Option<i32>> = result
1375            .value(0)
1376            .as_any()
1377            .downcast_ref::<Int32Array>()
1378            .unwrap()
1379            .iter()
1380            .collect();
1381        assert_eq!(first_row, vec![Some(1), None]);
1382
1383        Ok(())
1384    }
1385
1386    #[test]
1387    fn test_element_sliced_capacity() -> Result<()> {
1388        crate::utils::tests::check_sliced_list_behavior(|input| {
1389            super::array_element_inner(&[
1390                Arc::clone(input),
1391                Arc::new(Int64Array::from(vec![1; input.len()])),
1392            ])
1393        })
1394    }
1395
1396    #[test]
1397    fn test_slice_sliced_capacity() -> Result<()> {
1398        crate::utils::tests::check_sliced_list_behavior(|input| {
1399            super::array_slice_inner(&[
1400                Arc::clone(input),
1401                Arc::new(Int64Array::from(vec![1; input.len()])),
1402                Arc::new(Int64Array::from(vec![3; input.len()])),
1403            ])
1404        })
1405    }
1406}