Skip to content

Apache DataFusion SQL Query Engine

ARROW-10389: [Rust] [DataFusion] Make the custom source implementation API more explicit

rdettai1b98ac1aa921
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index 308623c866..57f9caf606 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -34,7 +34,9 @@ use crate::datasource::parquet::ParquetTable;
use crate::datasource::TableProvider;
use crate::error::{DataFusionError, Result};
use crate::execution::dataframe_impl::DataFrameImpl;
-use crate::logical_plan::{FunctionRegistry, LogicalPlan, LogicalPlanBuilder};
+use crate::logical_plan::{
+ FunctionRegistry, LogicalPlan, LogicalPlanBuilder, TableSource,
+};
use crate::optimizer::filter_push_down::FilterPushDown;
use crate::optimizer::optimizer::OptimizerRule;
use crate::optimizer::projection_push_down::ProjectionPushDown;
@@ -237,6 +239,25 @@ impl ExecutionContext {
)))
}
+ /// Creates a DataFrame for reading a custom TableProvider
+ pub fn read_table(
+ &mut self,
+ provider: Arc<dyn TableProvider + Send + Sync>,
+ ) -> Result<Arc<dyn DataFrame>> {
+ let schema = provider.schema().clone();
+ let table_scan = LogicalPlan::TableScan {
+ schema_name: "".to_string(),
+ source: TableSource::FromProvider(provider),
+ table_schema: schema.clone(),
+ projected_schema: schema,
+ projection: None,
+ };
+ Ok(Arc::new(DataFrameImpl::new(
+ self.state.clone(),
+ &LogicalPlanBuilder::from(&table_scan).build()?,
+ )))
+ }
+
/// Register a CSV data source so that it can be referenced from SQL statements
/// executed against this context.
pub fn register_csv(
@@ -278,7 +299,7 @@ impl ExecutionContext {
let schema = provider.schema().clone();
let table_scan = LogicalPlan::TableScan {
schema_name: "".to_string(),
- table_name: table_name.to_string(),
+ source: TableSource::FromContext(table_name.to_string()),
table_schema: schema.clone(),
projected_schema: schema,
projection: None,
diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rs
index b3004f23da..19ee56d76b 100644
--- a/rust/datafusion/src/logical_plan/mod.rs
+++ b/rust/datafusion/src/logical_plan/mod.rs
@@ -763,6 +763,15 @@ pub trait UserDefinedLogicalNode: Debug {
) -> Arc<dyn UserDefinedLogicalNode + Send + Sync>;
}
+/// 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>),
+}
+
/// A LogicalPlan represents the different types of relational
/// operators (such as Projection, Filter, etc) and can be created by
/// the SQL query planner and the DataFrame API.
@@ -816,14 +825,13 @@ pub enum LogicalPlan {
/// The incoming logical plan
input: Arc<LogicalPlan>,
},
- /// Produces rows from a table that has been registered on a
- /// context
+ /// 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 schema of the CSV file(s)
+ /// The source of the table
+ source: TableSource,
+ /// The schema of the source data
table_schema: SchemaRef,
/// Optional column indices to use as a projection
projection: Option<Vec<usize>>,
@@ -959,10 +967,17 @@ impl LogicalPlan {
match *self {
LogicalPlan::EmptyRelation { .. } => write!(f, "EmptyRelation"),
LogicalPlan::TableScan {
- ref table_name,
+ ref source,
ref projection,
..
- } => write!(f, "TableScan: {} projection={:?}", table_name, projection),
+ } => match source {
+ TableSource::FromContext(table_name) => {
+ write!(f, "TableScan: {} projection={:?}", table_name, projection)
+ }
+ TableSource::FromProvider(_) => {
+ write!(f, "TableScan: projection={:?}", projection)
+ }
+ },
LogicalPlan::InMemoryScan { ref projection, .. } => {
write!(f, "InMemoryScan: projection={:?}", projection)
}
@@ -1156,7 +1171,7 @@ impl LogicalPlanBuilder {
Ok(Self::from(&LogicalPlan::TableScan {
schema_name: schema_name.to_owned(),
- table_name: table_name.to_owned(),
+ source: TableSource::FromContext(table_name.to_owned()),
table_schema,
projected_schema,
projection,
diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rs
index ce4ebd38c7..f4f190cd19 100644
--- a/rust/datafusion/src/optimizer/projection_push_down.rs
+++ b/rust/datafusion/src/optimizer/projection_push_down.rs
@@ -216,7 +216,7 @@ fn optimize_plan(
// * remove un-used columns from the scan projection
LogicalPlan::TableScan {
schema_name,
- table_name,
+ source,
table_schema,
projection,
..
@@ -231,7 +231,7 @@ 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: projected_schema,
diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rs
index bb88b1f49b..1303fa4b0f 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::{
- Expr, LogicalPlan, PlanType, StringifiedPlan, UserDefinedLogicalNode,
+ Expr, LogicalPlan, PlanType, StringifiedPlan, TableSource, UserDefinedLogicalNode,
};
use crate::physical_plan::csv::{CsvExec, CsvReadOptions};
use crate::physical_plan::explain::ExplainExec;
@@ -136,16 +136,21 @@ impl DefaultPhysicalPlanner {
match logical_plan {
LogicalPlan::TableScan {
- table_name,
- projection,
- ..
- } => 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<_>>(),
- ))),
+ 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)
+ }
},
LogicalPlan::InMemoryScan {
data,
diff --git a/rust/datafusion/tests/dataframe.rs b/rust/datafusion/tests/dataframe.rs
new file mode 100644
index 0000000000..3d303ecccd
--- /dev/null
+++ b/rust/datafusion/tests/dataframe.rs
@@ -0,0 +1,188 @@
+// 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.
+
+use arrow::array::Int32Array;
+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use datafusion::datasource::TableProvider;
+use datafusion::error::{DataFusionError, Result};
+
+use datafusion::execution::context::ExecutionContext;
+use datafusion::logical_plan::{col, LogicalPlan, LogicalPlanBuilder};
+use datafusion::physical_plan::{
+ ExecutionPlan, Partitioning, RecordBatchStream, SendableRecordBatchStream,
+};
+
+use futures::stream::Stream;
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use async_trait::async_trait;
+
+//// Custom source dataframe tests ////
+
+struct CustomTableProvider;
+#[derive(Debug, Clone)]
+struct CustomExecutionPlan {
+ projection: Option<Vec<usize>>,
+}
+struct TestCustomRecordBatchStream {
+ /// the nb of batches of TEST_CUSTOM_RECORD_BATCH generated
+ nb_batch: i32,
+}
+macro_rules! TEST_CUSTOM_SCHEMA_REF {
+ () => {
+ Arc::new(Schema::new(vec![
+ Field::new("c1", DataType::Int32, false),
+ Field::new("c2", DataType::Int32, false),
+ ]))
+ };
+}
+macro_rules! TEST_CUSTOM_RECORD_BATCH {
+ () => {
+ RecordBatch::try_new(
+ TEST_CUSTOM_SCHEMA_REF!(),
+ vec![
+ Arc::new(Int32Array::from(vec![1, 10, 10, 100])),
+ Arc::new(Int32Array::from(vec![2, 12, 12, 120])),
+ ],
+ )
+ };
+}
+
+impl RecordBatchStream for TestCustomRecordBatchStream {
+ fn schema(&self) -> SchemaRef {
+ TEST_CUSTOM_SCHEMA_REF!()
+ }
+}
+
+impl Stream for TestCustomRecordBatchStream {
+ type Item = ArrowResult<RecordBatch>;
+
+ fn poll_next(
+ self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ ) -> Poll<Option<Self::Item>> {
+ if self.nb_batch > 0 {
+ self.get_mut().nb_batch -= 1;
+ Poll::Ready(Some(TEST_CUSTOM_RECORD_BATCH!()))
+ } else {
+ Poll::Ready(None)
+ }
+ }
+}
+
+#[async_trait]
+impl ExecutionPlan for CustomExecutionPlan {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn schema(&self) -> SchemaRef {
+ let schema = TEST_CUSTOM_SCHEMA_REF!();
+ match &self.projection {
+ None => schema,
+ Some(p) => Arc::new(Schema::new(
+ p.iter().map(|i| schema.field(*i).clone()).collect(),
+ )),
+ }
+ }
+ fn output_partitioning(&self) -> Partitioning {
+ Partitioning::UnknownPartitioning(1)
+ }
+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+ vec![]
+ }
+ fn with_new_children(
+ &self,
+ children: Vec<Arc<dyn ExecutionPlan>>,
+ ) -> Result<Arc<dyn ExecutionPlan>> {
+ if children.is_empty() {
+ Ok(Arc::new(self.clone()))
+ } else {
+ Err(DataFusionError::Internal(
+ "Children cannot be replaced in CustomExecutionPlan".to_owned(),
+ ))
+ }
+ }
+ async fn execute(&self, _partition: usize) -> Result<SendableRecordBatchStream> {
+ Ok(Box::pin(TestCustomRecordBatchStream { nb_batch: 1 }))
+ }
+}
+
+impl TableProvider for CustomTableProvider {
+ fn schema(&self) -> SchemaRef {
+ TEST_CUSTOM_SCHEMA_REF!()
+ }
+
+ /// Create an ExecutionPlan that will scan the table.
+ fn scan(
+ &self,
+ projection: &Option<Vec<usize>>,
+ _batch_size: usize,
+ ) -> Result<Arc<dyn ExecutionPlan>> {
+ Ok(Arc::new(CustomExecutionPlan {
+ projection: projection.clone(),
+ }))
+ }
+}
+
+#[tokio::test]
+async fn custom_source_dataframe() -> Result<()> {
+ let mut ctx = ExecutionContext::new();
+
+ let table = ctx.read_table(Arc::new(CustomTableProvider))?;
+ let logical_plan = LogicalPlanBuilder::from(&table.to_logical_plan())
+ .project(vec![col("c2")])?
+ .build()?;
+
+ let optimized_plan = ctx.optimize(&logical_plan)?;
+ match &optimized_plan {
+ LogicalPlan::Projection { input, .. } => match &**input {
+ LogicalPlan::TableScan {
+ table_schema,
+ projected_schema,
+ ..
+ } => {
+ assert_eq!(table_schema.fields().len(), 2);
+ assert_eq!(projected_schema.fields().len(), 1);
+ }
+ _ => assert!(false, "input to projection should be TableScan"),
+ },
+ _ => assert!(false, "expect optimized_plan to be projection"),
+ }
+
+ let expected = "Projection: #c2\
+ \n TableScan: projection=Some([1])";
+ assert_eq!(format!("{:?}", optimized_plan), expected);
+
+ let physical_plan = ctx.create_physical_plan(&optimized_plan)?;
+
+ assert_eq!(1, physical_plan.schema().fields().len());
+ assert_eq!("c2", physical_plan.schema().field(0).name().as_str());
+
+ let batches = ctx.collect(physical_plan).await?;
+ let origin_rec_batch = TEST_CUSTOM_RECORD_BATCH!()?;
+ assert_eq!(1, batches.len());
+ assert_eq!(1, batches[0].num_columns());
+ assert_eq!(origin_rec_batch.num_rows(), batches[0].num_rows());
+
+ Ok(())
+}