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