Skip to main content

datafusion_catalog/
cte_worktable.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//! CteWorkTable implementation used for recursive queries
6
7use std::borrow::Cow;
8use std::future::ready;
9use std::sync::Arc;
10
11use arrow::datatypes::SchemaRef;
12use async_trait::async_trait;
13use datafusion_common::error::Result;
14use datafusion_expr::{Expr, LogicalPlan, TableProviderFilterPushDown, TableType};
15use datafusion_physical_plan::ExecutionPlan;
16use datafusion_physical_plan::work_table::WorkTableExec;
17use futures::future::BoxFuture;
18
19use crate::{ScanArgs, ScanResult, Session, TableProvider};
20
21/// The temporary working table where the previous iteration of a recursive query is stored
22/// Naming is based on PostgreSQL's implementation.
23/// See here for more details: www.postgresql.org/docs/11/queries-with.html#id-1.5.6.12.5.4
24#[derive(Debug)]
25pub struct CteWorkTable {
26    /// The name of the CTE work table
27    name: String,
28    /// Schema exposed by recursive self-references while planning the recursive term.
29    ///
30    /// This is a conservative work-table schema, not the final recursive query output
31    /// schema. For example, the SQL planner may mark fields nullable here so recursive
32    /// references do not inherit unsound anchor-term nullability assumptions.
33    table_schema: SchemaRef,
34}
35
36impl CteWorkTable {
37    /// Construct a new CteWorkTable with the given name and self-reference schema.
38    pub fn new(name: &str, table_schema: SchemaRef) -> Self {
39        Self {
40            name: name.to_owned(),
41            table_schema,
42        }
43    }
44
45    /// The user-provided name of the CTE
46    pub fn name(&self) -> &str {
47        &self.name
48    }
49
50    /// The schema exposed by scans of the recursive self-reference.
51    pub fn schema(&self) -> SchemaRef {
52        Arc::clone(&self.table_schema)
53    }
54}
55
56#[async_trait]
57impl TableProvider for CteWorkTable {
58    fn get_logical_plan(&'_ self) -> Option<Cow<'_, LogicalPlan>> {
59        None
60    }
61
62    fn schema(&self) -> SchemaRef {
63        Arc::clone(&self.table_schema)
64    }
65
66    fn table_type(&self) -> TableType {
67        TableType::Temporary
68    }
69
70    // Hand-written `#[async_trait]` expansion to reduce compile time. See
71    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
72    fn scan<'life0, 'life1, 'life2, 'life3, 'async_trait>(
73        &'life0 self,
74        state: &'life1 dyn Session,
75        projection: Option<&'life2 [usize]>,
76        filters: &'life3 [Expr],
77        limit: Option<usize>,
78    ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
79    where
80        'life0: 'async_trait,
81        'life1: 'async_trait,
82        'life2: 'async_trait,
83        'life3: 'async_trait,
84        Self: 'async_trait,
85    {
86        self.scan_boxed(state, projection, filters, limit)
87    }
88
89    // Hand-written `#[async_trait]` expansion to reduce compile time. See
90    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
91    fn scan_with_args<'a, 'life0, 'life1, 'async_trait>(
92        &'life0 self,
93        state: &'life1 dyn Session,
94        args: ScanArgs<'a>,
95    ) -> BoxFuture<'async_trait, Result<ScanResult>>
96    where
97        'a: 'async_trait,
98        'life0: 'async_trait,
99        'life1: 'async_trait,
100        Self: 'async_trait,
101    {
102        Box::pin(ready(self.scan_with_args_inner(state, &args)))
103    }
104
105    fn supports_filters_pushdown(
106        &self,
107        filters: &[&Expr],
108    ) -> Result<Vec<TableProviderFilterPushDown>> {
109        // TODO: should we support filter pushdown?
110        Ok(vec![
111            TableProviderFilterPushDown::Unsupported;
112            filters.len()
113        ])
114    }
115}
116
117impl CteWorkTable {
118    fn scan_with_args_inner(
119        &self,
120        _state: &dyn Session,
121        args: &ScanArgs<'_>,
122    ) -> Result<ScanResult> {
123        Ok(ScanResult::new(Arc::new(WorkTableExec::new(
124            self.name.clone(),
125            Arc::clone(&self.table_schema),
126            args.projection().map(|p| p.to_vec()),
127        )?)))
128    }
129
130    fn scan_boxed<'a>(
131        &'a self,
132        state: &'a dyn Session,
133        projection: Option<&'a [usize]>,
134        filters: &'a [Expr],
135        limit: Option<usize>,
136    ) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
137        Box::pin(self.scan_inner(state, projection, filters, limit))
138    }
139
140    async fn scan_inner(
141        &self,
142        state: &dyn Session,
143        projection: Option<&[usize]>,
144        filters: &[Expr],
145        limit: Option<usize>,
146    ) -> Result<Arc<dyn ExecutionPlan>> {
147        let options = ScanArgs::default()
148            .with_projection(projection)
149            .with_filters(Some(filters))
150            .with_limit(limit);
151        Ok(self.scan_with_args(state, options).await?.into_inner())
152    }
153}