Skip to content

Apache DataFusion SQL Query Engine

Add statement helper command to cli (#1285)

Matthew Turner42f8ab1e4451
diff --git a/datafusion-cli/src/command.rs b/datafusion-cli/src/command.rs
index 94d7ca3c5e..3b4d1c566a 100644
--- a/datafusion-cli/src/command.rs
+++ b/datafusion-cli/src/command.rs
@@ -18,6 +18,7 @@
//! Command within CLI
use crate::context::Context;
+use crate::functions::{display_all_functions, Function};
use crate::print_options::PrintOptions;
use datafusion::arrow::array::{ArrayRef, StringArray};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
@@ -34,6 +35,8 @@ pub enum Command {
Help,
ListTables,
DescribeTable(String),
+ ListFunctions,
+ SearchFunctions(String),
}
impl Command {
@@ -64,6 +67,17 @@ impl Command {
Self::Quit => Err(DataFusionError::Execution(
"Unexpected quit, this should be handled outside".into(),
)),
+ Self::ListFunctions => display_all_functions(),
+ Self::SearchFunctions(function) => {
+ if let Ok(func) = function.parse::<Function>() {
+ let details = func.function_details()?;
+ println!("{}", details);
+ Ok(())
+ } else {
+ let msg = format!("{} is not a supported function", function);
+ Err(DataFusionError::Execution(msg))
+ }
+ }
}
}
@@ -73,15 +87,19 @@ impl Command {
Self::ListTables => ("\\d", "list tables"),
Self::DescribeTable(_) => ("\\d name", "describe table"),
Self::Help => ("\\?", "help"),
+ Self::ListFunctions => ("\\h", "function list"),
+ Self::SearchFunctions(_) => ("\\h function", "search function"),
}
}
}
-const ALL_COMMANDS: [Command; 4] = [
+const ALL_COMMANDS: [Command; 6] = [
Command::ListTables,
Command::DescribeTable(String::new()),
Command::Quit,
Command::Help,
+ Command::ListFunctions,
+ Command::SearchFunctions(String::new()),
];
fn all_commands_info() -> RecordBatch {
@@ -117,6 +135,8 @@ impl FromStr for Command {
("d", None) => Self::ListTables,
("d", Some(name)) => Self::DescribeTable(name.into()),
("?", None) => Self::Help,
+ ("h", None) => Self::ListFunctions,
+ ("h", Some(function)) => Self::SearchFunctions(function.into()),
_ => return Err(()),
})
}
diff --git a/datafusion-cli/src/functions.rs b/datafusion-cli/src/functions.rs
new file mode 100644
index 0000000000..2372e648d0
--- /dev/null
+++ b/datafusion-cli/src/functions.rs
@@ -0,0 +1,198 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Functions that are query-able and searchable via the `\h` command
+use arrow::array::StringArray;
+use arrow::datatypes::{DataType, Field, Schema};
+use arrow::record_batch::RecordBatch;
+use arrow::util::pretty::pretty_format_batches;
+use datafusion::error::{DataFusionError, Result};
+use std::fmt;
+use std::str::FromStr;
+use std::sync::Arc;
+
+#[derive(Debug)]
+pub enum Function {
+ Select,
+ Explain,
+ Show,
+ CreateTable,
+ CreateTableAs,
+ Insert,
+ DropTable,
+}
+
+const ALL_FUNCTIONS: [Function; 7] = [
+ Function::CreateTable,
+ Function::CreateTableAs,
+ Function::DropTable,
+ Function::Explain,
+ Function::Insert,
+ Function::Select,
+ Function::Show,
+];
+
+impl Function {
+ pub fn function_details(&self) -> Result<&str> {
+ let details = match self {
+ Function::Select => {
+ r#"
+Command: SELECT
+Description: retrieve rows from a table or view
+Syntax:
+SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
+ [ * | expression [ [ AS ] output_name ] [, ...] ]
+ [ FROM from_item [, ...] ]
+ [ WHERE condition ]
+ [ GROUP BY [ ALL | DISTINCT ] grouping_element [, ...] ]
+ [ HAVING condition ]
+ [ WINDOW window_name AS ( window_definition ) [, ...] ]
+ [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ]
+ [ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ]
+ [ LIMIT { count | ALL } ]
+ [ OFFSET start [ ROW | ROWS ] ]
+
+where from_item can be one of:
+
+ [ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
+ [ TABLESAMPLE sampling_method ( argument [, ...] ) [ REPEATABLE ( seed ) ] ]
+ [ LATERAL ] ( select ) [ AS ] alias [ ( column_alias [, ...] ) ]
+ with_query_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
+ [ LATERAL ] function_name ( [ argument [, ...] ] )
+ [ WITH ORDINALITY ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
+ [ LATERAL ] function_name ( [ argument [, ...] ] ) [ AS ] alias ( column_definition [, ...] )
+ [ LATERAL ] function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] )
+ [ LATERAL ] ROWS FROM( function_name ( [ argument [, ...] ] ) [ AS ( column_definition [, ...] ) ] [, ...] )
+ [ WITH ORDINALITY ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
+ from_item [ NATURAL ] join_type from_item [ ON join_condition | USING ( join_column [, ...] ) [ AS join_using_alias ] ]
+
+and grouping_element can be one of:
+
+ ( )
+ expression
+ ( expression [, ...] )
+
+and with_query is:
+
+ with_query_name [ ( column_name [, ...] ) ] AS [ [ NOT ] MATERIALIZED ] ( select | values | insert | update | delete )
+
+TABLE [ ONLY ] table_name [ * ]"#
+ }
+ Function::Explain => {
+ r#"
+Command: EXPLAIN
+Description: show the execution plan of a statement
+Syntax:
+EXPLAIN [ ANALYZE ] statement
+"#
+ }
+ Function::Show => {
+ r#"
+Command: SHOW
+Description: show the value of a run-time parameter
+Syntax:
+SHOW name
+"#
+ }
+ Function::CreateTable => {
+ r#"
+Command: CREATE TABLE
+Description: define a new table
+Syntax:
+CREATE [ EXTERNAL ] TABLE table_name ( [
+ { column_name data_type }
+ [, ... ]
+] )
+"#
+ }
+ Function::CreateTableAs => {
+ r#"
+Command: CREATE TABLE AS
+Description: define a new table from the results of a query
+Syntax:
+CREATE TABLE table_name
+ [ (column_name [, ...] ) ]
+ AS query
+ [ WITH [ NO ] DATA ]
+"#
+ }
+ Function::Insert => {
+ r#"
+Command: INSERT
+Description: create new rows in a table
+Syntax:
+INSERT INTO table_name [ ( column_name [, ...] ) ]
+ { VALUES ( { expression } [, ...] ) [, ...] }
+"#
+ }
+ Function::DropTable => {
+ r#"
+Command: DROP TABLE
+Description: remove a table
+Syntax:
+DROP TABLE [ IF EXISTS ] name [, ...]
+"#
+ }
+ };
+ Ok(details)
+ }
+}
+
+impl FromStr for Function {
+ type Err = ();
+
+ fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
+ Ok(match s.trim().to_uppercase().as_str() {
+ "SELECT" => Self::Select,
+ "EXPLAIN" => Self::Explain,
+ "SHOW" => Self::Show,
+ "CREATE TABLE" => Self::CreateTable,
+ "CREATE TABLE AS" => Self::CreateTableAs,
+ "INSERT" => Self::Insert,
+ "DROP TABLE" => Self::DropTable,
+ _ => return Err(()),
+ })
+ }
+}
+
+impl fmt::Display for Function {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ Function::Select => write!(f, "SELECT"),
+ Function::Explain => write!(f, "EXPLAIN"),
+ Function::Show => write!(f, "SHOW"),
+ Function::CreateTable => write!(f, "CREATE TABLE"),
+ Function::CreateTableAs => write!(f, "CREATE TABLE AS"),
+ Function::Insert => write!(f, "INSERT"),
+ Function::DropTable => write!(f, "DROP TABLE"),
+ }
+ }
+}
+
+pub fn display_all_functions() -> Result<()> {
+ println!("Available help:");
+ let array = StringArray::from(
+ ALL_FUNCTIONS
+ .iter()
+ .map(|f| format!("{}", f))
+ .collect::<Vec<String>>(),
+ );
+ let schema = Schema::new(vec![Field::new("Function", DataType::Utf8, false)]);
+ let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(array)])?;
+ println!("{}", pretty_format_batches(&[batch]).unwrap());
+ Ok(())
+}
diff --git a/datafusion-cli/src/lib.rs b/datafusion-cli/src/lib.rs
index e9c6c25a1c..b2bcdd3e48 100644
--- a/datafusion-cli/src/lib.rs
+++ b/datafusion-cli/src/lib.rs
@@ -22,6 +22,7 @@ pub const DATAFUSION_CLI_VERSION: &str = env!("CARGO_PKG_VERSION");
pub mod command;
pub mod context;
pub mod exec;
+pub mod functions;
pub mod helper;
pub mod print_format;
pub mod print_options;