diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index d3410dc1da8e3..266fb9f1c0f85 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -1652,6 +1652,28 @@ config_namespace! { /// past window functions, if possible pub enable_window_limits: bool, default = true + /// When set to true, the SQL planner plans each non-recursive CTE that + /// has no `MATERIALIZED` or `NOT MATERIALIZED` directive as a + /// materialized CTE, and the optimizer rule `inline_automatic_ctes` + /// decides which of them stay materialized. A CTE stays materialized, + /// and is computed one time, when it has more than one reference and + /// its body is more than projections and filters on one table, and no + /// `LIMIT` is above all of its references. A CTE + /// with a volatile body is inlined, unless + /// `automatic_cte_materialization_keeps_volatile` is true. All other + /// CTEs are inlined at each reference. + /// When set to false, a CTE is materialized only with `AS MATERIALIZED`. + pub enable_automatic_cte_materialization: bool, default = false + + /// When set to true, together with + /// `enable_automatic_cte_materialization`, a CTE with a volatile body + /// and more than one reference stays materialized, so that each + /// reference reads the same rows. PostgreSQL and DuckDB do the same. + /// When set to false, such a CTE is inlined at each reference, and + /// each reference evaluates the volatile expressions again, as with + /// `enable_automatic_cte_materialization` set to false. + pub automatic_cte_materialization_keeps_volatile: bool, default = false + /// When set to true, the optimizer will replace /// Filter(rn<=K) → Window(ROW_NUMBER, RANK or DENSE_RANK) → Sort /// patterns with a PartitionedTopKExec that keeps only the top K rows diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs index 35c1304d566df..ac4ee6fac6785 100644 --- a/datafusion/core/src/physical_planner.rs +++ b/datafusion/core/src/physical_planner.rs @@ -83,8 +83,8 @@ 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, MaterializedCtePlan, Operator, RecursiveQuery, Show, ShowKind, - SkipType, StringifiedPlan, WindowFrame, WindowFrameBound, WriteOp, + Filter, JoinType, MaterializedCteId, MaterializedCtePlan, Operator, RecursiveQuery, + Show, ShowKind, SkipType, StringifiedPlan, WindowFrame, WindowFrameBound, WriteOp, renumber_materialized_ctes, }; use datafusion_physical_expr::aggregate::{ @@ -238,6 +238,47 @@ impl DefaultPhysicalPlanner { } } +/// The body of the automatic [`MaterializedCte`](datafusion_expr::MaterializedCte) with this id is unbounded, so +/// the CTE must be inlined. This error does not reach the user: +/// `create_initial_plan` handles it. +#[derive(Debug)] +struct UnboundedAutomaticCte(MaterializedCteId); + +impl std::fmt::Display for UnboundedAutomaticCte { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "The automatic materialized CTE {} reads an unbounded source", + self.0 + ) + } +} + +impl std::error::Error for UnboundedAutomaticCte {} + +/// Replace each occurrence of the [`MaterializedCte`](datafusion_expr::MaterializedCte) `id` in `plan` with its +/// continuation, in which each scan is a copy of the body. A copy of the body +/// can hold another materialized CTE, so the CTEs get new ids. +fn inline_materialized_cte( + plan: &LogicalPlan, + id: MaterializedCteId, +) -> Result { + let inlined = plan + .clone() + .transform_up_with_subqueries(|node| match node { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) + if cte.id() == id => + { + Ok(Transformed::yes(cte.inline()?)) + } + _ => Ok(Transformed::no(node)), + })?; + if !inlined.transformed { + return internal_err!("The materialized CTE {id} is not in the plan"); + } + Ok(renumber_materialized_ctes(&inlined.data)?.unwrap_or(inlined.data)) +} + /// Points every [`MaterializedCteScanExec`] at the buffer of the /// [`MaterializedCteExec`] with the same id, and gives it the statistics of /// the CTE body. @@ -501,6 +542,38 @@ impl DefaultPhysicalPlanner { &'a self, logical_plan: &'a LogicalPlan, session_state: &'a dyn Session, + ) -> BoxFuture<'a, Result>> { + Box::pin(async move { + // An automatic materialized CTE with an unbounded body cannot be + // buffered. The user did not ask for materialization, so inline + // the CTE and plan again. Each round removes one CTE. + let mut inlined: Option = None; + loop { + let plan = inlined.as_ref().unwrap_or(logical_plan); + let result = self.create_initial_plan_once(plan, session_state).await; + let id = match &result { + Err(e) => match e.find_root() { + DataFusionError::External(e) => { + e.downcast_ref::().map(|e| e.0) + } + _ => None, + }, + Ok(_) => None, + }; + let Some(id) = id else { + return result; + }; + inlined = Some(inline_materialized_cte(plan, id)?); + } + }) + } + + /// Plans `logical_plan` and its uncorrelated scalar subqueries. See + /// [`Self::create_initial_plan`]. + fn create_initial_plan_once<'a>( + &'a self, + logical_plan: &'a LogicalPlan, + session_state: &'a dyn Session, ) -> BoxFuture<'a, Result>> { Box::pin(async move { // When `enable_physical_uncorrelated_scalar_subquery` is disabled, the @@ -1973,6 +2046,13 @@ impl DefaultPhysicalPlanner { // The body is fully buffered before a scan yields a row, so an // unbounded body would never produce output. if body.boundedness().is_unbounded() { + // The user did not ask for this CTE to be materialized. + // `create_initial_plan` inlines it and plans again. + if cte.is_automatic() { + return Err(DataFusionError::External(Box::new( + UnboundedAutomaticCte(cte.id()), + ))); + } return plan_err!( "MATERIALIZED CTE {} reads an unbounded source, which cannot be materialized", cte.name() diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 0967137147a0b..b691d219b270e 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -104,6 +104,12 @@ pub struct MaterializedCte { pub(crate) cte: Arc, /// The query that declared the CTE and reads it pub(crate) continuation: Arc, + /// `false` when the query asked for this node with `AS MATERIALIZED`. + /// `true` when the planner created the node without a directive from the + /// user (see `datafusion.optimizer.enable_automatic_cte_materialization`). + /// The optimizer can replace an automatic node with [`Self::inline`], and + /// never does that for an explicit node. + pub(crate) automatic: bool, } /// Builds a [`MaterializedCte`]: the body first, then one @@ -134,6 +140,7 @@ pub struct MaterializedCteBuilder { id: MaterializedCteId, name: String, body: Arc, + automatic: bool, } impl MaterializedCteBuilder { @@ -143,9 +150,22 @@ impl MaterializedCteBuilder { id: MaterializedCteId::next(), name: name.into(), body: Arc::new(body), + automatic: false, } } + /// Mark the node as automatic or explicit. See + /// [`MaterializedCte::is_automatic`]. + pub fn with_automatic(mut self, automatic: bool) -> Self { + self.automatic = automatic; + self + } + + /// Returns `true` when the node will be automatic. + pub fn is_automatic(&self) -> bool { + self.automatic + } + /// 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 { @@ -163,6 +183,7 @@ impl MaterializedCteBuilder { /// 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)) + .map(|cte| cte.with_automatic(self.automatic)) } } @@ -197,9 +218,102 @@ impl MaterializedCte { name, cte, continuation, + automatic: false, }) } + /// Mark this node as automatic or explicit. See [`Self::is_automatic`]. + pub fn with_automatic(mut self, automatic: bool) -> Self { + self.automatic = automatic; + self + } + + /// Returns `true` when the user did not ask for this node with `AS + /// MATERIALIZED`, so the optimizer is free to inline it. + pub fn is_automatic(&self) -> bool { + self.automatic + } + + /// Return the continuation with a copy of the body in place of each scan + /// of this CTE, also in subquery expressions. The result does not contain + /// this node, and computes the body once for each scan. + /// + /// Each copy has the schema of the scan that it replaces, so the parents + /// of the scans stay valid. A copy for a scan with a + /// [`projection`](MaterializedCteScan::projection) outputs only the + /// columns that the scan reads. + pub fn inline(&self) -> Result { + let id = self.id; + self.continuation + .as_ref() + .clone() + .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 => + { + Ok(Transformed::new( + self.body_with_schema_of(&scan)?, + true, + TreeNodeRecursion::Jump, + )) + } + _ => Ok(Transformed::no(node)), + }) + .map(|t| t.data) + } + + /// Return a copy of the body that outputs the columns that `scan` reads, + /// with the qualified column names of `scan`. + fn body_with_schema_of(&self, scan: &MaterializedCteScan) -> Result { + let body = self.cte.as_ref().clone(); + let body_schema = body.schema(); + let body_len = body_schema.fields().len(); + // The positions of the columns of the body that the scan outputs. + let indices: Vec = match scan.projection() { + Some(projection) => projection.to_vec(), + None => (0..body_len).collect(), + }; + if indices.len() != scan.schema.fields().len() + || indices.iter().any(|index| *index >= body_len) + { + return internal_err!( + "A scan of the materialized CTE {} does not match the {body_len} columns of the CTE", + self.name + ); + } + let same_columns = indices.iter().copied().eq(0..body_len) + && scan + .schema + .iter() + .zip(body_schema.iter()) + .all(|((sq, sf), (bq, bf))| sq == bq && sf.name() == bf.name()); + if same_columns { + return Ok(body); + } + // The scan reads a subset of the columns, or a rule changed the names + // of the body after the scan was created. + let exprs = indices + .iter() + .zip(scan.schema.iter()) + .map(|(index, (sq, sf))| { + let (bq, bf) = body_schema.qualified_field(*index); + let column = Expr::Column(Column::from((bq, bf))); + if sq == bq && sf.name() == bf.name() { + column + } else { + column.alias_qualified(sq.cloned(), sf.name()) + } + }) + .collect(); + Projection::try_new(exprs, Arc::new(body)).map(LogicalPlan::Projection) + } + /// The id that binds the scans in the continuation to this node. pub fn id(&self) -> MaterializedCteId { self.id @@ -265,9 +379,12 @@ impl MaterializedCte { name, cte, continuation, + automatic, } = self; - f(Arc::unwrap_or_clone(continuation))? - .map_data(|continuation| Self::try_new(id, name, cte, Arc::new(continuation))) + f(Arc::unwrap_or_clone(continuation))?.map_data(|continuation| { + Self::try_new(id, name, cte, Arc::new(continuation)) + .map(|cte| cte.with_automatic(automatic)) + }) } /// Replace the body with the result of `f`. The scans do not change. @@ -283,9 +400,12 @@ impl MaterializedCte { name, cte, continuation, + automatic, } = self; - f(Arc::unwrap_or_clone(cte))? - .map_data(|cte| Self::try_new(id, name, Arc::new(cte), continuation)) + f(Arc::unwrap_or_clone(cte))?.map_data(|cte| { + Self::try_new(id, name, Arc::new(cte), continuation) + .map(|cte| cte.with_automatic(automatic)) + }) } /// Replace the body with the result of `f`, give each scan the new types @@ -306,6 +426,7 @@ impl MaterializedCte { name, cte, continuation, + automatic, } = self; let body = f(Arc::unwrap_or_clone(cte))?; let continuation = Self::map_scans(id, continuation, |scan| { @@ -318,6 +439,7 @@ impl MaterializedCte { })?; let continuation = f(Arc::unwrap_or_clone(continuation))?; Self::try_new(id, name, Arc::new(body), Arc::new(continuation)) + .map(|cte| cte.with_automatic(automatic)) } /// Remove from the body the columns that no scan of this CTE reads. The @@ -418,6 +540,7 @@ impl MaterializedCte { name: self.name.clone(), cte, continuation, + automatic: self.automatic, } } } @@ -810,6 +933,7 @@ mod tests { name: "c".to_string(), cte: empty(false), continuation: empty(false), + automatic: false, }; let mut b = a.clone(); assert_eq!(a.partial_cmp(&b), Some(Ordering::Equal)); @@ -1323,4 +1447,75 @@ mod tests { ); Ok(()) } + + #[test] + fn inline_replaces_the_scans_and_keeps_their_schema() -> Result<()> { + let id = MaterializedCteId::next(); + // The scan in the subquery expression has another qualifier than the + // body, so its copy of the body gets a projection. + let other_schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]); + let other = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( + MaterializedCteScan::new( + id, + "c", + Arc::new(DFSchema::try_from_qualified_schema("d", &other_schema)?), + ), + )); + let continuation = LogicalPlanBuilder::from(scan(id, DataType::Int32)) + .filter(exists(Arc::new(other)))? + .build()?; + let cte = MaterializedCte::try_new( + id, + "c", + body(DataType::Int32), + Arc::new(continuation), + )? + .with_automatic(true); + assert!(cte.is_automatic()); + assert_eq!( + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte.clone())) + .display_indent() + .to_string() + .lines() + .next(), + Some("MaterializedCte: name=c, automatic=true") + ); + + let inlined = cte.inline()?; + assert_eq!(inlined.schema(), cte.schema()); + assert!(MaterializedCteScan::find_in(&inlined, id)?.is_empty()); + assert_eq!( + inlined.display_indent().to_string(), + "Filter: EXISTS ()\ + \n Subquery:\ + \n Projection: c.a AS a\ + \n EmptyRelation: rows=0\ + \n EmptyRelation: rows=0" + ); + Ok(()) + } + + #[test] + fn inline_applies_the_projection_of_a_scan() -> Result<()> { + let builder = MaterializedCteBuilder::new( + "c", + LogicalPlan::EmptyRelation(EmptyRelation { + produce_one_row: false, + schema: wide_schema(), + }), + ); + // The scan reads the columns 2 and 0 of the body, in this order. + let scan = builder.scan().with_projection(&[2, 0])?; + let expected_schema = Arc::clone(scan.schema()); + let cte = builder.build(LogicalPlan::from(scan))?; + + let inlined = cte.inline()?; + assert_eq!(inlined.schema(), &expected_schema); + assert_eq!( + inlined.display_indent().to_string(), + "Projection: c.c, c.a\ + \n EmptyRelation: rows=0" + ); + Ok(()) + } } diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index efcce332fd6fe..2905f5620cc14 100644 --- a/datafusion/expr/src/logical_plan/plan.rs +++ b/datafusion/expr/src/logical_plan/plan.rs @@ -2518,9 +2518,15 @@ impl LogicalPlan { LogicalPlan::Union(_) => write!(f, "Union"), LogicalPlan::Extension(e) => e.node.fmt_for_explain(f), LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte { name, .. }, + MaterializedCte { + name, automatic, .. + }, )) => { - write!(f, "MaterializedCte: name={name}") + write!(f, "MaterializedCte: name={name}")?; + if *automatic { + write!(f, ", automatic=true")?; + } + Ok(()) } LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) => { write!(f, "MaterializedCteScan: name={}", scan.name())?; diff --git a/datafusion/expr/src/logical_plan/tree_node.rs b/datafusion/expr/src/logical_plan/tree_node.rs index c9895d8607521..6a0481aea8c6f 100644 --- a/datafusion/expr/src/logical_plan/tree_node.rs +++ b/datafusion/expr/src/logical_plan/tree_node.rs @@ -369,6 +369,7 @@ impl TreeNode for LogicalPlan { name, cte, continuation, + automatic, })) => { (cte, continuation) .map_elements(f)? @@ -378,6 +379,7 @@ impl TreeNode for LogicalPlan { name, cte, continuation, + automatic, }) }) } diff --git a/datafusion/optimizer/src/inline_automatic_ctes.rs b/datafusion/optimizer/src/inline_automatic_ctes.rs new file mode 100644 index 0000000000000..dfc846479d609 --- /dev/null +++ b/datafusion/optimizer/src/inline_automatic_ctes.rs @@ -0,0 +1,664 @@ +// SPDX-License-Identifier: Apache-2.0 +// 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 + +//! [`InlineAutomaticCtes`] inlines the automatic materialized CTEs for which +//! materialization is not expected to help. + +use datafusion_common::Result; +use datafusion_common::tree_node::{Transformed, TreeNodeRecursion}; +use datafusion_expr::logical_plan::FetchType; +use datafusion_expr::{ + LogicalPlan, MaterializedCte, MaterializedCtePlan, renumber_materialized_ctes, +}; + +use crate::{OptimizerConfig, OptimizerRule}; + +/// Decides, for each automatic [`MaterializedCte`], if the CTE stays +/// materialized or is inlined at each reference. +/// +/// With `datafusion.optimizer.enable_automatic_cte_materialization`, the SQL +/// planner creates an automatic [`MaterializedCte`] for each CTE that has no +/// `MATERIALIZED` or `NOT MATERIALIZED` directive. Materialization computes +/// the body one time, but it buffers the full output of the body, and it stops +/// the pushdown of the filters and projections of each reference into the +/// body. This rule replaces the node with [`MaterializedCte::inline`] when one +/// of these conditions is true: +/// +/// 1. The CTE has zero or one reference. A scan in a subquery expression or +/// in the body of another CTE is a reference. +/// 2. The body has a volatile expression, and +/// `datafusion.optimizer.automatic_cte_materialization_keeps_volatile` is +/// false. Each reference of an inlined CTE evaluates such an expression +/// again, so the result is the same as with automatic materialization off. +/// When the option is true, a volatile body with more than one reference +/// stays materialized and each reference reads the same rows, as in +/// PostgreSQL and DuckDB. The conditions 4 and 5 do not apply to it. +/// 3. The body has an outer reference. Such a body cannot be computed one +/// time. +/// 4. The body is cheap: it has only projections, filters and aliases on one +/// table scan, materialized CTE scan, `VALUES` list or empty relation, and +/// it has no subquery expression. To compute such a body again costs +/// about the same as to read it from the buffer, and the inlined copies +/// get filter and projection pushdown. +/// 5. A `LIMIT` with a fetch is above all references. The rule follows the +/// nodes with one input from the root of the continuation down, and it +/// stops at a node with a subquery expression. A materialized body is +/// computed completely before a reference reads a row, so the limit +/// cannot stop it early. An inlined copy stops when the limit has its +/// rows. A limit above only some references, for example above one side +/// of a join, does not inline the CTE, because the other references read +/// the full body. A limit in the body does not count. A limit does not +/// count when a sort, an aggregate, a window or another node that reads +/// all of its input is between the limit and the references, as in +/// `ORDER BY x LIMIT 1`. A sort with a fetch (TopK) does not count for the +/// same reason. DuckDB also follows only the chain of nodes with one +/// input, but it also counts TopK. +/// +/// In all other cases the CTE stays materialized. The rule does not use +/// statistics or a cost model. +/// +/// A node from `AS MATERIALIZED` is not automatic and is never changed. +/// +/// The rule decides the innermost CTE first. A later CTE of a `WITH` clause is +/// nested in the continuation of an earlier one, so when a later CTE that +/// reads an earlier CTE is inlined, the earlier CTE is decided with the new +/// number of references. +/// +/// A body can hold another [`MaterializedCte`]. Each inlined copy of such a +/// body is a separate occurrence of that CTE, so the rule gives the +/// materialized CTEs new ids after it inlines a CTE. +#[derive(Default, Debug)] +pub struct InlineAutomaticCtes; + +impl InlineAutomaticCtes { + #[expect(missing_docs)] + pub fn new() -> Self { + Self {} + } +} + +impl OptimizerRule for InlineAutomaticCtes { + fn name(&self) -> &str { + "inline_automatic_ctes" + } + + fn rewrite( + &self, + plan: LogicalPlan, + config: &dyn OptimizerConfig, + ) -> Result> { + // Most plans have no automatic CTE. Do not rebuild them. + if !has_automatic_cte(&plan)? { + return Ok(Transformed::no(plan)); + } + let keep_volatile = config + .options() + .optimizer + .automatic_cte_materialization_keeps_volatile; + let plan = plan.transform_up_with_subqueries(|node| match node { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) + if cte.is_automatic() && should_inline(&cte, keep_volatile)? => + { + Ok(Transformed::yes(cte.inline()?)) + } + _ => Ok(Transformed::no(node)), + })?; + if !plan.transformed { + return Ok(plan); + } + plan.transform_data(|plan| { + Ok(match renumber_materialized_ctes(&plan)? { + Some(renumbered) => Transformed::yes(renumbered), + None => Transformed::no(plan), + }) + }) + } +} + +fn has_automatic_cte(plan: &LogicalPlan) -> Result { + let mut found = false; + plan.apply_with_subqueries(|node| { + if matches!(node, LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) if cte.is_automatic()) { + found = true; + return Ok(TreeNodeRecursion::Stop); + } + Ok(TreeNodeRecursion::Continue) + })?; + Ok(found) +} + +/// See the conditions on [`InlineAutomaticCtes`]. +fn should_inline(cte: &MaterializedCte, keep_volatile: bool) -> Result { + let body = cte.body(); + if cte.scans()?.len() <= 1 || !body.all_out_ref_exprs().is_empty() { + return Ok(true); + } + // The option decides for a volatile body. A cheap body or a limit must + // not inline a volatile body that the user wants to keep materialized. + if is_volatile(body)? { + return Ok(!keep_volatile); + } + Ok(is_cheap(body) || has_limit_above_all_references(cte.continuation())?) +} + +/// Returns `true` if a `LIMIT` with a fetch can stop all references early. +/// +/// The function follows the chain of nodes with one input that starts at +/// `plan`. The chain ends at a node with a subquery expression, or at a node +/// that does not have exactly one input, for example a join. The result is +/// `true` if the chain has a `LIMIT` with a fetch, and only nodes that pass +/// their rows on as they read them are between that limit and the end of the +/// chain. +fn has_limit_above_all_references(mut plan: &LogicalPlan) -> Result { + let mut under_limit = false; + loop { + match plan { + LogicalPlan::Limit(limit) + if matches!(limit.get_fetch_type()?, FetchType::Literal(Some(_))) => + { + under_limit = true; + } + LogicalPlan::Limit(_) + | LogicalPlan::Projection(_) + | LogicalPlan::Filter(_) + | LogicalPlan::SubqueryAlias(_) + | LogicalPlan::Repartition(_) + | LogicalPlan::Unnest(_) => {} + // All other nodes can read all of their input before they output + // a row (sort, aggregate, window, distinct), so a limit above + // them does not stop the references early. + _ if plan.inputs().len() == 1 => under_limit = false, + _ => {} + } + match plan.inputs().as_slice() { + [input] if !has_subquery_expr(plan) => plan = input, + _ => return Ok(under_limit), + } + } +} + +/// Returns `true` if `plan` has a volatile expression, also in a subquery. +fn is_volatile(plan: &LogicalPlan) -> Result { + let mut volatile = false; + plan.apply_with_subqueries(|node| { + node.apply_expressions(|expr| { + if expr.is_volatile() { + volatile = true; + return Ok(TreeNodeRecursion::Stop); + } + Ok(TreeNodeRecursion::Continue) + }) + })?; + Ok(volatile) +} + +/// Returns `true` if `plan` is only projections, filters and aliases, without +/// subquery expressions, on one leaf that reads rows which already exist. +fn is_cheap(plan: &LogicalPlan) -> bool { + match plan { + LogicalPlan::Projection(_) + | LogicalPlan::Filter(_) + | LogicalPlan::SubqueryAlias(_) => { + !has_subquery_expr(plan) && is_cheap(plan.inputs()[0]) + } + LogicalPlan::TableScan(_) + | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) + | LogicalPlan::Values(_) + | LogicalPlan::EmptyRelation(_) => !has_subquery_expr(plan), + _ => false, + } +} + +fn has_subquery_expr(plan: &LogicalPlan) -> bool { + let mut found = false; + plan.apply_subqueries(|_| { + found = true; + Ok(TreeNodeRecursion::Stop) + }) + .expect("subquery traversal is infallible"); + found +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::assert_optimized_plan_eq_snapshot; + use crate::test::test_table_scan; + use crate::test::udfs::PlacementTestUDF; + use crate::{Optimizer, OptimizerContext, OptimizerRule}; + use datafusion_common::config::ConfigOptions; + use datafusion_expr::logical_plan::builder::LogicalPlanBuilder; + use datafusion_expr::{ + Expr, JoinType, MaterializedCteBuilder, ScalarUDF, Volatility, col, in_subquery, + lit, + }; + use datafusion_functions_aggregate::expr_fn::sum; + + macro_rules! assert_optimized_plan_equal { + ($plan:expr, @ $expected:literal $(,)?) => {{ + let optimizer_ctx = OptimizerContext::new().with_max_passes(1); + let rules: Vec> = + vec![Arc::new(InlineAutomaticCtes::new())]; + assert_optimized_plan_eq_snapshot!(optimizer_ctx, rules, $plan, @ $expected,) + }}; + } + + /// A CTE named `name` with the body `body`. `continuation` builds the + /// query from a function that returns a scan of the CTE with an alias. + fn cte( + name: &str, + body: LogicalPlan, + automatic: bool, + continuation: impl FnOnce(&dyn Fn(&str) -> Result) -> Result, + ) -> Result { + let body = LogicalPlanBuilder::from(body).alias(name)?.build()?; + let builder = MaterializedCteBuilder::new(name, body).with_automatic(automatic); + let scan = |alias: &str| { + LogicalPlanBuilder::from(LogicalPlan::from(builder.scan())) + .alias(alias)? + .build() + }; + let continuation = continuation(&scan)?; + Ok(LogicalPlan::from(builder.build(continuation)?)) + } + + /// Run the rule with + /// `datafusion.optimizer.automatic_cte_materialization_keeps_volatile` on. + fn optimize_keeping_volatile(plan: LogicalPlan) -> Result { + let mut options = ConfigOptions::default(); + options + .optimizer + .automatic_cte_materialization_keeps_volatile = true; + let optimizer_ctx = OptimizerContext::new_with_config_options(Arc::new(options)) + .with_max_passes(1); + let rules: Vec> = + vec![Arc::new(InlineAutomaticCtes::new())]; + Optimizer::with_rules(rules).optimize(plan, &optimizer_ctx, |_, _| {}) + } + + /// `SELECT a, sum(b) AS s FROM test GROUP BY a` + fn aggregate_body() -> Result { + LogicalPlanBuilder::from(test_table_scan()?) + .aggregate(vec![col("a")], vec![sum(col("b")).alias("s")])? + .build() + } + + /// `SELECT a, b AS s FROM test WHERE c > 1` + fn cheap_body() -> Result { + LogicalPlanBuilder::from(test_table_scan()?) + .filter(col("c").gt(lit(1u32)))? + .project(vec![col("a"), col("b").alias("s")])? + .build() + } + + /// `SELECT x.a FROM x JOIN y ON x.s = y.s` + fn self_join(scan: &dyn Fn(&str) -> Result) -> Result { + LogicalPlanBuilder::from(scan("x")?) + .join( + scan("y")?, + JoinType::Inner, + (vec!["x.s"], vec!["y.s"]), + None, + )? + .project(vec![col("x.a")])? + .build() + } + + #[test] + fn keeps_two_references_to_an_aggregate() -> Result<()> { + let plan = cte("c", aggregate_body()?, true, self_join)?; + assert_optimized_plan_equal!(plan, @" + MaterializedCte: name=c, automatic=true + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + MaterializedCteScan: name=c + SubqueryAlias: y + MaterializedCteScan: name=c + ") + } + + #[test] + fn inlines_one_reference() -> Result<()> { + let plan = cte("c", aggregate_body()?, true, |scan| { + LogicalPlanBuilder::from(scan("x")?) + .filter(col("x.a").eq(lit(1u32)))? + .build() + })?; + assert_optimized_plan_equal!(plan, @" + Filter: x.a = UInt32(1) + SubqueryAlias: x + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + ") + } + + #[test] + fn removes_a_cte_without_reference() -> Result<()> { + let plan = cte("c", aggregate_body()?, true, |_| test_table_scan())?; + assert_optimized_plan_equal!(plan, @"TableScan: test") + } + + #[test] + fn inlines_a_cheap_body() -> Result<()> { + let plan = cte("c", cheap_body()?, true, self_join)?; + assert_optimized_plan_equal!(plan, @" + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + SubqueryAlias: c + Projection: test.a, test.b AS s + Filter: test.c > UInt32(1) + TableScan: test + SubqueryAlias: y + SubqueryAlias: c + Projection: test.a, test.b AS s + Filter: test.c > UInt32(1) + TableScan: test + ") + } + + #[test] + fn keeps_a_volatile_body_with_the_option() -> Result<()> { + let volatile = ScalarUDF::new_from_impl( + PlacementTestUDF::new().with_volatility(Volatility::Volatile), + ); + let body = LogicalPlanBuilder::from(aggregate_body()?) + .project(vec![col("a"), volatile.call(vec![col("s")]).alias("s")])? + .build()?; + let plan = cte("c", body, true, self_join)?; + assert_eq!(optimize_keeping_volatile(plan.clone())?, plan); + Ok(()) + } + + #[test] + fn keeps_a_cheap_volatile_body_under_a_limit_with_the_option() -> Result<()> { + let volatile = ScalarUDF::new_from_impl( + PlacementTestUDF::new().with_volatility(Volatility::Volatile), + ); + let body = LogicalPlanBuilder::from(test_table_scan()?) + .project(vec![col("a"), volatile.call(vec![col("b")]).alias("s")])? + .build()?; + let plan = cte("c", body, true, |scan| { + LogicalPlanBuilder::from(self_join(scan)?) + .limit(0, Some(1))? + .build() + })?; + assert_eq!(optimize_keeping_volatile(plan.clone())?, plan); + Ok(()) + } + + #[test] + fn inlines_a_volatile_body() -> Result<()> { + let volatile = ScalarUDF::new_from_impl( + PlacementTestUDF::new().with_volatility(Volatility::Volatile), + ); + let body = LogicalPlanBuilder::from(aggregate_body()?) + .project(vec![col("a"), volatile.call(vec![col("s")]).alias("s")])? + .build()?; + let plan = cte("c", body, true, self_join)?; + assert_optimized_plan_equal!(plan, @" + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + SubqueryAlias: c + Projection: test.a, leaf_udf(s) AS s + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + SubqueryAlias: y + SubqueryAlias: c + Projection: test.a, leaf_udf(s) AS s + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + ") + } + + #[test] + fn never_inlines_an_explicit_cte() -> Result<()> { + // One reference and a cheap body, but the user asked for the CTE. + let plan = cte("c", cheap_body()?, false, |scan| scan("x"))?; + assert_optimized_plan_equal!(plan, @" + MaterializedCte: name=c + SubqueryAlias: c + Projection: test.a, test.b AS s + Filter: test.c > UInt32(1) + TableScan: test + SubqueryAlias: x + MaterializedCteScan: name=c + ") + } + + #[test] + fn counts_a_scan_in_a_subquery_expression() -> Result<()> { + let plan = cte("c", aggregate_body()?, true, |scan| { + let subquery = LogicalPlanBuilder::from(scan("y")?) + .project(vec![col("y.s")])? + .build()?; + LogicalPlanBuilder::from(scan("x")?) + .filter(in_subquery(col("x.s"), Arc::new(subquery)))? + .build() + })?; + assert_optimized_plan_equal!(plan, @" + MaterializedCte: name=c, automatic=true + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + Filter: x.s IN () + Subquery: + Projection: y.s + SubqueryAlias: y + MaterializedCteScan: name=c + SubqueryAlias: x + MaterializedCteScan: name=c + ") + } + + #[test] + fn counts_the_references_again_after_another_cte_is_inlined() -> Result<()> { + // `c` has one reference, in the body of `d`. `d` is cheap and has + // two references, so it is inlined, and then `c` has two references. + let plan = cte("c", aggregate_body()?, true, |scan_c| { + let body_d = LogicalPlanBuilder::from(scan_c("c")?) + .filter(col("c.s").gt(lit(1u64)))? + .build()?; + cte("d", body_d, true, self_join) + })?; + assert_optimized_plan_equal!(plan, @" + MaterializedCte: name=c, automatic=true + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + SubqueryAlias: d + Filter: c.s > UInt64(1) + SubqueryAlias: c + MaterializedCteScan: name=c + SubqueryAlias: y + SubqueryAlias: d + Filter: c.s > UInt64(1) + SubqueryAlias: c + MaterializedCteScan: name=c + ") + } + + #[test] + fn inlines_a_cte_into_the_body_of_another_cte() -> Result<()> { + // `c` has one reference, in the body of `d`, which stays materialized. + let plan = cte("c", aggregate_body()?, true, |scan_c| { + let body_d = LogicalPlanBuilder::from(scan_c("c")?) + .aggregate(vec![col("c.s")], vec![sum(col("c.a")).alias("a")])? + .build()?; + cte("d", body_d, true, self_join) + })?; + assert_optimized_plan_equal!(plan, @" + MaterializedCte: name=d, automatic=true + SubqueryAlias: d + Aggregate: groupBy=[[c.s]], aggr=[[sum(c.a) AS a]] + SubqueryAlias: c + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + MaterializedCteScan: name=d + SubqueryAlias: y + MaterializedCteScan: name=d + ") + } + + #[test] + fn inlines_under_a_limit_above_all_references() -> Result<()> { + let plan = cte("c", aggregate_body()?, true, |scan| { + LogicalPlanBuilder::from(self_join(scan)?) + .limit(0, Some(1))? + .build() + })?; + assert_optimized_plan_equal!(plan, @" + Limit: skip=0, fetch=1 + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + SubqueryAlias: y + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + ") + } + + #[test] + fn keeps_a_cte_with_a_limit_above_one_reference() -> Result<()> { + let plan = cte("c", aggregate_body()?, true, |scan| { + let limited = LogicalPlanBuilder::from(scan("x")?) + .limit(0, Some(1))? + .build()?; + LogicalPlanBuilder::from(limited) + .join( + scan("y")?, + JoinType::Inner, + (vec!["x.s"], vec!["y.s"]), + None, + )? + .project(vec![col("x.a")])? + .build() + })?; + assert_optimized_plan_equal!(plan, @" + MaterializedCte: name=c, automatic=true + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + Projection: x.a + Inner Join: x.s = y.s + Limit: skip=0, fetch=1 + SubqueryAlias: x + MaterializedCteScan: name=c + SubqueryAlias: y + MaterializedCteScan: name=c + ") + } + + #[test] + fn keeps_a_cte_with_a_topk_above_all_references() -> Result<()> { + let plan = cte("c", aggregate_body()?, true, |scan| { + LogicalPlanBuilder::from(self_join(scan)?) + .sort_with_limit(vec![col("x.a").sort(true, false)], Some(1))? + .build() + })?; + assert_optimized_plan_equal!(plan, @" + MaterializedCte: name=c, automatic=true + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + Sort: x.a ASC NULLS LAST, fetch=1 + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + MaterializedCteScan: name=c + SubqueryAlias: y + MaterializedCteScan: name=c + ") + } + + #[test] + fn keeps_a_cte_with_a_limit_in_the_body() -> Result<()> { + let body = LogicalPlanBuilder::from(aggregate_body()?) + .limit(0, Some(1))? + .build()?; + let plan = cte("c", body, true, self_join)?; + assert_optimized_plan_equal!(plan, @" + MaterializedCte: name=c, automatic=true + SubqueryAlias: c + Limit: skip=0, fetch=1 + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + MaterializedCteScan: name=c + SubqueryAlias: y + MaterializedCteScan: name=c + ") + } + + #[test] + fn keeps_a_cte_with_a_sort_between_the_limit_and_the_references() -> Result<()> { + // `ORDER BY x.a LIMIT 1`: the sort reads all of its input. + let plan = cte("c", aggregate_body()?, true, |scan| { + LogicalPlanBuilder::from(self_join(scan)?) + .sort(vec![col("x.a").sort(true, false)])? + .limit(0, Some(1))? + .build() + })?; + assert_optimized_plan_equal!(plan, @" + MaterializedCte: name=c, automatic=true + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + Limit: skip=0, fetch=1 + Sort: x.a ASC NULLS LAST + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + MaterializedCteScan: name=c + SubqueryAlias: y + MaterializedCteScan: name=c + ") + } + + #[test] + fn inlines_under_a_limit_below_an_aggregate() -> Result<()> { + // The limit is between the aggregate and the references. + let plan = cte("c", aggregate_body()?, true, |scan| { + LogicalPlanBuilder::from(self_join(scan)?) + .limit(0, Some(1))? + .aggregate(Vec::::new(), vec![sum(col("x.a"))])? + .build() + })?; + assert_optimized_plan_equal!(plan, @" + Aggregate: groupBy=[[]], aggr=[[sum(x.a)]] + Limit: skip=0, fetch=1 + Projection: x.a + Inner Join: x.s = y.s + SubqueryAlias: x + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + SubqueryAlias: y + SubqueryAlias: c + Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS s]] + TableScan: test + ") + } +} diff --git a/datafusion/optimizer/src/lib.rs b/datafusion/optimizer/src/lib.rs index 754e37000b895..4c236e150e30e 100644 --- a/datafusion/optimizer/src/lib.rs +++ b/datafusion/optimizer/src/lib.rs @@ -47,6 +47,7 @@ pub mod eliminate_outer_join; pub mod extract_equijoin_predicate; pub mod extract_leaf_expressions; pub mod filter_null_join_keys; +pub mod inline_automatic_ctes; pub mod optimize_projections; pub mod optimize_unions; pub mod optimizer; diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rs index 89961a7041b1c..d21dfea8fd9fa 100644 --- a/datafusion/optimizer/src/optimizer.rs +++ b/datafusion/optimizer/src/optimizer.rs @@ -42,6 +42,7 @@ use crate::eliminate_outer_join::EliminateOuterJoin; use crate::extract_equijoin_predicate::ExtractEquijoinPredicate; use crate::extract_leaf_expressions::{ExtractLeafExpressions, PushDownLeafProjections}; use crate::filter_null_join_keys::FilterNullJoinKeys; +use crate::inline_automatic_ctes::InlineAutomaticCtes; use crate::optimize_projections::OptimizeProjections; use crate::optimize_unions::OptimizeUnions; use crate::plan_signature::LogicalPlanSignature; @@ -245,6 +246,7 @@ impl OptimizerConfig for OptimizerContext { /// /// | rule (name in EXPLAIN plan) | struct name | summary | /// | ----------------------------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +/// | `inline_automatic_ctes` | [`InlineAutomaticCtes`] | Inlines the automatic materialized CTEs for which materialization is not expected to help. | /// | `rewrite_set_comparison` | [`RewriteSetComparison`] | Rewrites `ANY` and `ALL` subqueries into `EXISTS` expressions with SQL NULL semantics. | /// | `optimize_unions` | [`OptimizeUnions`] | Flattens nested unions and removes single-input unions. | /// | `unions_to_filter` | [`UnionsToFilter`] | Merges `UNION DISTINCT` branches over the same source into one filtered branch. | @@ -309,6 +311,7 @@ impl Optimizer { // (e.g. if the plan doesn't contain any of the nodes you are looking for // return `Transformed::no`; only works if you control the traversal). let rules: Vec> = vec![ + Arc::new(InlineAutomaticCtes::new()), Arc::new(RewriteSetComparison::new()), Arc::new(OptimizeUnions::new()), Arc::new(UnionsToFilter::new()), diff --git a/datafusion/sql/src/cte.rs b/datafusion/sql/src/cte.rs index 9a8a913dd5065..aac473f85d18f 100644 --- a/datafusion/sql/src/cte.rs +++ b/datafusion/sql/src/cte.rs @@ -23,6 +23,14 @@ impl SqlToRel<'_, S> { planner_context: &mut PlannerContext, ) -> Result> { let is_recursive = with.recursive; + // Without a directive, a CTE of a `WITH RECURSIVE` block is always + // inlined. + let automatic_enabled = !is_recursive + && self + .context_provider + .options() + .optimizer + .enable_automatic_cte_materialization; let mut materialized = vec![]; // Process CTEs from top to bottom for cte in with.cte_tables { @@ -48,8 +56,14 @@ impl SqlToRel<'_, S> { // A body that refers to an outer query would have to run once // per outer row, which is not supported. Such a CTE is inlined, // as if MATERIALIZED was not given. - let is_materialized = cte.materialized - == Some(CteAsMaterialized::Materialized) + // + // Without a directive, the CTE is planned as an automatic + // materialized CTE when the option is on, and the optimizer + // decides if it stays materialized (`InlineAutomaticCtes`). + // `NOT MATERIALIZED` always inlines the CTE here. + let automatic = cte.materialized.is_none() && automatic_enabled; + let is_materialized = (automatic + || cte.materialized == Some(CteAsMaterialized::Materialized)) && cte_plan.all_out_ref_exprs().is_empty(); let final_plan = if is_recursive { LogicalPlanBuilder::from(cte_plan) @@ -64,7 +78,8 @@ 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 builder = MaterializedCteBuilder::new(cte_name.clone(), final_plan); + let builder = MaterializedCteBuilder::new(cte_name.clone(), final_plan) + .with_automatic(automatic); planner_context.insert_cte(cte_name, builder.scan().into()); materialized.push(builder); continue; diff --git a/datafusion/sql/src/query.rs b/datafusion/sql/src/query.rs index e825dd23766cc..09939031432f3 100644 --- a/datafusion/sql/src/query.rs +++ b/datafusion/sql/src/query.rs @@ -85,14 +85,28 @@ impl SqlToRel<'_, S> { }?; let plan = self.pipe_operators(plan, pipe_operators, planner_context)?; - if !materialized_ctes.is_empty() && matches!(plan, LogicalPlan::Ddl(_)) { + if matches!(plan, LogicalPlan::Ddl(_)) + && materialized_ctes.iter().any(|cte| !cte.is_automatic()) + { return not_impl_err!("MATERIALIZED CTEs are not supported with SELECT INTO"); } // A later CTE may read an earlier one, so the first CTE is the outermost. materialized_ctes .into_iter() .rev() - .try_fold(plan, |plan, cte| cte.build(plan).map(LogicalPlan::from)) + .try_fold(plan, |plan, builder| { + let automatic = builder.is_automatic(); + let cte = builder.build(plan)?; + // A DDL statement (`SELECT INTO`) must stay the root of the + // plan, so an automatic CTE is inlined here, as if the option + // was off. + if automatic && matches!(cte.continuation().as_ref(), LogicalPlan::Ddl(_)) + { + cte.inline() + } else { + Ok(LogicalPlan::from(cte)) + } + }) } /// Apply pipe operators to a plan diff --git a/datafusion/sqllogictest/test_files/cte_auto_materialize.slt b/datafusion/sqllogictest/test_files/cte_auto_materialize.slt new file mode 100644 index 0000000000000..3b016aff56f57 --- /dev/null +++ b/datafusion/sqllogictest/test_files/cte_auto_materialize.slt @@ -0,0 +1,983 @@ +# SPDX-License-Identifier: Apache-2.0 +# 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 + +# Tests for `datafusion.optimizer.enable_automatic_cte_materialization`: the +# SQL planner plans each CTE without a directive as an automatic materialized +# CTE, and the optimizer rule `inline_automatic_ctes` decides which of them +# stay materialized. + +statement ok +CREATE TABLE t(k INT, v INT) AS VALUES (1, 10), (2, 20), (3, 30), (4, 40); + +# The option is off by default: the body runs once for each reference. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s +---- +logical_plan +01)Projection: a.k +02)--Inner Join: a.s = b.s +03)----SubqueryAlias: a +04)------SubqueryAlias: c +05)--------Projection: t.k, sum(t.v) AS s +06)----------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +07)------------TableScan: t projection=[k, v] +08)----SubqueryAlias: b +09)------SubqueryAlias: c +10)--------Projection: sum(t.v) AS s +11)----------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +12)------------TableScan: t projection=[k, v] +physical_plan +01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(s@0, s@1)], projection=[k@1] +02)--CoalescePartitionsExec +03)----ProjectionExec: expr=[sum(t.v)@1 as s] +04)------AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +05)--------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +06)----------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +07)------------DataSourceExec: partitions=1, partition_sizes=[1] +08)--ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +09)----AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +10)------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +11)--------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +12)----------DataSourceExec: partitions=1, partition_sizes=[1] + +statement ok +set datafusion.optimizer.enable_automatic_cte_materialization = true; + +# Two references to an aggregate body: the body is computed once. This is the +# default dialect, which has no MATERIALIZED keyword. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s +---- +logical_plan +01)MaterializedCte: name=c, automatic=true +02)--SubqueryAlias: c +03)----Projection: t.k, sum(t.v) AS s +04)------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +05)--------TableScan: t projection=[k, v] +06)--Projection: a.k +07)----Inner Join: a.s = b.s +08)------SubqueryAlias: a +09)--------MaterializedCteScan: name=c +10)------SubqueryAlias: b +11)--------MaterializedCteScan: name=c projection=[s] +physical_plan +01)MaterializedCteExec: name=c +02)--ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +03)----AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +04)------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +05)--------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +06)----------DataSourceExec: partitions=1, partition_sizes=[1] +07)--HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(s@0, s@1)], projection=[k@1] +08)----CoalescePartitionsExec +09)------MaterializedCteScanExec: name=c, projection=[s] +10)----MaterializedCteScanExec: name=c + +query I rowsort +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s +---- +1 +2 +3 +4 + +# One reference: the CTE is inlined, and the filter of the reference is pushed +# below the aggregate. The plan is the same as the plan with the option off. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT s FROM c WHERE k = 1 +---- +logical_plan +01)SubqueryAlias: c +02)--Projection: sum(t.v) AS s +03)----Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +04)------Filter: t.k = Int32(1) +05)--------TableScan: t projection=[k, v] +physical_plan +01)ProjectionExec: expr=[sum(t.v)@1 as s] +02)--AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +03)----RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=4 +04)------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +06)----------FilterExec: k@0 = 1 +07)------------DataSourceExec: partitions=1, partition_sizes=[1] + +statement ok +set datafusion.optimizer.enable_automatic_cte_materialization = false; + +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT s FROM c WHERE k = 1 +---- +logical_plan +01)SubqueryAlias: c +02)--Projection: sum(t.v) AS s +03)----Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +04)------Filter: t.k = Int32(1) +05)--------TableScan: t projection=[k, v] +physical_plan +01)ProjectionExec: expr=[sum(t.v)@1 as s] +02)--AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +03)----RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=4 +04)------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +06)----------FilterExec: k@0 = 1 +07)------------DataSourceExec: partitions=1, partition_sizes=[1] + +statement ok +set datafusion.optimizer.enable_automatic_cte_materialization = true; + +# No reference: the CTE is removed. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT k FROM t +---- +logical_plan TableScan: t projection=[k] +physical_plan DataSourceExec: partitions=1, partition_sizes=[1] + +# A cheap body (projections and filters on one table) is inlined for each +# reference, so the filter of each reference reaches the table scan. +query TT +EXPLAIN WITH c AS (SELECT k, v * 2 AS v2 FROM t WHERE v > 5) +SELECT k FROM c WHERE k = 1 +UNION ALL +SELECT k FROM c WHERE k = 2 +---- +logical_plan +01)Union +02)--SubqueryAlias: c +03)----Projection: t.k +04)------Filter: t.v > Int32(5) AND t.k = Int32(1) +05)--------TableScan: t projection=[k, v] +06)--SubqueryAlias: c +07)----Projection: t.k +08)------Filter: t.v > Int32(5) AND t.k = Int32(2) +09)--------TableScan: t projection=[k, v] +physical_plan +01)UnionExec +02)--FilterExec: v@1 > 5 AND k@0 = 1, projection=[k@0] +03)----DataSourceExec: partitions=1, partition_sizes=[1] +04)--FilterExec: v@1 > 5 AND k@0 = 2, projection=[k@0] +05)----DataSourceExec: partitions=1, partition_sizes=[1] + +# A volatile body is inlined: each reference evaluates random() again, as with +# the option off. Materialization would change the result from 2 to 1. +query TT +EXPLAIN WITH r AS (SELECT sum(random()) AS x FROM t) +SELECT x FROM r UNION ALL SELECT x FROM r +---- +logical_plan +01)Union +02)--SubqueryAlias: r +03)----Projection: sum(random()) AS x +04)------Aggregate: groupBy=[[]], aggr=[[sum(random())]] +05)--------TableScan: t projection=[] +06)--SubqueryAlias: r +07)----Projection: sum(random()) AS x +08)------Aggregate: groupBy=[[]], aggr=[[sum(random())]] +09)--------TableScan: t projection=[] +physical_plan +01)UnionExec +02)--ProjectionExec: expr=[sum(random())@0 as x] +03)----AggregateExec: mode=Single, gby=[], aggr=[sum(random())] +04)------DataSourceExec: partitions=1, partition_sizes=[1] +05)--ProjectionExec: expr=[sum(random())@0 as x] +06)----AggregateExec: mode=Single, gby=[], aggr=[sum(random())] +07)------DataSourceExec: partitions=1, partition_sizes=[1] + +query I +WITH r AS (SELECT sum(random()) AS x FROM t) +SELECT count(DISTINCT x) FROM (SELECT x FROM r UNION ALL SELECT x FROM r) +---- +2 + +# With automatic_cte_materialization_keeps_volatile, a volatile body stays +# materialized, as in PostgreSQL and DuckDB. Both references read the same row. +statement ok +set datafusion.optimizer.automatic_cte_materialization_keeps_volatile = true; + +query I +WITH r AS (SELECT sum(random()) AS x FROM t) +SELECT count(DISTINCT x) FROM (SELECT x FROM r UNION ALL SELECT x FROM r) +---- +1 + +statement ok +set datafusion.optimizer.automatic_cte_materialization_keeps_volatile = false; + +# A scan in a subquery expression is a reference. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT k FROM c WHERE s = (SELECT max(s) FROM c) +---- +logical_plan +01)MaterializedCte: name=c, automatic=true +02)--SubqueryAlias: c +03)----Projection: t.k, sum(t.v) AS s +04)------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +05)--------TableScan: t projection=[k, v] +06)--Projection: c.k +07)----Filter: c.s = () +08)------Subquery: +09)--------Aggregate: groupBy=[[]], aggr=[[max(c.s)]] +10)----------MaterializedCteScan: name=c projection=[s] +11)------MaterializedCteScan: name=c +physical_plan +01)ScalarSubqueryExec: subqueries=1 +02)--MaterializedCteExec: name=c +03)----ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +04)------AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +05)--------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +06)----------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +07)------------DataSourceExec: partitions=1, partition_sizes=[1] +08)----FilterExec: s@1 = scalar_subquery(), projection=[k@0] +09)------MaterializedCteScanExec: name=c +10)--AggregateExec: mode=Final, gby=[], aggr=[max(c.s)] +11)----CoalescePartitionsExec +12)------AggregateExec: mode=Partial, gby=[], aggr=[max(c.s)] +13)--------MaterializedCteScanExec: name=c, projection=[s] + +query I +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT k FROM c WHERE s = (SELECT max(s) FROM c) +---- +4 + +# A scan in the body of another CTE is a reference. `d` has one reference and +# is inlined, and then `c` has two references and stays materialized. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k), + d AS (SELECT max(s) AS m FROM c) +SELECT c.k FROM c JOIN d ON c.s = d.m +---- +logical_plan +01)MaterializedCte: name=c, automatic=true +02)--SubqueryAlias: c +03)----Projection: t.k, sum(t.v) AS s +04)------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +05)--------TableScan: t projection=[k, v] +06)--Projection: c.k +07)----Inner Join: c.s = d.m +08)------MaterializedCteScan: name=c +09)------SubqueryAlias: d +10)--------Projection: max(c.s) AS m +11)----------Aggregate: groupBy=[[]], aggr=[[max(c.s)]] +12)------------MaterializedCteScan: name=c projection=[s] +physical_plan +01)MaterializedCteExec: name=c +02)--ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +03)----AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +04)------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +05)--------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +06)----------DataSourceExec: partitions=1, partition_sizes=[1] +07)--HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(m@0, s@1)], projection=[k@1] +08)----ProjectionExec: expr=[max(c.s)@0 as m] +09)------AggregateExec: mode=Final, gby=[], aggr=[max(c.s)] +10)--------CoalescePartitionsExec +11)----------AggregateExec: mode=Partial, gby=[], aggr=[max(c.s)] +12)------------MaterializedCteScanExec: name=c, projection=[s] +13)----MaterializedCteScanExec: name=c + +query I +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k), + d AS (SELECT max(s) AS m FROM c) +SELECT c.k FROM c JOIN d ON c.s = d.m +---- +4 + +# `d` is a cheap body on `c` and is inlined at its two references. `c` has one +# reference in the query text, and two references after `d` is inlined, so it +# stays materialized. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k), + d AS (SELECT k, s FROM c WHERE s > 10) +SELECT a.k FROM d a JOIN d b ON a.s = b.s +---- +logical_plan +01)MaterializedCte: name=c, automatic=true +02)--SubqueryAlias: c +03)----Projection: t.k, sum(t.v) AS s +04)------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +05)--------TableScan: t projection=[k, v] +06)--Projection: a.k +07)----Inner Join: a.s = b.s +08)------SubqueryAlias: a +09)--------SubqueryAlias: d +10)----------Filter: c.s > Int64(10) +11)------------MaterializedCteScan: name=c +12)------SubqueryAlias: b +13)--------SubqueryAlias: d +14)----------Filter: c.s > Int64(10) +15)------------MaterializedCteScan: name=c projection=[s] +physical_plan +01)MaterializedCteExec: name=c +02)--ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +03)----AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +04)------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +05)--------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +06)----------DataSourceExec: partitions=1, partition_sizes=[1] +07)--HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(s@0, s@1)], projection=[k@1] +08)----CoalescePartitionsExec +09)------FilterExec: s@0 > 10 +10)--------MaterializedCteScanExec: name=c, projection=[s] +11)----FilterExec: s@1 > 10 +12)------MaterializedCteScanExec: name=c + +query I rowsort +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k), + d AS (SELECT k, s FROM c WHERE s > 10) +SELECT a.k FROM d a JOIN d b ON a.s = b.s +---- +2 +3 +4 + +# `c` has one reference, in the body of `d`, and is inlined into that body. +# `d` has two references and stays materialized. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k), + d AS (SELECT s, count(*) AS n FROM c GROUP BY s) +SELECT a.s FROM d a JOIN d b ON a.n = b.n +---- +logical_plan +01)MaterializedCte: name=d, automatic=true +02)--SubqueryAlias: d +03)----Projection: c.s, count(Int64(1)) AS count(*) AS n +04)------Aggregate: groupBy=[[c.s]], aggr=[[count(Int64(1))]] +05)--------SubqueryAlias: c +06)----------Projection: sum(t.v) AS s +07)------------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +08)--------------TableScan: t projection=[k, v] +09)--Projection: a.s +10)----Inner Join: a.n = b.n +11)------SubqueryAlias: a +12)--------MaterializedCteScan: name=d +13)------SubqueryAlias: b +14)--------MaterializedCteScan: name=d projection=[n] +physical_plan +01)MaterializedCteExec: name=d +02)--ProjectionExec: expr=[s@0 as s, count(Int64(1))@1 as n] +03)----AggregateExec: mode=FinalPartitioned, gby=[s@0 as s], aggr=[count(Int64(1))] +04)------RepartitionExec: partitioning=Hash([s@0], 4), input_partitions=4 +05)--------AggregateExec: mode=Partial, gby=[s@0 as s], aggr=[count(Int64(1))] +06)----------ProjectionExec: expr=[sum(t.v)@1 as s] +07)------------AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +08)--------------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +09)----------------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +10)------------------DataSourceExec: partitions=1, partition_sizes=[1] +11)--HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(n@0, n@1)], projection=[s@1] +12)----CoalescePartitionsExec +13)------MaterializedCteScanExec: name=d, projection=[n] +14)----MaterializedCteScanExec: name=d + +# Type coercion changes the type of `a` in the body from Null to Int64, and +# the scans get the new type. +query II +WITH c AS (SELECT DISTINCT a, b FROM (SELECT NULL a, 12 b UNION ALL SELECT 11 a, 13 b)) +SELECT x.a, x.b FROM c x JOIN c y ON x.a = y.a +---- +11 13 + +# A CTE in a subquery, and a CTE with a column list. +query I rowsort +SELECT k FROM t WHERE v IN ( + WITH c(x) AS (SELECT sum(v) FROM t GROUP BY k) + SELECT a.x FROM c a JOIN c b ON a.x = b.x WHERE a.x > 15 +) +---- +2 +3 +4 + +# A body that refers to the outer query is inlined by the SQL planner. +query II rowsort +SELECT k, (WITH c AS (SELECT sum(v) AS s FROM t WHERE t.k = o.k) + SELECT s FROM c) FROM t o +---- +1 10 +2 20 +3 30 +4 40 + +# A recursive CTE is planned as before. +query TT +EXPLAIN WITH RECURSIVE n AS (SELECT 1 AS i UNION ALL SELECT i + 1 FROM n WHERE i < 3) +SELECT a.i FROM n a JOIN n b ON a.i = b.i +---- +logical_plan +01)Projection: a.i +02)--Inner Join: a.i = b.i +03)----SubqueryAlias: a +04)------SubqueryAlias: n +05)--------RecursiveQuery: is_distinct=false +06)----------Projection: Int64(1) AS i +07)------------EmptyRelation: rows=1 +08)----------Projection: n.i + Int64(1) +09)------------Filter: n.i < Int64(3) +10)--------------TableScan: n projection=[i] +11)----SubqueryAlias: b +12)------SubqueryAlias: n +13)--------RecursiveQuery: is_distinct=false +14)----------Projection: Int64(1) AS i +15)------------EmptyRelation: rows=1 +16)----------Projection: n.i + Int64(1) +17)------------Filter: n.i < Int64(3) +18)--------------TableScan: n projection=[i] +physical_plan +01)HashJoinExec: mode=Partitioned, join_type=Inner, on=[(i@0, i@0)], projection=[i@0] +02)--RepartitionExec: partitioning=Hash([i@0], 4), input_partitions=1 +03)----RecursiveQueryExec: name=n, is_distinct=false +04)------ProjectionExec: expr=[CAST(1 AS Int64;N) as i] +05)--------PlaceholderRowExec +06)------CoalescePartitionsExec +07)--------ProjectionExec: expr=[i@0 + 1 as i] +08)----------FilterExec: i@0 < 3 +09)------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +10)--------------WorkTableExec: name=n +11)--RepartitionExec: partitioning=Hash([i@0], 4), input_partitions=1 +12)----RecursiveQueryExec: name=n, is_distinct=false +13)------ProjectionExec: expr=[CAST(1 AS Int64;N) as i] +14)--------PlaceholderRowExec +15)------CoalescePartitionsExec +16)--------ProjectionExec: expr=[i@0 + 1 as i] +17)----------FilterExec: i@0 < 3 +18)------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +19)--------------WorkTableExec: name=n + +# SELECT INTO keeps the DDL statement at the root, so the CTE is inlined. +statement ok +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k INTO into_t FROM c a JOIN c b ON a.s = b.s + +query I rowsort +SELECT * FROM into_t +---- +1 +2 +3 +4 + +statement ok +DROP TABLE into_t; + +# CREATE TABLE AS and CREATE VIEW keep the materialized CTE. +statement ok +CREATE TABLE ctas_t AS +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s + +query I +SELECT count(*) FROM ctas_t +---- +4 + +statement ok +DROP TABLE ctas_t; + +statement ok +CREATE VIEW cte_v AS +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s + +query I +SELECT count(*) FROM cte_v x JOIN cte_v y ON x.k = y.k +---- +4 + +statement ok +DROP VIEW cte_v; + +# The directives override the rule. They need the PostgreSQL dialect. +statement ok +set datafusion.sql_parser.dialect = 'PostgreSQL'; + +# NOT MATERIALIZED: two references to an aggregate body, inlined. +query TT +EXPLAIN WITH c AS NOT MATERIALIZED (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s +---- +logical_plan +01)Projection: a.k +02)--Inner Join: a.s = b.s +03)----SubqueryAlias: a +04)------SubqueryAlias: c +05)--------Projection: t.k, sum(t.v) AS s +06)----------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +07)------------TableScan: t projection=[k, v] +08)----SubqueryAlias: b +09)------SubqueryAlias: c +10)--------Projection: sum(t.v) AS s +11)----------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +12)------------TableScan: t projection=[k, v] +physical_plan +01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(s@0, s@1)], projection=[k@1] +02)--CoalescePartitionsExec +03)----ProjectionExec: expr=[sum(t.v)@1 as s] +04)------AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +05)--------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +06)----------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +07)------------DataSourceExec: partitions=1, partition_sizes=[1] +08)--ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +09)----AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +10)------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +11)--------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +12)----------DataSourceExec: partitions=1, partition_sizes=[1] + +# MATERIALIZED: one reference to a cheap body, materialized. The node is not +# marked as automatic. +query TT +EXPLAIN WITH c AS MATERIALIZED (SELECT k, v * 2 AS v2 FROM t) +SELECT k FROM c WHERE v2 > 30 +---- +logical_plan +01)MaterializedCte: name=c +02)--SubqueryAlias: c +03)----Projection: t.k, CAST(t.v AS Int64) * Int64(2) AS v2 +04)------TableScan: t projection=[k, v] +05)--Projection: c.k +06)----Filter: c.v2 > Int64(30) +07)------MaterializedCteScan: name=c +physical_plan +01)MaterializedCteExec: name=c +02)--ProjectionExec: expr=[k@0 as k, CAST(v@1 AS Int64) * 2 as v2] +03)----DataSourceExec: partitions=1, partition_sizes=[1] +04)--FilterExec: v2@1 > 30, projection=[k@0] +05)----MaterializedCteScanExec: name=c + +# MATERIALIZED: a volatile body is evaluated once. +query I +WITH r AS MATERIALIZED (SELECT random() AS x) +SELECT count(DISTINCT x) FROM (SELECT x FROM r UNION ALL SELECT x FROM r) +---- +1 + +# A dialect other than PostgreSQL. +statement ok +set datafusion.sql_parser.dialect = 'MySQL'; + +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s +---- +logical_plan +01)MaterializedCte: name=c, automatic=true +02)--SubqueryAlias: c +03)----Projection: t.k, sum(t.v) AS s +04)------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +05)--------TableScan: t projection=[k, v] +06)--Projection: a.k +07)----Inner Join: a.s = b.s +08)------SubqueryAlias: a +09)--------MaterializedCteScan: name=c +10)------SubqueryAlias: b +11)--------MaterializedCteScan: name=c projection=[s] +physical_plan +01)MaterializedCteExec: name=c +02)--ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +03)----AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +04)------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +05)--------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +06)----------DataSourceExec: partitions=1, partition_sizes=[1] +07)--HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(s@0, s@1)], projection=[k@1] +08)----CoalescePartitionsExec +09)------MaterializedCteScanExec: name=c, projection=[s] +10)----MaterializedCteScanExec: name=c + +statement ok +set datafusion.sql_parser.dialect = 'Generic'; + +# An unbounded body cannot be buffered. An automatic CTE with such a body +# stays in the logical plan, and the physical planner inlines it, so the query +# still plans. +statement ok +CREATE UNBOUNDED EXTERNAL TABLE unbounded_t(c1 integer, c2 integer, c3 integer) +STORED AS CSV +LOCATION '../core/tests/data/empty.csv' +OPTIONS ('format.has_header' 'true'); + +query TT +EXPLAIN WITH u AS (SELECT c1 FROM unbounded_t UNION ALL SELECT c1 + 1 FROM unbounded_t) +SELECT c1 FROM u UNION ALL SELECT c1 FROM u +---- +logical_plan +01)MaterializedCte: name=u, automatic=true +02)--SubqueryAlias: u +03)----Union +04)------Projection: CAST(unbounded_t.c1 AS Int64) AS c1 +05)--------TableScan: unbounded_t projection=[c1] +06)------Projection: CAST(unbounded_t.c1 AS Int64) + Int64(1) AS c1 +07)--------TableScan: unbounded_t projection=[c1] +08)--Union +09)----MaterializedCteScan: name=u +10)----MaterializedCteScan: name=u +physical_plan +01)UnionExec +02)--UnionExec +03)----ProjectionExec: expr=[CAST(c1@0 AS Int64) as c1] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +05)--------StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true +06)----ProjectionExec: expr=[CAST(c1@0 AS Int64) + 1 as c1] +07)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +08)--------StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true +09)--UnionExec +10)----ProjectionExec: expr=[CAST(c1@0 AS Int64) as c1] +11)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +12)--------StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true +13)----ProjectionExec: expr=[CAST(c1@0 AS Int64) + 1 as c1] +14)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +15)--------StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true + +# The same with one reference in a scalar subquery. +query TT +EXPLAIN WITH u AS (SELECT c1 FROM unbounded_t UNION ALL SELECT c1 + 1 FROM unbounded_t) +SELECT c1 FROM u WHERE c1 = (SELECT c1 FROM u LIMIT 1) +---- +logical_plan +01)MaterializedCte: name=u, automatic=true +02)--SubqueryAlias: u +03)----Union +04)------Projection: CAST(unbounded_t.c1 AS Int64) AS c1 +05)--------TableScan: unbounded_t projection=[c1] +06)------Projection: CAST(unbounded_t.c1 AS Int64) + Int64(1) AS c1 +07)--------TableScan: unbounded_t projection=[c1] +08)--Filter: u.c1 = () +09)----Subquery: +10)------Limit: skip=0, fetch=1 +11)--------MaterializedCteScan: name=u +12)----MaterializedCteScan: name=u +physical_plan +01)ScalarSubqueryExec: subqueries=1 +02)--UnionExec +03)----FilterExec: c1@0 = scalar_subquery() +04)------ProjectionExec: expr=[CAST(c1@0 AS Int64) as c1] +05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +06)----------StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true +07)----FilterExec: c1@0 = scalar_subquery() +08)------ProjectionExec: expr=[CAST(c1@0 AS Int64) + 1 as c1] +09)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +10)----------StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true +11)--CoalescePartitionsExec: fetch=1 +12)----UnionExec +13)------ProjectionExec: expr=[CAST(c1@0 AS Int64) as c1] +14)--------LocalLimitExec: fetch=1 +15)----------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +16)------------StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true +17)------ProjectionExec: expr=[CAST(c1@0 AS Int64) + 1 as c1] +18)--------LocalLimitExec: fetch=1 +19)----------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +20)------------StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true + +# The query also runs. The file has no rows. +query I +WITH u AS (SELECT c1 FROM unbounded_t UNION ALL SELECT c1 + 1 FROM unbounded_t) +SELECT c1 FROM u WHERE c1 = (SELECT c1 FROM u LIMIT 1) +---- + +# Each reference reads another column of the body. The scans have a +# projection, and each inlined copy of the body outputs the column of its +# scan. +query TT +EXPLAIN WITH u AS (SELECT c1, c2 FROM unbounded_t UNION ALL SELECT c2, c1 FROM unbounded_t) +SELECT c1 FROM u UNION ALL SELECT c2 FROM u +---- +logical_plan +01)MaterializedCte: name=u, automatic=true +02)--SubqueryAlias: u +03)----Union +04)------TableScan: unbounded_t projection=[c1, c2] +05)------Projection: unbounded_t.c2 AS c1, unbounded_t.c1 AS c2 +06)--------TableScan: unbounded_t projection=[c1, c2] +07)--Union +08)----MaterializedCteScan: name=u projection=[c1] +09)----Projection: u.c2 AS c1 +10)------MaterializedCteScan: name=u projection=[c2] +physical_plan +01)UnionExec +02)--UnionExec +03)----StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true +04)----ProjectionExec: expr=[c2@1 as c1] +05)------StreamingTableExec: partition_sizes=1, projection=[c1, c2], infinite_source=true +06)--UnionExec +07)----ProjectionExec: expr=[c2@1 as c1] +08)------StreamingTableExec: partition_sizes=1, projection=[c1, c2], infinite_source=true +09)----StreamingTableExec: partition_sizes=1, projection=[c1], infinite_source=true + +query I +WITH u AS (SELECT c1, c2 FROM unbounded_t UNION ALL SELECT c2, c1 FROM unbounded_t) +SELECT c1 FROM u UNION ALL SELECT c2 FROM u +---- + +statement ok +DROP TABLE unbounded_t; + +# Limits and automatic materialization. + +# A `LIMIT` above all references inlines the CTE, so the limit can stop each +# copy early. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s LIMIT 1 +---- +logical_plan +01)Projection: a.k +02)--Limit: skip=0, fetch=1 +03)----Inner Join: a.s = b.s +04)------SubqueryAlias: a +05)--------SubqueryAlias: c +06)----------Projection: t.k, sum(t.v) AS s +07)------------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +08)--------------TableScan: t projection=[k, v] +09)------SubqueryAlias: b +10)--------SubqueryAlias: c +11)----------Projection: sum(t.v) AS s +12)------------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +13)--------------TableScan: t projection=[k, v] +physical_plan +01)CoalescePartitionsExec: fetch=1 +02)--ProjectionExec: expr=[k@0 as k] +03)----HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(s@0, s@1)], projection=[k@1, s@2, s@0], fetch=1 +04)------CoalescePartitionsExec +05)--------ProjectionExec: expr=[sum(t.v)@1 as s] +06)----------AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +07)------------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +08)--------------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +09)----------------DataSourceExec: partitions=1, partition_sizes=[1] +10)------ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +11)--------AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +12)----------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +13)------------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +14)--------------DataSourceExec: partitions=1, partition_sizes=[1] + +query I rowsort +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s ORDER BY a.k LIMIT 2 +---- +1 +2 + +# A `LIMIT` above only one side of the join keeps the CTE materialized, +# because the other side reads the full body. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM (SELECT * FROM c LIMIT 2) a JOIN c b ON a.s = b.s +---- +logical_plan +01)MaterializedCte: name=c, automatic=true +02)--SubqueryAlias: c +03)----Projection: t.k, sum(t.v) AS s +04)------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +05)--------TableScan: t projection=[k, v] +06)--Projection: a.k +07)----Inner Join: a.s = b.s +08)------SubqueryAlias: a +09)--------Limit: skip=0, fetch=2 +10)----------MaterializedCteScan: name=c +11)------SubqueryAlias: b +12)--------MaterializedCteScan: name=c projection=[s] +physical_plan +01)MaterializedCteExec: name=c +02)--ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +03)----AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +04)------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +05)--------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +06)----------DataSourceExec: partitions=1, partition_sizes=[1] +07)--HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(s@1, s@0)], projection=[k@0] +08)----CoalescePartitionsExec: fetch=2 +09)------LocalLimitExec: fetch=2 +10)--------MaterializedCteScanExec: name=c +11)----MaterializedCteScanExec: name=c, projection=[s] + +query I rowsort +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM (SELECT * FROM c ORDER BY k LIMIT 2) a JOIN c b ON a.s = b.s +---- +1 +2 + +# Without a limit the CTE stays materialized. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s +---- +logical_plan +01)MaterializedCte: name=c, automatic=true +02)--SubqueryAlias: c +03)----Projection: t.k, sum(t.v) AS s +04)------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +05)--------TableScan: t projection=[k, v] +06)--Projection: a.k +07)----Inner Join: a.s = b.s +08)------SubqueryAlias: a +09)--------MaterializedCteScan: name=c +10)------SubqueryAlias: b +11)--------MaterializedCteScan: name=c projection=[s] +physical_plan +01)MaterializedCteExec: name=c +02)--ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +03)----AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +04)------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +05)--------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +06)----------DataSourceExec: partitions=1, partition_sizes=[1] +07)--HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(s@0, s@1)], projection=[k@1] +08)----CoalescePartitionsExec +09)------MaterializedCteScanExec: name=c, projection=[s] +10)----MaterializedCteScanExec: name=c + +query I rowsort +WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s +---- +1 +2 +3 +4 + +# `ORDER BY ... LIMIT` reads all of the join output, so the limit does not +# inline the CTE. +query TT +EXPLAIN WITH c AS (SELECT k, sum(v) AS s FROM t GROUP BY k) +SELECT a.k FROM c a JOIN c b ON a.s = b.s ORDER BY a.k LIMIT 2 +---- +logical_plan +01)MaterializedCte: name=c, automatic=true +02)--SubqueryAlias: c +03)----Projection: t.k, sum(t.v) AS s +04)------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +05)--------TableScan: t projection=[k, v] +06)--Sort: a.k ASC NULLS LAST, fetch=2 +07)----Projection: a.k +08)------Inner Join: a.s = b.s +09)--------SubqueryAlias: a +10)----------MaterializedCteScan: name=c +11)--------SubqueryAlias: b +12)----------MaterializedCteScan: name=c projection=[s] +physical_plan +01)MaterializedCteExec: name=c +02)--ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +03)----AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +04)------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +05)--------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +06)----------DataSourceExec: partitions=1, partition_sizes=[1] +07)--SortPreservingMergeExec: [k@0 ASC NULLS LAST], fetch=2 +08)----SortExec: TopK(fetch=2), expr=[k@0 ASC NULLS LAST], preserve_partitioning=[true] +09)------HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(s@0, s@1)], projection=[k@1] +10)--------CoalescePartitionsExec +11)----------MaterializedCteScanExec: name=c, projection=[s] +12)--------MaterializedCteScanExec: name=c + +# The optimizer removes the empty branch of the union, and then the body is +# cheap and is inlined. The scans already have a projection at that time, so +# each copy of the body outputs only the columns of its scan. +query I rowsort +WITH c AS (SELECT k, v FROM t UNION ALL SELECT k, v FROM t WHERE false) +SELECT k FROM c UNION ALL SELECT v FROM c +---- +1 +10 +2 +20 +3 +30 +4 +40 + +# With automatic_cte_materialization_keeps_volatile, a cheap volatile body and +# a volatile body under a limit also stay materialized. +statement ok +set datafusion.optimizer.automatic_cte_materialization_keeps_volatile = true; + +query I +WITH r AS (SELECT random() AS x) +SELECT count(DISTINCT x) FROM (SELECT x FROM r UNION ALL SELECT x FROM r) +---- +1 + +query B +WITH r AS (SELECT sum(random()) AS x FROM t) +SELECT a.x = b.x FROM r a CROSS JOIN r b LIMIT 1 +---- +true + +statement ok +set datafusion.optimizer.automatic_cte_materialization_keeps_volatile = false; + +# An inlined body that holds a materialized CTE: each copy is a separate CTE. +query TT +EXPLAIN WITH c AS ( + WITH d AS (SELECT k, sum(v) AS s FROM t GROUP BY k) + SELECT d1.k, d2.s FROM d d1 JOIN d d2 ON d1.k = d2.k +) +SELECT a.k, b.s FROM c a JOIN c b ON a.k = b.k LIMIT 10 +---- +logical_plan +01)Projection: a.k, b.s +02)--Limit: skip=0, fetch=10 +03)----Inner Join: a.k = b.k +04)------SubqueryAlias: a +05)--------SubqueryAlias: c +06)----------MaterializedCte: name=d, automatic=true +07)------------SubqueryAlias: d +08)--------------Aggregate: groupBy=[[t.k]], aggr=[[]] +09)----------------TableScan: t projection=[k] +10)------------LeftSemi Join: d1.k = d2.k +11)--------------SubqueryAlias: d1 +12)----------------MaterializedCteScan: name=d +13)--------------SubqueryAlias: d2 +14)----------------MaterializedCteScan: name=d +15)------SubqueryAlias: b +16)--------SubqueryAlias: c +17)----------MaterializedCte: name=d, automatic=true +18)------------SubqueryAlias: d +19)--------------Projection: t.k, sum(t.v) AS s +20)----------------Aggregate: groupBy=[[t.k]], aggr=[[sum(CAST(t.v AS Int64))]] +21)------------------TableScan: t projection=[k, v] +22)------------Projection: d1.k, d2.s +23)--------------Inner Join: d1.k = d2.k +24)----------------SubqueryAlias: d1 +25)------------------MaterializedCteScan: name=d projection=[k] +26)----------------SubqueryAlias: d2 +27)------------------MaterializedCteScan: name=d +physical_plan +01)CoalescePartitionsExec: fetch=10 +02)--HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(k@0, k@0)], projection=[k@0, s@2], fetch=10 +03)----CoalescePartitionsExec +04)------MaterializedCteExec: name=d +05)--------AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[] +06)----------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +07)------------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[] +08)--------------DataSourceExec: partitions=1, partition_sizes=[1] +09)--------HashJoinExec: mode=CollectLeft, join_type=LeftSemi, on=[(k@0, k@0)] +10)----------CoalescePartitionsExec +11)------------MaterializedCteScanExec: name=d +12)----------MaterializedCteScanExec: name=d +13)----MaterializedCteExec: name=d +14)------ProjectionExec: expr=[k@0 as k, sum(t.v)@1 as s] +15)--------AggregateExec: mode=FinalPartitioned, gby=[k@0 as k], aggr=[sum(t.v)] +16)----------RepartitionExec: partitioning=Hash([k@0], 4), input_partitions=1 +17)------------AggregateExec: mode=Partial, gby=[k@0 as k], aggr=[sum(t.v)] +18)--------------DataSourceExec: partitions=1, partition_sizes=[1] +19)------HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(k@0, k@0)], projection=[k@0, s@2] +20)--------CoalescePartitionsExec +21)----------MaterializedCteScanExec: name=d, projection=[k] +22)--------MaterializedCteScanExec: name=d + +query II rowsort +WITH c AS ( + WITH d AS (SELECT k, sum(v) AS s FROM t GROUP BY k) + SELECT d1.k, d2.s FROM d d1 JOIN d d2 ON d1.k = d2.k +) +SELECT a.k, b.s FROM c a JOIN c b ON a.k = b.k LIMIT 10 +---- +1 10 +2 20 +3 30 +4 40 + +statement ok +set datafusion.optimizer.enable_automatic_cte_materialization = false; + +statement ok +DROP TABLE t; diff --git a/datafusion/sqllogictest/test_files/explain.slt b/datafusion/sqllogictest/test_files/explain.slt index 1bb69dade6fce..d69d5f1e8cf11 100644 --- a/datafusion/sqllogictest/test_files/explain.slt +++ b/datafusion/sqllogictest/test_files/explain.slt @@ -163,6 +163,7 @@ initial_logical_plan logical_plan after resolve_grouping_function SAME TEXT AS ABOVE logical_plan after type_coercion SAME TEXT AS ABOVE analyzed_logical_plan SAME TEXT AS ABOVE +logical_plan after inline_automatic_ctes SAME TEXT AS ABOVE logical_plan after rewrite_set_comparison SAME TEXT AS ABOVE logical_plan after optimize_unions SAME TEXT AS ABOVE logical_plan after unions_to_filter SAME TEXT AS ABOVE @@ -190,6 +191,7 @@ logical_plan after extract_leaf_expressions SAME TEXT AS ABOVE logical_plan after push_down_leaf_projections SAME TEXT AS ABOVE logical_plan after optimize_projections TableScan: simple_explain_test projection=[a, b, c] logical_plan after replace_filter_top1 SAME TEXT AS ABOVE +logical_plan after inline_automatic_ctes SAME TEXT AS ABOVE logical_plan after rewrite_set_comparison SAME TEXT AS ABOVE logical_plan after optimize_unions SAME TEXT AS ABOVE logical_plan after unions_to_filter SAME TEXT AS ABOVE @@ -670,6 +672,7 @@ initial_logical_plan logical_plan after resolve_grouping_function SAME TEXT AS ABOVE logical_plan after type_coercion SAME TEXT AS ABOVE analyzed_logical_plan SAME TEXT AS ABOVE +logical_plan after inline_automatic_ctes SAME TEXT AS ABOVE logical_plan after rewrite_set_comparison SAME TEXT AS ABOVE logical_plan after optimize_unions SAME TEXT AS ABOVE logical_plan after unions_to_filter SAME TEXT AS ABOVE @@ -697,6 +700,7 @@ logical_plan after extract_leaf_expressions SAME TEXT AS ABOVE logical_plan after push_down_leaf_projections SAME TEXT AS ABOVE logical_plan after optimize_projections TableScan: simple_explain_test projection=[a, b, c] logical_plan after replace_filter_top1 SAME TEXT AS ABOVE +logical_plan after inline_automatic_ctes SAME TEXT AS ABOVE logical_plan after rewrite_set_comparison SAME TEXT AS ABOVE logical_plan after optimize_unions SAME TEXT AS ABOVE logical_plan after unions_to_filter SAME TEXT AS ABOVE diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt index d483f6b91fcc6..186ad3a3d15a5 100644 --- a/datafusion/sqllogictest/test_files/information_schema.slt +++ b/datafusion/sqllogictest/test_files/information_schema.slt @@ -305,8 +305,10 @@ datafusion.format.timestamp_format %Y-%m-%dT%H:%M:%S%.f datafusion.format.timestamp_tz_format NULL datafusion.format.types_info false datafusion.optimizer.allow_symmetric_joins_without_pruning true +datafusion.optimizer.automatic_cte_materialization_keeps_volatile false datafusion.optimizer.default_filter_selectivity 20 datafusion.optimizer.enable_aggregate_dynamic_filter_pushdown true +datafusion.optimizer.enable_automatic_cte_materialization false datafusion.optimizer.enable_distinct_aggregation_soft_limit true datafusion.optimizer.enable_dynamic_filter_pushdown true datafusion.optimizer.enable_join_dynamic_filter_pushdown true @@ -477,8 +479,10 @@ datafusion.format.timestamp_format %Y-%m-%dT%H:%M:%S%.f Timestamp format for tim datafusion.format.timestamp_tz_format NULL Timestamp format for timestamp with timezone arrays. When `None`, ISO 8601 format is used. datafusion.format.types_info false Show types in visual representation batches datafusion.optimizer.allow_symmetric_joins_without_pruning true Should DataFusion allow symmetric hash joins for unbounded data sources even when its inputs do not have any ordering or filtering If the flag is not enabled, the SymmetricHashJoin operator will be unable to prune its internal buffers, resulting in certain join types - such as Full, Left, LeftAnti, LeftSemi, Right, RightAnti, and RightSemi - being produced only at the end of the execution. This is not typical in stream processing. Additionally, without proper design for long runner execution, all types of joins may encounter out-of-memory errors. +datafusion.optimizer.automatic_cte_materialization_keeps_volatile false When set to true, together with `enable_automatic_cte_materialization`, a CTE with a volatile body and more than one reference stays materialized, so that each reference reads the same rows. PostgreSQL and DuckDB do the same. When set to false, such a CTE is inlined at each reference, and each reference evaluates the volatile expressions again, as with `enable_automatic_cte_materialization` set to false. datafusion.optimizer.default_filter_selectivity 20 The default filter selectivity used by Filter Statistics when an exact selectivity cannot be determined. Valid values are between 0 (no selectivity) and 100 (all rows are selected). datafusion.optimizer.enable_aggregate_dynamic_filter_pushdown true When set to true, the optimizer will attempt to push down Aggregate dynamic filters into the file scan phase. +datafusion.optimizer.enable_automatic_cte_materialization false When set to true, the SQL planner plans each non-recursive CTE that has no `MATERIALIZED` or `NOT MATERIALIZED` directive as a materialized CTE, and the optimizer rule `inline_automatic_ctes` decides which of them stay materialized. A CTE stays materialized, and is computed one time, when it has more than one reference and its body is more than projections and filters on one table, and no `LIMIT` is above all of its references. A CTE with a volatile body is inlined, unless `automatic_cte_materialization_keeps_volatile` is true. All other CTEs are inlined at each reference. When set to false, a CTE is materialized only with `AS MATERIALIZED`. datafusion.optimizer.enable_distinct_aggregation_soft_limit true When set to true, the optimizer will push a limit operation into grouped aggregations which have no aggregate expressions, as a soft limit, emitting groups once the limit is reached, before all rows in the group are read. datafusion.optimizer.enable_dynamic_filter_pushdown true When set to true attempts to push down dynamic filters generated by operators (TopK, Join & Aggregate) into the file scan phase. For example, for a query such as `SELECT * FROM t ORDER BY timestamp DESC LIMIT 10`, the optimizer will attempt to push down the current top 10 timestamps that the TopK operator references into the file scans. This means that if we already have 10 timestamps in the year 2025 any files that only have timestamps in the year 2024 can be skipped / pruned at various stages in the scan. The config will suppress `enable_join_dynamic_filter_pushdown`, `enable_topk_dynamic_filter_pushdown` & `enable_aggregate_dynamic_filter_pushdown` So if you disable `enable_topk_dynamic_filter_pushdown`, then enable `enable_dynamic_filter_pushdown`, the `enable_topk_dynamic_filter_pushdown` will be overridden. datafusion.optimizer.enable_join_dynamic_filter_pushdown true When set to true, the optimizer will attempt to push down Join dynamic filters into the file scan phase. diff --git a/datafusion/sqllogictest/unparser_known_failures.txt b/datafusion/sqllogictest/unparser_known_failures.txt index 4aeade8cd397e..7cf54f44fd036 100644 --- a/datafusion/sqllogictest/unparser_known_failures.txt +++ b/datafusion/sqllogictest/unparser_known_failures.txt @@ -56,6 +56,7 @@ cast_extension_type_metadata.slt coalesce.slt cosine_distance.slt cte.slt +cte_auto_materialize.slt cte_materialized.slt date_bin_errors.slt datetime/arith_date_time.slt diff --git a/docs/source/library-user-guide/upgrading/index.md b/docs/source/library-user-guide/upgrading/index.md index d2372d78e87a2..0d54008c9a824 100644 --- a/docs/source/library-user-guide/upgrading/index.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -318,6 +318,18 @@ After the scans get new types, the closure must recompute the schemas of the continuation from its leaves, because the plans above a scan keep their old schemas until it does. +### Automatic materialized CTEs + +`MaterializedCte::is_automatic` is `false` for a CTE with `AS MATERIALIZED`. It +is `true` when the SQL planner created the node because +`datafusion.optimizer.enable_automatic_cte_materialization` is on (the default +is off). Set it with `MaterializedCteBuilder::with_automatic`. The optimizer +rule `InlineAutomaticCtes` replaces an automatic node with +`MaterializedCte::inline` when materialization is not expected to help. With the +option on, a plan that is not optimized has these nodes for each CTE, and the +unparser, the Substrait producer and the protobuf serializer return a "not +implemented" error for them. + ### Null-aware sort-merge joins add a protobuf field `SortMergeJoinExec` now supports null-aware (`NOT IN`) semantics for diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md index 49efa6e4ed6b8..225214ecd194c 100644 --- a/docs/source/user-guide/configs.md +++ b/docs/source/user-guide/configs.md @@ -145,6 +145,8 @@ The following configuration settings are available: | datafusion.optimizer.enable_round_robin_repartition | true | When set to true, the physical plan optimizer will try to add round robin repartitioning to increase parallelism to leverage more CPU cores | | datafusion.optimizer.enable_topk_aggregation | true | When set to true, the optimizer will attempt to perform limit operations during aggregations, if possible | | datafusion.optimizer.enable_window_limits | true | When set to true, the optimizer will attempt to push limit operations past window functions, if possible | +| datafusion.optimizer.enable_automatic_cte_materialization | false | When set to true, the SQL planner plans each non-recursive CTE that has no `MATERIALIZED` or `NOT MATERIALIZED` directive as a materialized CTE, and the optimizer rule `inline_automatic_ctes` decides which of them stay materialized. A CTE stays materialized, and is computed one time, when it has more than one reference and its body is more than projections and filters on one table, and no `LIMIT` is above all of its references. A CTE with a volatile body is inlined, unless `automatic_cte_materialization_keeps_volatile` is true. All other CTEs are inlined at each reference. When set to false, a CTE is materialized only with `AS MATERIALIZED`. | +| datafusion.optimizer.automatic_cte_materialization_keeps_volatile | false | When set to true, together with `enable_automatic_cte_materialization`, a CTE with a volatile body and more than one reference stays materialized, so that each reference reads the same rows. PostgreSQL and DuckDB do the same. When set to false, such a CTE is inlined at each reference, and each reference evaluates the volatile expressions again, as with `enable_automatic_cte_materialization` set to false. | | datafusion.optimizer.enable_window_topn | true | When set to true, the optimizer will replace Filter(rn<=K) → Window(ROW_NUMBER, RANK or DENSE_RANK) → Sort patterns with a PartitionedTopKExec that keeps only the top K rows of each window partition, avoiding a full sort of the input. | | datafusion.optimizer.enable_row_number_to_aggregate | false | When set to true, the optimizer will rewrite a "top-1 per group" pattern of the form `Filter(row_number() = 1)` over a `PARTITION BY` window into an `Aggregate(first_value(... ORDER BY ...) GROUP BY partition)`. This avoids buffering / fully sorting the input, which is especially beneficial on wide payloads. Disabled by default because on nested/wide value types the aggregate only becomes memory efficient once the columnar nested-type `GroupsAccumulator` fast path is available; enabling it without that support can route wide payloads onto the slow per-group accumulator path. | | datafusion.optimizer.enable_topk_repartition | true | When set to true, the optimizer will push TopK (Sort with fetch) below hash repartition when the partition key is a prefix of the sort key, reducing data volume before the shuffle. |