Skip to main content

risingwave_expr_impl/scalar/
array_sort.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use itertools::Itertools;
16use risingwave_common::array::*;
17use risingwave_common::util::sort_util::{OrderType, cmp_datum};
18use risingwave_expr::function;
19
20#[function("array_sort(anyarray) -> anyarray")]
21pub fn array_sort(array: ListRef<'_>, writer: &mut impl risingwave_common::array::ListWrite) {
22    array_sort_with_desc_and_nulls(array, false, false, writer);
23}
24
25#[function("array_sort(anyarray, boolean) -> anyarray")]
26pub fn array_sort_with_desc(
27    array: ListRef<'_>,
28    descending: bool,
29    writer: &mut impl risingwave_common::array::ListWrite,
30) {
31    array_sort_with_desc_and_nulls(array, descending, false, writer)
32}
33
34#[function("array_sort(anyarray, boolean, boolean) -> anyarray")]
35pub fn array_sort_with_desc_and_nulls(
36    array: ListRef<'_>,
37    descending: bool,
38    nulls_first: bool,
39    writer: &mut impl risingwave_common::array::ListWrite,
40) {
41    let order = OrderType::from_bools(Some(!descending), Some(nulls_first));
42
43    writer.write_iter(array.iter().sorted_by(|a, b| cmp_datum(*a, *b, order)));
44}