Skip to main content

datafusion_functions_nested/
empty.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_empty function.
6
7use crate::utils::make_scalar_function;
8use arrow::array::{Array, ArrayRef, BooleanArray, OffsetSizeTrait};
9use arrow::buffer::BooleanBuffer;
10use arrow::datatypes::{
11    DataType,
12    DataType::{Boolean, FixedSizeList, LargeList, List},
13};
14use datafusion_common::cast::as_generic_list_array;
15use datafusion_common::{Result, exec_err, utils::take_function_args};
16use datafusion_expr::{
17    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
18    Volatility,
19};
20use datafusion_macros::user_doc;
21use std::sync::Arc;
22
23make_udf_expr_and_func!(
24    ArrayEmpty,
25    array_empty,
26    array,
27    "returns true for an empty array or false for a non-empty array.",
28    array_empty_udf
29);
30
31#[user_doc(
32    doc_section(label = "Array Functions"),
33    description = "Returns true for an empty array or false for a non-empty array.",
34    syntax_example = "empty(array)",
35    sql_example = r#"```sql
36> select empty([1]);
37+------------------+
38| empty(List([1])) |
39+------------------+
40| false            |
41+------------------+
42```"#,
43    argument(
44        name = "array",
45        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
46    )
47)]
48#[derive(Debug, PartialEq, Eq, Hash)]
49pub struct ArrayEmpty {
50    signature: Signature,
51    aliases: Vec<String>,
52}
53
54impl Default for ArrayEmpty {
55    fn default() -> Self {
56        Self::new()
57    }
58}
59impl ArrayEmpty {
60    pub fn new() -> Self {
61        Self {
62            signature: Signature::arrays(1, None, Volatility::Immutable),
63            aliases: vec!["array_empty".to_string(), "list_empty".to_string()],
64        }
65    }
66}
67
68impl ScalarUDFImpl for ArrayEmpty {
69    fn name(&self) -> &str {
70        "empty"
71    }
72
73    fn signature(&self) -> &Signature {
74        &self.signature
75    }
76
77    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
78        Ok(Boolean)
79    }
80
81    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
82        make_scalar_function(array_empty_inner)(&args.args)
83    }
84
85    fn aliases(&self) -> &[String] {
86        &self.aliases
87    }
88
89    fn documentation(&self) -> Option<&Documentation> {
90        self.doc()
91    }
92}
93
94fn array_empty_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
95    let [array] = take_function_args("array_empty", args)?;
96    match array.data_type() {
97        List(_) => general_array_empty::<i32>(array),
98        LargeList(_) => general_array_empty::<i64>(array),
99        FixedSizeList(_, size) => {
100            let values = if *size == 0 {
101                BooleanBuffer::new_set(array.len())
102            } else {
103                BooleanBuffer::new_unset(array.len())
104            };
105            Ok(Arc::new(BooleanArray::new(values, array.nulls().cloned())))
106        }
107        arg_type => exec_err!("array_empty does not support type {arg_type}"),
108    }
109}
110
111fn general_array_empty<O: OffsetSizeTrait>(array: &ArrayRef) -> Result<ArrayRef> {
112    let result = as_generic_list_array::<O>(array)?;
113    let is_empty_iter = result.offsets().lengths().map(|n| n == 0);
114    // SAFETY: this is safe since the iterator lengths is exact size and
115    // trusted - it maps over fixed known number of elements
116    let output_buffer = unsafe { BooleanArray::from_trusted_len_iter(is_empty_iter) };
117
118    let (values, _) = output_buffer.into_parts();
119
120    // Add the nulls
121    let result = BooleanArray::new(
122        values,
123        result.nulls().filter(|n| n.null_count() > 0).cloned(),
124    );
125
126    Ok(Arc::new(result))
127}