datafusion_expr/table_source.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//! Table source
6
7use crate::{Expr, LogicalPlan};
8
9use arrow::datatypes::SchemaRef;
10use datafusion_common::{Constraints, Result};
11
12use std::{any::Any, borrow::Cow};
13
14/// Indicates how a filter expression is handled by
15/// [`TableProvider::scan`].
16///
17/// Filter expressions are boolean expressions used to reduce the number of
18/// rows that are read from a table. Only rows that evaluate to `true` ("pass
19/// the filter") are returned. Rows that evaluate to `false` or `NULL` are
20/// omitted.
21///
22/// [`TableProvider::scan`]: https://docs.rs/datafusion/latest/datafusion/datasource/trait.TableProvider.html#tymethod.scan
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum TableProviderFilterPushDown {
25 /// The filter cannot be used by the provider and will not be pushed down.
26 Unsupported,
27 /// The filter can be used, but the provider might still return some tuples
28 /// that do not pass the filter.
29 ///
30 /// In this case, DataFusion applies an additional `Filter` operation
31 /// after the scan to ensure all rows are filtered correctly.
32 Inexact,
33 /// The provider **guarantees** that it will omit **only** tuples which
34 /// pass the filter.
35 ///
36 /// In this case, DataFusion will not apply additional filtering.
37 Exact,
38}
39
40/// Indicates the type of this table for metadata/catalog purposes.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum TableType {
43 /// An ordinary physical table.
44 Base,
45 /// A non-materialized table that itself uses a query internally to provide data.
46 View,
47 /// A transient table.
48 Temporary,
49}
50
51impl std::fmt::Display for TableType {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 match self {
54 TableType::Base => write!(f, "Base"),
55 TableType::View => write!(f, "View"),
56 TableType::Temporary => write!(f, "Temporary"),
57 }
58 }
59}
60
61/// Planning time information about a table.
62///
63/// This trait is used during logical query planning and optimizations, and
64/// provides a subset of the [`TableProvider`] trait, such as schema information
65/// and filter push-down capabilities. The [`TableProvider`] trait provides
66/// additional information needed for physical query execution, such as the
67/// ability to perform a scan or insert data.
68///
69/// # See Also:
70///
71/// [`DefaultTableSource`] to go from [`TableProvider`], to `TableSource`
72///
73/// # Rationale
74///
75/// The reason for having two separate traits is to avoid having the logical
76/// plan code be dependent on the DataFusion execution engine. Some projects use
77/// DataFusion's logical plans and have their own execution engine.
78///
79/// [`TableProvider`]: https://docs.rs/datafusion/latest/datafusion/datasource/trait.TableProvider.html
80/// [`DefaultTableSource`]: https://docs.rs/datafusion/latest/datafusion/datasource/default_table_source/struct.DefaultTableSource.html
81pub trait TableSource: Any + Sync + Send {
82 /// Get a reference to the schema for this table
83 fn schema(&self) -> SchemaRef;
84
85 /// Get primary key indices, if any
86 fn constraints(&self) -> Option<&Constraints> {
87 None
88 }
89
90 /// Get the type of this table for metadata/catalog purposes.
91 fn table_type(&self) -> TableType {
92 TableType::Base
93 }
94
95 /// Tests whether the table provider can make use of any or all filter expressions
96 /// to optimize data retrieval. Only non-volatile expressions are passed to this function.
97 fn supports_filters_pushdown(
98 &self,
99 filters: &[&Expr],
100 ) -> Result<Vec<TableProviderFilterPushDown>> {
101 Ok((0..filters.len())
102 .map(|_| TableProviderFilterPushDown::Unsupported)
103 .collect())
104 }
105
106 /// Tests whether the underlying table provider can guarantee that a scan
107 /// omits *exactly* the first `skip` rows it would otherwise have
108 /// produced.
109 fn supports_skip_pushdown(&self) -> bool {
110 false
111 }
112
113 /// Get the Logical plan of this table provider, if available.
114 ///
115 /// For example, a view may have a logical plan, but a CSV file does not.
116 fn get_logical_plan(&'_ self) -> Option<Cow<'_, LogicalPlan>> {
117 None
118 }
119
120 /// Get the default value for a column, if available.
121 fn get_column_default(&self, _column: &str) -> Option<&Expr> {
122 None
123 }
124}
125
126impl dyn TableSource {
127 pub fn is<T: TableSource>(&self) -> bool {
128 (self as &dyn Any).is::<T>()
129 }
130
131 pub fn downcast_ref<T: TableSource>(&self) -> Option<&T> {
132 (self as &dyn Any).downcast_ref()
133 }
134}