diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs index 946962e2a95f8..35c1304d566df 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,6 +227,8 @@ impl DefaultPhysicalPlanner { { return Ok(plan); } + // The ids must be new for each planning run. See + // `renumber_materialized_ctes`. let renumbered = renumber_materialized_ctes(logical_plan)?; let logical_plan = renumbered.as_ref().unwrap_or(logical_plan); let plan = self @@ -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(), ); @@ -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..18b8641b9cef5 100644 --- a/datafusion/expr/src/logical_plan/invariants.rs +++ b/datafusion/expr/src/logical_plan/invariants.rs @@ -106,14 +106,7 @@ fn assert_valid_semantic_plan(plan: &LogicalPlan) -> Result<()> { fn assert_materialized_cte_scans_are_valid(plan: &LogicalPlan) -> Result<()> { 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() - )) - })?; - } + cte.check_scans()?; } Ok(TreeNodeRecursion::Continue) }) diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 4df766bae5eb8..afa2a7258e444 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,21 +183,14 @@ 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, continuation: Arc, ) -> Result { let name = name.into(); - for scan in MaterializedCteScan::find_in(&continuation, id)? { - scan.check_body_schema(cte.schema()) - .map_err(|e| { - e.context(format!( - "A scan of the materialized CTE {name} does not have the schema of the CTE" - )) - })?; - } + check_scans(id, &name, cte.schema(), &continuation)?; Ok(Self { id, name, @@ -145,15 +224,197 @@ impl MaterializedCte { self.continuation.schema() } + /// 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> { 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, + ) -> Result { + 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>, + ) -> 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 the result of `f`, give each scan the new types + /// of the columns that it reads, then replace the continuation with the + /// result of `f`. A scan keeps its qualifiers. Type coercion uses this. + /// + /// `f` must recompute the schemas of the continuation from its leaves, + /// because the new types of the scans can change the schemas above them. + /// + /// Returns an error if `f` changes a column name that a scan reads, or if + /// a scan in the new continuation does not match the new body. + pub fn coerce_inputs( + self, + mut f: impl FnMut(LogicalPlan) -> Result, + ) -> Result { + let Self { + id, + name, + cte, + continuation, + } = self; + let body = f(Arc::unwrap_or_clone(cte))?; + let continuation = Self::map_scans(id, 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) + }) + })?; + let continuation = f(Arc::unwrap_or_clone(continuation))?; + Self::try_new(id, name, Arc::new(body), Arc::new(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 mut has_scans = false; + let mut is_read = vec![false; body_len]; + visit_scans(&self.continuation, self.id, |scan| { + has_scans = true; + 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; + } + } + } + Ok(TreeNodeRecursion::Continue) + })?; + 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 !has_scans || 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) + })?; + // `with_body_columns` checked that each scan reads a kept column. + Ok(Transformed::yes(Self { + cte: Arc::new(body), + continuation, + ..self + })) + } + + /// 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 +444,56 @@ 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. +/// +/// Returns `None`, and does not clone `plan`, if it has no materialized CTE. +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(None); + } + plan.clone() + .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 + }))) + }) + .map(|t| Some(t.data)) +} + /// 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 +501,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 +517,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 +583,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 +613,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 +668,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) => { @@ -382,25 +693,58 @@ impl MaterializedCteScan { /// copied when a plan is cloned) and owns the scans below it. pub fn find_in(plan: &LogicalPlan, id: MaterializedCteId) -> Result> { let mut scans = vec![]; - plan.apply_with_subqueries(|node| match node { - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) - if cte.id == id => - { - Ok(TreeNodeRecursion::Jump) - } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) - if scan.id == id => - { - scans.push(scan.clone()); - Ok(TreeNodeRecursion::Continue) - } - _ => Ok(TreeNodeRecursion::Continue), + visit_scans(plan, id, |scan| { + scans.push(scan.clone()); + Ok(TreeNodeRecursion::Continue) })?; Ok(scans) } } /// The columns `indices` of `schema`, with their qualifiers. +/// Call `f` with each scan of the CTE `id` in `plan`, also in subquery +/// expressions, until `f` returns [`TreeNodeRecursion::Stop`]. +/// +/// The traversal does not go below a [`MaterializedCte`] with the same `id`. +/// 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. +fn visit_scans( + plan: &LogicalPlan, + id: MaterializedCteId, + mut f: impl FnMut(&MaterializedCteScan) -> Result, +) -> Result<()> { + plan.apply_with_subqueries(|node| match node { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) if cte.id == id => { + Ok(TreeNodeRecursion::Jump) + } + LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) + if scan.id == id => + { + f(scan) + } + _ => Ok(TreeNodeRecursion::Continue), + }) + .map(|_| ()) +} + +/// Returns an error if a scan of the CTE `id` in `continuation` does not have +/// the names and types of the columns of `body` that it reads. +fn check_scans( + id: MaterializedCteId, + name: &str, + body: &DFSchema, + continuation: &LogicalPlan, +) -> Result<()> { + visit_scans(continuation, id, |scan| { + scan.check_body_schema(body).map_err(|e| { + e.context(format!( + "A scan of the materialized CTE {name} does not have the schema of the CTE" + )) + })?; + Ok(TreeNodeRecursion::Continue) + }) +} + fn project_schema(schema: &DFSchema, indices: &[usize]) -> Result { let fields = indices .iter() @@ -434,6 +778,7 @@ impl PartialOrd for MaterializedCteScan { #[cfg(test)] mod tests { use super::*; + use crate::logical_plan::InvariantLevel; use crate::logical_plan::builder::LogicalPlanBuilder; use crate::{EmptyRelation, exists}; use arrow::datatypes::{DataType, Field, Schema}; @@ -460,11 +805,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,9 +1071,176 @@ mod tests { Ok(()) } + /// A body with the columns `a` and `b`, and a scan that reads only `a`. + fn cte_that_reads_a() -> Result { + let id = MaterializedCteId::next(); + let body = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation { + produce_one_row: false, + schema: wide_schema(), + })); + let scan = + MaterializedCteScan::new(id, "c", wide_schema()).with_projection(&[0])?; + MaterializedCte::try_new(id, "c", body, Arc::new(scan.into())) + } + + /// The body with only the first `n` columns of [`wide_schema`]. + fn narrow_body( + cte: &MaterializedCte, + n: usize, + data_type: DataType, + ) -> Result { + let fields = cte.body().schema().fields()[..n] + .iter() + .map(|f| Field::new(f.name(), data_type.clone(), true)) + .collect::>(); + Ok(LogicalPlan::EmptyRelation(EmptyRelation { + produce_one_row: false, + schema: Arc::new(DFSchema::try_from_qualified_schema( + "c", + &Schema::new(fields), + )?), + })) + } + + #[test] + fn map_inputs_mut_checks_the_scans_after_both_calls() -> Result<()> { + let mut cte = cte_that_reads_a()?; + let mut visited = 0; + assert!(!cte.map_inputs_mut(|_| { + visited += 1; + Ok(false) + })?); + assert_eq!(visited, 2); + + // A rule can remove the column `b`, because no scan reads it. + let mut pruned = cte.clone(); + let new_body = narrow_body(&pruned, 1, DataType::Int32)?; + let mut new_body = Some(new_body); + assert!(pruned.map_inputs_mut(|input| { + if let Some(body) = new_body.take() { + *input = body; + return Ok(true); + } + Ok(false) + })?); + assert_eq!(pruned.body().schema().fields().len(), 1); + LogicalPlan::from(pruned).check_invariants(InvariantLevel::Executable)?; + + // A rule cannot change the type of the column `a`, because a scan + // reads it. + let mut new_body = Some(narrow_body(&cte, 1, DataType::Utf8)?); + let err = cte + .map_inputs_mut(|input| { + if let Some(body) = new_body.take() { + *input = body; + } + Ok(true) + }) + .unwrap_err(); + assert!( + err.to_string().contains( + "A scan of the materialized CTE c does not have the schema of the CTE" + ), + "{err}" + ); + Ok(()) + } + + /// The same body changes through [`TreeNode::map_children`], which does + /// not check the scans. [`LogicalPlan::check_invariants`] gives the + /// result of [`MaterializedCte::map_inputs_mut`]. + #[test] + fn check_invariants_agrees_with_map_inputs_mut() -> Result<()> { + use datafusion_common::tree_node::TreeNode; + let cte = cte_that_reads_a()?; + let replace_body = |data_type: DataType| -> Result { + let new_body = narrow_body(&cte, 1, data_type)?; + let mut new_body = Some(new_body); + LogicalPlan::from(cte.clone()) + .map_children(|child| { + Ok(match new_body.take() { + Some(body) => Transformed::yes(body), + None => Transformed::no(child), + }) + }) + .map(|t| t.data) + }; + replace_body(DataType::Int32)?.check_invariants(InvariantLevel::Executable)?; + let err = replace_body(DataType::Utf8)? + .check_invariants(InvariantLevel::Executable) + .unwrap_err(); + assert!( + err.to_string().contains( + "A scan of the materialized CTE c does not have the schema of the CTE" + ), + "{err}" + ); + Ok(()) + } + + #[test] + fn coerce_inputs_updates_the_continuation_and_dependent_ctes() -> Result<()> { + use datafusion_common::tree_node::{TransformedResult, TreeNode}; + // c AS (a Int32), d AS (SELECT * FROM c) SELECT a FROM d + let c = + MaterializedCteBuilder::new("c", LogicalPlan::clone(&body(DataType::Int32))); + let d = MaterializedCteBuilder::new("d", c.scan().into()); + let project = LogicalPlanBuilder::from(LogicalPlan::from(d.scan())) + .project(vec![Expr::Column(Column::from( + d.scan().schema().qualified_field(0), + ))])? + .build()?; + let cte = c.build(d.build(project)?.into())?; + + fn coerce(plan: LogicalPlan) -> Result { + plan.transform_down_up( + |node| match node { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { + Ok(Transformed::new( + cte.coerce_inputs(coerce)?.into(), + true, + TreeNodeRecursion::Jump, + )) + } + LogicalPlan::EmptyRelation(_) => { + Ok(Transformed::yes(LogicalPlan::clone(&body(DataType::Int64)))) + } + node => Ok(Transformed::no(node)), + }, + |node| node.recompute_schema().map(Transformed::yes), + ) + .data() + } + let plan = LogicalPlan::from(cte.coerce_inputs(coerce)?); + plan.check_invariants(InvariantLevel::Executable)?; + assert_eq!(plan.schema().field(0).data_type(), &DataType::Int64); + Ok(()) + } + + #[test] + fn coerce_inputs_consumes_a_uniquely_owned_body() -> Result<()> { + let c = MaterializedCteBuilder::new( + "c", + LogicalPlanBuilder::from(LogicalPlan::clone(&body(DataType::Int32))) + .limit(0, Some(1))? + .build()?, + ); + let scan = c.scan(); + let mut is_body = true; + c.build(scan.into())?.coerce_inputs(|plan| { + if std::mem::take(&mut is_body) { + let LogicalPlan::Limit(limit) = &plan else { + panic!("expected a limit: {plan}") + }; + assert_eq!(Arc::strong_count(&limit.input), 1); + } + Ok(plan) + })?; + Ok(()) + } + #[test] fn check_invariants_rejects_a_scan_that_does_not_match_the_body() -> Result<()> { - use crate::logical_plan::InvariantLevel; let id = MaterializedCteId::next(); let cte = MaterializedCte::try_new( id, @@ -740,20 +1248,22 @@ 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) .unwrap_err(); assert!( - err.to_string() - .contains("A scan of the materialized CTE c does not match the CTE"), + err.to_string().contains( + "A scan of the materialized CTE c does not have the schema of the CTE" + ), "{err}" ); @@ -771,8 +1281,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 +1293,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 +1315,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..fa8d9f27cebaf 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 @@ -128,25 +127,9 @@ 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 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, - )) + let cte = + cte.coerce_inputs(|plan| coerce_plan_and_subqueries(plan, config))?; + Ok(Transformed::new(cte.into(), true, TreeNodeRecursion::Jump)) } _ => Ok(Transformed::no(plan)), }, @@ -161,40 +144,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 efbfa00776743..67aec73c49313 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 @@ -238,7 +238,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)) @@ -246,16 +246,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 7b90380a3cb9b..2b6503be6119d 100644 --- a/docs/source/library-user-guide/upgrading/57.0.0.md +++ b/docs/source/library-user-guide/upgrading/57.0.0.md @@ -237,23 +237,63 @@ 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`, which were public in +56.0.0, are private. Replace the 56.0.0 API as follows: + +| 56.0.0 | 57.0.0 | +| --------------------------------------------------------------------------------- | ---------------------------------------------- | +| Read a field of `MaterializedCte` | `id()`, `name()`, `body()`, `continuation()` | +| Read a field of `MaterializedCteScan` | `id()`, `name()`, `schema()` | +| `MaterializedCteId::next`, `MaterializedCteScan::new`, `MaterializedCte::try_new` | `MaterializedCteBuilder::new`, `scan`, `build` | +| `MaterializedCte::with_new_inputs`, struct update | A method in the table below | + +`MaterializedCte::scans` and `MaterializedCteScan::find_in` do not change. + +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::coerce_inputs` | Replaces the body, gives its new types to the scans, then replaces the continuation. | +| `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 `renumber_materialized_ctes` checks that the scans have +the names and types of the columns that they read from the body. +`map_inputs_mut` does this check after both calls of the closure, so a rule +can remove a column of the body that no scan reads. 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