Copilot commented on code in PR #27725:
URL: https://github.com/apache/datafusion/pull/27725#discussion_r4750688231
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -227,86 +227,17 @@ impl DefaultPhysicalPlanner {
{
return Ok(plan);
}
- let renumbered = renumber_materialized_ctes(logical_plan)?;
- let logical_plan = renumbered.as_ref().unwrap_or(logical_plan);
+ // The ids must be new for each planning run. See
+ // `renumber_materialized_ctes`.
+ let logical_plan =
renumber_materialized_ctes(logical_plan.clone())?.data;
+ let logical_plan = &logical_plan;
Review Comment:
This clones the plan even when it contains no materialized CTE, whereas the
previous implementation borrowed such plans. The clone is not always cheap:
`LogicalPlan::Values` owns a `Vec<Vec<Expr>>`
(`expr/src/logical_plan/plan.rs:2753–2757`), so a large top-level `VALUES`
query now duplicates every literal before physical planning, despite being
unrelated to this feature. Please keep the borrowed no-CTE fast path by
checking for a CTE before cloning.
##########
docs/source/library-user-guide/upgrading/57.0.0.md:
##########
@@ -228,33 +228,6 @@ let statistics = Statistics::new_unknown(&self.schema())
.with_num_rows(Precision::Exact(num_rows));
```
-### Materialized CTE scans have a projection
-
-`MaterializedCteScan` and `MaterializedCteScanExec` have a `projection`. It
gives
-the indexes of the columns of the CTE body that the scan outputs. `None` means
all
-the columns. `OptimizeProjections` uses it to remove from the body the columns
-that no scan reads.
-
-A custom optimizer rule that changes the schema of the body of a
-`MaterializedCte` must also change the `projection` of every scan of that CTE,
-because a scan reads the columns of the body by position. Use
-`MaterializedCteScan::with_body_columns` to remap a scan, and
-`MaterializedCteScan::with_body_schema` to give a scan the new types of the
-columns that it reads.
-
-The `schema` and `projection` fields of `MaterializedCteScan` are private, so
-that the two always match. Read them with `MaterializedCteScan::schema` and
-`MaterializedCteScan::projection`. Build a scan with `MaterializedCteScan::new`
-and `MaterializedCteScan::with_projection`. To build a physical scan with a
-projection, use `MaterializedCteScanExec::with_body_projection`. It returns an
-error if the projection does not have one index for each column of the scan
-schema.
-
-`LogicalPlan::check_invariants` checks that each scan of a `MaterializedCte`
-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.
-
### Null-aware sort-merge joins add a protobuf field
Review Comment:
This deletes the only 57.0.0 materialized-CTE migration section without
replacing it, despite restricting public constructors, fields and scan helpers.
The claim that the affected API is unreleased also conflicts with the 56.0.0
guide, which already documents `MaterializedCteScan::find_in` at
`docs/source/library-user-guide/upgrading/56.0.0.md:1418`. Restore migration
guidance for the builder and checked rewrite methods, retain the physical-scan
projection notes, and correct the compatibility statement in the PR description.
##########
datafusion/expr/src/logical_plan/materialized_cte.rs:
##########
@@ -145,15 +224,203 @@ impl MaterializedCte {
self.continuation.schema()
}
+ /// Whether a scan in the continuation reads this CTE, also in a subquery
+ /// expression. A CTE that nothing reads does not need to be computed.
+ pub fn is_read(&self) -> Result<bool> {
+ let mut is_read = false;
+ visit_scans(&self.continuation, self.id, |_| {
+ is_read = true;
+ Ok(TreeNodeRecursion::Stop)
+ })?;
+ Ok(is_read)
+ }
+
+ /// Returns an error if a scan of this CTE in the continuation does not
+ /// have the names and types of the columns of the body that it reads.
+ pub(crate) fn check_scans(&self) -> Result<()> {
+ check_scans(self.id, &self.name, self.cte.schema(), &self.continuation)
+ }
+
/// The scans in the continuation that read this CTE, also in subquery
/// expressions. See [`MaterializedCteScan::find_in`].
- pub fn scans(&self) -> Result<Vec<MaterializedCteScan>> {
+ #[cfg(test)]
+ fn scans(&self) -> Result<Vec<MaterializedCteScan>> {
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.
- pub fn with_new_inputs(
+ /// Call `f` with the body, then with the continuation, so that a rule can
+ /// change them in place. Return `true` if a call of `f` returns `true`.
+ ///
+ /// After both calls, if an input changed, check the scans of this CTE in
+ /// the continuation against the body, as [`LogicalPlan::check_invariants`]
+ /// does. Returns an error if a scan does not have the names and types of
+ /// the columns of the body that it reads. A rule can remove a column of
+ /// the body that no scan reads. The continuation can change its schema,
+ /// and the optimizer then recomputes the schema of this node.
+ pub fn map_inputs_mut(
+ &mut self,
+ mut f: impl FnMut(&mut LogicalPlan) -> Result<bool>,
+ ) -> Result<bool> {
+ let schema = Arc::clone(self.cte.schema());
+ let body = f(Arc::make_mut(&mut self.cte))?;
+ let continuation = f(Arc::make_mut(&mut self.continuation))?;
+ if body || continuation || !Arc::ptr_eq(&schema, self.cte.schema()) {
+ self.check_scans()?;
+ }
+ Ok(body || continuation)
+ }
+
+ /// Replace the continuation with the result of `f`.
+ ///
+ /// Returns an error if a scan of this CTE in the new continuation does
+ /// not have the names and types of the columns of the body that it reads.
+ pub fn map_continuation(
+ self,
+ f: impl FnOnce(LogicalPlan) -> Result<Transformed<LogicalPlan>>,
+ ) -> Result<Transformed<Self>> {
+ let Self {
+ id,
+ name,
+ cte,
+ continuation,
+ } = self;
+ f(Arc::unwrap_or_clone(continuation))?
+ .map_data(|continuation| Self::try_new(id, name, cte,
Arc::new(continuation)))
+ }
+
+ /// Replace the body with the result of `f`. The scans do not change.
+ ///
+ /// Returns an error if a scan of this CTE does not have the names and
+ /// types of the columns of the new body that it reads.
+ pub fn map_body(
+ self,
+ f: impl FnOnce(LogicalPlan) -> Result<Transformed<LogicalPlan>>,
+ ) -> Result<Transformed<Self>> {
+ let Self {
+ id,
+ name,
+ cte,
+ continuation,
+ } = self;
+ f(Arc::unwrap_or_clone(cte))?
+ .map_data(|cte| Self::try_new(id, name, Arc::new(cte),
continuation))
+ }
+
+ /// Replace the body with `body`, which has the column names of the
+ /// current body and maybe other types, for example after type coercion.
+ /// Each scan gets the new types of the columns that it reads, and keeps
+ /// its qualifiers.
Review Comment:
`with_coerced_body` updates scan leaves but not cached schemas or scans of
dependent CTEs in the continuation. After an Int32-to-Int64 change, a
projecting continuation can still report Int32, and a dependent CTE can fail
executable invariants. Require continuation reanalysis as part of this
operation, or explicitly document that the returned node is intermediate and
must be reanalyzed before execution.
##########
datafusion/optimizer/src/analyzer/type_coercion.rs:
##########
@@ -129,24 +128,15 @@ fn coerce_plan_and_subqueries(
// its new schema to the scans before the continuation is coerced.
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
let body =
- coerce_plan_and_subqueries(Arc::unwrap_or_clone(cte.cte),
config)?;
- let continuation = with_materialized_cte_scan_schema(
- Arc::unwrap_or_clone(cte.continuation),
- cte.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
- },
- )),
- true,
- TreeNodeRecursion::Jump,
- ))
+ coerce_plan_and_subqueries(LogicalPlan::clone(cte.body()),
config)?;
Review Comment:
Cloning through `cte.body()` retains the original tree during recursive
coercion, so even a uniquely owned body now shares its children with that
retained copy. Traversal then clones those children through `Arc::make_mut`,
copying plan nodes and expressions even when coercion does not change their
types. Please provide an owning coercion callback on `MaterializedCte` so this
caller can consume the body with `Arc::unwrap_or_clone` before remapping its
scans.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]