datafusion_expr/logical_plan/
materialized_cte.rs1use std::cmp::Ordering;
19use std::fmt;
20use std::hash::Hash;
21use std::sync::Arc;
22use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
23
24use datafusion_common::tree_node::TreeNodeRecursion;
25use datafusion_common::{DFSchemaRef, Result};
26
27use crate::LogicalPlan;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct MaterializedCteId(u64);
35
36impl MaterializedCteId {
37 pub fn next() -> Self {
39 static NEXT: AtomicU64 = AtomicU64::new(0);
40 Self(NEXT.fetch_add(1, AtomicOrdering::Relaxed))
41 }
42
43 pub fn as_u64(self) -> u64 {
45 self.0
46 }
47}
48
49impl fmt::Display for MaterializedCteId {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 write!(f, "{}", self.0)
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
57pub enum MaterializedCtePlan {
58 Cte(MaterializedCte),
60 Scan(MaterializedCteScan),
62}
63
64#[derive(Debug, Clone, PartialEq, Eq, Hash)]
75pub struct MaterializedCte {
76 pub id: MaterializedCteId,
78 pub name: String,
80 pub cte: Arc<LogicalPlan>,
82 pub continuation: Arc<LogicalPlan>,
84}
85
86impl MaterializedCte {
87 pub fn try_new(
92 id: MaterializedCteId,
93 name: impl Into<String>,
94 cte: Arc<LogicalPlan>,
95 continuation: Arc<LogicalPlan>,
96 ) -> Result<Self> {
97 let name = name.into();
98 for scan in MaterializedCteScan::find_in(&continuation, id)? {
99 scan.schema
100 .has_equivalent_names_and_types(cte.schema())
101 .map_err(|e| {
102 e.context(format!(
103 "A scan of the materialized CTE {name} does not have the schema of the CTE"
104 ))
105 })?;
106 }
107 Ok(Self {
108 id,
109 name,
110 cte,
111 continuation,
112 })
113 }
114
115 pub fn id(&self) -> MaterializedCteId {
117 self.id
118 }
119
120 pub fn name(&self) -> &str {
122 &self.name
123 }
124
125 pub fn body(&self) -> &Arc<LogicalPlan> {
127 &self.cte
128 }
129
130 pub fn continuation(&self) -> &Arc<LogicalPlan> {
132 &self.continuation
133 }
134
135 pub fn schema(&self) -> &DFSchemaRef {
137 self.continuation.schema()
138 }
139
140 pub fn scans(&self) -> Result<Vec<MaterializedCteScan>> {
143 MaterializedCteScan::find_in(&self.continuation, self.id)
144 }
145
146 pub fn with_new_inputs(
149 &self,
150 cte: Arc<LogicalPlan>,
151 continuation: Arc<LogicalPlan>,
152 ) -> Self {
153 Self {
154 id: self.id,
155 name: self.name.clone(),
156 cte,
157 continuation,
158 }
159 }
160}
161
162impl PartialOrd for MaterializedCte {
166 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
167 match self
168 .id
169 .cmp(&other.id)
170 .then_with(|| self.name.cmp(&other.name))
171 {
172 Ordering::Equal if self != other => None,
173 ord => Some(ord),
174 }
175 }
176}
177
178#[derive(Debug, Clone, PartialEq, Eq, Hash)]
183pub struct MaterializedCteScan {
184 pub id: MaterializedCteId,
186 pub name: String,
188 pub schema: DFSchemaRef,
190}
191
192impl MaterializedCteScan {
193 pub fn new(
195 id: MaterializedCteId,
196 name: impl Into<String>,
197 schema: DFSchemaRef,
198 ) -> Self {
199 Self {
200 id,
201 name: name.into(),
202 schema,
203 }
204 }
205
206 pub fn id(&self) -> MaterializedCteId {
208 self.id
209 }
210
211 pub fn name(&self) -> &str {
213 &self.name
214 }
215
216 pub fn schema(&self) -> &DFSchemaRef {
218 &self.schema
219 }
220
221 pub fn find_in(plan: &LogicalPlan, id: MaterializedCteId) -> Result<Vec<Self>> {
228 let mut scans = vec![];
229 plan.apply_with_subqueries(|node| match node {
230 LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte))
231 if cte.id == id =>
232 {
233 Ok(TreeNodeRecursion::Jump)
234 }
235 LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan))
236 if scan.id == id =>
237 {
238 scans.push(scan.clone());
239 Ok(TreeNodeRecursion::Continue)
240 }
241 _ => Ok(TreeNodeRecursion::Continue),
242 })?;
243 Ok(scans)
244 }
245}
246
247impl PartialOrd for MaterializedCteScan {
250 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
251 match self
252 .id
253 .cmp(&other.id)
254 .then_with(|| self.name.cmp(&other.name))
255 {
256 Ordering::Equal if self != other => None,
257 ord => Some(ord),
258 }
259 }
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265 use crate::logical_plan::builder::LogicalPlanBuilder;
266 use crate::{EmptyRelation, exists};
267 use arrow::datatypes::{DataType, Field, Schema};
268 use datafusion_common::DFSchema;
269
270 fn empty(produce_one_row: bool) -> Arc<LogicalPlan> {
271 Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
272 produce_one_row,
273 schema: Arc::new(DFSchema::empty()),
274 }))
275 }
276
277 fn schema(data_type: DataType) -> DFSchemaRef {
278 let schema = Schema::new(vec![Field::new("a", data_type, true)]);
279 Arc::new(DFSchema::try_from_qualified_schema("c", &schema).unwrap())
280 }
281
282 fn body(data_type: DataType) -> Arc<LogicalPlan> {
283 Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
284 produce_one_row: false,
285 schema: schema(data_type),
286 }))
287 }
288
289 fn scan(id: MaterializedCteId, data_type: DataType) -> LogicalPlan {
290 LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(MaterializedCteScan::new(
291 id,
292 "c",
293 schema(data_type),
294 )))
295 }
296
297 #[test]
298 fn partial_cmp_is_equal_only_for_equal_nodes() {
299 let id = MaterializedCteId::next();
300 let a = MaterializedCte {
301 id,
302 name: "c".to_string(),
303 cte: empty(false),
304 continuation: empty(false),
305 };
306 let mut b = a.clone();
307 assert_eq!(a.partial_cmp(&b), Some(Ordering::Equal));
308
309 b.continuation = empty(true);
310 assert_ne!(a, b);
311 assert_eq!(a.partial_cmp(&b), None);
312
313 let c = MaterializedCte {
314 id: MaterializedCteId::next(),
315 ..a.clone()
316 };
317 assert_eq!(a.partial_cmp(&c), Some(Ordering::Less));
318 }
319
320 #[test]
321 fn try_new_checks_the_schema_of_the_scans() -> Result<()> {
322 let id = MaterializedCteId::next();
323 let cte = MaterializedCte::try_new(
324 id,
325 "c",
326 body(DataType::Int32),
327 Arc::new(scan(id, DataType::Int32)),
328 )?;
329 assert_eq!(cte.id(), id);
330 assert_eq!(cte.name(), "c");
331 assert_eq!(cte.schema(), cte.continuation().schema());
332 assert_eq!(cte.scans()?.len(), 1);
333
334 let plan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte));
335 assert_eq!(plan.inputs().len(), 2);
336 assert_eq!(
337 plan.display_indent().to_string(),
338 "MaterializedCte: name=c\n EmptyRelation: rows=0\n MaterializedCteScan: name=c"
339 );
340
341 let err = MaterializedCte::try_new(
342 id,
343 "c",
344 body(DataType::Int32),
345 Arc::new(scan(id, DataType::Utf8)),
346 )
347 .unwrap_err();
348 assert!(
349 err.to_string().contains(
350 "A scan of the materialized CTE c does not have the schema of the CTE"
351 ),
352 "{err}"
353 );
354
355 MaterializedCte::try_new(
357 id,
358 "c",
359 body(DataType::Int32),
360 Arc::new(scan(MaterializedCteId::next(), DataType::Utf8)),
361 )?;
362 Ok(())
363 }
364
365 #[test]
366 fn find_in_looks_in_subqueries_and_stops_at_the_same_cte() -> Result<()> {
367 let id = MaterializedCteId::next();
368 let other = MaterializedCteId::next();
369 let plan = LogicalPlanBuilder::from(scan(id, DataType::Int32))
373 .filter(exists(Arc::new(scan(id, DataType::Int32))))?
374 .union(scan(other, DataType::Int32))?
375 .union(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
376 MaterializedCte::try_new(
377 id,
378 "c",
379 body(DataType::Int32),
380 Arc::new(scan(id, DataType::Int32)),
381 )?,
382 )))?
383 .build()?;
384 assert_eq!(MaterializedCteScan::find_in(&plan, id)?.len(), 2);
385 assert_eq!(MaterializedCteScan::find_in(&plan, other)?.len(), 1);
386 assert!(
387 MaterializedCteScan::find_in(&plan, MaterializedCteId::next())?.is_empty()
388 );
389 Ok(())
390 }
391}