Apache DataFusion SQL Query Engine
ARROW-6104: [Rust] [DataFusion] Remove use of bare trait objects
Andy Grove1e4e81b853e7
diff --git a/rust/datafusion/src/datasource/datasource.rs b/rust/datafusion/src/datasource/datasource.rsindex cdbe8a57c2..715f518026 100644--- a/rust/datafusion/src/datasource/datasource.rs+++ b/rust/datafusion/src/datasource/datasource.rs@@ -26,7 +26,7 @@ use crate::error::Result;/// Returned by implementors of `Table#scan`, this `RecordBatchIterator` is wrapped with/// an `Arc` and `Mutex` so that it can be shared across threads as it is used.-pub type ScanResult = Arc<Mutex<RecordBatchIterator>>;+pub type ScanResult = Arc<Mutex<dyn RecordBatchIterator>>;/// Source tablepub trait TableProvider {diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rsindex f14883ae3b..c2dd0da544 100644--- a/rust/datafusion/src/datasource/memory.rs+++ b/rust/datafusion/src/datasource/memory.rs@@ -49,7 +49,7 @@ impl MemTable {}/// Create a mem table by reading from another data source- pub fn load(t: &TableProvider) -> Result<Self> {+ pub fn load(t: &dyn TableProvider) -> Result<Self> {let schema = t.schema();let partitions = t.scan(&None, 1024 * 1024)?;diff --git a/rust/datafusion/src/datasource/parquet.rs b/rust/datafusion/src/datasource/parquet.rsindex 0ba328938d..1703c33e93 100644--- a/rust/datafusion/src/datasource/parquet.rs+++ b/rust/datafusion/src/datasource/parquet.rs@@ -79,7 +79,7 @@ pub struct ParquetFile {projection_schema: Arc<Schema>,batch_size: usize,row_group_index: usize,- current_row_group: Option<Box<RowGroupReader>>,+ current_row_group: Option<Box<dyn RowGroupReader>>,column_readers: Vec<ColumnReader>,}@@ -256,11 +256,12 @@ impl ParquetFile {fn load_batch(&mut self) -> Result<Option<RecordBatch>> {match &self.current_row_group {Some(reader) => {- let mut batch: Vec<Arc<Array>> = Vec::with_capacity(reader.num_columns());+ let mut batch: Vec<Arc<dyn Array>> =+ Vec::with_capacity(reader.num_columns());for i in 0..self.column_readers.len() {let dt = self.schema().field(i).data_type().clone();let is_nullable = self.schema().field(i).is_nullable();- let array: Arc<Array> = match self.column_readers[i] {+ let array: Arc<dyn Array> = match self.column_readers[i] {ColumnReader::BoolColumnReader(ref mut r) => {ArrowReader::<BooleanType>::read(r,@@ -678,7 +679,7 @@ mod tests {);}- fn load_table(name: &str) -> Box<TableProvider> {+ fn load_table(name: &str) -> Box<dyn TableProvider> {let testdata =env::var("PARQUET_TEST_DATA").expect("PARQUET_TEST_DATA not defined");let filename = format!("{}/{}", testdata, name);diff --git a/rust/datafusion/src/execution/aggregate.rs b/rust/datafusion/src/execution/aggregate.rsindex 11e766a784..fc1223c4a7 100644--- a/rust/datafusion/src/execution/aggregate.rs+++ b/rust/datafusion/src/execution/aggregate.rs@@ -41,7 +41,7 @@ use fnv::FnvHashMap;/// or more aggregate expressionspub(super) struct AggregateRelation {schema: Arc<Schema>,- input: Rc<RefCell<Relation>>,+ input: Rc<RefCell<dyn Relation>>,group_expr: Vec<CompiledExpr>,aggr_expr: Vec<CompiledAggregateExpression>,end_of_results: bool,@@ -50,7 +50,7 @@ pub(super) struct AggregateRelation {impl AggregateRelation {pub fn new(schema: Arc<Schema>,- input: Rc<RefCell<Relation>>,+ input: Rc<RefCell<dyn Relation>>,group_expr: Vec<CompiledExpr>,aggr_expr: Vec<CompiledAggregateExpression>,) -> Self {@@ -472,7 +472,7 @@ impl AggregateFunction for CountFunction {}struct AccumulatorSet {- aggr_values: Vec<Rc<RefCell<AggregateFunction>>>,+ aggr_values: Vec<Rc<RefCell<dyn AggregateFunction>>>,}impl AccumulatorSet {@@ -504,27 +504,27 @@ struct MapEntry {fn create_accumulators(aggr_expr: &Vec<CompiledAggregateExpression>,) -> Result<AccumulatorSet> {- let aggr_values: Vec<Rc<RefCell<AggregateFunction>>> = aggr_expr+ let aggr_values: Vec<Rc<RefCell<dyn AggregateFunction>>> = aggr_expr.iter().map(|e| match e.aggr_type() {AggregateType::Min => {Ok(Rc::new(RefCell::new(MinFunction::new(e.data_type())))- as Rc<RefCell<AggregateFunction>>)+ as Rc<RefCell<dyn AggregateFunction>>)}AggregateType::Max => {Ok(Rc::new(RefCell::new(MaxFunction::new(e.data_type())))- as Rc<RefCell<AggregateFunction>>)+ as Rc<RefCell<dyn AggregateFunction>>)}AggregateType::Sum => {Ok(Rc::new(RefCell::new(SumFunction::new(e.data_type())))- as Rc<RefCell<AggregateFunction>>)+ as Rc<RefCell<dyn AggregateFunction>>)}AggregateType::Avg => {Ok(Rc::new(RefCell::new(AvgFunction::new(e.data_type())))- as Rc<RefCell<AggregateFunction>>)+ as Rc<RefCell<dyn AggregateFunction>>)}AggregateType::Count => Ok(Rc::new(RefCell::new(CountFunction::new()))- as Rc<RefCell<AggregateFunction>>),+ as Rc<RefCell<dyn AggregateFunction>>),_ => Err(ExecutionError::ExecutionError("unsupported aggregate function".to_string(),)),@@ -1482,7 +1482,7 @@ mod tests {]))}- fn load_csv(filename: &str, schema: &Arc<Schema>) -> Rc<RefCell<Relation>> {+ fn load_csv(filename: &str, schema: &Arc<Schema>) -> Rc<RefCell<dyn Relation>> {let ds = CsvBatchIterator::new(filename, schema.clone(), true, &None, 10);Rc::new(RefCell::new(DataSourceRelation::new(Arc::new(Mutex::new(ds,diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex b041f55d75..1e6f28e8dc 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -51,7 +51,7 @@ use sqlparser::sqlast::{SQLColumnDef, SQLType};/// Execution context for registering data sources and executing queriespub struct ExecutionContext {- datasources: Rc<RefCell<HashMap<String, Rc<TableProvider>>>>,+ datasources: Rc<RefCell<HashMap<String, Rc<dyn TableProvider>>>>,}impl ExecutionContext {@@ -64,7 +64,11 @@ impl ExecutionContext {/// Execute a SQL query and produce a Relation (a schema-aware iterator over a series/// of RecordBatch instances)- pub fn sql(&mut self, sql: &str, batch_size: usize) -> Result<Rc<RefCell<Relation>>> {+ pub fn sql(+ &mut self,+ sql: &str,+ batch_size: usize,+ ) -> Result<Rc<RefCell<dyn Relation>>> {let plan = self.create_logical_plan(sql)?;let plan = self.optimize(&plan)?;Ok(self.execute(&plan, batch_size)?)@@ -76,7 +80,7 @@ impl ExecutionContext {match ast {DFASTNode::ANSI(ansi) => {- let schema_provider: Arc<SchemaProvider> =+ let schema_provider: Arc<dyn SchemaProvider> =Arc::new(ExecutionContextSchemaProvider {datasources: self.datasources.clone(),});@@ -160,14 +164,14 @@ impl ExecutionContext {}/// Register a table so that it can be queried from SQL- pub fn register_table(&mut self, name: &str, provider: Rc<TableProvider>) {+ pub fn register_table(&mut self, name: &str, provider: Rc<dyn 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>> {+ pub fn table(&mut self, table_name: &str) -> Result<Arc<dyn Table>> {match (*self.datasources).borrow().get(table_name) {Some(provider) => {Ok(Arc::new(TableImpl::new(Arc::new(LogicalPlan::TableScan {@@ -187,7 +191,7 @@ impl ExecutionContext {/// Optimize the logical plan by applying optimizer rulespub fn optimize(&self, plan: &LogicalPlan) -> Result<Arc<LogicalPlan>> {- let rules: Vec<Box<OptimizerRule>> = vec![+ let rules: Vec<Box<dyn OptimizerRule>> = vec![Box::new(ProjectionPushDown::new()),Box::new(TypeCoercionRule::new()),];@@ -204,7 +208,7 @@ impl ExecutionContext {&mut self,plan: &LogicalPlan,batch_size: usize,- ) -> Result<Rc<RefCell<Relation>>> {+ ) -> Result<Rc<RefCell<dyn Relation>>> {match *plan {LogicalPlan::TableScan {ref table_name,@@ -376,7 +380,7 @@ impl ExecutionContext {}struct ExecutionContextSchemaProvider {- datasources: Rc<RefCell<HashMap<String, Rc<TableProvider>>>>,+ datasources: Rc<RefCell<HashMap<String, Rc<dyn TableProvider>>>>,}impl SchemaProvider for ExecutionContextSchemaProvider {fn get_table_meta(&self, name: &str) -> Option<Arc<Schema>> {diff --git a/rust/datafusion/src/execution/expression.rs b/rust/datafusion/src/execution/expression.rsindex 6282e77b76..8b182b7035 100644--- a/rust/datafusion/src/execution/expression.rs+++ b/rust/datafusion/src/execution/expression.rs@@ -30,10 +30,10 @@ use crate::execution::context::ExecutionContext;use crate::logicalplan::{Expr, Operator, ScalarValue};/// Function that accepts a RecordBatch and returns an ArrayRef-pub type ArrayFunction = Rc<Fn(&RecordBatch) -> Result<ArrayRef>>;+pub type ArrayFunction = Rc<dyn Fn(&RecordBatch) -> Result<ArrayRef>>;/// Function that accepts an ArrayRef and returns an ArrayRef-pub type CompiledCastFunction = Rc<Fn(&ArrayRef) -> Result<ArrayRef>>;+pub type CompiledCastFunction = Rc<dyn Fn(&ArrayRef) -> Result<ArrayRef>>;/// Enumeration of supported aggregate functions#[allow(missing_docs)] // seems like these variants are self-evidentdiff --git a/rust/datafusion/src/execution/filter.rs b/rust/datafusion/src/execution/filter.rsindex 4cb5b25854..f003517c22 100644--- a/rust/datafusion/src/execution/filter.rs+++ b/rust/datafusion/src/execution/filter.rs@@ -37,14 +37,14 @@ pub(super) struct FilterRelation {/// input relation.schema: Arc<Schema>,/// Relation that is being filtered- input: Rc<RefCell<Relation>>,+ input: Rc<RefCell<dyn Relation>>,/// Filter expressionexpr: CompiledExpr,}impl FilterRelation {pub fn new(- input: Rc<RefCell<Relation>>,+ input: Rc<RefCell<dyn Relation>>,expr: CompiledExpr,schema: Arc<Schema>,) -> Self {diff --git a/rust/datafusion/src/execution/limit.rs b/rust/datafusion/src/execution/limit.rsindex ec31ea0662..11c9a2db8f 100644--- a/rust/datafusion/src/execution/limit.rs+++ b/rust/datafusion/src/execution/limit.rs@@ -32,7 +32,7 @@ use crate::execution::relation::Relation;/// Implementation of a LIMIT relationpub(super) struct LimitRelation {/// The relation which the limit is being applied to- input: Rc<RefCell<Relation>>,+ input: Rc<RefCell<dyn Relation>>,/// The schema for the limit relation, which is always the same as the schema of the/// input relationschema: Arc<Schema>,@@ -43,7 +43,11 @@ pub(super) struct LimitRelation {}impl LimitRelation {- pub fn new(input: Rc<RefCell<Relation>>, limit: usize, schema: Arc<Schema>) -> Self {+ pub fn new(+ input: Rc<RefCell<dyn Relation>>,+ limit: usize,+ schema: Arc<Schema>,+ ) -> Self {Self {input,schema,diff --git a/rust/datafusion/src/execution/physical_plan.rs b/rust/datafusion/src/execution/physical_plan.rsindex 79fb88e3ed..ee7c62ad2b 100644--- a/rust/datafusion/src/execution/physical_plan.rs+++ b/rust/datafusion/src/execution/physical_plan.rs@@ -28,13 +28,13 @@ pub trait ExecutionPlan {/// Get the schema for this execution planfn schema(&self) -> Arc<Schema>;/// Get the partitions for this execution plan. Each partition can be executed in parallel.- fn partitions(&self) -> Result<Vec<Arc<Partition>>>;+ fn partitions(&self) -> Result<Vec<Arc<dyn Partition>>>;}/// Represents a partition of an execution plan that can be executed on a threadpub trait Partition: Send + Sync {/// Execute this partition and return an iterator over RecordBatch- fn execute(&self) -> Result<Arc<BatchIterator>>;+ fn execute(&self) -> Result<Arc<dyn BatchIterator>>;}/// Iterator over RecordBatch that can be sent between threadsdiff --git a/rust/datafusion/src/execution/projection.rs b/rust/datafusion/src/execution/projection.rsindex 44b3951c1e..80510a1b98 100644--- a/rust/datafusion/src/execution/projection.rs+++ b/rust/datafusion/src/execution/projection.rs@@ -37,14 +37,14 @@ pub(super) struct ProjectRelation {/// Schema for the result of the projectionschema: Arc<Schema>,/// The relation that the projection is being applied to- input: Rc<RefCell<Relation>>,+ input: Rc<RefCell<dyn Relation>>,/// Projection expressionsexpr: Vec<CompiledExpr>,}impl ProjectRelation {pub fn new(- input: Rc<RefCell<Relation>>,+ input: Rc<RefCell<dyn Relation>>,expr: Vec<CompiledExpr>,schema: Arc<Schema>,) -> Self {diff --git a/rust/datafusion/src/execution/relation.rs b/rust/datafusion/src/execution/relation.rsindex 14dc11318b..c65055fdfc 100644--- a/rust/datafusion/src/execution/relation.rs+++ b/rust/datafusion/src/execution/relation.rs@@ -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<RecordBatchIterator>>,+ ds: Arc<Mutex<dyn RecordBatchIterator>>,}impl DataSourceRelation {- pub fn new(ds: Arc<Mutex<RecordBatchIterator>>) -> Self {+ pub fn new(ds: Arc<Mutex<dyn RecordBatchIterator>>) -> Self {let schema = ds.lock().unwrap().schema().clone();Self { ds, schema }}diff --git a/rust/datafusion/src/execution/table_impl.rs b/rust/datafusion/src/execution/table_impl.rsindex 1a92aacf4f..6b7c5bd30c 100644--- a/rust/datafusion/src/execution/table_impl.rs+++ b/rust/datafusion/src/execution/table_impl.rs@@ -40,7 +40,7 @@ impl TableImpl {impl Table for TableImpl {/// Apply a projection based on a list of column names- fn select_columns(&self, columns: Vec<&str>) -> Result<Arc<Table>> {+ fn select_columns(&self, columns: Vec<&str>) -> Result<Arc<dyn Table>> {let mut expr: Vec<Expr> = Vec::with_capacity(columns.len());for column_name in columns {let i = self.column_index(column_name)?;@@ -50,7 +50,7 @@ impl Table for TableImpl {}/// Create a projection based on arbitrary expressions- fn select(&self, expr_list: Vec<Expr>) -> Result<Arc<Table>> {+ fn select(&self, expr_list: Vec<Expr>) -> Result<Arc<dyn Table>> {let schema = self.plan.schema();let mut field: Vec<Field> = Vec::with_capacity(expr_list.len());@@ -78,7 +78,7 @@ impl Table for TableImpl {}/// Create a selection based on a filter expression- fn filter(&self, expr: Expr) -> Result<Arc<Table>> {+ fn filter(&self, expr: Expr) -> Result<Arc<dyn Table>> {Ok(Arc::new(TableImpl::new(Arc::new(LogicalPlan::Selection {expr,input: self.plan.clone(),@@ -90,7 +90,7 @@ impl Table for TableImpl {&self,group_expr: Vec<Expr>,aggr_expr: Vec<Expr>,- ) -> Result<Arc<Table>> {+ ) -> Result<Arc<dyn Table>> {Ok(Arc::new(TableImpl::new(Arc::new(LogicalPlan::Aggregate {input: self.plan.clone(),group_expr,@@ -100,7 +100,7 @@ impl Table for TableImpl {}/// Limit the number of rows- fn limit(&self, n: usize) -> Result<Arc<Table>> {+ fn limit(&self, n: usize) -> Result<Arc<dyn Table>> {Ok(Arc::new(TableImpl::new(Arc::new(LogicalPlan::Limit {expr: Literal(ScalarValue::UInt32(n as u32)),input: self.plan.clone(),diff --git a/rust/datafusion/src/lib.rs b/rust/datafusion/src/lib.rsindex 6e48162c6b..5f4d5ce388 100644--- a/rust/datafusion/src/lib.rs+++ b/rust/datafusion/src/lib.rs@@ -19,7 +19,6 @@//! Apache Arrow as the memory model#![warn(missing_docs)]-#![allow(bare_trait_objects)]extern crate arrow;extern crate sqlparser;diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex 90cb3bd8d8..7af24d7ba5 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -39,12 +39,12 @@ pub trait SchemaProvider {/// SQL query plannerpub struct SqlToRel {- schema_provider: Arc<SchemaProvider>,+ schema_provider: Arc<dyn SchemaProvider>,}impl SqlToRel {/// Create a new query planner- pub fn new(schema_provider: Arc<SchemaProvider>) -> Self {+ pub fn new(schema_provider: Arc<dyn SchemaProvider>) -> Self {SqlToRel { schema_provider }}diff --git a/rust/datafusion/src/table.rs b/rust/datafusion/src/table.rsindex b9ae895b8a..0c117938a7 100644--- a/rust/datafusion/src/table.rs+++ b/rust/datafusion/src/table.rs@@ -25,23 +25,23 @@ use std::sync::Arc;/// Table is an abstraction of a logical query planpub trait Table {/// Select columns by name- fn select_columns(&self, columns: Vec<&str>) -> Result<Arc<Table>>;+ fn select_columns(&self, columns: Vec<&str>) -> Result<Arc<dyn Table>>;/// Create a projection based on arbitrary expressions- fn select(&self, expr: Vec<Expr>) -> Result<Arc<Table>>;+ fn select(&self, expr: Vec<Expr>) -> Result<Arc<dyn Table>>;/// Create a selection based on a filter expression- fn filter(&self, expr: Expr) -> Result<Arc<Table>>;+ fn filter(&self, expr: Expr) -> Result<Arc<dyn Table>>;/// Perform an aggregate queryfn aggregate(&self,group_expr: Vec<Expr>,aggr_expr: Vec<Expr>,- ) -> Result<Arc<Table>>;+ ) -> Result<Arc<dyn Table>>;/// limit the number of rows- fn limit(&self, n: usize) -> Result<Arc<Table>>;+ fn limit(&self, n: usize) -> Result<Arc<dyn Table>>;/// Return the logical planfn to_logical_plan(&self) -> Arc<LogicalPlan>;