Apache DataFusion SQL Query Engine
ARROW-10732: [Rust] [DataFusion] Integrate DFSchema as a step towards supporting qualified column names
Andy Grove77b36a3bc059
diff --git a/rust/datafusion/src/dataframe.rs b/rust/datafusion/src/dataframe.rsindex 0945fa593d..68884217eb 100644--- a/rust/datafusion/src/dataframe.rs+++ b/rust/datafusion/src/dataframe.rs@@ -19,8 +19,7 @@use crate::arrow::record_batch::RecordBatch;use crate::error::Result;-use crate::logical_plan::{Expr, FunctionRegistry, JoinType, LogicalPlan};-use arrow::datatypes::Schema;+use crate::logical_plan::{DFSchema, Expr, FunctionRegistry, JoinType, LogicalPlan};use std::sync::Arc;use async_trait::async_trait;@@ -201,7 +200,7 @@ pub trait DataFrame {/// # Ok(())/// # }/// ```- fn schema(&self) -> &Schema;+ fn schema(&self) -> &DFSchema;/// Return the logical plan represented by this DataFrame.fn to_logical_plan(&self) -> LogicalPlan;diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex ee28f2ed9f..91f80cb90d 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -35,7 +35,7 @@ use crate::datasource::TableProvider;use crate::error::{DataFusionError, Result};use crate::execution::dataframe_impl::DataFrameImpl;use crate::logical_plan::{- FunctionRegistry, LogicalPlan, LogicalPlanBuilder, TableSource,+ DFSchema, DFSchemaRef, FunctionRegistry, LogicalPlan, LogicalPlanBuilder, TableSource,};use crate::optimizer::filter_push_down::FilterPushDown;use crate::optimizer::optimizer::OptimizerRule;@@ -140,7 +140,7 @@ impl ExecutionContext {name,location,CsvReadOptions::new()- .schema(&schema)+ .schema(&schema.as_ref().to_owned().into()).has_header(*has_header),)?;let plan = LogicalPlanBuilder::empty(false).build()?;@@ -214,7 +214,7 @@ impl ExecutionContext {has_header: options.has_header,delimiter: Some(options.delimiter),projection: None,- projected_schema: csv.schema(),+ projected_schema: Arc::new(DFSchema::from(&csv.schema())?),};Ok(Arc::new(DataFrameImpl::new(@@ -231,7 +231,7 @@ impl ExecutionContext {path: filename.to_string(),schema: parquet.schema(),projection: None,- projected_schema: parquet.schema(),+ projected_schema: Arc::new(DFSchema::from(&parquet.schema())?),};Ok(Arc::new(DataFrameImpl::new(@@ -250,7 +250,7 @@ impl ExecutionContext {schema_name: "".to_string(),source: TableSource::FromProvider(provider),table_schema: schema.clone(),- projected_schema: schema,+ projected_schema: DFSchemaRef::new(DFSchema::from(&schema)?),projection: None,};Ok(Arc::new(DataFrameImpl::new(@@ -302,7 +302,7 @@ impl ExecutionContext {schema_name: "".to_string(),source: TableSource::FromContext(table_name.to_string()),table_schema: schema.clone(),- projected_schema: schema,+ projected_schema: DFSchemaRef::new(DFSchema::from(&schema)?),projection: None,};Ok(Arc::new(DataFrameImpl::new(@@ -758,7 +758,7 @@ mod tests {)?]],schema: schema.clone(),projection: None,- projected_schema: schema.clone(),+ projected_schema: DFSchemaRef::new(DFSchema::from(&schema)?),}).project(vec![col("b")])?.build()?;diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rsindex d7141d4556..ce5d876cc4 100644--- a/rust/datafusion/src/execution/dataframe_impl.rs+++ b/rust/datafusion/src/execution/dataframe_impl.rs@@ -24,9 +24,8 @@ use crate::dataframe::*;use crate::error::Result;use crate::execution::context::{ExecutionContext, ExecutionContextState};use crate::logical_plan::{- col, Expr, FunctionRegistry, JoinType, LogicalPlan, LogicalPlanBuilder,+ col, DFSchema, Expr, FunctionRegistry, JoinType, LogicalPlan, LogicalPlanBuilder,};-use arrow::datatypes::Schema;use async_trait::async_trait;@@ -50,18 +49,12 @@ impl DataFrameImpl {impl DataFrame for DataFrameImpl {/// Apply a projection based on a list of column namesfn select_columns(&self, columns: Vec<&str>) -> Result<Arc<dyn DataFrame>> {- let exprs = columns+ let fields = columns.iter()- .map(|name| {- self.plan- .schema()- // take the index to ensure that the column exists in the schema- .index_of(name.to_owned())- .and_then(|_| Ok(col(name)))- .map_err(|e| e.into())- })+ .map(|name| self.plan.schema().field_with_unqualified_name(name)).collect::<Result<Vec<_>>>()?;- self.select(exprs)+ let expr = fields.iter().map(|f| col(f.name())).collect();+ self.select(expr)}/// Create a projection based on arbitrary expressions@@ -133,7 +126,7 @@ impl DataFrame for DataFrameImpl {}/// Returns the schema from the logical plan- fn schema(&self) -> &Schema {+ fn schema(&self) -> &DFSchema {self.plan.schema()}@@ -332,7 +325,7 @@ mod tests {ctx.register_csv("aggregate_test_100",&format!("{}/csv/aggregate_test_100.csv", testdata),- CsvReadOptions::new().schema(&schema),+ CsvReadOptions::new().schema(&schema.as_ref()),)?;Ok(())}diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rsindex ca3d8ed6cc..57ef80cd83 100644--- a/rust/datafusion/src/logical_plan/builder.rs+++ b/rust/datafusion/src/logical_plan/builder.rs@@ -30,7 +30,8 @@ use super::{col, exprlist_to_fields, Expr, JoinType, LogicalPlan, PlanType, StringifiedPlan,TableSource,};-use crate::physical_plan::hash_utils;+use crate::logical_plan::{DFField, DFSchema, DFSchemaRef};+use std::collections::HashSet;/// Builder for logical planspub struct LogicalPlanBuilder {@@ -49,7 +50,7 @@ impl LogicalPlanBuilder {pub fn empty(produce_one_row: bool) -> Self {Self::from(&LogicalPlan::EmptyRelation {produce_one_row,- schema: SchemaRef::new(Schema::empty()),+ schema: DFSchemaRef::new(DFSchema::empty()),})}@@ -69,15 +70,11 @@ impl LogicalPlanBuilder {.to_owned(),};- let projected_schema = SchemaRef::new(- projection- .clone()- .map(|p| {- Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect())- })- .or(Some(schema.clone()))- .unwrap(),- );+ let projected_schema = projection+ .clone()+ .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()))+ .or(Some(schema.clone()))+ .unwrap();Ok(Self::from(&LogicalPlan::CsvScan {path: path.to_owned(),@@ -85,7 +82,7 @@ impl LogicalPlanBuilder {has_header,delimiter: Some(delimiter),projection,- projected_schema,+ projected_schema: DFSchemaRef::new(DFSchema::from(&projected_schema)?),}))}@@ -103,7 +100,7 @@ impl LogicalPlanBuilder {path: path.to_owned(),schema,projection,- projected_schema,+ projected_schema: DFSchemaRef::new(DFSchema::from(&projected_schema)?),}))}@@ -125,7 +122,7 @@ impl LogicalPlanBuilder {schema_name: schema_name.to_owned(),source: TableSource::FromContext(table_name.to_owned()),table_schema,- projected_schema,+ projected_schema: DFSchemaRef::new(DFSchema::from(&projected_schema)?),projection,}))}@@ -149,12 +146,12 @@ impl LogicalPlanBuilder {validate_unique_names("Projections", &projected_expr, input_schema)?;- let schema = Schema::new(exprlist_to_fields(&projected_expr, input_schema)?);+ let schema = DFSchema::new(exprlist_to_fields(&projected_expr, input_schema)?)?;Ok(Self::from(&LogicalPlan::Projection {expr: projected_expr,input: Arc::new(self.plan.clone()),- schema: SchemaRef::new(schema),+ schema: DFSchemaRef::new(schema),}))}@@ -200,17 +197,8 @@ impl LogicalPlanBuilder {.zip(right_keys.iter()).map(|(x, y)| (x.to_string(), y.to_string())).collect::<Vec<_>>();- let physical_join_type = match join_type {- JoinType::Inner => hash_utils::JoinType::Inner,- JoinType::Left => hash_utils::JoinType::Left,- JoinType::Right => hash_utils::JoinType::Right,- };- let physical_schema = hash_utils::build_join_schema(- self.plan.schema(),- right.schema(),- &on,- &physical_join_type,- );+ let join_schema =+ build_join_schema(self.plan.schema(), right.schema(), &on, &join_type)?;Ok(Self::from(&LogicalPlan::Join {left: Arc::new(self.plan.clone()),right: Arc::new(right.clone()),@@ -220,7 +208,7 @@ impl LogicalPlanBuilder {.map(|(l, r)| (l.to_string(), r.to_string())).collect(),join_type,- schema: Arc::new(physical_schema),+ schema: DFSchemaRef::new(join_schema),}))}}@@ -232,13 +220,14 @@ impl LogicalPlanBuilder {validate_unique_names("Aggregations", &all_expr, self.plan.schema())?;- let aggr_schema = Schema::new(exprlist_to_fields(&all_expr, self.plan.schema())?);+ let aggr_schema =+ DFSchema::new(exprlist_to_fields(&all_expr, self.plan.schema())?)?;Ok(Self::from(&LogicalPlan::Aggregate {input: Arc::new(self.plan.clone()),group_expr,aggr_expr,- schema: SchemaRef::new(aggr_schema),+ schema: DFSchemaRef::new(aggr_schema),}))}@@ -255,7 +244,7 @@ impl LogicalPlanBuilder {verbose,plan: Arc::new(self.plan.clone()),stringified_plans,- schema,+ schema: DFSchemaRef::new(DFSchema::from(&schema)?),}))}@@ -265,11 +254,60 @@ impl LogicalPlanBuilder {}}+/// Creates a schema for a join operation.+/// The fields from the left side are first+fn build_join_schema(+ left: &DFSchema,+ right: &DFSchema,+ on: &[(String, String)],+ join_type: &JoinType,+) -> Result<DFSchema> {+ let fields: Vec<DFField> = match join_type {+ JoinType::Inner | JoinType::Left => {+ // remove right-side join keys if they have the same names as the left-side+ let duplicate_keys = &on+ .iter()+ .filter(|(l, r)| l == r)+ .map(|on| on.1.to_string())+ .collect::<HashSet<_>>();++ let left_fields = left.fields().iter();++ let right_fields = right+ .fields()+ .iter()+ .filter(|f| !duplicate_keys.contains(f.name()));++ // left then right+ left_fields.chain(right_fields).cloned().collect()+ }+ JoinType::Right => {+ // remove left-side join keys if they have the same names as the right-side+ let duplicate_keys = &on+ .iter()+ .filter(|(l, r)| l == r)+ .map(|on| on.1.to_string())+ .collect::<HashSet<_>>();++ let left_fields = left+ .fields()+ .iter()+ .filter(|f| !duplicate_keys.contains(f.name()));++ let right_fields = right.fields().iter();++ // left then right+ left_fields.chain(right_fields).cloned().collect()+ }+ };+ DFSchema::new(fields)+}+/// Errors if one or more expressions have equal names.fn validate_unique_names(node_name: &str,expressions: &[Expr],- input_schema: &Schema,+ input_schema: &DFSchema,) -> Result<()> {let mut unique_names = HashMap::new();expressions.iter().enumerate().map(|(position, expr)| {diff --git a/rust/datafusion/src/logical_plan/display.rs b/rust/datafusion/src/logical_plan/display.rsindex e430d1f069..9e2118dacf 100644--- a/rust/datafusion/src/logical_plan/display.rs+++ b/rust/datafusion/src/logical_plan/display.rs@@ -62,7 +62,11 @@ impl<'a, 'b> PlanVisitor for IndentVisitor<'a, 'b> {write!(self.f, "{}", plan.display())?;if self.with_schema {- write!(self.f, " {}", display_schema(plan.schema()))?;+ write!(+ self.f,+ " {}",+ display_schema(&plan.schema().as_ref().to_owned().into())+ )?;}self.indent += 1;@@ -202,7 +206,7 @@ impl<'a, 'b> PlanVisitor for GraphvizVisitor<'a, 'b> {format!("{}\\nSchema: {}",plan.display(),- display_schema(plan.schema())+ display_schema(&plan.schema().as_ref().to_owned().into()))} else {format!("{}", plan.display())diff --git a/rust/datafusion/src/logical_plan/expr.rs b/rust/datafusion/src/logical_plan/expr.rsindex 43edf62855..ae2ea25c75 100644--- a/rust/datafusion/src/logical_plan/expr.rs+++ b/rust/datafusion/src/logical_plan/expr.rs@@ -23,12 +23,10 @@ use std::fmt;use std::sync::Arc;use aggregates::{AccumulatorFunctionImplementation, StateTypeFunction};-use arrow::{- compute::can_cast_types,- datatypes::{DataType, Field, Schema},-};+use arrow::{compute::can_cast_types, datatypes::DataType};use crate::error::{DataFusionError, Result};+use crate::logical_plan::{DFField, DFSchema};use crate::physical_plan::{aggregates, expressions::binary_operator_data_type, functions, udf::ScalarUDF,};@@ -161,10 +159,13 @@ impl Expr {/// This function errors when it is not possible to compute its [arrow::datatypes::DataType]./// This happens when e.g. the expression refers to a column that does not exist in the schema, or when/// the expression is incorrectly typed (e.g. `[utf8] + [bool]`).- pub fn get_type(&self, schema: &Schema) -> Result<DataType> {+ pub fn get_type(&self, schema: &DFSchema) -> Result<DataType> {match self {Expr::Alias(expr, _) => expr.get_type(schema),- Expr::Column(name) => Ok(schema.field_with_name(name)?.data_type().clone()),+ Expr::Column(name) => Ok(schema+ .field_with_unqualified_name(name)?+ .data_type()+ .clone()),Expr::ScalarVariable(_) => Ok(DataType::Utf8),Expr::Literal(l) => Ok(l.get_datatype()),Expr::Case { when_then_expr, .. } => when_then_expr[0].1.get_type(schema),@@ -223,10 +224,12 @@ impl Expr {////// This function errors when it is not possible to compute its nullability./// This happens when the expression refers to a column that does not exist in the schema.- pub fn nullable(&self, input_schema: &Schema) -> Result<bool> {+ pub fn nullable(&self, input_schema: &DFSchema) -> Result<bool> {match self {Expr::Alias(expr, _) => expr.nullable(input_schema),- Expr::Column(name) => Ok(input_schema.field_with_name(name)?.is_nullable()),+ Expr::Column(name) => Ok(input_schema+ .field_with_unqualified_name(name)?+ .is_nullable()),Expr::Literal(value) => Ok(value.is_null()),Expr::ScalarVariable(_) => Ok(true),Expr::Case {@@ -271,13 +274,14 @@ impl Expr {/// Returns the name of this expression based on [arrow::datatypes::Schema].////// This represents how a column with this expression is named when no alias is chosen- pub fn name(&self, input_schema: &Schema) -> Result<String> {+ pub fn name(&self, input_schema: &DFSchema) -> Result<String> {create_name(self, input_schema)}/// Returns a [arrow::datatypes::Field] compatible with this expression.- pub fn to_field(&self, input_schema: &Schema) -> Result<Field> {- Ok(Field::new(+ pub fn to_field(&self, input_schema: &DFSchema) -> Result<DFField> {+ Ok(DFField::new(+ None, //TODO qualifier&self.name(input_schema)?,self.get_type(input_schema)?,self.nullable(input_schema)?,@@ -290,7 +294,7 @@ impl Expr {////// This function errors when it is impossible to cast the/// expression to the target [arrow::datatypes::DataType].- pub fn cast_to(&self, cast_to_type: &DataType, schema: &Schema) -> Result<Expr> {+ pub fn cast_to(&self, cast_to_type: &DataType, schema: &DFSchema) -> Result<Expr> {let this_type = self.get_type(schema)?;if this_type == *cast_to_type {Ok(self.clone())@@ -426,7 +430,7 @@ impl CaseBuilder {let then_types: Vec<DataType> = then_expr.iter().map(|e| match e {- Expr::Literal(_) => e.get_type(&Schema::empty()),+ Expr::Literal(_) => e.get_type(&DFSchema::empty()),_ => Ok(DataType::Null),}).collect::<Result<Vec<_>>>()?;@@ -779,7 +783,7 @@ fn create_function_name(fun: &String,distinct: bool,args: &[Expr],- input_schema: &Schema,+ input_schema: &DFSchema,) -> Result<String> {let names: Vec<String> = args.iter()@@ -794,7 +798,7 @@ fn create_function_name(/// Returns a readable name of an expression based on the input schema./// This function recursively transverses the expression for names such as "CAST(a > 2)".-fn create_name(e: &Expr, input_schema: &Schema) -> Result<String> {+fn create_name(e: &Expr, input_schema: &DFSchema) -> Result<String> {match e {Expr::Alias(_, name) => Ok(name.clone()),Expr::Column(name) => Ok(name.clone()),@@ -870,7 +874,10 @@ fn create_name(e: &Expr, input_schema: &Schema) -> Result<String> {}/// Create field meta-data from an expression, for use in a result set schema-pub fn exprlist_to_fields(expr: &[Expr], input_schema: &Schema) -> Result<Vec<Field>> {+pub fn exprlist_to_fields(+ expr: &[Expr],+ input_schema: &DFSchema,+) -> Result<Vec<DFField>> {expr.iter().map(|e| e.to_field(input_schema)).collect()}diff --git a/rust/datafusion/src/logical_plan/extension.rs b/rust/datafusion/src/logical_plan/extension.rsindex d4bf644311..184310229b 100644--- a/rust/datafusion/src/logical_plan/extension.rs+++ b/rust/datafusion/src/logical_plan/extension.rs@@ -17,7 +17,7 @@//! This module defines the interface for logical nodesuse super::{Expr, LogicalPlan};-use arrow::datatypes::SchemaRef;+use crate::logical_plan::DFSchemaRef;use std::{any::Any, collections::HashSet, fmt, sync::Arc};/// This defines the interface for `LogicalPlan` nodes that can be@@ -34,7 +34,7 @@ pub trait UserDefinedLogicalNode: fmt::Debug {fn inputs(&self) -> Vec<&LogicalPlan>;/// Return the output schema of this logical plan node- fn schema(&self) -> &SchemaRef;+ fn schema(&self) -> &DFSchemaRef;/// returns all expressions in the current logical plan node. This/// should not include expressions of any inputs (akadiff --git a/rust/datafusion/src/logical_plan/plan.rs b/rust/datafusion/src/logical_plan/plan.rsindex 075c9dd436..79a1fb07d6 100644--- a/rust/datafusion/src/logical_plan/plan.rs+++ b/rust/datafusion/src/logical_plan/plan.rs@@ -31,6 +31,7 @@ use crate::sql::parser::FileType;use super::display::{GraphvizVisitor, IndentVisitor};use super::expr::Expr;use super::extension::UserDefinedLogicalNode;+use crate::logical_plan::dfschema::DFSchemaRef;/// Describes the source of the table, either registered on the context or by reference#[derive(Clone)]@@ -70,7 +71,7 @@ pub enum LogicalPlan {/// The incoming logical planinput: Arc<LogicalPlan>,/// The schema description of the output- schema: SchemaRef,+ schema: DFSchemaRef,},/// Filters rows from its input that do not match an/// expression (essentially a WHERE clause with a predicate@@ -96,7 +97,7 @@ pub enum LogicalPlan {/// Aggregate expressionsaggr_expr: Vec<Expr>,/// The schema description of the aggregate output- schema: SchemaRef,+ schema: DFSchemaRef,},/// Sorts its input according to a list of sort expressions.Sort {@@ -116,7 +117,7 @@ pub enum LogicalPlan {/// Join typejoin_type: JoinType,/// The output schema, containing fields from the left and right inputs- schema: SchemaRef,+ schema: DFSchemaRef,},/// Produces rows from a table provider by reference or from the contextTableScan {@@ -129,7 +130,7 @@ pub enum LogicalPlan {/// Optional column indices to use as a projectionprojection: Option<Vec<usize>>,/// The schema description of the output- projected_schema: SchemaRef,+ projected_schema: DFSchemaRef,},/// Produces rows that come from a `Vec` of in memory `RecordBatch`esInMemoryScan {@@ -140,7 +141,7 @@ pub enum LogicalPlan {/// Optional column indices to use as a projectionprojection: Option<Vec<usize>>,/// The schema description of the output- projected_schema: SchemaRef,+ projected_schema: DFSchemaRef,},/// Produces rows by scanning Parquet file(s)ParquetScan {@@ -151,7 +152,7 @@ pub enum LogicalPlan {/// Optional column indices to use as a projectionprojection: Option<Vec<usize>>,/// The schema description of the output- projected_schema: SchemaRef,+ projected_schema: DFSchemaRef,},/// Produces rows by scanning a CSV file(s)CsvScan {@@ -166,14 +167,14 @@ pub enum LogicalPlan {/// Optional column indices to use as a projectionprojection: Option<Vec<usize>>,/// The schema description of the output- projected_schema: SchemaRef,+ projected_schema: DFSchemaRef,},/// Produces no rows: An empty relation with an empty schemaEmptyRelation {/// Whether to produce a placeholder rowproduce_one_row: bool,/// The schema description of the output- schema: SchemaRef,+ schema: DFSchemaRef,},/// Produces the first `n` tuples from its input and discards the rest.Limit {@@ -185,7 +186,7 @@ pub enum LogicalPlan {/// Creates an external table.CreateExternalTable {/// The table schema- schema: SchemaRef,+ schema: DFSchemaRef,/// The table namename: String,/// The physical location@@ -205,7 +206,7 @@ pub enum LogicalPlan {/// Represent the various stages plans have gone throughstringified_plans: Vec<StringifiedPlan>,/// The output schema of the explain (2 columns of text)- schema: SchemaRef,+ schema: DFSchemaRef,},/// Extension operator defined outside of DataFusionExtension {@@ -216,7 +217,7 @@ pub enum LogicalPlan {impl LogicalPlan {/// Get a reference to the logical plan's schema- pub fn schema(&self) -> &SchemaRef {+ pub fn schema(&self) -> &DFSchemaRef {match self {LogicalPlan::EmptyRelation { schema, .. } => &schema,LogicalPlan::InMemoryScan {diff --git a/rust/datafusion/src/optimizer/filter_push_down.rs b/rust/datafusion/src/optimizer/filter_push_down.rsindex 26d4410cd1..f095f8d5aa 100644--- a/rust/datafusion/src/optimizer/filter_push_down.rs+++ b/rust/datafusion/src/optimizer/filter_push_down.rs@@ -14,11 +14,9 @@//! Filter Push Down optimizer rule ensures that filters are applied as early as possible in the plan-use arrow::datatypes::Schema;-use crate::error::Result;-use crate::logical_plan::Expr;use crate::logical_plan::{and, LogicalPlan};+use crate::logical_plan::{DFSchema, Expr};use crate::optimizer::optimizer::OptimizerRule;use crate::optimizer::utils;use std::{@@ -87,8 +85,8 @@ fn get_predicates<'a>(// Note that a predicate can be both pushed to the left and to the right.fn get_join_predicates<'a>(state: &'a State,- left: &Schema,- right: &Schema,+ left: &DFSchema,+ right: &DFSchema,) -> (Vec<&'a HashSet<String>>,Vec<&'a HashSet<String>>,diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex ac653065cc..f2df7e1cba 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -19,10 +19,10 @@//! loaded into memoryuse crate::error::{DataFusionError, Result};-use crate::logical_plan::LogicalPlan;+use crate::logical_plan::{DFField, DFSchema, DFSchemaRef, LogicalPlan};use crate::optimizer::optimizer::OptimizerRule;use crate::optimizer::utils;-use arrow::datatypes::{Field, Schema, SchemaRef};+use arrow::datatypes::Schema;use arrow::error::Result as ArrowResult;use std::{collections::HashSet, sync::Arc};use utils::optimize_explain;@@ -60,7 +60,7 @@ fn get_projected_schema(projection: &Option<Vec<usize>>,required_columns: &HashSet<String>,has_projection: bool,-) -> Result<(Vec<usize>, SchemaRef)> {+) -> Result<(Vec<usize>, DFSchemaRef)> {if projection.is_some() {return Err(DataFusionError::Internal("Cannot run projection push-down rule more than once".to_string(),@@ -98,12 +98,15 @@ fn get_projected_schema(projection.sort();// create the projected schema- let mut projected_fields: Vec<Field> = Vec::with_capacity(projection.len());+ let mut projected_fields: Vec<DFField> = Vec::with_capacity(projection.len());for i in &projection {- projected_fields.push(schema.fields()[*i].clone());+ projected_fields.push(DFField::from(schema.fields()[*i].clone()));}- Ok((projection, SchemaRef::new(Schema::new(projected_fields))))+ Ok((+ projection,+ DFSchemaRef::new(DFSchema::new(projected_fields)?),+ ))}/// Recursively transverses the logical plan removing expressions and that are not needed.@@ -154,7 +157,7 @@ fn optimize_plan(Ok(LogicalPlan::Projection {expr: new_expr,input: Arc::new(new_input),- schema: SchemaRef::new(Schema::new(new_fields)),+ schema: DFSchemaRef::new(DFSchema::new(new_fields)?),})}}@@ -220,14 +223,14 @@ fn optimize_plan(}).collect::<Result<()>>()?;- let new_schema = Schema::new(+ let new_schema = DFSchema::new(schema.fields().iter().filter(|x| new_required_columns.contains(x.name())).cloned().collect(),- );+ )?;Ok(LogicalPlan::Aggregate {group_expr: group_expr.clone(),@@ -238,7 +241,7 @@ fn optimize_plan(&new_required_columns,true,)?),- schema: SchemaRef::new(new_schema),+ schema: DFSchemaRef::new(new_schema),})}// scans:@@ -334,7 +337,10 @@ fn optimize_plan(plan,stringified_plans,schema,- } => optimize_explain(optimizer, *verbose, &*plan, stringified_plans, &*schema),+ } => {+ let schema = schema.as_ref().to_owned().into();+ optimize_explain(optimizer, *verbose, &*plan, stringified_plans, &schema)+ }// all other nodes: Add any additional columns used by// expressions in this node to the list of required columnsLogicalPlan::Limit { .. }diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex ade195a771..aebb791591 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -19,11 +19,13 @@use std::{collections::HashSet, sync::Arc};-use arrow::datatypes::{Schema, SchemaRef};+use arrow::datatypes::Schema;use super::optimizer::OptimizerRule;use crate::error::{DataFusionError, Result};-use crate::logical_plan::{Expr, LogicalPlan, PlanType, StringifiedPlan};+use crate::logical_plan::{+ DFSchema, DFSchemaRef, Expr, LogicalPlan, PlanType, StringifiedPlan,+};use crate::prelude::{col, lit};use crate::scalar::ScalarValue;@@ -117,13 +119,11 @@ pub fn optimize_explain(PlanType::OptimizedLogicalPlan { optimizer_name },format!("{:#?}", plan),));- let schema = SchemaRef::new(schema.clone());-Ok(LogicalPlan::Explain {verbose,plan,stringified_plans,- schema,+ schema: DFSchemaRef::new(DFSchema::from(schema)?),})}@@ -429,7 +429,7 @@ mod tests {true,&empty_plan,&vec![StringifiedPlan::new(PlanType::LogicalPlan, "...")],- &*schema,+ schema.as_ref(),)?;match &optimized_explain {diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex 80f0613c19..a296885bda 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -23,7 +23,8 @@ use super::{aggregates, empty::EmptyExec, expressions::binary, functions, udaf};use crate::error::{DataFusionError, Result};use crate::execution::context::ExecutionContextState;use crate::logical_plan::{- Expr, LogicalPlan, PlanType, StringifiedPlan, TableSource, UserDefinedLogicalNode,+ DFSchema, Expr, LogicalPlan, PlanType, StringifiedPlan, TableSource,+ UserDefinedLogicalNode,};use crate::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::physical_plan::explain::ExplainExec;@@ -44,7 +45,7 @@ use crate::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr, PhysicalPuse crate::prelude::JoinType;use crate::variable::VarType;use arrow::compute::SortOptions;-use arrow::datatypes::Schema;+use arrow::datatypes::{Schema, SchemaRef};use expressions::col;/// This trait permits the `DefaultPhysicalPlanner` to create plans for@@ -162,7 +163,7 @@ impl DefaultPhysicalPlanner {..} => Ok(Arc::new(MemoryExec::try_new(data,- Arc::new(projected_schema.as_ref().to_owned()),+ projected_schema.as_ref().to_owned().into(),projection.to_owned(),)?)),LogicalPlan::CsvScan {@@ -181,27 +182,6 @@ impl DefaultPhysicalPlanner {projection.to_owned(),batch_size,)?)),- LogicalPlan::ParquetScan {- path, projection, ..- } => Ok(Arc::new(ParquetExec::try_new(- path,- projection.to_owned(),- batch_size,- )?)),- LogicalPlan::Projection { input, expr, .. } => {- let input = self.create_physical_plan(input, ctx_state)?;- let input_schema = input.as_ref().schema();- let runtime_expr = expr- .iter()- .map(|e| {- tuple_err((- self.create_physical_expr(e, &input_schema, &ctx_state),- e.name(&input_schema),- ))- })- .collect::<Result<Vec<_>>>()?;- Ok(Arc::new(ProjectionExec::try_new(runtime_expr, input)?))- }LogicalPlan::Aggregate {input,group_expr,@@ -209,28 +189,40 @@ impl DefaultPhysicalPlanner {..} => {// Initially need to perform the aggregate and then merge the partitions- let input = self.create_physical_plan(input, ctx_state)?;- let input_schema = input.as_ref().schema();+ let input_exec = self.create_physical_plan(input, ctx_state)?;+ let physical_input_schema = input_exec.as_ref().schema();+ let logical_input_schema = input.as_ref().schema();let groups = group_expr.iter().map(|e| {tuple_err((- self.create_physical_expr(e, &input_schema, ctx_state),- e.name(&input_schema),+ self.create_physical_expr(+ e,+ &physical_input_schema,+ ctx_state,+ ),+ e.name(&logical_input_schema),))}).collect::<Result<Vec<_>>>()?;let aggregates = aggr_expr.iter()- .map(|e| self.create_aggregate_expr(e, &input_schema, ctx_state))+ .map(|e| {+ self.create_aggregate_expr(+ e,+ &logical_input_schema,+ &physical_input_schema,+ ctx_state,+ )+ }).collect::<Result<Vec<_>>>()?;let initial_aggr = Arc::new(HashAggregateExec::try_new(AggregateMode::Partial,groups.clone(),aggregates.clone(),- input,+ input_exec,)?);let final_group: Vec<Arc<dyn PhysicalExpr>> =@@ -249,6 +241,31 @@ impl DefaultPhysicalPlanner {initial_aggr,)?))}+ LogicalPlan::ParquetScan {+ path, projection, ..+ } => Ok(Arc::new(ParquetExec::try_new(+ path,+ projection.to_owned(),+ batch_size,+ )?)),+ LogicalPlan::Projection { input, expr, .. } => {+ let input_exec = self.create_physical_plan(input, ctx_state)?;+ let input_schema = input.as_ref().schema();+ let runtime_expr = expr+ .iter()+ .map(|e| {+ tuple_err((+ self.create_physical_expr(+ e,+ &input_exec.schema(),+ &ctx_state,+ ),+ e.name(&input_schema),+ ))+ })+ .collect::<Result<Vec<_>>>()?;+ Ok(Arc::new(ProjectionExec::try_new(runtime_expr, input_exec)?))+ }LogicalPlan::Filter {input, predicate, ..} => {@@ -316,7 +333,7 @@ impl DefaultPhysicalPlanner {schema,} => Ok(Arc::new(EmptyExec::new(*produce_one_row,- Arc::new(schema.as_ref().clone()),+ SchemaRef::new(schema.as_ref().to_owned().into()),))),LogicalPlan::Limit { input, n, .. } => {let limit = *n;@@ -367,8 +384,10 @@ impl DefaultPhysicalPlanner {format!("{:#?}", input),));}- let schema_ref = Arc::new(schema.as_ref().clone());- Ok(Arc::new(ExplainExec::new(schema_ref, stringified_plans)))+ Ok(Arc::new(ExplainExec::new(+ SchemaRef::new(schema.as_ref().to_owned().into()),+ stringified_plans,+ )))}LogicalPlan::Extension { node } => {let inputs = node@@ -386,7 +405,7 @@ impl DefaultPhysicalPlanner {// Ensure the ExecutionPlan's schema matches the// declared logical schema to catch and warn about// logic errors when creating user defined plans.- if plan.schema() != *node.schema() {+ if plan.schema() != node.schema().as_ref().to_owned().into() {Err(DataFusionError::Plan(format!("Extension planner for {:?} created an ExecutionPlan with mismatched schema. \LogicalPlan schema: {:?}, ExecutionPlan schema: {:?}",@@ -550,13 +569,14 @@ impl DefaultPhysicalPlanner {pub fn create_aggregate_expr(&self,e: &Expr,- input_schema: &Schema,+ logical_input_schema: &DFSchema,+ physical_input_schema: &Schema,ctx_state: &ExecutionContextState,) -> Result<Arc<dyn AggregateExpr>> {// unpack aliased logical expressions, e.g. "sum(col) as total"let (name, e) = match e {Expr::Alias(sub_expr, alias) => (alias.clone(), sub_expr.as_ref()),- _ => (e.name(input_schema)?, e),+ _ => (e.name(logical_input_schema)?, e),};match e {@@ -568,23 +588,27 @@ impl DefaultPhysicalPlanner {} => {let args = args.iter()- .map(|e| self.create_physical_expr(e, input_schema, ctx_state))+ .map(|e| {+ self.create_physical_expr(e, physical_input_schema, ctx_state)+ }).collect::<Result<Vec<_>>>()?;aggregates::create_aggregate_expr(fun,*distinct,&args,- input_schema,+ physical_input_schema,name,)}Expr::AggregateUDF { fun, args, .. } => {let args = args.iter()- .map(|e| self.create_physical_expr(e, input_schema, ctx_state))+ .map(|e| {+ self.create_physical_expr(e, physical_input_schema, ctx_state)+ }).collect::<Result<Vec<_>>>()?;- udaf::create_aggregate_expr(fun, &args, input_schema, name)+ udaf::create_aggregate_expr(fun, &args, physical_input_schema, name)}other => Err(DataFusionError::Internal(format!("Invalid aggregate expression '{:?}'",@@ -637,6 +661,7 @@ impl ExtensionPlanner for DefaultExtensionPlanner {#[cfg(test)]mod tests {use super::*;+ use crate::logical_plan::{DFField, DFSchema, DFSchemaRef};use crate::physical_plan::{csv::CsvReadOptions, expressions, Partitioning};use crate::{logical_plan::{col, lit, sum, LogicalPlanBuilder},@@ -792,8 +817,24 @@ mod tests {};let plan = planner.create_physical_plan(&logical_plan, &ctx_state);- let expected_error = "Extension planner for NoOp created an ExecutionPlan with mismatched schema. LogicalPlan schema: Schema { fields: [Field { name: \"a\", data_type: Int32, nullable: false, dict_id: 0, dict_is_ordered: false }], metadata: {} }, ExecutionPlan schema: Schema { fields: [Field { name: \"b\", data_type: Int32, nullable: false, dict_id: 0, dict_is_ordered: false }], metadata: {} }";-+ let expected_error: &str = "Error during planning: \+ Extension planner for NoOp created an ExecutionPlan with mismatched schema. \+ LogicalPlan schema: DFSchema { fields: [\+ DFField { qualifier: None, field: Field { \+ name: \"a\", \+ data_type: Int32, \+ nullable: false, \+ dict_id: 0, \+ dict_is_ordered: false } }\+ ] }, \+ ExecutionPlan schema: Schema { fields: [\+ Field { \+ name: \"b\", \+ data_type: Int32, \+ nullable: false, \+ dict_id: 0, \+ dict_is_ordered: false }\+ ], metadata: {} }";match plan {Ok(_) => assert!(false, "Expected planning failure"),Err(e) => assert!(@@ -808,17 +849,16 @@ mod tests {/// An example extension node that doesn't do anythingstruct NoOpExtensionNode {- schema: SchemaRef,+ schema: DFSchemaRef,}impl Default for NoOpExtensionNode {fn default() -> Self {Self {- schema: SchemaRef::new(Schema::new(vec![Field::new(- "a",- DataType::Int32,- false,- )])),+ schema: DFSchemaRef::new(+ DFSchema::new(vec![DFField::new(None, "a", DataType::Int32, false)])+ .unwrap(),+ ),}}}@@ -838,7 +878,7 @@ mod tests {vec![]}- fn schema(&self) -> &SchemaRef {+ fn schema(&self) -> &DFSchemaRef {&self.schema}diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex 7ea81a090a..b18e1f3944 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -22,7 +22,8 @@ use std::sync::Arc;use crate::logical_plan::Expr::Alias;use crate::logical_plan::{- and, lit, Expr, LogicalPlan, LogicalPlanBuilder, Operator, PlanType, StringifiedPlan,+ and, lit, DFSchema, DFSchemaRef, Expr, LogicalPlan, LogicalPlanBuilder, Operator,+ PlanType, StringifiedPlan,};use crate::scalar::ScalarValue;use crate::{@@ -47,7 +48,6 @@ use sqlparser::ast::{use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};use sqlparser::ast::{OrderByExpr, Statement};use sqlparser::parser::ParserError::ParserError;-use std::collections::HashSet;/// The SchemaProvider trait allows the query planner to obtain meta-data about tables and/// functions referenced in SQL statements@@ -138,10 +138,10 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {FileType::NdJson => {}};- let schema = SchemaRef::new(self.build_schema(&columns)?);+ let schema = self.build_schema(&columns)?;Ok(LogicalPlan::CreateExternalTable {- schema,+ schema: DFSchemaRef::new(DFSchema::from(&schema)?),name: name.clone(),location: location.clone(),file_type: file_type.clone(),@@ -170,7 +170,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {verbose,plan,stringified_plans,- schema,+ schema: DFSchemaRef::new(DFSchema::from(&schema)?),})}@@ -269,7 +269,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {match constraint {JoinConstraint::On(sql_expr) => {let mut keys: Vec<(String, String)> = vec![];- let join_schema = create_join_schema(left.schema(), &right.schema())?;+ let join_schema = left.schema().join(&right.schema())?;// parse ON expressionlet expr = self.sql_to_rex(sql_expr, &join_schema)?;@@ -343,8 +343,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {for plan in &plans {fields.extend_from_slice(&plan.schema().fields());}- check_unique_columns(&fields)?;- let join_schema = Schema::new(fields);+ let join_schema = DFSchema::new(fields)?;let filter_expr = self.sql_to_rex(predicate_expr, &join_schema)?;@@ -360,12 +359,12 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {let right_schema = right.schema();let mut join_keys = vec![];for (l, r) in &possible_join_keys {- if left_schema.field_with_name(l).is_ok()- && right_schema.field_with_name(r).is_ok()+ if left_schema.field_with_unqualified_name(l).is_ok()+ && right_schema.field_with_unqualified_name(r).is_ok(){join_keys.push((l.as_str(), r.as_str()));- } else if left_schema.field_with_name(r).is_ok()- && right_schema.field_with_name(l).is_ok()+ } else if left_schema.field_with_unqualified_name(r).is_ok()+ && right_schema.field_with_unqualified_name(l).is_ok(){join_keys.push((r.as_str(), l.as_str()));}@@ -528,7 +527,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {}/// Generate a relational expression from a select SQL expression- fn sql_select_to_rex(&self, sql: &SelectItem, schema: &Schema) -> Result<Expr> {+ fn sql_select_to_rex(&self, sql: &SelectItem, schema: &DFSchema) -> Result<Expr> {match sql {SelectItem::UnnamedExpr(expr) => self.sql_to_rex(expr, schema),SelectItem::ExprWithAlias { expr, alias } => Ok(Alias(@@ -543,7 +542,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {}/// Generate a relational expression from a SQL expression- pub fn sql_to_rex(&self, sql: &SQLExpr, schema: &Schema) -> Result<Expr> {+ pub fn sql_to_rex(&self, sql: &SQLExpr, schema: &DFSchema) -> Result<Expr> {match sql {SQLExpr::Value(Value::Number(n)) => match n.parse::<i64>() {Ok(n) => Ok(lit(n)),@@ -556,7 +555,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {let var_names = vec![id.value.clone()];Ok(Expr::ScalarVariable(var_names))} else {- match schema.field_with_name(&id.value) {+ match schema.field_with_unqualified_name(&id.value) {Ok(field) => Ok(Expr::Column(field.name().clone())),Err(_) => Err(DataFusionError::Plan(format!("Invalid identifier '{}' for schema {}",@@ -777,27 +776,6 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {}}-fn create_join_schema(left: &SchemaRef, right: &SchemaRef) -> Result<Schema> {- let mut fields = vec![];- fields.extend_from_slice(&left.fields());- fields.extend_from_slice(&right.fields());- check_unique_columns(&fields)?;- Ok(Schema::new(fields))-}--fn check_unique_columns(fields: &[Field]) -> Result<()> {- // Until https://issues.apache.org/jira/browse/ARROW-10732 is implemented, we need- // to ensure that schemas have unique field names- let unique_field_names = fields.iter().map(|f| f.name()).collect::<HashSet<_>>();- if unique_field_names.len() == fields.len() {- Ok(())- } else {- Err(DataFusionError::Plan(- "JOIN would result in schema with duplicate column names".to_string(),- ))- }-}-/// Remove join expressions from a filter expressionfn remove_join_expressions(expr: &Expr,diff --git a/rust/datafusion/src/test/user_defined.rs b/rust/datafusion/src/test/user_defined.rsindex 505f5cdafa..745ae3d3e3 100644--- a/rust/datafusion/src/test/user_defined.rs+++ b/rust/datafusion/src/test/user_defined.rs@@ -23,9 +23,7 @@ use std::{sync::Arc,};-use arrow::datatypes::SchemaRef;--use crate::logical_plan::{Expr, LogicalPlan, UserDefinedLogicalNode};+use crate::logical_plan::{DFSchemaRef, Expr, LogicalPlan, UserDefinedLogicalNode};/// Create a new user defined plan node, for testingpub fn new(input: LogicalPlan) -> LogicalPlan {@@ -52,7 +50,7 @@ impl UserDefinedLogicalNode for TestUserDefinedPlanNode {vec![&self.input]}- fn schema(&self) -> &SchemaRef {+ fn schema(&self) -> &DFSchemaRef {self.input.schema()}diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex 07922e1c5f..b92f2777ae 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -32,7 +32,7 @@ use arrow::{use datafusion::datasource::{csv::CsvReadOptions, MemTable};use datafusion::error::Result;use datafusion::execution::context::ExecutionContext;-use datafusion::logical_plan::LogicalPlan;+use datafusion::logical_plan::{DFSchema, LogicalPlan};use datafusion::prelude::create_udf;#[tokio::test]@@ -1350,7 +1350,10 @@ async fn execute(ctx: &mut ExecutionContext, sql: &str) -> Vec<Vec<String>> {let results = ctx.collect(plan).await.expect(&msg);assert_eq!(logical_schema.as_ref(), optimized_logical_schema.as_ref());- assert_eq!(logical_schema.as_ref(), physical_schema.as_ref());+ assert_eq!(+ logical_schema.as_ref(),+ &DFSchema::from(physical_schema.as_ref()).unwrap()+ );result_vec(&results)}diff --git a/rust/datafusion/tests/user_defined_plan.rs b/rust/datafusion/tests/user_defined_plan.rsindex b059f5cecb..315a89eb6b 100644--- a/rust/datafusion/tests/user_defined_plan.rs+++ b/rust/datafusion/tests/user_defined_plan.rs@@ -85,6 +85,7 @@ use std::task::{Context, Poll};use std::{any::Any, collections::BTreeMap, fmt, sync::Arc};use async_trait::async_trait;+use datafusion::logical_plan::DFSchemaRef;/// Execute the specified sql and return the resulting record batches/// pretty printed as a String.@@ -246,7 +247,7 @@ impl OptimizerRule for TopKOptimizerRule {*verbose,&*plan,stringified_plans,- &*schema,+ &schema.as_ref().to_owned().into(),)}_ => {}@@ -288,7 +289,7 @@ impl UserDefinedLogicalNode for TopKPlanNode {}/// Schema for TopK is the same as the input- fn schema(&self) -> &SchemaRef {+ fn schema(&self) -> &DFSchemaRef {self.input.schema()}