Skip to content

Apache DataFusion SQL Query Engine

ARROW-10900: [Rust] [DataFusion] Resolve TableScan provider eagerly

rdettai54d671ad0aa5
diff --git a/rust/datafusion/src/datasource/empty.rs b/rust/datafusion/src/datasource/empty.rs
new file mode 100644
index 0000000000..d8467d931b
--- /dev/null
+++ b/rust/datafusion/src/datasource/empty.rs
@@ -0,0 +1,76 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! An empty plan that is usefull for testing and generating plans without mapping them to actual data.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::datatypes::*;
+
+use crate::datasource::datasource::Statistics;
+use crate::datasource::TableProvider;
+use crate::error::Result;
+use crate::physical_plan::{empty::EmptyExec, ExecutionPlan};
+
+/// A table with a schema but no data.
+pub struct EmptyTable {
+ schema: SchemaRef,
+}
+
+impl EmptyTable {
+ /// Initialize a new `EmptyTable` from a schema.
+ pub fn new(schema: SchemaRef) -> Self {
+ Self { schema }
+ }
+}
+
+impl TableProvider for EmptyTable {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn schema(&self) -> SchemaRef {
+ self.schema.clone()
+ }
+
+ fn scan(
+ &self,
+ projection: &Option<Vec<usize>>,
+ _batch_size: usize,
+ ) -> Result<Arc<dyn ExecutionPlan>> {
+ // even though there is no data, projections apply
+ let projection = match projection.clone() {
+ Some(p) => p,
+ None => (0..self.schema.fields().len()).collect(),
+ };
+ let projected_schema = Schema::new(
+ projection
+ .iter()
+ .map(|i| self.schema.field(*i).clone())
+ .collect(),
+ );
+ Ok(Arc::new(EmptyExec::new(false, Arc::new(projected_schema))))
+ }
+
+ fn statistics(&self) -> Statistics {
+ Statistics {
+ num_rows: Some(0),
+ total_byte_size: Some(0),
+ }
+ }
+}
diff --git a/rust/datafusion/src/datasource/mod.rs b/rust/datafusion/src/datasource/mod.rs
index 5c3b9401be..099098dd6f 100644
--- a/rust/datafusion/src/datasource/mod.rs
+++ b/rust/datafusion/src/datasource/mod.rs
@@ -19,6 +19,7 @@
pub mod csv;
pub mod datasource;
+pub mod empty;
pub mod memory;
pub mod parquet;
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index d01bf6ffeb..4d00ced9ea 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -26,7 +26,6 @@ use std::sync::Arc;
use futures::{StreamExt, TryStreamExt};
use arrow::csv;
-use arrow::datatypes::*;
use crate::datasource::csv::CsvFile;
use crate::datasource::parquet::ParquetTable;
@@ -34,7 +33,7 @@ use crate::datasource::TableProvider;
use crate::error::{DataFusionError, Result};
use crate::execution::dataframe_impl::DataFrameImpl;
use crate::logical_plan::{
- FunctionRegistry, LogicalPlan, LogicalPlanBuilder, TableSource, ToDFSchema,
+ FunctionRegistry, LogicalPlan, LogicalPlanBuilder, ToDFSchema,
};
use crate::optimizer::filter_push_down::FilterPushDown;
use crate::optimizer::optimizer::OptimizerRule;
@@ -46,7 +45,7 @@ use crate::physical_plan::ExecutionPlan;
use crate::physical_plan::PhysicalPlanner;
use crate::sql::{
parser::{DFParser, FileType},
- planner::{SchemaProvider, SqlToRel},
+ planner::{ContextProvider, SqlToRel},
};
use crate::variable::{VarProvider, VarType};
use crate::{dataframe::DataFrame, physical_plan::udaf::AggregateUDF};
@@ -223,9 +222,8 @@ impl ExecutionContext {
) -> Result<Arc<dyn DataFrame>> {
let schema = provider.schema();
let table_scan = LogicalPlan::TableScan {
- schema_name: "".to_string(),
- source: TableSource::FromProvider(provider),
- table_schema: schema.clone(),
+ table_name: "".to_string(),
+ source: provider,
projected_schema: schema.to_dfschema_ref()?,
projection: None,
};
@@ -275,9 +273,8 @@ impl ExecutionContext {
Some(provider) => {
let schema = provider.schema();
let table_scan = LogicalPlan::TableScan {
- schema_name: "".to_string(),
- source: TableSource::FromContext(table_name.to_string()),
- table_schema: schema.clone(),
+ table_name: table_name.to_string(),
+ source: Arc::clone(provider),
projected_schema: schema.to_dfschema_ref()?,
projection: None,
};
@@ -483,9 +480,12 @@ pub struct ExecutionContextState {
pub config: ExecutionConfig,
}
-impl SchemaProvider for ExecutionContextState {
- fn get_table_meta(&self, name: &str) -> Option<SchemaRef> {
- self.datasources.get(name).map(|ds| ds.schema())
+impl ContextProvider for ExecutionContextState {
+ fn get_table_provider(
+ &self,
+ name: &str,
+ ) -> Option<Arc<dyn TableProvider + Send + Sync>> {
+ self.datasources.get(name).map(|ds| Arc::clone(ds))
}
fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>> {
@@ -540,6 +540,7 @@ mod tests {
};
use arrow::array::{ArrayRef, Float64Array, Int32Array, StringArray};
use arrow::compute::add;
+ use arrow::datatypes::*;
use arrow::record_batch::RecordBatch;
use std::fs::File;
use std::thread::{self, JoinHandle};
@@ -643,11 +644,11 @@ mod tests {
match &optimized_plan {
LogicalPlan::Projection { input, .. } => match &**input {
LogicalPlan::TableScan {
- table_schema,
+ source,
projected_schema,
..
} => {
- assert_eq!(table_schema.fields().len(), 2);
+ assert_eq!(source.schema().fields().len(), 2);
assert_eq!(projected_schema.fields().len(), 1);
}
_ => panic!("input to projection should be TableScan"),
@@ -680,7 +681,7 @@ mod tests {
let schema = ctx.state.datasources.get("test").unwrap().schema();
assert_eq!(schema.field_with_name("c1")?.is_nullable(), false);
- let plan = LogicalPlanBuilder::scan("default", "test", schema.as_ref(), None)?
+ let plan = LogicalPlanBuilder::scan_empty("", schema.as_ref(), None)?
.project(vec![col("c1")])?
.build()?;
@@ -721,11 +722,11 @@ mod tests {
match &optimized_plan {
LogicalPlan::Projection { input, .. } => match &**input {
LogicalPlan::TableScan {
- table_schema,
+ source,
projected_schema,
..
} => {
- assert_eq!(table_schema.fields().len(), 3);
+ assert_eq!(source.schema().fields().len(), 3);
assert_eq!(projected_schema.fields().len(), 1);
}
_ => panic!("input to projection should be InMemoryScan"),
@@ -1112,7 +1113,7 @@ mod tests {
Field::new("c2", DataType::UInt32, false),
]));
- let plan = LogicalPlanBuilder::scan("default", "test", schema.as_ref(), None)?
+ let plan = LogicalPlanBuilder::scan_empty("", schema.as_ref(), None)?
.aggregate(vec![col("c1")], vec![sum(col("c2"))])?
.project(vec![col("c1"), col("SUM(c2)").alias("total_salary")])?
.build()?;
diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rs
index dc758146f8..75a6798df1 100644
--- a/rust/datafusion/src/logical_plan/builder.rs
+++ b/rust/datafusion/src/logical_plan/builder.rs
@@ -27,14 +27,13 @@ use arrow::{
use crate::datasource::TableProvider;
use crate::error::{DataFusionError, Result};
use crate::{
- datasource::{parquet::ParquetTable, CsvFile, MemTable},
+ datasource::{empty::EmptyTable, parquet::ParquetTable, CsvFile, MemTable},
prelude::CsvReadOptions,
};
use super::dfschema::ToDFSchema;
use super::{
col, exprlist_to_fields, Expr, JoinType, LogicalPlan, PlanType, StringifiedPlan,
- TableSource,
};
use crate::logical_plan::{DFField, DFSchema, DFSchemaRef};
use std::collections::HashSet;
@@ -66,22 +65,8 @@ impl LogicalPlanBuilder {
schema: SchemaRef,
projection: Option<Vec<usize>>,
) -> Result<Self> {
- let provider = Arc::new(MemTable::try_new(schema.clone(), partitions)?);
-
- let projected_schema = projection
- .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()))
- .map_or(schema.clone(), SchemaRef::new)
- .to_dfschema_ref()?;
-
- let table_scan = LogicalPlan::TableScan {
- schema_name: "".to_string(),
- source: TableSource::FromProvider(provider),
- table_schema: schema,
- projected_schema,
- projection: None,
- };
-
- Ok(Self::from(&table_scan))
+ let provider = Arc::new(MemTable::try_new(schema, partitions)?);
+ Self::scan("", provider, projection)
}
/// Scan a CSV data source
@@ -90,77 +75,51 @@ impl LogicalPlanBuilder {
options: CsvReadOptions,
projection: Option<Vec<usize>>,
) -> Result<Self> {
- let schema: Schema = match options.schema {
- Some(s) => s.to_owned(),
- None => CsvFile::try_new(path, options)?
- .schema()
- .as_ref()
- .to_owned(),
- };
-
- let projected_schema = projection
- .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()))
- .map_or(SchemaRef::new(schema), SchemaRef::new)
- .to_dfschema_ref()?;
-
let provider = Arc::new(CsvFile::try_new(path, options)?);
- let schema = provider.schema();
-
- let table_scan = LogicalPlan::TableScan {
- schema_name: "".to_string(),
- source: TableSource::FromProvider(provider),
- table_schema: schema,
- projected_schema,
- projection: None,
- };
-
- Ok(Self::from(&table_scan))
+ Self::scan("", provider, projection)
}
/// Scan a Parquet data source
pub fn scan_parquet(path: &str, projection: Option<Vec<usize>>) -> Result<Self> {
let provider = Arc::new(ParquetTable::try_new(path)?);
+ Self::scan("", provider, projection)
+ }
+
+ /// Scan an empty data source, mainly used in tests
+ pub fn scan_empty(
+ name: &str,
+ table_schema: &Schema,
+ projection: Option<Vec<usize>>,
+ ) -> Result<Self> {
+ let table_schema = Arc::new(table_schema.clone());
+ let provider = Arc::new(EmptyTable::new(table_schema));
+ Self::scan(name, provider, projection)
+ }
+
+ /// Convert a table provider into a builder with a TableScan
+ pub fn scan(
+ name: &str,
+ provider: Arc<dyn TableProvider + Send + Sync>,
+ projection: Option<Vec<usize>>,
+ ) -> Result<Self> {
let schema = provider.schema();
let projected_schema = projection
+ .as_ref()
.map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()))
- .map_or(schema.clone(), SchemaRef::new)
+ .map_or(schema, SchemaRef::new)
.to_dfschema_ref()?;
let table_scan = LogicalPlan::TableScan {
- schema_name: "".to_string(),
- source: TableSource::FromProvider(provider),
- table_schema: schema,
+ table_name: name.to_string(),
+ source: provider,
projected_schema,
- projection: None,
+ projection,
};
Ok(Self::from(&table_scan))
}
- /// Scan a data source
- pub fn scan(
- schema_name: &str,
- table_name: &str,
- table_schema: &Schema,
- projection: Option<Vec<usize>>,
- ) -> Result<Self> {
- let table_schema = SchemaRef::new(table_schema.clone());
- let projected_schema = projection.clone().map(|p| {
- Schema::new(p.iter().map(|i| table_schema.field(*i).clone()).collect())
- });
- let projected_schema =
- projected_schema.map_or(table_schema.clone(), SchemaRef::new);
-
- Ok(Self::from(&LogicalPlan::TableScan {
- schema_name: schema_name.to_owned(),
- source: TableSource::FromContext(table_name.to_owned()),
- table_schema,
- projected_schema: projected_schema.to_dfschema_ref()?,
- projection,
- }))
- }
-
/// Apply a projection.
///
/// # Errors
@@ -373,8 +332,7 @@ mod tests {
#[test]
fn plan_builder_simple() -> Result<()> {
- let plan = LogicalPlanBuilder::scan(
- "default",
+ let plan = LogicalPlanBuilder::scan_empty(
"employee.csv",
&employee_schema(),
Some(vec![0, 3]),
@@ -394,8 +352,7 @@ mod tests {
#[test]
fn plan_builder_aggregate() -> Result<()> {
- let plan = LogicalPlanBuilder::scan(
- "default",
+ let plan = LogicalPlanBuilder::scan_empty(
"employee.csv",
&employee_schema(),
Some(vec![3, 4]),
@@ -418,8 +375,7 @@ mod tests {
#[test]
fn plan_builder_sort() -> Result<()> {
- let plan = LogicalPlanBuilder::scan(
- "default",
+ let plan = LogicalPlanBuilder::scan_empty(
"employee.csv",
&employee_schema(),
Some(vec![3, 4]),
@@ -448,8 +404,7 @@ mod tests {
#[test]
fn projection_non_unique_names() -> Result<()> {
- let plan = LogicalPlanBuilder::scan(
- "default",
+ let plan = LogicalPlanBuilder::scan_empty(
"employee.csv",
&employee_schema(),
Some(vec![0, 3]),
@@ -472,8 +427,7 @@ mod tests {
#[test]
fn aggregate_non_unique_names() -> Result<()> {
- let plan = LogicalPlanBuilder::scan(
- "default",
+ let plan = LogicalPlanBuilder::scan_empty(
"employee.csv",
&employee_schema(),
Some(vec![0, 3]),
diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rs
index d6fd5fcfa5..fc38057dfe 100644
--- a/rust/datafusion/src/logical_plan/mod.rs
+++ b/rust/datafusion/src/logical_plan/mod.rs
@@ -41,7 +41,5 @@ pub use expr::{
};
pub use extension::UserDefinedLogicalNode;
pub use operators::Operator;
-pub use plan::{
- JoinType, LogicalPlan, PlanType, PlanVisitor, StringifiedPlan, TableSource,
-};
+pub use plan::{JoinType, LogicalPlan, PlanType, PlanVisitor, StringifiedPlan};
pub use registry::FunctionRegistry;
diff --git a/rust/datafusion/src/logical_plan/plan.rs b/rust/datafusion/src/logical_plan/plan.rs
index 76c6d02d69..bdc8c8541e 100644
--- a/rust/datafusion/src/logical_plan/plan.rs
+++ b/rust/datafusion/src/logical_plan/plan.rs
@@ -18,6 +18,7 @@
//! via a logical query plan.
use std::{
+ cmp::min,
fmt::{self, Display},
sync::Arc,
};
@@ -32,15 +33,6 @@ use super::expr::Expr;
use super::extension::UserDefinedLogicalNode;
use crate::logical_plan::dfschema::DFSchemaRef;
-/// Describes the source of the table, either registered on the context or by reference
-#[derive(Clone)]
-pub enum TableSource {
- /// The source provider is registered in the context with the corresponding name
- FromContext(String),
- /// The source provider is passed directly by reference
- FromProvider(Arc<dyn TableProvider + Send + Sync>),
-}
-
/// Join type
#[derive(Debug, Clone)]
pub enum JoinType {
@@ -120,12 +112,10 @@ pub enum LogicalPlan {
},
/// Produces rows from a table provider by reference or from the context
TableScan {
- /// The name of the schema
- schema_name: String,
+ /// The name of the table
+ table_name: String,
/// The source of the table
- source: TableSource,
- /// The schema of the source data
- table_schema: SchemaRef,
+ source: Arc<dyn TableProvider + Send + Sync>,
/// Optional column indices to use as a projection
projection: Option<Vec<usize>>,
/// The schema description of the output
@@ -318,7 +308,7 @@ impl LogicalPlan {
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int32, false),
/// ]);
- /// let plan = LogicalPlanBuilder::scan("default", "foo.csv", &schema, None).unwrap()
+ /// let plan = LogicalPlanBuilder::scan_empty("foo.csv", &schema, None).unwrap()
/// .filter(col("id").eq(lit(5))).unwrap()
/// .build().unwrap();
///
@@ -359,7 +349,7 @@ impl LogicalPlan {
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int32, false),
/// ]);
- /// let plan = LogicalPlanBuilder::scan("default", "foo.csv", &schema, None).unwrap()
+ /// let plan = LogicalPlanBuilder::scan_empty("foo.csv", &schema, None).unwrap()
/// .filter(col("id").eq(lit(5))).unwrap()
/// .build().unwrap();
///
@@ -399,7 +389,7 @@ impl LogicalPlan {
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int32, false),
/// ]);
- /// let plan = LogicalPlanBuilder::scan("default", "foo.csv", &schema, None).unwrap()
+ /// let plan = LogicalPlanBuilder::scan_empty("foo.csv", &schema, None).unwrap()
/// .filter(col("id").eq(lit(5))).unwrap()
/// .build().unwrap();
///
@@ -458,7 +448,7 @@ impl LogicalPlan {
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int32, false),
/// ]);
- /// let plan = LogicalPlanBuilder::scan("default", "foo.csv", &schema, None).unwrap()
+ /// let plan = LogicalPlanBuilder::scan_empty("foo.csv", &schema, None).unwrap()
/// .build().unwrap();
///
/// // Format using display
@@ -475,19 +465,17 @@ impl LogicalPlan {
match *self.0 {
LogicalPlan::EmptyRelation { .. } => write!(f, "EmptyRelation"),
LogicalPlan::TableScan {
- ref source,
+ ref table_name,
ref projection,
..
- } => match source {
- TableSource::FromContext(table_name) => write!(
+ } => {
+ let sep = " ".repeat(min(1, table_name.len()));
+ write!(
f,
- "TableScan: {} projection={:?}",
- table_name, projection
- ),
- TableSource::FromProvider(_) => {
- write!(f, "TableScan: projection={:?}", projection)
- }
- },
+ "TableScan: {}{}projection={:?}",
+ table_name, sep, projection
+ )
+ }
LogicalPlan::Projection { ref expr, .. } => {
write!(f, "Projection: ")?;
for i in 0..expr.len() {
@@ -613,8 +601,7 @@ mod tests {
}
fn display_plan() -> LogicalPlan {
- LogicalPlanBuilder::scan(
- "default",
+ LogicalPlanBuilder::scan_empty(
"employee.csv",
&employee_schema(),
Some(vec![0, 3]),
@@ -911,7 +898,7 @@ mod tests {
fn test_plan() -> LogicalPlan {
let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
- LogicalPlanBuilder::scan("default", "employee.csv", &schema, Some(vec![0]))
+ LogicalPlanBuilder::scan_empty("", &schema, Some(vec![0]))
.unwrap()
.filter(col("state").eq(lit("CO")))
.unwrap()
diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rs
index c1240d9175..0084d68d5c 100644
--- a/rust/datafusion/src/optimizer/projection_push_down.rs
+++ b/rust/datafusion/src/optimizer/projection_push_down.rs
@@ -240,14 +240,13 @@ fn optimize_plan(
// scans:
// * remove un-used columns from the scan projection
LogicalPlan::TableScan {
- schema_name,
+ table_name,
source,
- table_schema,
projection,
..
} => {
let (projection, projected_schema) = get_projected_schema(
- &table_schema,
+ &source.schema(),
projection,
required_columns,
has_projection,
@@ -255,9 +254,8 @@ fn optimize_plan(
// return the table scan with projection
Ok(LogicalPlan::TableScan {
- schema_name: schema_name.to_string(),
+ table_name: table_name.to_string(),
source: source.clone(),
- table_schema: table_schema.clone(),
projection: Some(projection),
projected_schema,
})
diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rs
index cae2e4e82d..a1fb5b1877 100644
--- a/rust/datafusion/src/physical_plan/planner.rs
+++ b/rust/datafusion/src/physical_plan/planner.rs
@@ -23,7 +23,7 @@ use super::{aggregates, empty::EmptyExec, expressions::binary, functions, udaf};
use crate::error::{DataFusionError, Result};
use crate::execution::context::ExecutionContextState;
use crate::logical_plan::{
- DFSchema, Expr, LogicalPlan, Operator, PlanType, StringifiedPlan, TableSource,
+ DFSchema, Expr, LogicalPlan, Operator, PlanType, StringifiedPlan,
UserDefinedLogicalNode,
};
use crate::physical_plan::explain::ExplainExec;
@@ -138,21 +138,7 @@ impl DefaultPhysicalPlanner {
match logical_plan {
LogicalPlan::TableScan {
source, projection, ..
- } => match source {
- TableSource::FromContext(table_name) => {
- match ctx_state.datasources.get(table_name) {
- Some(provider) => provider.scan(projection, batch_size),
- _ => Err(DataFusionError::Plan(format!(
- "No table named {}. Existing tables: {:?}",
- table_name,
- ctx_state.datasources.keys().collect::<Vec<_>>(),
- ))),
- }
- }
- TableSource::FromProvider(ref provider) => {
- provider.scan(projection, batch_size)
- }
- },
+ } => source.scan(projection, batch_size),
LogicalPlan::Aggregate {
input,
group_expr,
diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rs
index eb9a1a54d1..4d469c8305 100644
--- a/rust/datafusion/src/sql/planner.rs
+++ b/rust/datafusion/src/sql/planner.rs
@@ -20,6 +20,7 @@
use std::str::FromStr;
use std::sync::Arc;
+use crate::datasource::TableProvider;
use crate::logical_plan::Expr::Alias;
use crate::logical_plan::{
and, lit, DFSchema, Expr, LogicalPlan, LogicalPlanBuilder, Operator, PlanType,
@@ -49,11 +50,14 @@ use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};
use sqlparser::ast::{OrderByExpr, Statement};
use sqlparser::parser::ParserError::ParserError;
-/// The SchemaProvider trait allows the query planner to obtain meta-data about tables and
+/// The ContextProvider trait allows the query planner to obtain meta-data about tables and
/// functions referenced in SQL statements
-pub trait SchemaProvider {
- /// Getter for a field description
- fn get_table_meta(&self, name: &str) -> Option<SchemaRef>;
+pub trait ContextProvider {
+ /// Getter for a datasource
+ fn get_table_provider(
+ &self,
+ name: &str,
+ ) -> Option<Arc<dyn TableProvider + Send + Sync>>;
/// Getter for a UDF description
fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>>;
/// Getter for a UDAF description
@@ -61,11 +65,11 @@ pub trait SchemaProvider {
}
/// SQL query planner
-pub struct SqlToRel<'a, S: SchemaProvider> {
+pub struct SqlToRel<'a, S: ContextProvider> {
schema_provider: &'a S,
}
-impl<'a, S: SchemaProvider> SqlToRel<'a, S> {
+impl<'a, S: ContextProvider> SqlToRel<'a, S> {
/// Create a new query planner
pub fn new(schema_provider: &'a S) -> Self {
SqlToRel { schema_provider }
@@ -305,16 +309,12 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {
match relation {
TableFactor::Table { name, .. } => {
let table_name = name.to_string();
- match self.schema_provider.get_table_meta(&table_name) {
- Some(schema) => LogicalPlanBuilder::scan(
- "default",
- &table_name,
- schema.as_ref(),
- None,
- )?
- .build(),
+ match self.schema_provider.get_table_provider(&table_name) {
+ Some(provider) => {
+ LogicalPlanBuilder::scan(&table_name, provider, None)?.build()
+ }
None => Err(DataFusionError::Plan(format!(
- "no schema found for table {}",
+ "no provider found for table {}",
name
))),
}
@@ -920,6 +920,7 @@ pub fn convert_data_type(sql: &SQLDataType) -> Result<DataType> {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::datasource::empty::EmptyTable;
use crate::{logical_plan::create_udf, sql::parser::DFParser};
use functions::ScalarFunctionImplementation;
@@ -1328,7 +1329,7 @@ mod tests {
}
fn logical_plan(sql: &str) -> Result<LogicalPlan> {
- let planner = SqlToRel::new(&MockSchemaProvider {});
+ let planner = SqlToRel::new(&MockContextProvider {});
let result = DFParser::parse_sql(&sql);
let ast = result.unwrap();
planner.statement_to_plan(&ast[0])
@@ -1340,12 +1341,15 @@ mod tests {
assert_eq!(expected, format!("{:?}", plan));
}
- struct MockSchemaProvider {}
+ struct MockContextProvider {}
- impl SchemaProvider for MockSchemaProvider {
- fn get_table_meta(&self, name: &str) -> Option<SchemaRef> {
- match name {
- "person" => Some(Arc::new(Schema::new(vec![
+ impl ContextProvider for MockContextProvider {
+ fn get_table_provider(
+ &self,
+ name: &str,
+ ) -> Option<Arc<dyn TableProvider + Send + Sync>> {
+ let schema = match name {
+ "person" => Some(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("first_name", DataType::Utf8, false),
Field::new("last_name", DataType::Utf8, false),
@@ -1357,19 +1361,19 @@ mod tests {
DataType::Timestamp(TimeUnit::Nanosecond, None),
false,
),
- ]))),
- "orders" => Some(Arc::new(Schema::new(vec![
+ ])),
+ "orders" => Some(Schema::new(vec![
Field::new("order_id", DataType::UInt32, false),
Field::new("customer_id", DataType::UInt32, false),
Field::new("o_item_id", DataType::Utf8, false),
Field::new("qty", DataType::Int32, false),
Field::new("price", DataType::Float64, false),
- ]))),
- "lineitem" => Some(Arc::new(Schema::new(vec![
+ ])),
+ "lineitem" => Some(Schema::new(vec![
Field::new("l_item_id", DataType::UInt32, false),
Field::new("l_description", DataType::Utf8, false),
- ]))),
- "aggregate_test_100" => Some(Arc::new(Schema::new(vec![
+ ])),
+ "aggregate_test_100" => Some(Schema::new(vec![
Field::new("c1", DataType::Utf8, false),
Field::new("c2", DataType::UInt32, false),
Field::new("c3", DataType::Int8, false),
@@ -1383,9 +1387,12 @@ mod tests {
Field::new("c11", DataType::Float32, false),
Field::new("c12", DataType::Float64, false),
Field::new("c13", DataType::Utf8, false),
- ]))),
+ ])),
_ => None,
- }
+ };
+ schema.map(|s| -> Arc<dyn TableProvider + Send + Sync> {
+ Arc::new(EmptyTable::new(Arc::new(s)))
+ })
}
fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>> {
diff --git a/rust/datafusion/src/test/mod.rs b/rust/datafusion/src/test/mod.rs
index fb7dbdb297..a380df0797 100644
--- a/rust/datafusion/src/test/mod.rs
+++ b/rust/datafusion/src/test/mod.rs
@@ -231,7 +231,7 @@ pub fn test_table_scan() -> Result<LogicalPlan> {
Field::new("b", DataType::UInt32, false),
Field::new("c", DataType::UInt32, false),
]);
- LogicalPlanBuilder::scan("default", "test", &schema, None)?.build()
+ LogicalPlanBuilder::scan_empty("test", &schema, None)?.build()
}
pub fn assert_fields_eq(plan: &LogicalPlan, expected: Vec<&str>) {
diff --git a/rust/datafusion/tests/dataframe.rs b/rust/datafusion/tests/dataframe.rs
index af6aeda88e..45ba517503 100644
--- a/rust/datafusion/tests/dataframe.rs
+++ b/rust/datafusion/tests/dataframe.rs
@@ -165,11 +165,11 @@ async fn custom_source_dataframe() -> Result<()> {
match &optimized_plan {
LogicalPlan::Projection { input, .. } => match &**input {
LogicalPlan::TableScan {
- table_schema,
+ source,
projected_schema,
..
} => {
- assert_eq!(table_schema.fields().len(), 2);
+ assert_eq!(source.schema().fields().len(), 2);
assert_eq!(projected_schema.fields().len(), 1);
}
_ => panic!("input to projection should be TableScan"),