diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs index 946962e2a95f8..e97d75be3efc6 100644 --- a/datafusion/core/src/physical_planner.rs +++ b/datafusion/core/src/physical_planner.rs @@ -83,9 +83,9 @@ use datafusion_expr::physical_planning_context::{ use datafusion_expr::utils::{expr_to_columns, split_conjunction}; use datafusion_expr::{ Analyze, BinaryExpr, DmlStatement, Explain, ExplainFormat, Extension, FetchType, - Filter, JoinType, MaterializedCte, MaterializedCteId, MaterializedCtePlan, Operator, - RecursiveQuery, Show, ShowKind, SkipType, StringifiedPlan, WindowFrame, - WindowFrameBound, WriteOp, + Filter, JoinType, MaterializedCtePlan, Operator, RecursiveQuery, Show, ShowKind, + SkipType, StringifiedPlan, WindowFrame, WindowFrameBound, WriteOp, + renumber_materialized_ctes, }; use datafusion_physical_expr::aggregate::{ AggregateFunctionExpr, LoweredAggregate, LoweredAggregateBuilder, @@ -227,8 +227,10 @@ 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; let plan = self .create_initial_plan(logical_plan, session_state) .await?; @@ -236,77 +238,6 @@ impl DefaultPhysicalPlanner { } } -/// Give each occurrence of a [`MaterializedCte`] in `plan` a new id, and -/// update the scans in its continuation, including the scans in subqueries. -/// -/// The id is copied when a logical plan is cloned, so one CTE can occur more -/// than once, for example when a view that declares it is referenced two -/// times, or when a DataFrame is joined to itself. Each occurrence is a -/// separate CTE, as in PostgreSQL. -/// -/// The ids must also be new for each planning run, not only unique within -/// `plan`. A table provider can plan a saved logical plan in its `scan`, as a -/// [`ViewTable`] that is not inlined does. Each such scan is a separate -/// planning run of the same saved plan, and its CTEs end up in the same -/// physical plan as the CTEs of the outer run. -/// -/// Returns `None` when `plan` has no materialized CTE. -/// -/// [`ViewTable`]: crate::datasource::ViewTable -fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result> { - let mut has_cte = false; - plan.apply_with_subqueries(|node| { - if matches!( - node, - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_)) - ) { - has_cte = true; - return Ok(TreeNodeRecursion::Stop); - } - Ok(TreeNodeRecursion::Continue) - })?; - if !has_cte { - return Ok(None); - } - - plan.clone() - .transform_down_with_subqueries(|node| { - 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) - .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 => { - Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) - } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(mut scan)) - if scan.id == old_id => - { - scan.id = new_id; - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Scan(scan), - ))) - } - _ => Ok(Transformed::no(node)), - })? - .data; - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Cte(MaterializedCte { - id: new_id, - continuation: Arc::new(continuation), - ..cte - }), - ))) - }) - .map(|t| Some(t.data)) -} - /// Points every [`MaterializedCteScanExec`] at the buffer of the /// [`MaterializedCteExec`] with the same id, and gives it the statistics of /// the CTE body. @@ -947,8 +878,8 @@ impl DefaultPhysicalPlanner { LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) => { // Unbound until `bind_materialized_cte_scans` runs on the whole plan. let exec = MaterializedCteScanExec::new( - scan.id.as_u64(), - &scan.name, + scan.id().as_u64(), + scan.name(), Arc::clone(scan.schema().inner()), session.config().target_partitions(), ); @@ -2036,7 +1967,7 @@ impl DefaultPhysicalPlanner { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { let [body, continuation] = children.two()?; // A CTE that nothing reads is never evaluated. - if cte.scans()?.is_empty() { + if !cte.is_read()? { return Ok(continuation); } // The body is fully buffered before a scan yields a row, so an @@ -2044,11 +1975,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/invariants.rs b/datafusion/expr/src/logical_plan/invariants.rs index 18b8193835127..00771b948bb56 100644 --- a/datafusion/expr/src/logical_plan/invariants.rs +++ b/datafusion/expr/src/logical_plan/invariants.rs @@ -2,9 +2,12 @@ // 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 -use crate::logical_plan::MaterializedCtePlan; +use std::collections::HashSet; +use std::sync::Arc; + +use crate::logical_plan::{MaterializedCteId, MaterializedCtePlan}; use datafusion_common::{ - DFSchemaRef, Result, assert_or_internal_err, plan_err, + DFSchemaRef, Result, assert_or_internal_err, internal_err, plan_err, tree_node::{TreeNode, TreeNodeRecursion}, }; @@ -98,26 +101,82 @@ fn assert_valid_semantic_plan(plan: &LogicalPlan) -> Result<()> { Ok(()) } -/// Returns an error if a scan of a materialized CTE does not have the names -/// and types of the columns that it reads from the body of the CTE. +/// Returns an error if a scan of a materialized CTE is not in the +/// continuation of its CTE, or does not have the names and types of the +/// columns that it reads from the body of the CTE. +/// +/// The id of a CTE is in scope only in its continuation, also in subquery +/// expressions there. It is not in scope in the body of the CTE or above the +/// CTE. A nested CTE with the same id owns the scans below it. /// /// A scan whose CTE is not in `plan` is not checked, because `plan` can be a /// part of a larger plan. fn assert_materialized_cte_scans_are_valid(plan: &LogicalPlan) -> Result<()> { + let mut ids = HashSet::new(); plan.apply_with_subqueries(|node| { if let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node { - for scan in cte.scans()? { - scan.check_body_schema(cte.body().schema()).map_err(|e| { - e.context(format!( - "A scan of the materialized CTE {} does not match the CTE", - cte.name() - )) - })?; - } + ids.insert(cte.id()); } Ok(TreeNodeRecursion::Continue) - }) - .map(|_| ()) + })?; + if ids.is_empty() { + return Ok(()); + } + check_materialized_cte_scope(plan, &ids, &mut vec![]) +} + +/// The id and body schema of each CTE whose continuation contains the +/// current node, innermost last. It holds owned values because +/// `apply_subqueries` hands out temporary plans. +type MaterializedCteScope = Vec<(MaterializedCteId, DFSchemaRef)>; + +#[cfg_attr(feature = "recursive_protection", recursive::recursive)] +fn check_materialized_cte_scope( + plan: &LogicalPlan, + ids: &HashSet, + scope: &mut MaterializedCteScope, +) -> Result<()> { + match plan { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { + check_materialized_cte_scope(cte.body(), ids, scope)?; + scope.push((cte.id(), Arc::clone(cte.body().schema()))); + let result = check_materialized_cte_scope(cte.continuation(), ids, scope); + scope.pop(); + return result; + } + LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) + if ids.contains(&scan.id()) => + { + let Some((_, body_schema)) = + scope.iter().rev().find(|(id, _)| *id == scan.id()) + else { + return internal_err!( + "A scan of the materialized CTE {} is not in the continuation of the CTE", + scan.name() + ); + }; + return scan.check_body_schema(body_schema).map_err(|e| { + e.context(format!( + "A scan of the materialized CTE {} does not match the CTE", + scan.name() + )) + }); + } + _ => {} + } + for input in plan.inputs() { + check_materialized_cte_scope(input, ids, scope)?; + } + let mut result = Ok(()); + plan.apply_subqueries(|subquery| { + result = check_materialized_cte_scope(subquery, ids, scope); + Ok(if result.is_ok() { + TreeNodeRecursion::Jump + } else { + TreeNodeRecursion::Stop + }) + })?; + result } /// Returns an error if the plan does not have the expected schema. diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 4df766bae5eb8..f15a6759bda56 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -18,6 +18,20 @@ //! A scan can read a subset of the columns of the body (see //! [`MaterializedCteScan::projection`]). The optimizer removes from the body //! the columns that no scan reads. +//! +//! # Checks +//! +//! A scan reads the columns of the body by position, so the scans must +//! match the body. [`MaterializedCteBuilder::build`] and the methods of +//! [`MaterializedCte`] that change an input check this. +//! +//! The generic tree APIs do not check it: [`LogicalPlan::with_new_exprs`] +//! and [`TreeNode::map_children`] replace the inputs as they are given. +//! [`LogicalPlan::check_invariants`] checks the scans of every +//! [`MaterializedCte`] in a plan. The optimizer runs it before and after +//! the rules. +//! +//! [`TreeNode::map_children`]: datafusion_common::tree_node::TreeNode::map_children use std::cmp::Ordering; use std::fmt; @@ -25,12 +39,12 @@ use std::hash::Hash; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; -use datafusion_common::tree_node::TreeNodeRecursion; +use datafusion_common::tree_node::{Transformed, TreeNodeRecursion}; use datafusion_common::{ - DFSchema, DFSchemaRef, Result, internal_datafusion_err, internal_err, + Column, DFSchema, DFSchemaRef, Result, internal_datafusion_err, internal_err, }; -use crate::LogicalPlan; +use crate::{Expr, LogicalPlan, Projection}; /// Identifies one materialized CTE and binds its scans to it. /// @@ -41,7 +55,7 @@ pub struct MaterializedCteId(u64); impl MaterializedCteId { /// Allocate a new unique id. - pub fn next() -> Self { + pub(crate) fn next() -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); Self(NEXT.fetch_add(1, AtomicOrdering::Relaxed)) } @@ -82,13 +96,85 @@ 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, +} + +/// Builds a [`MaterializedCte`]: the body first, then one +/// [`MaterializedCteScan`] for each reference to the CTE, then the +/// continuation that holds the references. +/// +/// The builder allocates the id that binds the scans to the node. It is not +/// `Clone`, so two nodes built from it cannot share an id. +/// +/// ``` +/// # use std::sync::Arc; +/// # use datafusion_common::{DFSchema, Result}; +/// # use datafusion_expr::{EmptyRelation, LogicalPlan, MaterializedCteBuilder}; +/// # fn main() -> Result<()> { +/// let body = LogicalPlan::EmptyRelation(EmptyRelation { +/// produce_one_row: true, +/// schema: Arc::new(DFSchema::empty()), +/// }); +/// let builder = MaterializedCteBuilder::new("c", body); +/// let continuation = LogicalPlan::from(builder.scan()); +/// let cte = builder.build(continuation)?; +/// assert_eq!(cte.name(), "c"); +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug)] +pub struct MaterializedCteBuilder { + id: MaterializedCteId, + name: String, + body: Arc, +} + +impl MaterializedCteBuilder { + /// Start a materialized CTE with the name `name` and the body `body`. + pub fn new(name: impl Into, body: LogicalPlan) -> Self { + Self { + id: MaterializedCteId::next(), + name: name.into(), + body: Arc::new(body), + } + } + + /// A scan of all the columns of the body. Call this once for each + /// reference to the CTE in the continuation. + pub fn scan(&self) -> MaterializedCteScan { + MaterializedCteScan::new( + self.id, + self.name.clone(), + Arc::clone(self.body.schema()), + ) + } + + /// Build the node that computes the body once and evaluates + /// `continuation`. + /// + /// Returns an error if a scan of this CTE in `continuation` does not have + /// the names and types of the columns of the body that it reads. + pub fn build(self, continuation: LogicalPlan) -> Result { + MaterializedCte::try_new(self.id, self.name, self.body, Arc::new(continuation)) + } +} + +impl From for LogicalPlan { + fn from(cte: MaterializedCte) -> Self { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) + } +} + +impl From for LogicalPlan { + fn from(scan: MaterializedCteScan) -> Self { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) + } } impl MaterializedCte { @@ -97,7 +183,7 @@ impl MaterializedCte { /// Returns an error if a scan of this CTE in `continuation` (also in a /// subquery expression) does not have the names and types of the columns /// of `cte` that it reads. - pub fn try_new( + pub(crate) fn try_new( id: MaterializedCteId, name: impl Into, cte: Arc, @@ -145,15 +231,184 @@ 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 { + self.scans().map(|scans| !scans.is_empty()) + } + /// The scans in the continuation that read this CTE, also in subquery /// expressions. See [`MaterializedCteScan::find_in`]. - pub fn scans(&self) -> Result> { + pub(crate) fn scans(&self) -> Result> { 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`. + /// + /// Returns an error if `f` changes the names or the types of the columns + /// of the body, because the scans read them by position. The continuation + /// is not checked: its schema can change, and the optimizer then + /// recomputes the schema of this node. + pub fn map_inputs_mut( + &mut self, + mut f: impl FnMut(&mut LogicalPlan) -> Result, + ) -> Result { + let schema = Arc::clone(self.cte.schema()); + let body = f(Arc::make_mut(&mut self.cte))?; + if !Arc::ptr_eq(&schema, self.cte.schema()) { + schema + .has_equivalent_names_and_types(self.cte.schema()) + .map_err(|e| { + e.context(format!( + "The body of the materialized CTE {} changed its columns", + self.name + )) + })?; + } + let continuation = f(Arc::make_mut(&mut self.continuation))?; + 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>, + ) -> Result> { + 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>, + ) -> Result> { + 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. + /// + /// Returns an error if `body` does not have the column names of the + /// current body that the scans read. + pub fn with_coerced_body(self, body: LogicalPlan) -> Result { + let body_schema = Arc::clone(body.schema()); + let continuation = Self::map_scans(self.id, self.continuation, |scan| { + let new_scan = scan.with_body_schema(&body_schema)?; + Ok(if new_scan.schema().inner() == scan.schema().inner() { + Transformed::no(scan) + } else { + Transformed::yes(new_scan) + }) + })?; + Self::try_new(self.id, self.name, Arc::new(body), continuation) + } + + /// Remove from the body the columns that no scan of this CTE reads. The + /// body becomes a [`Projection`] of the other columns, and each scan + /// reads the new positions of its columns. The output of each scan does + /// not change. + /// + /// The body keeps one column if no scan reads a column, as + /// `SELECT count(*) FROM c` does, so that it still has its rows. The node + /// does not change if nothing reads the CTE or if every column is read. + pub fn prune_body_columns(self) -> Result> { + let body_len = self.cte.schema().fields().len(); + let scans = self.scans()?; + let mut is_read = vec![false; body_len]; + for scan in &scans { + match scan.projection() { + None => is_read.fill(true), + Some(projection) => { + for index in projection { + let Some(is_read) = is_read.get_mut(*index) else { + return internal_err!( + "A scan of the materialized CTE {} reads the column {index}, but the CTE has {body_len} columns", + self.name + ); + }; + *is_read = true; + } + } + } + } + if !is_read.contains(&true) + && let Some(first) = is_read.first_mut() + { + *first = true; + } + let kept: Vec = (0..body_len).filter(|index| is_read[*index]).collect(); + // A CTE that nothing reads is not planned, so its body is left as it is. + if scans.is_empty() || kept.len() == body_len { + return Ok(Transformed::no(self)); + } + + let schema = self.cte.schema(); + let exprs = kept + .iter() + .map(|index| Expr::Column(Column::from(schema.qualified_field(*index)))) + .collect(); + let body = Projection::try_new(exprs, Arc::clone(&self.cte)) + .map(LogicalPlan::Projection)?; + let continuation = Self::map_scans(self.id, self.continuation, |scan| { + scan.with_body_columns(&kept).map(Transformed::yes) + })?; + Self::try_new(self.id, self.name, Arc::new(body), continuation) + .map(Transformed::yes) + } + + /// Apply `f` to each scan of the CTE `id` in `continuation`, also in + /// subquery expressions, and return the new continuation. + /// + /// The traversal does not go below a [`MaterializedCte`] with the same id. + /// Such a node is a separate occurrence of the CTE and owns its scans. + fn map_scans( + id: MaterializedCteId, + continuation: Arc, + mut f: impl FnMut(MaterializedCteScan) -> Result>, + ) -> Result> { + Arc::unwrap_or_clone(continuation) + .transform_down_with_subqueries(|node| match node { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref nested)) + if nested.id == id => + { + Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) + } + LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) + if scan.id == id => + { + f(scan).map(|scan| scan.update_data(LogicalPlan::from)) + } + _ => Ok(Transformed::no(node)), + }) + .map(|t| Arc::new(t.data)) + } + + /// Return a new node with the same id and name, and new inputs. The + /// scans are not checked. See the [module documentation](self). + pub(crate) fn with_new_inputs_unchecked( &self, cte: Arc, continuation: Arc, @@ -183,6 +438,52 @@ impl PartialOrd for MaterializedCte { } } +/// Give each occurrence of a [`MaterializedCte`] in `plan` a new id, and +/// update the scans in its continuation, including the scans in subqueries. +/// +/// The id is copied when a logical plan is cloned, so one CTE can occur more +/// than once, for example when a view that declares it is referenced two +/// times, or when a DataFrame is joined to itself. Each occurrence is a +/// separate CTE, as in PostgreSQL. +/// +/// The new ids are also unique across calls. A physical planner can thus +/// call this function for each planning run of the same saved plan, and put +/// the results in one physical plan. +/// +/// A new id does not change a schema, so the scans are not checked again. +pub fn renumber_materialized_ctes(plan: LogicalPlan) -> Result> { + let mut has_cte = false; + plan.apply_with_subqueries(|node| { + if matches!( + node, + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_)) + ) { + has_cte = true; + return Ok(TreeNodeRecursion::Stop); + } + Ok(TreeNodeRecursion::Continue) + })?; + if !has_cte { + return Ok(Transformed::no(plan)); + } + plan.transform_down_with_subqueries(|node| { + let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node else { + return Ok(Transformed::no(node)); + }; + let id = MaterializedCteId::next(); + let continuation = + MaterializedCte::map_scans(cte.id, cte.continuation, |mut scan| { + scan.id = id; + Ok(Transformed::yes(scan)) + })?; + Ok(Transformed::yes(LogicalPlan::from(MaterializedCte { + id, + continuation, + ..cte + }))) + }) +} + /// Reads the buffered output of the [`MaterializedCte`] with the same `id`. /// /// This is a leaf. It outputs all the columns of the CTE body, or the columns @@ -190,9 +491,9 @@ impl PartialOrd for MaterializedCte { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct MaterializedCteScan { /// The id of the [`MaterializedCte`] that this scan reads - 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 schema of this scan: the columns of the CTE body that /// `projection` selects schema: DFSchemaRef, @@ -206,8 +507,8 @@ pub struct MaterializedCteScan { impl MaterializedCteScan { /// Create a scan of all the columns of the CTE `id`, whose body has the - /// schema `schema`. - pub fn new( + /// schema `schema`. See [`MaterializedCteBuilder::scan`]. + pub(crate) fn new( id: MaterializedCteId, name: impl Into, schema: DFSchemaRef, @@ -272,7 +573,7 @@ impl MaterializedCteScan { /// columns `kept`, in this order. /// /// Returns an error if this scan reads a column that is not in `kept`. - pub fn with_body_columns(&self, kept: &[usize]) -> Result { + pub(crate) fn with_body_columns(&self, kept: &[usize]) -> Result { let old: Vec = match &self.projection { Some(projection) => projection.clone(), // The scan reads all the columns, so `kept` must be all of them. @@ -302,7 +603,7 @@ impl MaterializedCteScan { /// Return this scan with the fields that it reads from a CTE body with /// the schema `body`. The scan keeps its qualifiers and its projection. - pub fn with_body_schema(&self, body: &DFSchema) -> Result { + pub(crate) fn with_body_schema(&self, body: &DFSchema) -> Result { // The analyzer can change the types of the body, so only the indexes // and the names are checked here. self.check_body_names(body)?; @@ -357,7 +658,7 @@ impl MaterializedCteScan { /// Check that this scan has the names and types of the columns that it /// reads from a CTE body with the schema `body`. - pub fn check_body_schema(&self, body: &DFSchema) -> Result<()> { + pub(crate) fn check_body_schema(&self, body: &DFSchema) -> Result<()> { match &self.projection { None => self.schema.has_equivalent_names_and_types(body), Some(projection) => { @@ -380,7 +681,10 @@ impl MaterializedCteScan { /// The search does not go below a [`MaterializedCte`] with the same `id` /// in `plan`. Such a node is a separate occurrence of the CTE (the id is /// copied when a plan is cloned) and owns the scans below it. - pub fn find_in(plan: &LogicalPlan, id: MaterializedCteId) -> Result> { + pub(crate) fn find_in( + plan: &LogicalPlan, + id: MaterializedCteId, + ) -> Result> { let mut scans = vec![]; plan.apply_with_subqueries(|node| match node { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) @@ -435,7 +739,7 @@ impl PartialOrd for MaterializedCteScan { mod tests { use super::*; use crate::logical_plan::builder::LogicalPlanBuilder; - use crate::{EmptyRelation, exists}; + use crate::{EmptyRelation, Filter, exists}; use arrow::datatypes::{DataType, Field, Schema}; use datafusion_common::{Constraint, Constraints, DFSchema, FunctionalDependencies}; use std::collections::HashMap; @@ -460,11 +764,7 @@ mod tests { } fn scan(id: MaterializedCteId, data_type: DataType) -> LogicalPlan { - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(MaterializedCteScan::new( - id, - "c", - schema(data_type), - ))) + MaterializedCteScan::new(id, "c", schema(data_type)).into() } #[test] @@ -730,6 +1030,44 @@ mod tests { Ok(()) } + #[test] + fn map_inputs_mut_rejects_a_body_with_other_columns() -> Result<()> { + let id = MaterializedCteId::next(); + let mut cte = MaterializedCte::try_new( + id, + "c", + body(DataType::Int32), + Arc::new(scan(id, DataType::Int32)), + )?; + assert!(!cte.map_inputs_mut(|_| Ok(false))?); + + // A new body with the same names and types is accepted. + let mut visited = 0; + assert!(cte.map_inputs_mut(|input| { + visited += 1; + if visited == 1 { + *input = LogicalPlan::clone(&body(DataType::Int32)); + } + Ok(visited == 1) + })?); + assert_eq!(visited, 2); + + let err = cte + .map_inputs_mut(|input| { + if matches!(input, LogicalPlan::EmptyRelation(_)) { + *input = LogicalPlan::clone(&body(DataType::Utf8)); + } + Ok(true) + }) + .unwrap_err(); + assert!( + err.to_string() + .contains("The body of the materialized CTE c changed its columns"), + "{err}" + ); + Ok(()) + } + #[test] fn check_invariants_rejects_a_scan_that_does_not_match_the_body() -> Result<()> { use crate::logical_plan::InvariantLevel; @@ -740,13 +1078,14 @@ mod tests { body(DataType::Int32), Arc::new(scan(id, DataType::Int32)), )?; - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte.clone())) - .check_invariants(InvariantLevel::Executable)?; + LogicalPlan::from(cte.clone()).check_invariants(InvariantLevel::Executable)?; - // `with_new_inputs` does not check the scans, so a rule can build + // `with_new_exprs` 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))); + let invalid = cte.with_new_inputs_unchecked( + body(DataType::Int32), + Arc::new(scan(id, DataType::Utf8)), + ); let invalid = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(invalid)); let err = invalid .check_invariants(InvariantLevel::Executable) @@ -762,6 +1101,109 @@ mod tests { Ok(()) } + /// Build a node without the checks of `try_new`. + fn unchecked( + id: MaterializedCteId, + cte: LogicalPlan, + continuation: LogicalPlan, + ) -> LogicalPlan { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte { + id, + name: "c".to_string(), + cte: Arc::new(cte), + continuation: Arc::new(continuation), + })) + } + + fn assert_out_of_scope(plan: &LogicalPlan) { + use crate::logical_plan::InvariantLevel; + let err = plan + .check_invariants(InvariantLevel::Executable) + .unwrap_err(); + assert!( + err.to_string().contains( + "A scan of the materialized CTE c is not in the continuation of the CTE" + ), + "{err}" + ); + } + + #[test] + fn check_invariants_rejects_a_scan_outside_the_continuation() -> Result<()> { + use crate::logical_plan::InvariantLevel; + let id = MaterializedCteId::next(); + let valid = || { + unchecked( + id, + (*body(DataType::Int32)).clone(), + scan(id, DataType::Int32), + ) + }; + valid().check_invariants(InvariantLevel::Executable)?; + + // In the body of its own CTE. + assert_out_of_scope(&unchecked( + id, + scan(id, DataType::Int32), + scan(id, DataType::Int32), + )); + + // Beside its CTE. + let beside = LogicalPlanBuilder::from(valid()) + .union(scan(id, DataType::Int32))? + .build()?; + assert_out_of_scope(&beside); + + // In a subquery expression above its CTE. + let above = LogicalPlan::Filter(Filter::try_new( + exists(Arc::new(scan(id, DataType::Int32))), + Arc::new(valid()), + )?); + assert_out_of_scope(&above); + + // In a subquery expression in the continuation, the scan is in scope. + let in_subquery = unchecked( + id, + (*body(DataType::Int32)).clone(), + LogicalPlan::Filter(Filter::try_new( + exists(Arc::new(scan(id, DataType::Int32))), + Arc::new(scan(id, DataType::Int32)), + )?), + ); + in_subquery.check_invariants(InvariantLevel::Executable)?; + Ok(()) + } + + #[test] + fn check_invariants_binds_a_scan_to_the_innermost_cte_with_its_id() -> Result<()> { + use crate::logical_plan::InvariantLevel; + let id = MaterializedCteId::next(); + // Two copies of one CTE, with different body types. Each scan must + // match the body of the copy whose continuation holds it. + let inner = unchecked( + id, + (*body(DataType::Utf8)).clone(), + scan(id, DataType::Utf8), + ); + unchecked(id, (*body(DataType::Int32)).clone(), inner.clone()) + .check_invariants(InvariantLevel::Executable)?; + + let wrong = unchecked( + id, + (*body(DataType::Utf8)).clone(), + scan(id, DataType::Int32), + ); + let err = unchecked(id, (*body(DataType::Int32)).clone(), wrong) + .check_invariants(InvariantLevel::Executable) + .unwrap_err(); + assert!( + err.to_string() + .contains("A scan of the materialized CTE c does not match the CTE"), + "{err}" + ); + Ok(()) + } + #[test] fn try_new_checks_the_projection_of_the_scans() -> Result<()> { let id = MaterializedCteId::next(); @@ -771,8 +1213,7 @@ mod tests { })); let scan = MaterializedCteScan::new(id, "c", wide_schema()); let narrow = scan.with_projection(&[1, 3])?; - let plan = - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(narrow.clone())); + let plan = LogicalPlan::from(narrow.clone()); assert_eq!( plan.display_indent().to_string(), "MaterializedCteScan: name=c projection=[b, d]" @@ -784,18 +1225,14 @@ mod tests { projection: Some(vec![0, 1]), ..narrow.clone() }; - let plan = Arc::new(LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - wrong, - ))); + let plan = Arc::new(LogicalPlan::from(wrong)); assert!(MaterializedCte::try_new(id, "c", Arc::clone(&body), plan).is_err()); let out_of_range = MaterializedCteScan { projection: Some(vec![1, 9]), ..narrow }; - let plan = Arc::new(LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - out_of_range, - ))); + let plan = Arc::new(LogicalPlan::from(out_of_range)); assert!(MaterializedCte::try_new(id, "c", body, plan).is_err()); Ok(()) } @@ -810,14 +1247,12 @@ mod tests { let plan = LogicalPlanBuilder::from(scan(id, DataType::Int32)) .filter(exists(Arc::new(scan(id, DataType::Int32))))? .union(scan(other, DataType::Int32))? - .union(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new( - id, - "c", - body(DataType::Int32), - Arc::new(scan(id, DataType::Int32)), - )?, - )))? + .union(LogicalPlan::from(MaterializedCte::try_new( + id, + "c", + body(DataType::Int32), + Arc::new(scan(id, DataType::Int32)), + )?))? .build()?; assert_eq!(MaterializedCteScan::find_in(&plan, id)?.len(), 2); assert_eq!(MaterializedCteScan::find_in(&plan, other)?.len(), 1); diff --git a/datafusion/expr/src/logical_plan/mod.rs b/datafusion/expr/src/logical_plan/mod.rs index 5191b78392778..cab4b55e23af1 100644 --- a/datafusion/expr/src/logical_plan/mod.rs +++ b/datafusion/expr/src/logical_plan/mod.rs @@ -50,5 +50,6 @@ pub use display::display_schema; pub use extension::{UserDefinedLogicalNode, UserDefinedLogicalNodeCore}; pub use materialized_cte::{ - MaterializedCte, MaterializedCteId, MaterializedCtePlan, MaterializedCteScan, + MaterializedCte, MaterializedCteBuilder, MaterializedCteId, MaterializedCtePlan, + MaterializedCteScan, renumber_materialized_ctes, }; diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index 8bc9be1227b49..b4eabb45dd4be 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), @@ -1233,9 +1231,11 @@ impl LogicalPlan { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { 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)), - ))) + // The scans are not checked. See the documentation of + // `materialized_cte`. + Ok(cte + .with_new_inputs_unchecked(Arc::new(body), Arc::new(continuation)) + .into()) } LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => { self.assert_no_expressions(expr)?; diff --git a/datafusion/expr/src/logical_plan/tree_node.rs b/datafusion/expr/src/logical_plan/tree_node.rs index 7b9c4586bc4d1..c9895d8607521 100644 --- a/datafusion/expr/src/logical_plan/tree_node.rs +++ b/datafusion/expr/src/logical_plan/tree_node.rs @@ -373,14 +373,12 @@ impl TreeNode for LogicalPlan { (cte, continuation) .map_elements(f)? .update_data(|(cte, continuation)| { - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte { - id, - name, - cte, - continuation, - }, - )) + LogicalPlan::from(MaterializedCte { + id, + name, + cte, + continuation, + }) }) } LogicalPlan::Statement(stmt) => match stmt { diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index faf7531496291..195f7f7c0e00d 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -47,10 +47,9 @@ use datafusion_expr::type_coercion::{ use datafusion_expr::utils::merge_schema; use datafusion_expr::{ AsOfJoin, AsOfMatch, Cast, DmlStatement, Expr, ExprSchemable, Join, Limit, - LogicalPlan, MaterializedCte, MaterializedCteId, MaterializedCtePlan, Operator, - Projection, Union, ValueOrLambda, WindowFrame, WindowFrameBound, WindowFrameUnits, - WriteOp, is_false, is_not_false, is_not_true, is_not_unknown, is_true, is_unknown, - lit, not, + LogicalPlan, MaterializedCtePlan, Operator, Projection, Union, ValueOrLambda, + WindowFrame, WindowFrameBound, WindowFrameUnits, WriteOp, is_false, is_not_false, + is_not_true, is_not_unknown, is_true, is_unknown, lit, not, }; /// Performs type coercion by determining the schema @@ -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)?; + let cte = cte + .with_coerced_body(body)? + .map_continuation(|continuation| { + coerce_plan_and_subqueries(continuation, config) + .map(Transformed::yes) + })? + .data; + Ok(Transformed::new(cte.into(), true, TreeNodeRecursion::Jump)) } _ => Ok(Transformed::no(plan)), }, @@ -161,40 +151,6 @@ fn coerce_plan_and_subqueries( .map(|t| t.data) } -/// Give the fields of `body_schema` to each scan of the materialized CTE `id` -/// in `continuation`, also in subquery expressions. A scan keeps its -/// qualifiers and reads only the fields of its projection. -fn with_materialized_cte_scan_schema( - continuation: LogicalPlan, - id: MaterializedCteId, - body_schema: &DFSchemaRef, -) -> Result { - continuation - .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 => - { - Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) - } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) - if scan.id == id => - { - let new_scan = scan.with_body_schema(body_schema)?; - if new_scan.schema().inner() == scan.schema().inner() { - return Ok(Transformed::no(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Scan(scan), - ))); - } - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Scan(new_scan), - ))) - } - _ => Ok(Transformed::no(node)), - }) - .map(|t| t.data) -} - /// use the external schema to handle the correlated subqueries case /// /// Assumes that children have already been optimized diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rs index 4f1b72a7dd4bf..a4979905725b7 100644 --- a/datafusion/optimizer/src/decorrelate.rs +++ b/datafusion/optimizer/src/decorrelate.rs @@ -28,8 +28,8 @@ use datafusion_expr::simplify::SimplifyContext; use datafusion_expr::utils::{collect_subquery_cols, conjunction, split_conjunction}; use datafusion_expr::{ Aggregate, BinaryExpr, Cast, Distinct, EmptyRelation, Expr, ExprSchemable, FetchType, - LogicalPlan, LogicalPlanBuilder, MaterializedCte, MaterializedCtePlan, Operator, - SkipType, Window, expr, lit, + LogicalPlan, LogicalPlanBuilder, MaterializedCtePlan, Operator, SkipType, Window, + expr, lit, }; /// This struct rewrite the sub query plan by pull up the correlated @@ -233,7 +233,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)) @@ -241,16 +241,11 @@ 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 cte = + cte.map_continuation(|continuation| continuation.rewrite(self))?; Ok(Transformed::new( - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte { - continuation: Arc::new(continuation.data), - ..cte - }, - )), - continuation.transformed, + cte.data.into(), + cte.transformed, TreeNodeRecursion::Jump, )) } diff --git a/datafusion/optimizer/src/optimize_projections/mod.rs b/datafusion/optimizer/src/optimize_projections/mod.rs index f8b997f82b964..b5d62a1632955 100644 --- a/datafusion/optimizer/src/optimize_projections/mod.rs +++ b/datafusion/optimizer/src/optimize_projections/mod.rs @@ -29,15 +29,13 @@ use datafusion_common::{ use datafusion_expr::expr::Alias; use datafusion_expr::utils::passthrough_field_index; use datafusion_expr::{ - Aggregate, Distinct, EmptyRelation, Expr, MaterializedCte, MaterializedCteScan, - Projection, TableScanBuilder, Unnest, Window, logical_plan::LogicalPlan, + Aggregate, Distinct, EmptyRelation, Expr, MaterializedCte, Projection, + TableScanBuilder, Unnest, Window, logical_plan::LogicalPlan, }; use crate::optimize_projections::required_indices::RequiredIndices; use crate::utils::NamePreserver; -use datafusion_common::tree_node::{ - Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion, -}; +use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeContainer}; /// Optimizer rule to prune unnecessary columns from intermediate schemas /// inside the [`LogicalPlan`]. This rule: @@ -286,10 +284,7 @@ fn optimize_projections( // scan reads. let new_scan = scan.with_projection(indices.indices())?; let transformed = new_scan.projection() != scan.projection(); - return Ok(Transformed::new_transformed( - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(new_scan)), - transformed, - )); + return Ok(Transformed::new_transformed(new_scan.into(), transformed)); } LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { return optimize_materialized_cte(cte, config, indices); @@ -528,85 +523,20 @@ fn optimize_materialized_cte( config: &dyn OptimizerConfig, indices: RequiredIndices, ) -> Result> { - let MaterializedCte { - id, - name, - cte: body, - continuation, - } = cte; // The output is the output of the continuation, so the continuation // needs what the parent needs. - let continuation = - optimize_projections(Arc::unwrap_or_clone(continuation), config, indices)?; - let mut transformed = continuation.transformed; - let mut continuation = continuation.data; - let mut body = Arc::unwrap_or_clone(body); - - let body_len = body.schema().fields().len(); - let scans = MaterializedCteScan::find_in(&continuation, id)?; - let mut is_read = vec![false; body_len]; - for scan in &scans { - match scan.projection() { - None => is_read.fill(true), - Some(projection) => { - for index in projection { - let Some(is_read) = is_read.get_mut(*index) else { - return internal_err!( - "A scan of the materialized CTE {name} reads the column {index}, but the CTE has {body_len} columns" - ); - }; - *is_read = true; - } - } - } - } - // A reference such as `SELECT count(*) FROM c` reads no column. Keep one - // column then, so that the body is never a projection without columns. - if !is_read.contains(&true) - && let Some(first) = is_read.first_mut() - { - *first = true; - } - let kept: Vec = (0..body_len).filter(|index| is_read[*index]).collect(); - // A CTE that nothing reads is not planned, so its body is left as it is. - if !scans.is_empty() && kept.len() < body_len { - let exprs = RequiredIndices::new_from_indices(kept.clone()) - .get_required_exprs(body.schema()); - body = Projection::try_new(exprs, Arc::new(body)).map(LogicalPlan::Projection)?; - continuation = continuation - .transform_down_with_subqueries(|node| match node { - // 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 => - { - Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) - } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) - if scan.id == id => - { - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Scan(scan.with_body_columns(&kept)?), - ))) - } - _ => Ok(Transformed::no(node)), - })? - .data; - transformed = true; - } - + let continuation = cte.map_continuation(|continuation| { + optimize_projections(continuation, config, indices) + })?; + let pruned = continuation.data.prune_body_columns()?; // All the columns that the body has now are necessary. - let body_indices = RequiredIndices::new_for_all_exprs(&body); - let body = optimize_projections(body, config, body_indices)?; - transformed |= body.transformed; + let body = pruned.data.map_body(|body| { + let indices = RequiredIndices::new_for_all_exprs(&body); + optimize_projections(body, config, indices) + })?; Ok(Transformed::new_transformed( - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte::try_new( - id, - name, - Arc::new(body.data), - Arc::new(continuation), - )?)), - transformed, + body.data.into(), + continuation.transformed || pruned.transformed || body.transformed, )) } @@ -1134,9 +1064,9 @@ mod tests { Column, DFSchema, DFSchemaRef, JoinType, Result, ScalarValue, TableReference, }; use datafusion_expr::ExprFunctionExt; + use datafusion_expr::logical_plan::InvariantLevel; use datafusion_expr::{ - BinaryExpr, Expr, Extension, Like, LogicalPlan, MaterializedCte, - MaterializedCteId, MaterializedCtePlan, MaterializedCteScan, Operator, + BinaryExpr, Expr, Extension, Like, LogicalPlan, MaterializedCteBuilder, Operator, Projection, UserDefinedLogicalNodeCore, WindowFunctionDefinition, binary_expr, build_join_schema, builder::table_scan_with_filters, @@ -3036,32 +2966,21 @@ mod tests { /// `WITH w AS MATERIALIZED (test), x AS MATERIALIZED (SELECT a, b FROM w) /// SELECT a FROM x UNION ALL SELECT c FROM w` fn nested_materialized_ctes() -> Result { - let w = MaterializedCteId::next(); - let x = MaterializedCteId::next(); - let body_w = test_table_scan()?; - let scan_w = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new(w, "w", Arc::clone(body_w.schema())), - )); - let body_x = LogicalPlanBuilder::from(scan_w.clone()) + let w = MaterializedCteBuilder::new("w", test_table_scan()?); + let body_x = LogicalPlanBuilder::from(LogicalPlan::from(w.scan())) .project(vec![col("a"), col("b")])? .build()?; - let scan_x = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new(x, "x", Arc::clone(body_x.schema())), - )); - let continuation = LogicalPlanBuilder::from(scan_x) + let x = MaterializedCteBuilder::new("x", body_x); + let continuation = LogicalPlanBuilder::from(LogicalPlan::from(x.scan())) .project(vec![col("a")])? .union( - LogicalPlanBuilder::from(scan_w) + LogicalPlanBuilder::from(LogicalPlan::from(w.scan())) .project(vec![col("c")])? .build()?, )? .build()?; - let inner = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new(x, "x", Arc::new(body_x), Arc::new(continuation))?, - )); - Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new(w, "w", Arc::new(body_w), Arc::new(inner))?, - ))) + let inner = LogicalPlan::from(x.build(continuation)?); + Ok(w.build(inner)?.into()) } /// The body of `w` keeps the columns that its scan in the body of `x` and @@ -3089,16 +3008,8 @@ mod tests { let once = optimize(nested_materialized_ctes()?)?; let twice = optimize(once.clone())?; assert_eq!(once, twice); - // The checks of `try_new` pass for the pruned plan. - let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = &twice else { - panic!("expected a MaterializedCte, got {twice}"); - }; - MaterializedCte::try_new( - cte.id(), - cte.name(), - Arc::clone(cte.body()), - Arc::clone(cte.continuation()), - )?; + // The scans of the pruned plan match the bodies. + twice.check_invariants(InvariantLevel::Executable)?; Ok(()) } @@ -3106,17 +3017,11 @@ mod tests { /// first column. #[test] fn materialized_cte_scan_without_columns() -> Result<()> { - let id = MaterializedCteId::next(); - let body = test_table_scan()?; - let scan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new(id, "w", Arc::clone(body.schema())), - )); - let continuation = LogicalPlanBuilder::from(scan) + let w = MaterializedCteBuilder::new("w", test_table_scan()?); + let continuation = LogicalPlanBuilder::from(LogicalPlan::from(w.scan())) .aggregate(Vec::::new(), vec![count(lit(1))])? .build()?; - let plan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new(id, "w", Arc::new(body), Arc::new(continuation))?, - )); + let plan = LogicalPlan::from(w.build(continuation)?); assert_optimized_plan_equal!( plan, @r" @@ -3134,28 +3039,22 @@ mod tests { /// body from its own scans. #[test] fn materialized_cte_nested_occurrence_with_the_same_id() -> Result<()> { - let id = MaterializedCteId::next(); - let occurrence = - |column: &str, rest: Option| -> Result { - let body = test_table_scan()?; - let scan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new(id, "w", Arc::clone(body.schema())), - )); - let mut continuation = - LogicalPlanBuilder::from(scan).project(vec![col(column)])?; - if let Some(rest) = rest { - continuation = continuation.union(rest)?; - } - Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new( - id, - "w", - Arc::new(body), - Arc::new(continuation.build()?), - )?, - ))) - }; - let plan = occurrence("c", Some(occurrence("b", None)?))?; + // The inner occurrence is a clone of a plan that declares `w`. The + // outer occurrence rewrites the continuation of another clone. + let w = MaterializedCteBuilder::new("w", test_table_scan()?); + let outer_scan = LogicalPlan::from(w.scan()); + let inner_continuation = LogicalPlanBuilder::from(LogicalPlan::from(w.scan())) + .project(vec![col("b")])? + .build()?; + let inner = w.build(inner_continuation)?; + let outer = inner.clone().map_continuation(|_| { + LogicalPlanBuilder::from(outer_scan) + .project(vec![col("c")])? + .union(LogicalPlan::from(inner))? + .build() + .map(Transformed::yes) + })?; + let plan = LogicalPlan::from(outer.data); assert_optimized_plan_equal!( plan, @r" diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rs index fdf5e5bbb1bf8..1f53923fdff58 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,14 +467,8 @@ 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.map_inputs_mut(f)? } LogicalPlan::Statement(Statement::Prepare(p)) => f(Arc::make_mut(&mut p.input))?, LogicalPlan::Extension(Extension { node }) => { diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index 892941d66d6b8..2167bb2545276 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -1410,17 +1410,15 @@ impl OptimizerRule for PushDownFilter { LogicalPlan::TableScan(scan), ))) } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(mut cte)) => { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { // 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, - ))); - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Cte(cte), - ))) + let cte = cte.map_continuation(|continuation| { + Filter::try_new(filter.predicate, Arc::new(continuation)) + .map(|filter| Transformed::yes(LogicalPlan::Filter(filter))) + })?; + Ok(Transformed::yes(cte.data.into())) } // A scan reads the shared body, so the filter stays above it. scan @ LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => { diff --git a/datafusion/sql/src/cte.rs b/datafusion/sql/src/cte.rs index bc36cf0203b96..9a8a913dd5065 100644 --- a/datafusion/sql/src/cte.rs +++ b/datafusion/sql/src/cte.rs @@ -12,38 +12,16 @@ use datafusion_common::{ tree_node::{TreeNode, TreeNodeRecursion}, }; use datafusion_expr::{ - LogicalPlan, LogicalPlanBuilder, MaterializedCte, MaterializedCteId, - MaterializedCtePlan, MaterializedCteScan, TableSource, + LogicalPlan, LogicalPlanBuilder, MaterializedCteBuilder, TableSource, }; use sqlparser::ast::{CteAsMaterialized, Ident, Query, SetExpr, SetOperator, With}; -/// A `WITH x AS MATERIALIZED (...)` CTE whose body must wrap the query that -/// declared it. See [`MaterializedCte`]. -pub(crate) struct PendingMaterializedCte { - id: MaterializedCteId, - name: String, - cte: LogicalPlan, -} - -impl PendingMaterializedCte { - /// Wrap `continuation` so that its scans of this CTE read one shared result. - pub(crate) fn wrap(self, continuation: LogicalPlan) -> Result { - MaterializedCte::try_new( - self.id, - self.name, - Arc::new(self.cte), - Arc::new(continuation), - ) - .map(|cte| LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte))) - } -} - impl SqlToRel<'_, S> { pub(super) fn plan_with_clause( &self, with: With, planner_context: &mut PlannerContext, - ) -> Result> { + ) -> Result> { let is_recursive = with.recursive; let mut materialized = vec![]; // Process CTEs from top to bottom @@ -86,20 +64,9 @@ impl SqlToRel<'_, S> { // Every reference reads the shared result instead of a copy // of the body. The body is already planned, so a reference // of a recursive CTE to itself stays a work table scan. - let id = MaterializedCteId::next(); - let scan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new( - id, - cte_name.clone(), - Arc::clone(final_plan.schema()), - ), - )); - materialized.push(PendingMaterializedCte { - id, - name: cte_name.clone(), - cte: final_plan, - }); - planner_context.insert_cte(cte_name, scan); + let builder = MaterializedCteBuilder::new(cte_name.clone(), final_plan); + planner_context.insert_cte(cte_name, builder.scan().into()); + materialized.push(builder); continue; } // Export the CTE to the outer query diff --git a/datafusion/sql/src/query.rs b/datafusion/sql/src/query.rs index d68e8b80cf76a..e825dd23766cc 100644 --- a/datafusion/sql/src/query.rs +++ b/datafusion/sql/src/query.rs @@ -92,7 +92,7 @@ impl SqlToRel<'_, S> { materialized_ctes .into_iter() .rev() - .try_fold(plan, |plan, cte| cte.wrap(plan)) + .try_fold(plan, |plan, cte| cte.build(plan).map(LogicalPlan::from)) } /// Apply pipe operators to a plan 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 9621d51aa9f23..7ca3e7bf7486f 100644 --- a/docs/source/library-user-guide/upgrading/57.0.0.md +++ b/docs/source/library-user-guide/upgrading/57.0.0.md @@ -218,23 +218,51 @@ 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. +because a scan reads the columns of the body by position. Use the methods of +`MaterializedCte` below, which change the body and the scans together. 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 +`MaterializedCteScan::projection`. Narrow a scan with +`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. +The fields of `MaterializedCte` and `MaterializedCteScan` are private. Read +them with `id`, `name`, `body` and `continuation`. Build a node with +`MaterializedCteBuilder`, which allocates the id that binds the scans to the +node: + +```rust,ignore +let builder = MaterializedCteBuilder::new("c", body); +// One scan for each reference to the CTE. +let continuation = LogicalPlan::from(builder.scan()); +let plan = LogicalPlan::from(builder.build(continuation)?); +``` + +Use these methods to change a node: + +| API | What it does | +| ------------------------------------- | ------------------------------------------------------------------------------ | +| `MaterializedCte::map_continuation` | Replaces the continuation with the result of a closure. | +| `MaterializedCte::map_body` | Replaces the body with the result of a closure. The scans do not change. | +| `MaterializedCte::with_coerced_body` | Replaces the body with one that has new column types. The scans get the types. | +| `MaterializedCte::prune_body_columns` | Removes the body columns that no scan reads. The scans read the new positions. | +| `MaterializedCte::map_inputs_mut` | Calls a closure that changes the body, then the continuation, in place. | +| `renumber_materialized_ctes` | Gives each `MaterializedCte` in a plan, and its scans, a new id. | + +Each method except `map_inputs_mut` and `renumber_materialized_ctes` checks +that the scans have the names and types of the columns that they read from +the body. `map_inputs_mut` checks that the body keeps the names and types of +its columns. A new id does not change a schema. + +`LogicalPlan::with_new_exprs` and `TreeNode::map_children` replace the inputs +of a `MaterializedCte` without these checks. `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 before and +after the rules, and after each rule in debug builds, so a custom rule that does not remap the scans fails with an +error. ### Null-aware sort-merge joins add a protobuf field