query/optimizer/
count_wildcard.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use datafusion::datasource::DefaultTableSource;
16use datafusion_common::tree_node::{
17    Transformed, TransformedResult, TreeNode, TreeNodeRecursion, TreeNodeVisitor,
18};
19use datafusion_common::{Column, Result as DataFusionResult};
20use datafusion_expr::expr::{AggregateFunction, WindowFunction};
21use datafusion_expr::utils::COUNT_STAR_EXPANSION;
22use datafusion_expr::{col, lit, Expr, LogicalPlan, WindowFunctionDefinition};
23use datafusion_optimizer::utils::NamePreserver;
24use datafusion_optimizer::AnalyzerRule;
25use datafusion_sql::TableReference;
26use table::table::adapter::DfTableProviderAdapter;
27
28/// A replacement to DataFusion's [`CountWildcardRule`]. This rule
29/// would prefer to use TIME INDEX for counting wildcard as it's
30/// faster to read comparing to PRIMARY KEYs.
31///
32/// [`CountWildcardRule`]: datafusion::optimizer::analyzer::CountWildcardRule
33#[derive(Debug)]
34pub struct CountWildcardToTimeIndexRule;
35
36impl AnalyzerRule for CountWildcardToTimeIndexRule {
37    fn name(&self) -> &str {
38        "count_wildcard_to_time_index_rule"
39    }
40
41    fn analyze(
42        &self,
43        plan: LogicalPlan,
44        _config: &datafusion::config::ConfigOptions,
45    ) -> DataFusionResult<LogicalPlan> {
46        plan.transform_down_with_subqueries(&Self::analyze_internal)
47            .data()
48    }
49}
50
51impl CountWildcardToTimeIndexRule {
52    fn analyze_internal(plan: LogicalPlan) -> DataFusionResult<Transformed<LogicalPlan>> {
53        let name_preserver = NamePreserver::new(&plan);
54        let new_arg = if let Some(time_index) = Self::try_find_time_index_col(&plan) {
55            vec![col(time_index)]
56        } else {
57            vec![lit(COUNT_STAR_EXPANSION)]
58        };
59        plan.map_expressions(|expr| {
60            let original_name = name_preserver.save(&expr);
61            let transformed_expr = expr.transform_up(|expr| match expr {
62                Expr::WindowFunction(mut window_function)
63                    if Self::is_count_star_window_aggregate(&window_function) =>
64                {
65                    window_function.args.clone_from(&new_arg);
66                    Ok(Transformed::yes(Expr::WindowFunction(window_function)))
67                }
68                Expr::AggregateFunction(mut aggregate_function)
69                    if Self::is_count_star_aggregate(&aggregate_function) =>
70                {
71                    aggregate_function.args.clone_from(&new_arg);
72                    Ok(Transformed::yes(Expr::AggregateFunction(
73                        aggregate_function,
74                    )))
75                }
76                _ => Ok(Transformed::no(expr)),
77            })?;
78            Ok(transformed_expr.update_data(|data| original_name.restore(data)))
79        })
80    }
81
82    fn try_find_time_index_col(plan: &LogicalPlan) -> Option<Column> {
83        let mut finder = TimeIndexFinder::default();
84        // Safety: `TimeIndexFinder` won't throw error.
85        plan.visit(&mut finder).unwrap();
86        let col = finder.into_column();
87
88        // check if the time index is a valid column as for current plan
89        if let Some(col) = &col {
90            let mut is_valid = false;
91            for input in plan.inputs() {
92                if input.schema().has_column(col) {
93                    is_valid = true;
94                    break;
95                }
96            }
97            if !is_valid {
98                return None;
99            }
100        }
101
102        col
103    }
104}
105
106/// Utility functions from the original rule.
107impl CountWildcardToTimeIndexRule {
108    fn is_wildcard(expr: &Expr) -> bool {
109        matches!(expr, Expr::Wildcard { .. })
110    }
111
112    fn is_count_star_aggregate(aggregate_function: &AggregateFunction) -> bool {
113        matches!(aggregate_function,
114            AggregateFunction {
115                func,
116                args,
117                ..
118            } if func.name() == "count" && (args.len() == 1 && Self::is_wildcard(&args[0]) || args.is_empty()))
119    }
120
121    fn is_count_star_window_aggregate(window_function: &WindowFunction) -> bool {
122        let args = &window_function.args;
123        matches!(window_function.fun,
124                WindowFunctionDefinition::AggregateUDF(ref udaf)
125                    if udaf.name() == "count" && (args.len() == 1 && Self::is_wildcard(&args[0]) || args.is_empty()))
126    }
127}
128
129#[derive(Default)]
130struct TimeIndexFinder {
131    time_index_col: Option<String>,
132    table_alias: Option<TableReference>,
133}
134
135impl TreeNodeVisitor<'_> for TimeIndexFinder {
136    type Node = LogicalPlan;
137
138    fn f_down(&mut self, node: &Self::Node) -> DataFusionResult<TreeNodeRecursion> {
139        if let LogicalPlan::SubqueryAlias(subquery_alias) = node {
140            self.table_alias = Some(subquery_alias.alias.clone());
141        }
142
143        if let LogicalPlan::TableScan(table_scan) = &node {
144            if let Some(source) = table_scan
145                .source
146                .as_any()
147                .downcast_ref::<DefaultTableSource>()
148            {
149                if let Some(adapter) = source
150                    .table_provider
151                    .as_any()
152                    .downcast_ref::<DfTableProviderAdapter>()
153                {
154                    let table_info = adapter.table().table_info();
155                    self.table_alias
156                        .get_or_insert(TableReference::bare(table_info.name.clone()));
157                    self.time_index_col = table_info
158                        .meta
159                        .schema
160                        .timestamp_column()
161                        .map(|c| c.name.clone());
162
163                    return Ok(TreeNodeRecursion::Stop);
164                }
165            }
166        }
167
168        Ok(TreeNodeRecursion::Continue)
169    }
170
171    fn f_up(&mut self, _node: &Self::Node) -> DataFusionResult<TreeNodeRecursion> {
172        Ok(TreeNodeRecursion::Stop)
173    }
174}
175
176impl TimeIndexFinder {
177    fn into_column(self) -> Option<Column> {
178        self.time_index_col
179            .map(|c| Column::new(self.table_alias, c))
180    }
181}
182
183#[cfg(test)]
184mod test {
185    use std::sync::Arc;
186
187    use datafusion::functions_aggregate::count::count;
188    use datafusion_expr::{wildcard, LogicalPlanBuilder};
189    use table::table::numbers::NumbersTable;
190
191    use super::*;
192
193    #[test]
194    fn uppercase_table_name() {
195        let numbers_table = NumbersTable::table_with_name(0, "AbCdE".to_string());
196        let table_source = Arc::new(DefaultTableSource::new(Arc::new(
197            DfTableProviderAdapter::new(numbers_table),
198        )));
199
200        let plan = LogicalPlanBuilder::scan_with_filters("t", table_source, None, vec![])
201            .unwrap()
202            .aggregate(Vec::<Expr>::new(), vec![count(wildcard())])
203            .unwrap()
204            .alias(r#""FgHiJ""#)
205            .unwrap()
206            .build()
207            .unwrap();
208
209        let mut finder = TimeIndexFinder::default();
210        plan.visit(&mut finder).unwrap();
211
212        assert_eq!(finder.table_alias, Some(TableReference::bare("FgHiJ")));
213        assert!(finder.time_index_col.is_none());
214    }
215}