datafusion_optimizer/analyzer/
function_rewrite.rs1use super::AnalyzerRule;
21use datafusion_common::config::ConfigOptions;
22use datafusion_common::tree_node::{Transformed, TreeNode};
23use datafusion_common::{DFSchema, Result};
24
25use crate::utils::NamePreserver;
26use datafusion_expr::expr_rewriter::FunctionRewrite;
27use datafusion_expr::utils::merge_schema;
28use datafusion_expr::LogicalPlan;
29use std::sync::Arc;
30
31#[derive(Default, Debug)]
33pub struct ApplyFunctionRewrites {
34 function_rewrites: Vec<Arc<dyn FunctionRewrite + Send + Sync>>,
36}
37
38impl ApplyFunctionRewrites {
39 pub fn new(function_rewrites: Vec<Arc<dyn FunctionRewrite + Send + Sync>>) -> Self {
40 Self { function_rewrites }
41 }
42
43 fn rewrite_plan(
45 &self,
46 plan: LogicalPlan,
47 options: &ConfigOptions,
48 ) -> Result<Transformed<LogicalPlan>> {
49 let mut schema = merge_schema(&plan.inputs());
52
53 if let LogicalPlan::TableScan(ts) = &plan {
54 let source_schema = DFSchema::try_from_qualified_schema(
55 ts.table_name.clone(),
56 &ts.source.schema(),
57 )?;
58 schema.merge(&source_schema);
59 }
60
61 let name_preserver = NamePreserver::new(&plan);
62
63 plan.map_expressions(|expr| {
64 let original_name = name_preserver.save(&expr);
65
66 let transformed_expr = expr.transform_up(|expr| {
68 let mut result = Transformed::no(expr);
69 for rewriter in self.function_rewrites.iter() {
70 result = result.transform_data(|expr| {
71 rewriter.rewrite(expr, &schema, options)
72 })?;
73 }
74 Ok(result)
75 })?;
76
77 Ok(transformed_expr.update_data(|expr| original_name.restore(expr)))
78 })
79 }
80}
81
82impl AnalyzerRule for ApplyFunctionRewrites {
83 fn name(&self) -> &str {
84 "apply_function_rewrites"
85 }
86
87 fn analyze(&self, plan: LogicalPlan, options: &ConfigOptions) -> Result<LogicalPlan> {
88 plan.transform_up_with_subqueries(|plan| self.rewrite_plan(plan, options))
89 .map(|res| res.data)
90 }
91}