Apache DataFusion SQL Query Engine
ARROW-8784: [Rust] [DataFusion] Remove use of Arc from LogicalPlan
Andy Groveac74bb871df3
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 8e765b725d..35bb2d23b5 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -144,7 +144,7 @@ impl ExecutionContext {header_row,location,} => {- let schema = Arc::new(self.build_schema(columns)?);+ let schema = Box::new(self.build_schema(columns)?);Ok(LogicalPlan::CreateExternalTable {schema,@@ -233,11 +233,12 @@ impl ExecutionContext {pub fn table(&mut self, table_name: &str) -> Result<Arc<dyn Table>> {match self.datasources.get(table_name) {Some(provider) => {+ let schema = provider.schema().as_ref().clone();let table_scan = LogicalPlan::TableScan {schema_name: "".to_string(),table_name: table_name.to_string(),- table_schema: provider.schema().clone(),- projected_schema: provider.schema().clone(),+ table_schema: Box::new(schema.to_owned()),+ projected_schema: Box::new(schema),projection: None,};Ok(Arc::new(TableImpl::new(@@ -859,13 +860,13 @@ mod tests {#[test]fn scalar_udf() -> Result<()> {- let schema = Arc::new(Schema::new(vec![+ let schema = Schema::new(vec![Field::new("a", DataType::Int32, false),Field::new("b", DataType::Int32, false),- ]));+ ]);let batch = RecordBatch::try_new(- schema.clone(),+ Arc::new(schema.clone()),vec![Arc::new(Int32Array::from(vec![1, 10, 10, 100])),Arc::new(Int32Array::from(vec![2, 12, 12, 120])),@@ -874,7 +875,7 @@ mod tests {let mut ctx = ExecutionContext::new();- let provider = MemTable::new(schema, vec![batch])?;+ let provider = MemTable::new(Arc::new(schema), vec![batch])?;ctx.register_table("t", Box::new(provider));let myfunc: ScalarUdf = |args: &[ArrayRef]| {diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rsindex 0443e6cd8e..2ce940daa3 100644--- a/rust/datafusion/src/logicalplan.rs+++ b/rust/datafusion/src/logicalplan.rs@@ -22,7 +22,6 @@//! physical query plans and executed.use std::fmt;-use std::sync::Arc;use arrow::datatypes::{DataType, Field, Schema};@@ -180,7 +179,7 @@ impl ScalarValue {#[derive(Clone, PartialEq)]pub enum Expr {/// An aliased expression- Alias(Arc<Expr>, String),+ Alias(Box<Expr>, String),/// index into a value within the row or complex valueColumn(usize),/// Reference to column by name@@ -190,29 +189,29 @@ pub enum Expr {/// binary expression e.g. "age > 21"BinaryExpr {/// Left-hand side of the expression- left: Arc<Expr>,+ left: Box<Expr>,/// The comparison operatorop: Operator,/// Right-hand side of the expression- right: Arc<Expr>,+ right: Box<Expr>,},/// unary NOT- Not(Arc<Expr>),+ Not(Box<Expr>),/// unary IS NOT NULL- IsNotNull(Arc<Expr>),+ IsNotNull(Box<Expr>),/// unary IS NULL- IsNull(Arc<Expr>),+ IsNull(Box<Expr>),/// cast a value to a different typeCast {/// The expression being cast- expr: Arc<Expr>,+ expr: Box<Expr>,/// The `DataType` the expression will yielddata_type: DataType,},/// sort expressionSort {/// The expression to sort on- expr: Arc<Expr>,+ expr: Box<Expr>,/// The direction of the sortasc: bool,},@@ -285,7 +284,7 @@ impl Expr {Ok(self.clone())} else if can_coerce_from(cast_to_type, &this_type) {Ok(Expr::Cast {- expr: Arc::new(self.clone()),+ expr: Box::new(self.clone()),data_type: cast_to_type.clone(),})} else {@@ -299,65 +298,65 @@ impl Expr {/// Equalpub fn eq(&self, other: &Expr) -> Expr {Expr::BinaryExpr {- left: Arc::new(self.clone()),+ left: Box::new(self.clone()),op: Operator::Eq,- right: Arc::new(other.clone()),+ right: Box::new(other.clone()),}}/// Not equalpub fn not_eq(&self, other: &Expr) -> Expr {Expr::BinaryExpr {- left: Arc::new(self.clone()),+ left: Box::new(self.clone()),op: Operator::NotEq,- right: Arc::new(other.clone()),+ right: Box::new(other.clone()),}}/// Greater thanpub fn gt(&self, other: &Expr) -> Expr {Expr::BinaryExpr {- left: Arc::new(self.clone()),+ left: Box::new(self.clone()),op: Operator::Gt,- right: Arc::new(other.clone()),+ right: Box::new(other.clone()),}}/// Greater than or equal topub fn gt_eq(&self, other: &Expr) -> Expr {Expr::BinaryExpr {- left: Arc::new(self.clone()),+ left: Box::new(self.clone()),op: Operator::GtEq,- right: Arc::new(other.clone()),+ right: Box::new(other.clone()),}}/// Less thanpub fn lt(&self, other: &Expr) -> Expr {Expr::BinaryExpr {- left: Arc::new(self.clone()),+ left: Box::new(self.clone()),op: Operator::Lt,- right: Arc::new(other.clone()),+ right: Box::new(other.clone()),}}/// Less than or equal topub fn lt_eq(&self, other: &Expr) -> Expr {Expr::BinaryExpr {- left: Arc::new(self.clone()),+ left: Box::new(self.clone()),op: Operator::LtEq,- right: Arc::new(other.clone()),+ right: Box::new(other.clone()),}}/// Notpub fn not(&self) -> Expr {- Expr::Not(Arc::new(self.clone()))+ Expr::Not(Box::new(self.clone()))}/// Aliaspub fn alias(&self, name: &str) -> Expr {- Expr::Alias(Arc::new(self.clone()), name.to_owned())+ Expr::Alias(Box::new(self.clone()), name.to_owned())}}@@ -482,36 +481,36 @@ pub enum LogicalPlan {/// The list of expressionsexpr: Vec<Expr>,/// The incoming logic plan- input: Arc<LogicalPlan>,+ input: Box<LogicalPlan>,/// The schema description- schema: Arc<Schema>,+ schema: Box<Schema>,},/// A Selection (essentially a WHERE clause with a predicate expression)Selection {/// The expressionexpr: Expr,/// The incoming logic plan- input: Arc<LogicalPlan>,+ input: Box<LogicalPlan>,},/// Represents a list of aggregate expressions with optional grouping expressionsAggregate {/// The incoming logic plan- input: Arc<LogicalPlan>,+ input: Box<LogicalPlan>,/// Grouping expressionsgroup_expr: Vec<Expr>,/// Aggregate expressionsaggr_expr: Vec<Expr>,/// The schema description- schema: Arc<Schema>,+ schema: Box<Schema>,},/// Represents a list of sort expressions to be applied to a relationSort {/// The sort expressionsexpr: Vec<Expr>,/// The incoming logic plan- input: Arc<LogicalPlan>,+ input: Box<LogicalPlan>,/// The schema description- schema: Arc<Schema>,+ schema: Box<Schema>,},/// A table scan against a table that has been registered on a contextTableScan {@@ -520,30 +519,30 @@ pub enum LogicalPlan {/// The name of the tabletable_name: String,/// The underlying table schema- table_schema: Arc<Schema>,+ table_schema: Box<Schema>,/// The projected schema- projected_schema: Arc<Schema>,+ projected_schema: Box<Schema>,/// Optional column indices to use as a projectionprojection: Option<Vec<usize>>,},/// An empty relation with an empty schemaEmptyRelation {/// The schema description- schema: Arc<Schema>,+ schema: Box<Schema>,},/// Represents the maximum number of records to returnLimit {/// The expressionexpr: Expr,/// The logical plan- input: Arc<LogicalPlan>,+ input: Box<LogicalPlan>,/// The schema description- schema: Arc<Schema>,+ schema: Box<Schema>,},/// Represents a create external table expression.CreateExternalTable {/// The table schema- schema: Arc<Schema>,+ schema: Box<Schema>,/// The table namename: String,/// The physical location@@ -557,7 +556,7 @@ pub enum LogicalPlan {impl LogicalPlan {/// Get a reference to the logical plan's schema- pub fn schema(&self) -> &Arc<Schema> {+ pub fn schema(&self) -> &Box<Schema> {match self {LogicalPlan::EmptyRelation { schema } => &schema,LogicalPlan::TableScan {@@ -725,7 +724,7 @@ impl LogicalPlanBuilder {/// Create an empty relationpub fn empty() -> Self {Self::from(&LogicalPlan::EmptyRelation {- schema: Arc::new(Schema::empty()),+ schema: Box::new(Schema::empty()),})}@@ -742,8 +741,8 @@ impl LogicalPlanBuilder {Ok(Self::from(&LogicalPlan::TableScan {schema_name: schema_name.to_owned(),table_name: table_name.to_owned(),- table_schema: Arc::new(table_schema.clone()),- projected_schema: Arc::new(+ table_schema: Box::new(table_schema.clone()),+ projected_schema: Box::new(projected_schema.or(Some(table_schema.clone())).unwrap(),),projection,@@ -774,8 +773,8 @@ impl LogicalPlanBuilder {Ok(Self::from(&LogicalPlan::Projection {expr: projected_expr,- input: Arc::new(self.plan.clone()),- schema: Arc::new(schema),+ input: Box::new(self.plan.clone()),+ schema: Box::new(schema),}))}@@ -783,7 +782,7 @@ impl LogicalPlanBuilder {pub fn filter(&self, expr: Expr) -> Result<Self> {Ok(Self::from(&LogicalPlan::Selection {expr,- input: Arc::new(self.plan.clone()),+ input: Box::new(self.plan.clone()),}))}@@ -791,7 +790,7 @@ impl LogicalPlanBuilder {pub fn limit(&self, expr: Expr) -> Result<Self> {Ok(Self::from(&LogicalPlan::Limit {expr,- input: Arc::new(self.plan.clone()),+ input: Box::new(self.plan.clone()),schema: self.plan.schema().clone(),}))}@@ -800,7 +799,7 @@ impl LogicalPlanBuilder {pub fn sort(&self, expr: Vec<Expr>) -> Result<Self> {Ok(Self::from(&LogicalPlan::Sort {expr,- input: Arc::new(self.plan.clone()),+ input: Box::new(self.plan.clone()),schema: self.plan.schema().clone(),}))}@@ -814,10 +813,10 @@ impl LogicalPlanBuilder {Schema::new(utils::exprlist_to_fields(&all_fields, self.plan.schema())?);Ok(Self::from(&LogicalPlan::Aggregate {- input: Arc::new(self.plan.clone()),+ input: Box::new(self.plan.clone()),group_expr,aggr_expr,- schema: Arc::new(aggr_schema),+ schema: Box::new(aggr_schema),}))}@@ -830,28 +829,6 @@ impl LogicalPlanBuilder {#[cfg(test)]mod tests {use super::*;- use std::thread;-- #[test]- fn logical_plan_can_be_shared_between_threads() -> Result<()> {- let plan = LogicalPlanBuilder::scan(- "default",- "employee.csv",- &employee_schema(),- Some(vec![0, 3]),- )?- .filter(col("id").eq(&lit_str("CO")))?- .project(vec![col("id")])?- .build()?;-- // prove that a plan can be passed to a thread- let plan1 = plan.clone();- thread::spawn(move || {- println!("plan: {:?}", plan1);- });-- Ok(())- }#[test]fn plan_builder_simple() -> Result<()> {diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex b7e66cf5de..6781fcc057 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -25,7 +25,6 @@ use crate::optimizer::optimizer::OptimizerRule;use crate::optimizer::utils;use arrow::datatypes::{Field, Schema};use std::collections::{HashMap, HashSet};-use std::sync::Arc;/// Projection Push Down optimizer rule ensures that only referenced columns are/// loaded into memory@@ -154,7 +153,7 @@ impl ProjectionPushDown {schema_name: schema_name.to_string(),table_name: table_name.to_string(),table_schema: table_schema.clone(),- projected_schema: Arc::new(projected_schema),+ projected_schema: Box::new(projected_schema),projection: Some(projection),})}@@ -195,7 +194,7 @@ impl ProjectionPushDown {fn rewrite_expr(&self, expr: &Expr, mapping: &HashMap<usize, usize>) -> Result<Expr> {match expr {Expr::Alias(expr, name) => Ok(Expr::Alias(- Arc::new(self.rewrite_expr(expr, mapping)?),+ Box::new(self.rewrite_expr(expr, mapping)?),name.clone(),)),Expr::Column(i) => Ok(Expr::Column(self.new_index(mapping, i)?)),@@ -203,22 +202,22 @@ impl ProjectionPushDown {"Columns need to be resolved before this rule can run".to_owned(),)),Expr::Literal(_) => Ok(expr.clone()),- Expr::Not(e) => Ok(Expr::Not(Arc::new(self.rewrite_expr(e, mapping)?))),- Expr::IsNull(e) => Ok(Expr::IsNull(Arc::new(self.rewrite_expr(e, mapping)?))),+ Expr::Not(e) => Ok(Expr::Not(Box::new(self.rewrite_expr(e, mapping)?))),+ Expr::IsNull(e) => Ok(Expr::IsNull(Box::new(self.rewrite_expr(e, mapping)?))),Expr::IsNotNull(e) => {- Ok(Expr::IsNotNull(Arc::new(self.rewrite_expr(e, mapping)?)))+ Ok(Expr::IsNotNull(Box::new(self.rewrite_expr(e, mapping)?)))}Expr::BinaryExpr { left, op, right } => Ok(Expr::BinaryExpr {- left: Arc::new(self.rewrite_expr(left, mapping)?),+ left: Box::new(self.rewrite_expr(left, mapping)?),op: op.clone(),- right: Arc::new(self.rewrite_expr(right, mapping)?),+ right: Box::new(self.rewrite_expr(right, mapping)?),}),Expr::Cast { expr, data_type } => Ok(Expr::Cast {- expr: Arc::new(self.rewrite_expr(expr, mapping)?),+ expr: Box::new(self.rewrite_expr(expr, mapping)?),data_type: data_type.clone(),}),Expr::Sort { expr, asc } => Ok(Expr::Sort {- expr: Arc::new(self.rewrite_expr(expr, mapping)?),+ expr: Box::new(self.rewrite_expr(expr, mapping)?),asc: *asc,}),Expr::AggregateFunction {@@ -263,7 +262,6 @@ mod tests {use crate::logicalplan::ScalarValue;use crate::test::*;use arrow::datatypes::DataType;- use std::sync::Arc;#[test]fn aggregate_no_group_by() -> Result<()> {@@ -321,7 +319,7 @@ mod tests {let projection = LogicalPlanBuilder::from(&table_scan).project(vec![Cast {- expr: Arc::new(Column(2)),+ expr: Box::new(Column(2)),data_type: DataType::Float64,}])?.build()?;diff --git a/rust/datafusion/src/optimizer/resolve_columns.rs b/rust/datafusion/src/optimizer/resolve_columns.rsindex 69b48f0950..5a7f249b07 100644--- a/rust/datafusion/src/optimizer/resolve_columns.rs+++ b/rust/datafusion/src/optimizer/resolve_columns.rs@@ -22,7 +22,6 @@ use crate::logicalplan::LogicalPlan;use crate::logicalplan::{Expr, LogicalPlanBuilder};use crate::optimizer::optimizer::OptimizerRule;use arrow::datatypes::Schema;-use std::sync::Arc;/// Replace UnresolvedColumns with Columnspub struct ResolveColumnsRule {}@@ -75,21 +74,21 @@ fn rewrite_expr(expr: &Expr, schema: &Schema) -> Result<Expr> {Expr::Alias(expr, alias) => Ok(rewrite_expr(&expr, schema)?.alias(&alias)),Expr::UnresolvedColumn(name) => Ok(Expr::Column(schema.index_of(&name)?)),Expr::BinaryExpr { left, op, right } => Ok(Expr::BinaryExpr {- left: Arc::new(rewrite_expr(&left, schema)?),+ left: Box::new(rewrite_expr(&left, schema)?),op: op.clone(),- right: Arc::new(rewrite_expr(&right, schema)?),+ right: Box::new(rewrite_expr(&right, schema)?),}),- Expr::Not(expr) => Ok(Expr::Not(Arc::new(rewrite_expr(&expr, schema)?))),+ Expr::Not(expr) => Ok(Expr::Not(Box::new(rewrite_expr(&expr, schema)?))),Expr::IsNotNull(expr) => {- Ok(Expr::IsNotNull(Arc::new(rewrite_expr(&expr, schema)?)))+ Ok(Expr::IsNotNull(Box::new(rewrite_expr(&expr, schema)?)))}- Expr::IsNull(expr) => Ok(Expr::IsNull(Arc::new(rewrite_expr(&expr, schema)?))),+ Expr::IsNull(expr) => Ok(Expr::IsNull(Box::new(rewrite_expr(&expr, schema)?))),Expr::Cast { expr, data_type } => Ok(Expr::Cast {- expr: Arc::new(rewrite_expr(&expr, schema)?),+ expr: Box::new(rewrite_expr(&expr, schema)?),data_type: data_type.clone(),}),Expr::Sort { expr, asc } => Ok(Expr::Sort {- expr: Arc::new(rewrite_expr(&expr, schema)?),+ expr: Box::new(rewrite_expr(&expr, schema)?),asc: asc.clone(),}),Expr::ScalarFunction {diff --git a/rust/datafusion/src/optimizer/type_coercion.rs b/rust/datafusion/src/optimizer/type_coercion.rsindex 14ab1b956b..45f27d0db0 100644--- a/rust/datafusion/src/optimizer/type_coercion.rs+++ b/rust/datafusion/src/optimizer/type_coercion.rs@@ -21,7 +21,6 @@//! float)`. This keeps the runtime query execution code much simpler.use std::collections::HashMap;-use std::sync::Arc;use arrow::datatypes::Schema;@@ -62,22 +61,22 @@ impl<'a> TypeCoercionRule<'a> {let right_type = right.get_type(schema)?;if left_type == right_type {Ok(Expr::BinaryExpr {- left: Arc::new(left),+ left: Box::new(left),op: op.clone(),- right: Arc::new(right),+ right: Box::new(right),})} else {let super_type = utils::get_supertype(&left_type, &right_type)?;Ok(Expr::BinaryExpr {- left: Arc::new(left.cast_to(&super_type, schema)?),+ left: Box::new(left.cast_to(&super_type, schema)?),op: op.clone(),- right: Arc::new(right.cast_to(&super_type, schema)?),+ right: Box::new(right.cast_to(&super_type, schema)?),})}}- Expr::IsNull(e) => Ok(Expr::IsNull(Arc::new(self.rewrite_expr(e, schema)?))),+ Expr::IsNull(e) => Ok(Expr::IsNull(Box::new(self.rewrite_expr(e, schema)?))),Expr::IsNotNull(e) => {- Ok(Expr::IsNotNull(Arc::new(self.rewrite_expr(e, schema)?)))+ Ok(Expr::IsNotNull(Box::new(self.rewrite_expr(e, schema)?)))}Expr::ScalarFunction {name,@@ -129,7 +128,7 @@ impl<'a> TypeCoercionRule<'a> {Expr::Cast { .. } => Ok(expr.clone()),Expr::Column(_) => Ok(expr.clone()),Expr::Alias(expr, alias) => Ok(Expr::Alias(- Arc::new(self.rewrite_expr(expr, schema)?),+ Box::new(self.rewrite_expr(expr, schema)?),alias.to_owned(),)),Expr::Literal(_) => Ok(expr.clone()),@@ -250,9 +249,9 @@ mod tests {]);let expr = Expr::BinaryExpr {- left: Arc::new(Column(0)),+ left: Box::new(Column(0)),op: Operator::Plus,- right: Arc::new(Column(1)),+ right: Box::new(Column(1)),};let ctx = ExecutionContext::new();diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex de78f9c350..f9467a1209 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -250,21 +250,20 @@ mod tests {use crate::logicalplan::Expr;use arrow::datatypes::DataType;use std::collections::HashSet;- use std::sync::Arc;#[test]fn test_collect_expr() -> Result<()> {let mut accum: HashSet<usize> = HashSet::new();expr_to_column_indices(&Expr::Cast {- expr: Arc::new(Expr::Column(3)),+ expr: Box::new(Expr::Column(3)),data_type: DataType::Float64,},&mut accum,)?;expr_to_column_indices(&Expr::Cast {- expr: Arc::new(Expr::Column(3)),+ expr: Box::new(Expr::Column(3)),data_type: DataType::Float64,},&mut accum,diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex 714be1ebd0..a51aa41e02 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -243,7 +243,7 @@ impl<S: SchemaProvider> SqlToRel<S> {.iter().map(|e| {Ok(Expr::Sort {- expr: Arc::new(+ expr: Box::new(self.sql_to_rex(&e.expr, &input_schema).unwrap(),),asc: e.asc,@@ -273,7 +273,7 @@ impl<S: SchemaProvider> SqlToRel<S> {}ASTNode::SQLAliasedExpr(ref expr, ref alias) => Ok(Alias(- Arc::new(self.sql_to_rex(&expr, schema)?),+ Box::new(self.sql_to_rex(&expr, schema)?),alias.to_owned(),)),@@ -294,16 +294,16 @@ impl<S: SchemaProvider> SqlToRel<S> {ref expr,ref data_type,} => Ok(Expr::Cast {- expr: Arc::new(self.sql_to_rex(&expr, schema)?),+ expr: Box::new(self.sql_to_rex(&expr, schema)?),data_type: convert_data_type(data_type)?,}),ASTNode::SQLIsNull(ref expr) => {- Ok(Expr::IsNull(Arc::new(self.sql_to_rex(expr, schema)?)))+ Ok(Expr::IsNull(Box::new(self.sql_to_rex(expr, schema)?)))}ASTNode::SQLIsNotNull(ref expr) => {- Ok(Expr::IsNotNull(Arc::new(self.sql_to_rex(expr, schema)?)))+ Ok(Expr::IsNotNull(Box::new(self.sql_to_rex(expr, schema)?)))}ASTNode::SQLUnary {@@ -311,7 +311,7 @@ impl<S: SchemaProvider> SqlToRel<S> {ref expr,} => match *operator {SQLOperator::Not => {- Ok(Expr::Not(Arc::new(self.sql_to_rex(expr, schema)?)))+ Ok(Expr::Not(Box::new(self.sql_to_rex(expr, schema)?)))}_ => Err(ExecutionError::InternalError(format!("SQL binary operator cannot be interpreted as a unary operator"@@ -347,15 +347,15 @@ impl<S: SchemaProvider> SqlToRel<S> {"SQL unary operator \"NOT\" cannot be interpreted as a binary operator"))),_ => Ok(Expr::BinaryExpr {- left: Arc::new(self.sql_to_rex(&left, &schema)?),+ left: Box::new(self.sql_to_rex(&left, &schema)?),op: operator,- right: Arc::new(self.sql_to_rex(&right, &schema)?),+ right: Box::new(self.sql_to_rex(&right, &schema)?),})}}// &ASTNode::SQLOrderBy { ref expr, asc } => Ok(Expr::Sort {- // expr: Arc::new(self.sql_to_rex(&expr, &schema)?),+ // expr: Box::new(self.sql_to_rex(&expr, &schema)?),// asc,// }),ASTNode::SQLFunction { ref id, ref args } => {