Skip to main content

datafusion_optimizer/analyzer/
function_rewrite.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`ApplyFunctionRewrites`] to replace `Expr`s with function calls (e.g `||` to array_concat`)
6
7use 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/// Analyzer rule that invokes [`FunctionRewrite`]s on expressions
19#[derive(Default, Debug)]
20pub struct ApplyFunctionRewrites {
21    /// Expr --> Function writes to apply
22    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    /// Rewrite a single plan, and all its expressions using the provided rewriters
31    fn rewrite_plan(
32        &self,
33        plan: LogicalPlan,
34        options: &ConfigOptions,
35    ) -> Result<Transformed<LogicalPlan>> {
36        // get schema representing all available input fields. This is used for data type
37        // resolution only, so order does not matter here
38        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        // MERGE expressions reference the target table, which is not one of
49        // `plan.inputs()`. Use the operation's visible qualifier when adding
50        // its target schema.
51        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            // recursively transform the expression, applying the rewrites at each step
61            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}