|
| 1 | +// Copyright 2022 Datafuse Labs. |
| 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 | + |
| 15 | +use ahash::HashMap; |
| 16 | +use common_exception::ErrorCode; |
| 17 | +use common_exception::Result; |
| 18 | + |
| 19 | +use crate::optimizer::rule::Rule; |
| 20 | +use crate::optimizer::rule::TransformResult; |
| 21 | +use crate::optimizer::RuleID; |
| 22 | +use crate::optimizer::SExpr; |
| 23 | +use crate::plans::AggregateFunction; |
| 24 | +use crate::plans::AndExpr; |
| 25 | +use crate::plans::BoundColumnRef; |
| 26 | +use crate::plans::CastExpr; |
| 27 | +use crate::plans::ComparisonExpr; |
| 28 | +use crate::plans::Filter; |
| 29 | +use crate::plans::FunctionCall; |
| 30 | +use crate::plans::OrExpr; |
| 31 | +use crate::plans::PatternPlan; |
| 32 | +use crate::plans::RelOp; |
| 33 | +use crate::plans::Scalar; |
| 34 | +use crate::plans::UnionAll; |
| 35 | +use crate::ColumnBinding; |
| 36 | +use crate::IndexType; |
| 37 | +use crate::Visibility; |
| 38 | + |
| 39 | +// For a union query, it's not allowed to add `filter` after union |
| 40 | +// Such as: `(select * from t1 union all select * from t2) where a > 1`, it's invalid. |
| 41 | +// However, it's possible to have `filter` after `union` when involved `view` |
| 42 | +// Such as: `create view v_t as (select * from t1 union all select * from t2)`. |
| 43 | +// Then use the view with filter, `select * from v_t where a > 1`; |
| 44 | +// So it'll be efficient to push down `filter` to `union`, reduce the size of data to pull from table. |
| 45 | +pub struct RulePushDownFilterUnion { |
| 46 | + id: RuleID, |
| 47 | + pattern: SExpr, |
| 48 | +} |
| 49 | + |
| 50 | +impl RulePushDownFilterUnion { |
| 51 | + pub fn new() -> Self { |
| 52 | + Self { |
| 53 | + id: RuleID::PushDownFilterUnion, |
| 54 | + // Filter |
| 55 | + // \ |
| 56 | + // UnionAll |
| 57 | + // / \ |
| 58 | + // ... ... |
| 59 | + pattern: SExpr::create_unary( |
| 60 | + PatternPlan { |
| 61 | + plan_type: RelOp::Filter, |
| 62 | + } |
| 63 | + .into(), |
| 64 | + SExpr::create_binary( |
| 65 | + PatternPlan { |
| 66 | + plan_type: RelOp::UnionAll, |
| 67 | + } |
| 68 | + .into(), |
| 69 | + SExpr::create_leaf( |
| 70 | + PatternPlan { |
| 71 | + plan_type: RelOp::Pattern, |
| 72 | + } |
| 73 | + .into(), |
| 74 | + ), |
| 75 | + SExpr::create_leaf( |
| 76 | + PatternPlan { |
| 77 | + plan_type: RelOp::Pattern, |
| 78 | + } |
| 79 | + .into(), |
| 80 | + ), |
| 81 | + ), |
| 82 | + ), |
| 83 | + } |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +impl Rule for RulePushDownFilterUnion { |
| 88 | + fn id(&self) -> RuleID { |
| 89 | + self.id |
| 90 | + } |
| 91 | + |
| 92 | + fn apply(&self, s_expr: &SExpr, state: &mut TransformResult) -> Result<()> { |
| 93 | + let filter: Filter = s_expr.plan().clone().try_into()?; |
| 94 | + let union_s_expr = s_expr.child(0)?; |
| 95 | + let union: UnionAll = union_s_expr.plan().clone().try_into()?; |
| 96 | + |
| 97 | + // Create a filter which matches union's right child. |
| 98 | + let index_pairs: HashMap<IndexType, IndexType> = |
| 99 | + union.pairs.iter().map(|pair| (pair.0, pair.1)).collect(); |
| 100 | + let new_predicates = filter |
| 101 | + .predicates |
| 102 | + .iter() |
| 103 | + .map(|predicate| replace_column_binding(&index_pairs, predicate.clone())) |
| 104 | + .collect::<Result<Vec<_>>>()?; |
| 105 | + let right_filer = Filter { |
| 106 | + predicates: new_predicates, |
| 107 | + is_having: filter.is_having, |
| 108 | + }; |
| 109 | + |
| 110 | + let mut union_left_child = union_s_expr.child(0)?.clone(); |
| 111 | + let mut union_right_child = union_s_expr.child(1)?.clone(); |
| 112 | + |
| 113 | + // Add filter to union children |
| 114 | + union_left_child = SExpr::create_unary(filter.into(), union_left_child); |
| 115 | + union_right_child = SExpr::create_unary(right_filer.into(), union_right_child); |
| 116 | + |
| 117 | + let result = SExpr::create_binary(union.into(), union_left_child, union_right_child); |
| 118 | + state.add_result(result); |
| 119 | + |
| 120 | + Ok(()) |
| 121 | + } |
| 122 | + |
| 123 | + fn pattern(&self) -> &SExpr { |
| 124 | + &self.pattern |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +fn replace_column_binding( |
| 129 | + index_pairs: &HashMap<IndexType, IndexType>, |
| 130 | + scalar: Scalar, |
| 131 | +) -> Result<Scalar> { |
| 132 | + match scalar { |
| 133 | + Scalar::BoundColumnRef(column) => { |
| 134 | + let index = column.column.index; |
| 135 | + if index_pairs.contains_key(&index) { |
| 136 | + let new_column = ColumnBinding { |
| 137 | + database_name: None, |
| 138 | + table_name: None, |
| 139 | + column_name: "".to_string(), |
| 140 | + index: *index_pairs.get(&index).unwrap(), |
| 141 | + data_type: column.column.data_type, |
| 142 | + visibility: Visibility::Visible, |
| 143 | + }; |
| 144 | + return Ok(Scalar::BoundColumnRef(BoundColumnRef { |
| 145 | + column: new_column, |
| 146 | + })); |
| 147 | + } |
| 148 | + Ok(Scalar::BoundColumnRef(column)) |
| 149 | + } |
| 150 | + constant_expr @ Scalar::ConstantExpr(_) => Ok(constant_expr), |
| 151 | + Scalar::AndExpr(expr) => Ok(Scalar::AndExpr(AndExpr { |
| 152 | + left: Box::new(replace_column_binding(index_pairs, *expr.left)?), |
| 153 | + right: Box::new(replace_column_binding(index_pairs, *expr.right)?), |
| 154 | + return_type: expr.return_type, |
| 155 | + })), |
| 156 | + Scalar::OrExpr(expr) => Ok(Scalar::OrExpr(OrExpr { |
| 157 | + left: Box::new(replace_column_binding(index_pairs, *expr.left)?), |
| 158 | + right: Box::new(replace_column_binding(index_pairs, *expr.right)?), |
| 159 | + return_type: expr.return_type, |
| 160 | + })), |
| 161 | + Scalar::ComparisonExpr(expr) => Ok(Scalar::ComparisonExpr(ComparisonExpr { |
| 162 | + op: expr.op, |
| 163 | + left: Box::new(replace_column_binding(index_pairs, *expr.left)?), |
| 164 | + right: Box::new(replace_column_binding(index_pairs, *expr.right)?), |
| 165 | + return_type: expr.return_type, |
| 166 | + })), |
| 167 | + Scalar::AggregateFunction(expr) => Ok(Scalar::AggregateFunction(AggregateFunction { |
| 168 | + display_name: expr.display_name, |
| 169 | + func_name: expr.func_name, |
| 170 | + distinct: expr.distinct, |
| 171 | + params: expr.params, |
| 172 | + args: expr |
| 173 | + .args |
| 174 | + .into_iter() |
| 175 | + .map(|arg| replace_column_binding(index_pairs, arg)) |
| 176 | + .collect::<Result<Vec<_>>>()?, |
| 177 | + return_type: expr.return_type, |
| 178 | + })), |
| 179 | + Scalar::FunctionCall(expr) => Ok(Scalar::FunctionCall(FunctionCall { |
| 180 | + arguments: expr |
| 181 | + .arguments |
| 182 | + .into_iter() |
| 183 | + .map(|arg| replace_column_binding(index_pairs, arg)) |
| 184 | + .collect::<Result<Vec<_>>>()?, |
| 185 | + func_name: expr.func_name, |
| 186 | + arg_types: expr.arg_types, |
| 187 | + return_type: expr.return_type, |
| 188 | + })), |
| 189 | + Scalar::CastExpr(expr) => Ok(Scalar::CastExpr(CastExpr { |
| 190 | + argument: Box::new(replace_column_binding(index_pairs, *(expr.argument))?), |
| 191 | + from_type: expr.from_type, |
| 192 | + target_type: expr.target_type, |
| 193 | + })), |
| 194 | + Scalar::SubqueryExpr(_) => Err(ErrorCode::Unimplemented( |
| 195 | + "replace_column_binding: don't support subquery", |
| 196 | + )), |
| 197 | + } |
| 198 | +} |
0 commit comments