Skip to content

Apache DataFusion SQL Query Engine

Infer prepared statement parameter types (#4701)

Brent Gardnere6a050058bd7
diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rs
index 7af6849ffe..a78808b26c 100644
--- a/datafusion/expr/src/expr.rs
+++ b/datafusion/expr/src/expr.rs
@@ -218,7 +218,7 @@ pub enum Expr {
/// The identifier of the parameter (e.g, $1 or $foo)
id: String,
/// The type the parameter will be filled in with
- data_type: DataType,
+ data_type: Option<DataType>,
},
}
diff --git a/datafusion/expr/src/expr_schema.rs b/datafusion/expr/src/expr_schema.rs
index 782f23c7c0..4418c4b798 100644
--- a/datafusion/expr/src/expr_schema.rs
+++ b/datafusion/expr/src/expr_schema.rs
@@ -24,7 +24,7 @@ use crate::type_coercion::binary::binary_operator_data_type;
use crate::{aggregate_function, function, window_function};
use arrow::compute::can_cast_types;
use arrow::datatypes::DataType;
-use datafusion_common::{DFField, DFSchema, DataFusionError, ExprSchema, Result};
+use datafusion_common::{Column, DFField, DFSchema, DataFusionError, ExprSchema, Result};
/// trait to allow expr to typable with respect to a schema
pub trait ExprSchemable {
@@ -56,9 +56,14 @@ impl ExprSchemable for Expr {
/// (e.g. `[utf8] + [bool]`).
fn get_type<S: ExprSchema>(&self, schema: &S) -> Result<DataType> {
match self {
- Expr::Alias(expr, _)
- | Expr::Sort(Sort { expr, .. })
- | Expr::Negative(expr) => expr.get_type(schema),
+ Expr::Alias(expr, name) => match &**expr {
+ Expr::Placeholder { data_type, .. } => match &data_type {
+ None => schema.data_type(&Column::from_name(name)).cloned(),
+ Some(dt) => Ok(dt.clone()),
+ },
+ _ => expr.get_type(schema),
+ },
+ Expr::Sort(Sort { expr, .. }) | Expr::Negative(expr) => expr.get_type(schema),
Expr::Column(c) => Ok(schema.data_type(c)?.clone()),
Expr::ScalarVariable(ty, _) => Ok(ty.clone()),
Expr::Literal(l) => Ok(l.get_datatype()),
@@ -128,7 +133,9 @@ impl ExprSchemable for Expr {
Expr::Like { .. } | Expr::ILike { .. } | Expr::SimilarTo { .. } => {
Ok(DataType::Boolean)
}
- Expr::Placeholder { data_type, .. } => Ok(data_type.clone()),
+ Expr::Placeholder { data_type, .. } => data_type.clone().ok_or_else(|| {
+ DataFusionError::Plan("Placeholder type could not be resolved".to_owned())
+ }),
Expr::Wildcard => Err(DataFusionError::Internal(
"Wildcard expressions are not valid in a logical query plan".to_owned(),
)),
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs
index a9e4943be5..8aa2821ee7 100644
--- a/datafusion/expr/src/logical_plan/plan.rs
+++ b/datafusion/expr/src/logical_plan/plan.rs
@@ -17,6 +17,7 @@
use crate::expr_rewriter::{ExprRewritable, ExprRewriter};
use crate::expr_visitor::inspect_expr_pre;
+use crate::expr_visitor::{ExprVisitable, ExpressionVisitor, Recursion};
///! Logical plan types
use crate::logical_plan::builder::validate_unique_names;
use crate::logical_plan::display::{GraphvizVisitor, IndentVisitor};
@@ -623,6 +624,71 @@ impl LogicalPlan {
Ok(new_plan)
}
+ /// Walk the logical plan, find any `PlaceHolder` tokens, and return a map of their IDs and DataTypes
+ pub fn get_parameter_types(
+ &self,
+ ) -> Result<HashMap<String, Option<DataType>>, DataFusionError> {
+ struct ParamTypeVisitor {
+ param_types: HashMap<String, Option<DataType>>,
+ }
+
+ struct ExprParamTypeVisitor {
+ param_types: HashMap<String, Option<DataType>>,
+ }
+
+ impl ExpressionVisitor for ExprParamTypeVisitor {
+ fn pre_visit(
+ mut self,
+ expr: &Expr,
+ ) -> datafusion_common::Result<Recursion<Self>>
+ where
+ Self: ExpressionVisitor,
+ {
+ if let Expr::Placeholder { id, data_type } = expr {
+ let prev = self.param_types.get(id);
+ match (prev, data_type) {
+ (Some(Some(prev)), Some(dt)) => {
+ if prev != dt {
+ Err(DataFusionError::Plan(format!(
+ "Conflicting types for {id}"
+ )))?;
+ }
+ }
+ (_, Some(dt)) => {
+ let _ = self.param_types.insert(id.clone(), Some(dt.clone()));
+ }
+ _ => {}
+ }
+ }
+ Ok(Recursion::Continue(self))
+ }
+ }
+
+ impl PlanVisitor for ParamTypeVisitor {
+ type Error = DataFusionError;
+
+ fn pre_visit(&mut self, plan: &LogicalPlan) -> Result<bool, Self::Error> {
+ let mut param_types = HashMap::new();
+ plan.inspect_expressions(|expr| {
+ let mut visitor = ExprParamTypeVisitor {
+ param_types: Default::default(),
+ };
+ visitor = expr.accept(visitor)?;
+ param_types.extend(visitor.param_types);
+ Ok(()) as Result<(), DataFusionError>
+ })?;
+ self.param_types.extend(param_types);
+ Ok(true)
+ }
+ }
+
+ let mut visitor = ParamTypeVisitor {
+ param_types: Default::default(),
+ };
+ self.accept(&mut visitor)?;
+ Ok(visitor.param_types)
+ }
+
/// Return an Expr with all placeholders replaced with their
/// corresponding values provided in the params_values
fn replace_placeholders_with_values(
@@ -649,7 +715,7 @@ impl LogicalPlan {
))
})?;
// check if the data type of the value matches the data type of the placeholder
- if value.get_datatype() != *data_type {
+ if Some(value.get_datatype()) != *data_type {
return Err(DataFusionError::Internal(format!(
"Placeholder value type mismatch: expected {:?}, got {:?}",
data_type,
diff --git a/datafusion/proto/src/logical_plan/from_proto.rs b/datafusion/proto/src/logical_plan/from_proto.rs
index f9ded9237a..6e772e7c84 100644
--- a/datafusion/proto/src/logical_plan/from_proto.rs
+++ b/datafusion/proto/src/logical_plan/from_proto.rs
@@ -1325,13 +1325,13 @@ pub fn parse_expr(
)))
}
ExprType::Placeholder(PlaceholderNode { id, data_type }) => match data_type {
- None => {
- let message = format!("Protobuf deserialization error: data type must be provided for the placeholder {id}");
- Err(proto_error(message))
- }
+ None => Ok(Expr::Placeholder {
+ id: id.clone(),
+ data_type: None,
+ }),
Some(data_type) => Ok(Expr::Placeholder {
id: id.clone(),
- data_type: data_type.try_into()?,
+ data_type: Some(data_type.try_into()?),
}),
},
}
diff --git a/datafusion/proto/src/logical_plan/to_proto.rs b/datafusion/proto/src/logical_plan/to_proto.rs
index 7fe380566f..cd96cd97d6 100644
--- a/datafusion/proto/src/logical_plan/to_proto.rs
+++ b/datafusion/proto/src/logical_plan/to_proto.rs
@@ -892,8 +892,17 @@ impl TryFrom<&Expr> for protobuf::LogicalExprNode {
.collect::<Result<Vec<_>, Self::Error>>()?,
})),
},
- Expr::Placeholder{ id, data_type } => Self {
- expr_type: Some(ExprType::Placeholder(PlaceholderNode { id: id.clone(), data_type: Some(data_type.try_into()?) })),
+ Expr::Placeholder{ id, data_type } => {
+ let data_type = match data_type {
+ Some(data_type) => Some(data_type.try_into()?),
+ None => None,
+ };
+ Self {
+ expr_type: Some(ExprType::Placeholder(PlaceholderNode {
+ id: id.clone(),
+ data_type,
+ })),
+ }
},
Expr::QualifiedWildcard { .. } | Expr::TryCast { .. } =>
diff --git a/datafusion/sql/src/expr/mod.rs b/datafusion/sql/src/expr/mod.rs
index f397b82c4e..9ddd51076d 100644
--- a/datafusion/sql/src/expr/mod.rs
+++ b/datafusion/sql/src/expr/mod.rs
@@ -29,6 +29,7 @@ use crate::planner::{ContextProvider, PlannerContext, SqlToRel};
use crate::utils::normalize_ident;
use arrow_schema::DataType;
use datafusion_common::{Column, DFSchema, DataFusionError, Result, ScalarValue};
+use datafusion_expr::expr_rewriter::{ExprRewritable, ExprRewriter};
use datafusion_expr::{
col, expr, lit, AggregateFunction, Between, BinaryExpr, BuiltinScalarFunction, Cast,
Expr, ExprSchemable, GetIndexedField, Like, Operator, TryCast,
@@ -76,6 +77,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
let mut expr = self.sql_expr_to_logical_expr(sql, schema, planner_context)?;
expr = self.rewrite_partial_qualifier(expr, schema);
self.validate_schema_satisfies_exprs(schema, &[expr.clone()])?;
+ let expr = infer_placeholder_types(expr, schema.clone())?;
Ok(expr)
}
@@ -496,6 +498,52 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
}
}
+/// Find all `PlaceHolder` tokens in a logical plan, and try to infer their type from context
+fn infer_placeholder_types(expr: Expr, schema: DFSchema) -> Result<Expr> {
+ struct PlaceholderReplacer {
+ schema: DFSchema,
+ }
+
+ impl ExprRewriter for PlaceholderReplacer {
+ fn mutate(&mut self, expr: Expr) -> Result<Expr> {
+ let expr = match expr {
+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
+ let left = (*left).clone();
+ let right = (*right).clone();
+ let lt = left.get_type(&self.schema);
+ let rt = right.get_type(&self.schema);
+ let left = match (&left, rt) {
+ (Expr::Placeholder { id, data_type }, Ok(dt)) => {
+ Expr::Placeholder {
+ id: id.clone(),
+ data_type: Some(data_type.clone().unwrap_or(dt)),
+ }
+ }
+ _ => left.clone(),
+ };
+ let right = match (&right, lt) {
+ (Expr::Placeholder { id, data_type }, Ok(dt)) => {
+ Expr::Placeholder {
+ id: id.clone(),
+ data_type: Some(data_type.clone().unwrap_or(dt)),
+ }
+ }
+ _ => right.clone(),
+ };
+ Expr::BinaryExpr(BinaryExpr {
+ left: Box::new(left),
+ op,
+ right: Box::new(right),
+ })
+ }
+ _ => expr.clone(),
+ };
+ Ok(expr)
+ }
+ }
+ expr.rewrite(&mut PlaceholderReplacer { schema })
+}
+
fn plan_key(key: SQLExpr) -> Result<ScalarValue> {
let scalar = match key {
SQLExpr::Value(Value::Number(s, _)) => ScalarValue::Int64(Some(
diff --git a/datafusion/sql/src/expr/value.rs b/datafusion/sql/src/expr/value.rs
index 86ca28d4cd..07d7c9b6c9 100644
--- a/datafusion/sql/src/expr/value.rs
+++ b/datafusion/sql/src/expr/value.rs
@@ -106,13 +106,8 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
}
};
// Check if the placeholder is in the parameter list
- if param_data_types.len() <= idx {
- return Err(DataFusionError::Internal(format!(
- "Placehoder {param} does not exist in the parameter list: {param_data_types:?}"
- )));
- }
+ let param_type = param_data_types.get(idx);
// Data type of the parameter
- let param_type = param_data_types[idx].clone();
debug!(
"type of param {} param_data_types[idx]: {:?}",
param, param_type
@@ -120,7 +115,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
Ok(Expr::Placeholder {
id: param,
- data_type: param_type,
+ data_type: param_type.cloned(),
})
}
diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rs
index eaf89afd8b..616619a1bf 100644
--- a/datafusion/sql/src/statement.rs
+++ b/datafusion/sql/src/statement.rs
@@ -25,8 +25,8 @@ use crate::planner::{
use arrow_schema::DataType;
use datafusion_common::parsers::CompressionTypeVariant;
use datafusion_common::{
- Column, DFSchema, DFSchemaRef, DataFusionError, OwnedTableReference, Result,
- TableReference, ToDFSchema,
+ Column, DFSchema, DFSchemaRef, DataFusionError, ExprSchema, OwnedTableReference,
+ Result, TableReference, ToDFSchema,
};
use datafusion_expr::expr_rewriter::normalize_col_with_schemas;
use datafusion_expr::logical_plan::builder::project;
@@ -718,6 +718,22 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
let mut exprs = vec![];
for (col_name, expr) in values.into_iter() {
let expr = self.sql_to_expr(expr, &table_schema, &mut planner_context)?;
+ let expr = match expr {
+ datafusion_expr::Expr::Placeholder {
+ ref id,
+ ref data_type,
+ } => match data_type {
+ None => {
+ let dt = table_schema.data_type(&Column::from_name(&col_name))?;
+ datafusion_expr::Expr::Placeholder {
+ id: id.clone(),
+ data_type: Some(dt.clone()),
+ }
+ }
+ Some(_) => expr,
+ },
+ _ => expr,
+ };
let expr = expr.alias(col_name);
exprs.push(expr);
}
diff --git a/datafusion/sql/tests/integration_test.rs b/datafusion/sql/tests/integration_test.rs
index 2866bd9d86..8cc0f76155 100644
--- a/datafusion/sql/tests/integration_test.rs
+++ b/datafusion/sql/tests/integration_test.rs
@@ -3131,13 +3131,16 @@ fn test_prepare_statement_to_plan_panic_no_relation_and_constant_param() {
}
#[test]
-#[should_panic(
- expected = "value: Internal(\"Placehoder $2 does not exist in the parameter list: [Int32]\")"
-)]
-fn test_prepare_statement_to_plan_panic_no_data_types() {
+fn test_prepare_statement_should_infer_types() {
// only provide 1 data type while using 2 params
let sql = "PREPARE my_plan(INT) AS SELECT 1 + $1 + $2";
- logical_plan(sql).unwrap();
+ let plan = logical_plan(sql).unwrap();
+ let actual_types = plan.get_parameter_types().unwrap();
+ let expected_types = HashMap::from([
+ ("$1".to_string(), Some(DataType::Int32)),
+ ("$2".to_string(), Some(DataType::Int64)),
+ ]);
+ assert_eq!(actual_types, expected_types);
}
#[test]
@@ -3286,6 +3289,107 @@ fn test_prepare_statement_to_plan_params_as_constants() {
prepare_stmt_replace_params_quick_test(plan, param_values, expected_plan);
}
+#[test]
+fn test_prepare_statement_infer_types_from_join() {
+ let sql =
+ "SELECT id, order_id FROM person JOIN orders ON id = customer_id and age = $1";
+
+ let expected_plan = r#"
+Projection: person.id, orders.order_id
+ Inner Join: Filter: person.id = orders.customer_id AND person.age = $1
+ TableScan: person
+ TableScan: orders
+ "#
+ .trim();
+
+ let expected_dt = "[Int32]";
+ let plan = prepare_stmt_quick_test(sql, expected_plan, expected_dt);
+
+ let actual_types = plan.get_parameter_types().unwrap();
+ let expected_types = HashMap::from([("$1".to_string(), Some(DataType::Int32))]);
+ assert_eq!(actual_types, expected_types);
+
+ // replace params with values
+ let param_values = vec![ScalarValue::Int32(Some(10))];
+ let expected_plan = r#"
+Projection: person.id, orders.order_id
+ Inner Join: Filter: person.id = orders.customer_id AND person.age = Int32(10)
+ TableScan: person
+ TableScan: orders
+ "#
+ .trim();
+ let plan = plan.replace_params_with_values(&param_values).unwrap();
+
+ prepare_stmt_replace_params_quick_test(plan, param_values, expected_plan);
+}
+
+#[test]
+fn test_prepare_statement_infer_types_from_predicate() {
+ let sql = "SELECT id, age FROM person WHERE age = $1";
+
+ let expected_plan = r#"
+Projection: person.id, person.age
+ Filter: person.age = $1
+ TableScan: person
+ "#
+ .trim();
+
+ let expected_dt = "[Int32]";
+ let plan = prepare_stmt_quick_test(sql, expected_plan, expected_dt);
+
+ let actual_types = plan.get_parameter_types().unwrap();
+ let expected_types = HashMap::from([("$1".to_string(), Some(DataType::Int32))]);
+ assert_eq!(actual_types, expected_types);
+
+ // replace params with values
+ let param_values = vec![ScalarValue::Int32(Some(10))];
+ let expected_plan = r#"
+Projection: person.id, person.age
+ Filter: person.age = Int32(10)
+ TableScan: person
+ "#
+ .trim();
+ let plan = plan.replace_params_with_values(&param_values).unwrap();
+
+ prepare_stmt_replace_params_quick_test(plan, param_values, expected_plan);
+}
+
+#[test]
+fn test_prepare_statement_update_infer() {
+ let sql = "update person set age=$1 where id=$2";
+
+ let expected_plan = r#"
+Dml: op=[Update] table=[person]
+ Projection: $1 AS age, person.birth_date AS birth_date, person.first_name AS first_name, person.id AS id, person.last_name AS last_name, person.salary AS salary, person.state AS state, person.πŸ˜€ AS πŸ˜€
+ Filter: id = $2
+ TableScan: person
+ "#
+ .trim();
+
+ let expected_dt = "[Int32]";
+ let plan = prepare_stmt_quick_test(sql, expected_plan, expected_dt);
+
+ let actual_types = plan.get_parameter_types().unwrap();
+ let expected_types = HashMap::from([
+ ("$1".to_string(), Some(DataType::Int32)),
+ ("$2".to_string(), Some(DataType::UInt32)),
+ ]);
+ assert_eq!(actual_types, expected_types);
+
+ // replace params with values
+ let param_values = vec![ScalarValue::Int32(Some(42)), ScalarValue::UInt32(Some(1))];
+ let expected_plan = r#"
+Dml: op=[Update] table=[person]
+ Projection: Int32(42) AS age, person.birth_date AS birth_date, person.first_name AS first_name, person.id AS id, person.last_name AS last_name, person.salary AS salary, person.state AS state, person.πŸ˜€ AS πŸ˜€
+ Filter: id = UInt32(1)
+ TableScan: person
+ "#
+ .trim();
+ let plan = plan.replace_params_with_values(&param_values).unwrap();
+
+ prepare_stmt_replace_params_quick_test(plan, param_values, expected_plan);
+}
+
#[test]
fn test_prepare_statement_to_plan_one_param() {
let sql = "PREPARE my_plan(INT) AS SELECT id, age FROM person WHERE age = $1";