use super::AnalyzerRule;
use datafusion_common::config::ConfigOptions;
use datafusion_common::tree_node::{Transformed, TreeNode};
use datafusion_common::{DFSchema, Result};
use crate::utils::NamePreserver;
use datafusion_expr::expr_rewriter::FunctionRewrite;
use datafusion_expr::utils::merge_schema;
use datafusion_expr::LogicalPlan;
use std::sync::Arc;
#[derive(Default, Debug)]
pub struct ApplyFunctionRewrites {
function_rewrites: Vec<Arc<dyn FunctionRewrite + Send + Sync>>,
}
impl ApplyFunctionRewrites {
pub fn new(function_rewrites: Vec<Arc<dyn FunctionRewrite + Send + Sync>>) -> Self {
Self { function_rewrites }
}
fn rewrite_plan(
&self,
plan: LogicalPlan,
options: &ConfigOptions,
) -> Result<Transformed<LogicalPlan>> {
let mut schema = merge_schema(&plan.inputs());
if let LogicalPlan::TableScan(ts) = &plan {
let source_schema = DFSchema::try_from_qualified_schema(
ts.table_name.clone(),
&ts.source.schema(),
)?;
schema.merge(&source_schema);
}
let name_preserver = NamePreserver::new(&plan);
plan.map_expressions(|expr| {
let original_name = name_preserver.save(&expr);
let transformed_expr = expr.transform_up(|expr| {
let mut result = Transformed::no(expr);
for rewriter in self.function_rewrites.iter() {
result = result.transform_data(|expr| {
rewriter.rewrite(expr, &schema, options)
})?;
}
Ok(result)
})?;
Ok(transformed_expr.update_data(|expr| original_name.restore(expr)))
})
}
}
impl AnalyzerRule for ApplyFunctionRewrites {
fn name(&self) -> &str {
"apply_function_rewrites"
}
fn analyze(&self, plan: LogicalPlan, options: &ConfigOptions) -> Result<LogicalPlan> {
plan.transform_up_with_subqueries(|plan| self.rewrite_plan(plan, options))
.map(|res| res.data)
}
}