You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@arrow.apache.org by ag...@apache.org on 2019/03/04 04:17:32 UTC

[arrow] branch master updated: ARROW-4679: [Rust] Implement in-memory data source for DataFusion

This is an automated email from the ASF dual-hosted git repository.

agrove pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/arrow.git


The following commit(s) were added to refs/heads/master by this push:
     new c80e685  ARROW-4679: [Rust] Implement in-memory data source for DataFusion
c80e685 is described below

commit c80e6859eb4d9498d6bb5c74da656801a228fb62
Author: Andy Grove <an...@gmail.com>
AuthorDate: Sun Mar 3 21:17:20 2019 -0700

    ARROW-4679: [Rust] Implement in-memory data source for DataFusion
    
    This PR adds a new memory-based table implementation and updates the DataFusion benchmarks to load CSV data into memory before the benchmark starts and then measure the performance of executing queries against in-memory data.
    
    This PR also renames the data source traits and organizes them better in a new namespace.
    
    Finally, it is now possible to register arbitrary data sources with the execution context.
    
    Author: Andy Grove <an...@gmail.com>
    
    Closes #3754 from andygrove/ARROW-4679 and squashes the following commits:
    
    8b4c050 <Andy Grove> update benchmark
    5ce48e4 <Andy Grove> improve tests
    f1916a1 <Andy Grove> Add validation for projection in MemTable
    5e8ddad <Andy Grove> Add schema validation when creating MemTable
    2c72f08 <Andy Grove> Add check for batch column count, split test into two with better names
    afe1c06 <Andy Grove> benchmarks now run against in-memory data
    9b2136d <Andy Grove> update rustdoc
    30c2520 <Andy Grove> rename traits
    379d221 <Andy Grove> Implement in-memory data source for DataFusion
---
 rust/arrow/src/record_batch.rs                     |   1 +
 rust/datafusion/benches/aggregate_query_sql.rs     |  43 +++-
 .../{execution/datasource.rs => datasource/csv.rs} |  97 ++++----
 .../relation.rs => datasource/datasource.rs}       |  44 ++--
 rust/datafusion/src/datasource/memory.rs           | 263 +++++++++++++++++++++
 .../src/{execution => datasource}/mod.rs           |  15 +-
 rust/datafusion/src/execution/aggregate.rs         |  18 +-
 rust/datafusion/src/execution/context.rs           |  45 ++--
 rust/datafusion/src/execution/mod.rs               |   1 -
 rust/datafusion/src/execution/projection.rs        |  18 +-
 rust/datafusion/src/execution/relation.rs          |   8 +-
 rust/datafusion/src/lib.rs                         |   1 +
 12 files changed, 411 insertions(+), 143 deletions(-)

diff --git a/rust/arrow/src/record_batch.rs b/rust/arrow/src/record_batch.rs
index a2bbd8b..e3da628 100644
--- a/rust/arrow/src/record_batch.rs
+++ b/rust/arrow/src/record_batch.rs
@@ -27,6 +27,7 @@ use crate::array::*;
 use crate::datatypes::*;
 
 /// A batch of column-oriented data
+#[derive(Clone)]
 pub struct RecordBatch {
     schema: Arc<Schema>,
     columns: Vec<Arc<Array>>,
diff --git a/rust/datafusion/benches/aggregate_query_sql.rs b/rust/datafusion/benches/aggregate_query_sql.rs
index cd93d93..bde8787 100644
--- a/rust/datafusion/benches/aggregate_query_sql.rs
+++ b/rust/datafusion/benches/aggregate_query_sql.rs
@@ -19,6 +19,8 @@
 extern crate criterion;
 use criterion::Criterion;
 
+use std::cell::RefCell;
+use std::rc::Rc;
 use std::sync::Arc;
 
 extern crate arrow;
@@ -26,12 +28,21 @@ extern crate datafusion;
 
 use arrow::datatypes::{DataType, Field, Schema};
 
+use datafusion::datasource::{CsvFile, MemTable};
 use datafusion::execution::context::ExecutionContext;
 
-fn aggregate_query(sql: &str) {
-    // create local execution context
-    let mut ctx = ExecutionContext::new();
+fn aggregate_query(ctx: &Rc<RefCell<ExecutionContext>>, sql: &str) {
+    // execute the query
+    let mut mut_ctx = ctx.borrow_mut();
+    let relation = mut_ctx.sql(&sql, 1024 * 1024).unwrap();
+
+    // display the relation
+    let mut results = relation.borrow_mut();
 
+    while let Some(_) = results.next().unwrap() {}
+}
+
+fn create_context() -> Rc<RefCell<ExecutionContext>> {
     // define schema for data source (csv file)
     let schema = Arc::new(Schema::new(vec![
         Field::new("c1", DataType::Utf8, false),
@@ -49,43 +60,53 @@ fn aggregate_query(sql: &str) {
         Field::new("c13", DataType::Utf8, false),
     ]));
 
-    // register csv file with the execution context
-    ctx.register_csv(
-        "aggregate_test_100",
+    // create CSV data source
+    let csv = CsvFile::new(
         "../../testing/data/csv/aggregate_test_100.csv",
         &schema,
         true,
     );
 
-    // execute the query
-    let relation = ctx.sql(&sql, 1024 * 1024).unwrap();
+    let mem_table = MemTable::load(&csv).unwrap();
 
-    // display the relation
-    let mut results = relation.borrow_mut();
+    // create local execution context
+    let ctx = Rc::new(RefCell::new(ExecutionContext::new()));
 
-    while let Some(_) = results.next().unwrap() {}
+    let mut mut_ctx = ctx.borrow_mut();
+
+    mut_ctx.register_table("aggregate_test_100", Rc::new(mem_table));
+
+    ctx.clone()
 }
 
 fn criterion_benchmark(c: &mut Criterion) {
     c.bench_function("aggregate_query_no_group_by", |b| {
+        let ctx = create_context();
         b.iter(|| {
             aggregate_query(
+                &ctx,
                 "SELECT MIN(c12), MAX(c12) \
                  FROM aggregate_test_100",
             )
         })
     });
+
     c.bench_function("aggregate_query_group_by", |b| {
+        let ctx = create_context();
         b.iter(|| {
             aggregate_query(
+                &ctx,
                 "SELECT c1, MIN(c12), MAX(c12) \
                  FROM aggregate_test_100 GROUP BY c1",
             )
         })
     });
+
     c.bench_function("aggregate_query_group_by_with_filter", |b| {
+        let ctx = create_context();
         b.iter(|| {
             aggregate_query(
+                &ctx,
                 "SELECT c1, MIN(c12), MAX(c12) \
                  FROM aggregate_test_100 \
                  WHERE c11 > 0.1 AND c11 < 0.9 GROUP BY c1",
diff --git a/rust/datafusion/src/execution/datasource.rs b/rust/datafusion/src/datasource/csv.rs
similarity index 80%
rename from rust/datafusion/src/execution/datasource.rs
rename to rust/datafusion/src/datasource/csv.rs
index 992dfb0..1d0e4d7 100644
--- a/rust/datafusion/src/execution/datasource.rs
+++ b/rust/datafusion/src/datasource/csv.rs
@@ -15,7 +15,7 @@
 // specific language governing permissions and limitations
 // under the License.
 
-//! Data sources
+//! CSV Data source
 
 use std::cell::RefCell;
 use std::fs::File;
@@ -27,20 +27,53 @@ use arrow::csv;
 use arrow::datatypes::{Field, Schema};
 use arrow::record_batch::RecordBatch;
 
-use super::error::Result;
+use crate::datasource::{RecordBatchIterator, ScanResult, Table};
+use crate::execution::error::Result;
 
-pub trait DataSource {
-    fn schema(&self) -> &Arc<Schema>;
-    fn next(&mut self) -> Result<Option<RecordBatch>>;
+/// Represents a CSV file with a provided schema
+pub struct CsvFile {
+    filename: String,
+    schema: Arc<Schema>,
+    has_header: bool,
 }
 
-/// CSV data source
-pub struct CsvDataSource {
+impl CsvFile {
+    pub fn new(filename: &str, schema: &Schema, has_header: bool) -> Self {
+        Self {
+            filename: String::from(filename),
+            schema: Arc::new(schema.clone()),
+            has_header,
+        }
+    }
+}
+
+impl Table for CsvFile {
+    fn schema(&self) -> &Arc<Schema> {
+        &self.schema
+    }
+
+    fn scan(
+        &self,
+        projection: &Option<Vec<usize>>,
+        batch_size: usize,
+    ) -> Result<ScanResult> {
+        Ok(Rc::new(RefCell::new(CsvBatchIterator::new(
+            &self.filename,
+            self.schema.clone(),
+            self.has_header,
+            projection,
+            batch_size,
+        ))))
+    }
+}
+
+/// Iterator over CSV batches
+pub struct CsvBatchIterator {
     schema: Arc<Schema>,
     reader: csv::Reader<File>,
 }
 
-impl CsvDataSource {
+impl CsvBatchIterator {
     pub fn new(
         filename: &str,
         schema: Arc<Schema>,
@@ -74,7 +107,7 @@ impl CsvDataSource {
     }
 }
 
-impl DataSource for CsvDataSource {
+impl RecordBatchIterator for CsvBatchIterator {
     fn schema(&self) -> &Arc<Schema> {
         &self.schema
     }
@@ -83,49 +116,3 @@ impl DataSource for CsvDataSource {
         Ok(self.reader.next()?)
     }
 }
-
-pub trait DataSourceProvider {
-    fn schema(&self) -> &Arc<Schema>;
-    fn scan(
-        &self,
-        projection: &Option<Vec<usize>>,
-        batch_size: usize,
-    ) -> Rc<RefCell<DataSource>>;
-}
-
-/// Represents a CSV file with a provided schema
-pub struct CsvProvider {
-    filename: String,
-    schema: Arc<Schema>,
-    has_header: bool,
-}
-
-impl CsvProvider {
-    pub fn new(filename: &str, schema: &Schema, has_header: bool) -> Self {
-        Self {
-            filename: String::from(filename),
-            schema: Arc::new(schema.clone()),
-            has_header,
-        }
-    }
-}
-
-impl DataSourceProvider for CsvProvider {
-    fn schema(&self) -> &Arc<Schema> {
-        &self.schema
-    }
-
-    fn scan(
-        &self,
-        projection: &Option<Vec<usize>>,
-        batch_size: usize,
-    ) -> Rc<RefCell<DataSource>> {
-        Rc::new(RefCell::new(CsvDataSource::new(
-            &self.filename,
-            self.schema.clone(),
-            self.has_header,
-            projection,
-            batch_size,
-        )))
-    }
-}
diff --git a/rust/datafusion/src/execution/relation.rs b/rust/datafusion/src/datasource/datasource.rs
similarity index 59%
copy from rust/datafusion/src/execution/relation.rs
copy to rust/datafusion/src/datasource/datasource.rs
index 88eefab..2b6d4e7 100644
--- a/rust/datafusion/src/execution/relation.rs
+++ b/rust/datafusion/src/datasource/datasource.rs
@@ -15,6 +15,8 @@
 // specific language governing permissions and limitations
 // under the License.
 
+//! Data source traits
+
 use std::cell::RefCell;
 use std::rc::Rc;
 use std::sync::Arc;
@@ -22,36 +24,28 @@ use std::sync::Arc;
 use arrow::datatypes::Schema;
 use arrow::record_batch::RecordBatch;
 
-use super::datasource::DataSource;
-use super::error::Result;
+use crate::execution::error::Result;
 
-/// trait for all relations (a relation is essentially just an iterator over rows with
-/// a known schema)
-pub trait Relation {
-    fn next(&mut self) -> Result<Option<RecordBatch>>;
+pub type ScanResult = Rc<RefCell<RecordBatchIterator>>;
 
-    /// get the schema for this relation
+/// Source table
+pub trait Table {
+    /// Get a reference to the schema for this table
     fn schema(&self) -> &Arc<Schema>;
-}
 
-pub struct DataSourceRelation {
-    schema: Arc<Schema>,
-    ds: Rc<RefCell<DataSource>>,
+    /// Perform a scan of a table and return an iterator over the data
+    fn scan(
+        &self,
+        projection: &Option<Vec<usize>>,
+        batch_size: usize,
+    ) -> Result<ScanResult>;
 }
 
-impl DataSourceRelation {
-    pub fn new(ds: Rc<RefCell<DataSource>>) -> Self {
-        let schema = ds.borrow().schema().clone();
-        Self { ds, schema }
-    }
-}
-
-impl Relation for DataSourceRelation {
-    fn next(&mut self) -> Result<Option<RecordBatch>> {
-        self.ds.borrow_mut().next()
-    }
+/// 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>;
 
-    fn schema(&self) -> &Arc<Schema> {
-        &self.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.rs
new file mode 100644
index 0000000..3367393
--- /dev/null
+++ b/rust/datafusion/src/datasource/memory.rs
@@ -0,0 +1,263 @@
+// 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.
+
+//! In-memory data source for presenting a Vec<RecordBatch> as a data source that can be
+//! queried by DataFusion. This allows data to be pre-loaded into memory and then repeatedly
+//! queried without incurring additional file I/O overhead.
+
+use std::cell::RefCell;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use arrow::datatypes::{Field, Schema};
+use arrow::record_batch::RecordBatch;
+
+use crate::datasource::{RecordBatchIterator, ScanResult, Table};
+use crate::execution::error::{ExecutionError, Result};
+
+/// In-memory table
+pub struct MemTable {
+    schema: Arc<Schema>,
+    batches: Vec<RecordBatch>,
+}
+
+impl MemTable {
+    /// Create a new in-memory table from the provided schema and record batches
+    pub fn new(schema: Arc<Schema>, batches: Vec<RecordBatch>) -> Result<Self> {
+        if batches
+            .iter()
+            .all(|batch| batch.schema().as_ref() == schema.as_ref())
+        {
+            Ok(Self { schema, batches })
+        } else {
+            Err(ExecutionError::General(
+                "Mismatch between schema and batches".to_string(),
+            ))
+        }
+    }
+
+    /// Create a mem table by reading from another data source
+    pub fn load(t: &Table) -> Result<Self> {
+        let schema = t.schema();
+        let it = t.scan(&None, 1024 * 1024)?;
+        let mut it_mut = it.borrow_mut();
+
+        let mut data: Vec<RecordBatch> = vec![];
+
+        while let Ok(Some(batch)) = it_mut.next() {
+            data.push(batch);
+        }
+        MemTable::new(schema.clone(), data)
+    }
+}
+
+impl Table for MemTable {
+    fn schema(&self) -> &Arc<Schema> {
+        &self.schema
+    }
+
+    fn scan(
+        &self,
+        projection: &Option<Vec<usize>>,
+        _batch_size: usize,
+    ) -> Result<ScanResult> {
+        let columns: Vec<usize> = match projection {
+            Some(p) => p.clone(),
+            None => {
+                let l = self.schema.fields().len();
+                let mut v = Vec::with_capacity(l);
+                for i in 0..l {
+                    v.push(i);
+                }
+                v
+            }
+        };
+
+        let projected_columns: Result<Vec<Field>> = columns
+            .iter()
+            .map(|i| {
+                if *i < self.schema.fields().len() {
+                    Ok(self.schema.field(*i).clone())
+                } else {
+                    Err(ExecutionError::General(
+                        "Projection index out of range".to_string(),
+                    ))
+                }
+            })
+            .collect();
+
+        let projected_schema = Arc::new(Schema::new(projected_columns?));
+
+        Ok(Rc::new(RefCell::new(MemBatchIterator {
+            schema: projected_schema.clone(),
+            index: 0,
+            batches: self
+                .batches
+                .iter()
+                .map(|batch| {
+                    RecordBatch::new(
+                        projected_schema.clone(),
+                        columns.iter().map(|i| batch.column(*i).clone()).collect(),
+                    )
+                })
+                .collect(),
+        })))
+    }
+}
+
+/// Iterator over an in-memory table
+pub struct MemBatchIterator {
+    schema: Arc<Schema>,
+    index: usize,
+    batches: Vec<RecordBatch>,
+}
+
+impl RecordBatchIterator for MemBatchIterator {
+    fn schema(&self) -> &Arc<Schema> {
+        &self.schema
+    }
+
+    fn next(&mut self) -> Result<Option<RecordBatch>> {
+        if self.index < self.batches.len() {
+            self.index += 1;
+            Ok(Some(self.batches[self.index - 1].clone()))
+        } else {
+            Ok(None)
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use arrow::array::Int32Array;
+    use arrow::datatypes::{DataType, Field, Schema};
+
+    #[test]
+    fn test_with_projection() {
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("a", DataType::Int32, false),
+            Field::new("b", DataType::Int32, false),
+            Field::new("c", DataType::Int32, false),
+        ]));
+
+        let batch = RecordBatch::new(
+            schema.clone(),
+            vec![
+                Arc::new(Int32Array::from(vec![1, 2, 3])),
+                Arc::new(Int32Array::from(vec![4, 5, 6])),
+                Arc::new(Int32Array::from(vec![7, 8, 9])),
+            ],
+        );
+
+        let provider = MemTable::new(schema, vec![batch]).unwrap();
+
+        // scan with projection
+        let scan2 = provider.scan(&Some(vec![2, 1]), 1024).unwrap();
+        let batch2 = scan2.borrow_mut().next().unwrap().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());
+    }
+
+    #[test]
+    fn test_without_projection() {
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("a", DataType::Int32, false),
+            Field::new("b", DataType::Int32, false),
+            Field::new("c", DataType::Int32, false),
+        ]));
+
+        let batch = RecordBatch::new(
+            schema.clone(),
+            vec![
+                Arc::new(Int32Array::from(vec![1, 2, 3])),
+                Arc::new(Int32Array::from(vec![4, 5, 6])),
+                Arc::new(Int32Array::from(vec![7, 8, 9])),
+            ],
+        );
+
+        let provider = MemTable::new(schema, vec![batch]).unwrap();
+
+        let scan1 = provider.scan(&None, 1024).unwrap();
+        let batch1 = scan1.borrow_mut().next().unwrap().unwrap();
+        assert_eq!(3, batch1.schema().fields().len());
+        assert_eq!(3, batch1.num_columns());
+    }
+
+    #[test]
+    fn test_invalid_projection() {
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("a", DataType::Int32, false),
+            Field::new("b", DataType::Int32, false),
+            Field::new("c", DataType::Int32, false),
+        ]));
+
+        let batch = RecordBatch::new(
+            schema.clone(),
+            vec![
+                Arc::new(Int32Array::from(vec![1, 2, 3])),
+                Arc::new(Int32Array::from(vec![4, 5, 6])),
+                Arc::new(Int32Array::from(vec![7, 8, 9])),
+            ],
+        );
+
+        let provider = MemTable::new(schema, vec![batch]).unwrap();
+
+        let projection: Vec<usize> = vec![0, 4];
+
+        match provider.scan(&Some(projection), 1024) {
+            Err(ExecutionError::General(e)) => {
+                assert_eq!("\"Projection index out of range\"", format!("{:?}", e))
+            }
+            _ => panic!("Scan should failed on invalid projection"),
+        };
+    }
+
+    #[test]
+    fn test_schema_validation() {
+        let schema1 = Arc::new(Schema::new(vec![
+            Field::new("a", DataType::Int32, false),
+            Field::new("b", DataType::Int32, false),
+            Field::new("c", DataType::Int32, false),
+        ]));
+
+        let schema2 = Arc::new(Schema::new(vec![
+            Field::new("a", DataType::Int32, false),
+            Field::new("b", DataType::Float64, false),
+            Field::new("c", DataType::Int32, false),
+        ]));
+
+        let batch = RecordBatch::new(
+            schema1.clone(),
+            vec![
+                Arc::new(Int32Array::from(vec![1, 2, 3])),
+                Arc::new(Int32Array::from(vec![4, 5, 6])),
+                Arc::new(Int32Array::from(vec![7, 8, 9])),
+            ],
+        );
+
+        match MemTable::new(schema2, vec![batch]) {
+            Err(ExecutionError::General(e)) => assert_eq!(
+                "\"Mismatch between schema and batches\"",
+                format!("{:?}", e)
+            ),
+            _ => panic!("MemTable::new should have failed due to schema mismatch"),
+        }
+    }
+}
diff --git a/rust/datafusion/src/execution/mod.rs b/rust/datafusion/src/datasource/mod.rs
similarity index 80%
copy from rust/datafusion/src/execution/mod.rs
copy to rust/datafusion/src/datasource/mod.rs
index 9eb303f..1a22a23 100644
--- a/rust/datafusion/src/execution/mod.rs
+++ b/rust/datafusion/src/datasource/mod.rs
@@ -15,13 +15,10 @@
 // specific language governing permissions and limitations
 // under the License.
 
-pub mod aggregate;
-pub mod context;
+pub mod csv;
 pub mod datasource;
-pub mod error;
-pub mod expression;
-pub mod filter;
-pub mod limit;
-pub mod physicalplan;
-pub mod projection;
-pub mod relation;
+pub mod memory;
+
+pub use self::csv::{CsvBatchIterator, CsvFile};
+pub use self::datasource::{RecordBatchIterator, ScanResult, Table};
+pub use self::memory::{MemBatchIterator, MemTable};
diff --git a/rust/datafusion/src/execution/aggregate.rs b/rust/datafusion/src/execution/aggregate.rs
index 049c1f1..87a9f11 100644
--- a/rust/datafusion/src/execution/aggregate.rs
+++ b/rust/datafusion/src/execution/aggregate.rs
@@ -29,9 +29,9 @@ use arrow::compute;
 use arrow::datatypes::{DataType, Schema};
 use arrow::record_batch::RecordBatch;
 
-use super::error::{ExecutionError, Result};
-use super::expression::{AggregateType, RuntimeExpr};
-use super::relation::Relation;
+use crate::execution::error::{ExecutionError, Result};
+use crate::execution::expression::{AggregateType, RuntimeExpr};
+use crate::execution::relation::Relation;
 use crate::logicalplan::ScalarValue;
 
 use fnv::FnvHashMap;
@@ -1014,12 +1014,12 @@ impl AggregateRelation {
 
 #[cfg(test)]
 mod tests {
-    use super::super::super::logicalplan::Expr;
-    use super::super::context::ExecutionContext;
-    use super::super::datasource::CsvDataSource;
-    use super::super::expression;
-    use super::super::relation::DataSourceRelation;
     use super::*;
+    use crate::datasource::CsvBatchIterator;
+    use crate::execution::context::ExecutionContext;
+    use crate::execution::expression;
+    use crate::execution::relation::DataSourceRelation;
+    use crate::logicalplan::Expr;
     use arrow::datatypes::{DataType, Field, Schema};
 
     #[test]
@@ -1208,7 +1208,7 @@ mod tests {
     }
 
     fn load_csv(filename: &str, schema: &Arc<Schema>) -> Rc<RefCell<Relation>> {
-        let ds = CsvDataSource::new(filename, schema.clone(), true, &None, 1024);
+        let ds = CsvBatchIterator::new(filename, schema.clone(), true, &None, 1024);
         Rc::new(RefCell::new(DataSourceRelation::new(Rc::new(
             RefCell::new(ds),
         ))))
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index 95c5c85..ae1f1cd 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -25,22 +25,23 @@ use std::sync::Arc;
 
 use arrow::datatypes::*;
 
-use super::super::dfparser::{DFASTNode, DFParser};
-use super::super::logicalplan::*;
-use super::super::optimizer::optimizer::OptimizerRule;
-use super::super::optimizer::projection_push_down::ProjectionPushDown;
-use super::super::sqlplanner::{SchemaProvider, SqlToRel};
-use super::aggregate::AggregateRelation;
-use super::datasource::{CsvProvider, DataSourceProvider};
-use super::error::{ExecutionError, Result};
-use super::expression::*;
-use super::filter::FilterRelation;
-use super::limit::LimitRelation;
-use super::projection::ProjectRelation;
-use super::relation::{DataSourceRelation, Relation};
+use crate::datasource::csv::CsvFile;
+use crate::datasource::datasource::Table;
+use crate::dfparser::{DFASTNode, DFParser};
+use crate::execution::aggregate::AggregateRelation;
+use crate::execution::error::{ExecutionError, Result};
+use crate::execution::expression::*;
+use crate::execution::filter::FilterRelation;
+use crate::execution::limit::LimitRelation;
+use crate::execution::projection::ProjectRelation;
+use crate::execution::relation::{DataSourceRelation, Relation};
+use crate::logicalplan::*;
+use crate::optimizer::optimizer::OptimizerRule;
+use crate::optimizer::projection_push_down::ProjectionPushDown;
+use crate::sqlplanner::{SchemaProvider, SqlToRel};
 
 pub struct ExecutionContext {
-    datasources: Rc<RefCell<HashMap<String, Rc<DataSourceProvider>>>>,
+    datasources: Rc<RefCell<HashMap<String, Rc<Table>>>>,
 }
 
 impl ExecutionContext {
@@ -87,10 +88,14 @@ impl ExecutionContext {
         schema: &Schema,
         has_header: bool,
     ) {
-        self.datasources.borrow_mut().insert(
-            name.to_string(),
-            Rc::new(CsvProvider::new(filename, schema, has_header)),
-        );
+        self.register_table(name, Rc::new(CsvFile::new(filename, schema, has_header)));
+    }
+
+    /// Register a table so that it can be queried from SQL
+    pub fn register_table(&mut self, name: &str, provider: Rc<Table>) {
+        self.datasources
+            .borrow_mut()
+            .insert(name.to_string(), provider);
     }
 
     /// Optimize the logical plan by applying optimizer rules
@@ -113,7 +118,7 @@ impl ExecutionContext {
                 ..
             } => match self.datasources.borrow().get(table_name) {
                 Some(provider) => {
-                    let ds = provider.scan(projection, batch_size);
+                    let ds = provider.scan(projection, batch_size)?;
                     Ok(Rc::new(RefCell::new(DataSourceRelation::new(ds))))
                 }
                 _ => Err(ExecutionError::General(format!(
@@ -269,7 +274,7 @@ pub fn exprlist_to_fields(expr: &Vec<Expr>, input_schema: &Schema) -> Vec<Field>
 }
 
 struct ExecutionContextSchemaProvider {
-    datasources: Rc<RefCell<HashMap<String, Rc<DataSourceProvider>>>>,
+    datasources: Rc<RefCell<HashMap<String, Rc<Table>>>>,
 }
 impl SchemaProvider for ExecutionContextSchemaProvider {
     fn get_table_meta(&self, name: &str) -> Option<Arc<Schema>> {
diff --git a/rust/datafusion/src/execution/mod.rs b/rust/datafusion/src/execution/mod.rs
index 9eb303f..f775c16 100644
--- a/rust/datafusion/src/execution/mod.rs
+++ b/rust/datafusion/src/execution/mod.rs
@@ -17,7 +17,6 @@
 
 pub mod aggregate;
 pub mod context;
-pub mod datasource;
 pub mod error;
 pub mod expression;
 pub mod filter;
diff --git a/rust/datafusion/src/execution/projection.rs b/rust/datafusion/src/execution/projection.rs
index d9b4a94..bcf3ebb 100644
--- a/rust/datafusion/src/execution/projection.rs
+++ b/rust/datafusion/src/execution/projection.rs
@@ -25,9 +25,9 @@ use arrow::array::ArrayRef;
 use arrow::datatypes::{Field, Schema};
 use arrow::record_batch::RecordBatch;
 
-use super::error::Result;
-use super::expression::RuntimeExpr;
-use super::relation::Relation;
+use crate::execution::error::Result;
+use crate::execution::expression::RuntimeExpr;
+use crate::execution::relation::Relation;
 
 pub struct ProjectRelation {
     schema: Arc<Schema>,
@@ -79,12 +79,12 @@ impl Relation for ProjectRelation {
 
 #[cfg(test)]
 mod tests {
-    use super::super::super::logicalplan::Expr;
-    use super::super::context::ExecutionContext;
-    use super::super::datasource::CsvDataSource;
-    use super::super::expression;
-    use super::super::relation::DataSourceRelation;
     use super::*;
+    use crate::datasource::CsvBatchIterator;
+    use crate::execution::context::ExecutionContext;
+    use crate::execution::expression;
+    use crate::execution::relation::DataSourceRelation;
+    use crate::logicalplan::Expr;
     use arrow::datatypes::{DataType, Field, Schema};
 
     #[test]
@@ -105,7 +105,7 @@ mod tests {
             Field::new("c12", DataType::Utf8, false),
         ]));
 
-        let ds = CsvDataSource::new(
+        let ds = CsvBatchIterator::new(
             "../../testing/data/csv/aggregate_test_100.csv",
             schema.clone(),
             true,
diff --git a/rust/datafusion/src/execution/relation.rs b/rust/datafusion/src/execution/relation.rs
index 88eefab..b7f77c1 100644
--- a/rust/datafusion/src/execution/relation.rs
+++ b/rust/datafusion/src/execution/relation.rs
@@ -22,8 +22,8 @@ use std::sync::Arc;
 use arrow::datatypes::Schema;
 use arrow::record_batch::RecordBatch;
 
-use super::datasource::DataSource;
-use super::error::Result;
+use crate::datasource::RecordBatchIterator;
+use crate::execution::error::Result;
 
 /// trait for all relations (a relation is essentially just an iterator over rows with
 /// a known schema)
@@ -36,11 +36,11 @@ pub trait Relation {
 
 pub struct DataSourceRelation {
     schema: Arc<Schema>,
-    ds: Rc<RefCell<DataSource>>,
+    ds: Rc<RefCell<RecordBatchIterator>>,
 }
 
 impl DataSourceRelation {
-    pub fn new(ds: Rc<RefCell<DataSource>>) -> Self {
+    pub fn new(ds: Rc<RefCell<RecordBatchIterator>>) -> Self {
         let schema = ds.borrow().schema().clone();
         Self { ds, schema }
     }
diff --git a/rust/datafusion/src/lib.rs b/rust/datafusion/src/lib.rs
index a93872c..7fab046 100644
--- a/rust/datafusion/src/lib.rs
+++ b/rust/datafusion/src/lib.rs
@@ -24,6 +24,7 @@ extern crate serde_derive;
 extern crate serde_json;
 extern crate sqlparser;
 
+pub mod datasource;
 pub mod dfparser;
 pub mod execution;
 pub mod logicalplan;