Apache DataFusion SQL Query Engine
ARROW-8839: [Rust] [DataFusion] support CSV schema inference in logical plan
Qingping Houe6cb29f3598d
diff --git a/rust/datafusion/benches/aggregate_query_sql.rs b/rust/datafusion/benches/aggregate_query_sql.rsindex e3b3d56b6e..88b534b0a3 100644--- a/rust/datafusion/benches/aggregate_query_sql.rs+++ b/rust/datafusion/benches/aggregate_query_sql.rs@@ -63,6 +63,7 @@ fn create_context() -> ExecutionContext {&format!("{}/csv/aggregate_test_100.csv", testdata),&schema,true,+ None,);let mem_table = MemTable::load(&csv).unwrap();diff --git a/rust/datafusion/examples/csv_sql.rs b/rust/datafusion/examples/csv_sql.rsindex 17106d2414..dc538bf94f 100644--- a/rust/datafusion/examples/csv_sql.rs+++ b/rust/datafusion/examples/csv_sql.rs@@ -52,6 +52,7 @@ fn main() -> Result<()> {&format!("{}/csv/aggregate_test_100.csv", testdata),&schema,true,+ None,);let sql = "SELECT c1, MIN(c12), MAX(c12) FROM aggregate_test_100 WHERE c11 > 0.1 AND c11 < 0.9 GROUP BY c1";diff --git a/rust/datafusion/src/datasource/csv.rs b/rust/datafusion/src/datasource/csv.rsindex fb3014e737..a6a957d031 100644--- a/rust/datafusion/src/datasource/csv.rs+++ b/rust/datafusion/src/datasource/csv.rs@@ -36,17 +36,54 @@ pub struct CsvFile {filename: String,schema: Arc<Schema>,has_header: bool,+ delimiter: Option<u8>,}impl CsvFile {#[allow(missing_docs)]- pub fn new(filename: &str, schema: &Schema, has_header: bool) -> Self {+ pub fn new(+ filename: &str,+ schema: &Schema,+ has_header: bool,+ delimiter: Option<u8>,+ ) -> Self {Self {filename: String::from(filename),schema: Arc::new(schema.clone()),has_header,+ delimiter,}}++ /// Attempt to initialize a new `CsvFile` from a file path+ pub fn try_new(+ filename: &str,+ schema: Option<&Schema>,+ has_header: bool,+ delimiter: Option<u8>,+ ) -> Result<Self> {+ let schema = match schema {+ Some(s) => Arc::new(s.clone()),+ None => {+ let schema_infer_batch_size = 1024;+ let csv_exec = CsvExec::try_new(+ filename,+ None,+ has_header,+ delimiter,+ None,+ schema_infer_batch_size,+ )?;+ csv_exec.schema()+ }+ };+ Ok(Self {+ filename: String::from(filename),+ schema: schema,+ has_header,+ delimiter,+ })+ }}impl TableProvider for CsvFile {@@ -61,8 +98,9 @@ impl TableProvider for CsvFile {) -> Result<Vec<ScanResult>> {let exec = CsvExec::try_new(&self.filename,- self.schema.clone(),+ Some(self.schema.clone()),self.has_header,+ self.delimiter,projection.clone(),batch_size,)?;@@ -88,6 +126,7 @@ impl CsvBatchIterator {filename: &str,schema: Arc<Schema>,has_header: bool,+ delimiter: Option<u8>,projection: &Option<Vec<usize>>,batch_size: usize,) -> Result<Self> {@@ -96,6 +135,7 @@ impl CsvBatchIterator {file,schema.clone(),has_header,+ delimiter,batch_size,projection.clone(),);diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 9b8d068e58..d804ae4e2a 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -100,7 +100,7 @@ impl ExecutionContext {ref header_row,} => match file_type {FileType::CSV => {- self.register_csv(name, location, schema, *header_row);+ self.register_csv(name, location, schema, *header_row, None);Ok(vec![])}FileType::Parquet => {@@ -216,8 +216,12 @@ impl ExecutionContext {filename: &str,schema: &Schema,has_header: bool,+ delimiter: Option<u8>,) {- self.register_table(name, Box::new(CsvFile::new(filename, schema, has_header)));+ self.register_table(+ name,+ Box::new(CsvFile::new(filename, schema, has_header, delimiter)),+ );}/// Register a Parquet file as a table so that it can be queried from SQL@@ -314,12 +318,14 @@ impl ExecutionContext {path,schema,has_header,+ delimiter,projection,..} => Ok(Arc::new(CsvExec::try_new(path,- Arc::new(schema.as_ref().to_owned()),+ Some(Arc::new(schema.as_ref().to_owned())),*has_header,+ *delimiter,projection.to_owned(),batch_size,)?)),@@ -864,11 +870,35 @@ mod tests {]));// register each partition as well as the top level dir- ctx.register_csv("part0", &format!("{}/part-0.csv", out_dir), &schema, true);- ctx.register_csv("part1", &format!("{}/part-1.csv", out_dir), &schema, true);- ctx.register_csv("part2", &format!("{}/part-2.csv", out_dir), &schema, true);- ctx.register_csv("part3", &format!("{}/part-3.csv", out_dir), &schema, true);- ctx.register_csv("allparts", &out_dir, &schema, true);+ ctx.register_csv(+ "part0",+ &format!("{}/part-0.csv", out_dir),+ &schema,+ true,+ None,+ );+ ctx.register_csv(+ "part1",+ &format!("{}/part-1.csv", out_dir),+ &schema,+ true,+ None,+ );+ ctx.register_csv(+ "part2",+ &format!("{}/part-2.csv", out_dir),+ &schema,+ true,+ None,+ );+ ctx.register_csv(+ "part3",+ &format!("{}/part-3.csv", out_dir),+ &schema,+ true,+ None,+ );+ ctx.register_csv("allparts", &out_dir, &schema, true, None);let part0 = collect(&mut ctx, "SELECT c1, c2 FROM part0")?;let part1 = collect(&mut ctx, "SELECT c1, c2 FROM part1")?;@@ -1031,7 +1061,13 @@ mod tests {}// register csv file with the execution context- ctx.register_csv("test", tmp_dir.path().to_str().unwrap(), &schema, true);+ ctx.register_csv(+ "test",+ tmp_dir.path().to_str().unwrap(),+ &schema,+ true,+ None,+ );Ok(ctx)}diff --git a/rust/datafusion/src/execution/physical_plan/csv.rs b/rust/datafusion/src/execution/physical_plan/csv.rsindex a07417cf22..14df0d5c67 100644--- a/rust/datafusion/src/execution/physical_plan/csv.rs+++ b/rust/datafusion/src/execution/physical_plan/csv.rs@@ -18,9 +18,10 @@//! Execution plan for reading CSV filesuse std::fs::File;+use std::io::BufReader;use std::sync::{Arc, Mutex};-use crate::error::Result;+use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::common;use crate::execution::physical_plan::{BatchIterator, ExecutionPlan, Partition};use arrow::csv;@@ -35,6 +36,8 @@ pub struct CsvExec {schema: Arc<Schema>,/// Does the CSV file have a header?has_header: bool,+ /// An optional column delimiter. Defaults to `b','`+ delimiter: Option<u8>,/// Optional projection for which columns to loadprojection: Option<Vec<usize>>,/// Batch size@@ -58,6 +61,7 @@ impl ExecutionPlan for CsvExec {&filename,self.schema.clone(),self.has_header,+ self.delimiter,self.projection.clone(),self.batch_size,)) as Arc<dyn Partition>@@ -71,15 +75,35 @@ impl CsvExec {/// Create a new execution plan for reading a set of CSV filespub fn try_new(path: &str,- schema: Arc<Schema>,+ schema: Option<Arc<Schema>>,has_header: bool,+ delimiter: Option<u8>,projection: Option<Vec<usize>>,batch_size: usize,) -> Result<Self> {+ let schema = match schema {+ Some(s) => s,+ None => {+ let mut filenames: Vec<String> = vec![];+ common::build_file_list(path, &mut filenames, ".csv")?;+ if filenames.is_empty() {+ return Err(ExecutionError::General("No files found".to_string()));+ }++ let f = File::open(&filenames[0])?;+ Arc::new(csv::infer_file_schema(+ &mut BufReader::new(f),+ delimiter.unwrap_or(b','),+ Some(1000),+ has_header,+ )?)+ }+ };Ok(Self {path: path.to_string(),schema,has_header,+ delimiter,projection,batch_size,})@@ -94,6 +118,8 @@ struct CsvPartition {schema: Arc<Schema>,/// Does the CSV file have a header?has_header: bool,+ /// An optional column delimiter. Defaults to `b','`+ delimiter: Option<u8>,/// Optional projection for which columns to loadprojection: Option<Vec<usize>>,/// Batch size@@ -105,6 +131,7 @@ impl CsvPartition {path: &str,schema: Arc<Schema>,has_header: bool,+ delimiter: Option<u8>,projection: Option<Vec<usize>>,batch_size: usize,) -> Self {@@ -112,6 +139,7 @@ impl CsvPartition {path: path.to_string(),schema,has_header,+ delimiter,projection,batch_size,}@@ -125,6 +153,7 @@ impl Partition for CsvPartition {&self.path,self.schema.clone(),self.has_header,+ self.delimiter,&self.projection,self.batch_size,)?)))@@ -143,6 +172,7 @@ impl CsvIterator {filename: &str,schema: Arc<Schema>,has_header: bool,+ delimiter: Option<u8>,projection: &Option<Vec<usize>>,batch_size: usize,) -> Result<Self> {@@ -151,6 +181,7 @@ impl CsvIterator {file,schema.clone(),has_header,+ delimiter,batch_size,projection.clone(),);diff --git a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rsindex 0d1a376c37..83ffa73f0a 100644--- a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs+++ b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs@@ -736,7 +736,7 @@ mod tests {let partitions = 4;let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;- let csv = CsvExec::try_new(&path, schema.clone(), true, None, 1024)?;+ let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;let group_expr: Vec<Arc<dyn PhysicalExpr>> = vec![col(1, schema.as_ref())];diff --git a/rust/datafusion/src/execution/physical_plan/limit.rs b/rust/datafusion/src/execution/physical_plan/limit.rsindex bdc42df5dc..4aa25f84e9 100644--- a/rust/datafusion/src/execution/physical_plan/limit.rs+++ b/rust/datafusion/src/execution/physical_plan/limit.rs@@ -183,7 +183,7 @@ mod tests {let path =test::create_partitioned_csv("aggregate_test_100.csv", num_partitions)?;- let csv = CsvExec::try_new(&path, schema.clone(), true, None, 1024)?;+ let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;// input should have 4 partitionslet input = csv.partitions()?;diff --git a/rust/datafusion/src/execution/physical_plan/merge.rs b/rust/datafusion/src/execution/physical_plan/merge.rsindex 0ef8a39e8e..18283a9e36 100644--- a/rust/datafusion/src/execution/physical_plan/merge.rs+++ b/rust/datafusion/src/execution/physical_plan/merge.rs@@ -111,7 +111,7 @@ mod tests {let path =test::create_partitioned_csv("aggregate_test_100.csv", num_partitions)?;- let csv = CsvExec::try_new(&path, schema.clone(), true, None, 1024)?;+ let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;// input should have 4 partitionslet input = csv.partitions()?;diff --git a/rust/datafusion/src/execution/physical_plan/projection.rs b/rust/datafusion/src/execution/physical_plan/projection.rsindex 3ae8ba0ffb..d90050c03b 100644--- a/rust/datafusion/src/execution/physical_plan/projection.rs+++ b/rust/datafusion/src/execution/physical_plan/projection.rs@@ -150,7 +150,7 @@ mod tests {let partitions = 4;let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;- let csv = CsvExec::try_new(&path, schema.clone(), true, None, 1024)?;+ let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;let projection = ProjectionExec::try_new(vec![Arc::new(Column::new(0, &schema.as_ref().field(0).name()))],diff --git a/rust/datafusion/src/execution/physical_plan/selection.rs b/rust/datafusion/src/execution/physical_plan/selection.rsindex ea74a89147..e8956e7e39 100644--- a/rust/datafusion/src/execution/physical_plan/selection.rs+++ b/rust/datafusion/src/execution/physical_plan/selection.rs@@ -159,7 +159,7 @@ mod tests {let partitions = 4;let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;- let csv = CsvExec::try_new(&path, schema.clone(), true, None, 1024)?;+ let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;let predicate: Arc<dyn PhysicalExpr> = binary(binary(diff --git a/rust/datafusion/src/execution/table_impl.rs b/rust/datafusion/src/execution/table_impl.rsindex 10d65a43b5..de3bcb6a9c 100644--- a/rust/datafusion/src/execution/table_impl.rs+++ b/rust/datafusion/src/execution/table_impl.rs@@ -267,6 +267,7 @@ mod tests {&format!("{}/csv/aggregate_test_100.csv", testdata),&schema,true,+ None,);}}diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rsindex fddd60dbd2..ecae04ebdf 100644--- a/rust/datafusion/src/logicalplan.rs+++ b/rust/datafusion/src/logicalplan.rs@@ -25,6 +25,7 @@ use std::fmt;use arrow::datatypes::{DataType, Field, Schema};+use crate::datasource::csv::CsvFile;use crate::datasource::parquet::ParquetTable;use crate::datasource::TableProvider;use crate::error::{ExecutionError, Result};@@ -560,6 +561,8 @@ pub enum LogicalPlan {schema: Box<Schema>,/// Whether the CSV file(s) have a header containing column nameshas_header: bool,+ /// An optional column delimiter. Defaults to `b','`+ delimiter: Option<u8>,/// Optional column indices to use as a projectionprojection: Option<Vec<usize>>,/// The projected schema@@ -794,16 +797,27 @@ impl LogicalPlanBuilder {pub fn scan_csv(path: &str,has_header: bool,- schema: &Schema,+ schema: Option<&Schema>,+ delimiter: Option<u8>,projection: Option<Vec<usize>>,) -> Result<Self> {+ let schema: Schema = match schema {+ Some(s) => s.to_owned(),+ None => CsvFile::try_new(path, None, has_header, delimiter)?+ .schema()+ .as_ref()+ .to_owned(),+ };+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,+ delimiter,projection,projected_schema: Box::new(projected_schema.or(Some(schema.clone())).unwrap(),@@ -815,7 +829,6 @@ impl LogicalPlanBuilder {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()));@@ -957,7 +970,8 @@ mod tests {let plan = LogicalPlanBuilder::scan_csv("employee.csv",true,- &employee_schema(),+ Some(&employee_schema()),+ None,Some(vec![0, 3]),)?.filter(col("state").eq(&lit_str("CO")))?diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 8f614fc697..ea47215f11 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -133,6 +133,7 @@ impl ProjectionPushDown {LogicalPlan::CsvScan {path,has_header,+ delimiter,schema,projection,..@@ -144,6 +145,7 @@ impl ProjectionPushDown {path: path.to_owned(),has_header: *has_header,schema: schema.clone(),+ delimiter: *delimiter,projection: Some(projection),projected_schema: Box::new(projected_schema),})diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex 08aa656968..a4bf16e003 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -56,7 +56,7 @@ fn nyc() -> Result<()> {]);let mut ctx = ExecutionContext::new();- ctx.register_csv("tripdata", "file.csv", &schema, true);+ ctx.register_csv("tripdata", "file.csv", &schema, true, None);let logical_plan = ctx.create_logical_plan("SELECT passenger_count, MIN(fare_amount), MAX(fare_amount) \@@ -442,7 +442,7 @@ fn register_csv(filename: &str,schema: &Arc<Schema>,) {- ctx.register_csv(name, filename, &schema, true);+ ctx.register_csv(name, filename, &schema, true, None);}fn register_alltypes_parquet(ctx: &mut ExecutionContext) {