Skip to main content

datafusion_functions_nested/
sort.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_sort function.
6
7use crate::utils::make_scalar_function;
8use arrow::array::BooleanBufferBuilder;
9use arrow::array::{
10    Array, ArrayRef, ArrowPrimitiveType, GenericListArray, OffsetSizeTrait,
11    PrimitiveArray, UInt32Array, UInt64Array, new_empty_array, new_null_array,
12};
13use arrow::buffer::{NullBuffer, OffsetBuffer};
14use arrow::datatypes::{ArrowNativeTypeOp, DataType};
15use arrow::row::{RowConverter, Rows, SortField};
16use arrow::util::bit_iterator::BitIterator;
17use arrow::{compute, compute::SortOptions, downcast_primitive_array};
18use datafusion_common::cast::{as_large_list_array, as_list_array, as_string_array};
19use datafusion_common::utils::{ListCoercion, offset_span};
20use datafusion_common::{Result, exec_err};
21use datafusion_expr::{
22    ArrayFunctionArgument, ArrayFunctionSignature, ColumnarValue, Documentation,
23    ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature, Volatility,
24};
25use datafusion_macros::user_doc;
26use std::sync::Arc;
27
28make_udf_expr_and_func!(
29    ArraySort,
30    array_sort,
31    array desc null_first,
32    "returns sorted array.",
33    array_sort_udf
34);
35
36/// Implementation of `array_sort` function
37///
38/// `array_sort` sorts the elements of an array
39///
40/// # Example
41///
42/// `array_sort([3, 1, 2])` returns `[1, 2, 3]`
43#[user_doc(
44    doc_section(label = "Array Functions"),
45    description = "Sort array.",
46    syntax_example = "array_sort(array[, order[, nulls_order]])",
47    sql_example = r#"```sql
48> select array_sort([3, 1, 2]);
49+-----------------------------+
50| array_sort(List([3,1,2]))   |
51+-----------------------------+
52| [1, 2, 3]                   |
53+-----------------------------+
54> select array_sort([3, 1, NULL, 2], 'desc', 'nulls last');
55+--------------------------------------------------+
56| array_sort(List(3,1,NULL,2),'desc','nulls last') |
57+--------------------------------------------------+
58| [3, 2, 1, NULL]                                  |
59+--------------------------------------------------+
60```"#,
61    argument(
62        name = "array",
63        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
64    ),
65    argument(
66        name = "order",
67        description = "Whether to sort in ascending (`ASC`) or descending (`DESC`) order. The default is `ASC`."
68    ),
69    argument(
70        name = "nulls_order",
71        description = "Whether to sort nulls first (`NULLS FIRST`) or last (`NULLS LAST`). The default is `NULLS FIRST`."
72    )
73)]
74#[derive(Debug, PartialEq, Eq, Hash)]
75pub struct ArraySort {
76    signature: Signature,
77    aliases: Vec<String>,
78}
79
80impl Default for ArraySort {
81    fn default() -> Self {
82        Self::new()
83    }
84}
85
86impl ArraySort {
87    pub fn new() -> Self {
88        Self {
89            signature: Signature::one_of(
90                vec![
91                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
92                        arguments: vec![ArrayFunctionArgument::Array],
93                        array_coercion: Some(ListCoercion::FixedSizedListToList),
94                    }),
95                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
96                        arguments: vec![
97                            ArrayFunctionArgument::Array,
98                            ArrayFunctionArgument::String,
99                        ],
100                        array_coercion: Some(ListCoercion::FixedSizedListToList),
101                    }),
102                    TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
103                        arguments: vec![
104                            ArrayFunctionArgument::Array,
105                            ArrayFunctionArgument::String,
106                            ArrayFunctionArgument::String,
107                        ],
108                        array_coercion: Some(ListCoercion::FixedSizedListToList),
109                    }),
110                ],
111                Volatility::Immutable,
112            ),
113            aliases: vec!["list_sort".to_string()],
114        }
115    }
116}
117
118impl ScalarUDFImpl for ArraySort {
119    fn name(&self) -> &str {
120        "array_sort"
121    }
122
123    fn signature(&self) -> &Signature {
124        &self.signature
125    }
126
127    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
128        Ok(arg_types[0].clone())
129    }
130
131    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
132        make_scalar_function(array_sort_inner)(&args.args)
133    }
134
135    fn aliases(&self) -> &[String] {
136        &self.aliases
137    }
138
139    fn documentation(&self) -> Option<&Documentation> {
140        self.doc()
141    }
142}
143
144fn array_sort_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
145    if args.is_empty() || args.len() > 3 {
146        return exec_err!("array_sort expects one to three arguments");
147    }
148
149    if args[0].is_empty() || args[0].data_type().is_null() {
150        return Ok(Arc::clone(&args[0]));
151    }
152
153    if args[1..].iter().any(|array| array.is_null(0)) {
154        return Ok(new_null_array(args[0].data_type(), args[0].len()));
155    }
156
157    let sort_options = if args.len() >= 2 {
158        let order = as_string_array(&args[1])?.value(0);
159        let descending = order_desc(order)?;
160        let nulls_first = if args.len() >= 3 {
161            order_nulls_first(as_string_array(&args[2])?.value(0))?
162        } else {
163            true
164        };
165        Some(SortOptions {
166            descending,
167            nulls_first,
168        })
169    } else {
170        None
171    };
172
173    match args[0].data_type() {
174        DataType::List(field) | DataType::LargeList(field)
175            if field.data_type().is_null() =>
176        {
177            Ok(Arc::clone(&args[0]))
178        }
179        DataType::List(_) => {
180            let array = as_list_array(&args[0])?;
181            array_sort_generic(array, sort_options)
182        }
183        DataType::LargeList(_) => {
184            let array = as_large_list_array(&args[0])?;
185            array_sort_generic(array, sort_options)
186        }
187        // Signature should prevent this arm ever occurring
188        _ => exec_err!("array_sort expects list for first argument"),
189    }
190}
191
192fn array_sort_generic<OffsetSize: OffsetSizeTrait>(
193    list_array: &GenericListArray<OffsetSize>,
194    sort_options: Option<SortOptions>,
195) -> Result<ArrayRef> {
196    let values = list_array.values();
197
198    if values.data_type().is_primitive() {
199        array_sort_primitive(list_array, sort_options)
200    } else {
201        array_sort_non_primitive(list_array, sort_options)
202    }
203}
204
205/// Sort each row of a primitive-typed ListArray using a custom in-place sort
206/// kernel.
207fn array_sort_primitive<OffsetSize: OffsetSizeTrait>(
208    list_array: &GenericListArray<OffsetSize>,
209    sort_options: Option<SortOptions>,
210) -> Result<ArrayRef> {
211    let values = list_array.values().as_ref();
212    downcast_primitive_array! {
213        values => sort_primitive_list(values, list_array, sort_options),
214        _ => exec_err!("array_sort: unsupported primitive type")
215    }
216}
217
218fn sort_primitive_list<T: ArrowPrimitiveType, OffsetSize: OffsetSizeTrait>(
219    prim_values: &PrimitiveArray<T>,
220    list_array: &GenericListArray<OffsetSize>,
221    sort_options: Option<SortOptions>,
222) -> Result<ArrayRef>
223where
224    T::Native: ArrowNativeTypeOp,
225{
226    let descending = sort_options.is_some_and(|o| o.descending);
227    let nulls_first = sort_options.is_none_or(|o| o.nulls_first);
228    let list_nulls = list_array.nulls();
229    let offsets = list_array.offsets();
230
231    let (values, validity) = match prim_values.nulls() {
232        Some(element_nulls) if element_nulls.null_count() > 0 => {
233            let (values, validity) = sort_rows_with_nulls(
234                prim_values.values(),
235                element_nulls,
236                offsets,
237                list_nulls,
238                descending,
239                nulls_first,
240            );
241            (values, Some(validity))
242        }
243        _ => (
244            sort_rows_no_nulls(prim_values.values(), offsets, list_nulls, descending),
245            None,
246        ),
247    };
248
249    let sorted_values = Arc::new(
250        PrimitiveArray::<T>::new(values.into(), validity)
251            .with_data_type(prim_values.data_type().clone()),
252    );
253
254    Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
255        Arc::clone(list_array.value_field()),
256        rebase_offsets(offsets),
257        sorted_values,
258        list_nulls.cloned(),
259    )?))
260}
261
262/// Sorts one row's values in place.
263///
264/// [`ArrowNativeTypeOp::compare`] is a total order, so a descending sort is the
265/// reverse of the ascending one. Sorting one way and reversing keeps a single
266/// instantiation of the standard library's sort per native type, instead of one
267/// per comparator closure.
268#[inline]
269fn sort_row<N: ArrowNativeTypeOp>(row: &mut [N], descending: bool) {
270    row.sort_unstable_by(|a, b| a.compare(*b));
271    if descending {
272        row.reverse();
273    }
274}
275
276/// Fast path for primitive values with no element-level nulls. Copies all
277/// values into a single `Vec` and sorts each row's slice in-place.
278fn sort_rows_no_nulls<N: ArrowNativeTypeOp, O: OffsetSizeTrait>(
279    src_values: &[N],
280    offsets: &OffsetBuffer<O>,
281    list_nulls: Option<&NullBuffer>,
282    descending: bool,
283) -> Vec<N> {
284    let (values_start, total_values) = offset_span(offsets);
285
286    // Copy all values into a mutable buffer
287    let mut values = src_values[values_start..values_start + total_values].to_vec();
288
289    for (row_index, window) in offsets.windows(2).enumerate() {
290        if list_nulls.is_some_and(|n| n.is_null(row_index)) {
291            continue;
292        }
293        let start = window[0].as_usize() - values_start;
294        let end = window[1].as_usize() - values_start;
295        sort_row(&mut values[start..end], descending);
296    }
297
298    values
299}
300
301/// Slow path for primitive values with element-level nulls.
302fn sort_rows_with_nulls<N: ArrowNativeTypeOp, O: OffsetSizeTrait>(
303    src_values: &[N],
304    src_nulls: &NullBuffer,
305    offsets: &OffsetBuffer<O>,
306    list_nulls: Option<&NullBuffer>,
307    descending: bool,
308    nulls_first: bool,
309) -> (Vec<N>, NullBuffer) {
310    let (values_start, total_values) = offset_span(offsets);
311
312    let mut out_values: Vec<N> = vec![N::default(); total_values];
313    let mut validity = BooleanBufferBuilder::new(total_values);
314
315    for (row_index, window) in offsets.windows(2).enumerate() {
316        let start = window[0].as_usize();
317        let end = window[1].as_usize();
318        let row_len = end - start;
319        let out_start = start - values_start;
320
321        if list_nulls.is_some_and(|n| n.is_null(row_index)) || row_len == 0 {
322            validity.append_n(row_len, false);
323            continue;
324        }
325
326        // Compact valid values to the start of the row's output region and
327        // count them. The loop writes every value to the next slot but
328        // advances only past valid values, so it doesn't branch on each
329        // validity bit; that branch would be hard to predict when NULLs are
330        // scattered through the row.
331        let validity_bits =
332            BitIterator::new(src_nulls.validity(), src_nulls.offset() + start, row_len);
333        let mut write_pos = out_start;
334        for (&value, is_valid) in src_values[start..end].iter().zip(validity_bits) {
335            out_values[write_pos] = value;
336            write_pos += is_valid as usize;
337        }
338        let valid_count = write_pos - out_start;
339        let null_count = row_len - valid_count;
340
341        sort_row(&mut out_values[out_start..write_pos], descending);
342
343        // Build validity bits. With nulls_first, move the sorted values after
344        // the NULLs.
345        if nulls_first {
346            if null_count > 0 {
347                out_values.copy_within(out_start..write_pos, out_start + null_count);
348            }
349            validity.append_n(null_count, false);
350            validity.append_n(valid_count, true);
351        } else {
352            validity.append_n(valid_count, true);
353            validity.append_n(null_count, false);
354        }
355    }
356
357    (out_values, NullBuffer::from(validity.finish()))
358}
359
360/// Sort a non-pritive-typed ListArray by converting all rows at once using
361/// `RowConverter`, and then sort row indices by comparing encoded bytes (sort
362/// direction and null ordering are baked into the encoding), and materialize
363/// the result with a single `take()`.
364fn array_sort_non_primitive<OffsetSize: OffsetSizeTrait>(
365    list_array: &GenericListArray<OffsetSize>,
366    sort_options: Option<SortOptions>,
367) -> Result<ArrayRef> {
368    let row_count = list_array.len();
369    let values = list_array.values();
370    let offsets = list_array.offsets();
371    let (values_start, total_values) = offset_span(offsets);
372
373    let converter = RowConverter::new(vec![SortField::new_with_options(
374        values.data_type().clone(),
375        sort_options.unwrap_or_default(),
376    )])?;
377    let values_sliced = values.slice(values_start, total_values);
378    let rows = converter.convert_columns(&[Arc::clone(&values_sliced)])?;
379
380    let mut indices: Vec<OffsetSize> = Vec::with_capacity(total_values);
381    let mut new_offsets = Vec::with_capacity(row_count + 1);
382    new_offsets.push(OffsetSize::usize_as(0));
383
384    let mut sort_scratch: Vec<usize> = Vec::new();
385
386    for (row_index, window) in offsets.windows(2).enumerate() {
387        let start = window[0];
388        let end = window[1];
389
390        if list_array.is_null(row_index) {
391            new_offsets.push(new_offsets[row_index]);
392            continue;
393        }
394
395        let len = (end - start).as_usize();
396        let local_start = start.as_usize() - values_start;
397
398        if len <= 1 {
399            indices.extend((local_start..local_start + len).map(OffsetSize::usize_as));
400        } else {
401            sort_row_indices(&mut sort_scratch, &rows, local_start, len);
402            indices.extend(sort_scratch.iter().map(|&i| OffsetSize::usize_as(i)));
403        }
404
405        new_offsets.push(new_offsets[row_index] + (end - start));
406    }
407
408    let sorted_values = if indices.is_empty() {
409        new_empty_array(values.data_type())
410    } else {
411        take_by_indices(&values_sliced, indices)?
412    };
413
414    Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
415        Arc::clone(list_array.value_field()),
416        OffsetBuffer::<OffsetSize>::new(new_offsets.into()),
417        sorted_values,
418        list_array.nulls().cloned(),
419    )?))
420}
421
422/// Sorts `scratch` to hold the indices `start..start + len` ordered by their
423/// encoded rows. Kept free of the offset width so the standard library's sort
424/// is instantiated once rather than once per list type.
425fn sort_row_indices(scratch: &mut Vec<usize>, rows: &Rows, start: usize, len: usize) {
426    scratch.clear();
427    scratch.extend(start..start + len);
428    scratch.sort_unstable_by(|&a, &b| rows.row(a).cmp(&rows.row(b)));
429}
430
431/// Select elements from `values` at the given `indices` using `compute::take`.
432/// We consume `indices` in order to avoid an intermediate copy.
433fn take_by_indices<OffsetSize: OffsetSizeTrait>(
434    values: &ArrayRef,
435    indices: Vec<OffsetSize>,
436) -> Result<ArrayRef> {
437    let len = indices.len();
438    let buffer = arrow::buffer::Buffer::from_vec(indices);
439    let indices_array: ArrayRef = if OffsetSize::IS_LARGE {
440        Arc::new(UInt64Array::new(
441            arrow::buffer::ScalarBuffer::new(buffer, 0, len),
442            None,
443        ))
444    } else {
445        Arc::new(UInt32Array::new(
446            arrow::buffer::ScalarBuffer::new(buffer, 0, len),
447            None,
448        ))
449    };
450    Ok(compute::take(values.as_ref(), &indices_array, None)?)
451}
452
453/// Rebase offsets so they start at 0. For non-sliced ListArrays (the common
454/// case) offsets already start at 0 and we can clone the Arc-backed buffer
455/// cheaply instead of allocating a new Vec.
456fn rebase_offsets<OffsetSize: OffsetSizeTrait>(
457    offsets: &OffsetBuffer<OffsetSize>,
458) -> OffsetBuffer<OffsetSize> {
459    offsets.clone().subtract(offsets[0])
460}
461
462fn order_desc(modifier: &str) -> Result<bool> {
463    match modifier.to_uppercase().as_str() {
464        "DESC" => Ok(true),
465        "ASC" => Ok(false),
466        _ => exec_err!("the second parameter of array_sort expects DESC or ASC"),
467    }
468}
469
470fn order_nulls_first(modifier: &str) -> Result<bool> {
471    match modifier.to_uppercase().as_str() {
472        "NULLS FIRST" => Ok(true),
473        "NULLS LAST" => Ok(false),
474        _ => exec_err!(
475            "the third parameter of array_sort expects NULLS FIRST or NULLS LAST"
476        ),
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use arrow::array::{Array, ArrayRef, Int32Array, ListArray, StringArray};
483    use arrow::buffer::OffsetBuffer;
484    use arrow::datatypes::{DataType, Field, Int32Type};
485    use std::sync::Arc;
486
487    #[test]
488    fn test_sliced_list() -> datafusion_common::Result<()> {
489        crate::utils::tests::check_sliced_list_behavior(|input| {
490            super::array_sort_inner(&[Arc::clone(input)])
491        })
492    }
493
494    #[test]
495    fn test_sliced_values() -> datafusion_common::Result<()> {
496        // Slicing the child array makes its validity bitmap start partway
497        // through a byte.
498        let values = Int32Array::from(vec![
499            Some(0),
500            Some(0),
501            Some(0),
502            Some(3),
503            None,
504            Some(1),
505            Some(2),
506            None,
507        ]);
508        let input: ArrayRef = Arc::new(ListArray::new(
509            Arc::new(Field::new_list_field(DataType::Int32, true)),
510            OffsetBuffer::from_lengths([3, 2]),
511            Arc::new(values.slice(3, 5)),
512            None,
513        ));
514        for (nulls, expected) in [
515            (
516                "NULLS FIRST",
517                [vec![None, Some(1), Some(3)], vec![None, Some(2)]],
518            ),
519            (
520                "NULLS LAST",
521                [vec![Some(1), Some(3), None], vec![Some(2), None]],
522            ),
523        ] {
524            let result = super::array_sort_inner(&[
525                Arc::clone(&input),
526                Arc::new(StringArray::from(vec!["ASC"; 2])),
527                Arc::new(StringArray::from(vec![nulls; 2])),
528            ])?;
529            let expected = ListArray::from_iter_primitive::<Int32Type, _, _>(
530                expected.into_iter().map(Some),
531            );
532            assert_eq!(result.as_ref(), &expected as &dyn Array, "{nulls}");
533        }
534        Ok(())
535    }
536}