comphead commented on code in PR #26266: URL: https://github.com/apache/datafusion/pull/26266#discussion_r4261071443
########## datafusion/spark/src/function/generator/stack.rs: ########## @@ -0,0 +1,462 @@ +// 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. + +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, ListArray, PrimitiveArray, + StructArray, downcast_primitive, new_empty_array, new_null_array, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::compute::{cast, concat, interleave}; +use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, Fields}; +use datafusion_common::types::NativeType; +use datafusion_common::{ + Result, ScalarValue, exec_datafusion_err, internal_err, plan_err, +}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; + +/// Spark-compatible `stack` expression +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#stack> +/// +/// `stack(n, expr1, ..., exprk)` separates `expr1`, ..., `exprk` into `n` rows of +/// `ceil(k / n)` columns named `col0`, `col1`, ... The values fill the rows in +/// order, and the last rows are padded with NULLs. +/// +/// Note: In Spark, `stack` is a Generator that produces rows. In DataFusion, a +/// ScalarUDF can only return one value per row, so the `n` rows are returned as a +/// `List<Struct<col0, col1, ...>>`, which is the data type of Spark's Generator. +/// The caller (e.g. Comet) is expected to unnest the list. +/// +/// As in Spark, `n` must be an integer literal in `[1, 2147483647]`, and the +/// values of a column must have the same type. Only untyped NULLs are coerced, to +/// the type of the first non-NULL value in their column. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkStack { + signature: Signature, +} + +impl Default for SparkStack { + fn default() -> Self { + Self::new() + } +} + +impl SparkStack { + pub fn new() -> Self { + Self { + signature: Signature::user_defined(Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkStack { + fn name(&self) -> &str { + "stack" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + /// Validates the arguments in the order Spark's `Stack.checkInputDataTypes` does. + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let [n, values @ ..] = args.arg_fields else { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 0." + ); + }; + if values.is_empty() { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 1." + ); + } + if !n.data_type().is_integer() { + return plan_err!( + "The first parameter requires the \"INT\" type, however \"{}\" has the type \"{}\".", + n.name(), + n.data_type() + ); + } + let Some(n_value) = args.scalar_arguments.first().copied().flatten() else { + return plan_err!( + "the input `n` should be a foldable \"INT\" expression; however, got \"{}\". Only an integer literal is supported.", + n.name() + ); + }; + let num_fields = values.len().div_ceil(parse_n(n_value)?); + let fields = column_types(values, num_fields)? + .into_iter() + .enumerate() + .map(|(i, data_type)| Field::new(format!("col{i}"), data_type, true)) + .collect::<Fields>(); + Ok(Arc::new(Field::new( + self.name(), + DataType::new_list(DataType::Struct(fields), false), + false, + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + let ScalarFunctionArgs { + args, + number_rows, + return_field, + .. + } = args; + let DataType::List(item) = return_field.data_type() else { + return internal_err!("stack: unexpected return type {return_field}"); + }; + let [ColumnarValue::Scalar(n), values @ ..] = args.as_slice() else { + return internal_err!("stack: `n` must be a scalar"); + }; + let n = parse_n(n)?; + if values.iter().all(|v| matches!(v, ColumnarValue::Scalar(_))) { + let list = stack(values, item, n, 1)?; + return Ok(ColumnarValue::Scalar(ScalarValue::List(Arc::new(list)))); + } + Ok(ColumnarValue::Array(Arc::new(stack( + values, + item, + n, + number_rows, + )?))) + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> { + // Spark does no implicit casts. NULLs are coerced per column at execution. + Ok(arg_types.to_vec()) + } +} + +/// Returns the number of rows `n` to generate per input row. +fn parse_n(n: &ScalarValue) -> Result<usize> { + match n.cast_to(&DataType::Int32) { + Ok(ScalarValue::Int32(Some(v))) if v > 0 => Ok(v as usize), + _ => plan_err!("The `n` must be between (0, 2147483647] (current value = {n})."), + } +} + +/// Returns the type of each output column, which is the type of its first +/// non-NULL value as in Spark's `StackCoercion`. Errors on the first value, in +/// argument order, whose type differs from its column's. +fn column_types(values: &[FieldRef], num_fields: usize) -> Result<Vec<DataType>> { + let mut types = vec![DataType::Null; num_fields]; + for (i, value) in values.iter().enumerate() { + let column_type = &mut types[i % num_fields]; + if column_type.is_null() { + *column_type = value.data_type().clone(); + } + } + for (i, value) in values.iter().enumerate() { + let col = i % num_fields; + let (expected, actual) = (&types[col], value.data_type()); + // Compare logical types, so `Utf8` and `Utf8View` are both Spark's STRING + if !actual.is_null() + && actual != expected + && NativeType::from(actual) != NativeType::from(expected) + { + return plan_err!( + "The data type of the column ({col}) do not have the same type: \"{expected}\" ({}) <> \"{actual}\" ({}).", + col + 1, + i + 1 + ); + } + } + Ok(types) +} + +/// Generates `n` rows of `item`'s struct type for each of `num_rows` input rows. +/// Field `j` of generated row `i` is `values[i * num_fields + j]`, or NULL past the +/// last value. +fn stack( + values: &[ColumnarValue], + item: &FieldRef, + n: usize, + num_rows: usize, +) -> Result<ListArray> { + let DataType::Struct(fields) = item.data_type() else { + return internal_err!("stack: unexpected element type {item}"); + }; + let offsets = OffsetBuffer::try_from_repeated_length(n, num_rows).map_err(|_| { + exec_datafusion_err!( + "stack: {num_rows} rows of {n} generated rows exceed the maximum list size" + ) + })?; + let columns = if n == 1 { + // Every value is a column as is, without copying arrays + values + .iter() + .zip(fields.iter()) + .map(|(value, field)| cast_to(value.to_array(num_rows)?, field.data_type())) + .collect::<Result<_>>()? + } else { + stack_columns(values, fields, n, num_rows)? + }; + let rows = StructArray::try_new(fields.clone(), columns, None)?; + Ok(ListArray::try_new( + Arc::clone(item), + offsets, + Arc::new(rows), + None, + )?) +} + +/// Builds each output column from its `n` values. An array value is read at the +/// input row. A scalar or NULL is a single value array read at index 0, so it is +/// never broadcast. +fn stack_columns( + values: &[ColumnarValue], + fields: &Fields, + n: usize, + num_rows: usize, +) -> Result<Vec<ArrayRef>> { + macro_rules! primitive_helper { + ($t:ty, $sources:ident, $per_row:ident, $num_rows:ident, $data_type:ident) => { + Ok(stack_primitive::<$t>( + &$sources, &$per_row, $num_rows, $data_type, + )) + }; + } + let num_fields = fields.len(); + let mut indices = vec![]; + fields + .iter() + .enumerate() + .map(|(col, field)| { + let data_type = field.data_type(); + if data_type.is_null() { + return Ok(new_null_array(data_type, num_rows * n)); + } + let null = new_null_array(data_type, 1); + let mut sources = Vec::with_capacity(n); + let mut per_row = Vec::with_capacity(n); + for row in 0..n { + let (source, is_array) = match values.get(row * num_fields + col) { + Some(ColumnarValue::Array(array)) if !array.data_type().is_null() => { + (cast_to(Arc::clone(array), data_type)?, true) + } + Some(ColumnarValue::Scalar(scalar)) if !scalar.is_null() => { + (cast_to(scalar.to_array()?, data_type)?, false) + } + _ => (Arc::clone(&null), false), + }; + sources.push(source); + per_row.push(is_array); + } + if !per_row.contains(&true) { + // The same `n` values for every input row + let sources = sources.iter().map(AsRef::as_ref).collect::<Vec<_>>(); + return repeat(concat(&sources)?, num_rows); + } + downcast_primitive! { Review Comment: `Boolean`, `FixedSizeBinary` and `Union` have no arm in arrow's `interleave` and fall to `interleave_fallback`. The round-robin indices never form runs, so it does one `MutableArrayData` extend per element. On the bench shape of 2 columns into 2 rows over 8192 rows, booleans take 182 µs against 10.9 µs for `Int64`. A `Boolean` arm that writes bits the way `stack_primitive` does, or `take` over `concat(&sources)`, which has `take_boolean` and `take_fixed_size_binary`, avoids it. A boolean case in `benches/stack.rs` would cover it. ########## datafusion/spark/src/function/generator/stack.rs: ########## @@ -0,0 +1,462 @@ +// 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. + +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, ListArray, PrimitiveArray, + StructArray, downcast_primitive, new_empty_array, new_null_array, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::compute::{cast, concat, interleave}; +use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, Fields}; +use datafusion_common::types::NativeType; +use datafusion_common::{ + Result, ScalarValue, exec_datafusion_err, internal_err, plan_err, +}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; + +/// Spark-compatible `stack` expression +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#stack> +/// +/// `stack(n, expr1, ..., exprk)` separates `expr1`, ..., `exprk` into `n` rows of +/// `ceil(k / n)` columns named `col0`, `col1`, ... The values fill the rows in +/// order, and the last rows are padded with NULLs. +/// +/// Note: In Spark, `stack` is a Generator that produces rows. In DataFusion, a +/// ScalarUDF can only return one value per row, so the `n` rows are returned as a +/// `List<Struct<col0, col1, ...>>`, which is the data type of Spark's Generator. +/// The caller (e.g. Comet) is expected to unnest the list. +/// +/// As in Spark, `n` must be an integer literal in `[1, 2147483647]`, and the +/// values of a column must have the same type. Only untyped NULLs are coerced, to +/// the type of the first non-NULL value in their column. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkStack { + signature: Signature, +} + +impl Default for SparkStack { + fn default() -> Self { + Self::new() + } +} + +impl SparkStack { + pub fn new() -> Self { + Self { + signature: Signature::user_defined(Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkStack { + fn name(&self) -> &str { + "stack" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + /// Validates the arguments in the order Spark's `Stack.checkInputDataTypes` does. + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let [n, values @ ..] = args.arg_fields else { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 0." + ); + }; + if values.is_empty() { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 1." + ); + } + if !n.data_type().is_integer() { + return plan_err!( + "The first parameter requires the \"INT\" type, however \"{}\" has the type \"{}\".", + n.name(), + n.data_type() + ); + } + let Some(n_value) = args.scalar_arguments.first().copied().flatten() else { + return plan_err!( + "the input `n` should be a foldable \"INT\" expression; however, got \"{}\". Only an integer literal is supported.", + n.name() + ); + }; + let num_fields = values.len().div_ceil(parse_n(n_value)?); + let fields = column_types(values, num_fields)? + .into_iter() + .enumerate() + .map(|(i, data_type)| Field::new(format!("col{i}"), data_type, true)) + .collect::<Fields>(); + Ok(Arc::new(Field::new( + self.name(), + DataType::new_list(DataType::Struct(fields), false), + false, + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + let ScalarFunctionArgs { + args, + number_rows, + return_field, + .. + } = args; + let DataType::List(item) = return_field.data_type() else { + return internal_err!("stack: unexpected return type {return_field}"); + }; + let [ColumnarValue::Scalar(n), values @ ..] = args.as_slice() else { + return internal_err!("stack: `n` must be a scalar"); + }; + let n = parse_n(n)?; + if values.iter().all(|v| matches!(v, ColumnarValue::Scalar(_))) { + let list = stack(values, item, n, 1)?; + return Ok(ColumnarValue::Scalar(ScalarValue::List(Arc::new(list)))); + } + Ok(ColumnarValue::Array(Arc::new(stack( + values, + item, + n, + number_rows, + )?))) + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> { + // Spark does no implicit casts. NULLs are coerced per column at execution. + Ok(arg_types.to_vec()) + } +} + +/// Returns the number of rows `n` to generate per input row. +fn parse_n(n: &ScalarValue) -> Result<usize> { + match n.cast_to(&DataType::Int32) { + Ok(ScalarValue::Int32(Some(v))) if v > 0 => Ok(v as usize), + _ => plan_err!("The `n` must be between (0, 2147483647] (current value = {n})."), + } +} + +/// Returns the type of each output column, which is the type of its first +/// non-NULL value as in Spark's `StackCoercion`. Errors on the first value, in +/// argument order, whose type differs from its column's. +fn column_types(values: &[FieldRef], num_fields: usize) -> Result<Vec<DataType>> { + let mut types = vec![DataType::Null; num_fields]; + for (i, value) in values.iter().enumerate() { + let column_type = &mut types[i % num_fields]; + if column_type.is_null() { + *column_type = value.data_type().clone(); + } + } + for (i, value) in values.iter().enumerate() { + let col = i % num_fields; + let (expected, actual) = (&types[col], value.data_type()); + // Compare logical types, so `Utf8` and `Utf8View` are both Spark's STRING + if !actual.is_null() + && actual != expected Review Comment: This check is stricter than Spark in two cases that only DataFusion produces: - `stack(2, int_col, 0)` fails with `"Int32" (1) <> "Int64" (2)` because integer literals are `Int64` here. In Spark `0` is an `INT`, so the call is accepted. - `stack(2, array(1), [2])` fails with `"List(Int64, field: 'element')" (1) <> "List(Int64)" (2)` because `NativeType` compares list element field names. Spark has no element names, so both are `ARRAY<INT>`. Letting an integer literal take its column's integer type when the value fits, and comparing list and map element types without their field names, would close both. `DataType::equals_datatype` is not a substitute, as it also ignores struct field names, which Spark compares. ########## datafusion/spark/src/function/generator/stack.rs: ########## @@ -0,0 +1,462 @@ +// 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. + +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, ListArray, PrimitiveArray, + StructArray, downcast_primitive, new_empty_array, new_null_array, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::compute::{cast, concat, interleave}; +use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, Fields}; +use datafusion_common::types::NativeType; +use datafusion_common::{ + Result, ScalarValue, exec_datafusion_err, internal_err, plan_err, +}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; + +/// Spark-compatible `stack` expression +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#stack> +/// +/// `stack(n, expr1, ..., exprk)` separates `expr1`, ..., `exprk` into `n` rows of +/// `ceil(k / n)` columns named `col0`, `col1`, ... The values fill the rows in +/// order, and the last rows are padded with NULLs. +/// +/// Note: In Spark, `stack` is a Generator that produces rows. In DataFusion, a +/// ScalarUDF can only return one value per row, so the `n` rows are returned as a +/// `List<Struct<col0, col1, ...>>`, which is the data type of Spark's Generator. +/// The caller (e.g. Comet) is expected to unnest the list. +/// +/// As in Spark, `n` must be an integer literal in `[1, 2147483647]`, and the +/// values of a column must have the same type. Only untyped NULLs are coerced, to +/// the type of the first non-NULL value in their column. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkStack { + signature: Signature, +} + +impl Default for SparkStack { + fn default() -> Self { + Self::new() + } +} + +impl SparkStack { + pub fn new() -> Self { + Self { + signature: Signature::user_defined(Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkStack { + fn name(&self) -> &str { + "stack" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + /// Validates the arguments in the order Spark's `Stack.checkInputDataTypes` does. + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let [n, values @ ..] = args.arg_fields else { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 0." + ); + }; + if values.is_empty() { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 1." + ); + } + if !n.data_type().is_integer() { + return plan_err!( + "The first parameter requires the \"INT\" type, however \"{}\" has the type \"{}\".", + n.name(), + n.data_type() + ); + } + let Some(n_value) = args.scalar_arguments.first().copied().flatten() else { + return plan_err!( + "the input `n` should be a foldable \"INT\" expression; however, got \"{}\". Only an integer literal is supported.", + n.name() + ); + }; + let num_fields = values.len().div_ceil(parse_n(n_value)?); + let fields = column_types(values, num_fields)? + .into_iter() + .enumerate() + .map(|(i, data_type)| Field::new(format!("col{i}"), data_type, true)) + .collect::<Fields>(); + Ok(Arc::new(Field::new( + self.name(), + DataType::new_list(DataType::Struct(fields), false), + false, + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + let ScalarFunctionArgs { + args, + number_rows, + return_field, + .. + } = args; + let DataType::List(item) = return_field.data_type() else { + return internal_err!("stack: unexpected return type {return_field}"); + }; + let [ColumnarValue::Scalar(n), values @ ..] = args.as_slice() else { + return internal_err!("stack: `n` must be a scalar"); + }; + let n = parse_n(n)?; + if values.iter().all(|v| matches!(v, ColumnarValue::Scalar(_))) { + let list = stack(values, item, n, 1)?; + return Ok(ColumnarValue::Scalar(ScalarValue::List(Arc::new(list)))); + } + Ok(ColumnarValue::Array(Arc::new(stack( + values, + item, + n, + number_rows, + )?))) + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> { + // Spark does no implicit casts. NULLs are coerced per column at execution. + Ok(arg_types.to_vec()) + } +} + +/// Returns the number of rows `n` to generate per input row. +fn parse_n(n: &ScalarValue) -> Result<usize> { + match n.cast_to(&DataType::Int32) { + Ok(ScalarValue::Int32(Some(v))) if v > 0 => Ok(v as usize), + _ => plan_err!("The `n` must be between (0, 2147483647] (current value = {n})."), + } +} + +/// Returns the type of each output column, which is the type of its first +/// non-NULL value as in Spark's `StackCoercion`. Errors on the first value, in +/// argument order, whose type differs from its column's. +fn column_types(values: &[FieldRef], num_fields: usize) -> Result<Vec<DataType>> { Review Comment: One pass is enough. A column's first non-NULL value comes before its later values in argument order, so the type seen so far is already final when each value is checked. Setting the type on the first non-NULL value and checking later values against it reports the same first mismatch. ########## datafusion/spark/src/function/generator/stack.rs: ########## @@ -0,0 +1,462 @@ +// 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. + +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, ListArray, PrimitiveArray, + StructArray, downcast_primitive, new_empty_array, new_null_array, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::compute::{cast, concat, interleave}; +use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, Fields}; +use datafusion_common::types::NativeType; +use datafusion_common::{ + Result, ScalarValue, exec_datafusion_err, internal_err, plan_err, +}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; + +/// Spark-compatible `stack` expression +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#stack> +/// +/// `stack(n, expr1, ..., exprk)` separates `expr1`, ..., `exprk` into `n` rows of +/// `ceil(k / n)` columns named `col0`, `col1`, ... The values fill the rows in +/// order, and the last rows are padded with NULLs. +/// +/// Note: In Spark, `stack` is a Generator that produces rows. In DataFusion, a +/// ScalarUDF can only return one value per row, so the `n` rows are returned as a +/// `List<Struct<col0, col1, ...>>`, which is the data type of Spark's Generator. +/// The caller (e.g. Comet) is expected to unnest the list. +/// +/// As in Spark, `n` must be an integer literal in `[1, 2147483647]`, and the +/// values of a column must have the same type. Only untyped NULLs are coerced, to +/// the type of the first non-NULL value in their column. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkStack { + signature: Signature, +} + +impl Default for SparkStack { + fn default() -> Self { + Self::new() + } +} + +impl SparkStack { + pub fn new() -> Self { + Self { + signature: Signature::user_defined(Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkStack { + fn name(&self) -> &str { + "stack" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + /// Validates the arguments in the order Spark's `Stack.checkInputDataTypes` does. + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let [n, values @ ..] = args.arg_fields else { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 0." + ); + }; + if values.is_empty() { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 1." + ); + } + if !n.data_type().is_integer() { + return plan_err!( + "The first parameter requires the \"INT\" type, however \"{}\" has the type \"{}\".", + n.name(), + n.data_type() + ); + } + let Some(n_value) = args.scalar_arguments.first().copied().flatten() else { + return plan_err!( + "the input `n` should be a foldable \"INT\" expression; however, got \"{}\". Only an integer literal is supported.", + n.name() + ); + }; + let num_fields = values.len().div_ceil(parse_n(n_value)?); + let fields = column_types(values, num_fields)? + .into_iter() + .enumerate() + .map(|(i, data_type)| Field::new(format!("col{i}"), data_type, true)) + .collect::<Fields>(); + Ok(Arc::new(Field::new( + self.name(), + DataType::new_list(DataType::Struct(fields), false), + false, + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + let ScalarFunctionArgs { + args, + number_rows, + return_field, + .. + } = args; + let DataType::List(item) = return_field.data_type() else { + return internal_err!("stack: unexpected return type {return_field}"); + }; + let [ColumnarValue::Scalar(n), values @ ..] = args.as_slice() else { + return internal_err!("stack: `n` must be a scalar"); + }; + let n = parse_n(n)?; + if values.iter().all(|v| matches!(v, ColumnarValue::Scalar(_))) { + let list = stack(values, item, n, 1)?; + return Ok(ColumnarValue::Scalar(ScalarValue::List(Arc::new(list)))); + } + Ok(ColumnarValue::Array(Arc::new(stack( + values, + item, + n, + number_rows, + )?))) + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> { + // Spark does no implicit casts. NULLs are coerced per column at execution. + Ok(arg_types.to_vec()) + } +} + +/// Returns the number of rows `n` to generate per input row. +fn parse_n(n: &ScalarValue) -> Result<usize> { + match n.cast_to(&DataType::Int32) { + Ok(ScalarValue::Int32(Some(v))) if v > 0 => Ok(v as usize), + _ => plan_err!("The `n` must be between (0, 2147483647] (current value = {n})."), + } +} + +/// Returns the type of each output column, which is the type of its first +/// non-NULL value as in Spark's `StackCoercion`. Errors on the first value, in +/// argument order, whose type differs from its column's. +fn column_types(values: &[FieldRef], num_fields: usize) -> Result<Vec<DataType>> { + let mut types = vec![DataType::Null; num_fields]; + for (i, value) in values.iter().enumerate() { + let column_type = &mut types[i % num_fields]; + if column_type.is_null() { + *column_type = value.data_type().clone(); + } + } + for (i, value) in values.iter().enumerate() { + let col = i % num_fields; + let (expected, actual) = (&types[col], value.data_type()); + // Compare logical types, so `Utf8` and `Utf8View` are both Spark's STRING + if !actual.is_null() + && actual != expected + && NativeType::from(actual) != NativeType::from(expected) + { + return plan_err!( + "The data type of the column ({col}) do not have the same type: \"{expected}\" ({}) <> \"{actual}\" ({}).", + col + 1, + i + 1 + ); + } + } + Ok(types) +} + +/// Generates `n` rows of `item`'s struct type for each of `num_rows` input rows. +/// Field `j` of generated row `i` is `values[i * num_fields + j]`, or NULL past the +/// last value. +fn stack( + values: &[ColumnarValue], + item: &FieldRef, + n: usize, + num_rows: usize, +) -> Result<ListArray> { + let DataType::Struct(fields) = item.data_type() else { + return internal_err!("stack: unexpected element type {item}"); + }; + let offsets = OffsetBuffer::try_from_repeated_length(n, num_rows).map_err(|_| { + exec_datafusion_err!( + "stack: {num_rows} rows of {n} generated rows exceed the maximum list size" + ) + })?; + let columns = if n == 1 { + // Every value is a column as is, without copying arrays + values + .iter() + .zip(fields.iter()) + .map(|(value, field)| cast_to(value.to_array(num_rows)?, field.data_type())) + .collect::<Result<_>>()? + } else { + stack_columns(values, fields, n, num_rows)? + }; + let rows = StructArray::try_new(fields.clone(), columns, None)?; + Ok(ListArray::try_new( + Arc::clone(item), + offsets, + Arc::new(rows), + None, + )?) +} + +/// Builds each output column from its `n` values. An array value is read at the +/// input row. A scalar or NULL is a single value array read at index 0, so it is +/// never broadcast. +fn stack_columns( + values: &[ColumnarValue], + fields: &Fields, + n: usize, + num_rows: usize, +) -> Result<Vec<ArrayRef>> { + macro_rules! primitive_helper { + ($t:ty, $sources:ident, $per_row:ident, $num_rows:ident, $data_type:ident) => { + Ok(stack_primitive::<$t>( + &$sources, &$per_row, $num_rows, $data_type, + )) + }; + } + let num_fields = fields.len(); + let mut indices = vec![]; + fields + .iter() + .enumerate() + .map(|(col, field)| { + let data_type = field.data_type(); + if data_type.is_null() { + return Ok(new_null_array(data_type, num_rows * n)); + } + let null = new_null_array(data_type, 1); + let mut sources = Vec::with_capacity(n); + let mut per_row = Vec::with_capacity(n); + for row in 0..n { + let (source, is_array) = match values.get(row * num_fields + col) { + Some(ColumnarValue::Array(array)) if !array.data_type().is_null() => { + (cast_to(Arc::clone(array), data_type)?, true) + } + Some(ColumnarValue::Scalar(scalar)) if !scalar.is_null() => { + (cast_to(scalar.to_array()?, data_type)?, false) + } + _ => (Arc::clone(&null), false), + }; + sources.push(source); + per_row.push(is_array); + } + if !per_row.contains(&true) { Review Comment: `repeat` multiplies the buffer list of view arrays. `concat_byte_view` appends each input's `data_buffers()` without dedup, so every doubling doubles the handles. With two `Utf8View` keys longer than 12 bytes and 8192 rows, the key column ends up with 16384 buffer handles, and `get_array_memory_size()` reports 268,697,712 bytes for 16384 values of 22 bytes. Any reservation computed from that size is inflated by the same factor. Nested types with view children inherit it. This branch also runs before the primitive dispatch, so all-scalar primitive columns take `repeat` although `stack_primitive` already fills scalars. The measured gain is for `Utf8` keys. Restricting `repeat` to `Utf8`, `LargeUtf8`, `Binary` and `LargeBinary`, and sending other types to `interleave`, which adds each source buffer once, covers both. ########## datafusion/sqllogictest/test_files/spark/generator/stack.slt: ########## @@ -0,0 +1,156 @@ +# 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. + +# Tests for Spark-compatible stack function +# https://spark.apache.org/docs/latest/api/sql/index.html#stack +# +# Test cases derived from Spark GeneratorFunctionSuite, GeneratorExpressionSuite, +# TypeCoercionSuite and the generators.sql, table-valued-functions.sql and +# join-lateral.sql golden files: +# https://github.com/apache/spark/blob/master/sql/core/src/test/scala/org/apache/spark/sql/GeneratorFunctionSuite.scala +# +# Spark's stack generates rows. Here it returns them as a list of structs, which +# unnest expands. `n` must be a bare integer literal, so it is never cast. + +# Values fill n rows of ceil(k / n) columns in order, padded with NULLs +query ? +SELECT stack(1, 1, 2, 3); +---- +[{col0: 1, col1: 2, col2: 3}] + +query ? +SELECT stack(2, 1, 2, 3); +---- +[{col0: 1, col1: 2}, {col0: 3, col1: NULL}] + +query ? +SELECT stack(3, 1, 2, 3); +---- +[{col0: 1}, {col0: 2}, {col0: 3}] + +query ? +SELECT stack(4, 1, 2, 3); +---- +[{col0: 1}, {col0: 2}, {col0: 3}, {col0: NULL}] + +query TB +SELECT arrow_typeof(stack(2, a, b, c)), arrow_field(stack(2, a, b, c))['nullable'] FROM (VALUES (1, 2, 3)) AS t(a, b, c); +---- +List(non-null Struct("col0": Int64, "col1": Int64)) false + +# Various column types +query ? +SELECT stack(3, 1, 1.1, 'a', 2, 2.2, 'b', 3, 3.3, 'c'); +---- +[{col0: 1, col1: 1.1, col2: a}, {col0: 2, col1: 2.2, col2: b}, {col0: 3, col1: 3.3, col2: c}] + +query ? +SELECT stack(2, 1.5::DECIMAL(10, 2), '2024-01-01'::DATE, true, [1, 2], named_struct('a', 1), NULL, NULL, false, [3], named_struct('a', 2)); +---- +[{col0: 1.50, col1: 2024-01-01, col2: true, col3: [1, 2], col4: {a: 1}}, {col0: NULL, col1: NULL, col2: false, col3: [3], col4: {a: 2}}] + +# NULLs take the type of the first non-NULL value in their column +query ? +SELECT stack(3, 1, 1.1, NULL, 2, NULL, 'b', NULL, 3.3, 'c'); +---- +[{col0: 1, col1: 1.1, col2: NULL}, {col0: 2, col1: NULL, col2: b}, {col0: NULL, col1: 3.3, col2: c}] + +query TTTT +SELECT arrow_typeof(stack(3, 1, 2, NULL)), arrow_typeof(stack(3, NULL, '2', '3')), arrow_typeof(stack(2, NULL, NULL, 1, '2')), arrow_typeof(stack(3, NULL, NULL, NULL)); +---- +List(non-null Struct("col0": Int64)) List(non-null Struct("col0": Utf8)) List(non-null Struct("col0": Int64, "col1": Utf8)) List(non-null Struct("col0": Null)) + +# Array inputs +query ? +SELECT stack(2, a, b, c) FROM (VALUES (1, 2, 3), (4, 5, 6)) AS t(a, b, c); +---- +[{col0: 1, col1: 2}, {col0: 3, col1: NULL}] +[{col0: 4, col1: 5}, {col0: 6, col1: NULL}] + +# Array, scalar and NULL values in the same columns Review Comment: Test notes: - This case does not mix an array and a scalar in one column. Column 0 is `[a, b]` and column 1 is `[100, NULL]`, so the scalar fill in `stack_primitive` is only reached by the Rust test. A query with the layout of `test_stack_matches_interleave`, such as `stack(3, i, 'a', s, -1, NULL, 'b', i)` over a few rows, covers the strided, `repeat` and `interleave` paths in SQL. The 1000-row half of that Rust test can then go. The zero-row half has to stay, since `FilterExec` never emits an empty batch. - The `unnest(unnest(stack(2, 1, 2, 3)))` and `WHERE a > 1` cases do not exercise `stack`. The first is literal-only and is folded once during planning, so it only tests `unnest` of a constant. In the second no batch reaches the projection. - `stack(3, 1, 1.1, 'a', ...)` is covered by the NULL variant below it, and the `(1) ... (5)` mismatch case by the argument-order case after it. - There is no dictionary-encoded input. `stack(2, 'a', d)` and `stack(2, d, 'a')` with `d` cast to `Dictionary(Int32, Utf8)` cover the cast in both directions. ########## datafusion/spark/src/function/generator/stack.rs: ########## @@ -0,0 +1,462 @@ +// 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. + +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, ListArray, PrimitiveArray, + StructArray, downcast_primitive, new_empty_array, new_null_array, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::compute::{cast, concat, interleave}; +use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, Fields}; +use datafusion_common::types::NativeType; +use datafusion_common::{ + Result, ScalarValue, exec_datafusion_err, internal_err, plan_err, +}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; + +/// Spark-compatible `stack` expression +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#stack> +/// +/// `stack(n, expr1, ..., exprk)` separates `expr1`, ..., `exprk` into `n` rows of +/// `ceil(k / n)` columns named `col0`, `col1`, ... The values fill the rows in +/// order, and the last rows are padded with NULLs. +/// +/// Note: In Spark, `stack` is a Generator that produces rows. In DataFusion, a +/// ScalarUDF can only return one value per row, so the `n` rows are returned as a +/// `List<Struct<col0, col1, ...>>`, which is the data type of Spark's Generator. +/// The caller (e.g. Comet) is expected to unnest the list. +/// +/// As in Spark, `n` must be an integer literal in `[1, 2147483647]`, and the Review Comment: "As in Spark" is wrong for the literal rule. Spark accepts any foldable `INT` (`hasFoldableNumRows`), as the PR description and `stack.slt` say. The `expr_fn` doc in `generator/mod.rs` also does not mention that `n` must be a literal or that the result needs `unnest`. ########## datafusion/spark/src/function/generator/stack.rs: ########## @@ -0,0 +1,462 @@ +// 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. + +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, ListArray, PrimitiveArray, + StructArray, downcast_primitive, new_empty_array, new_null_array, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::compute::{cast, concat, interleave}; +use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, Fields}; +use datafusion_common::types::NativeType; +use datafusion_common::{ + Result, ScalarValue, exec_datafusion_err, internal_err, plan_err, +}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; + +/// Spark-compatible `stack` expression +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#stack> +/// +/// `stack(n, expr1, ..., exprk)` separates `expr1`, ..., `exprk` into `n` rows of +/// `ceil(k / n)` columns named `col0`, `col1`, ... The values fill the rows in +/// order, and the last rows are padded with NULLs. +/// +/// Note: In Spark, `stack` is a Generator that produces rows. In DataFusion, a +/// ScalarUDF can only return one value per row, so the `n` rows are returned as a +/// `List<Struct<col0, col1, ...>>`, which is the data type of Spark's Generator. +/// The caller (e.g. Comet) is expected to unnest the list. +/// +/// As in Spark, `n` must be an integer literal in `[1, 2147483647]`, and the +/// values of a column must have the same type. Only untyped NULLs are coerced, to +/// the type of the first non-NULL value in their column. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkStack { + signature: Signature, +} + +impl Default for SparkStack { + fn default() -> Self { + Self::new() + } +} + +impl SparkStack { + pub fn new() -> Self { + Self { + signature: Signature::user_defined(Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkStack { + fn name(&self) -> &str { + "stack" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + /// Validates the arguments in the order Spark's `Stack.checkInputDataTypes` does. + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let [n, values @ ..] = args.arg_fields else { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 0." + ); + }; + if values.is_empty() { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 1." + ); + } + if !n.data_type().is_integer() { + return plan_err!( + "The first parameter requires the \"INT\" type, however \"{}\" has the type \"{}\".", + n.name(), + n.data_type() + ); + } + let Some(n_value) = args.scalar_arguments.first().copied().flatten() else { + return plan_err!( + "the input `n` should be a foldable \"INT\" expression; however, got \"{}\". Only an integer literal is supported.", + n.name() + ); + }; + let num_fields = values.len().div_ceil(parse_n(n_value)?); + let fields = column_types(values, num_fields)? + .into_iter() + .enumerate() + .map(|(i, data_type)| Field::new(format!("col{i}"), data_type, true)) + .collect::<Fields>(); + Ok(Arc::new(Field::new( + self.name(), + DataType::new_list(DataType::Struct(fields), false), + false, + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + let ScalarFunctionArgs { + args, + number_rows, + return_field, + .. + } = args; + let DataType::List(item) = return_field.data_type() else { + return internal_err!("stack: unexpected return type {return_field}"); + }; + let [ColumnarValue::Scalar(n), values @ ..] = args.as_slice() else { + return internal_err!("stack: `n` must be a scalar"); + }; + let n = parse_n(n)?; + if values.iter().all(|v| matches!(v, ColumnarValue::Scalar(_))) { + let list = stack(values, item, n, 1)?; + return Ok(ColumnarValue::Scalar(ScalarValue::List(Arc::new(list)))); + } + Ok(ColumnarValue::Array(Arc::new(stack( + values, + item, + n, + number_rows, + )?))) + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> { + // Spark does no implicit casts. NULLs are coerced per column at execution. + Ok(arg_types.to_vec()) + } +} + +/// Returns the number of rows `n` to generate per input row. +fn parse_n(n: &ScalarValue) -> Result<usize> { + match n.cast_to(&DataType::Int32) { + Ok(ScalarValue::Int32(Some(v))) if v > 0 => Ok(v as usize), + _ => plan_err!("The `n` must be between (0, 2147483647] (current value = {n})."), + } +} + +/// Returns the type of each output column, which is the type of its first +/// non-NULL value as in Spark's `StackCoercion`. Errors on the first value, in +/// argument order, whose type differs from its column's. +fn column_types(values: &[FieldRef], num_fields: usize) -> Result<Vec<DataType>> { + let mut types = vec![DataType::Null; num_fields]; + for (i, value) in values.iter().enumerate() { + let column_type = &mut types[i % num_fields]; + if column_type.is_null() { + *column_type = value.data_type().clone(); + } + } + for (i, value) in values.iter().enumerate() { + let col = i % num_fields; + let (expected, actual) = (&types[col], value.data_type()); + // Compare logical types, so `Utf8` and `Utf8View` are both Spark's STRING + if !actual.is_null() + && actual != expected + && NativeType::from(actual) != NativeType::from(expected) + { + return plan_err!( + "The data type of the column ({col}) do not have the same type: \"{expected}\" ({}) <> \"{actual}\" ({}).", + col + 1, + i + 1 + ); + } + } + Ok(types) +} + +/// Generates `n` rows of `item`'s struct type for each of `num_rows` input rows. +/// Field `j` of generated row `i` is `values[i * num_fields + j]`, or NULL past the +/// last value. +fn stack( + values: &[ColumnarValue], + item: &FieldRef, + n: usize, + num_rows: usize, +) -> Result<ListArray> { + let DataType::Struct(fields) = item.data_type() else { + return internal_err!("stack: unexpected element type {item}"); + }; + let offsets = OffsetBuffer::try_from_repeated_length(n, num_rows).map_err(|_| { + exec_datafusion_err!( + "stack: {num_rows} rows of {n} generated rows exceed the maximum list size" + ) + })?; + let columns = if n == 1 { + // Every value is a column as is, without copying arrays + values + .iter() + .zip(fields.iter()) + .map(|(value, field)| cast_to(value.to_array(num_rows)?, field.data_type())) + .collect::<Result<_>>()? + } else { + stack_columns(values, fields, n, num_rows)? + }; + let rows = StructArray::try_new(fields.clone(), columns, None)?; + Ok(ListArray::try_new( + Arc::clone(item), + offsets, + Arc::new(rows), + None, + )?) +} + +/// Builds each output column from its `n` values. An array value is read at the +/// input row. A scalar or NULL is a single value array read at index 0, so it is +/// never broadcast. +fn stack_columns( + values: &[ColumnarValue], + fields: &Fields, + n: usize, + num_rows: usize, +) -> Result<Vec<ArrayRef>> { + macro_rules! primitive_helper { + ($t:ty, $sources:ident, $per_row:ident, $num_rows:ident, $data_type:ident) => { + Ok(stack_primitive::<$t>( + &$sources, &$per_row, $num_rows, $data_type, + )) + }; + } + let num_fields = fields.len(); + let mut indices = vec![]; + fields + .iter() + .enumerate() + .map(|(col, field)| { + let data_type = field.data_type(); + if data_type.is_null() { + return Ok(new_null_array(data_type, num_rows * n)); + } + let null = new_null_array(data_type, 1); + let mut sources = Vec::with_capacity(n); + let mut per_row = Vec::with_capacity(n); + for row in 0..n { + let (source, is_array) = match values.get(row * num_fields + col) { + Some(ColumnarValue::Array(array)) if !array.data_type().is_null() => { + (cast_to(Arc::clone(array), data_type)?, true) + } + Some(ColumnarValue::Scalar(scalar)) if !scalar.is_null() => { + (cast_to(scalar.to_array()?, data_type)?, false) + } + _ => (Arc::clone(&null), false), + }; + sources.push(source); + per_row.push(is_array); + } + if !per_row.contains(&true) { + // The same `n` values for every input row + let sources = sources.iter().map(AsRef::as_ref).collect::<Vec<_>>(); + return repeat(concat(&sources)?, num_rows); + } + downcast_primitive! { + data_type => (primitive_helper, sources, per_row, num_rows, data_type), + _ => { + indices.clear(); + indices.try_reserve(num_rows * n).map_err(|e| { + exec_datafusion_err!("stack: failed to allocate indices: {e}") + })?; + for input_row in 0..num_rows { + indices.extend(per_row.iter().enumerate().map(|(i, &per_row)| { + (i, if per_row { input_row } else { 0 }) + })); + } + let sources = sources.iter().map(AsRef::as_ref).collect::<Vec<_>>(); + Ok(interleave(&sources, &indices)?) + } + } + }) + .collect() +} + +/// Writes source `i` to every `n`-th slot starting at `i`. This avoids the +/// index lookups of `interleave`, and only visits the NULL slots of the +/// validity. It is about 2-3x faster for primitive types. +fn stack_primitive<T: ArrowPrimitiveType>( + sources: &[ArrayRef], + per_row: &[bool], + num_rows: usize, + data_type: &DataType, +) -> ArrayRef { + // `values[i..]` below needs at least one row + if num_rows == 0 { + return new_empty_array(data_type); + } + let n = sources.len(); + let len = num_rows * n; + let mut values = vec![T::Native::default(); len]; + let mut validity: Option<BooleanBufferBuilder> = None; Review Comment: `NullBufferBuilder::new_with_len(len)` does this lazily. `set_bit` materializes an all-valid bitmap on first use and `build()` returns `Option<NullBuffer>`, which replaces the `Option<BooleanBufferBuilder>`, the `get_or_insert_with` block and the final `map`. ########## datafusion/spark/src/function/generator/stack.rs: ########## @@ -0,0 +1,462 @@ +// 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. + +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, ListArray, PrimitiveArray, + StructArray, downcast_primitive, new_empty_array, new_null_array, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::compute::{cast, concat, interleave}; +use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, Fields}; +use datafusion_common::types::NativeType; +use datafusion_common::{ + Result, ScalarValue, exec_datafusion_err, internal_err, plan_err, +}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; + +/// Spark-compatible `stack` expression +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#stack> +/// +/// `stack(n, expr1, ..., exprk)` separates `expr1`, ..., `exprk` into `n` rows of +/// `ceil(k / n)` columns named `col0`, `col1`, ... The values fill the rows in +/// order, and the last rows are padded with NULLs. +/// +/// Note: In Spark, `stack` is a Generator that produces rows. In DataFusion, a +/// ScalarUDF can only return one value per row, so the `n` rows are returned as a +/// `List<Struct<col0, col1, ...>>`, which is the data type of Spark's Generator. +/// The caller (e.g. Comet) is expected to unnest the list. +/// +/// As in Spark, `n` must be an integer literal in `[1, 2147483647]`, and the +/// values of a column must have the same type. Only untyped NULLs are coerced, to +/// the type of the first non-NULL value in their column. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkStack { + signature: Signature, +} + +impl Default for SparkStack { + fn default() -> Self { + Self::new() + } +} + +impl SparkStack { + pub fn new() -> Self { + Self { + signature: Signature::user_defined(Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkStack { + fn name(&self) -> &str { + "stack" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + /// Validates the arguments in the order Spark's `Stack.checkInputDataTypes` does. + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let [n, values @ ..] = args.arg_fields else { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 0." + ); + }; + if values.is_empty() { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 1." + ); + } + if !n.data_type().is_integer() { + return plan_err!( + "The first parameter requires the \"INT\" type, however \"{}\" has the type \"{}\".", + n.name(), + n.data_type() + ); + } + let Some(n_value) = args.scalar_arguments.first().copied().flatten() else { + return plan_err!( + "the input `n` should be a foldable \"INT\" expression; however, got \"{}\". Only an integer literal is supported.", + n.name() + ); + }; + let num_fields = values.len().div_ceil(parse_n(n_value)?); + let fields = column_types(values, num_fields)? + .into_iter() + .enumerate() + .map(|(i, data_type)| Field::new(format!("col{i}"), data_type, true)) + .collect::<Fields>(); + Ok(Arc::new(Field::new( + self.name(), + DataType::new_list(DataType::Struct(fields), false), + false, + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + let ScalarFunctionArgs { + args, + number_rows, + return_field, + .. + } = args; + let DataType::List(item) = return_field.data_type() else { + return internal_err!("stack: unexpected return type {return_field}"); + }; + let [ColumnarValue::Scalar(n), values @ ..] = args.as_slice() else { + return internal_err!("stack: `n` must be a scalar"); + }; + let n = parse_n(n)?; + if values.iter().all(|v| matches!(v, ColumnarValue::Scalar(_))) { + let list = stack(values, item, n, 1)?; + return Ok(ColumnarValue::Scalar(ScalarValue::List(Arc::new(list)))); + } + Ok(ColumnarValue::Array(Arc::new(stack( + values, + item, + n, + number_rows, + )?))) + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> { + // Spark does no implicit casts. NULLs are coerced per column at execution. + Ok(arg_types.to_vec()) + } +} + +/// Returns the number of rows `n` to generate per input row. +fn parse_n(n: &ScalarValue) -> Result<usize> { + match n.cast_to(&DataType::Int32) { + Ok(ScalarValue::Int32(Some(v))) if v > 0 => Ok(v as usize), + _ => plan_err!("The `n` must be between (0, 2147483647] (current value = {n})."), + } +} + +/// Returns the type of each output column, which is the type of its first +/// non-NULL value as in Spark's `StackCoercion`. Errors on the first value, in +/// argument order, whose type differs from its column's. +fn column_types(values: &[FieldRef], num_fields: usize) -> Result<Vec<DataType>> { + let mut types = vec![DataType::Null; num_fields]; + for (i, value) in values.iter().enumerate() { + let column_type = &mut types[i % num_fields]; + if column_type.is_null() { + *column_type = value.data_type().clone(); + } + } + for (i, value) in values.iter().enumerate() { + let col = i % num_fields; + let (expected, actual) = (&types[col], value.data_type()); + // Compare logical types, so `Utf8` and `Utf8View` are both Spark's STRING + if !actual.is_null() + && actual != expected + && NativeType::from(actual) != NativeType::from(expected) + { + return plan_err!( + "The data type of the column ({col}) do not have the same type: \"{expected}\" ({}) <> \"{actual}\" ({}).", + col + 1, + i + 1 + ); + } + } + Ok(types) +} + +/// Generates `n` rows of `item`'s struct type for each of `num_rows` input rows. +/// Field `j` of generated row `i` is `values[i * num_fields + j]`, or NULL past the +/// last value. +fn stack( + values: &[ColumnarValue], + item: &FieldRef, + n: usize, + num_rows: usize, +) -> Result<ListArray> { + let DataType::Struct(fields) = item.data_type() else { + return internal_err!("stack: unexpected element type {item}"); + }; + let offsets = OffsetBuffer::try_from_repeated_length(n, num_rows).map_err(|_| { + exec_datafusion_err!( + "stack: {num_rows} rows of {n} generated rows exceed the maximum list size" + ) + })?; + let columns = if n == 1 { + // Every value is a column as is, without copying arrays + values + .iter() + .zip(fields.iter()) + .map(|(value, field)| cast_to(value.to_array(num_rows)?, field.data_type())) + .collect::<Result<_>>()? + } else { + stack_columns(values, fields, n, num_rows)? + }; + let rows = StructArray::try_new(fields.clone(), columns, None)?; + Ok(ListArray::try_new( + Arc::clone(item), + offsets, + Arc::new(rows), + None, + )?) +} + +/// Builds each output column from its `n` values. An array value is read at the +/// input row. A scalar or NULL is a single value array read at index 0, so it is +/// never broadcast. +fn stack_columns( + values: &[ColumnarValue], + fields: &Fields, + n: usize, + num_rows: usize, +) -> Result<Vec<ArrayRef>> { + macro_rules! primitive_helper { + ($t:ty, $sources:ident, $per_row:ident, $num_rows:ident, $data_type:ident) => { + Ok(stack_primitive::<$t>( + &$sources, &$per_row, $num_rows, $data_type, + )) + }; + } + let num_fields = fields.len(); + let mut indices = vec![]; + fields + .iter() + .enumerate() + .map(|(col, field)| { + let data_type = field.data_type(); + if data_type.is_null() { + return Ok(new_null_array(data_type, num_rows * n)); + } + let null = new_null_array(data_type, 1); + let mut sources = Vec::with_capacity(n); Review Comment: A large `n` aborts the process instead of returning an error (reasoned from the code, not run). `SELECT stack(2147483647, 1)` passes the offsets check with one row and is constant folded during planning. Each column then allocates `sources` and `per_row` with `n` entries, about 32 GiB for `sources` alone, before the output buffers. `range` in `functions-nested` guards the same case with `try_reserve` and a "Range too large to materialize" error. Padding rows also do not need a source entry each. ########## datafusion/spark/src/function/generator/stack.rs: ########## @@ -0,0 +1,462 @@ +// 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. + +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, ListArray, PrimitiveArray, + StructArray, downcast_primitive, new_empty_array, new_null_array, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::compute::{cast, concat, interleave}; +use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, Fields}; +use datafusion_common::types::NativeType; +use datafusion_common::{ + Result, ScalarValue, exec_datafusion_err, internal_err, plan_err, +}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; + +/// Spark-compatible `stack` expression +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#stack> +/// +/// `stack(n, expr1, ..., exprk)` separates `expr1`, ..., `exprk` into `n` rows of +/// `ceil(k / n)` columns named `col0`, `col1`, ... The values fill the rows in +/// order, and the last rows are padded with NULLs. +/// +/// Note: In Spark, `stack` is a Generator that produces rows. In DataFusion, a +/// ScalarUDF can only return one value per row, so the `n` rows are returned as a +/// `List<Struct<col0, col1, ...>>`, which is the data type of Spark's Generator. +/// The caller (e.g. Comet) is expected to unnest the list. +/// +/// As in Spark, `n` must be an integer literal in `[1, 2147483647]`, and the +/// values of a column must have the same type. Only untyped NULLs are coerced, to +/// the type of the first non-NULL value in their column. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkStack { + signature: Signature, +} + +impl Default for SparkStack { + fn default() -> Self { + Self::new() + } +} + +impl SparkStack { + pub fn new() -> Self { + Self { + signature: Signature::user_defined(Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkStack { + fn name(&self) -> &str { + "stack" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + /// Validates the arguments in the order Spark's `Stack.checkInputDataTypes` does. + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let [n, values @ ..] = args.arg_fields else { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 0." + ); + }; + if values.is_empty() { + return plan_err!( + "The `stack` requires > 1 parameters but the actual number is 1." + ); + } + if !n.data_type().is_integer() { + return plan_err!( + "The first parameter requires the \"INT\" type, however \"{}\" has the type \"{}\".", + n.name(), + n.data_type() + ); + } + let Some(n_value) = args.scalar_arguments.first().copied().flatten() else { + return plan_err!( + "the input `n` should be a foldable \"INT\" expression; however, got \"{}\". Only an integer literal is supported.", + n.name() + ); + }; + let num_fields = values.len().div_ceil(parse_n(n_value)?); + let fields = column_types(values, num_fields)? + .into_iter() + .enumerate() + .map(|(i, data_type)| Field::new(format!("col{i}"), data_type, true)) + .collect::<Fields>(); + Ok(Arc::new(Field::new( + self.name(), + DataType::new_list(DataType::Struct(fields), false), + false, + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + let ScalarFunctionArgs { + args, + number_rows, + return_field, + .. + } = args; + let DataType::List(item) = return_field.data_type() else { + return internal_err!("stack: unexpected return type {return_field}"); + }; + let [ColumnarValue::Scalar(n), values @ ..] = args.as_slice() else { + return internal_err!("stack: `n` must be a scalar"); + }; + let n = parse_n(n)?; + if values.iter().all(|v| matches!(v, ColumnarValue::Scalar(_))) { + let list = stack(values, item, n, 1)?; + return Ok(ColumnarValue::Scalar(ScalarValue::List(Arc::new(list)))); + } + Ok(ColumnarValue::Array(Arc::new(stack( + values, + item, + n, + number_rows, + )?))) + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> { + // Spark does no implicit casts. NULLs are coerced per column at execution. + Ok(arg_types.to_vec()) + } +} + +/// Returns the number of rows `n` to generate per input row. +fn parse_n(n: &ScalarValue) -> Result<usize> { + match n.cast_to(&DataType::Int32) { + Ok(ScalarValue::Int32(Some(v))) if v > 0 => Ok(v as usize), + _ => plan_err!("The `n` must be between (0, 2147483647] (current value = {n})."), + } +} + +/// Returns the type of each output column, which is the type of its first +/// non-NULL value as in Spark's `StackCoercion`. Errors on the first value, in +/// argument order, whose type differs from its column's. +fn column_types(values: &[FieldRef], num_fields: usize) -> Result<Vec<DataType>> { + let mut types = vec![DataType::Null; num_fields]; + for (i, value) in values.iter().enumerate() { + let column_type = &mut types[i % num_fields]; + if column_type.is_null() { + *column_type = value.data_type().clone(); + } + } + for (i, value) in values.iter().enumerate() { + let col = i % num_fields; + let (expected, actual) = (&types[col], value.data_type()); + // Compare logical types, so `Utf8` and `Utf8View` are both Spark's STRING + if !actual.is_null() + && actual != expected + && NativeType::from(actual) != NativeType::from(expected) + { + return plan_err!( + "The data type of the column ({col}) do not have the same type: \"{expected}\" ({}) <> \"{actual}\" ({}).", + col + 1, + i + 1 + ); + } + } + Ok(types) +} + +/// Generates `n` rows of `item`'s struct type for each of `num_rows` input rows. +/// Field `j` of generated row `i` is `values[i * num_fields + j]`, or NULL past the +/// last value. +fn stack( + values: &[ColumnarValue], + item: &FieldRef, + n: usize, + num_rows: usize, +) -> Result<ListArray> { + let DataType::Struct(fields) = item.data_type() else { + return internal_err!("stack: unexpected element type {item}"); + }; + let offsets = OffsetBuffer::try_from_repeated_length(n, num_rows).map_err(|_| { + exec_datafusion_err!( + "stack: {num_rows} rows of {n} generated rows exceed the maximum list size" + ) + })?; + let columns = if n == 1 { + // Every value is a column as is, without copying arrays + values + .iter() + .zip(fields.iter()) + .map(|(value, field)| cast_to(value.to_array(num_rows)?, field.data_type())) + .collect::<Result<_>>()? + } else { + stack_columns(values, fields, n, num_rows)? + }; + let rows = StructArray::try_new(fields.clone(), columns, None)?; + Ok(ListArray::try_new( + Arc::clone(item), + offsets, + Arc::new(rows), + None, + )?) +} + +/// Builds each output column from its `n` values. An array value is read at the +/// input row. A scalar or NULL is a single value array read at index 0, so it is +/// never broadcast. +fn stack_columns( + values: &[ColumnarValue], + fields: &Fields, + n: usize, + num_rows: usize, +) -> Result<Vec<ArrayRef>> { + macro_rules! primitive_helper { + ($t:ty, $sources:ident, $per_row:ident, $num_rows:ident, $data_type:ident) => { + Ok(stack_primitive::<$t>( + &$sources, &$per_row, $num_rows, $data_type, + )) + }; + } + let num_fields = fields.len(); + let mut indices = vec![]; + fields + .iter() + .enumerate() + .map(|(col, field)| { + let data_type = field.data_type(); + if data_type.is_null() { + return Ok(new_null_array(data_type, num_rows * n)); + } + let null = new_null_array(data_type, 1); + let mut sources = Vec::with_capacity(n); + let mut per_row = Vec::with_capacity(n); + for row in 0..n { + let (source, is_array) = match values.get(row * num_fields + col) { + Some(ColumnarValue::Array(array)) if !array.data_type().is_null() => { + (cast_to(Arc::clone(array), data_type)?, true) + } + Some(ColumnarValue::Scalar(scalar)) if !scalar.is_null() => { + (cast_to(scalar.to_array()?, data_type)?, false) + } + _ => (Arc::clone(&null), false), + }; + sources.push(source); + per_row.push(is_array); + } + if !per_row.contains(&true) { + // The same `n` values for every input row + let sources = sources.iter().map(AsRef::as_ref).collect::<Vec<_>>(); + return repeat(concat(&sources)?, num_rows); + } + downcast_primitive! { + data_type => (primitive_helper, sources, per_row, num_rows, data_type), + _ => { + indices.clear(); + indices.try_reserve(num_rows * n).map_err(|e| { + exec_datafusion_err!("stack: failed to allocate indices: {e}") + })?; + for input_row in 0..num_rows { + indices.extend(per_row.iter().enumerate().map(|(i, &per_row)| { + (i, if per_row { input_row } else { 0 }) + })); + } + let sources = sources.iter().map(AsRef::as_ref).collect::<Vec<_>>(); + Ok(interleave(&sources, &indices)?) + } + } + }) + .collect() +} + +/// Writes source `i` to every `n`-th slot starting at `i`. This avoids the +/// index lookups of `interleave`, and only visits the NULL slots of the +/// validity. It is about 2-3x faster for primitive types. +fn stack_primitive<T: ArrowPrimitiveType>( + sources: &[ArrayRef], + per_row: &[bool], + num_rows: usize, + data_type: &DataType, +) -> ArrayRef { + // `values[i..]` below needs at least one row + if num_rows == 0 { + return new_empty_array(data_type); + } + let n = sources.len(); + let len = num_rows * n; + let mut values = vec![T::Native::default(); len]; + let mut validity: Option<BooleanBufferBuilder> = None; + for (i, (source, &per_row)) in sources.iter().zip(per_row).enumerate() { + let source = source.as_primitive::<T>(); + let slots = values[i..].iter_mut().step_by(n); + // `for` loops, as `for_each` on these iterators is 2x slower + if per_row { + for (slot, value) in slots.zip(source.values().iter()) { + *slot = *value; + } + } else { + let value = source.value(0); + for slot in slots { + *slot = value; + } + } + if let Some(nulls) = source.nulls().filter(|nulls| nulls.null_count() > 0) { + let validity = validity.get_or_insert_with(|| { + let mut validity = BooleanBufferBuilder::new(len); + validity.append_n(len, true); + validity + }); + if per_row { + for row in (!nulls.inner()).set_indices() { + validity.set_bit(row * n + i, false); + } + } else { + for row in 0..num_rows { + validity.set_bit(row * n + i, false); + } + } + } + } + let nulls = validity.map(|mut validity| NullBuffer::new(validity.finish())); + Arc::new( + PrimitiveArray::<T>::new(values.into(), nulls).with_data_type(data_type.clone()), + ) +} + +/// Concatenates `count` copies of `array`, doubling a block of copies so it +/// takes O(log count) bulk copies instead of one copy per value. +fn repeat(array: ArrayRef, count: usize) -> Result<ArrayRef> { + let mut parts = vec![]; + let mut block = array; + let mut count = count; + while count > 0 { + if count & 1 == 1 { + parts.push(Arc::clone(&block)); + } + count >>= 1; + if count > 0 { + block = concat(&[block.as_ref(), block.as_ref()])?; + } + } + match parts.as_slice() { + [] => Ok(block.slice(0, 0)), + [part] => Ok(Arc::clone(part)), + parts => Ok(concat( + &parts.iter().map(AsRef::as_ref).collect::<Vec<_>>(), + )?), + } +} + +fn cast_to(array: ArrayRef, data_type: &DataType) -> Result<ArrayRef> { Review Comment: `ColumnarValue::cast_to(data_type, None)` already returns `Arc::clone` when the types match, so this helper can go, and the array and scalar arms in `stack_columns` can share one cast. The cast in the `n == 1` branch never changes anything: with `n == 1` each column has a single value and takes its type, so `ColumnarValue::values_to_arrays(values)` is enough there. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
