Skip to content

Apache DataFusion SQL Query Engine

ARROW-9815: [Rust][DataFusion] Add a trait for looking up scalar functions by name

alambabfeeb7cf999
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index 9fbc5c63b2..5a7adaa0c2 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -28,6 +28,7 @@ use arrow::csv;
use arrow::datatypes::*;
use arrow::record_batch::RecordBatch;
+use super::physical_plan::udf::ScalarFunctionRegistry;
use crate::dataframe::DataFrame;
use crate::datasource::csv::CsvFile;
use crate::datasource::parquet::ParquetTable;
@@ -106,8 +107,8 @@ impl ExecutionContext {
pub fn with_config(config: ExecutionConfig) -> Self {
let mut ctx = Self {
state: Arc::new(Mutex::new(ExecutionContextState {
- datasources: Box::new(HashMap::new()),
- scalar_functions: Box::new(HashMap::new()),
+ datasources: HashMap::new(),
+ scalar_functions: HashMap::new(),
config,
})),
};
@@ -189,16 +190,7 @@ impl ExecutionContext {
/// Register a scalar UDF
pub fn register_udf(&mut self, f: ScalarFunction) {
let mut state = self.state.lock().expect("failed to lock mutex");
- state.scalar_functions.insert(f.name.clone(), Box::new(f));
- }
-
- /// Get a reference to the registered scalar functions
- pub fn scalar_functions(&self) -> Box<HashMap<String, Box<ScalarFunction>>> {
- self.state
- .lock()
- .expect("failed to lock mutex")
- .scalar_functions
- .clone()
+ state.scalar_functions.insert(f.name.clone(), Arc::new(f));
}
/// Creates a DataFrame for reading a CSV data source.
@@ -317,22 +309,9 @@ impl ExecutionContext {
/// Optimize the logical plan by applying optimizer rules
pub fn optimize(&self, plan: &LogicalPlan) -> Result<LogicalPlan> {
- let rules: Vec<Box<dyn OptimizerRule>> = vec![
- Box::new(ProjectionPushDown::new()),
- Box::new(FilterPushDown::new()),
- Box::new(TypeCoercionRule::new(
- self.state
- .lock()
- .expect("failed to lock mutex")
- .scalar_functions
- .as_ref(),
- )),
- ];
- let mut plan = plan.clone();
-
- for mut rule in rules {
- plan = rule.optimize(&plan)?;
- }
+ let plan = ProjectionPushDown::new().optimize(&plan)?;
+ let plan = FilterPushDown::new().optimize(&plan)?;
+ let plan = TypeCoercionRule::new(self).optimize(&plan)?;
Ok(plan)
}
@@ -419,6 +398,16 @@ impl ExecutionContext {
}
}
+impl ScalarFunctionRegistry for ExecutionContext {
+ fn lookup(&self, name: &str) -> Option<Arc<ScalarFunction>> {
+ self.state
+ .lock()
+ .expect("failed to lock mutex")
+ .scalar_functions
+ .lookup(name)
+ }
+}
+
/// Configuration options for execution context
#[derive(Clone)]
pub struct ExecutionConfig {
@@ -469,9 +458,9 @@ impl ExecutionConfig {
/// Execution context for registering data sources and executing queries
pub struct ExecutionContextState {
/// Data sources that are registered with the context
- pub datasources: Box<HashMap<String, Box<dyn TableProvider + Send + Sync>>>,
+ pub datasources: HashMap<String, Box<dyn TableProvider + Send + Sync>>,
/// Scalar functions that are registered with the context
- pub scalar_functions: Box<HashMap<String, Box<ScalarFunction>>>,
+ pub scalar_functions: HashMap<String, Arc<ScalarFunction>>,
/// Context configuration
pub config: ExecutionConfig,
}
diff --git a/rust/datafusion/src/execution/physical_plan/planner.rs b/rust/datafusion/src/execution/physical_plan/planner.rs
index 339e5fe8b7..7dace61823 100644
--- a/rust/datafusion/src/execution/physical_plan/planner.rs
+++ b/rust/datafusion/src/execution/physical_plan/planner.rs
@@ -421,8 +421,8 @@ mod tests {
fn plan(logical_plan: &LogicalPlan) -> Result<Arc<dyn ExecutionPlan>> {
let ctx_state = ExecutionContextState {
- datasources: Box::new(HashMap::new()),
- scalar_functions: Box::new(HashMap::new()),
+ datasources: HashMap::new(),
+ scalar_functions: HashMap::new(),
config: ExecutionConfig::new(),
};
diff --git a/rust/datafusion/src/execution/physical_plan/udf.rs b/rust/datafusion/src/execution/physical_plan/udf.rs
index 944b5c9bef..fb777f9552 100644
--- a/rust/datafusion/src/execution/physical_plan/udf.rs
+++ b/rust/datafusion/src/execution/physical_plan/udf.rs
@@ -27,7 +27,7 @@ use crate::execution::physical_plan::PhysicalExpr;
use arrow::record_batch::RecordBatch;
use fmt::{Debug, Formatter};
-use std::sync::Arc;
+use std::{collections::HashMap, sync::Arc};
/// Scalar UDF
pub type ScalarUdf = Arc<dyn Fn(&[ArrayRef]) -> Result<ArrayRef> + Send + Sync>;
@@ -45,6 +45,18 @@ pub struct ScalarFunction {
pub fun: ScalarUdf,
}
+/// Something which provides information for particular scalar functions
+pub trait ScalarFunctionRegistry {
+ /// Return ScalarFunction for `name`
+ fn lookup(&self, name: &str) -> Option<Arc<ScalarFunction>>;
+}
+
+impl ScalarFunctionRegistry for HashMap<String, Arc<ScalarFunction>> {
+ fn lookup(&self, name: &str) -> Option<Arc<ScalarFunction>> {
+ self.get(name).and_then(|func| Some(func.clone()))
+ }
+}
+
impl Debug for ScalarFunction {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("ScalarFunction")
diff --git a/rust/datafusion/src/optimizer/type_coercion.rs b/rust/datafusion/src/optimizer/type_coercion.rs
index 0d7773cc30..22d49b5ff6 100644
--- a/rust/datafusion/src/optimizer/type_coercion.rs
+++ b/rust/datafusion/src/optimizer/type_coercion.rs
@@ -20,14 +20,11 @@
//! the operation `c_float + c_int` would be rewritten as `c_float + CAST(c_int AS
//! float)`. This keeps the runtime query execution code much simpler.
-use std::collections::HashMap;
-use std::sync::Arc;
-
use arrow::datatypes::Schema;
use crate::error::{ExecutionError, Result};
use crate::execution::physical_plan::{
- expressions::numerical_coercion, udf::ScalarFunction,
+ expressions::numerical_coercion, udf::ScalarFunctionRegistry,
};
use crate::logicalplan::Expr;
use crate::logicalplan::{LogicalPlan, Operator};
@@ -38,17 +35,21 @@ use utils::optimize_explain;
/// Optimizer that applies coercion rules to expressions in the logical plan.
///
/// This optimizer does not alter the structure of the plan, it only changes expressions on it.
-pub struct TypeCoercionRule {
- scalar_functions: Arc<HashMap<String, Box<ScalarFunction>>>,
+pub struct TypeCoercionRule<'a, P>
+where
+ P: ScalarFunctionRegistry,
+{
+ scalar_functions: &'a P,
}
-impl TypeCoercionRule {
+impl<'a, P> TypeCoercionRule<'a, P>
+where
+ P: ScalarFunctionRegistry,
+{
/// Create a new type coercion optimizer rule using meta-data about registered
/// scalar functions
- pub fn new(scalar_functions: &HashMap<String, Box<ScalarFunction>>) -> Self {
- Self {
- scalar_functions: Arc::new(scalar_functions.clone()),
- }
+ pub fn new(scalar_functions: &'a P) -> Self {
+ Self { scalar_functions }
}
/// Rewrite an expression to include explicit CAST operations when required
@@ -65,7 +66,7 @@ impl TypeCoercionRule {
match expr {
Expr::ScalarFunction { name, .. } => {
// cast the inputs of scalar functions to the appropriate type where possible
- match self.scalar_functions.get(name) {
+ match self.scalar_functions.lookup(name) {
Some(func_meta) => {
for i in 0..expressions.len() {
let field = &func_meta.args[i];
@@ -102,7 +103,10 @@ impl TypeCoercionRule {
}
}
-impl OptimizerRule for TypeCoercionRule {
+impl<'a, P> OptimizerRule for TypeCoercionRule<'a, P>
+where
+ P: ScalarFunctionRegistry,
+{
fn optimize(&mut self, plan: &LogicalPlan) -> Result<LogicalPlan> {
match plan {
LogicalPlan::Explain {