From f01e2d2364ede528d037c595ef22df97a8fb9bff Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:54:05 -0500 Subject: [PATCH 1/3] build: add protobuf messages for the materialized CTE plan nodes Add the schema for LogicalPlan::MaterializedCte and LogicalPlan::MaterializedCteScan (MaterializedCteNode and MaterializedCteScanNode) and for MaterializedCteExec and MaterializedCteScanExec (MaterializedCteExecNode and MaterializedCteScanExecNode), and regenerate the prost and pbjson code. A CTE node and its scans carry the same id, which binds each scan to its CTE in the encoded plan. The physical id is only valid within one encoded plan; the decoder allocates new ids. The decoders in datafusion-proto match the plan types exhaustively, so the new variants get arms that return a not-implemented error for now. The following commits replace them with the physical and the logical encode/decode. MaterializedCteScanNode also carries the functional dependencies of the scan schema (FunctionalDependence, DependencyMode). DfSchema does not encode them, and a scan is a leaf, so the decoder cannot compute them again. Co-Authored-By: Claude Opus 5.5 --- .../proto-models/proto/datafusion.proto | 66 ++ .../proto-models/src/generated/pbjson.rs | 1048 ++++++++++++++++- .../proto-models/src/generated/prost.rs | 123 +- datafusion/proto/src/logical_plan/mod.rs | 6 + datafusion/proto/src/physical_plan/mod.rs | 4 + 5 files changed, 1229 insertions(+), 18 deletions(-) diff --git a/datafusion/proto-models/proto/datafusion.proto b/datafusion/proto-models/proto/datafusion.proto index 083c371cdb69a..b1f524274fbe8 100644 --- a/datafusion/proto-models/proto/datafusion.proto +++ b/datafusion/proto-models/proto/datafusion.proto @@ -50,6 +50,8 @@ message LogicalPlanNode { DmlNode dml = 33; EmptyTableScanNode empty_table_scan = 34; AsOfJoinNode as_of_join = 35; + MaterializedCteNode materialized_cte = 36; + MaterializedCteScanNode materialized_cte_scan = 37; } } @@ -921,6 +923,8 @@ message PhysicalPlanNode { AsOfJoinExecNode as_of_join = 41; DataSourceExecNode data_source = 42; DataSinkExecNode data_sink = 43; + MaterializedCteExecNode materialized_cte = 44; + MaterializedCteScanExecNode materialized_cte_scan = 45; } } @@ -1686,6 +1690,43 @@ message CteWorkTableScanNode { datafusion_common.Schema schema = 2; } +// `WITH name AS MATERIALIZED (cte) continuation` +message MaterializedCteNode { + // Binds the scans in `continuation` to this node. + uint64 id = 1; + string name = 2; + LogicalPlanNode cte = 3; + LogicalPlanNode continuation = 4; +} + +message MaterializedCteScanNode { + // The id of the MaterializedCteNode that this scan reads. + uint64 id = 1; + string name = 2; + datafusion_common.DfSchema schema = 3; + // The columns of the CTE body that the scan outputs. Not set means all + // the columns. + MaterializedCteScanProjection projection = 4; + // The functional dependencies of `schema`. DfSchema does not encode them, + // and the decoder cannot compute them again, because the scan is a leaf. + repeated FunctionalDependence functional_dependencies = 5; +} + +// A functional dependency between the columns of a schema. The indexes are +// column positions in that schema. +message FunctionalDependence { + repeated uint64 source_indices = 1; + repeated uint64 target_indices = 2; + bool nullable = 3; + datafusion_common.NullEquality null_equality = 4; + DependencyMode mode = 5; +} + +enum DependencyMode { + DEPENDENCY_MODE_SINGLE = 0; + DEPENDENCY_MODE_MULTI = 1; +} + message EmptyTableScanNode { TableReference table_name = 1; datafusion_common.Schema schema = 2; @@ -1794,6 +1835,31 @@ message ScalarSubqueryExecNode { repeated PhysicalPlanNode subqueries = 2; } +message MaterializedCteExecNode { + // Binds the scans to this node. The id is valid in one encoded plan only: + // the decoder allocates a new id. + uint64 id = 1; + string name = 2; + PhysicalPlanNode body = 3; + PhysicalPlanNode continuation = 4; +} + +// Reads the buffered output of the MaterializedCteExecNode with the same id. +// That node must be in the same encoded plan. +message MaterializedCteScanExecNode { + uint64 id = 1; + string name = 2; + datafusion_common.Schema schema = 3; + uint64 partitions = 4; + // The columns of the body that the scan outputs. Not set means all the + // columns. + MaterializedCteScanProjection projection = 5; +} + +message MaterializedCteScanProjection { + repeated uint64 indices = 1; +} + message PhysicalScalarSubqueryExprNode { datafusion_common.ArrowType data_type = 1; bool nullable = 2; diff --git a/datafusion/proto-models/src/generated/pbjson.rs b/datafusion/proto-models/src/generated/pbjson.rs index affbcb8c604ed..08d82fa4724c3 100644 --- a/datafusion/proto-models/src/generated/pbjson.rs +++ b/datafusion/proto-models/src/generated/pbjson.rs @@ -6250,6 +6250,77 @@ impl<'de> serde::Deserialize<'de> for DateUnit { deserializer.deserialize_any(GeneratedVisitor) } } +impl serde::Serialize for DependencyMode { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> std::result::Result + where + S: serde::Serializer, + { + let variant = match self { + Self::Single => "DEPENDENCY_MODE_SINGLE", + Self::Multi => "DEPENDENCY_MODE_MULTI", + }; + serializer.serialize_str(variant) + } +} +impl<'de> serde::Deserialize<'de> for DependencyMode { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "DEPENDENCY_MODE_SINGLE", + "DEPENDENCY_MODE_MULTI", + ]; + + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = DependencyMode; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "expected one of: {:?}", &FIELDS) + } + + fn visit_i64(self, v: i64) -> std::result::Result + where + E: serde::de::Error, + { + i32::try_from(v) + .ok() + .and_then(|x| x.try_into().ok()) + .ok_or_else(|| { + serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) + }) + } + + fn visit_u64(self, v: u64) -> std::result::Result + where + E: serde::de::Error, + { + i32::try_from(v) + .ok() + .and_then(|x| x.try_into().ok()) + .ok_or_else(|| { + serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) + }) + } + + fn visit_str(self, value: &str) -> std::result::Result + where + E: serde::de::Error, + { + match value { + "DEPENDENCY_MODE_SINGLE" => Ok(DependencyMode::Single), + "DEPENDENCY_MODE_MULTI" => Ok(DependencyMode::Multi), + _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), + } + } + } + deserializer.deserialize_any(GeneratedVisitor) + } +} impl serde::Serialize for DistinctNode { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result @@ -9557,6 +9628,178 @@ impl<'de> serde::Deserialize<'de> for FullTableReference { deserializer.deserialize_struct("datafusion.FullTableReference", FIELDS, GeneratedVisitor) } } +impl serde::Serialize for FunctionalDependence { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> std::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.source_indices.is_empty() { + len += 1; + } + if !self.target_indices.is_empty() { + len += 1; + } + if self.nullable { + len += 1; + } + if self.null_equality != 0 { + len += 1; + } + if self.mode != 0 { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("datafusion.FunctionalDependence", len)?; + if !self.source_indices.is_empty() { + struct_ser.serialize_field("sourceIndices", &self.source_indices.iter().map(ToString::to_string).collect::>())?; + } + if !self.target_indices.is_empty() { + struct_ser.serialize_field("targetIndices", &self.target_indices.iter().map(ToString::to_string).collect::>())?; + } + if self.nullable { + struct_ser.serialize_field("nullable", &self.nullable)?; + } + if self.null_equality != 0 { + let v = super::datafusion_common::NullEquality::try_from(self.null_equality) + .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.null_equality)))?; + struct_ser.serialize_field("nullEquality", &v)?; + } + if self.mode != 0 { + let v = DependencyMode::try_from(self.mode) + .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.mode)))?; + struct_ser.serialize_field("mode", &v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for FunctionalDependence { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "source_indices", + "sourceIndices", + "target_indices", + "targetIndices", + "nullable", + "null_equality", + "nullEquality", + "mode", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + SourceIndices, + TargetIndices, + Nullable, + NullEquality, + Mode, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "expected one of: {:?}", &FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> std::result::Result + where + E: serde::de::Error, + { + match value { + "sourceIndices" | "source_indices" => Ok(GeneratedField::SourceIndices), + "targetIndices" | "target_indices" => Ok(GeneratedField::TargetIndices), + "nullable" => Ok(GeneratedField::Nullable), + "nullEquality" | "null_equality" => Ok(GeneratedField::NullEquality), + "mode" => Ok(GeneratedField::Mode), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = FunctionalDependence; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("struct datafusion.FunctionalDependence") + } + + fn visit_map(self, mut map_: V) -> std::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut source_indices__ = None; + let mut target_indices__ = None; + let mut nullable__ = None; + let mut null_equality__ = None; + let mut mode__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::SourceIndices => { + if source_indices__.is_some() { + return Err(serde::de::Error::duplicate_field("sourceIndices")); + } + source_indices__ = + Some(map_.next_value::>>()? + .into_iter().map(|x| x.0).collect()) + ; + } + GeneratedField::TargetIndices => { + if target_indices__.is_some() { + return Err(serde::de::Error::duplicate_field("targetIndices")); + } + target_indices__ = + Some(map_.next_value::>>()? + .into_iter().map(|x| x.0).collect()) + ; + } + GeneratedField::Nullable => { + if nullable__.is_some() { + return Err(serde::de::Error::duplicate_field("nullable")); + } + nullable__ = Some(map_.next_value()?); + } + GeneratedField::NullEquality => { + if null_equality__.is_some() { + return Err(serde::de::Error::duplicate_field("nullEquality")); + } + null_equality__ = Some(map_.next_value::()? as i32); + } + GeneratedField::Mode => { + if mode__.is_some() { + return Err(serde::de::Error::duplicate_field("mode")); + } + mode__ = Some(map_.next_value::()? as i32); + } + } + } + Ok(FunctionalDependence { + source_indices: source_indices__.unwrap_or_default(), + target_indices: target_indices__.unwrap_or_default(), + nullable: nullable__.unwrap_or_default(), + null_equality: null_equality__.unwrap_or_default(), + mode: mode__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("datafusion.FunctionalDependence", FIELDS, GeneratedVisitor) + } +} impl serde::Serialize for GenerateSeriesArgsContainsNull { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result @@ -15321,6 +15564,12 @@ impl serde::Serialize for LogicalPlanNode { logical_plan_node::LogicalPlanType::AsOfJoin(v) => { struct_ser.serialize_field("asOfJoin", v)?; } + logical_plan_node::LogicalPlanType::MaterializedCte(v) => { + struct_ser.serialize_field("materializedCte", v)?; + } + logical_plan_node::LogicalPlanType::MaterializedCteScan(v) => { + struct_ser.serialize_field("materializedCteScan", v)?; + } } } struct_ser.end() @@ -15384,6 +15633,10 @@ impl<'de> serde::Deserialize<'de> for LogicalPlanNode { "emptyTableScan", "as_of_join", "asOfJoin", + "materialized_cte", + "materializedCte", + "materialized_cte_scan", + "materializedCteScan", ]; #[allow(clippy::enum_variant_names)] @@ -15422,6 +15675,8 @@ impl<'de> serde::Deserialize<'de> for LogicalPlanNode { Dml, EmptyTableScan, AsOfJoin, + MaterializedCte, + MaterializedCteScan, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result @@ -15477,6 +15732,8 @@ impl<'de> serde::Deserialize<'de> for LogicalPlanNode { "dml" => Ok(GeneratedField::Dml), "emptyTableScan" | "empty_table_scan" => Ok(GeneratedField::EmptyTableScan), "asOfJoin" | "as_of_join" => Ok(GeneratedField::AsOfJoin), + "materializedCte" | "materialized_cte" => Ok(GeneratedField::MaterializedCte), + "materializedCteScan" | "materialized_cte_scan" => Ok(GeneratedField::MaterializedCteScan), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } @@ -15735,6 +15992,20 @@ impl<'de> serde::Deserialize<'de> for LogicalPlanNode { return Err(serde::de::Error::duplicate_field("asOfJoin")); } logical_plan_type__ = map_.next_value::<::std::option::Option<_>>()?.map(logical_plan_node::LogicalPlanType::AsOfJoin) +; + } + GeneratedField::MaterializedCte => { + if logical_plan_type__.is_some() { + return Err(serde::de::Error::duplicate_field("materializedCte")); + } + logical_plan_type__ = map_.next_value::<::std::option::Option<_>>()?.map(logical_plan_node::LogicalPlanType::MaterializedCte) +; + } + GeneratedField::MaterializedCteScan => { + if logical_plan_type__.is_some() { + return Err(serde::de::Error::duplicate_field("materializedCteScan")); + } + logical_plan_type__ = map_.next_value::<::std::option::Option<_>>()?.map(logical_plan_node::LogicalPlanType::MaterializedCteScan) ; } } @@ -15747,7 +16018,7 @@ impl<'de> serde::Deserialize<'de> for LogicalPlanNode { deserializer.deserialize_struct("datafusion.LogicalPlanNode", FIELDS, GeneratedVisitor) } } -impl serde::Serialize for MaybeFilter { +impl serde::Serialize for MaterializedCteExecNode { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where @@ -15755,29 +16026,55 @@ impl serde::Serialize for MaybeFilter { { use serde::ser::SerializeStruct; let mut len = 0; - if self.expr.is_some() { + if self.id != 0 { len += 1; } - let mut struct_ser = serializer.serialize_struct("datafusion.MaybeFilter", len)?; - if let Some(v) = self.expr.as_ref() { - struct_ser.serialize_field("expr", v)?; + if !self.name.is_empty() { + len += 1; + } + if self.body.is_some() { + len += 1; + } + if self.continuation.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("datafusion.MaterializedCteExecNode", len)?; + if self.id != 0 { + #[allow(clippy::needless_borrow)] + #[allow(clippy::needless_borrows_for_generic_args)] + struct_ser.serialize_field("id", ToString::to_string(&self.id).as_str())?; + } + if !self.name.is_empty() { + struct_ser.serialize_field("name", &self.name)?; + } + if let Some(v) = self.body.as_ref() { + struct_ser.serialize_field("body", v)?; + } + if let Some(v) = self.continuation.as_ref() { + struct_ser.serialize_field("continuation", v)?; } struct_ser.end() } } -impl<'de> serde::Deserialize<'de> for MaybeFilter { +impl<'de> serde::Deserialize<'de> for MaterializedCteExecNode { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ - "expr", + "id", + "name", + "body", + "continuation", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { - Expr, + Id, + Name, + Body, + Continuation, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result @@ -15799,7 +16096,10 @@ impl<'de> serde::Deserialize<'de> for MaybeFilter { E: serde::de::Error, { match value { - "expr" => Ok(GeneratedField::Expr), + "id" => Ok(GeneratedField::Id), + "name" => Ok(GeneratedField::Name), + "body" => Ok(GeneratedField::Body), + "continuation" => Ok(GeneratedField::Continuation), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } @@ -15809,22 +16109,710 @@ impl<'de> serde::Deserialize<'de> for MaybeFilter { } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { - type Value = MaybeFilter; + type Value = MaterializedCteExecNode; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.write_str("struct datafusion.MaybeFilter") + formatter.write_str("struct datafusion.MaterializedCteExecNode") } - fn visit_map(self, mut map_: V) -> std::result::Result + fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { - let mut expr__ = None; + let mut id__ = None; + let mut name__ = None; + let mut body__ = None; + let mut continuation__ = None; while let Some(k) = map_.next_key()? { match k { - GeneratedField::Expr => { - if expr__.is_some() { - return Err(serde::de::Error::duplicate_field("expr")); + GeneratedField::Id => { + if id__.is_some() { + return Err(serde::de::Error::duplicate_field("id")); + } + id__ = + Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) + ; + } + GeneratedField::Name => { + if name__.is_some() { + return Err(serde::de::Error::duplicate_field("name")); + } + name__ = Some(map_.next_value()?); + } + GeneratedField::Body => { + if body__.is_some() { + return Err(serde::de::Error::duplicate_field("body")); + } + body__ = map_.next_value()?; + } + GeneratedField::Continuation => { + if continuation__.is_some() { + return Err(serde::de::Error::duplicate_field("continuation")); + } + continuation__ = map_.next_value()?; + } + } + } + Ok(MaterializedCteExecNode { + id: id__.unwrap_or_default(), + name: name__.unwrap_or_default(), + body: body__, + continuation: continuation__, + }) + } + } + deserializer.deserialize_struct("datafusion.MaterializedCteExecNode", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for MaterializedCteNode { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> std::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if self.id != 0 { + len += 1; + } + if !self.name.is_empty() { + len += 1; + } + if self.cte.is_some() { + len += 1; + } + if self.continuation.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("datafusion.MaterializedCteNode", len)?; + if self.id != 0 { + #[allow(clippy::needless_borrow)] + #[allow(clippy::needless_borrows_for_generic_args)] + struct_ser.serialize_field("id", ToString::to_string(&self.id).as_str())?; + } + if !self.name.is_empty() { + struct_ser.serialize_field("name", &self.name)?; + } + if let Some(v) = self.cte.as_ref() { + struct_ser.serialize_field("cte", v)?; + } + if let Some(v) = self.continuation.as_ref() { + struct_ser.serialize_field("continuation", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for MaterializedCteNode { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "id", + "name", + "cte", + "continuation", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Id, + Name, + Cte, + Continuation, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "expected one of: {:?}", &FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> std::result::Result + where + E: serde::de::Error, + { + match value { + "id" => Ok(GeneratedField::Id), + "name" => Ok(GeneratedField::Name), + "cte" => Ok(GeneratedField::Cte), + "continuation" => Ok(GeneratedField::Continuation), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = MaterializedCteNode; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("struct datafusion.MaterializedCteNode") + } + + fn visit_map(self, mut map_: V) -> std::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut id__ = None; + let mut name__ = None; + let mut cte__ = None; + let mut continuation__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Id => { + if id__.is_some() { + return Err(serde::de::Error::duplicate_field("id")); + } + id__ = + Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) + ; + } + GeneratedField::Name => { + if name__.is_some() { + return Err(serde::de::Error::duplicate_field("name")); + } + name__ = Some(map_.next_value()?); + } + GeneratedField::Cte => { + if cte__.is_some() { + return Err(serde::de::Error::duplicate_field("cte")); + } + cte__ = map_.next_value()?; + } + GeneratedField::Continuation => { + if continuation__.is_some() { + return Err(serde::de::Error::duplicate_field("continuation")); + } + continuation__ = map_.next_value()?; + } + } + } + Ok(MaterializedCteNode { + id: id__.unwrap_or_default(), + name: name__.unwrap_or_default(), + cte: cte__, + continuation: continuation__, + }) + } + } + deserializer.deserialize_struct("datafusion.MaterializedCteNode", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for MaterializedCteScanExecNode { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> std::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if self.id != 0 { + len += 1; + } + if !self.name.is_empty() { + len += 1; + } + if self.schema.is_some() { + len += 1; + } + if self.partitions != 0 { + len += 1; + } + if self.projection.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("datafusion.MaterializedCteScanExecNode", len)?; + if self.id != 0 { + #[allow(clippy::needless_borrow)] + #[allow(clippy::needless_borrows_for_generic_args)] + struct_ser.serialize_field("id", ToString::to_string(&self.id).as_str())?; + } + if !self.name.is_empty() { + struct_ser.serialize_field("name", &self.name)?; + } + if let Some(v) = self.schema.as_ref() { + struct_ser.serialize_field("schema", v)?; + } + if self.partitions != 0 { + #[allow(clippy::needless_borrow)] + #[allow(clippy::needless_borrows_for_generic_args)] + struct_ser.serialize_field("partitions", ToString::to_string(&self.partitions).as_str())?; + } + if let Some(v) = self.projection.as_ref() { + struct_ser.serialize_field("projection", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for MaterializedCteScanExecNode { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "id", + "name", + "schema", + "partitions", + "projection", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Id, + Name, + Schema, + Partitions, + Projection, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "expected one of: {:?}", &FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> std::result::Result + where + E: serde::de::Error, + { + match value { + "id" => Ok(GeneratedField::Id), + "name" => Ok(GeneratedField::Name), + "schema" => Ok(GeneratedField::Schema), + "partitions" => Ok(GeneratedField::Partitions), + "projection" => Ok(GeneratedField::Projection), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = MaterializedCteScanExecNode; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("struct datafusion.MaterializedCteScanExecNode") + } + + fn visit_map(self, mut map_: V) -> std::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut id__ = None; + let mut name__ = None; + let mut schema__ = None; + let mut partitions__ = None; + let mut projection__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Id => { + if id__.is_some() { + return Err(serde::de::Error::duplicate_field("id")); + } + id__ = + Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) + ; + } + GeneratedField::Name => { + if name__.is_some() { + return Err(serde::de::Error::duplicate_field("name")); + } + name__ = Some(map_.next_value()?); + } + GeneratedField::Schema => { + if schema__.is_some() { + return Err(serde::de::Error::duplicate_field("schema")); + } + schema__ = map_.next_value()?; + } + GeneratedField::Partitions => { + if partitions__.is_some() { + return Err(serde::de::Error::duplicate_field("partitions")); + } + partitions__ = + Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) + ; + } + GeneratedField::Projection => { + if projection__.is_some() { + return Err(serde::de::Error::duplicate_field("projection")); + } + projection__ = map_.next_value()?; + } + } + } + Ok(MaterializedCteScanExecNode { + id: id__.unwrap_or_default(), + name: name__.unwrap_or_default(), + schema: schema__, + partitions: partitions__.unwrap_or_default(), + projection: projection__, + }) + } + } + deserializer.deserialize_struct("datafusion.MaterializedCteScanExecNode", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for MaterializedCteScanNode { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> std::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if self.id != 0 { + len += 1; + } + if !self.name.is_empty() { + len += 1; + } + if self.schema.is_some() { + len += 1; + } + if self.projection.is_some() { + len += 1; + } + if !self.functional_dependencies.is_empty() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("datafusion.MaterializedCteScanNode", len)?; + if self.id != 0 { + #[allow(clippy::needless_borrow)] + #[allow(clippy::needless_borrows_for_generic_args)] + struct_ser.serialize_field("id", ToString::to_string(&self.id).as_str())?; + } + if !self.name.is_empty() { + struct_ser.serialize_field("name", &self.name)?; + } + if let Some(v) = self.schema.as_ref() { + struct_ser.serialize_field("schema", v)?; + } + if let Some(v) = self.projection.as_ref() { + struct_ser.serialize_field("projection", v)?; + } + if !self.functional_dependencies.is_empty() { + struct_ser.serialize_field("functionalDependencies", &self.functional_dependencies)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for MaterializedCteScanNode { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "id", + "name", + "schema", + "projection", + "functional_dependencies", + "functionalDependencies", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Id, + Name, + Schema, + Projection, + FunctionalDependencies, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "expected one of: {:?}", &FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> std::result::Result + where + E: serde::de::Error, + { + match value { + "id" => Ok(GeneratedField::Id), + "name" => Ok(GeneratedField::Name), + "schema" => Ok(GeneratedField::Schema), + "projection" => Ok(GeneratedField::Projection), + "functionalDependencies" | "functional_dependencies" => Ok(GeneratedField::FunctionalDependencies), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = MaterializedCteScanNode; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("struct datafusion.MaterializedCteScanNode") + } + + fn visit_map(self, mut map_: V) -> std::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut id__ = None; + let mut name__ = None; + let mut schema__ = None; + let mut projection__ = None; + let mut functional_dependencies__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Id => { + if id__.is_some() { + return Err(serde::de::Error::duplicate_field("id")); + } + id__ = + Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) + ; + } + GeneratedField::Name => { + if name__.is_some() { + return Err(serde::de::Error::duplicate_field("name")); + } + name__ = Some(map_.next_value()?); + } + GeneratedField::Schema => { + if schema__.is_some() { + return Err(serde::de::Error::duplicate_field("schema")); + } + schema__ = map_.next_value()?; + } + GeneratedField::Projection => { + if projection__.is_some() { + return Err(serde::de::Error::duplicate_field("projection")); + } + projection__ = map_.next_value()?; + } + GeneratedField::FunctionalDependencies => { + if functional_dependencies__.is_some() { + return Err(serde::de::Error::duplicate_field("functionalDependencies")); + } + functional_dependencies__ = Some(map_.next_value()?); + } + } + } + Ok(MaterializedCteScanNode { + id: id__.unwrap_or_default(), + name: name__.unwrap_or_default(), + schema: schema__, + projection: projection__, + functional_dependencies: functional_dependencies__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("datafusion.MaterializedCteScanNode", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for MaterializedCteScanProjection { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> std::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.indices.is_empty() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("datafusion.MaterializedCteScanProjection", len)?; + if !self.indices.is_empty() { + struct_ser.serialize_field("indices", &self.indices.iter().map(ToString::to_string).collect::>())?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for MaterializedCteScanProjection { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "indices", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Indices, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "expected one of: {:?}", &FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> std::result::Result + where + E: serde::de::Error, + { + match value { + "indices" => Ok(GeneratedField::Indices), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = MaterializedCteScanProjection; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("struct datafusion.MaterializedCteScanProjection") + } + + fn visit_map(self, mut map_: V) -> std::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut indices__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Indices => { + if indices__.is_some() { + return Err(serde::de::Error::duplicate_field("indices")); + } + indices__ = + Some(map_.next_value::>>()? + .into_iter().map(|x| x.0).collect()) + ; + } + } + } + Ok(MaterializedCteScanProjection { + indices: indices__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("datafusion.MaterializedCteScanProjection", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for MaybeFilter { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> std::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if self.expr.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("datafusion.MaybeFilter", len)?; + if let Some(v) = self.expr.as_ref() { + struct_ser.serialize_field("expr", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for MaybeFilter { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "expr", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Expr, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "expected one of: {:?}", &FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> std::result::Result + where + E: serde::de::Error, + { + match value { + "expr" => Ok(GeneratedField::Expr), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = MaybeFilter; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("struct datafusion.MaybeFilter") + } + + fn visit_map(self, mut map_: V) -> std::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut expr__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Expr => { + if expr__.is_some() { + return Err(serde::de::Error::duplicate_field("expr")); } expr__ = map_.next_value()?; } @@ -22838,6 +23826,12 @@ impl serde::Serialize for PhysicalPlanNode { physical_plan_node::PhysicalPlanType::DataSink(v) => { struct_ser.serialize_field("dataSink", v)?; } + physical_plan_node::PhysicalPlanType::MaterializedCte(v) => { + struct_ser.serialize_field("materializedCte", v)?; + } + physical_plan_node::PhysicalPlanType::MaterializedCteScan(v) => { + struct_ser.serialize_field("materializedCteScan", v)?; + } } } struct_ser.end() @@ -22900,6 +23894,10 @@ impl<'de> serde::Deserialize<'de> for PhysicalPlanNode { "dataSource", "data_sink", "dataSink", + "materialized_cte", + "materializedCte", + "materialized_cte_scan", + "materializedCteScan", ]; #[allow(clippy::enum_variant_names)] @@ -22937,6 +23935,8 @@ impl<'de> serde::Deserialize<'de> for PhysicalPlanNode { AsOfJoin, DataSource, DataSink, + MaterializedCte, + MaterializedCteScan, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result @@ -22991,6 +23991,8 @@ impl<'de> serde::Deserialize<'de> for PhysicalPlanNode { "asOfJoin" | "as_of_join" => Ok(GeneratedField::AsOfJoin), "dataSource" | "data_source" => Ok(GeneratedField::DataSource), "dataSink" | "data_sink" => Ok(GeneratedField::DataSink), + "materializedCte" | "materialized_cte" => Ok(GeneratedField::MaterializedCte), + "materializedCteScan" | "materialized_cte_scan" => Ok(GeneratedField::MaterializedCteScan), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } @@ -23242,6 +24244,20 @@ impl<'de> serde::Deserialize<'de> for PhysicalPlanNode { return Err(serde::de::Error::duplicate_field("dataSink")); } physical_plan_type__ = map_.next_value::<::std::option::Option<_>>()?.map(physical_plan_node::PhysicalPlanType::DataSink) +; + } + GeneratedField::MaterializedCte => { + if physical_plan_type__.is_some() { + return Err(serde::de::Error::duplicate_field("materializedCte")); + } + physical_plan_type__ = map_.next_value::<::std::option::Option<_>>()?.map(physical_plan_node::PhysicalPlanType::MaterializedCte) +; + } + GeneratedField::MaterializedCteScan => { + if physical_plan_type__.is_some() { + return Err(serde::de::Error::duplicate_field("materializedCteScan")); + } + physical_plan_type__ = map_.next_value::<::std::option::Option<_>>()?.map(physical_plan_node::PhysicalPlanType::MaterializedCteScan) ; } } diff --git a/datafusion/proto-models/src/generated/prost.rs b/datafusion/proto-models/src/generated/prost.rs index 70105f0b51da5..ecfa76500c004 100644 --- a/datafusion/proto-models/src/generated/prost.rs +++ b/datafusion/proto-models/src/generated/prost.rs @@ -5,7 +5,7 @@ pub struct LogicalPlanNode { #[prost( oneof = "logical_plan_node::LogicalPlanType", - tags = "1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35" + tags = "1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37" )] pub logical_plan_type: ::core::option::Option, } @@ -81,6 +81,10 @@ pub mod logical_plan_node { EmptyTableScan(super::EmptyTableScanNode), #[prost(message, tag = "35")] AsOfJoin(::prost::alloc::boxed::Box), + #[prost(message, tag = "36")] + MaterializedCte(::prost::alloc::boxed::Box), + #[prost(message, tag = "37")] + MaterializedCteScan(super::MaterializedCteScanNode), } } #[derive(Clone, PartialEq, ::prost::Message)] @@ -1393,7 +1397,7 @@ pub mod table_reference { pub struct PhysicalPlanNode { #[prost( oneof = "physical_plan_node::PhysicalPlanType", - tags = "3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 25, 26, 27, 30, 32, 33, 34, 36, 37, 39, 40, 41, 42, 43" + tags = "3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 25, 26, 27, 30, 32, 33, 34, 36, 37, 39, 40, 41, 42, 43, 44, 45" )] pub physical_plan_type: ::core::option::Option, } @@ -1471,6 +1475,10 @@ pub mod physical_plan_node { DataSource(super::DataSourceExecNode), #[prost(message, tag = "43")] DataSink(::prost::alloc::boxed::Box), + #[prost(message, tag = "44")] + MaterializedCte(::prost::alloc::boxed::Box), + #[prost(message, tag = "45")] + MaterializedCteScan(super::MaterializedCteScanExecNode), } } #[derive(Clone, PartialEq, ::prost::Message)] @@ -2546,6 +2554,54 @@ pub struct CteWorkTableScanNode { #[prost(message, optional, tag = "2")] pub schema: ::core::option::Option, } +/// `WITH name AS MATERIALIZED (cte) continuation` +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct MaterializedCteNode { + /// Binds the scans in `continuation` to this node. + #[prost(uint64, tag = "1")] + pub id: u64, + #[prost(string, tag = "2")] + pub name: ::prost::alloc::string::String, + #[prost(message, optional, boxed, tag = "3")] + pub cte: ::core::option::Option<::prost::alloc::boxed::Box>, + #[prost(message, optional, boxed, tag = "4")] + pub continuation: ::core::option::Option< + ::prost::alloc::boxed::Box, + >, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct MaterializedCteScanNode { + /// The id of the MaterializedCteNode that this scan reads. + #[prost(uint64, tag = "1")] + pub id: u64, + #[prost(string, tag = "2")] + pub name: ::prost::alloc::string::String, + #[prost(message, optional, tag = "3")] + pub schema: ::core::option::Option, + /// The columns of the CTE body that the scan outputs. Not set means all + /// the columns. + #[prost(message, optional, tag = "4")] + pub projection: ::core::option::Option, + /// The functional dependencies of `schema`. DfSchema does not encode them, + /// and the decoder cannot compute them again, because the scan is a leaf. + #[prost(message, repeated, tag = "5")] + pub functional_dependencies: ::prost::alloc::vec::Vec, +} +/// A functional dependency between the columns of a schema. The indexes are +/// column positions in that schema. +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct FunctionalDependence { + #[prost(uint64, repeated, tag = "1")] + pub source_indices: ::prost::alloc::vec::Vec, + #[prost(uint64, repeated, tag = "2")] + pub target_indices: ::prost::alloc::vec::Vec, + #[prost(bool, tag = "3")] + pub nullable: bool, + #[prost(enumeration = "super::datafusion_common::NullEquality", tag = "4")] + pub null_equality: i32, + #[prost(enumeration = "DependencyMode", tag = "5")] + pub mode: i32, +} #[derive(Clone, PartialEq, ::prost::Message)] pub struct EmptyTableScanNode { #[prost(message, optional, tag = "1")] @@ -2716,6 +2772,43 @@ pub struct ScalarSubqueryExecNode { pub subqueries: ::prost::alloc::vec::Vec, } #[derive(Clone, PartialEq, ::prost::Message)] +pub struct MaterializedCteExecNode { + /// Binds the scans to this node. The id is valid in one encoded plan only: + /// the decoder allocates a new id. + #[prost(uint64, tag = "1")] + pub id: u64, + #[prost(string, tag = "2")] + pub name: ::prost::alloc::string::String, + #[prost(message, optional, boxed, tag = "3")] + pub body: ::core::option::Option<::prost::alloc::boxed::Box>, + #[prost(message, optional, boxed, tag = "4")] + pub continuation: ::core::option::Option< + ::prost::alloc::boxed::Box, + >, +} +/// Reads the buffered output of the MaterializedCteExecNode with the same id. +/// That node must be in the same encoded plan. +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct MaterializedCteScanExecNode { + #[prost(uint64, tag = "1")] + pub id: u64, + #[prost(string, tag = "2")] + pub name: ::prost::alloc::string::String, + #[prost(message, optional, tag = "3")] + pub schema: ::core::option::Option, + #[prost(uint64, tag = "4")] + pub partitions: u64, + /// The columns of the body that the scan outputs. Not set means all the + /// columns. + #[prost(message, optional, tag = "5")] + pub projection: ::core::option::Option, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct MaterializedCteScanProjection { + #[prost(uint64, repeated, tag = "1")] + pub indices: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, ::prost::Message)] pub struct PhysicalScalarSubqueryExprNode { #[prost(message, optional, tag = "1")] pub data_type: ::core::option::Option, @@ -3307,6 +3400,32 @@ impl AggregateMode { } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] +pub enum DependencyMode { + Single = 0, + Multi = 1, +} +impl DependencyMode { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + Self::Single => "DEPENDENCY_MODE_SINGLE", + Self::Multi => "DEPENDENCY_MODE_MULTI", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option { + match value { + "DEPENDENCY_MODE_SINGLE" => Some(Self::Single), + "DEPENDENCY_MODE_MULTI" => Some(Self::Multi), + _ => None, + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] +#[repr(i32)] pub enum GenerateSeriesName { GsGenerateSeries = 0, GsRange = 1, diff --git a/datafusion/proto/src/logical_plan/mod.rs b/datafusion/proto/src/logical_plan/mod.rs index b0aef619add52..26b68d473c6d4 100644 --- a/datafusion/proto/src/logical_plan/mod.rs +++ b/datafusion/proto/src/logical_plan/mod.rs @@ -1342,6 +1342,12 @@ impl AsLogicalPlan for LogicalPlanNode { ) .map(LogicalPlan::RecursiveQuery) } + LogicalPlanType::MaterializedCte(_) + | LogicalPlanType::MaterializedCteScan(_) => { + not_impl_err!( + "LogicalPlan serde is not yet implemented for MATERIALIZED CTEs" + ) + } LogicalPlanType::CteWorkTableScan(cte_work_table_scan_node) => { let CteWorkTableScanNode { name, schema } = cte_work_table_scan_node; let schema = convert_required!(*schema)?; diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rs index 36cd8f1c993ed..d8c45ac9f51b6 100644 --- a/datafusion/proto/src/physical_plan/mod.rs +++ b/datafusion/proto/src/physical_plan/mod.rs @@ -1318,6 +1318,10 @@ pub trait PhysicalPlanNodeExt: Sized { PhysicalPlanType::PiecewiseMergeJoin(_) => { PiecewiseMergeJoinExec::try_from_proto(self.node(), &decode_ctx) } + PhysicalPlanType::MaterializedCte(_) + | PhysicalPlanType::MaterializedCteScan(_) => not_impl_err!( + "PhysicalPlan serde is not yet implemented for MATERIALIZED CTEs" + ), } } From eb8a65d9b99be9c98491ff7e525eb9450daed50b Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:00:51 -0500 Subject: [PATCH 2/3] feat: protobuf encode/decode for MaterializedCteExec and MaterializedCteScanExec Implement try_to_proto/try_from_proto for the two physical materialized CTE nodes and wire them into the datafusion-proto decoder, replacing the not-implemented arm. The encoding carries only the id and the name of the CTE. The decode context holds one buffer per encoded id (DecodedMaterializedCteBuffers), reached through the new ExecutionPlanDecode::materialized_cte_buffer, so a decoded scan and its MaterializedCteExec share the buffer wherever they are in the plan, including when the scan sits in a scalar subquery and is not below the CTE. Decoded buffers get new ids, because ids from another process can collide with local ones. A decoded fragment that has a scan without its MaterializedCteExec now fails with a clear execution error instead of an internal error. The body statistics of a scan are not serialized: a decoded scan reports unknown statistics until the planner sets them again. Round-trip tests cover two scans of one CTE, a scan in a scalar subquery, and the error for a scan without its CTE. Two decoded MaterializedCteExec nodes with one id in one decode context return a planning error, not an internal error. Encoded bytes can cause it, and so can a decode context that is used for two plans. A test covers it. Co-Authored-By: Claude Opus 5.5 --- .../physical-plan/src/materialized_cte.rs | 230 +++++++++++++++++- datafusion/physical-plan/src/proto/mod.rs | 21 ++ .../physical-plan/src/proto_test_util.rs | 19 ++ datafusion/proto/src/physical_plan/mod.rs | 34 ++- .../tests/cases/plans/materialized_cte.rs | 208 ++++++++++++++++ datafusion/proto/tests/cases/plans/mod.rs | 1 + 6 files changed, 507 insertions(+), 6 deletions(-) create mode 100644 datafusion/proto/tests/cases/plans/materialized_cte.rs diff --git a/datafusion/physical-plan/src/materialized_cte.rs b/datafusion/physical-plan/src/materialized_cte.rs index 45588fd0ba078..174701a8d30df 100644 --- a/datafusion/physical-plan/src/materialized_cte.rs +++ b/datafusion/physical-plan/src/materialized_cte.rs @@ -31,16 +31,18 @@ //! the statistics of the body. The planner copies them to the scan with //! [`MaterializedCteScanExec::with_body_statistics`]. +use std::collections::HashMap; use std::fmt; use std::pin::Pin; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::task::{Context, Poll}; use arrow::datatypes::{Schema, SchemaRef}; use arrow::record_batch::RecordBatch; use datafusion_common::config::ConfigOptions; use datafusion_common::tree_node::TreeNodeRecursion; -use datafusion_common::{Result, Statistics, internal_err}; +use datafusion_common::{Result, Statistics, exec_err, internal_err, plan_err}; use datafusion_common_runtime::JoinSet; use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation}; use datafusion_execution::{SendableRecordBatchStream, SpillFile, TaskContext}; @@ -291,6 +293,11 @@ impl MaterializedCteBuffer { self.id } + /// The name of the CTE. + pub fn name(&self) -> &str { + &self.name + } + fn set_body(&self, body: Arc) { *self.body.lock() = Some(body); } @@ -305,8 +312,13 @@ impl MaterializedCteBuffer { self: &Arc, context: Arc, ) -> Result> { + // A plan from the planner always has the body. A decoded plan does + // not have it when the plan was split between the body and a scan. let Some(body) = self.body.lock().clone() else { - return internal_err!("MaterializedCte {} has no body", self.name); + return exec_err!( + "The materialized CTE {} has a MaterializedCteScanExec but no MaterializedCteExec in this plan. The body and the scans of a materialized CTE must be in one plan and run in one process", + self.name + ); }; let once = Arc::clone(&self.output.lock()); let name = self.name.clone(); @@ -318,6 +330,39 @@ impl MaterializedCteBuffer { } } +/// The buffers of the materialized CTEs in one decoded plan. +/// +/// A [`MaterializedCteExec`] and its [`MaterializedCteScanExec`]s are encoded +/// as separate nodes that have the same id. The decoder of each node asks for +/// the buffer of that id, so all of them share one buffer, in any decode +/// order. A scan in a scalar subquery is not below its `MaterializedCteExec`, +/// so one registry must be used for the whole plan. +/// +/// The ids in an encoded plan come from another process and can be equal to +/// the ids of plans made in this process. Each buffer therefore gets a new id +/// from a counter that starts at 2^63. The planner takes its ids from +/// `datafusion_expr::MaterializedCteId`, which counts up from 0, so the two +/// ranges do not overlap. +#[derive(Debug, Default)] +pub struct DecodedMaterializedCteBuffers { + /// The buffers, by the id in the encoded plan. + buffers: Mutex>>, +} + +impl DecodedMaterializedCteBuffers { + /// Return the buffer of the CTE that has the id `encoded_id` in the + /// encoded plan. The first call for an id creates the buffer. + pub fn buffer(&self, encoded_id: u64, name: &str) -> Arc { + let mut buffers = self.buffers.lock(); + let buffer = buffers.entry(encoded_id).or_insert_with(|| { + static NEXT_DECODED_ID: AtomicU64 = AtomicU64::new(1 << 63); + let id = NEXT_DECODED_ID.fetch_add(1, AtomicOrdering::Relaxed); + Arc::new(MaterializedCteBuffer::new(id, name)) + }); + Arc::clone(buffer) + } +} + async fn buffer_body( name: String, body: Arc, @@ -651,6 +696,85 @@ impl ExecutionPlan for MaterializedCteExec { // continuation handles it. Ok(FilterPushdownPropagation::if_any(child_pushdown_result)) } + + #[cfg(feature = "proto")] + fn try_to_proto( + &self, + ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>, + ) -> Result> { + use datafusion_proto_models::protobuf; + + // Destructure exhaustively (no `..`) so that adding a field to + // `MaterializedCteExec` is a compile error here until it is either + // serialized or explicitly documented as not needing to be. + let Self { + body, + continuation, + // Only the id and the name are encoded. The decoder makes a new + // buffer and shares it with the scans that have the same id. + buffer, + // Copied from the continuation's properties, recomputed on decode. + cache: _, + } = self; + Ok(Some(protobuf::PhysicalPlanNode { + physical_plan_type: Some( + protobuf::physical_plan_node::PhysicalPlanType::MaterializedCte( + Box::new(protobuf::MaterializedCteExecNode { + id: buffer.id(), + name: buffer.name().to_string(), + body: Some(Box::new(ctx.encode_child(body)?)), + continuation: Some(Box::new(ctx.encode_child(continuation)?)), + }), + ), + ), + })) + } +} + +#[cfg(feature = "proto")] +impl MaterializedCteExec { + /// Reconstruct a [`MaterializedCteExec`] from its protobuf representation. + /// + /// The node shares the buffer that the decode context holds for its id + /// with the decoded [`MaterializedCteScanExec`]s of the same id. + pub fn try_from_proto( + node: &datafusion_proto_models::protobuf::PhysicalPlanNode, + ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>, + ) -> Result> { + use datafusion_proto_models::protobuf; + + let cte = crate::expect_plan_variant!( + node, + protobuf::physical_plan_node::PhysicalPlanType::MaterializedCte, + "MaterializedCteExec", + ); + // Destructure exhaustively so that a new field on + // `MaterializedCteExecNode` is a compile error here rather than a + // silently dropped field. + let protobuf::MaterializedCteExecNode { + id, + name, + body, + continuation, + } = &**cte; + let body = + ctx.decode_required_child(body.as_deref(), "MaterializedCteExec", "body")?; + let continuation = ctx.decode_required_child( + continuation.as_deref(), + "MaterializedCteExec", + "continuation", + )?; + let buffer = ctx.materialized_cte_buffer(*id, name)?; + // A second node would replace the body that the scans read. Encoded + // bytes can cause this, and so can a decode context that is used for + // two plans, so it is not an internal error. + if buffer.body.lock().is_some() { + return plan_err!( + "Two MaterializedCteExec nodes have the id {id} in one decode context. An encoded plan must have one MaterializedCteExec for each id, and each plan must be decoded with a new decode context" + ); + } + Ok(Arc::new(Self::new(body, continuation, buffer))) + } } /// Reads the buffered output of a [`MaterializedCteExec`] body. @@ -950,6 +1074,108 @@ impl ExecutionPlan for MaterializedCteScanExec { _ => Ok(Arc::new(Statistics::new_unknown(&self.schema))), } } + + #[cfg(feature = "proto")] + fn try_to_proto( + &self, + _ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>, + ) -> Result> { + use datafusion_common::utils::usize_to_wire; + use datafusion_proto_models::protobuf; + + // Destructure exhaustively (no `..`) so that adding a field to + // `MaterializedCteScanExec` is a compile error here until it is + // either serialized or explicitly documented as not needing to be. + let Self { + id, + name, + schema, + // The decoder binds the scan to the buffer of `id` again. + buffer: _, + // Runtime metrics, created empty on decode. + metrics: _, + // The body statistics are not serialized: a decoded scan reports + // unknown statistics until the planner sets them again. + statistics: _, + projection, + cache, + } = self; + let partitions = usize_to_wire( + cache.partitioning.partition_count(), + "MaterializedCteScanExec", + "partitions", + )?; + Ok(Some(protobuf::PhysicalPlanNode { + physical_plan_type: Some( + protobuf::physical_plan_node::PhysicalPlanType::MaterializedCteScan( + protobuf::MaterializedCteScanExecNode { + id: *id, + name: name.clone(), + schema: Some(schema.as_ref().try_into()?), + partitions, + projection: projection.as_ref().map(|indices| { + protobuf::MaterializedCteScanProjection { + indices: indices.iter().map(|i| *i as u64).collect(), + } + }), + }, + ), + ), + })) + } +} + +#[cfg(feature = "proto")] +impl MaterializedCteScanExec { + /// Reconstruct a [`MaterializedCteScanExec`] from its protobuf + /// representation. + /// + /// The scan is bound to the buffer that the decode context holds for its + /// id. The decoded [`MaterializedCteExec`] of the same id gives that + /// buffer its body. If the decoded plan has no such node, the scan fails + /// when it is executed. + pub fn try_from_proto( + node: &datafusion_proto_models::protobuf::PhysicalPlanNode, + ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>, + ) -> Result> { + use datafusion_common::utils::usize_from_wire; + use datafusion_proto_models::protobuf; + + let scan = crate::expect_plan_variant!( + node, + protobuf::physical_plan_node::PhysicalPlanType::MaterializedCteScan, + "MaterializedCteScanExec", + ); + // Destructure exhaustively so that a new field on + // `MaterializedCteScanExecNode` is a compile error here rather than a + // silently dropped field. + let protobuf::MaterializedCteScanExecNode { + id, + name, + schema, + partitions, + projection, + } = scan; + let schema = schema.as_ref().ok_or_else(|| { + datafusion_common::internal_datafusion_err!( + "MaterializedCteScanExec is missing required field 'schema'" + ) + })?; + let schema = Arc::new(Schema::try_from(schema)?); + let partitions = + usize_from_wire(*partitions, "MaterializedCteScanExec", "partitions")?; + let buffer = ctx.materialized_cte_buffer(*id, name)?; + let mut scan = Self::new(buffer.id(), name, schema, partitions); + if let Some(projection) = projection { + let indices = projection + .indices + .iter() + .map(|i| usize_from_wire(*i, "MaterializedCteScanExec", "projection")) + .collect::>>()?; + scan = scan.with_body_projection(indices)?; + } + Ok(Arc::new(scan.bind(buffer))) + } } #[cfg(test)] diff --git a/datafusion/physical-plan/src/proto/mod.rs b/datafusion/physical-plan/src/proto/mod.rs index 9fe5113affc15..10881d862186d 100644 --- a/datafusion/physical-plan/src/proto/mod.rs +++ b/datafusion/physical-plan/src/proto/mod.rs @@ -80,6 +80,7 @@ use datafusion_proto_models::protobuf::{ }; use crate::ExecutionPlan; +use crate::materialized_cte::MaterializedCteBuffer; pub use datafusion_proto_models::ProtoDecoderRegistry; // Not public API: see `decode_execution_plan`. @@ -168,6 +169,16 @@ pub trait ExecutionPlanDecode { /// Reconstruct a window UDF from its name and optional payload. fn decode_udwf(&self, name: &str, payload: Option<&[u8]>) -> Result>; + + /// The buffer of the materialized CTE that has the id `encoded_id` in the + /// encoded plan. Every call for one id during the decoding of one plan + /// must return the same buffer. See + /// [`DecodedMaterializedCteBuffers`](crate::materialized_cte::DecodedMaterializedCteBuffers). + fn materialized_cte_buffer( + &self, + encoded_id: u64, + name: &str, + ) -> Result>; } /// Context handed to [`ExecutionPlan::try_to_proto`]. @@ -401,6 +412,16 @@ impl<'a> ExecutionPlanDecodeCtx<'a> { self.decoder.decode_udwf(name, payload) } + /// The buffer that a decoded `MaterializedCteExec` shares with the decoded + /// `MaterializedCteScanExec`s that have the same `encoded_id`. + pub fn materialized_cte_buffer( + &self, + encoded_id: u64, + name: &str, + ) -> Result> { + self.decoder.materialized_cte_buffer(encoded_id, name) + } + /// An expression-level decode context backed by this plan context, bound to /// `input_schema`. /// diff --git a/datafusion/physical-plan/src/proto_test_util.rs b/datafusion/physical-plan/src/proto_test_util.rs index 2b6eecc54e2d7..093309652cf21 100644 --- a/datafusion/physical-plan/src/proto_test_util.rs +++ b/datafusion/physical-plan/src/proto_test_util.rs @@ -41,6 +41,7 @@ use datafusion_proto_models::protobuf::{ use crate::ExecutionPlan; use crate::empty::EmptyExec; +use crate::materialized_cte::MaterializedCteBuffer; use crate::proto::{ExecutionPlanDecode, ExecutionPlanEncode}; /// The schema shared by the stub child plans: `a: Int32, b: Int32`. @@ -305,6 +306,14 @@ impl ExecutionPlanDecode for StubPlanDecoder { fn decode_udwf(&self, name: &str, _payload: Option<&[u8]>) -> Result> { internal_err!("stub decoder cannot decode the window UDF {name}") } + + fn materialized_cte_buffer( + &self, + _encoded_id: u64, + name: &str, + ) -> Result> { + internal_err!("stub decoder cannot decode the materialized CTE {name}") + } } /// Minimal extension plans for the [`crate::proto::registry`] tests. @@ -513,4 +522,14 @@ impl ExecutionPlanDecode for UnreachablePlanDecoder { ) -> Result> { unreachable!("decode_udwf must not be reached when the node is rejected") } + + fn materialized_cte_buffer( + &self, + _encoded_id: u64, + _name: &str, + ) -> Result> { + unreachable!( + "materialized_cte_buffer must not be reached when the node is rejected" + ) + } } diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rs index d8c45ac9f51b6..91e4b696f2ec2 100644 --- a/datafusion/proto/src/physical_plan/mod.rs +++ b/datafusion/proto/src/physical_plan/mod.rs @@ -55,6 +55,10 @@ use datafusion_physical_plan::joins::{ PiecewiseMergeJoinExec, SortMergeJoinExec, SymmetricHashJoinExec, }; use datafusion_physical_plan::limit::{GlobalLimitExec, LocalLimitExec}; +use datafusion_physical_plan::materialized_cte::{ + DecodedMaterializedCteBuffers, MaterializedCteBuffer, MaterializedCteExec, + MaterializedCteScanExec, +}; use datafusion_physical_plan::memory::LazyMemoryExec; use datafusion_physical_plan::placeholder_row::PlaceholderRowExec; use datafusion_physical_plan::projection::ProjectionExec; @@ -1035,11 +1039,19 @@ mod tests { /// This bundles the stable per-call inputs for deserialization and the /// per-scope `ScalarSubqueryResults` handle needed while reconstructing /// `ScalarSubqueryExpr` nodes inside a `ScalarSubqueryExec` input plan. +/// +/// It also holds the buffers that bind each decoded `MaterializedCteScanExec` +/// to the decoded `MaterializedCteExec` with the same id. Create one root +/// context for one plan and pass it (or a context derived from it) to every +/// nested decode call. A scan that is decoded with a different root context +/// than its `MaterializedCteExec` is not bound to it, and fails when it is +/// executed. #[derive(Clone)] pub struct PhysicalPlanDecodeContext<'a> { task_ctx: &'a TaskContext, codec: &'a dyn PhysicalExtensionCodec, scalar_subquery_results: Option, + materialized_cte_buffers: Arc, } impl<'a> PhysicalPlanDecodeContext<'a> { @@ -1049,6 +1061,7 @@ impl<'a> PhysicalPlanDecodeContext<'a> { task_ctx, codec, scalar_subquery_results: None, + materialized_cte_buffers: Arc::default(), } } @@ -1078,6 +1091,7 @@ impl<'a> PhysicalPlanDecodeContext<'a> { task_ctx: self.task_ctx, codec: self.codec, scalar_subquery_results: Some(scalar_subquery_results), + materialized_cte_buffers: Arc::clone(&self.materialized_cte_buffers), } } } @@ -1318,10 +1332,12 @@ pub trait PhysicalPlanNodeExt: Sized { PhysicalPlanType::PiecewiseMergeJoin(_) => { PiecewiseMergeJoinExec::try_from_proto(self.node(), &decode_ctx) } - PhysicalPlanType::MaterializedCte(_) - | PhysicalPlanType::MaterializedCteScan(_) => not_impl_err!( - "PhysicalPlan serde is not yet implemented for MATERIALIZED CTEs" - ), + PhysicalPlanType::MaterializedCte(_) => { + MaterializedCteExec::try_from_proto(self.node(), &decode_ctx) + } + PhysicalPlanType::MaterializedCteScan(_) => { + MaterializedCteScanExec::try_from_proto(self.node(), &decode_ctx) + } } } @@ -2118,6 +2134,16 @@ impl ExecutionPlanDecode for ConverterPlanDecoder<'_, '_> { .or_else(|_| self.ctx.codec().try_decode_udwf(name, &[])), } } + + // The buffers live in the root decode context, so a scan and its + // `MaterializedCteExec` get the same buffer wherever they are in the plan. + fn materialized_cte_buffer( + &self, + encoded_id: u64, + name: &str, + ) -> Result> { + Ok(self.ctx.materialized_cte_buffers.buffer(encoded_id, name)) + } } /// Borrow a required message field, or fail with a protobuf error naming it. diff --git a/datafusion/proto/tests/cases/plans/materialized_cte.rs b/datafusion/proto/tests/cases/plans/materialized_cte.rs new file mode 100644 index 0000000000000..a13f611c49695 --- /dev/null +++ b/datafusion/proto/tests/cases/plans/materialized_cte.rs @@ -0,0 +1,208 @@ +// 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 + +//! `MaterializedCteExec` and the `MaterializedCteScanExec`s that share its +//! buffer. + +use datafusion::arrow::array::Int64Array; +use datafusion::arrow::datatypes::{DataType, Field, Schema}; +use datafusion::physical_plan::materialized_cte::{ + MaterializedCteExec, MaterializedCteScanExec, +}; +use datafusion::physical_plan::{ + ExecutionPlan, ExecutionPlanProperties, collect, displayable, +}; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_common::Result; +use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; +use datafusion_proto::bytes::{physical_plan_from_bytes, physical_plan_to_bytes}; +use datafusion_proto::physical_plan::{ + DefaultPhysicalExtensionCodec, DefaultPhysicalProtoConverter, + PhysicalPlanDecodeContext, PhysicalProtoConverterExtension, +}; +use datafusion_proto::protobuf::PhysicalPlanNode; +use prost::Message; +use std::sync::Arc; + +/// The body returns 100 random values, so a query that compares the rows of +/// two scans returns 100 only if the body runs one time. +const BODY: &str = "SELECT value + random() AS r FROM generate_series(1, 100)"; + +fn context() -> SessionContext { + // sqlparser only parses `MATERIALIZED` for the PostgreSQL dialect. + SessionContext::new_with_config( + SessionConfig::new() + .with_target_partitions(4) + .set_str("datafusion.sql_parser.dialect", "PostgreSQL"), + ) +} + +/// The ids of the `MaterializedCteExec`s and of the scans in `plan`. +fn cte_ids(plan: &Arc) -> Result<(Vec, Vec)> { + let mut cte_ids = vec![]; + let mut scan_ids = vec![]; + plan.apply(|node| { + if let Some(cte) = node.downcast_ref::() { + cte_ids.push(cte.buffer().id()); + } else if let Some(scan) = node.downcast_ref::() { + assert!(scan.is_bound()); + scan_ids.push(scan.id()); + } + Ok(TreeNodeRecursion::Continue) + })?; + Ok((cte_ids, scan_ids)) +} + +fn buffered_rows(plan: &Arc) -> Result> { + let mut rows = vec![]; + plan.apply(|node| { + if node.is::() { + let metrics = node.metrics().unwrap(); + let buffered = metrics.sum_by_name("buffered_rows").unwrap(); + rows.push(buffered.as_usize()); + } + Ok(TreeNodeRecursion::Continue) + })?; + Ok(rows) +} + +/// Plan `sql`, which has one materialized CTE and returns one count. Then do +/// a serde round trip, run the decoded plan and return it with the count. +async fn roundtrip_and_count(sql: &str) -> Result<(Arc, i64)> { + let ctx = context(); + let plan = ctx.sql(sql).await?.create_physical_plan().await?; + let bytes = physical_plan_to_bytes(Arc::clone(&plan))?; + + // Decode in a new session, as another process does. + let ctx = context(); + let decoded = physical_plan_from_bytes(&bytes, ctx.task_ctx().as_ref())?; + assert_eq!( + displayable(plan.as_ref()).indent(true).to_string(), + displayable(decoded.as_ref()).indent(true).to_string() + ); + + // The decoded plan has new ids, and all its scans read the decoded CTE. + let (cte_ids, scan_ids) = cte_ids(&decoded)?; + assert_eq!(cte_ids.len(), 1); + assert_ne!(cte_ids, self::cte_ids(&plan)?.0); + assert!(scan_ids.iter().all(|id| *id == cte_ids[0]), "{scan_ids:?}"); + // A second decode of the same bytes gives a separate CTE. + let again = physical_plan_from_bytes(&bytes, ctx.task_ctx().as_ref())?; + assert_ne!(cte_ids, self::cte_ids(&again)?.0); + + let batches = collect(Arc::clone(&decoded), ctx.task_ctx()).await?; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 1); + let batch = batches.iter().find(|b| b.num_rows() == 1).unwrap(); + let count = batch.column(0).as_any().downcast_ref::(); + let count = count.unwrap().value(0); + // The body ran one time. + assert_eq!(buffered_rows(&decoded)?, vec![100]); + Ok((decoded, count)) +} + +#[tokio::test] +async fn roundtrip_materialized_cte_with_two_scans() -> Result<()> { + let sql = format!( + "WITH c AS MATERIALIZED ({BODY}) \ + SELECT count(*) FROM c AS a JOIN c AS b ON a.r = b.r" + ); + let (decoded, count) = roundtrip_and_count(&sql).await?; + assert_eq!(cte_ids(&decoded)?.1.len(), 2); + assert_eq!(count, 100); + Ok(()) +} + +/// The projections of the scans in `plan`. +fn scan_projections(plan: &Arc) -> Result>>> { + let mut projections = vec![]; + plan.apply(|node| { + if let Some(scan) = node.downcast_ref::() { + projections.push(scan.projection().map(<[usize]>::to_vec)); + } + Ok(TreeNodeRecursion::Continue) + })?; + Ok(projections) +} + +/// Each scan reads a different subset of the columns of the body. +#[tokio::test] +async fn roundtrip_materialized_cte_scans_with_projections() -> Result<()> { + let sql = "WITH c AS MATERIALIZED (\ + SELECT value AS v, value + random() AS r, value * 2 AS d \ + FROM generate_series(1, 100)) \ + SELECT count(*) FROM c AS a JOIN c AS b ON a.v = b.v \ + WHERE a.r > 0 AND b.d > 0"; + let ctx = context(); + let plan = ctx.sql(sql).await?.create_physical_plan().await?; + let (decoded, count) = roundtrip_and_count(sql).await?; + let projections = scan_projections(&decoded)?; + assert_eq!(projections, scan_projections(&plan)?); + assert!(projections.iter().all(Option::is_some), "{projections:?}"); + assert_ne!(projections[0], projections[1]); + assert_eq!(count, 100); + Ok(()) +} + +/// The scan in the scalar subquery is not below the `MaterializedCteExec`. +#[tokio::test] +async fn roundtrip_materialized_cte_scan_in_scalar_subquery() -> Result<()> { + let sql = format!( + "WITH c AS MATERIALIZED ({BODY}) \ + SELECT count(*) FROM c WHERE r <= (SELECT max(r) FROM c)" + ); + let (decoded, count) = roundtrip_and_count(&sql).await?; + let plan = displayable(decoded.as_ref()).indent(true).to_string(); + assert!(plan.starts_with("ScalarSubqueryExec"), "{plan}"); + assert_eq!(cte_ids(&decoded)?.1.len(), 2); + assert_eq!(count, 100); + Ok(()) +} + +/// A plan fragment that has a scan but not its `MaterializedCteExec` can be +/// decoded. It fails when the scan is executed. +#[tokio::test] +async fn materialized_cte_scan_without_its_cte_fails_at_execution() -> Result<()> { + let schema = Arc::new(Schema::new(vec![Field::new("r", DataType::Float64, true)])); + let scan = Arc::new(MaterializedCteScanExec::new(7, "c", schema, 2)); + let bytes = physical_plan_to_bytes(scan)?; + + let ctx = SessionContext::new(); + let decoded = physical_plan_from_bytes(&bytes, ctx.task_ctx().as_ref())?; + assert_eq!(decoded.output_partitioning().partition_count(), 2); + let err = decoded.execute(0, ctx.task_ctx()).err().unwrap(); + assert_eq!( + err.strip_backtrace(), + "Execution error: The materialized CTE c has a MaterializedCteScanExec but no MaterializedCteExec in this plan. The body and the scans of a materialized CTE must be in one plan and run in one process" + ); + Ok(()) +} + +/// The second decode with one decode context finds the body of the first +/// decode in the buffer of the same encoded id. +#[tokio::test] +async fn one_decode_context_rejects_a_second_materialized_cte_with_the_same_id() +-> Result<()> { + let ctx = context(); + let sql = format!("WITH c AS MATERIALIZED ({BODY}) SELECT count(*) FROM c"); + let plan = ctx.sql(&sql).await?.create_physical_plan().await?; + let id = cte_ids(&plan)?.0[0]; + let bytes = physical_plan_to_bytes(plan)?; + let node = PhysicalPlanNode::decode(bytes.as_ref()).unwrap(); + let codec = DefaultPhysicalExtensionCodec {}; + + let task_ctx = ctx.task_ctx(); + let decode_ctx = PhysicalPlanDecodeContext::new(task_ctx.as_ref(), &codec); + let converter = DefaultPhysicalProtoConverter {}; + converter.proto_to_execution_plan(&node, &decode_ctx)?; + let err = converter + .proto_to_execution_plan(&node, &decode_ctx) + .unwrap_err(); + assert_eq!( + err.strip_backtrace(), + format!( + "Error during planning: Two MaterializedCteExec nodes have the id {id} in one decode context. An encoded plan must have one MaterializedCteExec for each id, and each plan must be decoded with a new decode context" + ) + ); + Ok(()) +} diff --git a/datafusion/proto/tests/cases/plans/mod.rs b/datafusion/proto/tests/cases/plans/mod.rs index 71887fb955420..4e84e75aaae11 100644 --- a/datafusion/proto/tests/cases/plans/mod.rs +++ b/datafusion/proto/tests/cases/plans/mod.rs @@ -34,6 +34,7 @@ mod joins; mod lazy_memory; mod leaves; mod limits; +mod materialized_cte; mod misc; mod scalar_subquery; mod sinks; From a8afd63248d4ea9fe53579aefcc35ca238568875 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:05:32 -0500 Subject: [PATCH 3/3] feat: protobuf serialization for the materialized CTE logical plan nodes Encode and decode LogicalPlan::MaterializedCte and LogicalPlan::MaterializedCteScan, replacing the not-implemented errors. The ids of the encoded plan are kept on decode (via the new MaterializedCteId::from_u64), so the scans in the continuation, which are decoded before their CTE node, stay bound to it. Reusing ids from another process is safe in a logical plan: a scan reads the nearest MaterializedCte above it that has its id, and the physical planner gives every CTE a new id. The decoder needs to build the nodes from their parts, so MaterializedCte::try_new is public again and MaterializedCteScan gets a public try_from_parts. Both document MaterializedCteBuilder as the way to plan a new CTE. MaterializedCte::try_new checks the scan schemas and projections against the body. The scan encoding carries the projection that the optimizer sets when it prunes the body. Round-trip tests cover the plan before and after the optimizer, check that the decoded plan is equal to the original, and that it returns the same rows. Together with the previous commits, this adds protobuf encodings for LogicalPlan::MaterializedCte, LogicalPlan::MaterializedCteScan, MaterializedCteExec and MaterializedCteScanExec. A decoded physical plan fragment that has a scan without its MaterializedCteExec fails with a clear error when the scan is executed. Closes #26231. The scan encoding also carries the functional dependencies of the scan schema. Without them, a decoded scan of a body such as 'SELECT v, count(*) AS n ... GROUP BY v' has no dependency v -> n, and the decoded plan is not equal to the original. A test covers it. Co-Authored-By: Claude Opus 5.5 --- .../expr/src/logical_plan/materialized_cte.rs | 160 ++++++++++++++++ datafusion/proto/src/logical_plan/mod.rs | 172 ++++++++++++++++-- .../tests/cases/roundtrip_logical_plan.rs | 151 +++++++++++++++ .../library-user-guide/upgrading/index.md | 5 + 4 files changed, 477 insertions(+), 11 deletions(-) diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 0967137147a0b..1b921c02acaa8 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -43,6 +43,7 @@ use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use datafusion_common::tree_node::{Transformed, TreeNodeRecursion}; use datafusion_common::{ Column, DFSchema, DFSchemaRef, Result, internal_datafusion_err, internal_err, + plan_err, }; use crate::{Expr, LogicalPlan, Projection}; @@ -65,8 +66,26 @@ impl MaterializedCteId { pub fn as_u64(self) -> u64 { self.0 } + + /// The id that a scan decoded by [`MaterializedCteScan::try_from_encoded`] + /// carries until [`MaterializedCte::try_from_encoded`] gives it a new id. + /// + /// [`Self::next`] counts up from 0 and does not reach the range of + /// these ids, which have the bit 63 set. + fn encoded(encoded_id: u64) -> Result { + if encoded_id & DECODED_ID_TAG != 0 { + return plan_err!( + "The id {encoded_id} of an encoded materialized CTE is too large" + ); + } + Ok(Self(encoded_id | DECODED_ID_TAG)) + } } +/// The bit that marks the id of a scan that is decoded but not yet bound to +/// its decoded [`MaterializedCte`]. +const DECODED_ID_TAG: u64 = 1 << 63; + impl fmt::Display for MaterializedCteId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) @@ -200,6 +219,34 @@ impl MaterializedCte { }) } + /// Create a node from the parts of a serialized plan. This constructor + /// is for plan decoders only. To plan a new CTE, use + /// [`MaterializedCteBuilder`]. + /// + /// `encoded_id` is the id of this node in the serialized plan. The node + /// gets a new id, and the scans in `continuation` that + /// [`MaterializedCteScan::try_from_encoded`] decoded with `encoded_id` + /// get the same new id. A nested node with the same `encoded_id` is + /// decoded first and has already bound its own scans. + /// + /// Returns an error if `encoded_id` is out of range, or if a scan of + /// this CTE does not have the names and types of the columns of `body` + /// that it reads. + pub fn try_from_encoded( + encoded_id: u64, + name: impl Into, + body: Arc, + continuation: Arc, + ) -> Result { + let encoded = MaterializedCteId::encoded(encoded_id)?; + let id = MaterializedCteId::next(); + let continuation = Self::map_scans(encoded, continuation, |mut scan| { + scan.id = id; + Ok(Transformed::yes(scan)) + })?; + Self::try_new(id, name, body, continuation) + } + /// The id that binds the scans in the continuation to this node. pub fn id(&self) -> MaterializedCteId { self.id @@ -525,6 +572,45 @@ impl MaterializedCteScan { } } + /// Create a scan from the parts of a serialized plan. This constructor is + /// for plan decoders only. To plan a new scan, use + /// [`MaterializedCteBuilder::scan`]. + /// + /// `encoded_id` is the id of the CTE in the serialized plan. The scan is + /// not bound to a CTE of this process until + /// [`MaterializedCte::try_from_encoded`] decodes its CTE with the same + /// `encoded_id`. That call also checks the scan against the body. + /// + /// `schema` is the schema of this scan: the columns of the CTE body that + /// `projection` selects, or all of them if `projection` is `None`. + /// + /// Returns an error if `encoded_id` is out of range, or if `projection` + /// does not have one index for each column of `schema`. + pub fn try_from_encoded( + encoded_id: u64, + name: impl Into, + schema: DFSchemaRef, + projection: Option>, + ) -> Result { + let id = MaterializedCteId::encoded(encoded_id)?; + let name = name.into(); + if let Some(projection) = &projection + && projection.len() != schema.fields().len() + { + return plan_err!( + "The scan of the materialized CTE {name} has {} columns, but its projection has {} indexes", + schema.fields().len(), + projection.len() + ); + } + Ok(Self { + id, + name, + schema, + projection, + }) + } + /// The id of the [`MaterializedCte`] that this scan reads. pub fn id(&self) -> MaterializedCteId { self.id @@ -825,6 +911,80 @@ mod tests { assert_eq!(a.partial_cmp(&c), Some(Ordering::Less)); } + fn encoded_scan(encoded_id: u64) -> Result { + Ok(MaterializedCteScan::try_from_encoded( + encoded_id, + "c", + schema(DataType::Int32), + None, + )? + .into()) + } + + #[test] + fn try_from_encoded_binds_the_scans_to_a_new_id() -> Result<()> { + // An id that the planner of this process also uses. + let planned = MaterializedCteId::next(); + + // The inner node is decoded first and binds the scan. The outer node + // has the same encoded id, but it does not take the inner scan. + let inner = MaterializedCte::try_from_encoded( + planned.as_u64(), + "c", + body(DataType::Int32), + Arc::new(encoded_scan(planned.as_u64())?), + )?; + let inner_id = inner.id(); + assert_ne!(inner_id, planned); + assert_eq!( + inner.scans()?.iter().map(|s| s.id()).collect::>(), + vec![inner_id] + ); + let outer = MaterializedCte::try_from_encoded( + planned.as_u64(), + "c", + body(DataType::Int32), + Arc::new(inner.into()), + )?; + assert_ne!(outer.id(), inner_id); + assert_eq!(outer.scans()?, vec![]); + + // The decoder checks the schema of the scans. + let err = MaterializedCte::try_from_encoded( + 3, + "c", + body(DataType::Utf8), + Arc::new(encoded_scan(3)?), + ) + .unwrap_err(); + assert!( + err.to_string().contains( + "A scan of the materialized CTE c does not have the schema of the CTE" + ), + "{err}" + ); + Ok(()) + } + + #[test] + fn try_from_encoded_rejects_an_id_in_the_reserved_range() { + let err = encoded_scan(1 << 63).unwrap_err(); + assert!( + err.to_string().contains( + "The id 9223372036854775808 of an encoded materialized CTE is too large" + ), + "{err}" + ); + let err = MaterializedCte::try_from_encoded( + u64::MAX, + "c", + body(DataType::Int32), + Arc::new(scan(MaterializedCteId::next(), DataType::Int32)), + ) + .unwrap_err(); + assert!(err.to_string().contains("is too large"), "{err}"); + } + #[test] fn try_new_checks_the_schema_of_the_scans() -> Result<()> { let id = MaterializedCteId::next(); diff --git a/datafusion/proto/src/logical_plan/mod.rs b/datafusion/proto/src/logical_plan/mod.rs index 26b68d473c6d4..fce42a147a596 100644 --- a/datafusion/proto/src/logical_plan/mod.rs +++ b/datafusion/proto/src/logical_plan/mod.rs @@ -28,8 +28,9 @@ use datafusion_common::format::{ }; use datafusion_common::utils::{usize_from_wire, usize_to_wire}; use datafusion_common::{ - NullEquality, Result, TableReference, assert_or_internal_err, context, - internal_datafusion_err, internal_err, not_impl_err, plan_err, + DFSchema, Dependency, FunctionalDependence, FunctionalDependencies, NullEquality, + Result, TableReference, assert_or_internal_err, context, internal_datafusion_err, + internal_err, not_impl_err, plan_err, }; use datafusion_datasource::file_format::FileFormat; use datafusion_datasource::file_format::{ @@ -46,7 +47,8 @@ use datafusion_datasource_json::file_format::{ use datafusion_datasource_parquet::file_format::{ParquetFormat, ParquetFormatFactory}; use datafusion_expr::dml::InsertOp; use datafusion_expr::{ - AggregateUDF, DmlStatement, FetchType, HigherOrderUDF, Operator, RangePartitioning, + AggregateUDF, DmlStatement, FetchType, HigherOrderUDF, MaterializedCte, + MaterializedCtePlan, MaterializedCteScan, Operator, RangePartitioning, RecursiveQuery, SkipType, TableSource, Unnest, WriteOp, }; use datafusion_expr::{ @@ -465,6 +467,69 @@ fn explain_analyze_categories_to_proto( } } +fn functional_dependencies_to_proto( + dependencies: &FunctionalDependencies, +) -> Vec { + let indices = |indices: &[usize]| indices.iter().map(|i| *i as u64).collect(); + dependencies + .iter() + .map(|dependence| protobuf::FunctionalDependence { + source_indices: indices(&dependence.source_indices), + target_indices: indices(&dependence.target_indices), + nullable: dependence.nullable, + null_equality: protobuf::NullEquality::from(dependence.null_equality).into(), + mode: match dependence.mode { + Dependency::Single => protobuf::DependencyMode::Single, + Dependency::Multi => protobuf::DependencyMode::Multi, + } + .into(), + }) + .collect() +} + +fn functional_dependencies_from_proto( + dependencies: &[protobuf::FunctionalDependence], +) -> Result { + let indices = |indices: &[u64], field: &str| { + indices + .iter() + .map(|i| usize_from_wire(*i, "FunctionalDependence", field)) + .collect::>>() + }; + dependencies + .iter() + .map(|dependence| { + let null_equality = protobuf::NullEquality::try_from( + dependence.null_equality, + ) + .map_err(|_| { + proto_error(format!( + "Received a FunctionalDependence message with unknown NullEquality {}", + dependence.null_equality + )) + })?; + let mode = match protobuf::DependencyMode::try_from(dependence.mode) { + Ok(protobuf::DependencyMode::Single) => Dependency::Single, + Ok(protobuf::DependencyMode::Multi) => Dependency::Multi, + Err(_) => { + return Err(proto_error(format!( + "Received a FunctionalDependence message with unknown DependencyMode {}", + dependence.mode + ))); + } + }; + Ok(FunctionalDependence::new( + indices(&dependence.source_indices, "source_indices")?, + indices(&dependence.target_indices, "target_indices")?, + dependence.nullable, + ) + .with_null_equality(null_equality.into()) + .with_mode(mode)) + }) + .collect::>>() + .map(FunctionalDependencies::new) +} + impl AsLogicalPlan for LogicalPlanNode { fn try_decode(buf: &[u8]) -> Result where @@ -1342,11 +1407,64 @@ impl AsLogicalPlan for LogicalPlanNode { ) .map(LogicalPlan::RecursiveQuery) } - LogicalPlanType::MaterializedCte(_) - | LogicalPlanType::MaterializedCteScan(_) => { - not_impl_err!( - "LogicalPlan serde is not yet implemented for MATERIALIZED CTEs" + LogicalPlanType::MaterializedCte(cte_node) => { + let body = cte_node + .cte + .as_ref() + .ok_or_else(|| internal_datafusion_err!( + "Protobuf deserialization error, MaterializedCteNode was missing required field cte." + ))? + .try_into_logical_plan(ctx, extension_codec)?; + let continuation = cte_node + .continuation + .as_ref() + .ok_or_else(|| internal_datafusion_err!( + "Protobuf deserialization error, MaterializedCteNode was missing required field continuation." + ))? + .try_into_logical_plan(ctx, extension_codec)?; + + // The scans in the continuation are decoded before this node. + // `try_from_encoded` gives this node a new id, binds those + // scans to it, and checks their schemas. + MaterializedCte::try_from_encoded( + cte_node.id, + cte_node.name.clone(), + Arc::new(body), + Arc::new(continuation), ) + .map(|cte| LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte))) + } + LogicalPlanType::MaterializedCteScan(scan) => { + let schema: DFSchema = convert_required!(scan.schema)?; + // `with_functional_dependencies` checks the indexes. + let schema = schema.with_functional_dependencies( + functional_dependencies_from_proto(&scan.functional_dependencies)?, + )?; + let projection = scan + .projection + .as_ref() + .map(|projection| { + projection + .indices + .iter() + .map(|i| { + usize_from_wire( + *i, + "MaterializedCteScanNode", + "projection", + ) + }) + .collect::>>() + }) + .transpose()?; + Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( + MaterializedCteScan::try_from_encoded( + scan.id, + scan.name.clone(), + Arc::new(schema), + projection, + )?, + ))) } LogicalPlanType::CteWorkTableScan(cte_work_table_scan_node) => { let CteWorkTableScanNode { name, schema } = cte_work_table_scan_node; @@ -2404,11 +2522,43 @@ impl AsLogicalPlan for LogicalPlanNode { LogicalPlan::Show(_) => Err(proto_error( "LogicalPlan serde is not yet implemented for Show", )), - LogicalPlan::MaterializedCte(_) => { - not_impl_err!( - "LogicalPlan serde is not yet implemented for MATERIALIZED CTEs" - ) + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { + let body = LogicalPlanNode::try_from_logical_plan( + cte.body().as_ref(), + extension_codec, + )?; + let continuation = LogicalPlanNode::try_from_logical_plan( + cte.continuation().as_ref(), + extension_codec, + )?; + Ok(LogicalPlanNode { + logical_plan_type: Some(LogicalPlanType::MaterializedCte(Box::new( + protobuf::MaterializedCteNode { + id: cte.id().as_u64(), + name: cte.name().to_string(), + cte: Some(Box::new(body)), + continuation: Some(Box::new(continuation)), + }, + ))), + }) } + LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) => Ok(LogicalPlanNode { + logical_plan_type: Some(LogicalPlanType::MaterializedCteScan( + protobuf::MaterializedCteScanNode { + id: scan.id().as_u64(), + name: scan.name().to_string(), + schema: Some(scan.schema().try_into()?), + projection: scan.projection().map(|indices| { + protobuf::MaterializedCteScanProjection { + indices: indices.iter().map(|i| *i as u64).collect(), + } + }), + functional_dependencies: functional_dependencies_to_proto( + scan.schema().functional_dependencies(), + ), + }, + )), + }), LogicalPlan::RecursiveQuery(recursive) => { let static_term = LogicalPlanNode::try_from_logical_plan( recursive.static_term.as_ref(), diff --git a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs index a94f277a4a506..86a78ac269cac 100644 --- a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs +++ b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs @@ -23,6 +23,7 @@ use datafusion_common::parquet_config::{ DFParquetWriterVersion, RowGroupRangeAssignment, }; use datafusion_common::parsers::CompressionTypeVariant; +use datafusion_expr::logical_plan::MaterializedCtePlan; use datafusion_functions_aggregate::sum::sum_distinct; use prost::Message; use std::any::Any; @@ -3666,6 +3667,156 @@ async fn roundtrip_recursive_query() { ); } +/// Replace each `MaterializedCteId(n)` in `debug` with the index of the first +/// occurrence of `n`. +fn normalize_materialized_cte_ids(debug: &str) -> String { + const PREFIX: &str = "MaterializedCteId("; + let mut ids: Vec<&str> = vec![]; + let mut output = String::new(); + let mut rest = debug; + while let Some(start) = rest.find(PREFIX) { + let (before, after) = rest.split_at(start + PREFIX.len()); + let end = after.find(')').expect("the id is closed"); + let id = &after[..end]; + let index = ids.iter().position(|seen| *seen == id).unwrap_or_else(|| { + ids.push(id); + ids.len() - 1 + }); + output.push_str(before); + output.push_str(&index.to_string()); + rest = &after[end..]; + } + output.push_str(rest); + output +} + +/// Round trip the plan of `sql`, which uses a materialized CTE, before and +/// after the optimizer. The decoded plans must return the rows of `sql`. +async fn roundtrip_materialized_cte(sql: &str, scans: usize) -> Result<()> { + // sqlparser only parses `MATERIALIZED` for the PostgreSQL dialect. + let config = + SessionConfig::new().set_str("datafusion.sql_parser.dialect", "PostgreSQL"); + let ctx = SessionContext::new_with_config(config.clone()); + let dataframe = ctx.sql(sql).await?; + let plans = [ + dataframe.logical_plan().clone(), + dataframe.clone().into_optimized_plan()?, + ]; + let output = dataframe.collect().await?; + + for plan in plans { + let bytes = logical_plan_to_bytes(&plan)?; + let ctx = SessionContext::new_with_config(config.clone()); + let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + // The decoder gives each CTE a new id, so the plans are compared with + // the ids numbered in the order of their first occurrence. The scans + // must still have the id of their CTE. + assert_ne!(format!("{plan:?}"), format!("{logical_round_trip:?}")); + assert_eq!( + normalize_materialized_cte_ids(&format!("{plan:?}")), + normalize_materialized_cte_ids(&format!("{logical_round_trip:?}")) + ); + + let mut cte_scans = vec![]; + logical_round_trip.apply_with_subqueries(|node| { + if let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node { + cte_scans.push(cte.scans()?.len()); + } + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + })?; + assert_eq!(cte_scans, vec![scans]); + + let dataframe = ctx.execute_logical_plan(logical_round_trip).await?; + let output_round_trip = dataframe.collect().await?; + assert_eq!( + format!("{}", pretty_format_batches(&output)?), + format!("{}", pretty_format_batches(&output_round_trip)?) + ); + } + Ok(()) +} + +#[tokio::test] +async fn roundtrip_materialized_cte_with_two_scans() -> Result<()> { + roundtrip_materialized_cte( + "WITH c AS MATERIALIZED (SELECT * FROM (VALUES (1), (2), (3), (4), (5)) AS t(v)) + SELECT a.v, b.v FROM c AS a JOIN c AS b ON a.v + 1 = b.v ORDER BY a.v", + 2, + ) + .await +} + +/// After the optimizer, each scan reads a different subset of the columns of +/// the body. +#[tokio::test] +async fn roundtrip_materialized_cte_scans_with_projections() -> Result<()> { + let sql = "WITH c AS MATERIALIZED (SELECT * FROM (VALUES (1, 10, 100), (2, 20, 200)) AS t(v, w, x)) + SELECT a.w, b.x FROM c AS a JOIN c AS b ON a.v = b.v ORDER BY a.w"; + let config = + SessionConfig::new().set_str("datafusion.sql_parser.dialect", "PostgreSQL"); + let ctx = SessionContext::new_with_config(config); + let plan = ctx.sql(sql).await?.into_optimized_plan()?; + let mut projections = vec![]; + plan.apply_with_subqueries(|node| { + if let LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) = node { + projections.push(scan.projection().map(<[usize]>::to_vec)); + } + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + })?; + // The round trip below checks that the decoded plan is equal to `plan` + // except for the ids, so it covers these projections. + assert_eq!(projections.len(), 2); + assert!(projections.iter().all(Option::is_some), "{projections:?}"); + assert_ne!(projections[0], projections[1]); + + roundtrip_materialized_cte(sql, 2).await +} + +#[tokio::test] +async fn roundtrip_materialized_cte_scan_in_scalar_subquery() -> Result<()> { + roundtrip_materialized_cte( + "WITH c AS MATERIALIZED (SELECT * FROM (VALUES (1), (2), (3), (4), (5)) AS t(v)) + SELECT v FROM c WHERE v < (SELECT max(v) FROM c) ORDER BY v", + 2, + ) + .await +} + +/// The body groups by `v`, so the schema of each scan has the functional +/// dependency `v -> n`. The round trip must keep it: the decoder cannot +/// compute it again, because a scan is a leaf. +#[tokio::test] +async fn roundtrip_materialized_cte_scan_with_functional_dependencies() -> Result<()> { + let sql = "WITH c AS MATERIALIZED ( + SELECT v, count(*) AS n FROM (VALUES (1), (2), (2)) AS t(v) GROUP BY v) + SELECT v, n FROM c GROUP BY v ORDER BY v"; + let config = + SessionConfig::new().set_str("datafusion.sql_parser.dialect", "PostgreSQL"); + let ctx = SessionContext::new_with_config(config); + use datafusion_common::{Dependency, FunctionalDependence, NullEquality}; + + let plan = ctx.sql(sql).await?.into_unoptimized_plan(); + let bytes = logical_plan_to_bytes(&plan)?; + let decoded = logical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + let mut dependencies = vec![]; + decoded.apply_with_subqueries(|node| { + if let LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) = node { + dependencies.extend(scan.schema().functional_dependencies().iter().cloned()); + } + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + })?; + assert_eq!( + dependencies, + vec![ + FunctionalDependence::new(vec![0], vec![0, 1], false) + .with_null_equality(NullEquality::NullEqualsNull) + .with_mode(Dependency::Single) + ] + ); + + roundtrip_materialized_cte(sql, 1).await +} + #[tokio::test] async fn roundtrip_union_query() -> Result<()> { let query = "SELECT a FROM t1 diff --git a/docs/source/library-user-guide/upgrading/index.md b/docs/source/library-user-guide/upgrading/index.md index d2372d78e87a2..bf50b93cfb5d9 100644 --- a/docs/source/library-user-guide/upgrading/index.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -271,6 +271,11 @@ The fields of `MaterializedCte` and `MaterializedCteScan`, which were public in `MaterializedCte::scans` and `MaterializedCteScan::find_in` do not change. +A plan decoder uses `MaterializedCteScan::try_from_encoded` and +`MaterializedCte::try_from_encoded`. They take the id of the serialized plan, +give each CTE a new id, and bind its scans to it. A decoded plan therefore +has different ids than the plan that was encoded. + Build a node with `MaterializedCteBuilder`, which allocates the id that binds the scans to the node: