andygrove commented on code in PR #410:
URL: https://github.com/apache/datafusion-spark/pull/410#discussion_r4682583868
##########
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:
Storing the names in the UDF instance means they only exist when the plan
came through `SparkStruct::expression`. Anything that looks the UDF up by name
gets the default instance. That includes `ctx.udf("struct")`, `call_udf`, and
datafusion-proto deserialization. In a quick test, the registered `struct` UDF
applied to `col("a")` returns `Struct(col1)` instead of `Struct(a)`, so a
plan's schema would change after a proto round trip.
Spark rewrites `CreateStruct` into `CreateNamedStruct` during analysis, so
the names become literal arguments. What do you think about having
`plan_struct_literal` build `named_struct('col1', e1, 'a', a, ...)` instead?
The names would then travel with the plan, and the stateful UDF would go away.
If you want to keep Spark's per-child nullability, that could go into a Spark
`named_struct` (#224) as a separate change, so each coercion site can be
checked on its own.
##########
crates/spark/src/planner.rs:
##########
@@ -72,6 +71,56 @@ impl ExprPlanner for SparkFunctionPlanner {
)))
}
+ fn plan_array_literal(
Review Comment:
Switching `map_from_entries.slt` to `array(...)` makes sense, since Spark
has no `ARRAY[...]` syntax. That does leave this override without a test,
though, and it changes planning for every nested `[...]` literal. Could you add
a query like `SELECT [struct(1::INT, 'x'), struct(2::INT, NULL::STRING)]`? It
might fit under a short note that it is DataFusion-only syntax.
##########
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:
I found one regression from the new non-nullable child fields. `SELECT if(a
> 0, struct(1::INT), struct(NULL::INT)) FROM (VALUES (1), (-1)) AS t(a)` works
on `main` but fails on this branch with:
```
CASE expression 'then' values had multiple data types: Struct("col1":
non-null Int32), Struct("col1": Int32)
```
`SparkIf::coerce_types` uses `try_type_union_resolution`, which keeps nested
nullability. Before this PR every `struct` field was nullable, so the mismatch
never showed up. The PR already fixes this for `array()` and `[...]`. Could you
fix `if` the same way and add this query to `struct.slt`? It would also be
worth checking the other functions that coerce their arguments to a common
type, since they can hit the same thing.
##########
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:
`return_type` marks every field nullable, but `return_field_from_args` keeps
the child's nullability, so the two can disagree. Since
`return_field_from_args` is the one DataFusion calls, could `return_type`
return an `internal_err!` the way other UDFs do when they implement
`return_field_from_args`? That stops it from being used by accident.
##########
crates/sqllogictest/test_files/struct/struct.slt:
##########
@@ -8,7 +8,135 @@
# For more information, please see:
# https://github.com/apache/datafusion/issues/15914
-## Original Query: SELECT struct(1, 2, 3);
-## PySpark 3.5.5 Result: {'struct(1, 2, 3)': Row(col1=1, col2=2, col3=3),
'typeof(struct(1, 2, 3))': 'struct<col1:int,col2:int,col3:int>', 'typeof(1)':
'int', 'typeof(2)': 'int', 'typeof(3)': 'int'}
-#query
-#SELECT struct(1::int, 2::int, 3::int);
+# Literal fields use one-based names in Spark.
+query ?
+SELECT struct(1::INT, 2::INT, 3::INT);
+----
+{col1: 1, col2: 2, col3: 3}
+
+# Column names are retained, while expressions use their argument position.
+query ?
+SELECT struct(a, a + 1, b) FROM (VALUES (1::INT, 'x')) AS t(a, b);
+----
+{a: 1, col2: 2, b: x}
+
+# Qualified columns retain the unqualified name, including names resembling
defaults.
+query ?
+SELECT struct(t.a, t.c0, t.col1, 7::INT) FROM (VALUES (1::INT, 2::INT,
3::INT)) AS t(a, c0, col1);
+----
+{a: 1, c0: 2, col1: 3, col4: 7}
+
+# Field names survive constant folding; duplicate names are allowed.
+query ?
+SELECT struct(a, a, 1 + 2) FROM (VALUES (4::INT)) AS t(a);
+----
+{a: 4, a: 4, col3: 3}
+
+# Explicit aliases, including an alias matching DataFusion's generated names.
+query ?
+SELECT struct(1::INT AS c0, 'x' AS label);
+----
+{c0: 1, label: x}
+
+# Scalar NULLs are fields of a non-NULL struct.
+query ?B
+SELECT struct(NULL, NULL::INT, ''), struct(NULL) IS NULL;
+----
+{col1: NULL, col2: NULL, col3: } false
+
+# Column and scalar arguments broadcast across multiple rows.
+query ? rowsort
+SELECT struct(a, 'fixed', b) FROM (VALUES (1::INT, 'x'), (NULL::INT, NULL),
(3::INT, 'z')) AS t(a, b);
+----
+{a: 1, col2: fixed, b: x}
+{a: 3, col2: fixed, b: z}
+{a: NULL, col2: fixed, b: NULL}
+
+# Nested struct expressions use positional names. Nested field access retains
its name.
+query ?
+SELECT struct(struct(1::INT, 'x'));
+----
+{col1: {col1: 1, col2: x}}
+
+query ?
+SELECT struct(s.a) FROM (SELECT named_struct('a', 1::INT) AS s) t;
+----
+{a: 1}
+
+# Arrays must merge child nullability before combining structs.
+query ?
+SELECT array(struct(1::INT, NULL::STRING), struct(2::INT, 'x'));
+----
+[{col1: 1, col2: NULL}, {col1: 2, col2: x}]
+
+query ?
+SELECT array(struct(1::INT, 'x'), struct(2::INT, NULL::STRING));
+----
+[{col1: 1, col2: x}, {col1: 2, col2: NULL}]
+
+query ? rowsort
+SELECT array(struct(a), struct(7::INT AS a)) FROM (VALUES (1::INT),
(NULL::INT)) AS t(a);
+----
+[{a: 1}, {a: 7}]
+[{a: NULL}, {a: 7}]
+
+# Spark accepts empty structs, but DataFusion's SQL parser rejects struct()
Review Comment:
The audit skill asks for each commented-out divergence to link an issue so
the block gets re-enabled later. The mixed-alias block links #364. Could this
one link an issue too? Probably upstream in sqlparser or DataFusion, wherever
`struct()` is rejected. The mixed-alias case also depends on DataFusion's
`parse_struct` passing through which names were generated, so an upstream
DataFusion issue linked from that block would help too.
--
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]