1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// 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
use std::sync::Arc;
use crate::planner::{ContextProvider, PlannerContext, SqlToRel};
use arrow::datatypes::{Schema, SchemaRef};
use datafusion_common::{
Result, TableReference, not_impl_err, plan_err,
tree_node::{TreeNode, TreeNodeRecursion},
};
use datafusion_expr::{
LogicalPlan, LogicalPlanBuilder, MaterializedCte, MaterializedCteId,
MaterializedCtePlan, MaterializedCteScan, TableSource,
};
use sqlparser::ast::{CteAsMaterialized, Ident, Query, SetExpr, SetOperator, With};
/// A `WITH x AS MATERIALIZED (...)` CTE whose body must wrap the query that
/// declared it. See [`MaterializedCte`].
pub(crate) struct PendingMaterializedCte {
id: MaterializedCteId,
name: String,
cte: LogicalPlan,
}
impl PendingMaterializedCte {
/// Wrap `continuation` so that its scans of this CTE read one shared result.
pub(crate) fn wrap(self, continuation: LogicalPlan) -> Result<LogicalPlan> {
MaterializedCte::try_new(
self.id,
self.name,
Arc::new(self.cte),
Arc::new(continuation),
)
.map(|cte| LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)))
}
}
impl<S: ContextProvider> SqlToRel<'_, S> {
pub(super) fn plan_with_clause(
&self,
with: With,
planner_context: &mut PlannerContext,
) -> Result<Vec<PendingMaterializedCte>> {
let is_recursive = with.recursive;
let mut materialized = vec![];
// Process CTEs from top to bottom
for cte in with.cte_tables {
// A `WITH` block can't use the same name more than once
let cte_name = self.ident_normalizer.normalize(cte.alias.name.clone());
if planner_context.contains_cte(&cte_name) {
return plan_err!(
"WITH query name {cte_name:?} specified more than once"
);
}
// Create a logical plan for the CTE
let cte_plan = if is_recursive {
let columns = cte.alias.columns.iter().map(|c| c.name.clone()).collect();
self.recursive_cte(&cte_name, columns, *cte.query, planner_context)?
} else {
self.non_recursive_cte(*cte.query, planner_context)?
};
// Each `WITH` block can change the column names in the last projection
// (e.g. "WITH table(t1, t2) AS SELECT 1, 2"). Recursive CTEs apply those
// to the static term in recursive_cte(), so only the relation name here.
// 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)
&& cte_plan.all_out_ref_exprs().is_empty();
let final_plan = if is_recursive {
LogicalPlanBuilder::from(cte_plan)
.alias(TableReference::bare(
self.ident_normalizer.normalize(cte.alias.name),
))?
.build()?
} else {
self.apply_table_alias(cte_plan, cte.alias)?
};
if is_materialized {
// Every reference reads the shared result instead of a copy
// of the body. The body is already planned, so a reference
// of a recursive CTE to itself stays a work table scan.
let id = MaterializedCteId::next();
let scan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(
MaterializedCteScan::new(
id,
cte_name.clone(),
Arc::clone(final_plan.schema()),
),
));
materialized.push(PendingMaterializedCte {
id,
name: cte_name.clone(),
cte: final_plan,
});
planner_context.insert_cte(cte_name, scan);
continue;
}
// Export the CTE to the outer query
planner_context.insert_cte(cte_name, final_plan);
}
Ok(materialized)
}
fn non_recursive_cte(
&self,
cte_query: Query,
planner_context: &mut PlannerContext,
) -> Result<LogicalPlan> {
self.query_to_plan(cte_query, planner_context)
}
fn recursive_cte(
&self,
cte_name: &str,
columns: Vec<Ident>,
mut cte_query: Query,
planner_context: &mut PlannerContext,
) -> Result<LogicalPlan> {
if !self
.context_provider
.options()
.execution
.enable_recursive_ctes
{
return not_impl_err!("Recursive CTEs are not enabled");
}
let (left_expr, right_expr, set_quantifier) = match *cte_query.body {
SetExpr::SetOperation {
op: SetOperator::Union,
left,
right,
set_quantifier,
} => (left, right, set_quantifier),
other => {
// Not a UNION, so not actually a recursive CTE. The caller adds only
// the relation name for recursive CTEs, so apply the column aliases here.
*cte_query.body = other;
let plan = self.non_recursive_cte(cte_query, planner_context)?;
return self.apply_expr_alias(plan, columns);
}
};
// Each recursive CTE consists of two parts in the logical plan:
// 1. A static term (the left-hand side on the SQL, where the
// referencing to the same CTE is not allowed)
//
// 2. A recursive term (the right hand side, and the recursive
// part)
// Since static term does not have any specific properties, it can
// be compiled as if it was a regular expression. This will
// allow us to infer the schema to be used in the recursive term.
// ---------- Step 1: Compile the static term ------------------
let static_plan = self.set_expr_to_plan(*left_expr, planner_context)?;
// Apply the declared column-list aliases (e.g. `t(n)`) to the static term, so
// the work table built from its schema below exposes the declared names.
let static_plan = self.apply_expr_alias(static_plan, columns)?;
// Since the recursive CTEs include a component that references a
// table with its name, like the example below:
//
// WITH RECURSIVE values(n) AS (
// SELECT 1 as n -- static term
// UNION ALL
// SELECT n + 1
// FROM values -- self reference
// WHERE n < 100
// )
//
// We need a temporary 'relation' to be referenced and used. PostgreSQL
// calls this a 'working table', but it is entirely an implementation
// detail and a 'real' table with that name might not even exist (as
// in the case of DataFusion).
//
// Since we can't simply register a table during planning stage (it is
// an execution problem), we'll use a relation object that knows which
// recursive CTE it is bound to.
// ---------- Step 2: Create a temporary relation ------------------
// Step 2.1: Create a table source for the temporary relation
// Recursive self-references must expose conservative (nullable)
// columns. Deriving them from the static term's possibly non-nullable
// schema would let the recursive term treat values from previous
// iterations as non-nullable.
let work_table_source = self.context_provider.create_cte_work_table(
cte_name,
nullable_schema(static_plan.schema().inner()),
)?;
// Step 2.2: Create a temporary relation logical plan that will be used
// as the input to the recursive term
let work_table_plan = LogicalPlanBuilder::scan(
cte_name.to_string(),
Arc::clone(&work_table_source),
None,
)?
.build()?;
let name = cte_name.to_string();
// Step 2.3: Register the temporary relation in the planning context
// For all the self references in the variadic term, we'll replace it
// with the temporary relation we created above by temporarily registering
// it as a CTE. This temporary relation in the planning context will be
// replaced by the actual CTE plan once we're done with the planning.
planner_context.insert_cte(cte_name.to_string(), work_table_plan);
// ---------- Step 3: Compile the recursive term ------------------
// this uses the named_relation we inserted above to resolve the
// relation. This ensures that the recursive term uses the named relation logical plan
// and thus the 'continuance' physical plan as its input and source
let recursive_plan = self.set_expr_to_plan(*right_expr, planner_context)?;
// Check if the recursive term references the CTE itself,
// if not, it is a non-recursive CTE
if !has_work_table_reference(&recursive_plan, &work_table_source) {
// Remove the work table plan from the context
planner_context.remove_cte(cte_name);
// Compile it as a non-recursive CTE
return self.set_operation_to_plan(
SetOperator::Union,
static_plan,
recursive_plan,
set_quantifier,
);
}
// ---------- Step 4: Create the final plan ------------------
// Step 4.1: Compile the final plan
let distinct = !Self::is_union_all(set_quantifier)?;
LogicalPlanBuilder::from(static_plan)
.to_recursive_query(name, recursive_plan, distinct)?
.build()
}
}
/// Return a copy of `schema` with every field marked nullable, preserving field
/// and schema metadata.
fn nullable_schema(schema: &Schema) -> SchemaRef {
Arc::new(Schema::new_with_metadata(
schema
.fields()
.iter()
.map(|field| field.as_ref().clone().with_nullable(true))
.collect::<Vec<_>>(),
schema.metadata().clone(),
))
}
fn has_work_table_reference(
plan: &LogicalPlan,
work_table_source: &Arc<dyn TableSource>,
) -> bool {
let mut has_reference = false;
plan.apply(|node| {
if let LogicalPlan::TableScan(scan) = node
&& Arc::ptr_eq(&scan.source, work_table_source)
{
has_reference = true;
return Ok(TreeNodeRecursion::Stop);
}
Ok(TreeNodeRecursion::Continue)
})
// Closure always return Ok
.unwrap();
has_reference
}