datafusion_optimizer/analyzer/
function_rewrite.rs1use super::AnalyzerRule;
21use datafusion_common::config::ConfigOptions;
22use datafusion_common::tree_node::Transformed;
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 =
68 expr.transform_up_with_schema(&schema, |expr, schema| {
69 let mut result = Transformed::no(expr);
70 for rewriter in self.function_rewrites.iter() {
71 result = result.transform_data(|expr| {
72 rewriter.rewrite(expr, schema, options)
73 })?;
74 }
75 Ok(result)
76 })?;
77
78 Ok(transformed_expr.update_data(|expr| original_name.restore(expr)))
79 })
80 }
81}
82
83impl AnalyzerRule for ApplyFunctionRewrites {
84 fn name(&self) -> &str {
85 "apply_function_rewrites"
86 }
87
88 fn analyze(&self, plan: LogicalPlan, options: &ConfigOptions) -> Result<LogicalPlan> {
89 plan.transform_up_with_subqueries(|plan| self.rewrite_plan(plan, options))
90 .map(|res| res.data)
91 }
92}