Debian Codegraph @

src/main/org/h2/expression/condition/Comparison.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 java.util.ArrayList;
9 import org.h2.engine.SessionLocal;
10 import org.h2.expression.Expression;
11 import org.h2.expression.ExpressionColumn;
12 import org.h2.expression.ExpressionList;
13 import org.h2.expression.ExpressionVisitor;
14 import org.h2.expression.Parameter;
15 import org.h2.expression.TypedValueExpression;
16 import org.h2.expression.ValueExpression;
17 import org.h2.expression.aggregate.Aggregate;
18 import org.h2.expression.aggregate.AggregateType;
19 import org.h2.index.IndexCondition;
20 import org.h2.message.DbException;
21 import org.h2.table.Column;
22 import org.h2.table.ColumnResolver;
23 import org.h2.table.TableFilter;
24 import org.h2.value.DataType;
25 import org.h2.value.TypeInfo;
26 import org.h2.value.Value;
27 import org.h2.value.ValueBoolean;
28 import org.h2.value.ValueNull;
29 import org.h2.value.ValueRow;
30
31 /**
32 * Example comparison expressions are ID=1, NAME=NAME, NAME IS NULL.
33 *
34 * @author Thomas Mueller
35 * @author Noel Grandin
36 * @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
37 */
38 public final class Comparison extends Condition {
39
40 /**
41 * The comparison type meaning = as in ID=1.
42 */
43 public static final int EQUAL = 0;
44
45 /**
46 * The comparison type meaning <> as in ID<>1.
47 */
48 public static final int NOT_EQUAL = 1;
49
50 /**
51 * The comparison type meaning < as in ID<1.
52 */
53 public static final int SMALLER = 2;
54
55 /**
56 * The comparison type meaning > as in ID>1.
57 */
58 public static final int BIGGER = 3;
59
60 /**
61 * The comparison type meaning <= as in ID<=1.
62 */
63 public static final int SMALLER_EQUAL = 4;
64
65 /**
66 * The comparison type meaning >= as in ID>=1.
67 */
68 public static final int BIGGER_EQUAL = 5;
69
70 /**
71 * The comparison type meaning ID IS NOT DISTINCT FROM 1.
72 */
73 public static final int EQUAL_NULL_SAFE = 6;
74
75 /**
76 * The comparison type meaning ID IS DISTINCT FROM 1.
77 */
78 public static final int NOT_EQUAL_NULL_SAFE = 7;
79
80 /**
81 * This is a comparison type that is only used for spatial index
82 * conditions (operator "&&").
83 */
84 public static final int SPATIAL_INTERSECTS = 8;
85
86 static final String[] COMPARE_TYPES = { "=", "<>", "<", ">", "<=", ">=", //
87 "IS NOT DISTINCT FROM", "IS DISTINCT FROM", //
88 "&&" };
89
90 /**
91 * This is a pseudo comparison type that is only used for index conditions.
92 * It means the comparison will always yield FALSE. Example: 1=0.
93 */
94 public static final int FALSE = 9;
95
96 /**
97 * This is a pseudo comparison type that is only used for index conditions.
98 * It means equals any value of a list. Example: IN(1, 2, 3).
99 */
100 public static final int IN_LIST = 10;
101
102 /**
103 * This is a pseudo comparison type that is only used for index conditions.
104 * It means equals any value of an ARRAY. Example: ARRAY[1, 2, 3].
105 */
106 public static final int IN_ARRAY = 11;
107
108 /**
109 * This is a pseudo comparison type that is only used for index conditions.
110 * It means equals any value of a list. Example: IN(SELECT ...).
111 */
112 public static final int IN_QUERY = 12;
113
114 private int compareType;
115 private Expression left;
116 private Expression right;
117 private final boolean whenOperand;
118
119 public Comparison(int compareType, Expression left, Expression right, boolean whenOperand) {
120 this.left = left;
121 this.right = right;
122 this.compareType = compareType;
123 this.whenOperand = whenOperand;
124 }
125
126 @Override
127 public boolean needParentheses() {
128 return true;
129 }
130
131 @Override
132 public StringBuilder getUnenclosedSQL(StringBuilder builder, int sqlFlags) {
133 return getWhenSQL(left.getSQL(builder, sqlFlags, AUTO_PARENTHESES), sqlFlags);
134 }
135
136 @Override
137 public StringBuilder getWhenSQL(StringBuilder builder, int sqlFlags) {
138 builder.append(' ').append(COMPARE_TYPES[compareType]).append(' ');
139 return right.getSQL(builder, sqlFlags,
140 right instanceof Aggregate && ((Aggregate) right).getAggregateType() == AggregateType.ANY
141 ? WITH_PARENTHESES
142 : AUTO_PARENTHESES);
143 }
144
145 @Override
146 public Expression optimize(SessionLocal session) {
147 left = left.optimize(session);
148 right = right.optimize(session);
149 check: {
150 TypeInfo leftType = left.getType(), rightType = right.getType();
151 if (session.getMode().numericWithBooleanComparison) {
152 switch (compareType) {
153 case EQUAL:
154 case NOT_EQUAL:
155 case EQUAL_NULL_SAFE:
156 case NOT_EQUAL_NULL_SAFE:
157 int lValueType = leftType.getValueType();
158 if (lValueType == Value.BOOLEAN) {
159 if (DataType.isNumericType(rightType.getValueType())) {
160 break check;
161 }
162 } else if (DataType.isNumericType(lValueType) && rightType.getValueType() == Value.BOOLEAN) {
163 break check;
164 }
165 }
166 }
167 TypeInfo.checkComparable(leftType, rightType);
168 }
169 if (whenOperand) {
170 return this;
171 }
172 if (right instanceof ExpressionColumn) {
173 if (left.isConstant() || left instanceof Parameter) {
174 Expression temp = left;
175 left = right;
176 right = temp;
177 compareType = getReversedCompareType(compareType);
178 }
179 }
180 if (left instanceof ExpressionColumn) {
181 if (right.isConstant()) {
182 Value r = right.getValue(session);
183 if (r == ValueNull.INSTANCE) {
184 if ((compareType & ~1) != EQUAL_NULL_SAFE) {
185 return TypedValueExpression.UNKNOWN;
186 }
187 }
188 TypeInfo colType = left.getType(), constType = r.getType();
189 int constValueType = constType.getValueType();
190 if (constValueType != colType.getValueType() || constValueType >= Value.ARRAY) {
191 TypeInfo resType = TypeInfo.getHigherType(colType, constType);
192 // If not, the column values will need to be promoted
193 // to constant type, but vise versa, then let's do this here
194 // once.
195 if (constValueType != resType.getValueType() || constValueType >= Value.ARRAY) {
196 Column column = ((ExpressionColumn) left).getColumn();
197 right = ValueExpression.get(r.convertTo(resType, session, column));
198 }
199 }
200 } else if (right instanceof Parameter) {
201 ((Parameter) right).setColumn(((ExpressionColumn) left).getColumn());
202 }
203 }
204 if (left.isConstant() && right.isConstant()) {
205 return ValueExpression.getBoolean(getValue(session));
206 }
207 if (left.isNullConstant() || right.isNullConstant()) {
208 // TODO NULL handling: maybe issue a warning when comparing with
209 // a NULL constants
210 if ((compareType & ~1) != EQUAL_NULL_SAFE) {
211 return TypedValueExpression.UNKNOWN;
212 } else {
213 Expression e = left.isNullConstant() ? right : left;
214 int type = e.getType().getValueType();
215 if (type != Value.UNKNOWN && type != Value.ROW) {
216 return new NullPredicate(e, compareType == NOT_EQUAL_NULL_SAFE, false);
217 }
218 }
219 }
220 return this;
221 }
222
223 @Override
224 public Value getValue(SessionLocal session) {
225 Value l = left.getValue(session);
226 // Optimization: do not evaluate right if not necessary
227 if (l == ValueNull.INSTANCE && (compareType & ~1) != EQUAL_NULL_SAFE) {
228 return ValueNull.INSTANCE;
229 }
230 return compare(session, l, right.getValue(session), compareType);
231 }
232
233 @Override
234 public boolean getWhenValue(SessionLocal session, Value left) {
235 if (!whenOperand) {
236 return super.getWhenValue(session, left);
237 }
238 // Optimization: do not evaluate right if not necessary
239 if (left == ValueNull.INSTANCE && (compareType & ~1) != EQUAL_NULL_SAFE) {
240 return false;
241 }
242 return compare(session, left, right.getValue(session), compareType).isTrue();
243 }
244
245 /**
246 * Compare two values.
247 *
248 * @param session the session
249 * @param l the first value
250 * @param r the second value
251 * @param compareType the compare type
252 * @return result of comparison, either TRUE, FALSE, or NULL
253 */
254 static Value compare(SessionLocal session, Value l, Value r, int compareType) {
255 Value result;
256 switch (compareType) {
257 case EQUAL: {
258 int cmp = session.compareWithNull(l, r, true);
259 if (cmp == 0) {
260 result = ValueBoolean.TRUE;
261 } else if (cmp == Integer.MIN_VALUE) {
262 result = ValueNull.INSTANCE;
263 } else {
264 result = ValueBoolean.FALSE;
265 }
266 break;
267 }
268 case EQUAL_NULL_SAFE:
269 result = ValueBoolean.get(session.areEqual(l, r));
270 break;
271 case NOT_EQUAL: {
272 int cmp = session.compareWithNull(l, r, true);
273 if (cmp == 0) {
274 result = ValueBoolean.FALSE;
275 } else if (cmp == Integer.MIN_VALUE) {
276 result = ValueNull.INSTANCE;
277 } else {
278 result = ValueBoolean.TRUE;
279 }
280 break;
281 }
282 case NOT_EQUAL_NULL_SAFE:
283 result = ValueBoolean.get(!session.areEqual(l, r));
284 break;
285 case BIGGER_EQUAL: {
286 int cmp = session.compareWithNull(l, r, false);
287 if (cmp >= 0) {
288 result = ValueBoolean.TRUE;
289 } else if (cmp == Integer.MIN_VALUE) {
290 result = ValueNull.INSTANCE;
291 } else {
292 result = ValueBoolean.FALSE;
293 }
294 break;
295 }
296 case BIGGER: {
297 int cmp = session.compareWithNull(l, r, false);
298 if (cmp > 0) {
299 result = ValueBoolean.TRUE;
300 } else if (cmp == Integer.MIN_VALUE) {
301 result = ValueNull.INSTANCE;
302 } else {
303 result = ValueBoolean.FALSE;
304 }
305 break;
306 }
307 case SMALLER_EQUAL: {
308 int cmp = session.compareWithNull(l, r, false);
309 if (cmp == Integer.MIN_VALUE) {
310 result = ValueNull.INSTANCE;
311 } else {
312 result = ValueBoolean.get(cmp <= 0);
313 }
314 break;
315 }
316 case SMALLER: {
317 int cmp = session.compareWithNull(l, r, false);
318 if (cmp == Integer.MIN_VALUE) {
319 result = ValueNull.INSTANCE;
320 } else {
321 result = ValueBoolean.get(cmp < 0);
322 }
323 break;
324 }
325 case SPATIAL_INTERSECTS: {
326 if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
327 result = ValueNull.INSTANCE;
328 } else {
329 result = ValueBoolean.get(l.convertToGeometry(null).intersectsBoundingBox(r.convertToGeometry(null)));
330 }
331 break;
332 }
333 default:
334 throw DbException.getInternalError("type=" + compareType);
335 }
336 return result;
337 }
338
339 @Override
340 public boolean isWhenConditionOperand() {
341 return whenOperand;
342 }
343
344 private static int getReversedCompareType(int type) {
345 switch (type) {
346 case EQUAL:
347 case EQUAL_NULL_SAFE:
348 case NOT_EQUAL:
349 case NOT_EQUAL_NULL_SAFE:
350 case SPATIAL_INTERSECTS:
351 return type;
352 case BIGGER_EQUAL:
353 return SMALLER_EQUAL;
354 case BIGGER:
355 return SMALLER;
356 case SMALLER_EQUAL:
357 return BIGGER_EQUAL;
358 case SMALLER:
359 return BIGGER;
360 default:
361 throw DbException.getInternalError("type=" + type);
362 }
363 }
364
365 @Override
366 public Expression getNotIfPossible(SessionLocal session) {
367 if (compareType == SPATIAL_INTERSECTS || whenOperand) {
368 return null;
369 }
370 return new Comparison(getNotCompareType(compareType), left, right, false);
371 }
372
373 static int getNotCompareType(int type) {
374 switch (type) {
375 case EQUAL:
376 return NOT_EQUAL;
377 case EQUAL_NULL_SAFE:
378 return NOT_EQUAL_NULL_SAFE;
379 case NOT_EQUAL:
380 return EQUAL;
381 case NOT_EQUAL_NULL_SAFE:
382 return EQUAL_NULL_SAFE;
383 case BIGGER_EQUAL:
384 return SMALLER;
385 case BIGGER:
386 return SMALLER_EQUAL;
387 case SMALLER_EQUAL:
388 return BIGGER;
389 case SMALLER:
390 return BIGGER_EQUAL;
391 default:
392 throw DbException.getInternalError("type=" + type);
393 }
394 }
395
396 @Override
397 public void createIndexConditions(SessionLocal session, TableFilter filter) {
398 if (!whenOperand) {
399 createIndexConditions(filter, left, right, compareType);
400 }
401 }
402
403 static void createIndexConditions(TableFilter filter, Expression left, Expression right, int compareType) {
404 if (compareType == NOT_EQUAL || compareType == NOT_EQUAL_NULL_SAFE) {
405 return;
406 }
407 if (!filter.getTable().isQueryComparable()) {
408 return;
409 }
410 if (compareType != SPATIAL_INTERSECTS) {
411 boolean lIsList = left instanceof ExpressionList, rIsList = right instanceof ExpressionList;
412 if (lIsList) {
413 if (rIsList) {
414 createIndexConditions(filter, (ExpressionList) left, (ExpressionList) right, compareType);
415 } else if (right instanceof ValueExpression) {
416 createIndexConditions(filter, (ExpressionList) left, (ValueExpression) right, compareType);
417 }
418 } else if (rIsList && left instanceof ValueExpression) {
419 createIndexConditions(filter, (ExpressionList) right, (ValueExpression) left,
420 getReversedCompareType(compareType));
421 return;
422 }
423 }
424 ExpressionColumn l = null;
425 if (left instanceof ExpressionColumn) {
426 l = (ExpressionColumn) left;
427 if (filter != l.getTableFilter()) {
428 l = null;
429 }
430 }
431 ExpressionColumn r = null;
432 if (right instanceof ExpressionColumn) {
433 r = (ExpressionColumn) right;
434 if (filter != r.getTableFilter()) {
435 r = null;
436 }
437 }
438 // one side must be from the current filter
439 if ((l == null) == (r == null)) {
440 return;
441 }
442 if (l == null) {
443 if (!left.isEverything(ExpressionVisitor.getNotFromResolverVisitor(filter))) {
444 return;
445 }
446 } else { // r == null
447 if (!right.isEverything(ExpressionVisitor.getNotFromResolverVisitor(filter))) {
448 return;
449 }
450 }
451 switch (compareType) {
452 case EQUAL:
453 case EQUAL_NULL_SAFE:
454 case BIGGER:
455 case BIGGER_EQUAL:
456 case SMALLER_EQUAL:
457 case SMALLER:
458 case SPATIAL_INTERSECTS:
459 if (l != null) {
460 TypeInfo colType = l.getType();
461 if (TypeInfo.haveSameOrdering(colType, TypeInfo.getHigherType(colType, right.getType()))) {
462 filter.addIndexCondition(IndexCondition.get(compareType, l, right));
463 }
464 } else {
465 @SuppressWarnings("null")
466 TypeInfo colType = r.getType();
467 if (TypeInfo.haveSameOrdering(colType, TypeInfo.getHigherType(colType, left.getType()))) {
468 filter.addIndexCondition(IndexCondition.get(getReversedCompareType(compareType), r, left));
469 }
470 }
471 break;
472 default:
473 throw DbException.getInternalError("type=" + compareType);
474 }
475 }
476
477 private static void createIndexConditions(TableFilter filter, ExpressionList left, ExpressionList right,
478 int compareType) {
479 int c = left.getSubexpressionCount();
480 if (c == 0 || c != right.getSubexpressionCount()) {
481 return;
482 }
483 if (compareType != EQUAL && compareType != EQUAL_NULL_SAFE) {
484 if (c > 1) {
485 if (compareType == BIGGER) {
486 compareType = BIGGER_EQUAL;
487 } else if (compareType == SMALLER) {
488 compareType = SMALLER_EQUAL;
489 }
490 }
491 c = 1;
492 }
493 for (int i = 0; i < c; i++) {
494 createIndexConditions(filter, left.getSubexpression(i), right.getSubexpression(i), compareType);
495 }
496 }
497
498 private static void createIndexConditions(TableFilter filter, ExpressionList left, ValueExpression right,
499 int compareType) {
500 int c = left.getSubexpressionCount();
501 if (c == 0) {
502 return;
503 } else if (c == 1) {
504 createIndexConditions(filter, left.getSubexpression(0), right, compareType);
505 } else if (c > 1) {
506 Value v = right.getValue(null);
507 if (v.getValueType() == Value.ROW) {
508 Value[] values = ((ValueRow) v).getList();
509 if (c != values.length) {
510 return;
511 }
512 if (compareType != EQUAL && compareType != EQUAL_NULL_SAFE) {
513 if (compareType == BIGGER) {
514 compareType = BIGGER_EQUAL;
515 } else if (compareType == SMALLER) {
516 compareType = SMALLER_EQUAL;
517 }
518 c = 1;
519 }
520 for (int i = 0; i < c; i++) {
521 createIndexConditions(filter, left.getSubexpression(i), ValueExpression.get(values[i]),
522 compareType);
523 }
524 }
525 }
526 }
527
528 @Override
529 public void setEvaluatable(TableFilter tableFilter, boolean b) {
530 left.setEvaluatable(tableFilter, b);
531 if (right != null) {
532 right.setEvaluatable(tableFilter, b);
533 }
534 }
535
536 @Override
537 public void updateAggregate(SessionLocal session, int stage) {
538 left.updateAggregate(session, stage);
539 if (right != null) {
540 right.updateAggregate(session, stage);
541 }
542 }
543
544 @Override
545 public void mapColumns(ColumnResolver resolver, int level, int state) {
546 left.mapColumns(resolver, level, state);
547 right.mapColumns(resolver, level, state);
548 }
549
550 @Override
551 public boolean isEverything(ExpressionVisitor visitor) {
552 return left.isEverything(visitor) && right.isEverything(visitor);
553 }
554
555 @Override
556 public int getCost() {
557 return left.getCost() + right.getCost() + 1;
558 }
559
560 /**
561 * Get the other expression if this is an equals comparison and the other
562 * expression matches.
563 *
564 * @param match the expression that should match
565 * @return null if no match, the other expression if there is a match
566 */
567 Expression getIfEquals(Expression match) {
568 if (compareType == EQUAL) {
569 String sql = match.getSQL(DEFAULT_SQL_FLAGS);
570 if (left.getSQL(DEFAULT_SQL_FLAGS).equals(sql)) {
571 return right;
572 } else if (right.getSQL(DEFAULT_SQL_FLAGS).equals(sql)) {
573 return left;
574 }
575 }
576 return null;
577 }
578
579 /**
580 * Get an additional condition if possible. Example: given two conditions
581 * A=B AND B=C, the new condition A=C is returned.
582 *
583 * @param session the session
584 * @param other the second condition
585 * @return null or the third condition for indexes
586 */
587 Expression getAdditionalAnd(SessionLocal session, Comparison other) {
588 if (compareType == EQUAL && other.compareType == EQUAL && !whenOperand) {
589 boolean lc = left.isConstant();
590 boolean rc = right.isConstant();
591 boolean l2c = other.left.isConstant();
592 boolean r2c = other.right.isConstant();
593 String l = left.getSQL(DEFAULT_SQL_FLAGS);
594 String l2 = other.left.getSQL(DEFAULT_SQL_FLAGS);
595 String r = right.getSQL(DEFAULT_SQL_FLAGS);
596 String r2 = other.right.getSQL(DEFAULT_SQL_FLAGS);
597 // a=b AND a=c
598 // must not compare constants. example: NOT(B=2 AND B=3)
599 if (!(rc && r2c) && l.equals(l2)) {
600 return new Comparison(EQUAL, right, other.right, false);
601 } else if (!(rc && l2c) && l.equals(r2)) {
602 return new Comparison(EQUAL, right, other.left, false);
603 } else if (!(lc && r2c) && r.equals(l2)) {
604 return new Comparison(EQUAL, left, other.right, false);
605 } else if (!(lc && l2c) && r.equals(r2)) {
606 return new Comparison(EQUAL, left, other.left, false);
607 }
608 }
609 return null;
610 }
611
612 /**
613 * Replace the OR condition with IN condition if possible. Example: given
614 * the two conditions A=1 OR A=2, the new condition A IN(1, 2) is returned.
615 *
616 * @param session the session
617 * @param other the second condition
618 * @return null or the joined IN condition
619 */
620 Expression optimizeOr(SessionLocal session, Comparison other) {
621 if (compareType == EQUAL && other.compareType == EQUAL) {
622 Expression left2 = other.left;
623 Expression right2 = other.right;
624 String l2 = left2.getSQL(DEFAULT_SQL_FLAGS);
625 String r2 = right2.getSQL(DEFAULT_SQL_FLAGS);
626 if (left.isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR)) {
627 String l = left.getSQL(DEFAULT_SQL_FLAGS);
628 if (l.equals(l2)) {
629 return getConditionIn(left, right, right2);
630 } else if (l.equals(r2)) {
631 return getConditionIn(left, right, left2);
632 }
633 }
634 if (right.isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR)) {
635 String r = right.getSQL(DEFAULT_SQL_FLAGS);
636 if (r.equals(l2)) {
637 return getConditionIn(right, left, right2);
638 } else if (r.equals(r2)) {
639 return getConditionIn(right, left, left2);
640 }
641 }
642 }
643 return null;
644 }
645
646 private static ConditionIn getConditionIn(Expression left, Expression value1,
647 Expression value2) {
648 ArrayList<Expression> right = new ArrayList<>(2);
649 right.add(value1);
650 right.add(value2);
651 return new ConditionIn(left, false, false, right);
652 }
653
654 @Override
655 public int getSubexpressionCount() {
656 return 2;
657 }
658
659 @Override
660 public Expression getSubexpression(int index) {
661 switch (index) {
662 case 0:
663 return left;
664 case 1:
665 return right;
666 default:
667 throw new IndexOutOfBoundsException();
668 }
669 }
670
671 }