Apache DataFusion SQL Query Engine
ARROW-9833: [Rust] [DataFusion] TableProvider.scan now returns ExecutionPlan
Andy Grove9896016acb34
diff --git a/rust/datafusion/src/datasource/csv.rs b/rust/datafusion/src/datasource/csv.rsindex b9fea5ed2e..1ce765878e 100644--- a/rust/datafusion/src/datasource/csv.rs+++ b/rust/datafusion/src/datasource/csv.rs@@ -46,7 +46,7 @@ use crate::datasource::TableProvider;use crate::error::Result;use crate::execution::physical_plan::csv::CsvExec;pub use crate::execution::physical_plan::csv::CsvReadOptions;-use crate::execution::physical_plan::{ExecutionPlan, Partition};+use crate::execution::physical_plan::ExecutionPlan;/// Represents a CSV file with a provided schemapub struct CsvFile {@@ -84,8 +84,8 @@ impl TableProvider for CsvFile {&self,projection: &Option<Vec<usize>>,batch_size: usize,- ) -> Result<Vec<Arc<dyn Partition>>> {- let exec = CsvExec::try_new(+ ) -> Result<Arc<dyn ExecutionPlan>> {+ Ok(Arc::new(CsvExec::try_new(&self.filename,CsvReadOptions::new().schema(&self.schema)@@ -94,8 +94,7 @@ impl TableProvider for CsvFile {.file_extension(self.file_extension.as_str()),projection.clone(),batch_size,- )?;- exec.partitions()+ )?))}}diff --git a/rust/datafusion/src/datasource/datasource.rs b/rust/datafusion/src/datasource/datasource.rsindex 1bfedf6522..044a8ab429 100644--- a/rust/datafusion/src/datasource/datasource.rs+++ b/rust/datafusion/src/datasource/datasource.rs@@ -19,10 +19,9 @@use std::sync::Arc;-use arrow::datatypes::SchemaRef;-+use crate::arrow::datatypes::SchemaRef;use crate::error::Result;-use crate::execution::physical_plan::Partition;+use crate::execution::physical_plan::ExecutionPlan;/// Source tablepub trait TableProvider {@@ -35,5 +34,5 @@ pub trait TableProvider {&self,projection: &Option<Vec<usize>>,batch_size: usize,- ) -> Result<Vec<Arc<dyn Partition>>>;+ ) -> Result<Arc<dyn ExecutionPlan>>;}diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rsindex 2a98580676..96eebca592 100644--- a/rust/datafusion/src/datasource/memory.rs+++ b/rust/datafusion/src/datasource/memory.rs@@ -27,7 +27,7 @@ use arrow::record_batch::RecordBatch;use crate::datasource::TableProvider;use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::memory::MemoryExec;-use crate::execution::physical_plan::{ExecutionPlan, Partition};+use crate::execution::physical_plan::ExecutionPlan;/// In-memory tablepub struct MemTable {@@ -57,7 +57,8 @@ impl MemTable {/// Create a mem table by reading from another data sourcepub fn load(t: &dyn TableProvider) -> Result<Self> {let schema = t.schema();- let partitions = t.scan(&None, 1024 * 1024)?;+ let exec = t.scan(&None, 1024 * 1024)?;+ let partitions = exec.partitions()?;let mut data: Vec<Vec<RecordBatch>> = Vec::with_capacity(partitions.len());for partition in &partitions {@@ -83,7 +84,7 @@ impl TableProvider for MemTable {&self,projection: &Option<Vec<usize>>,_batch_size: usize,- ) -> Result<Vec<Arc<dyn Partition>>> {+ ) -> Result<Arc<dyn ExecutionPlan>> {let columns: Vec<usize> = match projection {Some(p) => p.clone(),None => {@@ -111,12 +112,11 @@ impl TableProvider for MemTable {let projected_schema = Arc::new(Schema::new(projected_columns?));- let exec = MemoryExec::try_new(+ Ok(Arc::new(MemoryExec::try_new(&self.batches.clone(),projected_schema,projection.clone(),- )?;- exec.partitions()+ )?))}}@@ -127,7 +127,7 @@ mod tests {use arrow::datatypes::{DataType, Field, Schema};#[test]- fn test_with_projection() {+ fn test_with_projection() -> Result<()> {let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false),Field::new("b", DataType::Int32, false),@@ -141,23 +141,25 @@ mod tests {Arc::new(Int32Array::from(vec![4, 5, 6])),Arc::new(Int32Array::from(vec![7, 8, 9])),],- )- .unwrap();+ )?;- let provider = MemTable::new(schema, vec![vec![batch]]).unwrap();+ let provider = MemTable::new(schema, vec![vec![batch]])?;// scan with projection- let partitions = provider.scan(&Some(vec![2, 1]), 1024).unwrap();- let it = partitions[0].execute().unwrap();- let batch2 = it.lock().unwrap().next_batch().unwrap().unwrap();+ let exec = provider.scan(&Some(vec![2, 1]), 1024)?;+ let partitions = exec.partitions()?;+ let it = partitions[0].execute()?;+ let batch2 = it.lock().expect("mutex lock").next_batch()?.unwrap();assert_eq!(2, batch2.schema().fields().len());assert_eq!("c", batch2.schema().field(0).name());assert_eq!("b", batch2.schema().field(1).name());assert_eq!(2, batch2.num_columns());++ Ok(())}#[test]- fn test_without_projection() {+ fn test_without_projection() -> Result<()> {let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false),Field::new("b", DataType::Int32, false),@@ -171,20 +173,22 @@ mod tests {Arc::new(Int32Array::from(vec![4, 5, 6])),Arc::new(Int32Array::from(vec![7, 8, 9])),],- )- .unwrap();+ )?;- let provider = MemTable::new(schema, vec![vec![batch]]).unwrap();+ let provider = MemTable::new(schema, vec![vec![batch]])?;- let partitions = provider.scan(&None, 1024).unwrap();- let it = partitions[0].execute().unwrap();- let batch1 = it.lock().unwrap().next_batch().unwrap().unwrap();+ let exec = provider.scan(&None, 1024)?;+ let partitions = exec.partitions()?;+ let it = partitions[0].execute()?;+ let batch1 = it.lock().expect("mutex lock").next_batch()?.unwrap();assert_eq!(3, batch1.schema().fields().len());assert_eq!(3, batch1.num_columns());++ Ok(())}#[test]- fn test_invalid_projection() {+ fn test_invalid_projection() -> Result<()> {let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false),Field::new("b", DataType::Int32, false),@@ -198,10 +202,9 @@ mod tests {Arc::new(Int32Array::from(vec![4, 5, 6])),Arc::new(Int32Array::from(vec![7, 8, 9])),],- )- .unwrap();+ )?;- let provider = MemTable::new(schema, vec![vec![batch]]).unwrap();+ let provider = MemTable::new(schema, vec![vec![batch]])?;let projection: Vec<usize> = vec![0, 4];@@ -211,10 +214,12 @@ mod tests {}_ => assert!(false, "Scan should failed on invalid projection"),};++ Ok(())}#[test]- fn test_schema_validation() {+ fn test_schema_validation() -> Result<()> {let schema1 = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false),Field::new("b", DataType::Int32, false),@@ -234,8 +239,7 @@ mod tests {Arc::new(Int32Array::from(vec![4, 5, 6])),Arc::new(Int32Array::from(vec![7, 8, 9])),],- )- .unwrap();+ )?;match MemTable::new(schema2, vec![vec![batch]]) {Err(ExecutionError::General(e)) => assert_eq!(@@ -247,5 +251,7 @@ mod tests {"MemTable::new should have failed due to schema mismatch"),}++ Ok(())}}diff --git a/rust/datafusion/src/datasource/parquet.rs b/rust/datafusion/src/datasource/parquet.rsindex 9dc480e190..776a5153db 100644--- a/rust/datafusion/src/datasource/parquet.rs+++ b/rust/datafusion/src/datasource/parquet.rs@@ -25,7 +25,7 @@ use arrow::datatypes::*;use crate::datasource::TableProvider;use crate::error::Result;use crate::execution::physical_plan::parquet::ParquetExec;-use crate::execution::physical_plan::{ExecutionPlan, Partition};+use crate::execution::physical_plan::ExecutionPlan;/// Table-based representation of a `ParquetFile`.pub struct ParquetTable {@@ -57,11 +57,12 @@ impl TableProvider for ParquetTable {&self,projection: &Option<Vec<usize>>,batch_size: usize,- ) -> Result<Vec<Arc<dyn Partition>>> {- let parquet_exec =- ParquetExec::try_new(&self.path, projection.clone(), batch_size)?;-- parquet_exec.partitions()+ ) -> Result<Arc<dyn ExecutionPlan>> {+ Ok(Arc::new(ParquetExec::try_new(+ &self.path,+ projection.clone(),+ batch_size,+ )?))}}@@ -72,19 +73,20 @@ mod tests {BinaryArray, BooleanArray, Float32Array, Float64Array, Int32Array,TimestampNanosecondArray,};+ use arrow::record_batch::RecordBatch;use std::env;#[test]- fn read_small_batches() {- let table = load_table("alltypes_plain.parquet");-+ fn read_small_batches() -> Result<()> {+ let table = load_table("alltypes_plain.parquet")?;let projection = None;- let scan = table.scan(&projection, 2).unwrap();- let it = scan[0].execute().unwrap();+ let exec = table.scan(&projection, 2)?;+ let partitions = exec.partitions()?;+ let it = partitions[0].execute()?;let mut it = it.lock().unwrap();let mut count = 0;- while let Some(batch) = it.next_batch().unwrap() {+ while let Some(batch) = it.next_batch()? {assert_eq!(11, batch.num_columns());assert_eq!(2, batch.num_rows());count += 1;@@ -92,11 +94,13 @@ mod tests {// we should have seen 4 batches of 2 rowsassert_eq!(4, count);++ Ok(())}#[test]- fn read_alltypes_plain_parquet() {- let table = load_table("alltypes_plain.parquet");+ fn read_alltypes_plain_parquet() -> Result<()> {+ let table = load_table("alltypes_plain.parquet")?;let x: Vec<String> = table.schema()@@ -121,24 +125,19 @@ mod tests {);let projection = None;- let scan = table.scan(&projection, 1024).unwrap();- let it = scan[0].execute().unwrap();- let mut it = it.lock().unwrap();- let batch = it.next_batch().unwrap().unwrap();+ let batch = get_first_batch(table, &projection)?;assert_eq!(11, batch.num_columns());assert_eq!(8, batch.num_rows());++ Ok(())}#[test]- fn read_bool_alltypes_plain_parquet() {- let table = load_table("alltypes_plain.parquet");-+ fn read_bool_alltypes_plain_parquet() -> Result<()> {+ let table = load_table("alltypes_plain.parquet")?;let projection = Some(vec![1]);- let scan = table.scan(&projection, 1024).unwrap();- let it = scan[0].execute().unwrap();- let mut it = it.lock().unwrap();- let batch = it.next_batch().unwrap().unwrap();+ let batch = get_first_batch(table, &projection)?;assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -157,17 +156,15 @@ mod tests {"[true, false, true, false, true, false, true, false]",format!("{:?}", values));++ Ok(())}#[test]- fn read_i32_alltypes_plain_parquet() {- let table = load_table("alltypes_plain.parquet");-+ fn read_i32_alltypes_plain_parquet() -> Result<()> {+ let table = load_table("alltypes_plain.parquet")?;let projection = Some(vec![0]);- let scan = table.scan(&projection, 1024).unwrap();- let it = scan[0].execute().unwrap();- let mut it = it.lock().unwrap();- let batch = it.next_batch().unwrap().unwrap();+ let batch = get_first_batch(table, &projection)?;assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -183,17 +180,15 @@ mod tests {}assert_eq!("[4, 5, 6, 7, 2, 3, 0, 1]", format!("{:?}", values));++ Ok(())}#[test]- fn read_i96_alltypes_plain_parquet() {- let table = load_table("alltypes_plain.parquet");-+ fn read_i96_alltypes_plain_parquet() -> Result<()> {+ let table = load_table("alltypes_plain.parquet")?;let projection = Some(vec![10]);- let scan = table.scan(&projection, 1024).unwrap();- let it = scan[0].execute().unwrap();- let mut it = it.lock().unwrap();- let batch = it.next_batch().unwrap().unwrap();+ let batch = get_first_batch(table, &projection)?;assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -209,17 +204,16 @@ mod tests {}assert_eq!("[1235865600000000000, 1235865660000000000, 1238544000000000000, 1238544060000000000, 1233446400000000000, 1233446460000000000, 1230768000000000000, 1230768060000000000]", format!("{:?}", values));++ Ok(())}#[test]- fn read_f32_alltypes_plain_parquet() {- let table = load_table("alltypes_plain.parquet");-+ fn read_f32_alltypes_plain_parquet() -> Result<()> {+ let table = load_table("alltypes_plain.parquet")?;let projection = Some(vec![6]);- let scan = table.scan(&projection, 1024).unwrap();- let it = scan[0].execute().unwrap();- let mut it = it.lock().unwrap();- let batch = it.next_batch().unwrap().unwrap();+ let batch = get_first_batch(table, &projection)?;+assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -237,17 +231,15 @@ mod tests {"[0.0, 1.1, 0.0, 1.1, 0.0, 1.1, 0.0, 1.1]",format!("{:?}", values));++ Ok(())}#[test]- fn read_f64_alltypes_plain_parquet() {- let table = load_table("alltypes_plain.parquet");-+ fn read_f64_alltypes_plain_parquet() -> Result<()> {+ let table = load_table("alltypes_plain.parquet")?;let projection = Some(vec![7]);- let scan = table.scan(&projection, 1024).unwrap();- let it = scan[0].execute().unwrap();- let mut it = it.lock().unwrap();- let batch = it.next_batch().unwrap().unwrap();+ let batch = get_first_batch(table, &projection)?;assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -266,17 +258,15 @@ mod tests {"[0.0, 10.1, 0.0, 10.1, 0.0, 10.1, 0.0, 10.1]",format!("{:?}", values));++ Ok(())}#[test]- fn read_binary_alltypes_plain_parquet() {- let table = load_table("alltypes_plain.parquet");-+ fn read_binary_alltypes_plain_parquet() -> Result<()> {+ let table = load_table("alltypes_plain.parquet")?;let projection = Some(vec![9]);- let scan = table.scan(&projection, 1024).unwrap();- let it = scan[0].execute().unwrap();- let mut it = it.lock().unwrap();- let batch = it.next_batch().unwrap().unwrap();+ let batch = get_first_batch(table, &projection)?;assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -295,13 +285,28 @@ mod tests {"[\"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\"]",format!("{:?}", values));++ Ok(())}- fn load_table(name: &str) -> Box<dyn TableProvider> {+ fn load_table(name: &str) -> Result<Box<dyn TableProvider>> {let testdata =env::var("PARQUET_TEST_DATA").expect("PARQUET_TEST_DATA not defined");let filename = format!("{}/{}", testdata, name);- let table = ParquetTable::try_new(&filename).unwrap();- Box::new(table)+ let table = ParquetTable::try_new(&filename)?;+ Ok(Box::new(table))+ }++ fn get_first_batch(+ table: Box<dyn TableProvider>,+ projection: &Option<Vec<usize>>,+ ) -> Result<RecordBatch> {+ let exec = table.scan(projection, 1024)?;+ let partitions = exec.partitions()?;+ let it = partitions[0].execute()?;+ let mut it = it.lock().expect("failed to lock mutex");+ Ok(it+ .next_batch()?+ .expect("should have received at least one batch"))}}diff --git a/rust/datafusion/src/execution/physical_plan/planner.rs b/rust/datafusion/src/execution/physical_plan/planner.rsindex b12304382a..3f2fe04a34 100644--- a/rust/datafusion/src/execution/physical_plan/planner.rs+++ b/rust/datafusion/src/execution/physical_plan/planner.rs@@ -72,7 +72,8 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {..} => match ctx_state.datasources.get(table_name) {Some(provider) => {- let partitions = provider.scan(projection, batch_size)?;+ let exec = provider.scan(projection, batch_size)?;+ let partitions = exec.partitions()?;if partitions.is_empty() {Err(ExecutionError::General("Table provider returned no partitions".to_string(),