Debian Codegraph @

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

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.expression.condition;
7
8 import org.h2.engine.SessionLocal;
9 import org.h2.expression.Expression;
10 import org.h2.expression.ExpressionVisitor;
11 import org.h2.expression.TypedValueExpression;
12 import org.h2.expression.ValueExpression;
13 import org.h2.message.DbException;
14 import org.h2.table.ColumnResolver;
15 import org.h2.table.TableFilter;
16 import org.h2.value.Value;
17 import org.h2.value.ValueBoolean;
18 import org.h2.value.ValueNull;
19
20 /**
21 * An 'and' or 'or' condition as in WHERE ID=1 AND NAME=?
22 */
23 public class ConditionAndOr extends Condition {
24
25 /**
26 * The AND condition type as in ID=1 AND NAME='Hello'.
27 */
28 public static final int AND = 0;
29
30 /**
31 * The OR condition type as in ID=1 OR NAME='Hello'.
32 */
33 public static final int OR = 1;
34
35 private final int andOrType;
36 private Expression left, right;
37
38 /**
39 * Additional condition for index only.
40 */
41 private Expression added;
42
43 public ConditionAndOr(int andOrType, Expression left, Expression right) {
44 if (left == null || right == null) {
45 throw DbException.getInternalError(left + " " + right);
46 }
47 this.andOrType = andOrType;
48 this.left = left;
49 this.right = right;
50 }
51
52 int getAndOrType() {
53 return this.andOrType;
54 }
55
56 @Override
57 public boolean needParentheses() {
58 return true;
59 }
60
61 @Override
62 public StringBuilder getUnenclosedSQL(StringBuilder builder, int sqlFlags) {
63 left.getSQL(builder, sqlFlags, AUTO_PARENTHESES);
64 switch (andOrType) {
65 case AND:
66 builder.append("\n AND ");
67 break;
68 case OR:
69 builder.append("\n OR ");
70 break;
71 default:
72 throw DbException.getInternalError("andOrType=" + andOrType);
73 }
74 return right.getSQL(builder, sqlFlags, AUTO_PARENTHESES);
75 }
76
77 @Override
78 public void createIndexConditions(SessionLocal session, TableFilter filter) {
79 if (andOrType == AND) {
80 left.createIndexConditions(session, filter);
81 right.createIndexConditions(session, filter);
82 if (added != null) {
83 added.createIndexConditions(session, filter);
84 }
85 }
86 }
87
88 @Override
89 public Expression getNotIfPossible(SessionLocal session) {
90 // (NOT (A OR B)): (NOT(A) AND NOT(B))
91 // (NOT (A AND B)): (NOT(A) OR NOT(B))
92 Expression l = left.getNotIfPossible(session);
93 if (l == null) {
94 l = new ConditionNot(left);
95 }
96 Expression r = right.getNotIfPossible(session);
97 if (r == null) {
98 r = new ConditionNot(right);
99 }
100 int reversed = andOrType == AND ? OR : AND;
101 return new ConditionAndOr(reversed, l, r);
102 }
103
104 @Override
105 public Value getValue(SessionLocal session) {
106 Value l = left.getValue(session);
107 Value r;
108 switch (andOrType) {
109 case AND: {
110 if (l.isFalse() || (r = right.getValue(session)).isFalse()) {
111 return ValueBoolean.FALSE;
112 }
113 if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
114 return ValueNull.INSTANCE;
115 }
116 return ValueBoolean.TRUE;
117 }
118 case OR: {
119 if (l.isTrue() || (r = right.getValue(session)).isTrue()) {
120 return ValueBoolean.TRUE;
121 }
122 if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
123 return ValueNull.INSTANCE;
124 }
125 return ValueBoolean.FALSE;
126 }
127 default:
128 throw DbException.getInternalError("type=" + andOrType);
129 }
130 }
131
132 @Override
133 public Expression optimize(SessionLocal session) {
134 // NULL handling: see wikipedia,
135 // http://www-cs-students.stanford.edu/~wlam/compsci/sqlnulls
136 left = left.optimize(session);
137 right = right.optimize(session);
138 int lc = left.getCost(), rc = right.getCost();
139 if (rc < lc) {
140 Expression t = left;
141 left = right;
142 right = t;
143 }
144 switch (andOrType) {
145 case AND:
146 if (!session.getDatabase().getSettings().optimizeTwoEquals) {
147 break;
148 }
149 // this optimization does not work in the following case,
150 // but NOT is optimized before:
151 // CREATE TABLE TEST(A INT, B INT);
152 // INSERT INTO TEST VALUES(1, NULL);
153 // SELECT * FROM TEST WHERE NOT (B=A AND B=0); // no rows
154 // SELECT * FROM TEST WHERE NOT (B=A AND B=0 AND A=0); // 1, NULL
155 // try to add conditions (A=B AND B=1: add A=1)
156 if (left instanceof Comparison && right instanceof Comparison) {
157 // try to add conditions (A=B AND B=1: add A=1)
158 Expression added = ((Comparison) left).getAdditionalAnd(session, (Comparison) right);
159 if (added != null) {
160 this.added = added.optimize(session);
161 }
162 }
163 break;
164 case OR:
165 if (!session.getDatabase().getSettings().optimizeOr) {
166 break;
167 }
168 Expression reduced;
169 if (left instanceof Comparison && right instanceof Comparison) {
170 reduced = ((Comparison) left).optimizeOr(session, (Comparison) right);
171 } else if (left instanceof ConditionIn && right instanceof Comparison) {
172 reduced = ((ConditionIn) left).getAdditional((Comparison) right);
173 } else if (right instanceof ConditionIn && left instanceof Comparison) {
174 reduced = ((ConditionIn) right).getAdditional((Comparison) left);
175 } else if (left instanceof ConditionInConstantSet && right instanceof Comparison) {
176 reduced = ((ConditionInConstantSet) left).getAdditional(session, (Comparison) right);
177 } else if (right instanceof ConditionInConstantSet && left instanceof Comparison) {
178 reduced = ((ConditionInConstantSet) right).getAdditional(session, (Comparison) left);
179 } else if (left instanceof ConditionAndOr && right instanceof ConditionAndOr) {
180 reduced = optimizeConditionAndOr((ConditionAndOr)left, (ConditionAndOr)right);
181 } else {
182 // TODO optimization: convert .. OR .. to UNION if the cost is lower
183 break;
184 }
185 if (reduced != null) {
186 return reduced.optimize(session);
187 }
188 }
189 Expression e = optimizeIfConstant(session, andOrType, left, right);
190 if (e == null) {
191 return optimizeN(this);
192 }
193 if (e instanceof ConditionAndOr) {
194 return optimizeN((ConditionAndOr) e);
195 }
196 return e;
197 }
198
199 private static Expression optimizeN(ConditionAndOr condition) {
200 if (condition.right instanceof ConditionAndOr) {
201 ConditionAndOr rightCondition = (ConditionAndOr) condition.right;
202 if (rightCondition.andOrType == condition.andOrType) {
203 return new ConditionAndOrN(condition.andOrType, condition.left, rightCondition.left,
204 rightCondition.right);
205 }
206 }
207 if (condition.right instanceof ConditionAndOrN) {
208 ConditionAndOrN rightCondition = (ConditionAndOrN) condition.right;
209 if (rightCondition.getAndOrType() == condition.andOrType) {
210 rightCondition.addFirst(condition.left);
211 return rightCondition;
212 }
213 }
214 return condition;
215 }
216
217 /**
218 * Optimize the condition if at least one part is constant.
219 *
220 * @param session the session
221 * @param andOrType the type
222 * @param left the left part of the condition
223 * @param right the right part of the condition
224 * @return the optimized condition, or {@code null} if condition cannot be optimized
225 */
226 static Expression optimizeIfConstant(SessionLocal session, int andOrType, Expression left, Expression right) {
227 if (!left.isConstant()) {
228 if (!right.isConstant()) {
229 return null;
230 } else {
231 return optimizeConstant(session, andOrType, right.getValue(session), left);
232 }
233 }
234 Value l = left.getValue(session);
235 if (!right.isConstant()) {
236 return optimizeConstant(session, andOrType, l, right);
237 }
238 Value r = right.getValue(session);
239 switch (andOrType) {
240 case AND: {
241 if (l.isFalse() || r.isFalse()) {
242 return ValueExpression.FALSE;
243 }
244 if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
245 return TypedValueExpression.UNKNOWN;
246 }
247 return ValueExpression.TRUE;
248 }
249 case OR: {
250 if (l.isTrue() || r.isTrue()) {
251 return ValueExpression.TRUE;
252 }
253 if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
254 return TypedValueExpression.UNKNOWN;
255 }
256 return ValueExpression.FALSE;
257 }
258 default:
259 throw DbException.getInternalError("type=" + andOrType);
260 }
261 }
262
263 private static Expression optimizeConstant(SessionLocal session, int andOrType, Value l, Expression right) {
264 if (l != ValueNull.INSTANCE) {
265 switch (andOrType) {
266 case AND:
267 return l.getBoolean() ? castToBoolean(session, right) : ValueExpression.FALSE;
268 case OR:
269 return l.getBoolean() ? ValueExpression.TRUE : castToBoolean(session, right);
270 default:
271 throw DbException.getInternalError("type=" + andOrType);
272 }
273 }
274 return null;
275 }
276
277 @Override
278 public void addFilterConditions(TableFilter filter) {
279 if (andOrType == AND) {
280 left.addFilterConditions(filter);
281 right.addFilterConditions(filter);
282 } else {
283 super.addFilterConditions(filter);
284 }
285 }
286
287 @Override
288 public void mapColumns(ColumnResolver resolver, int level, int state) {
289 left.mapColumns(resolver, level, state);
290 right.mapColumns(resolver, level, state);
291 }
292
293 @Override
294 public void setEvaluatable(TableFilter tableFilter, boolean b) {
295 left.setEvaluatable(tableFilter, b);
296 right.setEvaluatable(tableFilter, b);
297 }
298
299 @Override
300 public void updateAggregate(SessionLocal session, int stage) {
301 left.updateAggregate(session, stage);
302 right.updateAggregate(session, stage);
303 }
304
305 @Override
306 public boolean isEverything(ExpressionVisitor visitor) {
307 return left.isEverything(visitor) && right.isEverything(visitor);
308 }
309
310 @Override
311 public int getCost() {
312 return left.getCost() + right.getCost();
313 }
314
315 @Override
316 public int getSubexpressionCount() {
317 return 2;
318 }
319
320 @Override
321 public Expression getSubexpression(int index) {
322 switch (index) {
323 case 0:
324 return left;
325 case 1:
326 return right;
327 default:
328 throw new IndexOutOfBoundsException();
329 }
330 }
331
332 /**
333 * Optimize query according to the given condition. Example:
334 * (A AND B) OR (C AND B), the new condition B AND (A OR C) is returned
335 *
336 * @param left the session
337 * @param right the second condition
338 * @return null or the third condition
339 */
340 static Expression optimizeConditionAndOr(ConditionAndOr left, ConditionAndOr right) {
341 if (left.andOrType != AND || right.andOrType != AND) {
342 return null;
343 }
344 Expression leftLeft = left.getSubexpression(0), leftRight = left.getSubexpression(1);
345 Expression rightLeft = right.getSubexpression(0), rightRight = right.getSubexpression(1);
346 String rightLeftSQL = rightLeft.getSQL(DEFAULT_SQL_FLAGS);
347 String rightRightSQL = rightRight.getSQL(DEFAULT_SQL_FLAGS);
348 if (leftLeft.isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR)) {
349 String leftLeftSQL = leftLeft.getSQL(DEFAULT_SQL_FLAGS);
350 if (leftLeftSQL.equals(rightLeftSQL)) {
351 return new ConditionAndOr(AND, leftLeft, new ConditionAndOr(OR, leftRight, rightRight));
352 }
353 if (leftLeftSQL.equals(rightRightSQL)) {
354 return new ConditionAndOr(AND, leftLeft, new ConditionAndOr(OR, leftRight, rightLeft));
355 }
356 }
357 if (leftRight.isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR)) {
358 String leftRightSQL = leftRight.getSQL(DEFAULT_SQL_FLAGS);
359 if (leftRightSQL.equals(rightLeftSQL)) {
360 return new ConditionAndOr(AND, leftRight, new ConditionAndOr(OR, leftLeft, rightRight));
361 } else if (leftRightSQL.equals(rightRightSQL)) {
362 return new ConditionAndOr(AND, leftRight, new ConditionAndOr(OR, leftLeft, rightLeft));
363 }
364 }
365 return null;
366 }
367 }