Apache DataFusion SQL Query Engine
Issue-9761 - Extract array_empty and array_repeat functions from functions-array subcrate' s kernels and udf containers (#9762)
Eren Avsarogullarif5c534312764
diff --git a/datafusion/functions-array/src/empty.rs b/datafusion/functions-array/src/empty.rsnew file mode 100644index 0000000000..37b247deb4--- /dev/null+++ b/datafusion/functions-array/src/empty.rs@@ -0,0 +1,111 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++//! [`ScalarUDFImpl`] definitions for array_empty function.++use crate::utils::make_scalar_function;+use arrow_array::{ArrayRef, BooleanArray, OffsetSizeTrait};+use arrow_schema::DataType;+use arrow_schema::DataType::{Boolean, FixedSizeList, LargeList, List};+use datafusion_common::cast::{as_generic_list_array, as_null_array};+use datafusion_common::{exec_err, plan_err};+use datafusion_expr::expr::ScalarFunction;+use datafusion_expr::{ColumnarValue, Expr, ScalarUDFImpl, Signature, Volatility};+use std::any::Any;+use std::sync::Arc;++make_udf_function!(+ ArrayEmpty,+ array_empty,+ array,+ "returns true for an empty array or false for a non-empty array.",+ array_empty_udf+);++#[derive(Debug)]+pub(super) struct ArrayEmpty {+ signature: Signature,+ aliases: Vec<String>,+}+impl ArrayEmpty {+ pub fn new() -> Self {+ Self {+ signature: Signature::array(Volatility::Immutable),+ aliases: vec![String::from("empty")],+ }+ }+}++impl ScalarUDFImpl for ArrayEmpty {+ fn as_any(&self) -> &dyn Any {+ self+ }+ fn name(&self) -> &str {+ "empty"+ }++ fn signature(&self) -> &Signature {+ &self.signature+ }++ fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result<DataType> {+ Ok(match arg_types[0] {+ List(_) | LargeList(_) | FixedSizeList(_, _) => Boolean,+ _ => {+ return plan_err!("The array_empty function can only accept List/LargeList/FixedSizeList.");+ }+ })+ }++ fn invoke(&self, args: &[ColumnarValue]) -> datafusion_common::Result<ColumnarValue> {+ make_scalar_function(array_empty_inner)(args)+ }++ fn aliases(&self) -> &[String] {+ &self.aliases+ }+}++/// Array_empty SQL function+pub fn array_empty_inner(args: &[ArrayRef]) -> datafusion_common::Result<ArrayRef> {+ if args.len() != 1 {+ return exec_err!("array_empty expects one argument");+ }++ if as_null_array(&args[0]).is_ok() {+ // Make sure to return Boolean type.+ return Ok(Arc::new(BooleanArray::new_null(args[0].len())));+ }+ let array_type = args[0].data_type();++ match array_type {+ List(_) => general_array_empty::<i32>(&args[0]),+ LargeList(_) => general_array_empty::<i64>(&args[0]),+ _ => exec_err!("array_empty does not support type '{array_type:?}'."),+ }+}++fn general_array_empty<O: OffsetSizeTrait>(+ array: &ArrayRef,+) -> datafusion_common::Result<ArrayRef> {+ let array = as_generic_list_array::<O>(array)?;+ let builder = array+ .iter()+ .map(|arr| arr.map(|arr| arr.len() == arr.null_count()))+ .collect::<BooleanArray>();+ Ok(Arc::new(builder))+}diff --git a/datafusion/functions-array/src/kernels.rs b/datafusion/functions-array/src/kernels.rsindex 1fb3abd529..4745db0170 100644--- a/datafusion/functions-array/src/kernels.rs+++ b/datafusion/functions-array/src/kernels.rs@@ -18,18 +18,15 @@//! implementation kernels for array functionsuse arrow::array::{- Array, ArrayRef, BooleanArray, Capacities, GenericListArray, Int64Array, ListArray,+ Array, ArrayRef, Capacities, GenericListArray, Int64Array, ListArray,MutableArrayData, OffsetSizeTrait, UInt64Array,};-use arrow::compute;-use arrow::datatypes::{DataType, Field, UInt64Type};-use arrow_array::new_null_array;+use arrow::datatypes::{DataType, UInt64Type};use arrow_buffer::{ArrowNativeType, OffsetBuffer};use arrow_schema::FieldRef;use datafusion_common::cast::{as_generic_list_array, as_int64_array, as_large_list_array, as_list_array,- as_null_array,};use datafusion_common::{exec_err, internal_datafusion_err, DataFusionError, Result, ScalarValue,@@ -161,180 +158,6 @@ pub fn array_ndims(args: &[ArrayRef]) -> Result<ArrayRef> {}}-/// Array_empty SQL function-pub fn array_empty(args: &[ArrayRef]) -> Result<ArrayRef> {- if args.len() != 1 {- return exec_err!("array_empty expects one argument");- }-- if as_null_array(&args[0]).is_ok() {- // Make sure to return Boolean type.- return Ok(Arc::new(BooleanArray::new_null(args[0].len())));- }- let array_type = args[0].data_type();-- match array_type {- DataType::List(_) => general_array_empty::<i32>(&args[0]),- DataType::LargeList(_) => general_array_empty::<i64>(&args[0]),- _ => exec_err!("array_empty does not support type '{array_type:?}'."),- }-}--fn general_array_empty<O: OffsetSizeTrait>(array: &ArrayRef) -> Result<ArrayRef> {- let array = as_generic_list_array::<O>(array)?;- let builder = array- .iter()- .map(|arr| arr.map(|arr| arr.len() == arr.null_count()))- .collect::<BooleanArray>();- Ok(Arc::new(builder))-}--/// Array_repeat SQL function-pub fn array_repeat(args: &[ArrayRef]) -> Result<ArrayRef> {- if args.len() != 2 {- return exec_err!("array_repeat expects two arguments");- }-- let element = &args[0];- let count_array = as_int64_array(&args[1])?;-- match element.data_type() {- DataType::List(_) => {- let list_array = as_list_array(element)?;- general_list_repeat::<i32>(list_array, count_array)- }- DataType::LargeList(_) => {- let list_array = as_large_list_array(element)?;- general_list_repeat::<i64>(list_array, count_array)- }- _ => general_repeat::<i32>(element, count_array),- }-}--/// For each element of `array[i]` repeat `count_array[i]` times.-///-/// Assumption for the input:-/// 1. `count[i] >= 0`-/// 2. `array.len() == count_array.len()`-///-/// For example,-/// ```text-/// array_repeat(-/// [1, 2, 3], [2, 0, 1] => [[1, 1], [], [3]]-/// )-/// ```-fn general_repeat<O: OffsetSizeTrait>(- array: &ArrayRef,- count_array: &Int64Array,-) -> Result<ArrayRef> {- let data_type = array.data_type();- let mut new_values = vec![];-- let count_vec = count_array- .values()- .to_vec()- .iter()- .map(|x| *x as usize)- .collect::<Vec<_>>();-- for (row_index, &count) in count_vec.iter().enumerate() {- let repeated_array = if array.is_null(row_index) {- new_null_array(data_type, count)- } else {- let original_data = array.to_data();- let capacity = Capacities::Array(count);- let mut mutable =- MutableArrayData::with_capacities(vec![&original_data], false, capacity);-- for _ in 0..count {- mutable.extend(0, row_index, row_index + 1);- }-- let data = mutable.freeze();- arrow_array::make_array(data)- };- new_values.push(repeated_array);- }-- let new_values: Vec<_> = new_values.iter().map(|a| a.as_ref()).collect();- let values = compute::concat(&new_values)?;-- Ok(Arc::new(GenericListArray::<O>::try_new(- Arc::new(Field::new("item", data_type.to_owned(), true)),- OffsetBuffer::from_lengths(count_vec),- values,- None,- )?))-}--/// Handle List version of `general_repeat`-///-/// For each element of `list_array[i]` repeat `count_array[i]` times.-///-/// For example,-/// ```text-/// array_repeat(-/// [[1, 2, 3], [4, 5], [6]], [2, 0, 1] => [[[1, 2, 3], [1, 2, 3]], [], [[6]]]-/// )-/// ```-fn general_list_repeat<O: OffsetSizeTrait>(- list_array: &GenericListArray<O>,- count_array: &Int64Array,-) -> Result<ArrayRef> {- let data_type = list_array.data_type();- let value_type = list_array.value_type();- let mut new_values = vec![];-- let count_vec = count_array- .values()- .to_vec()- .iter()- .map(|x| *x as usize)- .collect::<Vec<_>>();-- for (list_array_row, &count) in list_array.iter().zip(count_vec.iter()) {- let list_arr = match list_array_row {- Some(list_array_row) => {- let original_data = list_array_row.to_data();- let capacity = Capacities::Array(original_data.len() * count);- let mut mutable = MutableArrayData::with_capacities(- vec![&original_data],- false,- capacity,- );-- for _ in 0..count {- mutable.extend(0, 0, original_data.len());- }-- let data = mutable.freeze();- let repeated_array = arrow_array::make_array(data);-- let list_arr = GenericListArray::<O>::try_new(- Arc::new(Field::new("item", value_type.clone(), true)),- OffsetBuffer::<O>::from_lengths(vec![original_data.len(); count]),- repeated_array,- None,- )?;- Arc::new(list_arr) as ArrayRef- }- None => new_null_array(data_type, count),- };- new_values.push(list_arr);- }-- let lengths = new_values.iter().map(|a| a.len()).collect::<Vec<_>>();- let new_values: Vec<_> = new_values.iter().map(|a| a.as_ref()).collect();- let values = compute::concat(&new_values)?;-- Ok(Arc::new(ListArray::try_new(- Arc::new(Field::new("item", data_type.to_owned(), true)),- OffsetBuffer::<i32>::from_lengths(lengths),- values,- None,- )?))-}-/// array_resize SQL functionpub fn array_resize(arg: &[ArrayRef]) -> Result<ArrayRef> {if arg.len() < 2 || arg.len() > 3 {diff --git a/datafusion/functions-array/src/lib.rs b/datafusion/functions-array/src/lib.rsindex f4ca5408aa..4a7bb3fda9 100644--- a/datafusion/functions-array/src/lib.rs+++ b/datafusion/functions-array/src/lib.rs@@ -31,6 +31,7 @@ pub mod macros;mod array_has;mod concat;mod core;+mod empty;mod except;mod extract;mod kernels;@@ -38,6 +39,7 @@ mod length;mod position;mod range;mod remove;+mod repeat;mod replace;mod reverse;mod rewrite;@@ -62,6 +64,7 @@ pub mod expr_fn {pub use super::concat::array_concat;pub use super::concat::array_prepend;pub use super::core::make_array;+ pub use super::empty::array_empty;pub use super::except::array_except;pub use super::extract::array_element;pub use super::extract::array_pop_back;@@ -75,6 +78,7 @@ pub mod expr_fn {pub use super::remove::array_remove;pub use super::remove::array_remove_all;pub use super::remove::array_remove_n;+ pub use super::repeat::array_repeat;pub use super::replace::array_replace;pub use super::replace::array_replace_all;pub use super::replace::array_replace_n;@@ -86,9 +90,7 @@ pub mod expr_fn {pub use super::string::array_to_string;pub use super::string::string_to_array;pub use super::udf::array_dims;- pub use super::udf::array_empty;pub use super::udf::array_ndims;- pub use super::udf::array_repeat;pub use super::udf::array_resize;pub use super::udf::cardinality;pub use super::udf::flatten;@@ -116,11 +118,11 @@ pub fn register_all(registry: &mut dyn FunctionRegistry) -> Result<()> {array_has::array_has_udf(),array_has::array_has_all_udf(),array_has::array_has_any_udf(),- udf::array_empty_udf(),+ empty::array_empty_udf(),length::array_length_udf(),udf::flatten_udf(),sort::array_sort_udf(),- udf::array_repeat_udf(),+ repeat::array_repeat_udf(),udf::array_resize_udf(),reverse::array_reverse_udf(),set_ops::array_distinct_udf(),diff --git a/datafusion/functions-array/src/repeat.rs b/datafusion/functions-array/src/repeat.rsnew file mode 100644index 0000000000..bf967f6572--- /dev/null+++ b/datafusion/functions-array/src/repeat.rs@@ -0,0 +1,232 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++//! [`ScalarUDFImpl`] definitions for array_repeat function.++use crate::utils::make_scalar_function;+use arrow::array::{Capacities, MutableArrayData};+use arrow::compute;+use arrow_array::{+ new_null_array, Array, ArrayRef, GenericListArray, Int64Array, ListArray,+ OffsetSizeTrait,+};+use arrow_buffer::OffsetBuffer;+use arrow_schema::DataType::{LargeList, List};+use arrow_schema::{DataType, Field};+use datafusion_common::cast::{as_int64_array, as_large_list_array, as_list_array};+use datafusion_common::exec_err;+use datafusion_expr::expr::ScalarFunction;+use datafusion_expr::{ColumnarValue, Expr, ScalarUDFImpl, Signature, Volatility};+use std::any::Any;+use std::sync::Arc;++make_udf_function!(+ ArrayRepeat,+ array_repeat,+ element count, // arg name+ "returns an array containing element `count` times.", // doc+ array_repeat_udf // internal function name+);+#[derive(Debug)]+pub(super) struct ArrayRepeat {+ signature: Signature,+ aliases: Vec<String>,+}++impl ArrayRepeat {+ pub fn new() -> Self {+ Self {+ signature: Signature::variadic_any(Volatility::Immutable),+ aliases: vec![String::from("array_repeat"), String::from("list_repeat")],+ }+ }+}++impl ScalarUDFImpl for ArrayRepeat {+ fn as_any(&self) -> &dyn Any {+ self+ }+ fn name(&self) -> &str {+ "array_repeat"+ }++ fn signature(&self) -> &Signature {+ &self.signature+ }++ fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result<DataType> {+ Ok(List(Arc::new(Field::new(+ "item",+ arg_types[0].clone(),+ true,+ ))))+ }++ fn invoke(&self, args: &[ColumnarValue]) -> datafusion_common::Result<ColumnarValue> {+ make_scalar_function(array_repeat_inner)(args)+ }++ fn aliases(&self) -> &[String] {+ &self.aliases+ }+}++/// Array_repeat SQL function+pub fn array_repeat_inner(args: &[ArrayRef]) -> datafusion_common::Result<ArrayRef> {+ if args.len() != 2 {+ return exec_err!("array_repeat expects two arguments");+ }++ let element = &args[0];+ let count_array = as_int64_array(&args[1])?;++ match element.data_type() {+ List(_) => {+ let list_array = as_list_array(element)?;+ general_list_repeat::<i32>(list_array, count_array)+ }+ LargeList(_) => {+ let list_array = as_large_list_array(element)?;+ general_list_repeat::<i64>(list_array, count_array)+ }+ _ => general_repeat::<i32>(element, count_array),+ }+}++/// For each element of `array[i]` repeat `count_array[i]` times.+///+/// Assumption for the input:+/// 1. `count[i] >= 0`+/// 2. `array.len() == count_array.len()`+///+/// For example,+/// ```text+/// array_repeat(+/// [1, 2, 3], [2, 0, 1] => [[1, 1], [], [3]]+/// )+/// ```+fn general_repeat<O: OffsetSizeTrait>(+ array: &ArrayRef,+ count_array: &Int64Array,+) -> datafusion_common::Result<ArrayRef> {+ let data_type = array.data_type();+ let mut new_values = vec![];++ let count_vec = count_array+ .values()+ .to_vec()+ .iter()+ .map(|x| *x as usize)+ .collect::<Vec<_>>();++ for (row_index, &count) in count_vec.iter().enumerate() {+ let repeated_array = if array.is_null(row_index) {+ new_null_array(data_type, count)+ } else {+ let original_data = array.to_data();+ let capacity = Capacities::Array(count);+ let mut mutable =+ MutableArrayData::with_capacities(vec![&original_data], false, capacity);++ for _ in 0..count {+ mutable.extend(0, row_index, row_index + 1);+ }++ let data = mutable.freeze();+ arrow_array::make_array(data)+ };+ new_values.push(repeated_array);+ }++ let new_values: Vec<_> = new_values.iter().map(|a| a.as_ref()).collect();+ let values = compute::concat(&new_values)?;++ Ok(Arc::new(GenericListArray::<O>::try_new(+ Arc::new(Field::new("item", data_type.to_owned(), true)),+ OffsetBuffer::from_lengths(count_vec),+ values,+ None,+ )?))+}++/// Handle List version of `general_repeat`+///+/// For each element of `list_array[i]` repeat `count_array[i]` times.+///+/// For example,+/// ```text+/// array_repeat(+/// [[1, 2, 3], [4, 5], [6]], [2, 0, 1] => [[[1, 2, 3], [1, 2, 3]], [], [[6]]]+/// )+/// ```+fn general_list_repeat<O: OffsetSizeTrait>(+ list_array: &GenericListArray<O>,+ count_array: &Int64Array,+) -> datafusion_common::Result<ArrayRef> {+ let data_type = list_array.data_type();+ let value_type = list_array.value_type();+ let mut new_values = vec![];++ let count_vec = count_array+ .values()+ .to_vec()+ .iter()+ .map(|x| *x as usize)+ .collect::<Vec<_>>();++ for (list_array_row, &count) in list_array.iter().zip(count_vec.iter()) {+ let list_arr = match list_array_row {+ Some(list_array_row) => {+ let original_data = list_array_row.to_data();+ let capacity = Capacities::Array(original_data.len() * count);+ let mut mutable = MutableArrayData::with_capacities(+ vec![&original_data],+ false,+ capacity,+ );++ for _ in 0..count {+ mutable.extend(0, 0, original_data.len());+ }++ let data = mutable.freeze();+ let repeated_array = arrow_array::make_array(data);++ let list_arr = GenericListArray::<O>::try_new(+ Arc::new(Field::new("item", value_type.clone(), true)),+ OffsetBuffer::<O>::from_lengths(vec![original_data.len(); count]),+ repeated_array,+ None,+ )?;+ Arc::new(list_arr) as ArrayRef+ }+ None => new_null_array(data_type, count),+ };+ new_values.push(list_arr);+ }++ let lengths = new_values.iter().map(|a| a.len()).collect::<Vec<_>>();+ let new_values: Vec<_> = new_values.iter().map(|a| a.as_ref()).collect();+ let values = compute::concat(&new_values)?;++ Ok(Arc::new(ListArray::try_new(+ Arc::new(Field::new("item", data_type.to_owned(), true)),+ OffsetBuffer::<i32>::from_lengths(lengths),+ values,+ None,+ )?))+}diff --git a/datafusion/functions-array/src/udf.rs b/datafusion/functions-array/src/udf.rsindex 943950447b..9cbcf0a923 100644--- a/datafusion/functions-array/src/udf.rs+++ b/datafusion/functions-array/src/udf.rs@@ -19,7 +19,6 @@use arrow::datatypes::DataType;use arrow::datatypes::Field;-use arrow_schema::DataType::List;use datafusion_common::exec_err;use datafusion_common::plan_err;use datafusion_common::Result;@@ -250,112 +249,6 @@ impl ScalarUDFImpl for ArrayNdims {}}-make_udf_function!(- ArrayEmpty,- array_empty,- array,- "returns true for an empty array or false for a non-empty array.",- array_empty_udf-);--#[derive(Debug)]-pub(super) struct ArrayEmpty {- signature: Signature,- aliases: Vec<String>,-}-impl ArrayEmpty {- pub fn new() -> Self {- Self {- signature: Signature::array(Volatility::Immutable),- aliases: vec![String::from("empty")],- }- }-}--impl ScalarUDFImpl for ArrayEmpty {- fn as_any(&self) -> &dyn Any {- self- }- fn name(&self) -> &str {- "empty"- }-- fn signature(&self) -> &Signature {- &self.signature- }-- fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {- use DataType::*;- Ok(match arg_types[0] {- List(_) | LargeList(_) | FixedSizeList(_, _) => Boolean,- _ => {- return plan_err!("The array_empty function can only accept List/LargeList/FixedSizeList.");- }- })- }-- fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {- let args = ColumnarValue::values_to_arrays(args)?;- crate::kernels::array_empty(&args).map(ColumnarValue::Array)- }-- fn aliases(&self) -> &[String] {- &self.aliases- }-}--make_udf_function!(- ArrayRepeat,- array_repeat,- element count, // arg name- "returns an array containing element `count` times.", // doc- array_repeat_udf // internal function name-);-#[derive(Debug)]-pub(super) struct ArrayRepeat {- signature: Signature,- aliases: Vec<String>,-}--impl ArrayRepeat {- pub fn new() -> Self {- Self {- signature: Signature::variadic_any(Volatility::Immutable),- aliases: vec![String::from("array_repeat"), String::from("list_repeat")],- }- }-}--impl ScalarUDFImpl for ArrayRepeat {- fn as_any(&self) -> &dyn Any {- self- }- fn name(&self) -> &str {- "array_repeat"- }-- fn signature(&self) -> &Signature {- &self.signature- }-- fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {- Ok(List(Arc::new(Field::new(- "item",- arg_types[0].clone(),- true,- ))))- }-- fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {- let args = ColumnarValue::values_to_arrays(args)?;- crate::kernels::array_repeat(&args).map(ColumnarValue::Array)- }-- fn aliases(&self) -> &[String] {- &self.aliases- }-}-make_udf_function!(Flatten,flatten,