Apache DataFusion SQL Query Engine
ARROW-10680: [Rust] [DataFusion] Add partial support for TPC-H query 12
Andy Grovee5a8adfe628e
diff --git a/rust/benchmarks/Cargo.toml b/rust/benchmarks/Cargo.tomlindex 7d7b6c9734..762461ee80 100644--- a/rust/benchmarks/Cargo.toml+++ b/rust/benchmarks/Cargo.toml@@ -30,5 +30,5 @@ arrow = { path = "../arrow" }parquet = { path = "../parquet" }datafusion = { path = "../datafusion" }structopt = { version = "0.3", default-features = false }-tokio = { version = "0.2", features = ["macros", "rt-core", "rt-threaded"] }+tokio = { version = "0.3", features = ["macros", "rt", "rt-multi-thread"] }futures = "0.3"diff --git a/rust/benchmarks/src/bin/tpch.rs b/rust/benchmarks/src/bin/tpch.rsindex 1a71c933a3..337eb9b159 100644--- a/rust/benchmarks/src/bin/tpch.rs+++ b/rust/benchmarks/src/bin/tpch.rs@@ -18,7 +18,6 @@//! Benchmark derived from TPC-H. This is not an official TPC-H benchmark.use std::path::PathBuf;-use std::process;use std::sync::Arc;use std::time::Instant;@@ -27,8 +26,9 @@ use arrow::util::pretty;use datafusion::datasource::parquet::ParquetTable;use datafusion::datasource::{CsvFile, MemTable, TableProvider};use datafusion::error::{DataFusionError, Result};-use datafusion::execution::context::{ExecutionConfig, ExecutionContext};-use datafusion::physical_plan::csv::{CsvExec, CsvReadOptions};+use datafusion::logical_plan::LogicalPlan;+use datafusion::physical_plan::csv::CsvExec;+use datafusion::prelude::*;use structopt::StructOpt;@@ -89,6 +89,8 @@ enum TpchOpt {Convert(ConvertOpt),}+const TABLES: &[&str] = &["lineitem", "orders"];+#[tokio::main]async fn main() -> Result<()> {match TpchOpt::from_args() {@@ -104,84 +106,32 @@ async fn benchmark(opt: BenchmarkOpt) -> Result<()> {.with_batch_size(opt.batch_size);let mut ctx = ExecutionContext::with_config(config);- let path = opt.path.to_str().unwrap();-- let tableprovider: Box<dyn TableProvider + Send + Sync> =- match opt.file_format.as_str() {- // dbgen creates .tbl ('|' delimited) files- "tbl" => {- let path = format!("{}/lineitem.tbl", path);- let schema = lineitem_schema();- let options = CsvReadOptions::new()- .schema(&schema)- .delimiter(b'|')- .file_extension(".tbl");-- Box::new(CsvFile::try_new(&path, options)?)- }- "csv" => {- let path = format!("{}/lineitem", path);- let schema = lineitem_schema();- let options = CsvReadOptions::new().schema(&schema).has_header(true);-- Box::new(CsvFile::try_new(&path, options)?)- }- "parquet" => {- let path = format!("{}/lineitem", path);- Box::new(ParquetTable::try_new(&path)?)- }- other => {- println!("Invalid file format '{}'", other);- process::exit(-1);- }- };-- if opt.mem_table {- println!("Loading data into memory");- let start = Instant::now();-- let memtable = MemTable::load(tableprovider.as_ref(), opt.batch_size).await?;- println!(- "Loaded data into memory in {} ms",- start.elapsed().as_millis()- );-- ctx.register_table("lineitem", Box::new(memtable));- } else {- ctx.register_table("lineitem", tableprovider);- }-- let sql = match opt.query {- 1 => {- "select- l_returnflag,- l_linestatus,- sum(l_quantity),- sum(l_extendedprice),- sum(l_extendedprice * (1 - l_discount)),- sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)),- avg(l_quantity),- avg(l_extendedprice),- avg(l_discount),- count(*)- from- lineitem- where- l_shipdate <= '1998-12-01'- group by- l_returnflag,- l_linestatus- order by- l_returnflag,- l_linestatus"+ // register tables+ for table in TABLES {+ let table_provider =+ get_table(opt.path.to_str().unwrap(), table, opt.file_format.as_str())?;+ if opt.mem_table {+ println!("Loading table '{}' into memory", table);+ let start = Instant::now();++ let memtable =+ MemTable::load(table_provider.as_ref(), opt.batch_size).await?;+ println!(+ "Loaded table '{}' into memory in {} ms",+ table,+ start.elapsed().as_millis()+ );+ ctx.register_table(table, Box::new(memtable));+ } else {+ ctx.register_table(table, table_provider);}+ }- _ => unimplemented!("unsupported query"),- };-+ // run benchmarkfor i in 0..opt.iterations {let start = Instant::now();- execute_sql(&mut ctx, sql, opt.debug).await?;+ let plan = create_logical_plan(&mut ctx, opt.query)?;+ execute_query(&mut ctx, &plan, opt.debug).await?;println!("Query {} iteration {} took {} ms",opt.query,@@ -193,8 +143,105 @@ async fn benchmark(opt: BenchmarkOpt) -> Result<()> {Ok(())}-async fn execute_sql(ctx: &mut ExecutionContext, sql: &str, debug: bool) -> Result<()> {- let plan = ctx.create_logical_plan(sql)?;+fn create_logical_plan(ctx: &mut ExecutionContext, query: usize) -> Result<LogicalPlan> {+ match query {+ 1 => ctx.create_logical_plan(+ "select+ l_returnflag,+ l_linestatus,+ sum(l_quantity),+ sum(l_extendedprice),+ sum(l_extendedprice * (1 - l_discount)),+ sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)),+ avg(l_quantity),+ avg(l_extendedprice),+ avg(l_discount),+ count(*)+ from+ lineitem+ where+ l_shipdate <= '1998-12-01'+ group by+ l_returnflag,+ l_linestatus+ order by+ l_returnflag,+ l_linestatus",+ ),++ 12 => {+ // We do not have sufficient SQL support for this query yet++ // "SELECT+ // l_shipmode,+ // sum(case+ // when o_orderpriority = '1-URGENT'+ // OR o_orderpriority = '2-HIGH'+ // then 1+ // else 0+ // end) as high_line_count,+ // sum(case+ // when o_orderpriority <> '1-URGENT'+ // AND o_orderpriority <> '2-HIGH'+ // then 1+ // else 0+ // end) AS low_line_count+ // FROM+ // orders,+ // lineitem+ // WHERE+ // o_orderkey = l_orderkey+ // AND l_shipmode in ('MAIL', 'SHIP')+ // AND l_commitdate < l_receiptdate+ // AND l_shipdate < l_commitdate+ // AND l_receiptdate >= date '1994-01-01'+ // AND l_receiptdate < date '1994-01-01' + interval '1' year+ // GROUP BY+ // l_shipmode+ // ORDER BY+ // l_shipmode"++ Ok(ctx+ .table("lineitem")?+ .filter(+ col("l_shipmode")+ .eq(lit("MAIL"))+ .or(col("l_shipmode").eq(lit("SHIP"))),+ )?+ .filter(col("l_commitdate").lt(col("l_receiptdate")))?+ .filter(col("l_shipdate").lt(col("l_commitdate")))?+ .filter(col("l_receiptdate").gt_eq(lit("1994-01-01")))?+ // we do not support date functions yet, so faking the "+ interval '1' year" part+ .filter(col("l_receiptdate").lt(lit("1995-01-01")))?+ .join(+ ctx.table("orders")?,+ JoinType::Inner,+ &["l_orderkey"],+ &["o_orderkey"],+ )?+ .aggregate(+ vec![col("l_shipmode")],+ vec![+ // we do not support CASE WHEN yet, so faking this part+ sum(lit(1)).alias("high_line_count"),+ sum(lit(0)).alias("low_line_count"),+ ],+ )?+ .to_logical_plan())+ }++ _ => unimplemented!("unsupported query"),+ }+}++async fn execute_query(+ ctx: &mut ExecutionContext,+ plan: &LogicalPlan,+ debug: bool,+) -> Result<()> {+ if debug {+ println!("Logical plan:\n{:?}", plan);+ }let plan = ctx.optimize(&plan)?;if debug {println!("Optimized logical plan:\n{:?}", plan);@@ -208,49 +255,101 @@ async fn execute_sql(ctx: &mut ExecutionContext, sql: &str, debug: bool) -> Resu}async fn convert_tbl(opt: ConvertOpt) -> Result<()> {- let schema = lineitem_schema();+ for table in TABLES {+ let schema = get_schema(table);- let path = format!("{}/lineitem.tbl", opt.input_path.to_str().unwrap());- let options = CsvReadOptions::new()- .schema(&schema)- .delimiter(b'|')- .file_extension(".tbl");+ let path = format!("{}/{}.tbl", opt.input_path.to_str().unwrap(), table);+ let options = CsvReadOptions::new()+ .schema(&schema)+ .delimiter(b'|')+ .file_extension(".tbl");- let ctx = ExecutionContext::new();- let csv = Arc::new(CsvExec::try_new(&path, options, None, 4096)?);- let output_path = opt.output_path.to_str().unwrap().to_owned();+ let ctx = ExecutionContext::new();+ let csv = Arc::new(CsvExec::try_new(&path, options, None, 4096)?);+ let output_path = opt.output_path.to_str().unwrap().to_owned();- match opt.file_format.as_str() {- "csv" => ctx.write_csv(csv, output_path).await?,- "parquet" => ctx.write_parquet(csv, output_path).await?,- other => {- return Err(DataFusionError::NotImplemented(format!(- "Invalid output format: {}",- other- )))+ match opt.file_format.as_str() {+ "csv" => ctx.write_csv(csv, output_path).await?,+ "parquet" => ctx.write_parquet(csv, output_path).await?,+ other => {+ return Err(DataFusionError::NotImplemented(format!(+ "Invalid output format: {}",+ other+ )))+ }}}Ok(())}-fn lineitem_schema() -> Schema {- Schema::new(vec![- Field::new("l_orderkey", DataType::UInt32, true),- Field::new("l_partkey", DataType::UInt32, true),- Field::new("l_suppkey", DataType::UInt32, true),- Field::new("l_linenumber", DataType::UInt32, true),- Field::new("l_quantity", DataType::Float64, true),- Field::new("l_extendedprice", DataType::Float64, true),- Field::new("l_discount", DataType::Float64, true),- Field::new("l_tax", DataType::Float64, true),- Field::new("l_returnflag", DataType::Utf8, true),- Field::new("l_linestatus", DataType::Utf8, true),- Field::new("l_shipdate", DataType::Utf8, true),- Field::new("l_commitdate", DataType::Utf8, true),- Field::new("l_receiptdate", DataType::Utf8, true),- Field::new("l_shipinstruct", DataType::Utf8, true),- Field::new("l_shipmode", DataType::Utf8, true),- Field::new("l_comment", DataType::Utf8, true),- ])+fn get_table(+ path: &str,+ table: &str,+ table_format: &str,+) -> Result<Box<dyn TableProvider + Send + Sync>> {+ match table_format {+ // dbgen creates .tbl ('|' delimited) files+ "tbl" => {+ let path = format!("{}/{}.tbl", path, table);+ let schema = get_schema(table);+ let options = CsvReadOptions::new()+ .schema(&schema)+ .delimiter(b'|')+ .file_extension(".tbl");++ Ok(Box::new(CsvFile::try_new(&path, options)?))+ }+ "csv" => {+ let path = format!("{}/{}", path, table);+ let schema = get_schema(table);+ let options = CsvReadOptions::new().schema(&schema).has_header(true);++ Ok(Box::new(CsvFile::try_new(&path, options)?))+ }+ "parquet" => {+ let path = format!("{}/{}", path, table);+ Ok(Box::new(ParquetTable::try_new(&path)?))+ }+ other => {+ unimplemented!("Invalid file format '{}'", other);+ }+ }+}++fn get_schema(table: &str) -> Schema {+ match table {+ "lineitem" => Schema::new(vec![+ Field::new("l_orderkey", DataType::UInt32, true),+ Field::new("l_partkey", DataType::UInt32, true),+ Field::new("l_suppkey", DataType::UInt32, true),+ Field::new("l_linenumber", DataType::UInt32, true),+ Field::new("l_quantity", DataType::Float64, true),+ Field::new("l_extendedprice", DataType::Float64, true),+ Field::new("l_discount", DataType::Float64, true),+ Field::new("l_tax", DataType::Float64, true),+ Field::new("l_returnflag", DataType::Utf8, true),+ Field::new("l_linestatus", DataType::Utf8, true),+ Field::new("l_shipdate", DataType::Utf8, true),+ Field::new("l_commitdate", DataType::Utf8, true),+ Field::new("l_receiptdate", DataType::Utf8, true),+ Field::new("l_shipinstruct", DataType::Utf8, true),+ Field::new("l_shipmode", DataType::Utf8, true),+ Field::new("l_comment", DataType::Utf8, true),+ ]),++ "orders" => Schema::new(vec![+ Field::new("o_orderkey", DataType::UInt32, true),+ Field::new("custkey", DataType::UInt32, true),+ Field::new("o_orderstatus", DataType::Utf8, true),+ Field::new("o_totalprice", DataType::Float64, true),+ Field::new("o_orderdate", DataType::Utf8, true),+ Field::new("o_orderpriority", DataType::Utf8, true),+ Field::new("o_clerk", DataType::Utf8, true),+ Field::new("o_shippriority", DataType::Utf8, true),+ Field::new("o_comment", DataType::Utf8, true),+ ]),++ _ => unimplemented!(),+ }}diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 4c99ab5b72..aabdbda829 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -158,6 +158,37 @@ fn optimize_plan(})}}+ LogicalPlan::Join {+ left,+ right,+ on,+ join_type,+ schema,+ } => {+ let mut new_required_columns = HashSet::new();+ for (l, r) in on {+ new_required_columns.insert(l.to_owned());+ new_required_columns.insert(r.to_owned());+ }+ Ok(LogicalPlan::Join {+ left: Arc::new(optimize_plan(+ optimizer,+ &left,+ &new_required_columns,+ true,+ )?),+ right: Arc::new(optimize_plan(+ optimizer,+ &right,+ &new_required_columns,+ true,+ )?),++ join_type: join_type.clone(),+ on: on.clone(),+ schema: schema.clone(),+ })+ }LogicalPlan::Aggregate {schema,input,@@ -312,7 +343,6 @@ fn optimize_plan(| LogicalPlan::Filter { .. }| LogicalPlan::EmptyRelation { .. }| LogicalPlan::Sort { .. }- | LogicalPlan::Join { .. }| LogicalPlan::CreateExternalTable { .. }| LogicalPlan::Extension { .. } => {let expr = utils::expressions(plan);diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex 7b19856cea..43222c9881 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -24,6 +24,7 @@ use arrow::datatypes::{Schema, SchemaRef};use super::optimizer::OptimizerRule;use crate::error::{DataFusionError, Result};use crate::logical_plan::{Expr, LogicalPlan, PlanType, StringifiedPlan};+use crate::prelude::col;/// Recursively walk a list of expression trees, collecting the unique set of column/// names referenced in the expression@@ -118,6 +119,9 @@ pub fn expressions(plan: &LogicalPlan) -> Vec<Expr> {result.extend(aggr_expr.clone());result}+ LogicalPlan::Join { on, .. } => {+ on.iter().flat_map(|(l, r)| vec![col(l), col(r)]).collect()+ }LogicalPlan::Sort { expr, .. } => expr.clone(),LogicalPlan::Extension { node } => node.expressions(),// plans without expressions@@ -127,7 +131,6 @@ pub fn expressions(plan: &LogicalPlan) -> Vec<Expr> {| LogicalPlan::CsvScan { .. }| LogicalPlan::EmptyRelation { .. }| LogicalPlan::Limit { .. }- | LogicalPlan::Join { .. }| LogicalPlan::CreateExternalTable { .. }| LogicalPlan::Explain { .. } => vec![],}diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex 90dc2da942..036da6624e 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -295,20 +295,19 @@ impl DefaultPhysicalPlanner {right,on: keys,join_type,- schema,+ ..} => {let left = self.create_physical_plan(left, ctx_state)?;let right = self.create_physical_plan(right, ctx_state)?;let physical_join_type = match join_type {JoinType::Inner => hash_utils::JoinType::Inner,};- let hash_join =- HashJoinExec::try_new(left, right, &keys, &physical_join_type)?;- if schema.as_ref() == hash_join.schema().as_ref() {- Ok(Arc::new(hash_join))- } else {- Err(DataFusionError::Plan("schema mismatch".to_string()))- }+ Ok(Arc::new(HashJoinExec::try_new(+ left,+ right,+ &keys,+ &physical_join_type,+ )?))}LogicalPlan::EmptyRelation {produce_one_row,