Skip to main content

datafusion_optimizer/analyzer/
mod.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//! [`Analyzer`] and [`AnalyzerRule`]
6
7use std::fmt::Debug;
8use std::sync::Arc;
9
10use log::debug;
11
12use datafusion_common::Result;
13use datafusion_common::config::ConfigOptions;
14use datafusion_common::instant::Instant;
15use datafusion_expr::expr_rewriter::FunctionRewrite;
16use datafusion_expr::{InvariantLevel, LogicalPlan};
17
18use crate::analyzer::resolve_grouping_function::ResolveGroupingFunction;
19use crate::analyzer::type_coercion::TypeCoercion;
20use crate::utils::log_plan;
21
22use self::function_rewrite::ApplyFunctionRewrites;
23
24pub mod function_rewrite;
25pub mod resolve_grouping_function;
26pub mod type_coercion;
27
28/// [`AnalyzerRule`]s transform [`LogicalPlan`]s in some way to make
29/// the plan valid prior to the rest of the DataFusion optimization process.
30///
31/// `AnalyzerRule`s are different than an [`OptimizerRule`](crate::OptimizerRule)s
32/// which must preserve the semantics of the `LogicalPlan`, while computing
33/// results in a more optimal way.
34///
35/// For example, an `AnalyzerRule` may resolve [`Expr`](datafusion_expr::Expr)s into more specific
36/// forms such as a subquery reference, or do type coercion to ensure the types
37/// of operands are correct.
38///
39/// Use [`SessionState::add_analyzer_rule`] to register additional
40/// `AnalyzerRule`s.
41///
42/// [`SessionState::add_analyzer_rule`]: https://docs.rs/datafusion/latest/datafusion/execution/session_state/struct.SessionState.html#method.add_analyzer_rule
43pub trait AnalyzerRule: Debug {
44    /// Rewrite `plan`
45    fn analyze(&self, plan: LogicalPlan, config: &ConfigOptions) -> Result<LogicalPlan>;
46
47    /// A human readable name for this analyzer rule
48    fn name(&self) -> &str;
49}
50
51/// Rule-based Analyzer.
52///
53/// Applies [`FunctionRewrite`]s and [`AnalyzerRule`]s to transform a
54/// [`LogicalPlan`] in preparation for execution.
55///
56/// For example, the `Analyzer` applies type coercion to ensure the types of
57/// operands match the types required by functions.
58#[derive(Clone, Debug)]
59pub struct Analyzer {
60    /// Expr --> Function writes to apply prior to analysis passes
61    pub function_rewrites: Vec<Arc<dyn FunctionRewrite + Send + Sync>>,
62    /// All rules to apply
63    pub rules: Vec<Arc<dyn AnalyzerRule + Send + Sync>>,
64}
65
66impl Default for Analyzer {
67    fn default() -> Self {
68        Self::new()
69    }
70}
71
72impl Analyzer {
73    /// Create a new analyzer using the recommended list of rules
74    pub fn new() -> Self {
75        let rules: Vec<Arc<dyn AnalyzerRule + Send + Sync>> = vec![
76            Arc::new(ResolveGroupingFunction::new()),
77            Arc::new(TypeCoercion::new()),
78        ];
79        Self::with_rules(rules)
80    }
81
82    /// Create a new analyzer with the given rules
83    pub fn with_rules(rules: Vec<Arc<dyn AnalyzerRule + Send + Sync>>) -> Self {
84        Self {
85            function_rewrites: vec![],
86            rules,
87        }
88    }
89
90    /// Add a function rewrite rule
91    pub fn add_function_rewrite(
92        &mut self,
93        rewrite: Arc<dyn FunctionRewrite + Send + Sync>,
94    ) {
95        self.function_rewrites.push(rewrite);
96    }
97
98    /// return the list of function rewrites in this analyzer
99    pub fn function_rewrites(&self) -> &[Arc<dyn FunctionRewrite + Send + Sync>] {
100        &self.function_rewrites
101    }
102
103    /// Analyze the logical plan by applying analyzer rules, and
104    /// do necessary check and fail the invalid plans
105    pub fn execute_and_check<F>(
106        &self,
107        plan: LogicalPlan,
108        config: &ConfigOptions,
109        mut observer: F,
110    ) -> Result<LogicalPlan>
111    where
112        F: FnMut(&LogicalPlan, &dyn AnalyzerRule),
113    {
114        // verify the logical plan required invariants at the start, before analyzer
115        plan.check_invariants(InvariantLevel::Always)
116            .map_err(|e| e.context("Invalid input plan passed to Analyzer"))?;
117
118        let start_time = Instant::now();
119        let mut new_plan = plan;
120
121        // Create an analyzer pass that rewrites `Expr`s to function_calls, as
122        // appropriate.
123        //
124        // Note this is run before all other rules since it rewrites based on
125        // the argument types (List or Scalar), and TypeCoercion may cast the
126        // argument types from Scalar to List.
127        let expr_to_function: Option<Arc<dyn AnalyzerRule + Send + Sync>> =
128            if self.function_rewrites.is_empty() {
129                None
130            } else {
131                Some(Arc::new(ApplyFunctionRewrites::new(
132                    self.function_rewrites.clone(),
133                )))
134            };
135        let rules = expr_to_function.iter().chain(self.rules.iter());
136
137        // TODO add common rule executor for Analyzer and Optimizer
138        for rule in rules {
139            new_plan = rule
140                .analyze(new_plan, config)
141                .map_err(|e| e.context(rule.name()))?;
142            log_plan(rule.name(), &new_plan);
143            observer(&new_plan, rule.as_ref());
144        }
145
146        // verify at the end, after the last LP analyzer pass, that the plan is executable.
147        new_plan
148            .check_invariants(InvariantLevel::Executable)
149            .map_err(|e| e.context("Invalid (non-executable) plan after Analyzer"))?;
150
151        log_plan("Final analyzed plan", &new_plan);
152        debug!("Analyzer took {} ms", start_time.elapsed().as_millis());
153        Ok(new_plan)
154    }
155}