Apache DataFusion SQL Query Engine
Support `create table` with explicit column definitions (#4194)
Jie Han74199d632d9d
diff --git a/datafusion/core/tests/sql/create_drop.rs b/datafusion/core/tests/sql/create_drop.rsindex 9df6027036..143c53f183 100644--- a/datafusion/core/tests/sql/create_drop.rs+++ b/datafusion/core/tests/sql/create_drop.rs@@ -49,6 +49,71 @@ async fn create_table_as() -> Result<()> {Ok(())}+#[tokio::test]+async fn create_table_with_schema_as_select() -> Result<()> {+ let ctx = SessionContext::new();+ register_aggregate_simple_csv(&ctx).await?;++ let sql = "CREATE TABLE my_table(c1 float, c2 double, c3 boolean, c4 varchar) \+ AS SELECT *,c3 as c4_tmp FROM aggregate_simple";+ ctx.sql(sql).await.unwrap();++ let sql_all = "SELECT * FROM my_table order by c1 LIMIT 1";+ let results_all = execute_to_batches(&ctx, sql_all).await;++ let expected = vec![+ "+---------+----------------+------+----+",+ "| c1 | c2 | c3 | c4 |",+ "+---------+----------------+------+----+",+ "| 0.00001 | 0.000000000001 | true | 1 |",+ "+---------+----------------+------+----+",+ ];++ assert_batches_eq!(expected, &results_all);++ Ok(())+}++#[tokio::test]+async fn create_table_with_schema_as_select_mismatch() -> Result<()> {+ let ctx = SessionContext::new();+ register_aggregate_simple_csv(&ctx).await?;++ let sql = "CREATE TABLE my_table(c1 float, c2 double, c3 boolean, c4 varchar) \+ AS SELECT * FROM aggregate_simple";+ let expected_err = ctx.sql(sql).await.unwrap_err();+ assert_contains!(+ expected_err.to_string(),+ "Mismatch: 4 columns specified, but result has 3 columns"+ );+ Ok(())+}++#[tokio::test]+async fn create_table_with_schema_as_values() -> Result<()> {+ let ctx = SessionContext::new();+ register_aggregate_simple_csv(&ctx).await?;++ let sql =+ "CREATE TABLE my_table(c1 int, c2 float, c3 varchar) AS VALUES(1, 2, 'hello')";+ ctx.sql(sql).await.unwrap();++ let sql_all = "SELECT * FROM my_table";+ let results_all = execute_to_batches(&ctx, sql_all).await;++ let expected = vec![+ "+----+----+-------+",+ "| c1 | c2 | c3 |",+ "+----+----+-------+",+ "| 1 | 2 | hello |",+ "+----+----+-------+",+ ];++ assert_batches_eq!(expected, &results_all);++ Ok(())+}+#[tokio::test]async fn create_or_replace_table_as() -> Result<()> {// the information schema used to introduce cyclic Arcsdiff --git a/datafusion/sql/src/planner.rs b/datafusion/sql/src/planner.rsindex 58d221e07b..d212527443 100644--- a/datafusion/sql/src/planner.rs+++ b/datafusion/sql/src/planner.rs@@ -17,57 +17,57 @@//! SQL Query Planner (produces logical plan from SQL AST)-use crate::parser::{CreateExternalTable, DescribeTable, Statement as DFStatement};+use std::collections::{HashMap, HashSet};+use std::str::FromStr;+use std::sync::Arc;+use std::{convert::TryInto, vec};+use arrow::datatypes::*;+use sqlparser::ast::ExactNumberInfo;+use sqlparser::ast::TimezoneInfo;+use sqlparser::ast::{+ BinaryOperator, DataType as SQLDataType, DateTimeField, Expr as SQLExpr, FunctionArg,+ FunctionArgExpr, Ident, Join, JoinConstraint, JoinOperator, ObjectName,+ Offset as SQLOffset, Query, Select, SelectItem, SetExpr, SetOperator,+ ShowCreateObject, ShowStatementFilter, TableAlias, TableFactor, TableWithJoins,+ TrimWhereField, UnaryOperator, Value, Values as SQLValues,+};+use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};+use sqlparser::ast::{ObjectType, OrderByExpr, Statement};+use sqlparser::parser::ParserError::ParserError;+use datafusion_common::parsers::parse_interval;+use datafusion_common::TableReference;use datafusion_common::{context, ToDFSchema};+use datafusion_common::{+ field_not_found, Column, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,+};+use datafusion_expr::expr::{Between, BinaryExpr, Case, Cast, GroupingSet, Like};use datafusion_expr::expr_rewriter::normalize_col;use datafusion_expr::expr_rewriter::normalize_col_with_schemas;+use datafusion_expr::logical_plan::builder::project_with_alias;use datafusion_expr::logical_plan::{Analyze, CreateCatalog, CreateCatalogSchema,CreateExternalTable as PlanCreateExternalTable, CreateMemoryTable, CreateView,DropTable, DropView, Explain, JoinType, LogicalPlan, LogicalPlanBuilder,Partitioning, PlanType, SetVariable, ToStringifiedPlan,};+use datafusion_expr::logical_plan::{Filter, Subquery};use datafusion_expr::utils::{can_hash, expand_qualified_wildcard, expand_wildcard, expr_as_column_expr,find_aggregate_exprs, find_column_exprs, find_window_exprs, COUNT_STAR_EXPANSION,};+use datafusion_expr::Expr::Alias;use datafusion_expr::{- and, col, lit, AggregateFunction, AggregateUDF, Expr, ExprSchemable, GetIndexedField,- Operator, ScalarUDF, WindowFrame, WindowFrameUnits,+ and, cast, col, lit, AggregateFunction, AggregateUDF, Expr, ExprSchemable,+ GetIndexedField, Operator, ScalarUDF, WindowFrame, WindowFrameUnits,};use datafusion_expr::{window_function::WindowFunction, BuiltinScalarFunction, TableSource,};-use std::collections::{HashMap, HashSet};-use std::str::FromStr;-use std::sync::Arc;-use std::{convert::TryInto, vec};+use crate::parser::{CreateExternalTable, DescribeTable, Statement as DFStatement};use crate::utils::{make_decimal_type, normalize_ident, resolve_columns};-use datafusion_common::TableReference;-use datafusion_common::{- field_not_found, Column, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,-};-use datafusion_expr::expr::{Between, BinaryExpr, Case, Cast, GroupingSet, Like};-use datafusion_expr::logical_plan::builder::project_with_alias;-use datafusion_expr::logical_plan::{Filter, Subquery};-use datafusion_expr::Expr::Alias;--use sqlparser::ast::TimezoneInfo;-use sqlparser::ast::{- BinaryOperator, DataType as SQLDataType, DateTimeField, Expr as SQLExpr, FunctionArg,- FunctionArgExpr, Ident, Join, JoinConstraint, JoinOperator, ObjectName,- Offset as SQLOffset, Query, Select, SelectItem, SetExpr, SetOperator,- ShowCreateObject, ShowStatementFilter, TableAlias, TableFactor, TableWithJoins,- TrimWhereField, UnaryOperator, Value, Values as SQLValues,-};-use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};-use sqlparser::ast::{ObjectType, OrderByExpr, Statement};-use sqlparser::parser::ParserError::ParserError;--use sqlparser::ast::ExactNumberInfo;use super::{parser::DFParser,@@ -195,12 +195,38 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {if_not_exists,or_replace,..- } if columns.is_empty()- && constraints.is_empty()+ } if constraints.is_empty()&& table_properties.is_empty()&& with_options.is_empty() =>{let plan = self.query_to_plan(*query, &mut HashMap::new())?;+ let input_schema = plan.schema();++ let plan = if !columns.is_empty() {+ let schema = self.build_schema(columns)?.to_dfschema_ref()?;+ if schema.fields().len() != input_schema.fields().len() {+ return Err(DataFusionError::Plan(format!(+ "Mismatch: {} columns specified, but result has {} columns",+ schema.fields().len(),+ input_schema.fields().len()+ )));+ }+ let input_fields = input_schema.fields();+ let project_exprs = schema+ .fields()+ .iter()+ .zip(input_fields)+ .map(|(field, input_field)| {+ cast(col(input_field.name()), field.data_type().clone())+ .alias(field.name())+ })+ .collect::<Vec<_>>();+ LogicalPlanBuilder::from(plan.clone())+ .project(project_exprs)?+ .build()?+ } else {+ plan+ };Ok(LogicalPlan::CreateMemoryTable(CreateMemoryTable {name: name.to_string(),@@ -2981,11 +3007,14 @@ fn extract_possible_join_keys(#[cfg(test)]mod tests {- use super::*;- use datafusion_common::assert_contains;- use sqlparser::dialect::{Dialect, GenericDialect, HiveDialect, MySqlDialect};use std::any::Any;+ use sqlparser::dialect::{Dialect, GenericDialect, HiveDialect, MySqlDialect};++ use datafusion_common::assert_contains;++ use super::*;+#[test]fn parse_decimals() {let test_data = [