Skip to content

Apache DataFusion SQL Query Engine

Allow usage of table functions in relations (#16571)

Artem Osipov649a36f3d4bc
diff --git a/datafusion/sql/src/relation/mod.rs b/datafusion/sql/src/relation/mod.rs
index 1c5a8ff4d2..aa37d74fd4 100644
--- a/datafusion/sql/src/relation/mod.rs
+++ b/datafusion/sql/src/relation/mod.rs
@@ -154,6 +154,35 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
"UNNEST table factor with offset is not supported yet"
);
}
+ TableFactor::Function {
+ name, args, alias, ..
+ } => {
+ let tbl_func_ref = self.object_name_to_table_reference(name)?;
+ let schema = planner_context
+ .outer_query_schema()
+ .cloned()
+ .unwrap_or_else(DFSchema::empty);
+ let func_args = args
+ .into_iter()
+ .map(|arg| match arg {
+ FunctionArg::Unnamed(FunctionArgExpr::Expr(expr))
+ | FunctionArg::Named {
+ arg: FunctionArgExpr::Expr(expr),
+ ..
+ } => {
+ self.sql_expr_to_logical_expr(expr, &schema, planner_context)
+ }
+ _ => plan_err!("Unsupported function argument: {arg:?}"),
+ })
+ .collect::<Result<Vec<Expr>>>()?;
+ let provider = self
+ .context_provider
+ .get_table_function_source(tbl_func_ref.table(), func_args)?;
+ let plan =
+ LogicalPlanBuilder::scan(tbl_func_ref.table(), provider, None)?
+ .build()?;
+ (plan, alias)
+ }
// @todo Support TableFactory::TableFunction?
_ => {
return not_impl_err!(
diff --git a/datafusion/sqllogictest/test_files/table_functions.slt b/datafusion/sqllogictest/test_files/table_functions.slt
index e53306958c..0159abe8d0 100644
--- a/datafusion/sqllogictest/test_files/table_functions.slt
+++ b/datafusion/sqllogictest/test_files/table_functions.slt
@@ -482,3 +482,15 @@ SELECT * FROM range(DATE '2023-01-01', DATE '2023-01-02', INTERVAL '-1' DAY)
query error DataFusion error: Error during planning: range function with dates requires exactly 3 arguments
SELECT * FROM range(DATE '2023-01-01', DATE '2023-01-03')
+
+# Table function as relation
+statement ok
+CREATE OR REPLACE TABLE json_table (c INT) AS VALUES (1), (2);
+
+query II
+SELECT c, f.* FROM json_table, LATERAL generate_series(1,2) f;
+----
+1 1
+1 2
+2 1
+2 2