Apache DataFusion SQL Query Engine
ARROW-6287: [Rust] [DataFusion] TableProvider.scan() returns thread-safe BatchIterator
Andy Grovebdccbf8418c3
diff --git a/rust/datafusion/Cargo.toml b/rust/datafusion/Cargo.tomlindex f28d7377a7..7db5909d01 100644--- a/rust/datafusion/Cargo.toml+++ b/rust/datafusion/Cargo.toml@@ -50,6 +50,7 @@ sqlparser = "0.2.0"clap = "2.33.0"prettytable-rs = "0.8.0"rustyline = {version = "4.1.0", optional = true}+crossbeam = "0.7.1"[dev-dependencies]criterion = "0.2.0"diff --git a/rust/datafusion/src/datasource/csv.rs b/rust/datafusion/src/datasource/csv.rsindex acbad1650e..c8f128d4ff 100644--- a/rust/datafusion/src/datasource/csv.rs+++ b/rust/datafusion/src/datasource/csv.rs@@ -25,8 +25,9 @@ use arrow::csv;use arrow::datatypes::{Field, Schema};use arrow::record_batch::RecordBatch;-use crate::datasource::{RecordBatchIterator, ScanResult, TableProvider};+use crate::datasource::{ScanResult, TableProvider};use crate::error::Result;+use crate::execution::physical_plan::BatchIterator;/// Represents a CSV file with a provided schema// TODO: usage example (rather than documenting `new()`)@@ -109,9 +110,9 @@ impl CsvBatchIterator {}}-impl RecordBatchIterator for CsvBatchIterator {- fn schema(&self) -> &Arc<Schema> {- &self.schema+impl BatchIterator for CsvBatchIterator {+ fn schema(&self) -> Arc<Schema> {+ self.schema.clone()}fn next(&mut self) -> Result<Option<RecordBatch>> {diff --git a/rust/datafusion/src/datasource/datasource.rs b/rust/datafusion/src/datasource/datasource.rsindex 715f518026..7249731d06 100644--- a/rust/datafusion/src/datasource/datasource.rs+++ b/rust/datafusion/src/datasource/datasource.rs@@ -20,13 +20,13 @@use std::sync::{Arc, Mutex};use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;use crate::error::Result;+use crate::execution::physical_plan::BatchIterator;-/// Returned by implementors of `Table#scan`, this `RecordBatchIterator` is wrapped with+/// Returned by implementors of `Table#scan`, this `BatchIterator` is wrapped with/// an `Arc` and `Mutex` so that it can be shared across threads as it is used.-pub type ScanResult = Arc<Mutex<dyn RecordBatchIterator>>;+pub type ScanResult = Arc<Mutex<dyn BatchIterator>>;/// Source tablepub trait TableProvider {@@ -41,12 +41,3 @@ pub trait TableProvider {batch_size: usize,) -> Result<Vec<ScanResult>>;}--/// Iterator for reading a series of record batches with a known schema-pub trait RecordBatchIterator {- /// Get the schema of this iterator- fn schema(&self) -> &Arc<Schema>;-- /// Get the next batch in this iterator- fn next(&mut self) -> Result<Option<RecordBatch>>;-}diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rsindex c2dd0da544..0fec2d6189 100644--- a/rust/datafusion/src/datasource/memory.rs+++ b/rust/datafusion/src/datasource/memory.rs@@ -24,8 +24,9 @@ use std::sync::{Arc, Mutex};use arrow::datatypes::{Field, Schema};use arrow::record_batch::RecordBatch;-use crate::datasource::{RecordBatchIterator, ScanResult, TableProvider};+use crate::datasource::{ScanResult, TableProvider};use crate::error::{ExecutionError, Result};+use crate::execution::physical_plan::BatchIterator;/// In-memory tablepub struct MemTable {@@ -130,9 +131,9 @@ pub struct MemBatchIterator {batches: Vec<RecordBatch>,}-impl RecordBatchIterator for MemBatchIterator {- fn schema(&self) -> &Arc<Schema> {- &self.schema+impl BatchIterator for MemBatchIterator {+ fn schema(&self) -> Arc<Schema> {+ self.schema.clone()}fn next(&mut self) -> Result<Option<RecordBatch>> {diff --git a/rust/datafusion/src/datasource/mod.rs b/rust/datafusion/src/datasource/mod.rsindex 504fbcc375..0adff45f69 100644--- a/rust/datafusion/src/datasource/mod.rs+++ b/rust/datafusion/src/datasource/mod.rs@@ -23,5 +23,5 @@ pub mod memory;pub mod parquet;pub use self::csv::{CsvBatchIterator, CsvFile};-pub use self::datasource::{RecordBatchIterator, ScanResult, TableProvider};+pub use self::datasource::{ScanResult, TableProvider};pub use self::memory::{MemBatchIterator, MemTable};diff --git a/rust/datafusion/src/datasource/parquet.rs b/rust/datafusion/src/datasource/parquet.rsindex 1703c33e93..d5da6ad68c 100644--- a/rust/datafusion/src/datasource/parquet.rs+++ b/rust/datafusion/src/datasource/parquet.rs@@ -15,11 +15,14 @@// specific language governing permissions and limitations// under the License.-//! Parquet Data source+//! Parquet data sourceuse std::fs::File;use std::string::String;use std::sync::{Arc, Mutex};+use std::thread;++use crossbeam::channel::{unbounded, Receiver, Sender};use arrow::array::{Array, BinaryBuilder, PrimitiveArray, PrimitiveBuilder, TimestampNanosecondBuilder,@@ -32,8 +35,9 @@ use parquet::column::reader::*;use parquet::data_type::{ByteArray, Int96};use parquet::file::reader::*;-use crate::datasource::{RecordBatchIterator, ScanResult, TableProvider};+use crate::datasource::{ScanResult, TableProvider};use crate::error::{ExecutionError, Result};+use crate::execution::physical_plan::BatchIterator;/// Table-based representation of a `ParquetFile`pub struct ParquetTable {@@ -44,8 +48,7 @@ pub struct ParquetTable {impl ParquetTable {/// Attempt to initialize a new `ParquetTable` from a file pathpub fn try_new(filename: &str) -> Result<Self> {- let file = File::open(filename)?;- let parquet_file = ParquetFile::open(file, None, 0)?;+ let parquet_file = ParquetFile::open(filename, None, 0)?;let schema = parquet_file.projection_schema.clone();Ok(Self {filename: filename.to_string(),@@ -55,17 +58,28 @@ impl ParquetTable {}impl TableProvider for ParquetTable {+ /// Get the schema for this parquet filefn schema(&self) -> &Arc<Schema> {&self.schema}+ /// Scan the file(s), using the provided projection, and return one BatchIterator per+ /// partitionfn scan(&self,projection: &Option<Vec<usize>>,batch_size: usize,) -> Result<Vec<ScanResult>> {- let file = File::open(self.filename.clone())?;- let parquet_file = ParquetFile::open(file, projection.clone(), batch_size)?;+ // note that this code currently assumes the filename is a file rather than a directory+ // and therefore only returns a single partition+ let parquet_file = match projection {+ Some(p) => ParquetScanPartition::try_new(+ &self.filename,+ Some(p.clone()),+ batch_size,+ )?,+ None => ParquetScanPartition::try_new(&self.filename, None, batch_size)?,+ };Ok(vec![Arc::new(Mutex::new(parquet_file))])}}@@ -83,6 +97,81 @@ pub struct ParquetFile {column_readers: Vec<ColumnReader>,}+/// Thread-safe wrapper around a ParquetFile+struct ParquetScanPartition {+ schema: Arc<Schema>,+ request_tx: Sender<()>,+ response_rx: Receiver<Result<Option<RecordBatch>>>,+}++impl ParquetScanPartition {+ pub fn try_new(+ filename: &str,+ projection: Option<Vec<usize>>,+ batch_size: usize,+ ) -> Result<Self> {+ // determine the schema after the projection is applied+ let schema = match &projection {+ Some(p) => {+ let table = ParquetFile::open(&filename, Some(p.clone()), batch_size)?;+ table.schema().clone()+ }+ None => {+ let table = ParquetFile::open(&filename, None, batch_size)?;+ table.schema().clone()+ }+ };++ // because the parquet implementation is not thread-safe, it is necessary to execute+ // on a thread and communicate with channels+ let (request_tx, request_rx): (Sender<()>, Receiver<()>) = unbounded();+ let (response_tx, response_rx): (+ Sender<Result<Option<RecordBatch>>>,+ Receiver<Result<Option<RecordBatch>>>,+ ) = unbounded();+ let filename = filename.to_string();+ thread::spawn(move || {+ match ParquetFile::open(&filename, projection, batch_size) {+ Ok(mut table) => {+ while let Ok(_) = request_rx.recv() {+ response_tx.send(table.next()).unwrap();+ }+ }+ Err(e) => {+ response_tx.send(Err(e)).unwrap();+ }+ }+ });++ Ok(Self {+ schema,+ request_tx,+ response_rx,+ })+ }+}++impl BatchIterator for ParquetScanPartition {+ fn schema(&self) -> Arc<Schema> {+ self.schema.clone()+ }++ fn next(&mut self) -> Result<Option<RecordBatch>> {+ match self.request_tx.send(()) {+ Ok(_) => match self.response_rx.recv() {+ Ok(batch) => batch,+ Err(e) => Err(ExecutionError::General(format!(+ "Error receiving batch: {:?}",+ e+ ))),+ },+ _ => Err(ExecutionError::General(+ "Error sending request for next batch".to_string(),+ )),+ }+ }+}+macro_rules! read_binary_column {($SELF:ident, $R:ident, $INDEX:expr) => {{let mut read_buffer: Vec<ByteArray> =@@ -178,10 +267,11 @@ whereimpl ParquetFile {/// Read parquet data from a `File`pub fn open(- file: File,+ filename: &str,projection: Option<Vec<usize>>,batch_size: usize,) -> Result<Self> {+ let file = File::open(filename)?;let reader = SerializedFileReader::new(file)?;let metadata = reader.metadata();@@ -426,7 +516,7 @@ fn convert_int96_timestamp(v: &[u32]) -> i64 {seconds * MILLIS_PER_SECOND * 1_000_000 + nanoseconds}-impl RecordBatchIterator for ParquetFile {+impl ParquetFile {fn schema(&self) -> &Arc<Schema> {&self.projection_schema}diff --git a/rust/datafusion/src/execution/physical_plan/csv.rs b/rust/datafusion/src/execution/physical_plan/csv.rsindex 2c7ebc2d9a..82285b0f7d 100644--- a/rust/datafusion/src/execution/physical_plan/csv.rs+++ b/rust/datafusion/src/execution/physical_plan/csv.rs@@ -190,6 +190,11 @@ impl CsvIterator {}impl BatchIterator for CsvIterator {+ /// Get the schema+ fn schema(&self) -> Arc<Schema> {+ self.reader.schema()+ }+/// Get the next RecordBatchfn next(&mut self) -> Result<Option<RecordBatch>> {Ok(self.reader.next()?)diff --git a/rust/datafusion/src/execution/physical_plan/mod.rs b/rust/datafusion/src/execution/physical_plan/mod.rsindex 7dae854b63..7006ca754a 100644--- a/rust/datafusion/src/execution/physical_plan/mod.rs+++ b/rust/datafusion/src/execution/physical_plan/mod.rs@@ -40,6 +40,8 @@ pub trait Partition: Send + Sync {/// Iterator over RecordBatch that can be sent between threadspub trait BatchIterator: Send + Sync {+ /// Get the schema for the batches returned by this iterator+ fn schema(&self) -> Arc<Schema>;/// Get the next RecordBatchfn next(&mut self) -> Result<Option<RecordBatch>>;}diff --git a/rust/datafusion/src/execution/physical_plan/projection.rs b/rust/datafusion/src/execution/physical_plan/projection.rsindex c384b864cc..563fc348b9 100644--- a/rust/datafusion/src/execution/physical_plan/projection.rs+++ b/rust/datafusion/src/execution/physical_plan/projection.rs@@ -116,6 +116,11 @@ struct ProjectionIterator {}impl BatchIterator for ProjectionIterator {+ /// Get the schema+ fn schema(&self) -> Arc<Schema> {+ self.schema.clone()+ }+/// Get the next batchfn next(&mut self) -> Result<Option<RecordBatch>> {let mut input = self.input.lock().unwrap();diff --git a/rust/datafusion/src/execution/relation.rs b/rust/datafusion/src/execution/relation.rsindex c65055fdfc..81ff138220 100644--- a/rust/datafusion/src/execution/relation.rs+++ b/rust/datafusion/src/execution/relation.rs@@ -24,8 +24,8 @@ use std::sync::{Arc, Mutex};use arrow::datatypes::Schema;use arrow::record_batch::RecordBatch;-use crate::datasource::RecordBatchIterator;use crate::error::Result;+use crate::execution::physical_plan::BatchIterator;/// trait for all relations (a relation is essentially just an iterator over batches/// of data, with a known schema)@@ -40,11 +40,11 @@ pub trait Relation {/// Implementation of a relation that represents a DataFusion data sourcepub(super) struct DataSourceRelation {schema: Arc<Schema>,- ds: Arc<Mutex<dyn RecordBatchIterator>>,+ ds: Arc<Mutex<dyn BatchIterator>>,}impl DataSourceRelation {- pub fn new(ds: Arc<Mutex<dyn RecordBatchIterator>>) -> Self {+ pub fn new(ds: Arc<Mutex<dyn BatchIterator>>) -> Self {let schema = ds.lock().unwrap().schema().clone();Self { ds, schema }}