Skip to content

Apache DataFusion SQL Query Engine

[bugfix] ScalarFunctionExpr does not preserve the nullable flag on roundtrip (#13830)

Costi Ciudatu34670116b056
diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.proto
index cb0235f1f2..416227f70d 100644
--- a/datafusion/proto/proto/datafusion.proto
+++ b/datafusion/proto/proto/datafusion.proto
@@ -838,6 +838,7 @@ message PhysicalScalarUdfNode {
repeated PhysicalExprNode args = 2;
optional bytes fun_definition = 3;
datafusion_common.ArrowType return_type = 4;
+ bool nullable = 5;
}
message PhysicalAggregateExprNode {
diff --git a/datafusion/proto/src/generated/pbjson.rs b/datafusion/proto/src/generated/pbjson.rs
index f920e16d0a..cffb630186 100644
--- a/datafusion/proto/src/generated/pbjson.rs
+++ b/datafusion/proto/src/generated/pbjson.rs
@@ -15720,6 +15720,9 @@ impl serde::Serialize for PhysicalScalarUdfNode {
if self.return_type.is_some() {
len += 1;
}
+ if self.nullable {
+ len += 1;
+ }
let mut struct_ser = serializer.serialize_struct("datafusion.PhysicalScalarUdfNode", len)?;
if !self.name.is_empty() {
struct_ser.serialize_field("name", &self.name)?;
@@ -15735,6 +15738,9 @@ impl serde::Serialize for PhysicalScalarUdfNode {
if let Some(v) = self.return_type.as_ref() {
struct_ser.serialize_field("returnType", v)?;
}
+ if self.nullable {
+ struct_ser.serialize_field("nullable", &self.nullable)?;
+ }
struct_ser.end()
}
}
@@ -15751,6 +15757,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode {
"funDefinition",
"return_type",
"returnType",
+ "nullable",
];
#[allow(clippy::enum_variant_names)]
@@ -15759,6 +15766,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode {
Args,
FunDefinition,
ReturnType,
+ Nullable,
}
impl<'de> serde::Deserialize<'de> for GeneratedField {
fn deserialize<D>(deserializer: D) -> std::result::Result<GeneratedField, D::Error>
@@ -15784,6 +15792,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode {
"args" => Ok(GeneratedField::Args),
"funDefinition" | "fun_definition" => Ok(GeneratedField::FunDefinition),
"returnType" | "return_type" => Ok(GeneratedField::ReturnType),
+ "nullable" => Ok(GeneratedField::Nullable),
_ => Err(serde::de::Error::unknown_field(value, FIELDS)),
}
}
@@ -15807,6 +15816,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode {
let mut args__ = None;
let mut fun_definition__ = None;
let mut return_type__ = None;
+ let mut nullable__ = None;
while let Some(k) = map_.next_key()? {
match k {
GeneratedField::Name => {
@@ -15835,6 +15845,12 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode {
}
return_type__ = map_.next_value()?;
}
+ GeneratedField::Nullable => {
+ if nullable__.is_some() {
+ return Err(serde::de::Error::duplicate_field("nullable"));
+ }
+ nullable__ = Some(map_.next_value()?);
+ }
}
}
Ok(PhysicalScalarUdfNode {
@@ -15842,6 +15858,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode {
args: args__.unwrap_or_default(),
fun_definition: fun_definition__,
return_type: return_type__,
+ nullable: nullable__.unwrap_or_default(),
})
}
}
diff --git a/datafusion/proto/src/generated/prost.rs b/datafusion/proto/src/generated/prost.rs
index a2be3207ac..d2fda5dc88 100644
--- a/datafusion/proto/src/generated/prost.rs
+++ b/datafusion/proto/src/generated/prost.rs
@@ -1228,6 +1228,8 @@ pub struct PhysicalScalarUdfNode {
pub fun_definition: ::core::option::Option<::prost::alloc::vec::Vec<u8>>,
#[prost(message, optional, tag = "4")]
pub return_type: ::core::option::Option<super::datafusion_common::ArrowType>,
+ #[prost(bool, tag = "5")]
+ pub nullable: bool,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PhysicalAggregateExprNode {
diff --git a/datafusion/proto/src/physical_plan/from_proto.rs b/datafusion/proto/src/physical_plan/from_proto.rs
index 5bf6218cb9..d1fe48cfec 100644
--- a/datafusion/proto/src/physical_plan/from_proto.rs
+++ b/datafusion/proto/src/physical_plan/from_proto.rs
@@ -358,12 +358,15 @@ pub fn parse_physical_expr(
let args = parse_physical_exprs(&e.args, registry, input_schema, codec)?;
- Arc::new(ScalarFunctionExpr::new(
- e.name.as_str(),
- scalar_fun_def,
- args,
- convert_required!(e.return_type)?,
- ))
+ Arc::new(
+ ScalarFunctionExpr::new(
+ e.name.as_str(),
+ scalar_fun_def,
+ args,
+ convert_required!(e.return_type)?,
+ )
+ .with_nullable(e.nullable),
+ )
}
ExprType::LikeExpr(like_expr) => Arc::new(LikeExpr::new(
like_expr.negated,
diff --git a/datafusion/proto/src/physical_plan/to_proto.rs b/datafusion/proto/src/physical_plan/to_proto.rs
index 3805b97059..000d0521de 100644
--- a/datafusion/proto/src/physical_plan/to_proto.rs
+++ b/datafusion/proto/src/physical_plan/to_proto.rs
@@ -347,6 +347,7 @@ pub fn serialize_physical_expr(
args: serialize_physical_exprs(expr.args(), codec)?,
fun_definition: (!buf.is_empty()).then_some(buf),
return_type: Some(expr.return_type().try_into()?),
+ nullable: expr.nullable(),
},
)),
})
diff --git a/datafusion/proto/tests/cases/roundtrip_physical_plan.rs b/datafusion/proto/tests/cases/roundtrip_physical_plan.rs
index 3311b57f5d..0a6ea6c7ff 100644
--- a/datafusion/proto/tests/cases/roundtrip_physical_plan.rs
+++ b/datafusion/proto/tests/cases/roundtrip_physical_plan.rs
@@ -39,6 +39,7 @@ use crate::cases::{
use datafusion::arrow::array::ArrayRef;
use datafusion::arrow::compute::kernels::sort::SortOptions;
use datafusion::arrow::datatypes::{DataType, Field, IntervalUnit, Schema};
+use datafusion::datasource::empty::EmptyTable;
use datafusion::datasource::file_format::csv::CsvSink;
use datafusion::datasource::file_format::json::JsonSink;
use datafusion::datasource::file_format::parquet::ParquetSink;
@@ -83,7 +84,7 @@ use datafusion::physical_plan::windows::{
WindowAggExec,
};
use datafusion::physical_plan::{
- ExecutionPlan, InputOrderMode, Partitioning, PhysicalExpr, Statistics,
+ displayable, ExecutionPlan, InputOrderMode, Partitioning, PhysicalExpr, Statistics,
};
use datafusion::prelude::SessionContext;
use datafusion::scalar::ScalarValue;
@@ -106,6 +107,7 @@ use datafusion_proto::physical_plan::{
AsExecutionPlan, DefaultPhysicalExtensionCodec, PhysicalExtensionCodec,
};
use datafusion_proto::protobuf;
+use datafusion_proto::protobuf::PhysicalPlanNode;
/// Perform a serde roundtrip and assert that the string representation of the before and after plans
/// are identical. Note that this often isn't sufficient to guarantee that no information is
@@ -1525,3 +1527,42 @@ fn roundtrip_unnest() -> Result<()> {
);
roundtrip_test(Arc::new(unnest))
}
+
+#[tokio::test]
+async fn roundtrip_coalesce() -> Result<()> {
+ let ctx = SessionContext::new();
+ ctx.register_table(
+ "t",
+ Arc::new(EmptyTable::new(Arc::new(Schema::new(Fields::from([
+ Arc::new(Field::new("f", DataType::Int64, false)),
+ ]))))),
+ )?;
+ let df = ctx.sql("select coalesce(f) as f from t").await?;
+ let plan = df.create_physical_plan().await?;
+
+ let node = PhysicalPlanNode::try_from_physical_plan(
+ plan.clone(),
+ &DefaultPhysicalExtensionCodec {},
+ )?;
+ let node = PhysicalPlanNode::decode(node.encode_to_vec().as_slice())
+ .map_err(|e| DataFusionError::External(Box::new(e)))?;
+ let restored = node.try_into_physical_plan(
+ &ctx,
+ ctx.runtime_env().as_ref(),
+ &DefaultPhysicalExtensionCodec {},
+ )?;
+
+ assert_eq!(
+ plan.schema(),
+ restored.schema(),
+ "Schema mismatch for plans:\n>> initial:\n{}>> final: \n{}",
+ displayable(plan.as_ref())
+ .set_show_schema(true)
+ .indent(true),
+ displayable(restored.as_ref())
+ .set_show_schema(true)
+ .indent(true),
+ );
+
+ Ok(())
+}