Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add statement helper command to cli #1285

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion datafusion-cli/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -34,6 +35,8 @@ pub enum Command {
Help,
ListTables,
DescribeTable(String),
ListFunctions,
SearchFunctions(String),
}

impl Command {
Expand Down Expand Up @@ -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))
}
}
}
}

Expand All @@ -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 {
Expand Down Expand Up @@ -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(()),
})
}
Expand Down
198 changes: 198 additions & 0 deletions datafusion-cli/src/functions.rs
Original file line number Diff line number Diff line change
@@ -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<()> {
alamb marked this conversation as resolved.
Show resolved Hide resolved
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(())
}
1 change: 1 addition & 0 deletions datafusion-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;