Apache DataFusion SQL Query Engine
fix: reject invalid placeholders in CREATE FUNCTION bodies at definition time (#25039)
Ethan Tran14aa185dd23d
diff --git a/datafusion/core/tests/user_defined/user_defined_scalar_functions.rs b/datafusion/core/tests/user_defined/user_defined_scalar_functions.rsindex b188f95417..c5fd2e1de1 100644--- a/datafusion/core/tests/user_defined/user_defined_scalar_functions.rs+++ b/datafusion/core/tests/user_defined/user_defined_scalar_functions.rs@@ -1112,23 +1112,6 @@ async fn create_scalar_function_from_sql_statement() -> Result<()> {"#;assert!(ctx.sql(bad_definition_sql).await.is_err());- // FIXME: Definitions with invalid placeholders are allowed, fail at runtime- let bad_expression_sql = r#"- CREATE FUNCTION better_add(DOUBLE, DOUBLE)- RETURNS DOUBLE- RETURN $1 + $3- "#;- assert!(ctx.sql(bad_expression_sql).await.is_ok());-- let err = ctx- .sql("select better_add(2.0, 2.0)")- .await?- .collect()- .await- .expect_err("unknown placeholder");- let expected = "Optimizer rule 'simplify_expressions' failed\ncaused by\nExecution error: Invalid placeholder, out of range: $3";- assert!(expected.starts_with(&err.strip_backtrace()));-Ok(())}diff --git a/datafusion/expr/src/logical_plan/ddl.rs b/datafusion/expr/src/logical_plan/ddl.rsindex 5719031c84..81d6fac189 100644--- a/datafusion/expr/src/logical_plan/ddl.rs+++ b/datafusion/expr/src/logical_plan/ddl.rs@@ -11,13 +11,15 @@ use std::{hash::{Hash, Hasher},};-use crate::expr::Sort;+use crate::expr::{Exists, InSubquery, SetComparison, Sort};#[cfg(not(feature = "sql"))]use crate::sql::Ident;use arrow::datatypes::DataType;-use datafusion_common::tree_node::{Transformed, TreeNodeContainer, TreeNodeRecursion};+use datafusion_common::tree_node::{+ Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion,+};use datafusion_common::{- Constraints, DFSchema, DFSchemaRef, Result, SchemaReference, TableReference,+ Constraints, DFSchema, DFSchemaRef, Result, SchemaReference, TableReference, plan_err,};#[cfg(feature = "sql")]use sqlparser::ast::Ident;@@ -904,6 +906,95 @@ pub struct CreateFunction {pub schema: DFSchemaRef,}+impl CreateFunction {+ /// Creates a function definition, validating placeholders in its body and+ /// argument defaults, including expressions inside subqueries.+ ///+ /// Placeholders must be positional (`$1`, `$2`, ...) and reference a+ /// declared argument. SQL argument names must be resolved before calling+ /// this constructor.+ pub fn try_new(+ or_replace: bool,+ temporary: bool,+ name: String,+ args: Option<Vec<OperateFunctionArg>>,+ return_type: Option<DataType>,+ params: CreateFunctionBody,+ ) -> Result<Self> {+ let arg_count = args.as_ref().map_or(0, |declared| declared.len());+ for default_expr in args+ .iter()+ .flatten()+ .filter_map(|arg| arg.default_expr.as_ref())+ {+ validate_function_body_placeholders(default_expr, arg_count)?;+ }+ if let Some(body) = ¶ms.function_body {+ validate_function_body_placeholders(body, arg_count)?;+ }+ Ok(Self {+ or_replace,+ temporary,+ name,+ args,+ return_type,+ params,+ schema: DFSchemaRef::new(DFSchema::empty()),+ })+ }+}++/// Rejects placeholders in a `CREATE FUNCTION` body or argument default+/// expression that do not reference a declared argument (e.g. `$3` for a+/// two-argument function) at definition time, instead of deferring the error+/// to function invocation.+fn validate_function_body_placeholders(expr: &Expr, arg_count: usize) -> Result<()> {+ expr.apply(|expr| {+ if let Expr::Placeholder(placeholder) = expr {+ match placeholder+ .id+ .strip_prefix('$')+ .and_then(|id| id.parse::<usize>().ok())+ {+ // In range, e.g. `$2` with two declared arguments+ Some(idx) if (1..=arg_count).contains(&idx) => {}+ // Out of range, e.g. `$3` with two declared arguments+ Some(_) => {+ return plan_err!(+ "Invalid placeholder, out of range: {}",+ placeholder.id+ );+ }+ // Named or malformed placeholder+ None => {+ return plan_err!("Unknown placeholder: {}", placeholder.id);+ }+ }+ }+ // `Expr::apply` does not descend into subqueries, so walk their+ // plans explicitly to validate placeholders inside them+ if let Some(subquery) = match expr {+ Expr::ScalarSubquery(subquery) => Some(&subquery.subquery),+ Expr::Exists(Exists { subquery, .. }) => Some(&subquery.subquery),+ Expr::InSubquery(InSubquery { subquery, .. }) => Some(&subquery.subquery),+ Expr::SetComparison(SetComparison { subquery, .. }) => {+ Some(&subquery.subquery)+ }+ _ => None,+ } {+ // Nested subqueries are handled by this expression visitor+ subquery.apply(|plan| {+ plan.apply_expressions(|e| {+ validate_function_body_placeholders(e, arg_count)?;+ Ok(TreeNodeRecursion::Continue)+ })+ })?;+ }+ Ok(TreeNodeRecursion::Continue)+ })?;+ Ok(())+}+// Manual implementation needed because of `schema` field. Comparison excludes this field.impl PartialOrd for CreateFunction {fn partial_cmp(&self, other: &Self) -> Option<Ordering> {@@ -1074,13 +1165,69 @@ impl PartialOrd for CreateIndex {#[cfg(test)]mod test {+ use super::{CreateFunction, CreateFunctionBody, OperateFunctionArg};+ use crate::expr_fn::placeholder;use crate::{- CreateCatalog, CreateExternalCatalog, DdlStatement, DropCatalog, DropView,+ CreateCatalog, CreateExternalCatalog, DdlStatement, DropCatalog, DropView, Expr,+ LogicalPlanBuilder, Subquery,};+ use arrow::datatypes::DataType;use datafusion_common::{DFSchema, DFSchemaRef, TableReference};- use std::cmp::Ordering;- use std::collections::HashMap;- use std::sync::Arc;+ use std::{cmp::Ordering, collections::HashMap, sync::Arc};++ #[test]+ fn create_function_try_new_validates_placeholders() {+ let create = |body, default_expr| {+ CreateFunction::try_new(+ false,+ false,+ "f".to_string(),+ Some(vec![OperateFunctionArg {+ name: None,+ data_type: DataType::Int64,+ default_expr,+ }]),+ Some(DataType::Int64),+ CreateFunctionBody {+ language: None,+ behavior: None,+ function_body: body,+ },+ )+ };++ assert!(create(Some(placeholder("$1")), Some(placeholder("$1"))).is_ok());+ assert!(create(None, None).is_ok());+ for (body, default_expr) in [+ (Some(placeholder("$2")), None),+ (None, Some(placeholder("$2"))),+ ] {+ let err = create(body, default_expr).unwrap_err();+ assert_eq!(+ err.strip_backtrace(),+ "Error during planning: Invalid placeholder, out of range: $2"+ );+ }++ let mut nested_body = placeholder("$2");+ for _ in 0..16 {+ let plan = LogicalPlanBuilder::empty(true)+ .project(vec![nested_body.alias("v")])+ .unwrap()+ .build()+ .unwrap();+ nested_body = Expr::ScalarSubquery(Subquery {+ subquery: Arc::new(plan),+ outer_ref_columns: vec![],+ spans: Default::default(),+ });+ }+ let err = create(Some(nested_body), None).unwrap_err();+ assert_eq!(+ err.strip_backtrace(),+ "Error during planning: Invalid placeholder, out of range: $2"+ );+ }#[test]fn test_partial_ord() {diff --git a/datafusion/sql/src/expr/value.rs b/datafusion/sql/src/expr/value.rsindex 47c3dd7c32..e7980aee91 100644--- a/datafusion/sql/src/expr/value.rs+++ b/datafusion/sql/src/expr/value.rs@@ -142,7 +142,8 @@ impl<S: ContextProvider> SqlToRel<'_, S> {}};// Check if the placeholder is in the parameter list- // FIXME: In the CREATE FUNCTION branch, param_type = None should raise an error+ // CreateFunction::try_new validates function placeholders; types stay+ // permissive so PREPARE can defer inference to bind time.let param_type = param_data_types.get(idx).and_then(|v| v.clone());// Data type of the parameterdebug!("type of param {param} param_data_types[idx]: {param_type:?}");diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rsindex 51929aa1f4..a6564512d3 100644--- a/datafusion/sql/src/statement.rs+++ b/datafusion/sql/src/statement.rs@@ -1498,15 +1498,15 @@ impl<S: ContextProvider> SqlToRel<'_, S> {function_body,};- let statement = DdlStatement::CreateFunction(Box::new(CreateFunction {- or_replace,- temporary,- name,- return_type: return_type.map(|f| f.data_type().clone()),- args,- params,- schema: DFSchemaRef::new(DFSchema::empty()),- }));+ let statement =+ DdlStatement::CreateFunction(Box::new(CreateFunction::try_new(+ or_replace,+ temporary,+ name,+ args,+ return_type.map(|f| f.data_type().clone()),+ params,+ )?));Ok(LogicalPlan::Ddl(statement))}diff --git a/datafusion/sqllogictest/test_files/create_function.slt b/datafusion/sqllogictest/test_files/create_function.sltindex 8e3b8196a6..244a836e33 100644--- a/datafusion/sqllogictest/test_files/create_function.slt+++ b/datafusion/sqllogictest/test_files/create_function.slt@@ -9,8 +9,62 @@# Create function will fail unless a user supplied function factory is suppliedstatement error DataFusion error: Invalid or Unsupported Configuration: Function factory has not been configured+CREATE FUNCTION foo (DOUBLE) RETURNS DOUBLE RETURN $1;++# Invalid placeholders are rejected during planning, before a function+# factory is consulted (see #25038)+statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$2CREATE FUNCTION foo (DOUBLE) RETURNS DOUBLE RETURN $1 + $2;+# a zero-argument function cannot reference arguments either+statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$1+CREATE FUNCTION foo_zero () RETURNS DOUBLE RETURN $1;++# placeholders inside subqueries are validated too+statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$9+CREATE FUNCTION foo_subquery (DOUBLE) RETURNS DOUBLE RETURN $1 + (SELECT $9);++# placeholders in argument default expressions are validated too+statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$9+CREATE FUNCTION foo_default (a DOUBLE, b DOUBLE DEFAULT $9) RETURNS DOUBLE RETURN $1 + $2;++# out of range placeholder in a subquery's LIMIT clause+statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$9+CREATE FUNCTION foo_limit (DOUBLE) RETURNS BOOLEAN RETURN $1 IN (SELECT v FROM (VALUES (1.0), (2.0)) AS t(v) ORDER BY v LIMIT $9);++# Named arguments are resolved before placeholder validation+statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$3+CREATE FUNCTION foo_named (a DOUBLE, b DOUBLE) RETURNS DOUBLE RETURN $a + $3;++statement error DataFusion error: Error during planning: Unknown placeholder: \$a+CREATE FUNCTION foo_unknown () RETURNS DOUBLE RETURN $a;++# Defaults use positional placeholders+statement error DataFusion error: Error during planning: Unknown placeholder: \$a+CREATE FUNCTION foo_named_default (a DOUBLE, b DOUBLE DEFAULT $a) RETURNS DOUBLE RETURN $1 + $2;++statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$9+CREATE FUNCTION foo_exists (DOUBLE) RETURNS BOOLEAN RETURN EXISTS (SELECT $9);++statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$9+CREATE FUNCTION foo_in (DOUBLE) RETURNS BOOLEAN RETURN $1 IN (SELECT $9);++statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$9+CREATE FUNCTION foo_any (DOUBLE) RETURNS BOOLEAN RETURN $1 = ANY (SELECT $9);++statement error DataFusion error: Error during planning: Invalid placeholder, out of range: \$9+CREATE FUNCTION foo_nested (DOUBLE) RETURNS BOOLEAN RETURN EXISTS (SELECT 1 WHERE (SELECT $9) > 0.0);++# Valid definitions reach the function factory+statement error DataFusion error: Invalid or Unsupported Configuration: Function factory has not been configured+CREATE FUNCTION foo_valid (DOUBLE, DOUBLE) RETURNS DOUBLE RETURN $1 + $2;++statement error DataFusion error: Invalid or Unsupported Configuration: Function factory has not been configured+CREATE FUNCTION foo_valid_default (a DOUBLE, b DOUBLE DEFAULT $1) RETURNS DOUBLE RETURN $1 + $2;++statement error DataFusion error: Invalid or Unsupported Configuration: Function factory has not been configured+CREATE FUNCTION foo_valid_subquery (DOUBLE) RETURNS BOOLEAN RETURN $1 IN (SELECT v FROM (VALUES (1.0)) AS t(v) WHERE v > $1);+# multi-part identifiers are not supportedstatement error DataFusion error: This feature is not implemented: Qualified functions are not supportedCREATE FUNCTION foo.bar (DOUBLE) RETURNS DOUBLE RETURN $1 + $2;