diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs index a861a538d6b13..0fa6ea0195f87 100644 --- a/datafusion/core/src/physical_planner.rs +++ b/datafusion/core/src/physical_planner.rs @@ -274,15 +274,15 @@ fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result> let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node else { return Ok(Transformed::no(node)); }; - let old_id = cte.id; let new_id = MaterializedCteId::next(); - let continuation = Arc::unwrap_or_clone(cte.continuation) + let (old_id, name, body, continuation) = cte.into_parts(); + let continuation = Arc::unwrap_or_clone(continuation) .transform_down_with_subqueries(|node| match node { // A nested occurrence of the same CTE owns the scans below // it, and is renumbered on its own. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( ref nested, - )) if nested.id == old_id => { + )) if nested.id() == old_id => { Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) } LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(mut scan)) @@ -297,11 +297,12 @@ fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result> })? .data; Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Cte(MaterializedCte { - id: new_id, - continuation: Arc::new(continuation), - ..cte - }), + MaterializedCtePlan::Cte(MaterializedCte::try_new( + new_id, + name, + body, + Arc::new(continuation), + )?), ))) }) .map(|t| Some(t.data)) @@ -2044,11 +2045,11 @@ impl DefaultPhysicalPlanner { if body.boundedness().is_unbounded() { return plan_err!( "MATERIALIZED CTE {} reads an unbounded source, which cannot be materialized", - cte.name + cte.name() ); } let buffer = - Arc::new(MaterializedCteBuffer::new(cte.id.as_u64(), &cte.name)); + Arc::new(MaterializedCteBuffer::new(cte.id().as_u64(), cte.name())); Arc::new(MaterializedCteExec::new(body, continuation, buffer)) } diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 4df766bae5eb8..199651d0c50b9 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -82,13 +82,13 @@ pub enum MaterializedCtePlan { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct MaterializedCte { /// Binds the scans in `continuation` to this node - pub id: MaterializedCteId, + pub(crate) id: MaterializedCteId, /// Name of the CTE, used for display and error messages only - pub name: String, + pub(crate) name: String, /// The body of the CTE - pub cte: Arc, + pub(crate) cte: Arc, /// The query that declared the CTE and reads it - pub continuation: Arc, + pub(crate) continuation: Arc, } impl MaterializedCte { @@ -151,19 +151,46 @@ impl MaterializedCte { MaterializedCteScan::find_in(&self.continuation, self.id) } - /// Return a node with the same id and name, and new inputs. The schemas - /// of the scans are not checked again. + /// Call `f` with the body and the continuation, in this order, so that a + /// rule can change them in place. Return the result of `f`. + /// + /// The schemas of the scans are not checked again. The signature lets a + /// later version validate the new inputs and return an error. + pub fn try_map_inputs_mut( + &mut self, + f: impl FnOnce(&mut Arc, &mut Arc) -> Result, + ) -> Result { + f(&mut self.cte, &mut self.continuation) + } + + /// The id, the name, the body and the continuation, in this order. Build + /// a node again with [`Self::try_new`]. + pub fn into_parts( + self, + ) -> ( + MaterializedCteId, + String, + Arc, + Arc, + ) { + (self.id, self.name, self.cte, self.continuation) + } + + /// Return a new node with the same id and name, and new inputs. + /// + /// The schemas of the scans are not checked again. The signature lets a + /// later version validate the new inputs and return an error. pub fn with_new_inputs( &self, cte: Arc, continuation: Arc, - ) -> Self { - Self { + ) -> Result { + Ok(Self { id: self.id, name: self.name.clone(), cte, continuation, - } + }) } } @@ -746,7 +773,7 @@ mod tests { // `with_new_inputs` does not check the scans, so a rule can build // this plan. The invariant check rejects it. let invalid = cte - .with_new_inputs(body(DataType::Int32), Arc::new(scan(id, DataType::Utf8))); + .with_new_inputs(body(DataType::Int32), Arc::new(scan(id, DataType::Utf8)))?; let invalid = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(invalid)); let err = invalid .check_invariants(InvariantLevel::Executable) diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index d2467e2346c44..956d31d0ed8d6 100644 --- a/datafusion/expr/src/logical_plan/plan.rs +++ b/datafusion/expr/src/logical_plan/plan.rs @@ -530,11 +530,9 @@ impl LogicalPlan { LogicalPlan::Subquery(Subquery { subquery, .. }) => vec![subquery], LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => vec![input], LogicalPlan::Extension(extension) => extension.node.inputs(), - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte { - cte, - continuation, - .. - })) => vec![cte, continuation], + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { + vec![cte.body(), cte.continuation()] + } LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => vec![], LogicalPlan::Union(Union { inputs, .. }) => { inputs.iter().map(|arc| arc.as_ref()).collect() @@ -673,7 +671,7 @@ impl LogicalPlan { } // A materialized CTE outputs the output of its continuation. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { - cte.continuation.head_output_expr() + cte.continuation().head_output_expr() } LogicalPlan::Extension(_) | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => Ok(None), @@ -1234,7 +1232,7 @@ impl LogicalPlan { self.assert_no_expressions(expr)?; let (body, continuation) = self.only_two_inputs(inputs)?; Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - cte.with_new_inputs(Arc::new(body), Arc::new(continuation)), + cte.with_new_inputs(Arc::new(body), Arc::new(continuation))?, ))) } LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => { diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index 42e74b0d70437..4f8843dbc83cb 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -128,21 +128,23 @@ fn coerce_plan_and_subqueries( // of a `NULL` column of a `UNION`. Coerce the body first, and give // its new schema to the scans before the continuation is coerced. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { + let (id, name, body, continuation) = cte.into_parts(); let body = - coerce_plan_and_subqueries(Arc::unwrap_or_clone(cte.cte), config)?; + coerce_plan_and_subqueries(Arc::unwrap_or_clone(body), config)?; let continuation = with_materialized_cte_scan_schema( - Arc::unwrap_or_clone(cte.continuation), - cte.id, + Arc::unwrap_or_clone(continuation), + id, body.schema(), )?; let continuation = coerce_plan_and_subqueries(continuation, config)?; Ok(Transformed::new( LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte { - cte: Arc::new(body), - continuation: Arc::new(continuation), - ..cte - }, + MaterializedCte::try_new( + id, + name, + Arc::new(body), + Arc::new(continuation), + )?, )), true, TreeNodeRecursion::Jump, @@ -173,7 +175,7 @@ fn with_materialized_cte_scan_schema( .transform_down_with_subqueries(|node| match node { // A nested occurrence of the same CTE owns the scans below it. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref nested)) - if nested.id == id => + if nested.id() == id => { Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) } diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rs index 3e6f141af5d9c..25918d6f48071 100644 --- a/datafusion/optimizer/src/decorrelate.rs +++ b/datafusion/optimizer/src/decorrelate.rs @@ -215,7 +215,7 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr { Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump)) } LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref cte)) - if !cte.cte.all_out_ref_exprs().is_empty() => + if !cte.body().all_out_ref_exprs().is_empty() => { // A correlated body would have to run once per outer row. Ok(self.stop_pull_up(plan)) @@ -223,14 +223,16 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { // Only the continuation can hold correlated expressions. Rewrite // it alone, so that the body shared by every scan keeps its schema. - let continuation = - Arc::unwrap_or_clone(cte.continuation).rewrite(self)?; + let (id, name, body, continuation) = cte.into_parts(); + let continuation = Arc::unwrap_or_clone(continuation).rewrite(self)?; Ok(Transformed::new( LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte { - continuation: Arc::new(continuation.data), - ..cte - }, + MaterializedCte::try_new( + id, + name, + body, + Arc::new(continuation.data), + )?, )), continuation.transformed, TreeNodeRecursion::Jump, diff --git a/datafusion/optimizer/src/optimize_projections/mod.rs b/datafusion/optimizer/src/optimize_projections/mod.rs index f8b997f82b964..6d1f550b77416 100644 --- a/datafusion/optimizer/src/optimize_projections/mod.rs +++ b/datafusion/optimizer/src/optimize_projections/mod.rs @@ -528,12 +528,7 @@ fn optimize_materialized_cte( config: &dyn OptimizerConfig, indices: RequiredIndices, ) -> Result> { - let MaterializedCte { - id, - name, - cte: body, - continuation, - } = cte; + let (id, name, body, continuation) = cte.into_parts(); // The output is the output of the continuation, so the continuation // needs what the parent needs. let continuation = @@ -578,7 +573,7 @@ fn optimize_materialized_cte( // A nested occurrence of the same CTE has its own body and // owns the scans below it. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref nested)) - if nested.id == id => + if nested.id() == id => { Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) } diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rs index fdf5e5bbb1bf8..7e738809fac98 100644 --- a/datafusion/optimizer/src/optimizer.rs +++ b/datafusion/optimizer/src/optimizer.rs @@ -24,8 +24,8 @@ use datafusion_expr::logical_plan::LogicalPlan; use datafusion_expr::{ Aggregate, Analyze, CreateMemoryTable, CreateView, DdlStatement, Distinct, DistinctOn, DmlStatement, Explain, Expr, Extension, Filter, Join, Limit, - MaterializedCte, MaterializedCtePlan, Projection, RecursiveQuery, Repartition, Sort, - Statement, Subquery, SubqueryAlias, Union, Unnest, Window, + MaterializedCtePlan, Projection, RecursiveQuery, Repartition, Sort, Statement, + Subquery, SubqueryAlias, Union, Unnest, Window, }; use crate::common_subexpr_eliminate::CommonSubexprEliminate; @@ -467,15 +467,12 @@ fn map_children_mut Result>( let r = f(Arc::make_mut(recursive_term))?; s || r } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte { - cte, - continuation, - .. - })) => { - let b = f(Arc::make_mut(cte))?; - let c = f(Arc::make_mut(continuation))?; - b || c - } + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => cte + .try_map_inputs_mut(|cte, continuation| { + let b = f(Arc::make_mut(cte))?; + let c = f(Arc::make_mut(continuation))?; + Ok(b || c) + })?, LogicalPlan::Statement(Statement::Prepare(p)) => f(Arc::make_mut(&mut p.input))?, LogicalPlan::Extension(Extension { node }) => { let inputs = node.inputs(); diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index efaea281a14e2..8b006ffb29f7c 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -1403,10 +1403,13 @@ impl OptimizerRule for PushDownFilter { // The output is the output of the continuation, so the filter // moves onto the continuation. The body is shared by every scan // of the CTE and is never filtered for one of them. - cte.continuation = Arc::new(LogicalPlan::Filter(Filter::new( - filter.predicate, - cte.continuation, - ))); + cte.try_map_inputs_mut(|_, continuation| { + *continuation = Arc::new(LogicalPlan::Filter(Filter::new( + filter.predicate, + Arc::clone(continuation), + ))); + Ok(()) + })?; Ok(Transformed::yes(LogicalPlan::MaterializedCte( MaterializedCtePlan::Cte(cte), ))) diff --git a/docs/source/library-user-guide/upgrading/57.0.0.md b/docs/source/library-user-guide/upgrading/57.0.0.md index 438b0ed3b1a76..73707c3d7e2d9 100644 --- a/docs/source/library-user-guide/upgrading/57.0.0.md +++ b/docs/source/library-user-guide/upgrading/57.0.0.md @@ -168,3 +168,20 @@ schema. has the names and types of the columns that it reads from the body. The optimizer runs this check after each rule in debug builds, so a custom rule that does not remap the scans now fails with an error that names the rule. + +The fields of `MaterializedCte` are private. Read them with +`MaterializedCte::id`, `name`, `body` and `continuation`. Build a node with +`MaterializedCte::try_new`, which checks the scans of the CTE. +`MaterializedCte::into_parts` takes the id, name, body and continuation by +value, so that a rule can rebuild the node with `try_new`. + +Two other APIs do not check the scans: + +| API | What it does | +| ------------------------------------- | -------------------------------------------------------------------- | +| `MaterializedCte::try_map_inputs_mut` | Calls a closure that changes the body and the continuation in place. | +| `MaterializedCte::with_new_inputs` | Returns a new node with the same id and name, and new inputs. | + +Both return a `Result`, so that a later version can check the scans. +`LogicalPlan::check_invariants` checks the scans of a plan that these APIs +build.