Apache DataFusion SQL Query Engine
ARROW-9652: [Rust][DataFusion] Error message rather than panic for external csv tables with no column defs
alamb908ed2d42f00
diff --git a/rust/datafusion/src/error.rs b/rust/datafusion/src/error.rsindex 7acad285aa..6f903025de 100644--- a/rust/datafusion/src/error.rs+++ b/rust/datafusion/src/error.rs@@ -24,7 +24,6 @@ use std::result;use arrow::error::ArrowError;use parquet::errors::ParquetError;-use sqlparser::parser::ParserError;/// Result type for operations that could result in an `ExecutionError`diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 6f0f65ed1a..f822bc12ea 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -57,11 +57,10 @@ use crate::optimizer::optimizer::OptimizerRule;use crate::optimizer::projection_push_down::ProjectionPushDown;use crate::optimizer::type_coercion::TypeCoercionRule;use crate::sql::{- parser::{DFParser, FileType, Statement},+ parser::{DFParser, FileType},planner::{SchemaProvider, SqlToRel},};use crate::table::Table;-use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption, DataType as SQLDataType};/// Execution context for registering data sources and executing queriespub struct ExecutionContext {@@ -150,39 +149,14 @@ impl ExecutionContext {)));}- match &statements[0] {- Statement::Statement(s) => {- let schema_provider = ExecutionContextSchemaProvider {- datasources: &self.datasources,- scalar_functions: &self.scalar_functions,- };-- // create a query planner- let query_planner = SqlToRel::new(schema_provider);-- // plan the query (create a logical relational plan)- let plan = query_planner.statement_to_plan(&s)?;-- Ok(plan)- }- Statement::CreateExternalTable {- name,- columns,- file_type,- has_header,- location,- } => {- let schema = Box::new(self.build_schema(&columns)?);+ let schema_provider = ExecutionContextSchemaProvider {+ datasources: &self.datasources,+ scalar_functions: &self.scalar_functions,+ };- Ok(LogicalPlan::CreateExternalTable {- schema,- name: name.clone(),- location: location.clone(),- file_type: file_type.clone(),- has_header: has_header.clone(),- })- }- }+ // create a query planner+ let query_planner = SqlToRel::new(schema_provider);+ Ok(query_planner.statement_to_plan(&statements[0])?)}/// Register a scalar UDF@@ -195,44 +169,6 @@ impl ExecutionContext {&self.scalar_functions}- /// Get schema from columns- pub fn build_schema(&self, columns: &Vec<SQLColumnDef>) -> Result<Schema> {- let mut fields = Vec::new();-- for column in columns {- let data_type = self.make_data_type(&column.data_type)?;- let allow_null = column- .options- .iter()- .any(|x| x.option == ColumnOption::Null);- fields.push(Field::new(&column.name.value, data_type, allow_null));- }-- Ok(Schema::new(fields))- }-- fn make_data_type(&self, sql_type: &SQLDataType) -> Result<DataType> {- match sql_type {- SQLDataType::BigInt => Ok(DataType::Int64),- SQLDataType::Int => Ok(DataType::Int32),- SQLDataType::SmallInt => Ok(DataType::Int16),- SQLDataType::Char(_) | SQLDataType::Varchar(_) | SQLDataType::Text => {- Ok(DataType::Utf8)- }- SQLDataType::Decimal(_, _) => Ok(DataType::Float64),- SQLDataType::Float(_) => Ok(DataType::Float32),- SQLDataType::Real | SQLDataType::Double => Ok(DataType::Float64),- SQLDataType::Boolean => Ok(DataType::Boolean),- SQLDataType::Date => Ok(DataType::Date64(DateUnit::Day)),- SQLDataType::Time => Ok(DataType::Time64(TimeUnit::Millisecond)),- SQLDataType::Timestamp => Ok(DataType::Date64(DateUnit::Millisecond)),- _ => Err(ExecutionError::General(format!(- "Unsupported data type: {:?}.",- sql_type- ))),- }- }-/// Register a CSV file as a table so that it can be queried from SQLpub fn register_csv(&mut self,diff --git a/rust/datafusion/src/sql/parser.rs b/rust/datafusion/src/sql/parser.rsindex 613fdf73c0..e8089a8181 100644--- a/rust/datafusion/src/sql/parser.rs+++ b/rust/datafusion/src/sql/parser.rs@@ -44,6 +44,21 @@ pub enum FileType {CSV,}+/// DataFusion extension DDL for `CREATE EXTERNAL TABLE`+#[derive(Debug, Clone, PartialEq)]+pub struct CreateExternalTable {+ /// Table name+ pub name: String,+ /// Optional schema+ pub columns: Vec<ColumnDef>,+ /// File type (Parquet, NDJSON, CSV)+ pub file_type: FileType,+ /// CSV Header row?+ pub has_header: bool,+ /// Path to file+ pub location: String,+}+/// DataFusion Statement representations.////// Tokens parsed by `DFParser` are converted into these values.@@ -51,19 +66,8 @@ pub enum FileType {pub enum Statement {/// ANSI SQL AST nodeStatement(SQLStatement),- /// DDL for creating an external table in DataFusion- CreateExternalTable {- /// Table name- name: String,- /// Optional schema- columns: Vec<ColumnDef>,- /// File type (Parquet, NDJSON, CSV)- file_type: FileType,- /// CSV Header row?- has_header: bool,- /// Path to file- location: String,- },+ /// Extension: `CREATE EXTERNAL TABLE`+ CreateExternalTable(CreateExternalTable),}/// SQL Parser@@ -222,13 +226,14 @@ impl DFParser {self.parser.expect_keyword(Keyword::LOCATION)?;let location = self.parser.parse_literal_string()?;- Ok(Statement::CreateExternalTable {+ let create = CreateExternalTable {name: table_name.to_string(),columns,file_type,has_header,location,- })+ };+ Ok(Statement::CreateExternalTable(create))}/// Parses the set of valid formats@@ -315,24 +320,24 @@ mod tests {fn create_external_table() -> Result<(), ParserError> {// positive caselet sql = "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV LOCATION 'foo.csv'";- let expected = Statement::CreateExternalTable {+ let expected = Statement::CreateExternalTable(CreateExternalTable {name: "t".into(),columns: vec![make_column_def("c1", DataType::Int)],file_type: FileType::CSV,has_header: false,location: "foo.csv".into(),- };+ });expect_parse_ok(sql, expected)?;// positive case: it is ok for parquet files not to have columns specifiedlet sql = "CREATE EXTERNAL TABLE t STORED AS PARQUET LOCATION 'foo.parquet'";- let expected = Statement::CreateExternalTable {+ let expected = Statement::CreateExternalTable(CreateExternalTable {name: "t".into(),columns: vec![],file_type: FileType::Parquet,has_header: false,location: "foo.parquet".into(),- };+ });expect_parse_ok(sql, expected)?;// Error cases: Invalid typediff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex 5746af0a61..d80a70ff7f 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -24,6 +24,7 @@ use crate::logicalplan::Expr::Alias;use crate::logicalplan::{lit, Expr, FunctionMeta, LogicalPlan, LogicalPlanBuilder, Operator, ScalarValue,};+use crate::sql::parser::{CreateExternalTable, FileType, Statement as DFStatement};use arrow::datatypes::*;@@ -31,6 +32,7 @@ use sqlparser::ast::{BinaryOperator, DataType as SQLDataType, Expr as SQLExpr, Query, Select, SelectItem,SetExpr, TableFactor, TableWithJoins, UnaryOperator, Value,};+use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};use sqlparser::ast::{OrderByExpr, Statement};/// The SchemaProvider trait allows the query planner to obtain meta-data about tables and@@ -53,8 +55,16 @@ impl<S: SchemaProvider> SqlToRel<S> {SqlToRel { schema_provider }}- /// Generate a logic plan from an SQL statement- pub fn statement_to_plan(&self, sql: &Statement) -> Result<LogicalPlan> {+ /// Generate a logical plan from an DataFusion SQL statement+ pub fn statement_to_plan(&self, statement: &DFStatement) -> Result<LogicalPlan> {+ match statement {+ DFStatement::CreateExternalTable(s) => self.external_table_to_plan(&s),+ DFStatement::Statement(s) => self.sql_statement_to_plan(&s),+ }+ }++ /// Generate a logical plan from an SQL statement+ fn sql_statement_to_plan(&self, sql: &Statement) -> Result<LogicalPlan> {match sql {Statement::Query(query) => self.query_to_plan(&query),_ => Err(ExecutionError::NotImplemented(@@ -77,6 +87,87 @@ impl<S: SchemaProvider> SqlToRel<S> {self.limit(&plan, &query.limit)}+ /// Generate a logical plan from a CREATE EXTERNAL TABLE statement+ pub fn external_table_to_plan(+ &self,+ statement: &CreateExternalTable,+ ) -> Result<LogicalPlan> {+ let CreateExternalTable {+ name,+ columns,+ file_type,+ has_header,+ location,+ } = statement;++ // semantic checks+ match *file_type {+ FileType::CSV => {+ if columns.is_empty() {+ return Err(ExecutionError::General(+ "Column definitions required for CSV files. None found".into(),+ ));+ }+ }+ FileType::Parquet => {+ if !columns.is_empty() {+ return Err(ExecutionError::General(+ "Column definitions can not be specified for PARQUET files."+ .into(),+ ));+ }+ }+ FileType::NdJson => {}+ };++ let schema = Box::new(self.build_schema(&columns)?);++ Ok(LogicalPlan::CreateExternalTable {+ schema,+ name: name.clone(),+ location: location.clone(),+ file_type: file_type.clone(),+ has_header: has_header.clone(),+ })+ }++ fn build_schema(&self, columns: &Vec<SQLColumnDef>) -> Result<Schema> {+ let mut fields = Vec::new();++ for column in columns {+ let data_type = self.make_data_type(&column.data_type)?;+ let allow_null = column+ .options+ .iter()+ .any(|x| x.option == ColumnOption::Null);+ fields.push(Field::new(&column.name.value, data_type, allow_null));+ }++ Ok(Schema::new(fields))+ }++ fn make_data_type(&self, sql_type: &SQLDataType) -> Result<DataType> {+ match sql_type {+ SQLDataType::BigInt => Ok(DataType::Int64),+ SQLDataType::Int => Ok(DataType::Int32),+ SQLDataType::SmallInt => Ok(DataType::Int16),+ SQLDataType::Char(_) | SQLDataType::Varchar(_) | SQLDataType::Text => {+ Ok(DataType::Utf8)+ }+ SQLDataType::Decimal(_, _) => Ok(DataType::Float64),+ SQLDataType::Float(_) => Ok(DataType::Float32),+ SQLDataType::Real | SQLDataType::Double => Ok(DataType::Float64),+ SQLDataType::Boolean => Ok(DataType::Boolean),+ SQLDataType::Date => Ok(DataType::Date64(DateUnit::Day)),+ SQLDataType::Time => Ok(DataType::Time64(TimeUnit::Millisecond)),+ SQLDataType::Timestamp => Ok(DataType::Date64(DateUnit::Millisecond)),+ _ => Err(ExecutionError::General(format!(+ "Unsupported data type: {:?}.",+ sql_type+ ))),+ }+ }+fn from_join_to_plan(&self, from: &Vec<TableWithJoins>) -> Result<LogicalPlan> {if from.len() == 0 {return Ok(LogicalPlanBuilder::empty().build()?);@@ -460,10 +551,9 @@ pub fn convert_data_type(sql: &SQLDataType) -> Result<DataType> {#[cfg(test)]mod tests {-use super::*;use crate::logicalplan::FunctionType;- use sqlparser::{dialect::GenericDialect, parser::Parser};+ use crate::sql::parser::DFParser;#[test]fn select_no_relation() {@@ -688,10 +778,44 @@ mod tests {);}+ #[test]+ fn create_external_table_csv() {+ let sql = "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV LOCATION 'foo.csv'";+ let expected = "CreateExternalTable: \"t\"";+ quick_test(sql, expected);+ }++ #[test]+ fn create_external_table_csv_no_schema() {+ let sql = "CREATE EXTERNAL TABLE t STORED AS CSV LOCATION 'foo.csv'";+ let err = logical_plan(sql).expect_err("query should have failed");+ assert_eq!(+ "General(\"Column definitions required for CSV files. None found\")",+ format!("{:?}", err)+ );+ }++ #[test]+ fn create_external_table_parquet() {+ let sql =+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS PARQUET LOCATION 'foo.parquet'";+ let err = logical_plan(sql).expect_err("query should have failed");+ assert_eq!(+ "General(\"Column definitions can not be specified for PARQUET files.\")",+ format!("{:?}", err)+ );+ }++ #[test]+ fn create_external_table_parquet_no_schema() {+ let sql = "CREATE EXTERNAL TABLE t STORED AS PARQUET LOCATION 'foo.parquet'";+ let expected = "CreateExternalTable: \"t\"";+ quick_test(sql, expected);+ }+fn logical_plan(sql: &str) -> Result<LogicalPlan> {- let dialect = GenericDialect {};let planner = SqlToRel::new(MockSchemaProvider {});- let ast = Parser::parse_sql(&dialect, sql).unwrap();+ let ast = DFParser::parse_sql(&sql).unwrap();planner.statement_to_plan(&ast[0])}