From ffb77b4d60804d7d820e47a053dd9b567dddbaae Mon Sep 17 00:00:00 2001
From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>
Date: Wed, 18 Nov 2026 14:29:49 -0600
Subject: [PATCH 1/2] refactor: make the fields of MaterializedCte private
A rule that builds a MaterializedCte with a struct literal or struct update
skips the scan check in try_new. Private fields send every new node through
try_new, and every in-place change through inputs_mut or with_new_inputs.
The fields are pub(crate), so the tree-node and display code of
datafusion-expr is unchanged. inputs_mut and into_inputs replace the
remaining direct field access in the optimizer and the physical planner.
---
datafusion/core/src/physical_planner.rs | 22 ++++++++++---------
.../expr/src/logical_plan/materialized_cte.rs | 20 +++++++++++++----
datafusion/expr/src/logical_plan/plan.rs | 10 ++++-----
.../optimizer/src/analyzer/type_coercion.rs | 21 ++++++++++--------
datafusion/optimizer/src/decorrelate.rs | 17 ++++++++------
.../optimizer/src/optimize_projections/mod.rs | 10 +++------
datafusion/optimizer/src/optimizer.rs | 11 ++++------
datafusion/optimizer/src/push_down_filter.rs | 5 +++--
.../library-user-guide/upgrading/57.0.0.md | 7 ++++++
9 files changed, 71 insertions(+), 52 deletions(-)
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs
index a861a538d6b13..601f2e4a10746 100644
--- a/datafusion/core/src/physical_planner.rs
+++ b/datafusion/core/src/physical_planner.rs
@@ -274,15 +274,16 @@ 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 (old_id, name) = (cte.id(), cte.name().to_string());
let new_id = MaterializedCteId::next();
- let continuation = Arc::unwrap_or_clone(cte.continuation)
+ let (body, continuation) = cte.into_inputs();
+ 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 +298,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 +2046,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..bcde76056f3c4 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,6 +151,18 @@ impl MaterializedCte {
MaterializedCteScan::find_in(&self.continuation, self.id)
}
+ /// The body and the continuation, in this order, for a rule that changes
+ /// them in place. The schemas of the scans are not checked again.
+ pub fn inputs_mut(&mut self) -> (&mut Arc, &mut Arc) {
+ (&mut self.cte, &mut self.continuation)
+ }
+
+ /// The body and the continuation, in this order. Build a node again with
+ /// [`Self::try_new`].
+ pub fn into_inputs(self) -> (Arc, Arc) {
+ (self.cte, self.continuation)
+ }
+
/// Return a node with the same id and name, and new inputs. The schemas
/// of the scans are not checked again.
pub fn with_new_inputs(
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs
index d2467e2346c44..cd812eafa6aca 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),
diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs
index 42e74b0d70437..d54e64587f43c 100644
--- a/datafusion/optimizer/src/analyzer/type_coercion.rs
+++ b/datafusion/optimizer/src/analyzer/type_coercion.rs
@@ -128,21 +128,24 @@ 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) = (cte.id(), cte.name().to_string());
+ let (body, continuation) = cte.into_inputs();
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 +176,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..3f7e0bb2089f0 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,17 @@ 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) = (cte.id(), cte.name().to_string());
+ let (body, continuation) = cte.into_inputs();
+ 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..59444c93f43f3 100644
--- a/datafusion/optimizer/src/optimize_projections/mod.rs
+++ b/datafusion/optimizer/src/optimize_projections/mod.rs
@@ -528,12 +528,8 @@ fn optimize_materialized_cte(
config: &dyn OptimizerConfig,
indices: RequiredIndices,
) -> Result> {
- let MaterializedCte {
- id,
- name,
- cte: body,
- continuation,
- } = cte;
+ let (id, name) = (cte.id(), cte.name().to_string());
+ let (body, continuation) = cte.into_inputs();
// The output is the output of the continuation, so the continuation
// needs what the parent needs.
let continuation =
@@ -578,7 +574,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..612a53964c512 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,11 +467,8 @@ fn map_children_mut Result>(
let r = f(Arc::make_mut(recursive_term))?;
s || r
}
- LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte {
- cte,
- continuation,
- ..
- })) => {
+ LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
+ let (cte, continuation) = cte.inputs_mut();
let b = f(Arc::make_mut(cte))?;
let c = f(Arc::make_mut(continuation))?;
b || c
diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs
index efaea281a14e2..75344182f2ea4 100644
--- a/datafusion/optimizer/src/push_down_filter.rs
+++ b/datafusion/optimizer/src/push_down_filter.rs
@@ -1403,9 +1403,10 @@ 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(
+ let (_, continuation) = cte.inputs_mut();
+ *continuation = Arc::new(LogicalPlan::Filter(Filter::new(
filter.predicate,
- cte.continuation,
+ Arc::clone(continuation),
)));
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..ef806290325f5 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,10 @@ 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. A rule that
+changes the inputs in place can use `MaterializedCte::inputs_mut` or
+`MaterializedCte::with_new_inputs`, and `MaterializedCte::into_inputs` takes
+the inputs by value.
From d367c8ee89c0ca070c839f8608db29b0df695072 Mon Sep 17 00:00:00 2001
From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>
Date: Mon, 23 Nov 2026 23:35:04 -0600
Subject: [PATCH 2/2] refactor: make MaterializedCte input mutation APIs
fallible
Review asked that the unchecked mutation APIs keep room for future
validation. try_map_inputs_mut replaces inputs_mut and takes a fallible
closure, and with_new_inputs returns a Result. into_parts replaces
into_inputs and also returns the id and name, so that callers do not copy
the name before they consume the node.
Co-Authored-By: Claude Opus 5.5
---
datafusion/core/src/physical_planner.rs | 3 +-
.../expr/src/logical_plan/materialized_cte.rs | 51 ++++++++++++-------
datafusion/expr/src/logical_plan/plan.rs | 2 +-
.../optimizer/src/analyzer/type_coercion.rs | 3 +-
datafusion/optimizer/src/decorrelate.rs | 3 +-
.../optimizer/src/optimize_projections/mod.rs | 3 +-
datafusion/optimizer/src/optimizer.rs | 12 ++---
datafusion/optimizer/src/push_down_filter.rs | 12 +++--
.../library-user-guide/upgrading/57.0.0.md | 18 +++++--
9 files changed, 65 insertions(+), 42 deletions(-)
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs
index 601f2e4a10746..0fa6ea0195f87 100644
--- a/datafusion/core/src/physical_planner.rs
+++ b/datafusion/core/src/physical_planner.rs
@@ -274,9 +274,8 @@ fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result>
let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node else {
return Ok(Transformed::no(node));
};
- let (old_id, name) = (cte.id(), cte.name().to_string());
let new_id = MaterializedCteId::next();
- let (body, continuation) = cte.into_inputs();
+ 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
diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs
index bcde76056f3c4..199651d0c50b9 100644
--- a/datafusion/expr/src/logical_plan/materialized_cte.rs
+++ b/datafusion/expr/src/logical_plan/materialized_cte.rs
@@ -151,31 +151,46 @@ impl MaterializedCte {
MaterializedCteScan::find_in(&self.continuation, self.id)
}
- /// The body and the continuation, in this order, for a rule that changes
- /// them in place. The schemas of the scans are not checked again.
- pub fn inputs_mut(&mut self) -> (&mut Arc, &mut Arc) {
- (&mut self.cte, &mut self.continuation)
- }
-
- /// The body and the continuation, in this order. Build a node again with
- /// [`Self::try_new`].
- pub fn into_inputs(self) -> (Arc, Arc) {
- (self.cte, self.continuation)
- }
-
- /// 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,
- }
+ })
}
}
@@ -758,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 cd812eafa6aca..956d31d0ed8d6 100644
--- a/datafusion/expr/src/logical_plan/plan.rs
+++ b/datafusion/expr/src/logical_plan/plan.rs
@@ -1232,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 d54e64587f43c..4f8843dbc83cb 100644
--- a/datafusion/optimizer/src/analyzer/type_coercion.rs
+++ b/datafusion/optimizer/src/analyzer/type_coercion.rs
@@ -128,8 +128,7 @@ 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) = (cte.id(), cte.name().to_string());
- let (body, continuation) = cte.into_inputs();
+ let (id, name, body, continuation) = cte.into_parts();
let body =
coerce_plan_and_subqueries(Arc::unwrap_or_clone(body), config)?;
let continuation = with_materialized_cte_scan_schema(
diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rs
index 3f7e0bb2089f0..25918d6f48071 100644
--- a/datafusion/optimizer/src/decorrelate.rs
+++ b/datafusion/optimizer/src/decorrelate.rs
@@ -223,8 +223,7 @@ 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 (id, name) = (cte.id(), cte.name().to_string());
- let (body, continuation) = cte.into_inputs();
+ let (id, name, body, continuation) = cte.into_parts();
let continuation = Arc::unwrap_or_clone(continuation).rewrite(self)?;
Ok(Transformed::new(
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
diff --git a/datafusion/optimizer/src/optimize_projections/mod.rs b/datafusion/optimizer/src/optimize_projections/mod.rs
index 59444c93f43f3..6d1f550b77416 100644
--- a/datafusion/optimizer/src/optimize_projections/mod.rs
+++ b/datafusion/optimizer/src/optimize_projections/mod.rs
@@ -528,8 +528,7 @@ fn optimize_materialized_cte(
config: &dyn OptimizerConfig,
indices: RequiredIndices,
) -> Result> {
- let (id, name) = (cte.id(), cte.name().to_string());
- let (body, continuation) = cte.into_inputs();
+ 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 =
diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rs
index 612a53964c512..7e738809fac98 100644
--- a/datafusion/optimizer/src/optimizer.rs
+++ b/datafusion/optimizer/src/optimizer.rs
@@ -467,12 +467,12 @@ fn map_children_mut Result>(
let r = f(Arc::make_mut(recursive_term))?;
s || r
}
- LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
- let (cte, continuation) = cte.inputs_mut();
- 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 75344182f2ea4..8b006ffb29f7c 100644
--- a/datafusion/optimizer/src/push_down_filter.rs
+++ b/datafusion/optimizer/src/push_down_filter.rs
@@ -1403,11 +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.
- let (_, continuation) = cte.inputs_mut();
- *continuation = Arc::new(LogicalPlan::Filter(Filter::new(
- filter.predicate,
- Arc::clone(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 ef806290325f5..73707c3d7e2d9 100644
--- a/docs/source/library-user-guide/upgrading/57.0.0.md
+++ b/docs/source/library-user-guide/upgrading/57.0.0.md
@@ -171,7 +171,17 @@ 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. A rule that
-changes the inputs in place can use `MaterializedCte::inputs_mut` or
-`MaterializedCte::with_new_inputs`, and `MaterializedCte::into_inputs` takes
-the inputs by value.
+`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.