1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#include "optimizer/bool_folding_optimizer.h"
#include "binder/expression/literal_expression.h"
#include "binder/expression/scalar_function_expression.h"
#include "common/enums/expression_type.h"
#include "common/types/value/value.h"
#include "planner/operator/logical_empty_result.h"
#include "planner/operator/logical_filter.h"
using namespace lbug::binder;
using namespace lbug::common;
using namespace lbug::planner;
namespace lbug {
namespace optimizer {
// ---------------------------------------------------------------------------
// Helper: detect whether two expressions are logical negations
// ---------------------------------------------------------------------------
/// Returns true if `a` and `b` can never be true simultaneously.
///
/// Recognised forms:
/// - NOT(p) and p
/// - IS_NULL(x) and IS_NOT_NULL(x)
static bool areNegations(const Expression& a, const Expression& b) {
// NOT(p) == b
if (a.expressionType == ExpressionType::NOT && a.getNumChildren() == 1 && *a.getChild(0) == b) {
return true;
}
// NOT(q) == a
if (b.expressionType == ExpressionType::NOT && b.getNumChildren() == 1 && *b.getChild(0) == a) {
return true;
}
// IS_NULL(x) vs IS_NOT_NULL(x)
if (a.expressionType == ExpressionType::IS_NULL &&
b.expressionType == ExpressionType::IS_NOT_NULL) {
return a.getNumChildren() > 0 && b.getNumChildren() > 0 && *a.getChild(0) == *b.getChild(0);
}
if (a.expressionType == ExpressionType::IS_NOT_NULL &&
b.expressionType == ExpressionType::IS_NULL) {
return a.getNumChildren() > 0 && b.getNumChildren() > 0 && *a.getChild(0) == *b.getChild(0);
}
return false;
}
// ---------------------------------------------------------------------------
// Helper: build a boolean literal expression
// ---------------------------------------------------------------------------
static std::shared_ptr<Expression> boolLiteral(bool v) {
return std::make_shared<LiteralExpression>(Value(v),
std::string("_lit_") + (v ? "true" : "false"));
}
// ---------------------------------------------------------------------------
// Core folding (tree-propagating version)
// ---------------------------------------------------------------------------
/// Recursively simplify a boolean expression through constant folding and
/// algebraic simplification (bottom-up tree propagation).
///
/// Returns `nullptr` when the expression is already as simple as it can be.
/// Otherwise returns a simplified expression: a LiteralExpression when the
/// whole expression is always-true or always-false, or a non-literal when
/// a subtree collapsed (e.g. `AND(true, x)` β `x`).
///
/// Because children are folded before the parent is examined, nested
/// simplifications cascade upward:
///
/// AND(OR(IS_NULL(x), IS_NOT_NULL(x)), y > 5)
/// β AND(true, y > 5) [OR tautology folded to true]
/// β y > 5 [AND(true, x) β x]
///
/// OR(AND(IS_NULL(x), IS_NOT_NULL(x)), n.k = 1)
/// β OR(false, n.k = 1) [AND contradiction folded to false]
/// β n.k = 1 [OR(false, x) β x]
static std::shared_ptr<Expression> foldBool(const std::shared_ptr<Expression>& expr) {
// --- NOT -----------------------------------------------------------
if (expr->expressionType == ExpressionType::NOT) {
// NOT(NOT(x)) β x β structural, no folding needed.
auto child = expr->getChild(0);
if (child->expressionType == ExpressionType::NOT && child->getNumChildren() == 1) {
return child->getChild(0);
}
// Fold the inner expression and invert if it becomes a constant.
auto folded = foldBool(child);
auto effective = folded ? folded : child;
if (effective->expressionType == ExpressionType::LITERAL) {
auto& lit = effective->constCast<LiteralExpression>();
return boolLiteral(lit.isNull() || !lit.getValue().getValue<bool>());
}
return folded ? effective : nullptr;
}
// --- AND -----------------------------------------------------------
if (expr->expressionType == ExpressionType::AND) {
auto parts = expr->splitOnAND();
expression_vector kept;
bool anyChanged = false;
// 1) Fold each child; short-circuit on false; drop true.
for (auto& part : parts) {
auto folded = foldBool(part);
auto effective = folded ? folded : part;
if (folded) {
anyChanged = true;
}
if (effective->expressionType == ExpressionType::LITERAL) {
auto& lit = effective->constCast<LiteralExpression>();
if (lit.isNull() || !lit.getValue().getValue<bool>()) {
return boolLiteral(false); // false β§ β¦ β‘ false
}
// true conjunct is a no-op β drop it.
continue;
}
kept.push_back(effective);
}
// 2) Check pair-wise contradictions among kept children.
for (auto i = 0u; i < kept.size(); ++i) {
for (auto j = i + 1; j < kept.size(); ++j) {
if (areNegations(*kept[i], *kept[j])) {
return boolLiteral(false); // p β§ Β¬p β‘ false
}
}
}
// 3) All conjuncts were true.
if (kept.empty()) {
return boolLiteral(true);
}
// 4) Single remaining child β e.g. AND(true, x) β x.
if (kept.size() == 1) {
return kept[0];
}
// 5) Multiple children remain; we currently do not rebuild the
// AND tree. If any child was simplified it is a missed
// opportunity, but the predicate is still correct as-is.
return anyChanged ? kept[0] : nullptr;
}
// --- OR ------------------------------------------------------------
if (expr->expressionType == ExpressionType::OR) {
// 1) Fold all children in one pass.
std::vector<std::shared_ptr<Expression>> folded;
bool anyChanged = false;
for (auto i = 0u; i < expr->getNumChildren(); ++i) {
auto f = foldBool(expr->getChild(i));
auto eff = f ? f : expr->getChild(i);
if (f) {
anyChanged = true;
}
folded.push_back(eff);
}
// 2) Walk children; short-circuit on true, drop false, detect
// tautology pairs.
expression_vector kept;
for (auto i = 0u; i < folded.size(); ++i) {
auto& eff = folded[i];
if (eff->expressionType == ExpressionType::LITERAL) {
auto& lit = eff->constCast<LiteralExpression>();
if (!lit.isNull() && lit.getValue().getValue<bool>()) {
return boolLiteral(true); // true β¨ β¦ β‘ true
}
// false disjunct is a no-op.
continue;
}
// Check for tautology: p β¨ Β¬p β‘ true.
for (auto j = i + 1; j < folded.size(); ++j) {
if (areNegations(*eff, *folded[j])) {
return boolLiteral(true);
}
}
kept.push_back(eff);
}
// 3) All disjuncts were false.
if (kept.empty()) {
return boolLiteral(false);
}
// 4) Single remaining child β e.g. OR(false, x) β x.
if (kept.size() == 1) {
return kept[0];
}
return anyChanged ? kept[0] : nullptr;
}
return nullptr;
}
// ---------------------------------------------------------------------------
// BoolFoldingOptimizer
// ---------------------------------------------------------------------------
void BoolFoldingOptimizer::rewrite(LogicalPlan* plan) {
visitOperator(plan->getLastOperator());
}
std::shared_ptr<LogicalOperator> BoolFoldingOptimizer::visitOperator(
const std::shared_ptr<LogicalOperator>& op) {
// bottom-up traversal
for (auto i = 0u; i < op->getNumChildren(); ++i) {
op->setChild(i, visitOperator(op->getChild(i)));
}
auto result = visitOperatorReplaceSwitch(op);
result->computeFlatSchema();
return result;
}
std::shared_ptr<LogicalOperator> BoolFoldingOptimizer::visitFilterReplace(
std::shared_ptr<LogicalOperator> op) {
auto& filter = op->constCast<LogicalFilter>();
auto predicate = filter.getPredicate();
// Already a literal β handled by the existing filter-push-down logic too,
// but folding may produce new literals from composite expressions.
if (predicate->expressionType == ExpressionType::LITERAL) {
auto& lit = predicate->constCast<LiteralExpression>();
if (lit.isNull() || !lit.getValue().getValue<bool>()) {
return std::make_shared<LogicalEmptyResult>(*op->getSchema());
}
return op->getChild(0); // true literal β drop filter
}
auto folded = foldBool(predicate);
if (!folded) {
return op; // no simplification
}
if (folded->expressionType == ExpressionType::LITERAL) {
auto& lit = folded->constCast<LiteralExpression>();
if (lit.isNull() || !lit.getValue().getValue<bool>()) {
return std::make_shared<LogicalEmptyResult>(*op->getSchema());
}
// Folded to true β the filter is redundant.
return op->getChild(0);
}
// Non-literal simplification β replace the filter predicate.
auto newFilter = std::make_shared<LogicalFilter>(std::move(folded), op->getChild(0));
newFilter->computeFlatSchema();
return newFilter;
}
} // namespace optimizer
} // namespace lbug