Skip to content
Draft
93 changes: 12 additions & 81 deletions datafusion/core/src/physical_planner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ use datafusion_expr::physical_planning_context::{
use datafusion_expr::utils::{expr_to_columns, split_conjunction};
use datafusion_expr::{
Analyze, BinaryExpr, DmlStatement, Explain, ExplainFormat, Extension, FetchType,
Filter, JoinType, MaterializedCte, MaterializedCteId, MaterializedCtePlan, Operator,
RecursiveQuery, Show, ShowKind, SkipType, StringifiedPlan, WindowFrame,
WindowFrameBound, WriteOp,
Filter, JoinType, MaterializedCtePlan, Operator, RecursiveQuery, Show, ShowKind,
SkipType, StringifiedPlan, WindowFrame, WindowFrameBound, WriteOp,
renumber_materialized_ctes,
};
use datafusion_physical_expr::aggregate::{
AggregateFunctionExpr, LoweredAggregate, LoweredAggregateBuilder,
Expand Down Expand Up @@ -227,86 +227,17 @@ impl DefaultPhysicalPlanner {
{
return Ok(plan);
}
let renumbered = renumber_materialized_ctes(logical_plan)?;
let logical_plan = renumbered.as_ref().unwrap_or(logical_plan);
// The ids must be new for each planning run. See
// `renumber_materialized_ctes`.
let logical_plan = renumber_materialized_ctes(logical_plan.clone())?.data;
let logical_plan = &logical_plan;
let plan = self
.create_initial_plan(logical_plan, session_state)
.await?;
self.optimize_physical_plan(plan, session_state, |_, _| {})
}
}

/// Give each occurrence of a [`MaterializedCte`] in `plan` a new id, and
/// update the scans in its continuation, including the scans in subqueries.
///
/// The id is copied when a logical plan is cloned, so one CTE can occur more
/// than once, for example when a view that declares it is referenced two
/// times, or when a DataFrame is joined to itself. Each occurrence is a
/// separate CTE, as in PostgreSQL.
///
/// The ids must also be new for each planning run, not only unique within
/// `plan`. A table provider can plan a saved logical plan in its `scan`, as a
/// [`ViewTable`] that is not inlined does. Each such scan is a separate
/// planning run of the same saved plan, and its CTEs end up in the same
/// physical plan as the CTEs of the outer run.
///
/// Returns `None` when `plan` has no materialized CTE.
///
/// [`ViewTable`]: crate::datasource::ViewTable
fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result<Option<LogicalPlan>> {
let mut has_cte = false;
plan.apply_with_subqueries(|node| {
if matches!(
node,
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_))
) {
has_cte = true;
return Ok(TreeNodeRecursion::Stop);
}
Ok(TreeNodeRecursion::Continue)
})?;
if !has_cte {
return Ok(None);
}

plan.clone()
.transform_down_with_subqueries(|node| {
let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node else {
return Ok(Transformed::no(node));
};
let old_id = cte.id;
let new_id = MaterializedCteId::next();
let continuation = Arc::unwrap_or_clone(cte.continuation)
.transform_down_with_subqueries(|node| match node {
// A nested occurrence of the same CTE owns the scans below
// it, and is renumbered on its own.
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
ref nested,
)) if nested.id == old_id => {
Ok(Transformed::new(node, false, TreeNodeRecursion::Jump))
}
LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(mut scan))
if scan.id == old_id =>
{
scan.id = new_id;
Ok(Transformed::yes(LogicalPlan::MaterializedCte(
MaterializedCtePlan::Scan(scan),
)))
}
_ => Ok(Transformed::no(node)),
})?
.data;
Ok(Transformed::yes(LogicalPlan::MaterializedCte(
MaterializedCtePlan::Cte(MaterializedCte {
id: new_id,
continuation: Arc::new(continuation),
..cte
}),
)))
})
.map(|t| Some(t.data))
}

/// Points every [`MaterializedCteScanExec`] at the buffer of the
/// [`MaterializedCteExec`] with the same id, and gives it the statistics of
/// the CTE body.
Expand Down Expand Up @@ -947,8 +878,8 @@ impl DefaultPhysicalPlanner {
LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) => {
// Unbound until `bind_materialized_cte_scans` runs on the whole plan.
let exec = MaterializedCteScanExec::new(
scan.id.as_u64(),
&scan.name,
scan.id().as_u64(),
scan.name(),
Arc::clone(scan.schema().inner()),
session.config().target_partitions(),
);
Expand Down Expand Up @@ -2036,19 +1967,19 @@ impl DefaultPhysicalPlanner {
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
let [body, continuation] = children.two()?;
// A CTE that nothing reads is never evaluated.
if cte.scans()?.is_empty() {
if !cte.is_read()? {
return Ok(continuation);
}
// The body is fully buffered before a scan yields a row, so an
// unbounded body would never produce output.
if body.boundedness().is_unbounded() {
return plan_err!(
"MATERIALIZED CTE {} reads an unbounded source, which cannot be materialized",
cte.name
cte.name()
);
}
let buffer =
Arc::new(MaterializedCteBuffer::new(cte.id.as_u64(), &cte.name));
Arc::new(MaterializedCteBuffer::new(cte.id().as_u64(), cte.name()));
Arc::new(MaterializedCteExec::new(body, continuation, buffer))
}

Expand Down
87 changes: 73 additions & 14 deletions datafusion/expr/src/logical_plan/invariants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

use crate::logical_plan::MaterializedCtePlan;
use std::collections::HashSet;
use std::sync::Arc;

use crate::logical_plan::{MaterializedCteId, MaterializedCtePlan};
use datafusion_common::{
DFSchemaRef, Result, assert_or_internal_err, plan_err,
DFSchemaRef, Result, assert_or_internal_err, internal_err, plan_err,
tree_node::{TreeNode, TreeNodeRecursion},
};

Expand Down Expand Up @@ -98,26 +101,82 @@ fn assert_valid_semantic_plan(plan: &LogicalPlan) -> Result<()> {
Ok(())
}

/// Returns an error if a scan of a materialized CTE does not have the names
/// and types of the columns that it reads from the body of the CTE.
/// Returns an error if a scan of a materialized CTE is not in the
/// continuation of its CTE, or does not have the names and types of the
/// columns that it reads from the body of the CTE.
///
/// The id of a CTE is in scope only in its continuation, also in subquery
/// expressions there. It is not in scope in the body of the CTE or above the
/// CTE. A nested CTE with the same id owns the scans below it.
///
/// A scan whose CTE is not in `plan` is not checked, because `plan` can be a
/// part of a larger plan.
fn assert_materialized_cte_scans_are_valid(plan: &LogicalPlan) -> Result<()> {
let mut ids = HashSet::new();
plan.apply_with_subqueries(|node| {
if let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node {
for scan in cte.scans()? {
scan.check_body_schema(cte.body().schema()).map_err(|e| {
e.context(format!(
"A scan of the materialized CTE {} does not match the CTE",
cte.name()
))
})?;
}
ids.insert(cte.id());
}
Ok(TreeNodeRecursion::Continue)
})
.map(|_| ())
})?;
if ids.is_empty() {
return Ok(());
}
check_materialized_cte_scope(plan, &ids, &mut vec![])
}

/// The id and body schema of each CTE whose continuation contains the
/// current node, innermost last. It holds owned values because
/// `apply_subqueries` hands out temporary plans.
type MaterializedCteScope = Vec<(MaterializedCteId, DFSchemaRef)>;

#[cfg_attr(feature = "recursive_protection", recursive::recursive)]
fn check_materialized_cte_scope(
plan: &LogicalPlan,
ids: &HashSet<MaterializedCteId>,
scope: &mut MaterializedCteScope,
) -> Result<()> {
match plan {
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
check_materialized_cte_scope(cte.body(), ids, scope)?;
scope.push((cte.id(), Arc::clone(cte.body().schema())));
let result = check_materialized_cte_scope(cte.continuation(), ids, scope);
scope.pop();
return result;
}
LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan))
if ids.contains(&scan.id()) =>
{
let Some((_, body_schema)) =
scope.iter().rev().find(|(id, _)| *id == scan.id())
else {
return internal_err!(
"A scan of the materialized CTE {} is not in the continuation of the CTE",
scan.name()
);
};
return scan.check_body_schema(body_schema).map_err(|e| {
e.context(format!(
"A scan of the materialized CTE {} does not match the CTE",
scan.name()
))
});
}
_ => {}
}
for input in plan.inputs() {
check_materialized_cte_scope(input, ids, scope)?;
}
let mut result = Ok(());
plan.apply_subqueries(|subquery| {
result = check_materialized_cte_scope(subquery, ids, scope);
Ok(if result.is_ok() {
TreeNodeRecursion::Jump
} else {
TreeNodeRecursion::Stop
})
})?;
result
}

/// Returns an error if the plan does not have the expected schema.
Expand Down
Loading