Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions datafusion/common/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
84 changes: 82 additions & 2 deletions datafusion/core/src/physical_planner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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<LogicalPlan> {
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.
Expand Down Expand Up @@ -501,6 +542,38 @@ impl DefaultPhysicalPlanner {
&'a self,
logical_plan: &'a LogicalPlan,
session_state: &'a dyn Session,
) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
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<LogicalPlan> = 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::<UnboundedAutomaticCte>().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<Arc<dyn ExecutionPlan>>> {
Box::pin(async move {
// When `enable_physical_uncorrelated_scalar_subquery` is disabled, the
Expand Down Expand Up @@ -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()
Expand Down
Loading