Copilot commented on code in PR #20928: URL: https://github.com/apache/datafusion/pull/20928#discussion_r2932604684
########## datafusion/spark/src/function/string/concat_ws.rs: ########## @@ -0,0 +1,502 @@ +// 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. + +//! Spark-compatible `concat_ws` function. +//! +//! Differences with DataFusion core `concat_ws`: +//! - Accepts array arguments and expands their elements +//! - Allows zero value arguments: `concat_ws(',')` → `""` +//! - Null array elements are skipped (same as null scalars) + +use std::any::Any; +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, GenericListArray, OffsetSizeTrait, StringBuilder, +}; +use arrow::datatypes::DataType; +use datafusion_common::cast::as_generic_string_array; +use datafusion_common::{Result, ScalarValue, exec_err}; +use datafusion_expr::{ + ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, +}; + +/// Spark-compatible `concat_ws` expression. +/// +/// In Spark, `concat_ws(sep, a, b, ...)` joins strings with separator. +/// If any argument is an array, its elements are joined with the separator. +/// Null values (both scalar and array elements) are skipped. +/// Null separator produces null result. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkConcatWs { + signature: Signature, +} + +impl Default for SparkConcatWs { + fn default() -> Self { + Self::new() + } +} + +impl SparkConcatWs { + pub fn new() -> Self { + Self { + signature: Signature::variadic_any(Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkConcatWs { + fn as_any(&self) -> &dyn Any { + self + } + + fn name(&self) -> &str { + "concat_ws" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + // Spark's concat_ws always returns STRING (Utf8) + Ok(DataType::Utf8) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + // Zero value args: concat_ws(',') → "" + if args.args.len() <= 1 { + if args.args.is_empty() { + return Ok(ColumnarValue::Scalar(ScalarValue::Utf8( + Some(String::new()), + ))); + } + // Only separator — return "" or NULL depending on separator + return match &args.args[0] { + ColumnarValue::Scalar(s) if s.is_null() => { + Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None))) + } + ColumnarValue::Scalar(_) => Ok(ColumnarValue::Scalar(ScalarValue::Utf8( + Some(String::new()), + ))), + ColumnarValue::Array(arr) => { + // Separator is a column: return "" for non-null, NULL for null + let mut builder = StringBuilder::with_capacity(arr.len(), 0); + for row_idx in 0..arr.len() { + if arr.is_null(row_idx) { + builder.append_null(); + } else { + builder.append_value(""); + } + } + Ok(ColumnarValue::Array(Arc::new(builder.finish()) as ArrayRef)) + } + }; + } + + // Use our implementation for all cases to guarantee consistent Utf8 return type. + // Core's concat_ws may return Utf8View which conflicts with our return_type. + spark_concat_ws_with_arrays(&args.args) + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> { + if arg_types.is_empty() { + return Ok(vec![]); + } + + let mut coerced = Vec::with_capacity(arg_types.len()); + // First arg is separator — must be string + coerced.push(DataType::Utf8); + + for dt in &arg_types[1..] { + match dt { + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => { + coerced.push(dt.clone()); + } + DataType::List(_) | DataType::LargeList(_) => { + // Keep list types as-is; elements will be extracted at runtime + coerced.push(dt.clone()); + } + DataType::Null => { + coerced.push(DataType::Utf8); + } + _ => { + // Cast other types to string + coerced.push(DataType::Utf8); + } + } + } + + Ok(coerced) + } +} + +/// Implementation of concat_ws that supports array arguments. +fn spark_concat_ws_with_arrays(args: &[ColumnarValue]) -> Result<ColumnarValue> { + // Determine number of rows + let num_rows = args + .iter() + .find_map(|x| match x { + ColumnarValue::Array(a) => Some(a.len()), + _ => None, + }) + .unwrap_or(1); + + // Convert all to arrays for uniform processing + let arrays: Vec<ArrayRef> = args + .iter() + .map(|arg| arg.to_array(num_rows)) + .collect::<Result<Vec<_>>>()?; + + // If separator is Null type, all results are null + if *arrays[0].data_type() == DataType::Null { + let mut builder = StringBuilder::with_capacity(num_rows, 0); + for _ in 0..num_rows { + builder.append_null(); + } + return Ok(ColumnarValue::Array(Arc::new(builder.finish()) as ArrayRef)); + } + + let mut builder = StringBuilder::new(); + + for row_idx in 0..num_rows { + // Null separator → null result + if arrays[0].is_null(row_idx) { + builder.append_null(); + continue; + } + + let separator = get_string_value(&arrays[0], row_idx)?; + let mut parts: Vec<String> = Vec::new(); + + // Process remaining arguments + for arr in &arrays[1..] { + collect_parts(arr, row_idx, &mut parts)?; + } + + builder.append_value(parts.join(&separator)); + } + + Ok(ColumnarValue::Array(Arc::new(builder.finish()) as ArrayRef)) +} + +/// Get a string value from an array at a given row index, supporting Utf8/LargeUtf8/Utf8View. +fn get_string_value(arr: &ArrayRef, row_idx: usize) -> Result<String> { + match arr.data_type() { + DataType::Utf8 => { + let str_arr = as_generic_string_array::<i32>(arr)?; + Ok(str_arr.value(row_idx).to_string()) + } + DataType::LargeUtf8 => { + let str_arr = as_generic_string_array::<i64>(arr)?; + Ok(str_arr.value(row_idx).to_string()) + } + DataType::Utf8View => { + let str_arr = arr.as_string_view(); + Ok(str_arr.value(row_idx).to_string()) + } + other => exec_err!("concat_ws separator must be a string, got {other:?}"), + } +} + +/// Collect string parts from an array at a given row index. +/// For scalar string: adds the value if non-null. +/// For list arrays: expands elements, skipping nulls. +fn collect_parts(arr: &ArrayRef, row_idx: usize, parts: &mut Vec<String>) -> Result<()> { + if arr.is_null(row_idx) { + return Ok(()); + } + + match arr.data_type() { + DataType::Null => {} + DataType::Utf8 => { + let str_arr = as_generic_string_array::<i32>(arr)?; + parts.push(str_arr.value(row_idx).to_string()); + } + DataType::LargeUtf8 => { + let str_arr = as_generic_string_array::<i64>(arr)?; + parts.push(str_arr.value(row_idx).to_string()); + } + DataType::Utf8View => { + let str_arr = arr.as_string_view(); + parts.push(str_arr.value(row_idx).to_string()); + } + DataType::List(_) => { + collect_parts_from_list::<i32>(arr.as_list(), row_idx, parts)?; + } + DataType::LargeList(_) => { + collect_parts_from_list::<i64>(arr.as_list(), row_idx, parts)?; Review Comment: `collect_parts` calls `arr.as_list()` for both `List` and `LargeList` branches, but elsewhere in this repo the `AsArray` helper is used with an explicit offset type (e.g. `as_list::<i32>()` / `as_list::<i64>()`). As written, this is very likely a compile error and/or will pick the wrong offset type for `LargeList`. Update these calls to use the correct `as_list::<i32>()` / `as_list::<i64>()` (or the appropriate Arrow helper for large lists). ########## datafusion/sqllogictest/test_files/spark/string/concat_ws.slt: ########## @@ -21,22 +21,111 @@ # For more information, please see: # https://github.com/apache/datafusion/issues/15914 -## Original Query: SELECT concat_ws(' ', 'Spark', 'SQL'); -## PySpark 3.5.5 Result: {'concat_ws( , Spark, SQL)': 'Spark SQL', 'typeof(concat_ws( , Spark, SQL))': 'string', 'typeof( )': 'string', 'typeof(Spark)': 'string', 'typeof(SQL)': 'string'} -#query -#SELECT concat_ws(' '::string, 'Spark'::string, 'SQL'::string); - -## Original Query: SELECT concat_ws('/', 'foo', null, 'bar'); -## PySpark 3.5.5 Result: {'concat_ws(/, foo, NULL, bar)': 'foo/bar', 'typeof(concat_ws(/, foo, NULL, bar))': 'string', 'typeof(/)': 'string', 'typeof(foo)': 'string', 'typeof(NULL)': 'void', 'typeof(bar)': 'string'} -#query -#SELECT concat_ws('/'::string, 'foo'::string, NULL::void, 'bar'::string); - -## Original Query: SELECT concat_ws('s'); -## PySpark 3.5.5 Result: {'concat_ws(s)': '', 'typeof(concat_ws(s))': 'string', 'typeof(s)': 'string'} -#query -#SELECT concat_ws('s'::string); - -## Original Query: SELECT concat_ws(null, 'Spark', 'SQL'); -## PySpark 3.5.5 Result: {'concat_ws(NULL, Spark, SQL)': None, 'typeof(concat_ws(NULL, Spark, SQL))': 'string', 'typeof(NULL)': 'void', 'typeof(Spark)': 'string', 'typeof(SQL)': 'string'} -#query -#SELECT concat_ws(NULL::void, 'Spark'::string, 'SQL'::string); +## ── Basic scalar usage ────────────────────────────────────── + +## Multiple string arguments +query T +SELECT concat_ws(',', 'a', 'b', 'c'); +---- +a,b,c + +## Space separator +query T +SELECT concat_ws(' ', 'Spark', 'SQL'); +---- +Spark SQL Review Comment: The SLT coverage doesn’t currently include the common case where `concat_ws` is called with only literal arguments but evaluated over multiple input rows (e.g. `SELECT concat_ws(',', 'a', 'b') FROM VALUES (1), (2) ...`). Adding a multi-row query like this would catch UDF broadcasting/row-count bugs (and would have caught the current `num_rows` inference issue). ########## datafusion/spark/src/function/string/concat_ws.rs: ########## @@ -0,0 +1,502 @@ +// 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. + +//! Spark-compatible `concat_ws` function. +//! +//! Differences with DataFusion core `concat_ws`: +//! - Accepts array arguments and expands their elements +//! - Allows zero value arguments: `concat_ws(',')` → `""` +//! - Null array elements are skipped (same as null scalars) + +use std::any::Any; +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, GenericListArray, OffsetSizeTrait, StringBuilder, +}; +use arrow::datatypes::DataType; +use datafusion_common::cast::as_generic_string_array; +use datafusion_common::{Result, ScalarValue, exec_err}; +use datafusion_expr::{ + ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, +}; + +/// Spark-compatible `concat_ws` expression. +/// +/// In Spark, `concat_ws(sep, a, b, ...)` joins strings with separator. +/// If any argument is an array, its elements are joined with the separator. +/// Null values (both scalar and array elements) are skipped. +/// Null separator produces null result. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkConcatWs { + signature: Signature, +} + +impl Default for SparkConcatWs { + fn default() -> Self { + Self::new() + } +} + +impl SparkConcatWs { + pub fn new() -> Self { + Self { + signature: Signature::variadic_any(Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkConcatWs { + fn as_any(&self) -> &dyn Any { + self + } + + fn name(&self) -> &str { + "concat_ws" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + // Spark's concat_ws always returns STRING (Utf8) + Ok(DataType::Utf8) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + // Zero value args: concat_ws(',') → "" + if args.args.len() <= 1 { + if args.args.is_empty() { + return Ok(ColumnarValue::Scalar(ScalarValue::Utf8( + Some(String::new()), + ))); + } + // Only separator — return "" or NULL depending on separator + return match &args.args[0] { + ColumnarValue::Scalar(s) if s.is_null() => { + Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None))) + } + ColumnarValue::Scalar(_) => Ok(ColumnarValue::Scalar(ScalarValue::Utf8( + Some(String::new()), + ))), + ColumnarValue::Array(arr) => { + // Separator is a column: return "" for non-null, NULL for null + let mut builder = StringBuilder::with_capacity(arr.len(), 0); + for row_idx in 0..arr.len() { + if arr.is_null(row_idx) { + builder.append_null(); + } else { + builder.append_value(""); + } + } + Ok(ColumnarValue::Array(Arc::new(builder.finish()) as ArrayRef)) + } + }; + } + + // Use our implementation for all cases to guarantee consistent Utf8 return type. + // Core's concat_ws may return Utf8View which conflicts with our return_type. + spark_concat_ws_with_arrays(&args.args) + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> { + if arg_types.is_empty() { + return Ok(vec![]); + } + + let mut coerced = Vec::with_capacity(arg_types.len()); + // First arg is separator — must be string + coerced.push(DataType::Utf8); + + for dt in &arg_types[1..] { + match dt { + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => { + coerced.push(dt.clone()); + } + DataType::List(_) | DataType::LargeList(_) => { + // Keep list types as-is; elements will be extracted at runtime + coerced.push(dt.clone()); + } + DataType::Null => { + coerced.push(DataType::Utf8); + } + _ => { + // Cast other types to string + coerced.push(DataType::Utf8); + } + } + } + + Ok(coerced) + } +} + +/// Implementation of concat_ws that supports array arguments. +fn spark_concat_ws_with_arrays(args: &[ColumnarValue]) -> Result<ColumnarValue> { + // Determine number of rows + let num_rows = args + .iter() + .find_map(|x| match x { + ColumnarValue::Array(a) => Some(a.len()), + _ => None, + }) + .unwrap_or(1); + + // Convert all to arrays for uniform processing + let arrays: Vec<ArrayRef> = args + .iter() + .map(|arg| arg.to_array(num_rows)) + .collect::<Result<Vec<_>>>()?; + Review Comment: `spark_concat_ws_with_arrays` infers `num_rows` by scanning for the first `ColumnarValue::Array` and falls back to `1` when all arguments are scalars. In DataFusion execution, a UDF can be invoked with `number_rows > 1` even if all inputs are scalars (e.g. `SELECT concat_ws(',', 'a','b') FROM some_table`). In that case this implementation will build an output array of length 1, which will later fail length validation or produce incorrect results. Use `ScalarFunctionArgs.number_rows` to size/broadcast scalar inputs, and consider returning `ColumnarValue::Scalar` when all inputs are scalar (similar to DataFusion core `concat_ws`). -- 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]
