Apache DataFusion SQL Query Engine
ARROW-8877: [Rust] [DataFusion] introduce CsvReadOption struct to simplify UX
Qingping Houc535a985b760
diff --git a/rust/datafusion/benches/aggregate_query_sql.rs b/rust/datafusion/benches/aggregate_query_sql.rsindex 88b534b0a3..ab374a0c64 100644--- a/rust/datafusion/benches/aggregate_query_sql.rs+++ b/rust/datafusion/benches/aggregate_query_sql.rs@@ -27,7 +27,7 @@ extern crate datafusion;use arrow::datatypes::{DataType, Field, Schema};-use datafusion::datasource::{CsvFile, MemTable};+use datafusion::datasource::{CsvFile, CsvReadOptions, MemTable};use datafusion::execution::context::ExecutionContext;fn aggregate_query(ctx: &mut ExecutionContext, sql: &str) {@@ -59,12 +59,11 @@ fn create_context() -> ExecutionContext {let testdata = env::var("ARROW_TEST_DATA").expect("ARROW_TEST_DATA not defined");// create CSV data source- let csv = CsvFile::new(+ let csv = CsvFile::try_new(&format!("{}/csv/aggregate_test_100.csv", testdata),- &schema,- true,- None,- );+ CsvReadOptions::new().schema(&schema),+ )+ .unwrap();let mem_table = MemTable::load(&csv).unwrap();diff --git a/rust/datafusion/examples/csv_sql.rs b/rust/datafusion/examples/csv_sql.rsindex dc538bf94f..7300bc862f 100644--- a/rust/datafusion/examples/csv_sql.rs+++ b/rust/datafusion/examples/csv_sql.rs@@ -15,9 +15,9 @@// specific language governing permissions and limitations// under the License.-use arrow::datatypes::{DataType, Field, Schema};use arrow::util::pretty;+use datafusion::datasource::csv::CsvReadOptions;use datafusion::error::Result;use datafusion::execution::context::ExecutionContext;@@ -27,38 +27,19 @@ fn main() -> Result<()> {// create local execution contextlet mut ctx = ExecutionContext::new();- // define schema for data source (csv file)- let schema = Schema::new(vec![- Field::new("c1", DataType::Utf8, false),- Field::new("c2", DataType::UInt32, false),- Field::new("c3", DataType::Int8, false),- Field::new("c4", DataType::Int16, false),- Field::new("c5", DataType::Int32, false),- Field::new("c6", DataType::Int64, false),- Field::new("c7", DataType::UInt8, false),- Field::new("c8", DataType::UInt16, false),- Field::new("c9", DataType::UInt32, false),- Field::new("c10", DataType::UInt64, false),- Field::new("c11", DataType::Float32, false),- Field::new("c12", DataType::Float64, false),- Field::new("c13", DataType::Utf8, false),- ]);-let testdata = std::env::var("ARROW_TEST_DATA").expect("ARROW_TEST_DATA not defined");// register csv file with the execution contextctx.register_csv("aggregate_test_100",&format!("{}/csv/aggregate_test_100.csv", testdata),- &schema,- true,- None,- );+ CsvReadOptions::new(),+ )?;let sql = "SELECT c1, MIN(c12), MAX(c12) FROM aggregate_test_100 WHERE c11 > 0.1 AND c11 < 0.9 GROUP BY c1";// create the query plan- let plan = ctx.create_logical_plan(&sql)?;+ let plan = ctx.create_logical_plan(sql)?;let plan = ctx.optimize(&plan)?;let plan = ctx.create_physical_plan(&plan, 1024 * 1024)?;diff --git a/rust/datafusion/src/datasource/csv.rs b/rust/datafusion/src/datasource/csv.rsindex a6a957d031..0835579d31 100644--- a/rust/datafusion/src/datasource/csv.rs+++ b/rust/datafusion/src/datasource/csv.rs@@ -15,7 +15,23 @@// specific language governing permissions and limitations// under the License.-//! CSV Data source+//! CSV data source+//!+//! This CSV data source allows CSV files to be used as input for queries.+//!+//! Example:+//!+//! ```+//! use datafusion::datasource::TableProvider;+//! use datafusion::datasource::csv::{CsvFile, CsvReadOptions};+//!+//! let testdata = std::env::var("ARROW_TEST_DATA").expect("ARROW_TEST_DATA not defined");+//! let csvdata = CsvFile::try_new(+//! &format!("{}/csv/aggregate_test_100.csv", testdata),+//! CsvReadOptions::new().delimiter(b'|'),+//! ).unwrap();+//! let schema = csvdata.schema();+//! ```use std::fs::File;@@ -28,60 +44,30 @@ use std::sync::Arc;use crate::datasource::{ScanResult, TableProvider};use crate::error::Result;use crate::execution::physical_plan::csv::CsvExec;+pub use crate::execution::physical_plan::csv::CsvReadOptions;use crate::execution::physical_plan::{BatchIterator, ExecutionPlan};/// Represents a CSV file with a provided schema-// TODO: usage example (rather than documenting `new()`)pub struct CsvFile {filename: String,schema: Arc<Schema>,has_header: bool,- delimiter: Option<u8>,+ delimiter: u8,}impl CsvFile {- #[allow(missing_docs)]- 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()- }- };+ pub fn try_new(filename: &str, options: CsvReadOptions) -> Result<Self> {+ let schema = Arc::new(match options.schema {+ Some(s) => s.clone(),+ None => CsvExec::try_infer_schema(filename, &options)?,+ });+Ok(Self {filename: String::from(filename),- schema: schema,- has_header,- delimiter,+ schema,+ has_header: options.has_header,+ delimiter: options.delimiter,})}}@@ -98,9 +84,10 @@ impl TableProvider for CsvFile {) -> Result<Vec<ScanResult>> {let exec = CsvExec::try_new(&self.filename,- Some(self.schema.clone()),- self.has_header,- self.delimiter,+ CsvReadOptions::new()+ .schema(&self.schema)+ .has_header(self.has_header)+ .delimiter(self.delimiter),projection.clone(),batch_size,)?;diff --git a/rust/datafusion/src/datasource/mod.rs b/rust/datafusion/src/datasource/mod.rsindex 075c81c58a..7ecc4a18d6 100644--- a/rust/datafusion/src/datasource/mod.rs+++ b/rust/datafusion/src/datasource/mod.rs@@ -22,6 +22,6 @@ pub mod datasource;pub mod memory;pub mod parquet;-pub use self::csv::{CsvBatchIterator, CsvFile};+pub use self::csv::{CsvBatchIterator, CsvFile, CsvReadOptions};pub use self::datasource::{ScanResult, TableProvider};pub use self::memory::MemTable;diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex d804ae4e2a..9952f8cae2 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -33,7 +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::csv::{CsvExec, CsvReadOptions};use crate::execution::physical_plan::datasource::DatasourceExec;use crate::execution::physical_plan::expressions::{Alias, Avg, BinaryExpr, CastExpr, Column, Count, Literal, Max, Min, Sum,@@ -97,10 +97,16 @@ impl ExecutionContext {ref name,ref location,ref file_type,- ref header_row,+ ref has_header,} => match file_type {FileType::CSV => {- self.register_csv(name, location, schema, *header_row, None);+ self.register_csv(+ name,+ location,+ CsvReadOptions::new()+ .schema(&schema)+ .has_header(*has_header),+ )?;Ok(vec![])}FileType::Parquet => {@@ -144,7 +150,7 @@ impl ExecutionContext {name,columns,file_type,- header_row,+ has_header,location,} => {let schema = Box::new(self.build_schema(columns)?);@@ -154,7 +160,7 @@ impl ExecutionContext {name,location,file_type,- header_row,+ has_header,})}}@@ -214,14 +220,10 @@ impl ExecutionContext {&mut self,name: &str,filename: &str,- schema: &Schema,- has_header: bool,- delimiter: Option<u8>,- ) {- self.register_table(- name,- Box::new(CsvFile::new(filename, schema, has_header, delimiter)),- );+ options: CsvReadOptions,+ ) -> Result<()> {+ self.register_table(name, Box::new(CsvFile::try_new(filename, options)?));+ Ok(())}/// Register a Parquet file as a table so that it can be queried from SQL@@ -323,9 +325,10 @@ impl ExecutionContext {..} => Ok(Arc::new(CsvExec::try_new(path,- Some(Arc::new(schema.as_ref().to_owned())),- *has_header,- *delimiter,+ CsvReadOptions::new()+ .schema(schema.as_ref())+ .delimiter_option(*delimiter)+ .has_header(*has_header),projection.to_owned(),batch_size,)?)),@@ -870,35 +873,12 @@ mod tests {]));// register each partition as well as the top level dir- 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 csv_read_option = CsvReadOptions::new().schema(&schema);+ ctx.register_csv("part0", &format!("{}/part-0.csv", out_dir), csv_read_option)?;+ ctx.register_csv("part1", &format!("{}/part-1.csv", out_dir), csv_read_option)?;+ ctx.register_csv("part2", &format!("{}/part-2.csv", out_dir), csv_read_option)?;+ ctx.register_csv("part3", &format!("{}/part-3.csv", out_dir), csv_read_option)?;+ ctx.register_csv("allparts", &out_dir, csv_read_option)?;let part0 = collect(&mut ctx, "SELECT c1, c2 FROM part0")?;let part1 = collect(&mut ctx, "SELECT c1, c2 FROM part1")?;@@ -1064,10 +1044,8 @@ mod tests {ctx.register_csv("test",tmp_dir.path().to_str().unwrap(),- &schema,- true,- None,- );+ CsvReadOptions::new().schema(&schema),+ )?;Ok(ctx)}diff --git a/rust/datafusion/src/execution/physical_plan/csv.rs b/rust/datafusion/src/execution/physical_plan/csv.rsindex 14df0d5c67..2d4a0fc5e4 100644--- a/rust/datafusion/src/execution/physical_plan/csv.rs+++ b/rust/datafusion/src/execution/physical_plan/csv.rs@@ -28,6 +28,70 @@ use arrow::csv;use arrow::datatypes::Schema;use arrow::record_batch::RecordBatch;+/// CSV file read option+#[derive(Copy, Clone)]+pub struct CsvReadOptions<'a> {+ /// Does the CSV file have a header?+ ///+ /// If schema inference is run on a file with no headers, default column names+ /// are created.+ pub has_header: bool,+ /// An optional column delimiter. Defaults to `b','`.+ pub delimiter: u8,+ /// An optional schema representing the CSV files. If None, CSV reader will try to infer it+ /// based on data in file.+ pub schema: Option<&'a Schema>,+ /// Max number of rows to read from CSV files for schema inference if needed. Defaults to 1000.+ pub schema_infer_max_records: usize,+}++impl<'a> CsvReadOptions<'a> {+ /// Create a CSV read option with default presets+ pub fn new() -> Self {+ Self {+ has_header: true,+ schema: None,+ schema_infer_max_records: 1000,+ delimiter: b',',+ }+ }++ /// Configure has_header setting+ pub fn has_header(mut self, has_header: bool) -> Self {+ self.has_header = has_header;+ self+ }++ /// Specify delimiter to use for CSV read+ pub fn delimiter(mut self, delimiter: u8) -> Self {+ self.delimiter = delimiter;+ self+ }++ /// Configure delimiter setting with Option, None value will be ignored+ pub fn delimiter_option(mut self, delimiter: Option<u8>) -> Self {+ match delimiter {+ Some(d) => {+ self.delimiter = d;+ }+ _ => (),+ }+ self+ }++ /// Specify schema to use for CSV read+ pub fn schema(mut self, schema: &'a Schema) -> Self {+ self.schema = Some(schema);+ self+ }++ /// Configure number of max records to read for schema inference+ pub fn schema_infer_max_records(mut self, max_records: usize) -> Self {+ self.schema_infer_max_records = max_records;+ self+ }+}+/// Execution plan for scanning a CSV filepub struct CsvExec {/// Path to directory containing partitioned CSV files with the same schema@@ -44,6 +108,48 @@ pub struct CsvExec {batch_size: usize,}+impl CsvExec {+ /// Create a new execution plan for reading a set of CSV files+ pub fn try_new(+ path: &str,+ options: CsvReadOptions,+ projection: Option<Vec<usize>>,+ batch_size: usize,+ ) -> Result<Self> {+ let schema = Arc::new(match options.schema {+ Some(s) => s.clone(),+ None => CsvExec::try_infer_schema(path, &options)?,+ });++ Ok(Self {+ path: path.to_string(),+ schema: schema,+ has_header: options.has_header,+ delimiter: Some(options.delimiter),+ projection,+ batch_size,+ })+ }++ /// Infer schema for given CSV dataset+ pub fn try_infer_schema(path: &str, options: &CsvReadOptions) -> Result<Schema> {+ 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])?;++ Ok(csv::infer_file_schema(+ &mut BufReader::new(f),+ options.delimiter,+ Some(options.schema_infer_max_records),+ options.has_header,+ )?)+ }+}+impl ExecutionPlan for CsvExec {/// Get the schema for this execution planfn schema(&self) -> Arc<Schema> {@@ -71,45 +177,6 @@ impl ExecutionPlan for CsvExec {}}-impl CsvExec {- /// Create a new execution plan for reading a set of CSV files- pub fn try_new(- path: &str,- 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,- })- }-}-/// CSV Partitionstruct CsvPartition {/// Path to the CSV Filediff --git a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rsindex 83ffa73f0a..ef14b0e178 100644--- a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs+++ b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs@@ -724,7 +724,7 @@ fn create_key(mod tests {use super::*;- use crate::execution::physical_plan::csv::CsvExec;+ use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::execution::physical_plan::expressions::{col, sum};use crate::execution::physical_plan::merge::MergeExec;use crate::test;@@ -736,7 +736,8 @@ mod tests {let partitions = 4;let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;- let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;+ let csv =+ CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), 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 4aa25f84e9..93dba721ab 100644--- a/rust/datafusion/src/execution/physical_plan/limit.rs+++ b/rust/datafusion/src/execution/physical_plan/limit.rs@@ -172,7 +172,7 @@ mod tests {use super::*;use crate::execution::physical_plan::common;- use crate::execution::physical_plan::csv::CsvExec;+ use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::test;#[test]@@ -183,7 +183,8 @@ mod tests {let path =test::create_partitioned_csv("aggregate_test_100.csv", num_partitions)?;- let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;+ let csv =+ CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), 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 18283a9e36..ea7921bb5f 100644--- a/rust/datafusion/src/execution/physical_plan/merge.rs+++ b/rust/datafusion/src/execution/physical_plan/merge.rs@@ -100,7 +100,7 @@ mod tests {use super::*;use crate::execution::physical_plan::common;- use crate::execution::physical_plan::csv::CsvExec;+ use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::test;#[test]@@ -111,7 +111,8 @@ mod tests {let path =test::create_partitioned_csv("aggregate_test_100.csv", num_partitions)?;- let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;+ let csv =+ CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), 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 d90050c03b..9c8e5170de 100644--- a/rust/datafusion/src/execution/physical_plan/projection.rs+++ b/rust/datafusion/src/execution/physical_plan/projection.rs@@ -139,7 +139,7 @@ impl BatchIterator for ProjectionIterator {mod tests {use super::*;- use crate::execution::physical_plan::csv::CsvExec;+ use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::execution::physical_plan::expressions::Column;use crate::test;@@ -150,7 +150,8 @@ mod tests {let partitions = 4;let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;- let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;+ let csv =+ CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), 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 e8956e7e39..5998aa4320 100644--- a/rust/datafusion/src/execution/physical_plan/selection.rs+++ b/rust/datafusion/src/execution/physical_plan/selection.rs@@ -145,7 +145,7 @@ impl BatchIterator for SelectionIterator {mod tests {use super::*;- use crate::execution::physical_plan::csv::CsvExec;+ use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::execution::physical_plan::expressions::*;use crate::execution::physical_plan::ExecutionPlan;use crate::logicalplan::{Operator, ScalarValue};@@ -159,7 +159,8 @@ mod tests {let partitions = 4;let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;- let csv = CsvExec::try_new(&path, Some(schema.clone()), true, None, None, 1024)?;+ let csv =+ CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), 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 de3bcb6a9c..c1dbb77407 100644--- a/rust/datafusion/src/execution/table_impl.rs+++ b/rust/datafusion/src/execution/table_impl.rs@@ -159,13 +159,14 @@ impl TableImpl {#[cfg(test)]mod tests {use super::*;+ use crate::datasource::csv::CsvReadOptions;use crate::execution::context::ExecutionContext;use crate::test;#[test]fn select_columns() -> Result<()> {// build plan using Table API- let t = test_table();+ let t = test_table()?;let t2 = t.select_columns(vec!["c1", "c2", "c11"])?;let plan = t2.to_logical_plan();@@ -181,7 +182,7 @@ mod tests {#[test]fn select_expr() -> Result<()> {// build plan using Table API- let t = test_table();+ let t = test_table()?;let t2 = t.select(vec![t.col("c1")?, t.col("c2")?, t.col("c11")?])?;let plan = t2.to_logical_plan();@@ -197,7 +198,7 @@ mod tests {#[test]fn aggregate() -> Result<()> {// build plan using Table API- let t = test_table();+ let t = test_table()?;let group_expr = vec![t.col("c1")?];let c12 = t.col("c12")?;let aggr_expr = vec![@@ -227,7 +228,7 @@ mod tests {#[test]fn limit() -> Result<()> {// build query using Table API- let t = test_table();+ let t = test_table()?;let t2 = t.select_columns(vec!["c1", "c2", "c11"])?.limit(10)?;let plan = t2.to_logical_plan();@@ -249,25 +250,24 @@ mod tests {/// Create a logical plan from a SQL queryfn create_plan(sql: &str) -> Result<LogicalPlan> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;ctx.create_logical_plan(sql)}- fn test_table() -> Arc<dyn Table + 'static> {+ fn test_table() -> Result<Arc<dyn Table + 'static>> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);- ctx.table("aggregate_test_100").unwrap()+ register_aggregate_csv(&mut ctx)?;+ ctx.table("aggregate_test_100")}- fn register_aggregate_csv(ctx: &mut ExecutionContext) {+ fn register_aggregate_csv(ctx: &mut ExecutionContext) -> Result<()> {let schema = test::aggr_test_schema();let testdata = test::arrow_testdata_path();ctx.register_csv("aggregate_test_100",&format!("{}/csv/aggregate_test_100.csv", testdata),- &schema,- true,- None,- );+ CsvReadOptions::new().schema(&schema),+ )?;+ Ok(())}}diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rsindex ecae04ebdf..704c548254 100644--- a/rust/datafusion/src/logicalplan.rs+++ b/rust/datafusion/src/logicalplan.rs@@ -25,7 +25,7 @@ use std::fmt;use arrow::datatypes::{DataType, Field, Schema};-use crate::datasource::csv::CsvFile;+use crate::datasource::csv::{CsvFile, CsvReadOptions};use crate::datasource::parquet::ParquetTable;use crate::datasource::TableProvider;use crate::error::{ExecutionError, Result};@@ -593,7 +593,7 @@ pub enum LogicalPlan {/// The file type of physical filefile_type: FileType,/// Whether the CSV file contains a header- header_row: bool,+ has_header: bool,},}@@ -796,32 +796,36 @@ impl LogicalPlanBuilder {/// Scan a CSV data sourcepub fn scan_csv(path: &str,- has_header: bool,- schema: Option<&Schema>,- delimiter: Option<u8>,+ options: CsvReadOptions,projection: Option<Vec<usize>>,) -> Result<Self> {- let schema: Schema = match schema {+ let has_header = options.has_header;+ let delimiter = options.delimiter;+ let schema: Schema = match options.schema {Some(s) => s.to_owned(),- None => CsvFile::try_new(path, None, has_header, delimiter)?+ None => CsvFile::try_new(path, options)?.schema().as_ref().to_owned(),};- let projected_schema = projection- .clone()- .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()));+ let projected_schema = Box::new(+ 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(),- schema: Box::new(schema.to_owned()),- has_header,- delimiter,+ schema: Box::new(schema),+ has_header: has_header,+ delimiter: Some(delimiter),projection,- projected_schema: Box::new(- projected_schema.or(Some(schema.clone())).unwrap(),- ),+ projected_schema,}))}@@ -969,9 +973,7 @@ mod tests {fn plan_builder_csv() -> Result<()> {let plan = LogicalPlanBuilder::scan_csv("employee.csv",- true,- Some(&employee_schema()),- None,+ CsvReadOptions::new().schema(&employee_schema()),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 ea47215f11..bb804fbcc2 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -178,13 +178,13 @@ impl ProjectionPushDown {name,location,file_type,- header_row,+ has_header,} => Ok(LogicalPlan::CreateExternalTable {schema: schema.clone(),name: name.to_string(),location: location.to_string(),file_type: file_type.clone(),- header_row: *header_row,+ has_header: *has_header,}),}}diff --git a/rust/datafusion/src/sql/parser.rs b/rust/datafusion/src/sql/parser.rsindex 4b8bf0f4c0..1b7af2ec0d 100644--- a/rust/datafusion/src/sql/parser.rs+++ b/rust/datafusion/src/sql/parser.rs@@ -57,8 +57,8 @@ pub enum DFASTNode {columns: Vec<SQLColumnDef>,/// File type (Parquet, NDJSON, CSV)file_type: FileType,- /// Header row?- header_row: bool,+ /// CSV Header row?+ has_header: bool,/// Path to filelocation: String,},@@ -162,18 +162,18 @@ impl DFParser {}}- let mut headers = true;+ let mut has_header = true;let file_type: FileType = if self.parser.parse_keywords(vec!["STORED", "AS", "CSV"]){if self.parser.parse_keywords(vec!["WITH", "HEADER", "ROW"]) {- headers = true;+ has_header = true;} else if self.parser.parse_keywords(vec!["WITHOUT", "HEADER", "ROW"]){- headers = false;+ has_header = false;}FileType::CSV} else if self.parser.parse_keywords(vec!["STORED", "AS", "NDJSON"]) {@@ -199,7 +199,7 @@ impl DFParser {name: id,columns,file_type,- header_row: headers,+ has_header,location,})}diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex a4bf16e003..44ddca2713 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -25,6 +25,7 @@ use arrow::array::*;use arrow::datatypes::{DataType, Field, Schema};use arrow::record_batch::RecordBatch;+use datafusion::datasource::csv::CsvReadOptions;use datafusion::error::Result;use datafusion::execution::context::ExecutionContext;use datafusion::execution::physical_plan::udf::ScalarFunction;@@ -56,7 +57,11 @@ fn nyc() -> Result<()> {]);let mut ctx = ExecutionContext::new();- ctx.register_csv("tripdata", "file.csv", &schema, true, None);+ ctx.register_csv(+ "tripdata",+ "file.csv",+ CsvReadOptions::new().schema(&schema),+ )?;let logical_plan = ctx.create_logical_plan("SELECT passenger_count, MIN(fare_amount), MAX(fare_amount) \@@ -115,40 +120,43 @@ fn parquet_single_nan_schema() {}#[test]-fn csv_count_star() {+fn csv_count_star() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT COUNT(*), COUNT(1), COUNT(c1) FROM aggregate_test_100";let actual = execute(&mut ctx, sql).join("\n");let expected = "100\t100\t100".to_string();assert_eq!(expected, actual);+ Ok(())}#[test]-fn csv_query_with_predicate() {+fn csv_query_with_predicate() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c1, c12 FROM aggregate_test_100 WHERE c12 > 0.376 AND c12 < 0.4";let actual = execute(&mut ctx, sql).join("\n");let expected = "\"e\"\t0.39144436569161134\n\"d\"\t0.38870280983958583".to_string();assert_eq!(expected, actual);+ Ok(())}#[test]-fn csv_query_group_by_int_min_max() {+fn csv_query_group_by_int_min_max() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c2, MIN(c12), MAX(c12) FROM aggregate_test_100 GROUP BY c2";let mut actual = execute(&mut ctx, sql);actual.sort();let expected = "1\t0.05636955101974106\t0.9965400387585364\n2\t0.16301110515739792\t0.991517828651004\n3\t0.047343434291126085\t0.9293883502480845\n4\t0.02182578039211991\t0.9237877978193884\n5\t0.01479305307777301\t0.9723580396501548".to_string();assert_eq!(expected, actual.join("\n"));+ Ok(())}#[test]fn csv_query_avg_sqrt() -> Result<()> {let mut ctx = create_ctx()?;- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT avg(custom_sqrt(c12)) FROM aggregate_test_100";let mut actual = execute(&mut ctx, sql);actual.sort();@@ -189,42 +197,45 @@ fn custom_sqrt(args: &[ArrayRef]) -> Result<ArrayRef> {}#[test]-fn csv_query_avg() {+fn csv_query_avg() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT avg(c12) FROM aggregate_test_100";let mut actual = execute(&mut ctx, sql);actual.sort();let expected = "0.5089725099127211".to_string();assert_eq!(expected, actual.join("\n"));+ Ok(())}#[test]-fn csv_query_group_by_avg() {+fn csv_query_group_by_avg() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c1, avg(c12) FROM aggregate_test_100 GROUP BY c1";let mut actual = execute(&mut ctx, sql);actual.sort();let expected = "\"a\"\t0.48754517466109415\n\"b\"\t0.41040709263815384\n\"c\"\t0.6600456536439784\n\"d\"\t0.48855379387549824\n\"e\"\t0.48600669271341534".to_string();assert_eq!(expected, actual.join("\n"));+ Ok(())}#[test]-fn csv_query_group_by_avg_with_projection() {+fn csv_query_group_by_avg_with_projection() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT avg(c12), c1 FROM aggregate_test_100 GROUP BY c1";let mut actual = execute(&mut ctx, sql);actual.sort();let expected = "0.41040709263815384\t\"b\"\n0.48600669271341534\t\"e\"\n0.48754517466109415\t\"a\"\n0.48855379387549824\t\"d\"\n0.6600456536439784\t\"c\"".to_string();assert_eq!(expected, actual.join("\n"));+ Ok(())}#[test]-fn csv_query_avg_multi_batch() {+fn csv_query_avg_multi_batch() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT avg(c12) FROM aggregate_test_100";let plan = ctx.create_logical_plan(&sql).unwrap();let plan = ctx.optimize(&plan).unwrap();@@ -238,99 +249,109 @@ fn csv_query_avg_multi_batch() {// Due to float number's accuracy, different batch size will lead to different// answers.assert!((expected - actual).abs() < 0.01);+ Ok(())}#[test]-fn csv_query_count() {+fn csv_query_count() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT count(c12) FROM aggregate_test_100";let actual = execute(&mut ctx, sql).join("\n");let expected = "100".to_string();assert_eq!(expected, actual);+ Ok(())}#[test]-fn csv_query_group_by_int_count() {+fn csv_query_group_by_int_count() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c1, count(c12) FROM aggregate_test_100 GROUP BY c1";let mut actual = execute(&mut ctx, sql);actual.sort();let expected = "\"a\"\t21\n\"b\"\t19\n\"c\"\t21\n\"d\"\t18\n\"e\"\t21".to_string();assert_eq!(expected, actual.join("\n"));+ Ok(())}#[test]-fn csv_query_group_by_string_min_max() {+fn csv_query_group_by_string_min_max() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c2, MIN(c12), MAX(c12) FROM aggregate_test_100 GROUP BY c1";let mut actual = execute(&mut ctx, sql);actual.sort();let expected ="\"a\"\t0.02182578039211991\t0.9800193410444061\n\"b\"\t0.04893135681998029\t0.9185813970744787\n\"c\"\t0.0494924465469434\t0.991517828651004\n\"d\"\t0.061029375346466685\t0.9748360509016578\n\"e\"\t0.01479305307777301\t0.9965400387585364".to_string();assert_eq!(expected, actual.join("\n"));+ Ok(())}#[test]-fn csv_query_cast() {+fn csv_query_cast() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT CAST(c12 AS float) FROM aggregate_test_100 WHERE c12 > 0.376 AND c12 < 0.4";let actual = execute(&mut ctx, sql).join("\n");let expected = "0.39144436569161134\n0.38870280983958583".to_string();assert_eq!(expected, actual);+ Ok(())}#[test]-fn csv_query_cast_literal() {+fn csv_query_cast_literal() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c12, CAST(1 AS float) FROM aggregate_test_100 WHERE c12 > CAST(0 AS float) LIMIT 2";let actual = execute(&mut ctx, sql).join("\n");let expected = "0.9294097332465232\t1.0\n0.3114712539863804\t1.0".to_string();assert_eq!(expected, actual);+ Ok(())}#[test]-fn csv_query_limit() {+fn csv_query_limit() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c1 FROM aggregate_test_100 LIMIT 2";let actual = execute(&mut ctx, sql).join("\n");let expected = "\"c\"\n\"d\"".to_string();assert_eq!(expected, actual);+ Ok(())}#[test]-fn csv_query_limit_bigger_than_nbr_of_rows() {+fn csv_query_limit_bigger_than_nbr_of_rows() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c2 FROM aggregate_test_100 LIMIT 200";let actual = execute(&mut ctx, sql).join("\n");let expected = "2\n5\n1\n1\n5\n4\n3\n3\n1\n4\n1\n4\n3\n2\n1\n1\n2\n1\n3\n2\n4\n1\n5\n4\n2\n1\n4\n5\n2\n3\n4\n2\n1\n5\n3\n1\n2\n3\n3\n3\n2\n4\n1\n3\n2\n5\n2\n1\n4\n1\n4\n2\n5\n4\n2\n3\n4\n4\n4\n5\n4\n2\n1\n2\n4\n2\n3\n5\n1\n1\n4\n2\n1\n2\n1\n1\n5\n4\n5\n2\n3\n2\n4\n1\n3\n4\n3\n2\n5\n3\n3\n2\n5\n5\n4\n1\n3\n3\n4\n4".to_string();assert_eq!(expected, actual);+ Ok(())}#[test]-fn csv_query_limit_with_same_nbr_of_rows() {+fn csv_query_limit_with_same_nbr_of_rows() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c2 FROM aggregate_test_100 LIMIT 100";let actual = execute(&mut ctx, sql).join("\n");let expected = "2\n5\n1\n1\n5\n4\n3\n3\n1\n4\n1\n4\n3\n2\n1\n1\n2\n1\n3\n2\n4\n1\n5\n4\n2\n1\n4\n5\n2\n3\n4\n2\n1\n5\n3\n1\n2\n3\n3\n3\n2\n4\n1\n3\n2\n5\n2\n1\n4\n1\n4\n2\n5\n4\n2\n3\n4\n4\n4\n5\n4\n2\n1\n2\n4\n2\n3\n5\n1\n1\n4\n2\n1\n2\n1\n1\n5\n4\n5\n2\n3\n2\n4\n1\n3\n4\n3\n2\n5\n3\n3\n2\n5\n5\n4\n1\n3\n3\n4\n4".to_string();assert_eq!(expected, actual);+ Ok(())}#[test]-fn csv_query_limit_zero() {+fn csv_query_limit_zero() -> Result<()> {let mut ctx = ExecutionContext::new();- register_aggregate_csv(&mut ctx);+ register_aggregate_csv(&mut ctx)?;let sql = "SELECT c1 FROM aggregate_test_100 LIMIT 0";let actual = execute(&mut ctx, sql).join("\n");let expected = "".to_string();assert_eq!(expected, actual);+ Ok(())}#[test]@@ -425,24 +446,15 @@ fn register_aggregate_csv_by_sql(ctx: &mut ExecutionContext) {.unwrap();}-fn register_aggregate_csv(ctx: &mut ExecutionContext) {+fn register_aggregate_csv(ctx: &mut ExecutionContext) -> Result<()> {let testdata = env::var("ARROW_TEST_DATA").expect("ARROW_TEST_DATA not defined");let schema = aggr_test_schema();- register_csv(- ctx,+ ctx.register_csv("aggregate_test_100",&format!("{}/csv/aggregate_test_100.csv", testdata),- &schema,- );-}--fn register_csv(- ctx: &mut ExecutionContext,- name: &str,- filename: &str,- schema: &Arc<Schema>,-) {- ctx.register_csv(name, filename, &schema, true, None);+ CsvReadOptions::new().schema(&schema),+ )?;+ Ok(())}fn register_alltypes_parquet(ctx: &mut ExecutionContext) {