Skip to main content

datafusion_catalog/
view.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//! View data source which uses a LogicalPlan as it's input.
6
7use std::{borrow::Cow, sync::Arc};
8
9use crate::Session;
10use crate::TableProvider;
11
12use arrow::datatypes::SchemaRef;
13use async_trait::async_trait;
14use datafusion_common::Column;
15use datafusion_common::error::Result;
16use datafusion_expr::TableType;
17use datafusion_expr::{Expr, LogicalPlan};
18use datafusion_expr::{LogicalPlanBuilder, TableProviderFilterPushDown};
19use datafusion_physical_plan::ExecutionPlan;
20use futures::future::BoxFuture;
21
22/// An implementation of `TableProvider` that uses another logical plan.
23#[derive(Debug)]
24pub struct ViewTable {
25    /// LogicalPlan of the view
26    logical_plan: LogicalPlan,
27    /// File fields + partition columns
28    table_schema: SchemaRef,
29    /// SQL used to create the view, if available
30    definition: Option<String>,
31}
32
33impl ViewTable {
34    /// Create new view that is executed at query runtime.
35    ///
36    /// Takes a `LogicalPlan` and optionally the SQL text of the `CREATE`
37    /// statement.
38    ///
39    /// Notes: the `LogicalPlan` is not validated or type coerced. If this is
40    /// needed it should be done after calling this function.
41    pub fn new(logical_plan: LogicalPlan, definition: Option<String>) -> Self {
42        let table_schema = Arc::clone(logical_plan.schema().inner());
43        Self {
44            logical_plan,
45            table_schema,
46            definition,
47        }
48    }
49
50    /// Get definition ref
51    pub fn definition(&self) -> Option<&String> {
52        self.definition.as_ref()
53    }
54
55    /// Get logical_plan ref
56    pub fn logical_plan(&self) -> &LogicalPlan {
57        &self.logical_plan
58    }
59}
60
61#[async_trait]
62impl TableProvider for ViewTable {
63    fn get_logical_plan(&'_ self) -> Option<Cow<'_, LogicalPlan>> {
64        Some(Cow::Borrowed(&self.logical_plan))
65    }
66
67    fn schema(&self) -> SchemaRef {
68        Arc::clone(&self.table_schema)
69    }
70
71    fn table_type(&self) -> TableType {
72        TableType::View
73    }
74
75    fn get_table_definition(&self) -> Option<&str> {
76        self.definition.as_deref()
77    }
78    fn supports_filters_pushdown(
79        &self,
80        filters: &[&Expr],
81    ) -> Result<Vec<TableProviderFilterPushDown>> {
82        // A filter is added on the View when given
83        Ok(vec![TableProviderFilterPushDown::Exact; filters.len()])
84    }
85
86    // Hand-written `#[async_trait]` expansion to reduce compile time. See
87    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
88    fn scan<'life0, 'life1, 'life2, 'life3, 'async_trait>(
89        &'life0 self,
90        state: &'life1 dyn Session,
91        projection: Option<&'life2 [usize]>,
92        filters: &'life3 [Expr],
93        limit: Option<usize>,
94    ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
95    where
96        'life0: 'async_trait,
97        'life1: 'async_trait,
98        'life2: 'async_trait,
99        'life3: 'async_trait,
100        Self: 'async_trait,
101    {
102        self.scan_boxed(state, projection, filters, limit)
103    }
104}
105
106impl ViewTable {
107    fn scan_boxed<'a>(
108        &'a self,
109        state: &'a dyn Session,
110        projection: Option<&'a [usize]>,
111        filters: &'a [Expr],
112        limit: Option<usize>,
113    ) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
114        Box::pin(self.scan_inner(state, projection, filters, limit))
115    }
116
117    async fn scan_inner(
118        &self,
119        state: &dyn Session,
120        projection: Option<&[usize]>,
121        filters: &[Expr],
122        limit: Option<usize>,
123    ) -> Result<Arc<dyn ExecutionPlan>> {
124        let filter = filters.iter().cloned().reduce(|acc, new| acc.and(new));
125        let plan = self.logical_plan().clone();
126        let mut plan = LogicalPlanBuilder::from(plan);
127
128        if let Some(filter) = filter {
129            plan = plan.filter(filter)?;
130        }
131
132        let mut plan = if let Some(projection) = projection {
133            // avoiding adding a redundant projection (e.g. SELECT * FROM view)
134            let current_projection =
135                (0..plan.schema().fields().len()).collect::<Vec<usize>>();
136            if projection == current_projection {
137                plan
138            } else {
139                let fields: Vec<Expr> = projection
140                    .iter()
141                    .map(|i| {
142                        Expr::Column(Column::from(
143                            self.logical_plan.schema().qualified_field(*i),
144                        ))
145                    })
146                    .collect();
147                plan.project(fields)?
148            }
149        } else {
150            plan
151        };
152
153        if let Some(limit) = limit {
154            plan = plan.limit(0, Some(limit))?;
155        }
156
157        state.create_physical_plan(&plan.build()?).await
158    }
159}