Skip to content

Apache DataFusion SQL Query Engine

ARROW-4595: [Rust] Implement Table API (a.k.a DataFrame)

Andy Grove43c37505aaa0
diff --git a/rust/datafusion/src/datasource/csv.rs b/rust/datafusion/src/datasource/csv.rs
index fa2f54b107..acbad1650e 100644
--- a/rust/datafusion/src/datasource/csv.rs
+++ b/rust/datafusion/src/datasource/csv.rs
@@ -25,7 +25,7 @@ use arrow::csv;
use arrow::datatypes::{Field, Schema};
use arrow::record_batch::RecordBatch;
-use crate::datasource::{RecordBatchIterator, ScanResult, Table};
+use crate::datasource::{RecordBatchIterator, ScanResult, TableProvider};
use crate::error::Result;
/// Represents a CSV file with a provided schema
@@ -47,7 +47,7 @@ impl CsvFile {
}
}
-impl Table for CsvFile {
+impl TableProvider for CsvFile {
fn schema(&self) -> &Arc<Schema> {
&self.schema
}
diff --git a/rust/datafusion/src/datasource/datasource.rs b/rust/datafusion/src/datasource/datasource.rs
index 7f9727aafb..fca24ab473 100644
--- a/rust/datafusion/src/datasource/datasource.rs
+++ b/rust/datafusion/src/datasource/datasource.rs
@@ -29,7 +29,7 @@ use crate::error::Result;
pub type ScanResult = Arc<Mutex<RecordBatchIterator>>;
/// Source table
-pub trait Table {
+pub trait TableProvider {
/// Get a reference to the schema for this table
fn schema(&self) -> &Arc<Schema>;
diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rs
index e12bec566e..67a7aff4fa 100644
--- a/rust/datafusion/src/datasource/memory.rs
+++ b/rust/datafusion/src/datasource/memory.rs
@@ -24,7 +24,7 @@ use std::sync::{Arc, Mutex};
use arrow::datatypes::{Field, Schema};
use arrow::record_batch::RecordBatch;
-use crate::datasource::{RecordBatchIterator, ScanResult, Table};
+use crate::datasource::{RecordBatchIterator, ScanResult, TableProvider};
use crate::error::{ExecutionError, Result};
/// In-memory table
@@ -49,7 +49,7 @@ impl MemTable {
}
/// Create a mem table by reading from another data source
- pub fn load(t: &Table) -> Result<Self> {
+ pub fn load(t: &TableProvider) -> Result<Self> {
let schema = t.schema();
let partitions = t.scan(&None, 1024 * 1024)?;
@@ -64,7 +64,7 @@ impl MemTable {
}
}
-impl Table for MemTable {
+impl TableProvider for MemTable {
fn schema(&self) -> &Arc<Schema> {
&self.schema
}
diff --git a/rust/datafusion/src/datasource/mod.rs b/rust/datafusion/src/datasource/mod.rs
index a927756fd5..504fbcc375 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, Table};
+pub use self::datasource::{RecordBatchIterator, ScanResult, TableProvider};
pub use self::memory::{MemBatchIterator, MemTable};
diff --git a/rust/datafusion/src/datasource/parquet.rs b/rust/datafusion/src/datasource/parquet.rs
index c357c37328..79e84ce8df 100644
--- a/rust/datafusion/src/datasource/parquet.rs
+++ b/rust/datafusion/src/datasource/parquet.rs
@@ -31,7 +31,7 @@ use parquet::data_type::{ByteArray, Int96};
use parquet::file::reader::*;
use parquet::reader::schema::parquet_to_arrow_schema;
-use crate::datasource::{RecordBatchIterator, ScanResult, Table};
+use crate::datasource::{RecordBatchIterator, ScanResult, TableProvider};
use crate::error::{ExecutionError, Result};
/// Table-based representation of a `ParquetFile`
@@ -53,7 +53,7 @@ impl ParquetTable {
}
}
-impl Table for ParquetTable {
+impl TableProvider for ParquetTable {
fn schema(&self) -> &Arc<Schema> {
&self.schema
}
@@ -677,7 +677,7 @@ mod tests {
);
}
- fn load_table(name: &str) -> Box<Table> {
+ fn load_table(name: &str) -> Box<TableProvider> {
let testdata = env::var("PARQUET_TEST_DATA").unwrap();
let filename = format!("{}/{}", testdata, name);
let table = ParquetTable::try_new(&filename).unwrap();
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index 8aee99f3b9..4d0071c2c3 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -26,7 +26,7 @@ use std::sync::Arc;
use arrow::datatypes::*;
use crate::datasource::csv::CsvFile;
-use crate::datasource::datasource::Table;
+use crate::datasource::TableProvider;
use crate::error::{ExecutionError, Result};
use crate::execution::aggregate::AggregateRelation;
use crate::execution::expression::*;
@@ -34,6 +34,7 @@ use crate::execution::filter::FilterRelation;
use crate::execution::limit::LimitRelation;
use crate::execution::projection::ProjectRelation;
use crate::execution::relation::{DataSourceRelation, Relation};
+use crate::execution::table_impl::TableImpl;
use crate::logicalplan::*;
use crate::optimizer::optimizer::OptimizerRule;
use crate::optimizer::projection_push_down::ProjectionPushDown;
@@ -41,10 +42,11 @@ use crate::optimizer::type_coercion::TypeCoercionRule;
use crate::optimizer::utils;
use crate::sql::parser::{DFASTNode, DFParser};
use crate::sql::planner::{SchemaProvider, SqlToRel};
+use crate::table::Table;
/// Execution context for registering data sources and executing queries
pub struct ExecutionContext {
- datasources: Rc<RefCell<HashMap<String, Rc<Table>>>>,
+ datasources: Rc<RefCell<HashMap<String, Rc<TableProvider>>>>,
}
impl ExecutionContext {
@@ -100,12 +102,30 @@ impl ExecutionContext {
}
/// Register a table so that it can be queried from SQL
- pub fn register_table(&mut self, name: &str, provider: Rc<Table>) {
+ pub fn register_table(&mut self, name: &str, provider: Rc<TableProvider>) {
self.datasources
.borrow_mut()
.insert(name.to_string(), provider);
}
+ /// Get a table by name
+ pub fn table(&mut self, table_name: &str) -> Result<Arc<Table>> {
+ match self.datasources.borrow().get(table_name) {
+ Some(provider) => {
+ Ok(Arc::new(TableImpl::new(Arc::new(LogicalPlan::TableScan {
+ schema_name: "".to_string(),
+ table_name: table_name.to_string(),
+ schema: provider.schema().clone(),
+ projection: None,
+ }))))
+ }
+ _ => Err(ExecutionError::General(format!(
+ "No table named '{}'",
+ table_name
+ ))),
+ }
+ }
+
/// Optimize the logical plan by applying optimizer rules
fn optimize(&self, plan: &LogicalPlan) -> Result<Arc<LogicalPlan>> {
let rules: Vec<Box<OptimizerRule>> = vec![
@@ -268,7 +288,7 @@ impl ExecutionContext {
}
struct ExecutionContextSchemaProvider {
- datasources: Rc<RefCell<HashMap<String, Rc<Table>>>>,
+ datasources: Rc<RefCell<HashMap<String, Rc<TableProvider>>>>,
}
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 475c5b71c7..cfd748a704 100644
--- a/rust/datafusion/src/execution/mod.rs
+++ b/rust/datafusion/src/execution/mod.rs
@@ -24,3 +24,4 @@ pub mod filter;
pub mod limit;
pub mod projection;
pub mod relation;
+pub mod table_impl;
diff --git a/rust/datafusion/src/execution/table_impl.rs b/rust/datafusion/src/execution/table_impl.rs
new file mode 100644
index 0000000000..680dec2284
--- /dev/null
+++ b/rust/datafusion/src/execution/table_impl.rs
@@ -0,0 +1,101 @@
+// 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.
+
+//! Implementation of Table API
+
+use std::sync::Arc;
+
+use crate::arrow::datatypes::{Field, Schema};
+use crate::error::{ExecutionError, Result};
+use crate::logicalplan::Expr::Literal;
+use crate::logicalplan::ScalarValue;
+use crate::logicalplan::{Expr, LogicalPlan};
+use crate::table::*;
+
+/// Implementation of Table API
+pub struct TableImpl {
+ plan: Arc<LogicalPlan>,
+}
+
+impl TableImpl {
+ /// Create a new Table based on an existing logical plan
+ pub fn new(plan: Arc<LogicalPlan>) -> Self {
+ Self { plan }
+ }
+}
+
+impl Table for TableImpl {
+ /// Apply a projection based on a list of column names
+ fn select_columns(&self, columns: Vec<&str>) -> Result<Arc<Table>> {
+ let schema = self.plan.schema();
+ let mut projection_index: Vec<usize> = Vec::with_capacity(columns.len());
+ let mut expr: Vec<Expr> = Vec::with_capacity(columns.len());
+
+ for column in columns {
+ match schema.column_with_name(column) {
+ Some((i, _)) => {
+ projection_index.push(i);
+ expr.push(Expr::Column(i));
+ }
+ _ => {
+ return Err(ExecutionError::InvalidColumn(format!(
+ "No column named '{}'",
+ column
+ )));
+ }
+ }
+ }
+
+ Ok(Arc::new(TableImpl::new(Arc::new(
+ LogicalPlan::Projection {
+ expr,
+ input: self.plan.clone(),
+ schema: projection(&schema, &projection_index)?,
+ },
+ ))))
+ }
+
+ /// Limit the number of rows
+ fn limit(&self, n: usize) -> Result<Arc<Table>> {
+ Ok(Arc::new(TableImpl::new(Arc::new(LogicalPlan::Limit {
+ expr: Literal(ScalarValue::UInt32(n as u32)),
+ input: self.plan.clone(),
+ schema: self.plan.schema().clone(),
+ }))))
+ }
+
+ /// Convert to logical plan
+ fn to_logical_plan(&self) -> Arc<LogicalPlan> {
+ self.plan.clone()
+ }
+}
+
+/// Create a new schema by applying a projection to this schema's fields
+fn projection(schema: &Schema, projection: &Vec<usize>) -> Result<Arc<Schema>> {
+ let mut fields: Vec<Field> = Vec::with_capacity(projection.len());
+ for i in projection {
+ if *i < schema.fields().len() {
+ fields.push(schema.field(*i).clone());
+ } else {
+ return Err(ExecutionError::InvalidColumn(format!(
+ "Invalid column index {} in projection",
+ i
+ )));
+ }
+ }
+ Ok(Arc::new(Schema::new(fields)))
+}
diff --git a/rust/datafusion/src/lib.rs b/rust/datafusion/src/lib.rs
index 8febb08dbe..22805cffcd 100644
--- a/rust/datafusion/src/lib.rs
+++ b/rust/datafusion/src/lib.rs
@@ -32,3 +32,4 @@ pub mod execution;
pub mod logicalplan;
pub mod optimizer;
pub mod sql;
+pub mod table;
diff --git a/rust/datafusion/src/table.rs b/rust/datafusion/src/table.rs
new file mode 100644
index 0000000000..b1421c6ff0
--- /dev/null
+++ b/rust/datafusion/src/table.rs
@@ -0,0 +1,89 @@
+// 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.
+
+//! Table API for building a logical query plan. This is similar to the Table API in Ibis and
+//! the DataFrame API in Apache Spark
+
+use crate::error::Result;
+use crate::logicalplan::LogicalPlan;
+use std::sync::Arc;
+
+/// Table is an abstraction of a logical query plan
+pub trait Table {
+ /// Select columns by name
+ fn select_columns(&self, columns: Vec<&str>) -> Result<Arc<Table>>;
+
+ /// limit the number of rows
+ fn limit(&self, n: usize) -> Result<Arc<Table>>;
+
+ /// Return the logical plan
+ fn to_logical_plan(&self) -> Arc<LogicalPlan>;
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::execution::context::ExecutionContext;
+ use arrow::datatypes::*;
+
+ #[test]
+ fn demonstrate_api_usage() {
+ let mut ctx = ExecutionContext::new();
+ register_aggregate_csv(&mut ctx);
+
+ let t = ctx.table("aggregate_test_100").unwrap();
+
+ let example = t
+ .select_columns(vec!["c1", "c2", "c11"])
+ .unwrap()
+ .limit(10)
+ .unwrap();
+
+ let plan = example.to_logical_plan();
+
+ assert_eq!("Limit: UInt32(10)\n Projection: #0, #1, #10\n TableScan: aggregate_test_100 projection=None", format!("{:?}", plan));
+ }
+
+ fn register_aggregate_csv(ctx: &mut ExecutionContext) {
+ let schema = aggr_test_schema();
+ ctx.register_csv(
+ "aggregate_test_100",
+ "../../testing/data/csv/aggregate_test_100.csv",
+ &schema,
+ true,
+ );
+ }
+
+ fn aggr_test_schema() -> Arc<Schema> {
+ Arc::new(Schema::new(vec![
+ Field::new("c1", DataType::Utf8, false),
+ Field::new("c2", DataType::UInt32, false),
+ Field::new("c3", DataType::Int8, false),
+ Field::new("c4", DataType::Int16, false),
+ Field::new("c5", DataType::Int32, false),
+ Field::new("c6", DataType::Int64, false),
+ Field::new("c7", DataType::UInt8, false),
+ Field::new("c8", DataType::UInt16, false),
+ Field::new("c9", DataType::UInt32, false),
+ Field::new("c10", DataType::UInt64, false),
+ Field::new("c11", DataType::Float32, false),
+ Field::new("c12", DataType::Float64, false),
+ Field::new("c13", DataType::Utf8, false),
+ ]))
+ }
+
+}
diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rs
index 9c24a504bd..9c64a447a0 100644
--- a/rust/datafusion/tests/sql.rs
+++ b/rust/datafusion/tests/sql.rs
@@ -27,7 +27,7 @@ use arrow::array::*;
use arrow::datatypes::{DataType, Field, Schema};
use datafusion::datasource::parquet::ParquetTable;
-use datafusion::datasource::Table;
+use datafusion::datasource::TableProvider;
use datafusion::execution::context::ExecutionContext;
use datafusion::execution::relation::Relation;
@@ -179,7 +179,7 @@ fn register_csv(
ctx.register_csv(name, filename, &schema, true);
}
-fn load_parquet_table(name: &str) -> Rc<Table> {
+fn load_parquet_table(name: &str) -> Rc<TableProvider> {
let testdata = env::var("PARQUET_TEST_DATA").unwrap();
let filename = format!("{}/{}", testdata, name);
let table = ParquetTable::try_new(&filename).unwrap();