Debian Codegraph @

src/main/org/h2/expression/condition/ConditionAndOrN.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, and the
3 * EPL 1.0 (https://h2database.com/html/license.html). Initial Developer: H2
4 * Group
5 */
6 package org.h2.expression.condition;
7
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.Comparator;
11 import java.util.Iterator;
12 import java.util.List;
13 import org.h2.engine.SessionLocal;
14 import org.h2.expression.Expression;
15 import org.h2.expression.ExpressionVisitor;
16 import org.h2.message.DbException;
17 import org.h2.table.ColumnResolver;
18 import org.h2.table.TableFilter;
19 import org.h2.value.Value;
20 import org.h2.value.ValueBoolean;
21 import org.h2.value.ValueNull;
22
23 /**
24 * An 'and' or 'or' condition as in WHERE ID=1 AND NAME=? with N operands.
25 * Mostly useful for optimisation and preventing stack overflow where generated
26 * SQL has tons of conditions.
27 */
28 public class ConditionAndOrN extends Condition {
29
30 private final int andOrType;
31 /**
32 * Use an ArrayDeque because we primarily insert at the front.
33 */
34 private final List<Expression> expressions;
35
36 /**
37 * Additional conditions for index only.
38 */
39 private List<Expression> added;
40
41 public ConditionAndOrN(int andOrType, Expression expr1, Expression expr2, Expression expr3) {
42 this.andOrType = andOrType;
43 this.expressions = new ArrayList<>(3);
44 expressions.add(expr1);
45 expressions.add(expr2);
46 expressions.add(expr3);
47 }
48
49 public ConditionAndOrN(int andOrType, List<Expression> expressions) {
50 this.andOrType = andOrType;
51 this.expressions = expressions;
52 }
53
54 int getAndOrType() {
55 return andOrType;
56 }
57
58 /**
59 * Add the expression at the beginning of the list.
60 *
61 * @param e the expression
62 */
63 void addFirst(Expression e) {
64 expressions.add(0, e);
65 }
66
67 @Override
68 public boolean needParentheses() {
69 return true;
70 }
71
72 @Override
73 public StringBuilder getUnenclosedSQL(StringBuilder builder, int sqlFlags) {
74 Iterator<Expression> it = expressions.iterator();
75 it.next().getSQL(builder, sqlFlags, AUTO_PARENTHESES);
76 while (it.hasNext()) {
77 switch (andOrType) {
78 case ConditionAndOr.AND:
79 builder.append("\n AND ");
80 break;
81 case ConditionAndOr.OR:
82 builder.append("\n OR ");
83 break;
84 default:
85 throw DbException.getInternalError("andOrType=" + andOrType);
86 }
87 it.next().getSQL(builder, sqlFlags, AUTO_PARENTHESES);
88 }
89 return builder;
90 }
91
92 @Override
93 public void createIndexConditions(SessionLocal session, TableFilter filter) {
94 if (andOrType == ConditionAndOr.AND) {
95 for (Expression e : expressions) {
96 e.createIndexConditions(session, filter);
97 }
98 if (added != null) {
99 for (Expression e : added) {
100 e.createIndexConditions(session, filter);
101 }
102 }
103 }
104 }
105
106 @Override
107 public Expression getNotIfPossible(SessionLocal session) {
108 // (NOT (A OR B)): (NOT(A) AND NOT(B))
109 // (NOT (A AND B)): (NOT(A) OR NOT(B))
110 final ArrayList<Expression> newList = new ArrayList<>(expressions.size());
111 for (Expression e : expressions) {
112 Expression l = e.getNotIfPossible(session);
113 if (l == null) {
114 l = new ConditionNot(e);
115 }
116 newList.add(l);
117 }
118 int reversed = andOrType == ConditionAndOr.AND ? ConditionAndOr.OR : ConditionAndOr.AND;
119 return new ConditionAndOrN(reversed, newList);
120 }
121
122 @Override
123 public Value getValue(SessionLocal session) {
124 boolean hasNull = false;
125 switch (andOrType) {
126 case ConditionAndOr.AND: {
127 for (Expression e : expressions) {
128 Value v = e.getValue(session);
129 if (v == ValueNull.INSTANCE) {
130 hasNull = true;
131 } else if (!v.getBoolean()) {
132 return ValueBoolean.FALSE;
133 }
134 }
135 return hasNull ? ValueNull.INSTANCE : ValueBoolean.TRUE;
136 }
137 case ConditionAndOr.OR: {
138 for (Expression e : expressions) {
139 Value v = e.getValue(session);
140 if (v == ValueNull.INSTANCE) {
141 hasNull = true;
142 } else if (v.getBoolean()) {
143 return ValueBoolean.TRUE;
144 }
145 }
146 return hasNull ? ValueNull.INSTANCE : ValueBoolean.FALSE;
147 }
148 default:
149 throw DbException.getInternalError("type=" + andOrType);
150 }
151 }
152
153 private static final Comparator<Expression> COMPARE_BY_COST = new Comparator<Expression>() {
154 @Override
155 public int compare(Expression lhs, Expression rhs) {
156 return lhs.getCost() - rhs.getCost();
157 }
158
159 };
160
161 @Override
162 public Expression optimize(SessionLocal session) {
163 // NULL handling: see wikipedia,
164 // http://www-cs-students.stanford.edu/~wlam/compsci/sqlnulls
165
166 // first pass, optimize individual sub-expressions
167 for (int i = 0; i < expressions.size(); i++ ) {
168 expressions.set(i, expressions.get(i).optimize(session));
169 }
170
171 Collections.sort(expressions, COMPARE_BY_COST);
172
173 // TODO we're only matching pairs so that are next to each other, so in complex expressions
174 // we will miss opportunities
175
176 // second pass, optimize combinations
177 optimizeMerge(0);
178 for (int i = 1; i < expressions.size(); ) {
179 Expression left = expressions.get(i-1);
180 Expression right = expressions.get(i);
181 switch (andOrType) {
182 case ConditionAndOr.AND:
183 if (!session.getDatabase().getSettings().optimizeTwoEquals) {
184 break;
185 }
186 // this optimization does not work in the following case,
187 // but NOT is optimized before:
188 // CREATE TABLE TEST(A INT, B INT);
189 // INSERT INTO TEST VALUES(1, NULL);
190 // SELECT * FROM TEST WHERE NOT (B=A AND B=0); // no rows
191 // SELECT * FROM TEST WHERE NOT (B=A AND B=0 AND A=0); // 1,
192 // NULL
193 // try to add conditions (A=B AND B=1: add A=1)
194 if (left instanceof Comparison && right instanceof Comparison) {
195 // try to add conditions (A=B AND B=1: add A=1)
196 Expression added = ((Comparison) left).getAdditionalAnd(session, (Comparison) right);
197 if (added != null) {
198 if (this.added == null) {
199 this.added = new ArrayList<>();
200 }
201 this.added.add(added.optimize(session));
202 }
203 }
204 break;
205 case ConditionAndOr.OR:
206 if (!session.getDatabase().getSettings().optimizeOr) {
207 break;
208 }
209 Expression reduced;
210 if (left instanceof Comparison && right instanceof Comparison) {
211 reduced = ((Comparison) left).optimizeOr(session, (Comparison) right);
212 } else if (left instanceof ConditionIn && right instanceof Comparison) {
213 reduced = ((ConditionIn) left).getAdditional((Comparison) right);
214 } else if (right instanceof ConditionIn && left instanceof Comparison) {
215 reduced = ((ConditionIn) right).getAdditional((Comparison) left);
216 } else if (left instanceof ConditionInConstantSet && right instanceof Comparison) {
217 reduced = ((ConditionInConstantSet) left).getAdditional(session, (Comparison) right);
218 } else if (right instanceof ConditionInConstantSet && left instanceof Comparison) {
219 reduced = ((ConditionInConstantSet) right).getAdditional(session, (Comparison) left);
220 } else if (left instanceof ConditionAndOr && right instanceof ConditionAndOr) {
221 reduced = ConditionAndOr.optimizeConditionAndOr((ConditionAndOr) left, (ConditionAndOr) right);
222 } else {
223 // TODO optimization: convert .. OR .. to UNION if the cost
224 // is lower
225 break;
226 }
227 if (reduced != null) {
228 expressions.remove(i);
229 expressions.set(i - 1, reduced.optimize(session));
230 continue; // because we don't want to increment, we want to compare the new pair exposed
231 }
232 }
233
234 Expression e = ConditionAndOr.optimizeIfConstant(session, andOrType, left, right);
235 if (e != null) {
236 expressions.remove(i);
237 expressions.set(i-1, e);
238 continue; // because we don't want to increment, we want to compare the new pair exposed
239 }
240
241 if (optimizeMerge(i)) {
242 continue;
243 }
244
245 i++;
246 }
247
248 Collections.sort(expressions, COMPARE_BY_COST);
249
250 if (expressions.size() == 1) {
251 return Condition.castToBoolean(session, expressions.get(0));
252 }
253 return this;
254 }
255
256
257 private boolean optimizeMerge(int i) {
258 Expression e = expressions.get(i);
259 // If we have a ConditionAndOrN as a sub-expression, see if we can merge it
260 // into this one.
261 if (e instanceof ConditionAndOrN) {
262 ConditionAndOrN rightCondition = (ConditionAndOrN) e;
263 if (this.andOrType == rightCondition.andOrType) {
264 expressions.remove(i);
265 expressions.addAll(i, rightCondition.expressions);
266 return true;
267 }
268 }
269 else if (e instanceof ConditionAndOr) {
270 ConditionAndOr rightCondition = (ConditionAndOr) e;
271 if (this.andOrType == rightCondition.getAndOrType()) {
272 expressions.set(i, rightCondition.getSubexpression(0));
273 expressions.add(i+1, rightCondition.getSubexpression(1));
274 return true;
275 }
276 }
277 return false;
278 }
279
280 @Override
281 public void addFilterConditions(TableFilter filter) {
282 if (andOrType == ConditionAndOr.AND) {
283 for (Expression e : expressions) {
284 e.addFilterConditions(filter);
285 }
286 } else {
287 super.addFilterConditions(filter);
288 }
289 }
290
291 @Override
292 public void mapColumns(ColumnResolver resolver, int level, int state) {
293 for (Expression e : expressions) {
294 e.mapColumns(resolver, level, state);
295 }
296 }
297
298 @Override
299 public void setEvaluatable(TableFilter tableFilter, boolean b) {
300 for (Expression e : expressions) {
301 e.setEvaluatable(tableFilter, b);
302 }
303 }
304
305 @Override
306 public void updateAggregate(SessionLocal session, int stage) {
307 for (Expression e : expressions) {
308 e.updateAggregate(session, stage);
309 }
310 }
311
312 @Override
313 public boolean isEverything(ExpressionVisitor visitor) {
314 for (Expression e : expressions) {
315 if (!e.isEverything(visitor)) {
316 return false;
317 }
318 }
319 return true;
320 }
321
322 @Override
323 public int getCost() {
324 int cost = 0;
325 for (Expression e : expressions) {
326 cost += e.getCost();
327 }
328 return cost;
329 }
330
331 @Override
332 public int getSubexpressionCount() {
333 return expressions.size();
334 }
335
336 @Override
337 public Expression getSubexpression(int index) {
338 return expressions.get(index);
339 }
340
341 }