Ritesh17rb commented on code in PR #410:
URL: https://github.com/apache/datafusion-spark/pull/410#discussion_r4684794740
##########
crates/spark/src/function/struct/spark_struct.rs:
##########
@@ -0,0 +1,312 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, StructArray};
+use arrow::datatypes::{DataType, Field, FieldRef, Fields};
+use datafusion_common::{Result, ScalarValue, internal_err};
+use datafusion_expr::{
+ ColumnarValue, Documentation, Expr, ReturnFieldArgs, ScalarFunctionArgs,
ScalarUDF,
+ ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_macros::user_doc;
+
+/// Spark-compatible `struct` expression.
+///
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#struct>
+#[user_doc(
+ doc_section(label = "Struct Functions"),
+ description = "Creates a non-NULL struct, retaining NULL fields. Unnamed
expressions use \
+ one-based field names `col1`, `col2`, etc., rather than DataFusion's
`c0`, `c1`, etc. \
+ The Spark SQL planner and Rust expression helper retain column and
nested field names. \
+ The physical UDF and Rust helper accept zero arguments for an empty
struct, \
+ but DataFusion's SQL parser currently rejects `struct()`. \
+ SQL calls mixing explicit aliases and unnamed arguments still receive
DataFusion's \
+ generated names for unnamed fields, because those names are assigned
before the Spark planner.",
+ syntax_example = "struct(expr, ...)",
+ sql_example = r#"```sql
+> SELECT struct(1, 2, 3);
+{col1: 1, col2: 2, col3: 3}
+```"#,
+ argument(name = "expr", description = "Zero or more expressions of any
type.")
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkStruct {
+ signature: Signature,
+ names: Vec<String>,
+}
+
+impl Default for SparkStruct {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkStruct {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ names: vec![],
+ }
+ }
+
+ /// Capture names before optimization folds expressions or changes columns.
+ pub(crate) fn expression(args: Vec<Expr>) -> Expr {
+ let names = args
+ .iter()
+ .enumerate()
+ .map(|(i, expr)| {
+ match expr {
+ Expr::Column(column) => Some(column.name.clone()),
+ Expr::Alias(alias) => Some(alias.name.clone()),
+ Expr::ScalarFunction(function)
+ if function.func.name() == "get_field" =>
+ {
+ match function.args.get(1) {
+ Some(Expr::Literal(ScalarValue::Utf8(Some(name)),
_)) => {
+ Some(name.clone())
+ }
+ _ => None,
+ }
+ }
+ _ => None,
+ }
+ .unwrap_or_else(|| format!("col{}", i + 1))
+ })
+ .collect();
+ Arc::new(ScalarUDF::from(Self {
+ names,
+ ..Self::new()
+ }))
+ .call(args)
+ }
+
+ /// SQL has already interleaved names and values when any argument has an
alias.
+ pub(crate) fn named_expression(args: Vec<Expr>) -> Result<Expr> {
+ let mut names = Vec::with_capacity(args.len() / 2);
+ let mut values = Vec::with_capacity(args.len() / 2);
+ let (pairs, remainder) = args.as_chunks::<2>();
+ if !remainder.is_empty() {
+ return internal_err!("struct planner expected name/value pairs");
+ }
+ for [name, value] in pairs {
+ let Expr::Literal(ScalarValue::Utf8(Some(name)), _) = name else {
+ return internal_err!("struct planner expected a literal field
name");
+ };
+ names.push(name.clone());
+ values.push(value.clone());
+ }
+ Ok(Arc::new(ScalarUDF::from(Self {
+ names,
+ ..Self::new()
+ }))
+ .call(values))
+ }
+
+ fn fields(&self, args: &[FieldRef]) -> Fields {
+ args.iter()
+ .enumerate()
+ .map(|(i, field)| {
+ let name = self
+ .names
+ .get(i)
+ .cloned()
+ .unwrap_or_else(|| format!("col{}", i + 1));
+ Arc::new(field.as_ref().clone().with_name(name))
+ })
+ .collect()
+ }
+}
+
+impl ScalarUDFImpl for SparkStruct {
+ fn name(&self) -> &str {
+ "struct"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+ Ok(arg_types.to_vec())
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ let fields = arg_types
+ .iter()
+ .map(|t| Arc::new(Field::new("", t.clone(), true)))
+ .collect::<Vec<_>>();
+ Ok(DataType::Struct(self.fields(&fields)))
+ }
+
+ fn return_field_from_args(&self, args: ReturnFieldArgs) ->
Result<FieldRef> {
Review Comment:
Thanks for catching this. I reproduced the failure. Changing child
nullability was too broad for the naming fix, so this PR now uses core
`named_struct` and retains main's nullability/coercion behavior. I added your
`if` query and checked `CASE`, `coalesce`, `greatest`/`least`, and array
insertion too. The `if` record keeps the existing `skipif evaluate` for #305;
the regression is checked in simplify mode. Spark child nullability stays with
#224.
##########
crates/spark/src/function/struct/spark_struct.rs:
##########
@@ -0,0 +1,312 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, StructArray};
+use arrow::datatypes::{DataType, Field, FieldRef, Fields};
+use datafusion_common::{Result, ScalarValue, internal_err};
+use datafusion_expr::{
+ ColumnarValue, Documentation, Expr, ReturnFieldArgs, ScalarFunctionArgs,
ScalarUDF,
+ ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_macros::user_doc;
+
+/// Spark-compatible `struct` expression.
+///
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#struct>
+#[user_doc(
+ doc_section(label = "Struct Functions"),
+ description = "Creates a non-NULL struct, retaining NULL fields. Unnamed
expressions use \
+ one-based field names `col1`, `col2`, etc., rather than DataFusion's
`c0`, `c1`, etc. \
+ The Spark SQL planner and Rust expression helper retain column and
nested field names. \
+ The physical UDF and Rust helper accept zero arguments for an empty
struct, \
+ but DataFusion's SQL parser currently rejects `struct()`. \
+ SQL calls mixing explicit aliases and unnamed arguments still receive
DataFusion's \
+ generated names for unnamed fields, because those names are assigned
before the Spark planner.",
+ syntax_example = "struct(expr, ...)",
+ sql_example = r#"```sql
+> SELECT struct(1, 2, 3);
+{col1: 1, col2: 2, col3: 3}
+```"#,
+ argument(name = "expr", description = "Zero or more expressions of any
type.")
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkStruct {
+ signature: Signature,
+ names: Vec<String>,
Review Comment:
Agreed, the names belong in the expression. The SQL planner and Rust helper
now build `named_struct` with literal name/value pairs. I removed `SparkStruct`
and added a test that rebuilds the expression through the registered function
and checks its schema. There is no UDF state left to lose when the function is
looked up by name.
##########
crates/spark/src/function/struct/spark_struct.rs:
##########
@@ -0,0 +1,312 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, StructArray};
+use arrow::datatypes::{DataType, Field, FieldRef, Fields};
+use datafusion_common::{Result, ScalarValue, internal_err};
+use datafusion_expr::{
+ ColumnarValue, Documentation, Expr, ReturnFieldArgs, ScalarFunctionArgs,
ScalarUDF,
+ ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_macros::user_doc;
+
+/// Spark-compatible `struct` expression.
+///
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#struct>
+#[user_doc(
+ doc_section(label = "Struct Functions"),
+ description = "Creates a non-NULL struct, retaining NULL fields. Unnamed
expressions use \
+ one-based field names `col1`, `col2`, etc., rather than DataFusion's
`c0`, `c1`, etc. \
+ The Spark SQL planner and Rust expression helper retain column and
nested field names. \
+ The physical UDF and Rust helper accept zero arguments for an empty
struct, \
+ but DataFusion's SQL parser currently rejects `struct()`. \
+ SQL calls mixing explicit aliases and unnamed arguments still receive
DataFusion's \
+ generated names for unnamed fields, because those names are assigned
before the Spark planner.",
+ syntax_example = "struct(expr, ...)",
+ sql_example = r#"```sql
+> SELECT struct(1, 2, 3);
+{col1: 1, col2: 2, col3: 3}
+```"#,
+ argument(name = "expr", description = "Zero or more expressions of any
type.")
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkStruct {
+ signature: Signature,
+ names: Vec<String>,
+}
+
+impl Default for SparkStruct {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkStruct {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ names: vec![],
+ }
+ }
+
+ /// Capture names before optimization folds expressions or changes columns.
+ pub(crate) fn expression(args: Vec<Expr>) -> Expr {
+ let names = args
+ .iter()
+ .enumerate()
+ .map(|(i, expr)| {
+ match expr {
+ Expr::Column(column) => Some(column.name.clone()),
+ Expr::Alias(alias) => Some(alias.name.clone()),
+ Expr::ScalarFunction(function)
+ if function.func.name() == "get_field" =>
+ {
+ match function.args.get(1) {
+ Some(Expr::Literal(ScalarValue::Utf8(Some(name)),
_)) => {
+ Some(name.clone())
+ }
+ _ => None,
+ }
+ }
+ _ => None,
+ }
+ .unwrap_or_else(|| format!("col{}", i + 1))
+ })
+ .collect();
+ Arc::new(ScalarUDF::from(Self {
+ names,
+ ..Self::new()
+ }))
+ .call(args)
+ }
+
+ /// SQL has already interleaved names and values when any argument has an
alias.
+ pub(crate) fn named_expression(args: Vec<Expr>) -> Result<Expr> {
+ let mut names = Vec::with_capacity(args.len() / 2);
+ let mut values = Vec::with_capacity(args.len() / 2);
+ let (pairs, remainder) = args.as_chunks::<2>();
+ if !remainder.is_empty() {
+ return internal_err!("struct planner expected name/value pairs");
+ }
+ for [name, value] in pairs {
+ let Expr::Literal(ScalarValue::Utf8(Some(name)), _) = name else {
+ return internal_err!("struct planner expected a literal field
name");
+ };
+ names.push(name.clone());
+ values.push(value.clone());
+ }
+ Ok(Arc::new(ScalarUDF::from(Self {
+ names,
+ ..Self::new()
+ }))
+ .call(values))
+ }
+
+ fn fields(&self, args: &[FieldRef]) -> Fields {
+ args.iter()
+ .enumerate()
+ .map(|(i, field)| {
+ let name = self
+ .names
+ .get(i)
+ .cloned()
+ .unwrap_or_else(|| format!("col{}", i + 1));
+ Arc::new(field.as_ref().clone().with_name(name))
+ })
+ .collect()
+ }
+}
+
+impl ScalarUDFImpl for SparkStruct {
+ fn name(&self) -> &str {
+ "struct"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+ Ok(arg_types.to_vec())
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
Review Comment:
Yes, those two inference paths should not disagree. The custom UDF is gone
now, so we use core `named_struct`, whose `return_type` already returns
`internal_err!` and requires `return_field_from_args`.
--
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]