Apache DataFusion SQL Query Engine
ARROW-8783: [Rust] [DataFusion] Add ParquetScan and CsvScan variants in LogicalPlan
Andy Grove4f0dae189ed8
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 35bb2d23b5..d5684a345c 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -33,6 +33,7 @@ use crate::datasource::parquet::ParquetTable;use crate::datasource::TableProvider;use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::common;+use crate::execution::physical_plan::csv::CsvExec;use crate::execution::physical_plan::datasource::DatasourceExec;use crate::execution::physical_plan::expressions::{Alias, Avg, BinaryExpr, CastExpr, Column, Count, Literal, Max, Min, Sum,@@ -41,6 +42,7 @@ use crate::execution::physical_plan::hash_aggregate::HashAggregateExec;use crate::execution::physical_plan::limit::LimitExec;use crate::execution::physical_plan::math_expressions::register_math_functions;use crate::execution::physical_plan::merge::MergeExec;+use crate::execution::physical_plan::parquet::ParquetExec;use crate::execution::physical_plan::projection::ProjectionExec;use crate::execution::physical_plan::selection::SelectionExec;use crate::execution::physical_plan::udf::{ScalarFunction, ScalarFunctionExpr};@@ -297,6 +299,26 @@ impl ExecutionContext {table_name))),},+ LogicalPlan::CsvScan {+ path,+ schema,+ has_header,+ projection,+ ..+ } => Ok(Arc::new(CsvExec::try_new(+ path,+ Arc::new(schema.as_ref().to_owned()),+ *has_header,+ 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, batch_size)?;let input_schema = input.as_ref().schema().clone();diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rsindex 2ce940daa3..40dd64eb86 100644--- a/rust/datafusion/src/logicalplan.rs+++ b/rust/datafusion/src/logicalplan.rs@@ -25,6 +25,8 @@ use std::fmt;use arrow::datatypes::{DataType, Field, Schema};+use crate::datasource::parquet::ParquetTable;+use crate::datasource::TableProvider;use crate::error::{ExecutionError, Result};use crate::optimizer::utils;use crate::sql::parser::FileType;@@ -518,12 +520,36 @@ pub enum LogicalPlan {schema_name: String,/// The name of the tabletable_name: String,- /// The underlying table schema+ /// The schema of the CSV file(s)table_schema: Box<Schema>,+ /// Optional column indices to use as a projection+ projection: Option<Vec<usize>>,+ /// The projected schema+ projected_schema: Box<Schema>,+ },+ /// A table scan against a Parquet data source+ ParquetScan {+ /// The path to the files+ path: String,+ /// The schema of the Parquet file(s)+ schema: Box<Schema>,+ /// Optional column indices to use as a projection+ projection: Option<Vec<usize>>,/// The projected schemaprojected_schema: Box<Schema>,+ },+ /// A table scan against a CSV data source+ CsvScan {+ /// The path to the files+ path: String,+ /// The underlying table schema+ schema: Box<Schema>,+ /// Whether the CSV file(s) have a header containing column names+ has_header: bool,/// Optional column indices to use as a projectionprojection: Option<Vec<usize>>,+ /// The projected schema+ projected_schema: Box<Schema>,},/// An empty relation with an empty schemaEmptyRelation {@@ -559,6 +585,12 @@ impl LogicalPlan {pub fn schema(&self) -> &Box<Schema> {match self {LogicalPlan::EmptyRelation { schema } => &schema,+ LogicalPlan::CsvScan {+ projected_schema, ..+ } => &projected_schema,+ LogicalPlan::ParquetScan {+ projected_schema, ..+ } => &projected_schema,LogicalPlan::TableScan {projected_schema, ..} => &projected_schema,@@ -587,6 +619,16 @@ impl LogicalPlan {ref projection,..} => write!(f, "TableScan: {} projection={:?}", table_name, projection),+ LogicalPlan::CsvScan {+ ref path,+ ref projection,+ ..+ } => write!(f, "CsvScan: {} projection={:?}", path, projection),+ LogicalPlan::ParquetScan {+ ref path,+ ref projection,+ ..+ } => write!(f, "ParquetScan: {} projection={:?}", path, projection),LogicalPlan::Projection {ref expr,ref input,@@ -728,6 +770,45 @@ impl LogicalPlanBuilder {})}+ /// Scan a CSV data source+ pub fn scan_csv(+ path: &str,+ has_header: bool,+ schema: &Schema,+ projection: Option<Vec<usize>>,+ ) -> Result<Self> {+ let projected_schema = projection+ .clone()+ .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()));+ Ok(Self::from(&LogicalPlan::CsvScan {+ path: path.to_owned(),+ schema: Box::new(schema.to_owned()),+ has_header,+ projection,+ projected_schema: Box::new(+ projected_schema.or(Some(schema.clone())).unwrap(),+ ),+ }))+ }++ /// Scan a Parquet data source+ pub fn scan_parquet(path: &str, projection: Option<Vec<usize>>) -> Result<Self> {+ let p = ParquetTable::try_new(path)?;+ let schema = p.schema().as_ref().to_owned();+ println!("{:?}", schema);+ let projected_schema = projection+ .clone()+ .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()));+ Ok(Self::from(&LogicalPlan::ParquetScan {+ path: path.to_owned(),+ schema: Box::new(schema.clone()),+ projection,+ projected_schema: Box::new(+ projected_schema.or(Some(schema.clone())).unwrap(),+ ),+ }))+ }+/// Scan a data sourcepub fn scan(schema_name: &str,@@ -851,6 +932,27 @@ mod tests {Ok(())}+ #[test]+ fn plan_builder_csv() -> Result<()> {+ let plan = LogicalPlanBuilder::scan_csv(+ "employee.csv",+ true,+ &employee_schema(),+ Some(vec![0, 3]),+ )?+ .filter(col("state").eq(&lit_str("CO")))?+ .project(vec![col("id")])?+ .build()?;++ let expected = "Projection: #id\+ \n Selection: #state Eq Utf8(\"CO\")\+ \n CsvScan: employee.csv projection=Some([0, 3])";++ assert_eq!(expected, format!("{:?}", plan));++ Ok(())+ }+#[test]fn plan_builder_aggregate() -> Result<()> {let plan = LogicalPlanBuilder::scan(diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 6781fcc057..fab371a9a2 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -102,51 +102,8 @@ impl ProjectionPushDown {projection,..} => {- if projection.is_some() {- return Err(ExecutionError::General(- "Cannot run projection push-down rule more than once".to_string(),- ));- }-- // once we reach the table scan, we can use the accumulated set of column- // indexes as the projection in the table scan- let mut projection: Vec<usize> = Vec::with_capacity(accum.len());- accum.iter().for_each(|i| projection.push(*i));-- // Ensure that we are reading at least one column from the table in case the query- // does not reference any columns directly such as "SELECT COUNT(1) FROM table"- if projection.is_empty() {- projection.push(0);- }-- // sort the projection otherwise we get non-deterministic behavior- projection.sort();-- // create the projected schema- let mut projected_fields: Vec<Field> =- Vec::with_capacity(projection.len());- for i in &projection {- projected_fields.push(table_schema.fields()[*i].clone());- }-- let projected_schema = Schema::new(projected_fields);-- // now that the table scan is returning a different schema we need to- // create a mapping from the original column index to the- // new column index so that we can rewrite expressions as- // we walk back up the tree-- if mapping.len() != 0 {- return Err(ExecutionError::InternalError(- "illegal state".to_string(),- ));- }-- for i in 0..table_schema.fields().len() {- if let Some(n) = projection.iter().position(|v| *v == i) {- mapping.insert(i, n);- }- }+ let (projection, projected_schema) =+ get_projected_schema(&table_schema, projection, accum, mapping)?;// return the table scan with projectionOk(LogicalPlan::TableScan {@@ -157,6 +114,40 @@ impl ProjectionPushDown {projection: Some(projection),})}+ LogicalPlan::CsvScan {+ path,+ has_header,+ schema,+ projection,+ ..+ } => {+ let (projection, projected_schema) =+ get_projected_schema(&schema, projection, accum, mapping)?;++ Ok(LogicalPlan::CsvScan {+ path: path.to_owned(),+ has_header: *has_header,+ schema: schema.clone(),+ projection: Some(projection),+ projected_schema: Box::new(projected_schema),+ })+ }+ LogicalPlan::ParquetScan {+ path,+ schema,+ projection,+ ..+ } => {+ let (projection, projected_schema) =+ get_projected_schema(&schema, projection, accum, mapping)?;++ Ok(LogicalPlan::ParquetScan {+ path: path.to_owned(),+ schema: schema.clone(),+ projection: Some(projection),+ projected_schema: Box::new(projected_schema),+ })+ }LogicalPlan::Limit { expr, input, .. } => {// Note that limit expressions are scalar values so there is no need to// rewrite them but we do need to optimize the input to the limit plan@@ -254,6 +245,56 @@ impl ProjectionPushDown {}}+fn get_projected_schema(+ table_schema: &Schema,+ projection: &Option<Vec<usize>>,+ accum: &HashSet<usize>,+ mapping: &mut HashMap<usize, usize>,+) -> Result<(Vec<usize>, Schema)> {+ if projection.is_some() {+ return Err(ExecutionError::General(+ "Cannot run projection push-down rule more than once".to_string(),+ ));+ }++ // once we reach the table scan, we can use the accumulated set of column+ // indexes as the projection in the table scan+ let mut projection: Vec<usize> = Vec::with_capacity(accum.len());+ accum.iter().for_each(|i| projection.push(*i));++ // Ensure that we are reading at least one column from the table in case the query+ // does not reference any columns directly such as "SELECT COUNT(1) FROM table"+ if projection.is_empty() {+ projection.push(0);+ }++ // sort the projection otherwise we get non-deterministic behavior+ projection.sort();++ // create the projected schema+ let mut projected_fields: Vec<Field> = Vec::with_capacity(projection.len());+ for i in &projection {+ projected_fields.push(table_schema.fields()[*i].clone());+ }++ // now that the table scan is returning a different schema we need to+ // create a mapping from the original column index to the+ // new column index so that we can rewrite expressions as+ // we walk back up the tree++ if mapping.len() != 0 {+ return Err(ExecutionError::InternalError("illegal state".to_string()));+ }++ for i in 0..table_schema.fields().len() {+ if let Some(n) = projection.iter().position(|v| *v == i) {+ mapping.insert(i, n);+ }+ }++ Ok((projection, Schema::new(projected_fields)))+}+#[cfg(test)]mod tests {