Skip to main content

datafusion_expr/logical_plan/
materialized_cte.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Logical nodes for `WITH x AS MATERIALIZED (...)`.
6//!
7//! A materialized CTE is planned as one [`MaterializedCte`] node, which owns
8//! the CTE body and the rest of the query (the "continuation"), and one
9//! [`MaterializedCteScan`] leaf for each reference to the CTE inside the
10//! continuation. Both are in the [`LogicalPlan::MaterializedCte`] variant,
11//! as cases of [`MaterializedCtePlan`]. The body is therefore optimized and executed once, and
12//! the scans read its buffered output.
13//!
14//! The scans are leaves, so filters and projections of one reference are not
15//! pushed into the shared body. This is the same optimization fence that
16//! PostgreSQL applies to `MATERIALIZED` CTEs.
17
18use 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/// Identifies one materialized CTE and binds its scans to it.
30///
31/// CTE names are not unique (two sibling subqueries can each declare `WITH t`),
32/// so the planner allocates a process-unique id.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct MaterializedCteId(u64);
35
36impl MaterializedCteId {
37    /// Allocate a new unique id.
38    pub fn next() -> Self {
39        static NEXT: AtomicU64 = AtomicU64::new(0);
40        Self(NEXT.fetch_add(1, AtomicOrdering::Relaxed))
41    }
42
43    /// The numeric value of this id.
44    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/// A node of a materialized CTE, in [`LogicalPlan::MaterializedCte`].
56#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
57pub enum MaterializedCtePlan {
58    /// Computes the body of the CTE once and evaluates the continuation
59    Cte(MaterializedCte),
60    /// Reads the buffered output of the CTE. This is a leaf.
61    Scan(MaterializedCteScan),
62}
63
64/// Computes `cte` once and evaluates `continuation`, in which every
65/// [`MaterializedCteScan`] with the same `id` reads the buffered output of
66/// `cte`. The output of this node is the output of `continuation`.
67///
68/// The node has two inputs with different roles, in this order:
69///
70/// 1. `cte`: the body of the CTE. It is shared by all the scans, so a rule
71///    must not change its schema, and must not push into it a filter, limit
72///    or projection that belongs to one scan only.
73/// 2. `continuation`: the query that declared the CTE.
74#[derive(Debug, Clone, PartialEq, Eq, Hash)]
75pub struct MaterializedCte {
76    /// Binds the scans in `continuation` to this node
77    pub id: MaterializedCteId,
78    /// Name of the CTE, used for display and error messages only
79    pub name: String,
80    /// The body of the CTE
81    pub cte: Arc<LogicalPlan>,
82    /// The query that declared the CTE and reads it
83    pub continuation: Arc<LogicalPlan>,
84}
85
86impl MaterializedCte {
87    /// Create a new node.
88    ///
89    /// Returns an error if a scan of this CTE in `continuation` (also in a
90    /// subquery expression) does not have the column names and types of `cte`.
91    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    /// The id that binds the scans in the continuation to this node.
116    pub fn id(&self) -> MaterializedCteId {
117        self.id
118    }
119
120    /// The name of the CTE.
121    pub fn name(&self) -> &str {
122        &self.name
123    }
124
125    /// The body of the CTE, which is computed once.
126    pub fn body(&self) -> &Arc<LogicalPlan> {
127        &self.cte
128    }
129
130    /// The query that declared the CTE. It gives this node its output.
131    pub fn continuation(&self) -> &Arc<LogicalPlan> {
132        &self.continuation
133    }
134
135    /// The schema of this node, which is the schema of the continuation.
136    pub fn schema(&self) -> &DFSchemaRef {
137        self.continuation.schema()
138    }
139
140    /// The scans in the continuation that read this CTE, also in subquery
141    /// expressions. See [`MaterializedCteScan::find_in`].
142    pub fn scans(&self) -> Result<Vec<MaterializedCteScan>> {
143        MaterializedCteScan::find_in(&self.continuation, self.id)
144    }
145
146    /// Return a node with the same id and name, and new inputs. The schemas
147    /// of the scans are not checked again.
148    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
162/// Orders by `id` and `name`. Nodes with the same `id` and `name` but a
163/// different `cte` or `continuation` are not comparable, so `Some(Equal)` is
164/// returned only for equal nodes.
165impl 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/// Reads the buffered output of the [`MaterializedCte`] with the same `id`.
179///
180/// This is a leaf. Its schema is the schema of the CTE body and is fixed when
181/// the scan is created.
182#[derive(Debug, Clone, PartialEq, Eq, Hash)]
183pub struct MaterializedCteScan {
184    /// The id of the [`MaterializedCte`] that this scan reads
185    pub id: MaterializedCteId,
186    /// Name of the CTE, used for display and error messages only
187    pub name: String,
188    /// The schema of the CTE body
189    pub schema: DFSchemaRef,
190}
191
192impl MaterializedCteScan {
193    /// Create a scan of the CTE `id`, whose body has the schema `schema`.
194    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    /// The id of the [`MaterializedCte`] that this scan reads.
207    pub fn id(&self) -> MaterializedCteId {
208        self.id
209    }
210
211    /// The name of the CTE.
212    pub fn name(&self) -> &str {
213        &self.name
214    }
215
216    /// The schema of this scan.
217    pub fn schema(&self) -> &DFSchemaRef {
218        &self.schema
219    }
220
221    /// Return a copy of each scan of the CTE `id` in `plan`, also in subquery
222    /// expressions.
223    ///
224    /// The search does not go below a [`MaterializedCte`] with the same `id`
225    /// in `plan`. Such a node is a separate occurrence of the CTE (the id is
226    /// copied when a plan is cloned) and owns the scans below it.
227    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
247/// Orders by `id` and `name`. Scans with the same `id` and `name` but a
248/// different `schema` are not comparable.
249impl 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        // A scan of another CTE is not checked.
356        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        // The union holds one scan, one scan in a subquery expression, one
370        // scan of another CTE, and a nested occurrence of the same CTE, which
371        // owns its scan.
372        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}