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

Implement SHOW FUNCTIONS #12266

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions datafusion/core/tests/sql/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ pub mod explain_analyze;
pub mod joins;
mod path_partition;
pub mod select;
pub mod show;
mod sql_api;

async fn register_aggregate_csv_by_sql(ctx: &SessionContext) {
Expand Down
44 changes: 44 additions & 0 deletions datafusion/core/tests/sql/show.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// 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.

use super::*;
use std::collections::HashSet;

#[tokio::test]
async fn test_show_functions() {
let ctx = SessionContext::new();
let result = execute(&ctx, "SHOW FUNCTIONS").await;
assert!(!result.is_empty(), "result is empty");
let names: HashSet<String> = result
.into_iter()
.map(|mut row| {
assert_eq!(row.len(), 1);
row.remove(0)
})
.collect();
[
"array_distinct",
"to_unixtime",
"covar_pop",
"max",
"concat",
]
.into_iter()
.for_each(|name| {
assert!(names.contains(name), "{} not found in {:?}", name, names);
});
}
43 changes: 39 additions & 4 deletions datafusion/sql/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
// specific language governing permissions and limitations
// under the License.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::iter;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;
Expand All @@ -29,7 +30,7 @@ use crate::planner::{
};
use crate::utils::normalize_ident;

use arrow_schema::{DataType, Fields};
use arrow_schema::{DataType, Field, Fields, Schema};
use datafusion_common::parsers::CompressionTypeVariant;
use datafusion_common::{
exec_err, not_impl_err, plan_datafusion_err, plan_err, schema_err,
Expand All @@ -43,15 +44,15 @@ use datafusion_expr::logical_plan::builder::project;
use datafusion_expr::logical_plan::DdlStatement;
use datafusion_expr::utils::expr_to_columns;
use datafusion_expr::{
cast, col, Analyze, CreateCatalog, CreateCatalogSchema,
cast, col, lit, Analyze, BuiltInWindowFunction, CreateCatalog, CreateCatalogSchema,
CreateExternalTable as PlanCreateExternalTable, CreateFunction, CreateFunctionBody,
CreateIndex as PlanCreateIndex, CreateMemoryTable, CreateView, DescribeTable,
DmlStatement, DropCatalogSchema, DropFunction, DropTable, DropView, EmptyRelation,
Explain, Expr, ExprSchemable, Filter, LogicalPlan, LogicalPlanBuilder,
OperateFunctionArg, PlanType, Prepare, SetVariable, SortExpr,
Statement as PlanStatement, ToStringifiedPlan, TransactionAccessMode,
TransactionConclusion, TransactionEnd, TransactionIsolationLevel, TransactionStart,
Volatility, WriteOp,
Values, Volatility, WriteOp,
};
use sqlparser::ast;
use sqlparser::ast::{
Expand All @@ -62,6 +63,7 @@ use sqlparser::ast::{
TableWithJoins, TransactionMode, UnaryOperator, Value,
};
use sqlparser::parser::ParserError::ParserError;
use strum::IntoEnumIterator;

fn ident_to_string(ident: &Ident) -> String {
normalize_ident(ident.to_owned())
Expand Down Expand Up @@ -469,6 +471,8 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
filter,
} => self.show_columns_to_plan(extended, full, table_name, filter),

Statement::ShowFunctions { filter } => self.show_functions_to_plan(filter),

Statement::Insert(Insert {
or,
into,
Expand Down Expand Up @@ -1588,6 +1592,37 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
self.statement_to_plan(rewrite.pop_front().unwrap()) // length of rewrite is 1
}

fn show_functions_to_plan(
&self,
filter: Option<ShowStatementFilter>,
) -> Result<LogicalPlan> {
if filter.is_some() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are we planning to apply the filter in future?

For example for SHOW now it is possible to display specific parameter like

show datafusion.execution.batch_size

I think it would be interesting to show the function by filter so ther user can get the name and ideally the signature.

Later we can use this metadata table to obtain correct signature in unified way instead of hardcoding signatures like now

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that is a good idea.
however, i think sqlparser-rs has the syntax potentialy mixed up.
the filter syntax is borrowed from MySQL while the statement itself isn't borrowed from there, creating a unique mix. see apache/datafusion-sqlparser-rs#1399
it would be best to resolve this (either fix or close the issue) before jumping on the filtering support

// See https://github.com/sqlparser-rs/sqlparser-rs/issues/1399 before adding support for filter.
return plan_err!("SHOW FUNCTIONS with WHERE or LIKE is not supported");
}

let names = iter::empty::<String>()
.chain(self.context_provider.udf_names())
.chain(self.context_provider.udaf_names())
.chain(BuiltInWindowFunction::iter().map(|func| func.to_string()))
.chain(self.context_provider.udwf_names())
// TODO list table functions
.map(|name| name.to_lowercase())
.collect::<BTreeSet<_>>();

Ok(LogicalPlan::Values(Values {
schema: Arc::new(
DFSchema::try_from(Schema::new(vec![Field::new(
"function_name",
DataType::Utf8,
false,
)]))
.unwrap(),
),
values: names.into_iter().map(|name| vec![lit(name)]).collect(),
}))
}

/// 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 {
Expand Down