Apache DataFusion SQL Query Engine
Add SHOW CREATE TABLE with initial support for views (#2830)
Mike Robertsd1bf06e0b0dc
diff --git a/datafusion/core/src/catalog/information_schema.rs b/datafusion/core/src/catalog/information_schema.rsindex ff5d12e7ff..fd8e250fea 100644--- a/datafusion/core/src/catalog/information_schema.rs+++ b/datafusion/core/src/catalog/information_schema.rs@@ -126,18 +126,26 @@ impl InformationSchemaProvider {&schema_name,table_name,table.table_type(),+ table.get_table_definition(),);}}}// Add a final list for the information schema tables themselves- builder.add_table(&catalog_name, INFORMATION_SCHEMA, TABLES, TableType::View);+ builder.add_table(+ &catalog_name,+ INFORMATION_SCHEMA,+ TABLES,+ TableType::View,+ None::<&str>,+ );builder.add_table(&catalog_name,INFORMATION_SCHEMA,COLUMNS,TableType::View,+ None::<&str>,);}@@ -212,6 +220,7 @@ struct InformationSchemaTablesBuilder {schema_names: StringBuilder,table_names: StringBuilder,table_types: StringBuilder,+ definitions: StringBuilder,}impl InformationSchemaTablesBuilder {@@ -225,6 +234,7 @@ impl InformationSchemaTablesBuilder {schema_names: StringBuilder::new(default_capacity),table_names: StringBuilder::new(default_capacity),table_types: StringBuilder::new(default_capacity),+ definitions: StringBuilder::new(default_capacity),}}@@ -234,6 +244,7 @@ impl InformationSchemaTablesBuilder {schema_name: impl AsRef<str>,table_name: impl AsRef<str>,table_type: TableType,+ definition: Option<impl AsRef<str>>,) {// Note: append_value is actually infallable.self.catalog_names@@ -250,6 +261,7 @@ impl InformationSchemaTablesBuilder {TableType::Temporary => "LOCAL TEMPORARY",}).unwrap();+ self.definitions.append_option(definition.as_ref()).unwrap();}}@@ -260,6 +272,7 @@ impl From<InformationSchemaTablesBuilder> for MemTable {Field::new("table_schema", DataType::Utf8, false),Field::new("table_name", DataType::Utf8, false),Field::new("table_type", DataType::Utf8, false),+ Field::new("definition", DataType::Utf8, true),]);let InformationSchemaTablesBuilder {@@ -267,6 +280,7 @@ impl From<InformationSchemaTablesBuilder> for MemTable {mut schema_names,mut table_names,mut table_types,+ mut definitions,} = value;let schema = Arc::new(schema);@@ -277,6 +291,7 @@ impl From<InformationSchemaTablesBuilder> for MemTable {Arc::new(schema_names.finish()),Arc::new(table_names.finish()),Arc::new(table_types.finish()),+ Arc::new(definitions.finish()),],).unwrap();diff --git a/datafusion/core/src/datasource/datasource.rs b/datafusion/core/src/datasource/datasource.rsindex 17b288bef4..7b86f8ec89 100644--- a/datafusion/core/src/datasource/datasource.rs+++ b/datafusion/core/src/datasource/datasource.rs@@ -42,6 +42,11 @@ pub trait TableProvider: Sync + Send {/// Get the type of this table for metadata/catalog purposes.fn table_type(&self) -> TableType;+ /// Get the create statement used to create this table, if available.+ fn get_table_definition(&self) -> Option<&str> {+ None+ }+/// Create an ExecutionPlan that will scan the table./// The table provider will be usually responsible of grouping/// the source data into partitions that can be efficientlydiff --git a/datafusion/core/src/datasource/view.rs b/datafusion/core/src/datasource/view.rsindex 9d6b33e3ed..da36077795 100644--- a/datafusion/core/src/datasource/view.rs+++ b/datafusion/core/src/datasource/view.rs@@ -37,17 +37,23 @@ pub struct ViewTable {logical_plan: LogicalPlan,/// File fields + partition columnstable_schema: SchemaRef,+ /// SQL used to create the view, if available+ definition: Option<String>,}impl ViewTable {/// Create new view that is executed at query runtime.- /// Takes a `LogicalPlan` as input.- pub fn try_new(logical_plan: LogicalPlan) -> Result<Self> {+ /// Takes a `LogicalPlan` and an optional create statement as input.+ pub fn try_new(+ logical_plan: LogicalPlan,+ definition: Option<String>,+ ) -> Result<Self> {let table_schema = logical_plan.schema().as_ref().to_owned().into();let view = Self {logical_plan,table_schema,+ definition,};Ok(view)@@ -68,6 +74,10 @@ impl TableProvider for ViewTable {TableType::View}+ fn get_table_definition(&self) -> Option<&str> {+ self.definition.as_deref()+ }+async fn scan(&self,ctx: &SessionState,diff --git a/datafusion/core/src/execution/context.rs b/datafusion/core/src/execution/context.rsindex b998ca5977..9170936afb 100644--- a/datafusion/core/src/execution/context.rs+++ b/datafusion/core/src/execution/context.rs@@ -350,6 +350,7 @@ impl SessionContext {name,input,or_replace,+ definition,}) => {let view = self.table(name.as_str());@@ -357,14 +358,16 @@ impl SessionContext {(true, Ok(_)) => {self.deregister_table(name.as_str())?;let plan = self.optimize(&input)?;- let table = Arc::new(ViewTable::try_new(plan.clone())?);+ let table =+ Arc::new(ViewTable::try_new(plan.clone(), definition)?);self.register_table(name.as_str(), table)?;Ok(Arc::new(DataFrame::new(self.state.clone(), &plan)))}(_, Err(_)) => {let plan = self.optimize(&input)?;- let table = Arc::new(ViewTable::try_new(plan.clone())?);+ let table =+ Arc::new(ViewTable::try_new(plan.clone(), definition)?);self.register_table(name.as_str(), table)?;Ok(Arc::new(DataFrame::new(self.state.clone(), &plan)))diff --git a/datafusion/core/tests/sql/information_schema.rs b/datafusion/core/tests/sql/information_schema.rsindex 4aef697822..f528c3c3c5 100644--- a/datafusion/core/tests/sql/information_schema.rs+++ b/datafusion/core/tests/sql/information_schema.rs@@ -52,12 +52,12 @@ async fn information_schema_tables_no_tables() {.unwrap();let expected = vec![- "+---------------+--------------------+------------+------------+",- "| table_catalog | table_schema | table_name | table_type |",- "+---------------+--------------------+------------+------------+",- "| datafusion | information_schema | columns | VIEW |",- "| datafusion | information_schema | tables | VIEW |",- "+---------------+--------------------+------------+------------+",+ "+---------------+--------------------+------------+------------+------------+",+ "| table_catalog | table_schema | table_name | table_type | definition |",+ "+---------------+--------------------+------------+------------+------------+",+ "| datafusion | information_schema | columns | VIEW | |",+ "| datafusion | information_schema | tables | VIEW | |",+ "+---------------+--------------------+------------+------------+------------+",];assert_batches_sorted_eq!(expected, &result);}@@ -76,13 +76,13 @@ async fn information_schema_tables_tables_default_catalog() {.unwrap();let expected = vec![- "+---------------+--------------------+------------+------------+",- "| table_catalog | table_schema | table_name | table_type |",- "+---------------+--------------------+------------+------------+",- "| datafusion | information_schema | tables | VIEW |",- "| datafusion | information_schema | columns | VIEW |",- "| datafusion | public | t | BASE TABLE |",- "+---------------+--------------------+------------+------------+",+ "+---------------+--------------------+------------+------------+------------+",+ "| table_catalog | table_schema | table_name | table_type | definition |",+ "+---------------+--------------------+------------+------------+------------+",+ "| datafusion | information_schema | columns | VIEW | |",+ "| datafusion | information_schema | tables | VIEW | |",+ "| datafusion | public | t | BASE TABLE | |",+ "+---------------+--------------------+------------+------------+------------+",];assert_batches_sorted_eq!(expected, &result);@@ -95,14 +95,14 @@ async fn information_schema_tables_tables_default_catalog() {.unwrap();let expected = vec![- "+---------------+--------------------+------------+------------+",- "| table_catalog | table_schema | table_name | table_type |",- "+---------------+--------------------+------------+------------+",- "| datafusion | information_schema | columns | VIEW |",- "| datafusion | information_schema | tables | VIEW |",- "| datafusion | public | t | BASE TABLE |",- "| datafusion | public | t2 | BASE TABLE |",- "+---------------+--------------------+------------+------------+",+ "+---------------+--------------------+------------+------------+------------+",+ "| table_catalog | table_schema | table_name | table_type | definition |",+ "+---------------+--------------------+------------+------------+------------+",+ "| datafusion | information_schema | columns | VIEW | |",+ "| datafusion | information_schema | tables | VIEW | |",+ "| datafusion | public | t | BASE TABLE | |",+ "| datafusion | public | t2 | BASE TABLE | |",+ "+---------------+--------------------+------------+------------+------------+",];assert_batches_sorted_eq!(expected, &result);}@@ -139,19 +139,19 @@ async fn information_schema_tables_tables_with_multiple_catalogs() {.unwrap();let expected = vec![- "+------------------+--------------------+------------+------------+",- "| table_catalog | table_schema | table_name | table_type |",- "+------------------+--------------------+------------+------------+",- "| datafusion | information_schema | columns | VIEW |",- "| datafusion | information_schema | tables | VIEW |",- "| my_catalog | information_schema | columns | VIEW |",- "| my_catalog | information_schema | tables | VIEW |",- "| my_catalog | my_schema | t1 | BASE TABLE |",- "| my_catalog | my_schema | t2 | BASE TABLE |",- "| my_other_catalog | information_schema | columns | VIEW |",- "| my_other_catalog | information_schema | tables | VIEW |",- "| my_other_catalog | my_other_schema | t3 | BASE TABLE |",- "+------------------+--------------------+------------+------------+",+ "+------------------+--------------------+------------+------------+------------+",+ "| table_catalog | table_schema | table_name | table_type | definition |",+ "+------------------+--------------------+------------+------------+------------+",+ "| datafusion | information_schema | columns | VIEW | |",+ "| datafusion | information_schema | tables | VIEW | |",+ "| my_catalog | information_schema | columns | VIEW | |",+ "| my_catalog | information_schema | tables | VIEW | |",+ "| my_catalog | my_schema | t1 | BASE TABLE | |",+ "| my_catalog | my_schema | t2 | BASE TABLE | |",+ "| my_other_catalog | information_schema | columns | VIEW | |",+ "| my_other_catalog | information_schema | tables | VIEW | |",+ "| my_other_catalog | my_other_schema | t3 | BASE TABLE | |",+ "+------------------+--------------------+------------+------------+------------+",];assert_batches_sorted_eq!(expected, &result);}@@ -200,15 +200,15 @@ async fn information_schema_tables_table_types() {.unwrap();let expected = vec![- "+---------------+--------------------+------------+-----------------+",- "| table_catalog | table_schema | table_name | table_type |",- "+---------------+--------------------+------------+-----------------+",- "| datafusion | information_schema | tables | VIEW |",- "| datafusion | information_schema | columns | VIEW |",- "| datafusion | public | physical | BASE TABLE |",- "| datafusion | public | query | VIEW |",- "| datafusion | public | temp | LOCAL TEMPORARY |",- "+---------------+--------------------+------------+-----------------+",+ "+---------------+--------------------+------------+-----------------+------------+",+ "| table_catalog | table_schema | table_name | table_type | definition |",+ "+---------------+--------------------+------------+-----------------+------------+",+ "| datafusion | information_schema | columns | VIEW | |",+ "| datafusion | information_schema | tables | VIEW | |",+ "| datafusion | public | physical | BASE TABLE | |",+ "| datafusion | public | query | VIEW | |",+ "| datafusion | public | temp | LOCAL TEMPORARY | |",+ "+---------------+--------------------+------------+-----------------+------------+",];assert_batches_sorted_eq!(expected, &result);}@@ -273,13 +273,13 @@ async fn information_schema_show_tables() {let result = plan_and_collect(&ctx, "SHOW TABLES").await.unwrap();let expected = vec![- "+---------------+--------------------+------------+------------+",- "| table_catalog | table_schema | table_name | table_type |",- "+---------------+--------------------+------------+------------+",- "| datafusion | information_schema | columns | VIEW |",- "| datafusion | information_schema | tables | VIEW |",- "| datafusion | public | t | BASE TABLE |",- "+---------------+--------------------+------------+------------+",+ "+---------------+--------------------+------------+------------+------------+",+ "| table_catalog | table_schema | table_name | table_type | definition |",+ "+---------------+--------------------+------------+------------+------------+",+ "| datafusion | information_schema | columns | VIEW | |",+ "| datafusion | information_schema | tables | VIEW | |",+ "| datafusion | public | t | BASE TABLE | |",+ "+---------------+--------------------+------------+------------+------------+",];assert_batches_sorted_eq!(expected, &result);@@ -528,6 +528,75 @@ async fn information_schema_columns() {assert_batches_sorted_eq!(expected, &result);}+#[tokio::test]+async fn show_create_view() {+ let ctx =+ SessionContext::with_config(SessionConfig::new().with_information_schema(true));+ let table_sql = "CREATE TABLE abc AS VALUES (1,2,3), (4,5,6)";+ plan_and_collect(&ctx, table_sql).await.unwrap();+ let view_sql = "CREATE VIEW xyz AS SELECT * FROM abc";+ plan_and_collect(&ctx, view_sql).await.unwrap();++ let results_sql = "SHOW CREATE TABLE xyz";+ let results = plan_and_collect(&ctx, results_sql).await.unwrap();+ assert_eq!(results[0].num_rows(), 1);++ let expected = vec![+ "+------+--------------------------------------+",+ "| name | definition |",+ "+------+--------------------------------------+",+ "| xyz | CREATE VIEW xyz AS SELECT * FROM abc |",+ "+------+--------------------------------------+",+ ];+ assert_batches_eq!(expected, &results);+}++#[tokio::test]+async fn show_create_view_in_catalog() {+ let ctx =+ SessionContext::with_config(SessionConfig::new().with_information_schema(true));+ let table_sql = "CREATE TABLE abc AS VALUES (1,2,3), (4,5,6)";+ plan_and_collect(&ctx, table_sql).await.unwrap();+ let schema_sql = "CREATE SCHEMA test";+ plan_and_collect(&ctx, schema_sql).await.unwrap();+ let view_sql = "CREATE VIEW test.xyz AS SELECT * FROM abc";+ plan_and_collect(&ctx, view_sql).await.unwrap();++ let result_sql = "SHOW CREATE TABLE test.xyz";+ let results = plan_and_collect(&ctx, result_sql).await.unwrap();+ assert_eq!(results[0].num_rows(), 1);++ let expected = vec![+ "+----------+-------------------------------------------+",+ "| name | definition |",+ "+----------+-------------------------------------------+",+ "| test.xyz | CREATE VIEW test.xyz AS SELECT * FROM abc |",+ "+----------+-------------------------------------------+",+ ];+ assert_batches_eq!(expected, &results);+}++#[tokio::test]+async fn show_create_table() {+ let ctx =+ SessionContext::with_config(SessionConfig::new().with_information_schema(true));+ let table_sql = "CREATE TABLE abc AS VALUES (1,2,3), (4,5,6)";+ plan_and_collect(&ctx, table_sql).await.unwrap();++ let result_sql = "SHOW CREATE TABLE abc";+ let results = plan_and_collect(&ctx, result_sql).await.unwrap();++ let expected = vec![+ "+------+------------+",+ "| name | definition |",+ "+------+------------+",+ "| abc | |",+ "+------+------------+",+ ];++ assert_batches_eq!(expected, &results);+}+/// Execute SQL and return resultsasync fn plan_and_collect(ctx: &SessionContext, sql: &str) -> Result<Vec<RecordBatch>> {ctx.sql(sql).await?.collect().awaitdiff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex 5e7e0cfc17..685225381a 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -1101,6 +1101,8 @@ pub struct CreateView {pub input: Arc<LogicalPlan>,/// Option to not error if table already existspub or_replace: bool,+ /// SQL used to create the view, if available+ pub definition: Option<String>,}/// Types of files to parse as DataFramesdiff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rsindex 707316fa44..8d7f554170 100644--- a/datafusion/expr/src/utils.rs+++ b/datafusion/expr/src/utils.rs@@ -461,11 +461,15 @@ pub fn from_plan(or_replace: *or_replace,})),LogicalPlan::CreateView(CreateView {- name, or_replace, ..+ name,+ or_replace,+ definition,+ ..}) => Ok(LogicalPlan::CreateView(CreateView {input: Arc::new(inputs[0].clone()),name: name.clone(),or_replace: *or_replace,+ definition: definition.clone(),})),LogicalPlan::Extension(e) => Ok(LogicalPlan::Extension(Extension {node: e.node.from_template(expr, inputs),diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.protoindex b3d31400c9..8896316fa0 100644--- a/datafusion/proto/proto/datafusion.proto+++ b/datafusion/proto/proto/datafusion.proto@@ -171,6 +171,7 @@ message CreateViewNode {string name = 1;LogicalPlanNode input = 2;bool or_replace = 3;+ string definition = 4;}// a node containing data for defining values list. unlike in SQL where it's two dimensional, herediff --git a/datafusion/proto/src/logical_plan.rs b/datafusion/proto/src/logical_plan.rsindex 3ea3d3f029..4010bd72c9 100644--- a/datafusion/proto/src/logical_plan.rs+++ b/datafusion/proto/src/logical_plan.rs@@ -515,11 +515,17 @@ impl AsLogicalPlan for LogicalPlanNode {"Protobuf deserialization error, CreateViewNode has invalid LogicalPlan input.",)))?.try_into_logical_plan(ctx, extension_codec)?;+ let definition = if !create_view.definition.is_empty() {+ Some(create_view.definition.clone())+ } else {+ None+ };Ok(LogicalPlan::CreateView(CreateView {name: create_view.name.clone(),input: Arc::new(plan),or_replace: create_view.or_replace,+ definition,}))}LogicalPlanType::CreateCatalogSchema(create_catalog_schema) => {@@ -1073,6 +1079,7 @@ impl AsLogicalPlan for LogicalPlanNode {name,input,or_replace,+ definition,}) => Ok(protobuf::LogicalPlanNode {logical_plan_type: Some(LogicalPlanType::CreateView(Box::new(protobuf::CreateViewNode {@@ -1082,6 +1089,7 @@ impl AsLogicalPlan for LogicalPlanNode {extension_codec,)?)),or_replace: *or_replace,+ definition: definition.clone().unwrap_or_else(|| "".to_string()),},))),}),diff --git a/datafusion/sql/src/planner.rs b/datafusion/sql/src/planner.rsindex 9452d21681..250b4e9c83 100644--- a/datafusion/sql/src/planner.rs+++ b/datafusion/sql/src/planner.rs@@ -60,8 +60,8 @@ 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,- ShowStatementFilter, TableFactor, TableWithJoins, TrimWhereField, UnaryOperator,- Value, Values as SQLValues,+ ShowCreateObject, ShowStatementFilter, TableFactor, TableWithJoins, TrimWhereField,+ UnaryOperator, Value, Values as SQLValues,};use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};use sqlparser::ast::{ObjectType, OrderByExpr, Statement};@@ -145,8 +145,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {}/// Generate a logical plan from an SQL statement- pub fn sql_statement_to_plan(&self, sql: Statement) -> Result<LogicalPlan> {- match sql {+ pub fn sql_statement_to_plan(&self, statement: Statement) -> Result<LogicalPlan> {+ let sql = Some(statement.to_string());+ match statement {Statement::Explain {verbose,statement,@@ -192,12 +193,19 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {name: name.to_string(),input: Arc::new(plan),or_replace,+ definition: sql,}))}Statement::CreateTable { .. } => Err(DataFusionError::NotImplemented("Only `CREATE TABLE table_name AS SELECT ...` statement is supported".to_string(),)),+ Statement::ShowCreate { obj_type, obj_name } => match obj_type {+ ShowCreateObject::Table => self.show_create_table_to_plan(&obj_name),+ _ => Err(DataFusionError::NotImplemented(+ "Only `SHOW CREATE TABLE ...` statement is supported".to_string(),+ )),+ },Statement::CreateSchema {schema_name,if_not_exists,@@ -2342,8 +2350,8 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {let variable = ObjectName(variable.to_vec()).to_string();if variable.as_str().eq_ignore_ascii_case("tables") {if self.has_table("information_schema", "tables") {- let mut rewrite =- DFParser::parse_sql("SELECT * FROM information_schema.tables;")?;+ let query = "SELECT * FROM information_schema.tables;";+ let mut rewrite = DFParser::parse_sql(query)?;assert_eq!(rewrite.len(), 1);self.statement_to_plan(rewrite.pop_front().unwrap())} else {@@ -2416,6 +2424,46 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {self.statement_to_plan(rewrite.pop_front().unwrap())}+ fn show_create_table_to_plan(+ &self,+ sql_table_name: &ObjectName,+ ) -> Result<LogicalPlan> {+ if !self.has_table("information_schema", "tables") {+ return Err(DataFusionError::Plan(+ "SHOW CREATE TABLE is not supported unless information_schema is enabled"+ .to_string(),+ ));+ }+ let table_name = normalize_sql_object_name(sql_table_name);+ let table_ref: TableReference = table_name.as_str().into();++ if let Err(e) = self.schema_provider.get_table_provider(table_ref) {+ return Err(e);+ }++ // Figure out the where clause+ let columns = vec!["table_name", "table_schema", "table_catalog"].into_iter();+ let where_clause = sql_table_name+ .0+ .iter()+ .rev()+ .zip(columns)+ .map(|(ident, column_name)| {+ format!(r#"{} = '{}'"#, column_name, normalize_ident(ident))+ })+ .collect::<Vec<_>>()+ .join(" AND ");++ let query = format!(+ "SELECT '{}' as name, definition FROM information_schema.tables WHERE {}",+ table_name, where_clause+ );++ let mut rewrite = DFParser::parse_sql(&query)?;+ assert_eq!(rewrite.len(), 1);+ self.statement_to_plan(rewrite.pop_front().unwrap())+ }+/// Return true if there is a table provider available for "schema.table"fn has_table(&self, schema: &str, table: &str) -> bool {let tables_reference = TableReference::Partial { schema, table };