Debian Codegraph @

src/main/org/h2/expression/condition/CompareLike.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.regex.Pattern;
9 import java.util.regex.PatternSyntaxException;
10 import org.h2.api.ErrorCode;
11 import org.h2.engine.Database;
12 import org.h2.engine.SessionLocal;
13 import org.h2.expression.Expression;
14 import org.h2.expression.ExpressionColumn;
15 import org.h2.expression.ExpressionVisitor;
16 import org.h2.expression.SearchedCase;
17 import org.h2.expression.TypedValueExpression;
18 import org.h2.expression.ValueExpression;
19 import org.h2.index.IndexCondition;
20 import org.h2.message.DbException;
21 import org.h2.table.ColumnResolver;
22 import org.h2.table.TableFilter;
23 import org.h2.value.CompareMode;
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.ValueVarchar;
30 import org.h2.value.ValueVarcharIgnoreCase;
31
32 /**
33 * Pattern matching comparison expression: WHERE NAME LIKE ?
34 */
35 public final class CompareLike extends Condition {
36
37 /**
38 * The type of comparison.
39 */
40 public enum LikeType {
41 /**
42 * LIKE.
43 */
44 LIKE,
45
46 /**
47 * ILIKE (case-insensitive LIKE).
48 */
49 ILIKE,
50
51 /**
52 * REGEXP
53 */
54 REGEXP
55 }
56
57 private static final int MATCH = 0, ONE = 1, ANY = 2;
58
59 private final CompareMode compareMode;
60 private final String defaultEscape;
61
62 private final LikeType likeType;
63 private Expression left;
64
65 private final boolean not;
66
67 private final boolean whenOperand;
68
69 private Expression right;
70 private Expression escape;
71
72 private boolean isInit;
73
74 private char[] patternChars;
75 private String patternString;
76 /** one of MATCH / ONE / ANY */
77 private int[] patternTypes;
78 private int patternLength;
79
80 private Pattern patternRegexp;
81
82 private boolean ignoreCase;
83 private boolean fastCompare;
84 private boolean invalidPattern;
85 /** indicates that we can shortcut the comparison and use startsWith */
86 private boolean shortcutToStartsWith;
87 /** indicates that we can shortcut the comparison and use endsWith */
88 private boolean shortcutToEndsWith;
89 /** indicates that we can shortcut the comparison and use contains */
90 private boolean shortcutToContains;
91
92 public CompareLike(Database db, Expression left, boolean not, boolean whenOperand, Expression right,
93 Expression escape, LikeType likeType) {
94 this(db.getCompareMode(), db.getSettings().defaultEscape, left, not, whenOperand, right, escape, likeType);
95 }
96
97 public CompareLike(CompareMode compareMode, String defaultEscape, Expression left, boolean not,
98 boolean whenOperand, Expression right, Expression escape, LikeType likeType) {
99 this.compareMode = compareMode;
100 this.defaultEscape = defaultEscape;
101 this.likeType = likeType;
102 this.left = left;
103 this.not = not;
104 this.whenOperand = whenOperand;
105 this.right = right;
106 this.escape = escape;
107 }
108
109 private static Character getEscapeChar(String s) {
110 return s == null || s.isEmpty() ? null : s.charAt(0);
111 }
112
113 @Override
114 public boolean needParentheses() {
115 return true;
116 }
117
118 @Override
119 public StringBuilder getUnenclosedSQL(StringBuilder builder, int sqlFlags) {
120 return getWhenSQL(left.getSQL(builder, sqlFlags, AUTO_PARENTHESES), sqlFlags);
121 }
122
123 @Override
124 public StringBuilder getWhenSQL(StringBuilder builder, int sqlFlags) {
125 if (not) {
126 builder.append(" NOT");
127 }
128 switch (likeType) {
129 case LIKE:
130 case ILIKE:
131 builder.append(likeType == LikeType.LIKE ? " LIKE " : " ILIKE ");
132 right.getSQL(builder, sqlFlags, AUTO_PARENTHESES);
133 if (escape != null) {
134 escape.getSQL(builder.append(" ESCAPE "), sqlFlags, AUTO_PARENTHESES);
135 }
136 break;
137 case REGEXP:
138 builder.append(" REGEXP ");
139 right.getSQL(builder, sqlFlags, AUTO_PARENTHESES);
140 break;
141 default:
142 throw DbException.getUnsupportedException(likeType.name());
143 }
144 return builder;
145 }
146
147 @Override
148 public Expression optimize(SessionLocal session) {
149 left = left.optimize(session);
150 right = right.optimize(session);
151 if (likeType == LikeType.ILIKE || left.getType().getValueType() == Value.VARCHAR_IGNORECASE) {
152 ignoreCase = true;
153 }
154 if (escape != null) {
155 escape = escape.optimize(session);
156 }
157 if (whenOperand) {
158 return this;
159 }
160 if (left.isValueSet()) {
161 Value l = left.getValue(session);
162 if (l == ValueNull.INSTANCE) {
163 // NULL LIKE something > NULL
164 return TypedValueExpression.UNKNOWN;
165 }
166 }
167 if (right.isValueSet() && (escape == null || escape.isValueSet())) {
168 if (left.isValueSet()) {
169 return ValueExpression.getBoolean(getValue(session));
170 }
171 Value r = right.getValue(session);
172 if (r == ValueNull.INSTANCE) {
173 // something LIKE NULL > NULL
174 return TypedValueExpression.UNKNOWN;
175 }
176 Value e = escape == null ? null : escape.getValue(session);
177 if (e == ValueNull.INSTANCE) {
178 return TypedValueExpression.UNKNOWN;
179 }
180 String p = r.getString();
181 initPattern(p, getEscapeChar(e));
182 if (invalidPattern) {
183 return TypedValueExpression.UNKNOWN;
184 }
185 if (likeType != LikeType.REGEXP && "%".equals(p)) {
186 // optimization for X LIKE '%'
187 return new SearchedCase(new Expression[] { new NullPredicate(left, true, false),
188 ValueExpression.getBoolean(!not), TypedValueExpression.UNKNOWN }).optimize(session);
189 }
190 if (isFullMatch()) {
191 // optimization for X LIKE 'Hello': convert to X = 'Hello'
192 Value value = ignoreCase ? ValueVarcharIgnoreCase.get(patternString) : ValueVarchar.get(patternString);
193 Expression expr = ValueExpression.get(value);
194 return new Comparison(not ? Comparison.NOT_EQUAL : Comparison.EQUAL, left, expr, false)
195 .optimize(session);
196 }
197 isInit = true;
198 }
199 return this;
200 }
201
202 private Character getEscapeChar(Value e) {
203 if (e == null) {
204 return getEscapeChar(defaultEscape);
205 }
206 String es = e.getString();
207 Character esc;
208 if (es == null) {
209 esc = getEscapeChar(defaultEscape);
210 } else if (es.length() == 0) {
211 esc = null;
212 } else if (es.length() > 1) {
213 throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, es);
214 } else {
215 esc = es.charAt(0);
216 }
217 return esc;
218 }
219
220 @Override
221 public void createIndexConditions(SessionLocal session, TableFilter filter) {
222 if (not || whenOperand || likeType == LikeType.REGEXP || !(left instanceof ExpressionColumn)) {
223 return;
224 }
225 ExpressionColumn l = (ExpressionColumn) left;
226 if (filter != l.getTableFilter() || !TypeInfo.haveSameOrdering(l.getType(),
227 ignoreCase ? TypeInfo.TYPE_VARCHAR_IGNORECASE : TypeInfo.TYPE_VARCHAR)) {
228 return;
229 }
230 // parameters are always evaluatable, but
231 // we need to check if the value is set
232 // (at prepare time)
233 // otherwise we would need to prepare at execute time,
234 // which may be slower (possibly not in this case)
235 if (!right.isEverything(ExpressionVisitor.INDEPENDENT_VISITOR)) {
236 return;
237 }
238 if (escape != null && !escape.isEverything(ExpressionVisitor.INDEPENDENT_VISITOR)) {
239 return;
240 }
241 String p = right.getValue(session).getString();
242 if (!isInit) {
243 Value e = escape == null ? null : escape.getValue(session);
244 if (e == ValueNull.INSTANCE) {
245 // should already be optimized
246 throw DbException.getInternalError();
247 }
248 initPattern(p, getEscapeChar(e));
249 }
250 if (invalidPattern) {
251 return;
252 }
253 if (patternLength <= 0 || patternTypes[0] != MATCH) {
254 // can't use an index
255 return;
256 }
257 if (!DataType.isStringType(l.getColumn().getType().getValueType())) {
258 // column is not a varchar - can't use the index
259 return;
260 }
261 // Get the MATCH prefix and see if we can create an index condition from
262 // that.
263 int maxMatch = 0;
264 StringBuilder buff = new StringBuilder();
265 while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
266 buff.append(patternChars[maxMatch++]);
267 }
268 String begin = buff.toString();
269 if (maxMatch == patternLength) {
270 filter.addIndexCondition(IndexCondition.get(Comparison.EQUAL, l,
271 ValueExpression.get(ValueVarchar.get(begin))));
272 } else {
273 // TODO check if this is correct according to Unicode rules
274 // (code points)
275 String end;
276 if (begin.length() > 0) {
277 filter.addIndexCondition(IndexCondition.get(
278 Comparison.BIGGER_EQUAL, l,
279 ValueExpression.get(ValueVarchar.get(begin))));
280 char next = begin.charAt(begin.length() - 1);
281 // search the 'next' unicode character (or at least a character
282 // that is higher)
283 for (int i = 1; i < 2000; i++) {
284 end = begin.substring(0, begin.length() - 1) + (char) (next + i);
285 if (compareMode.compareString(begin, end, ignoreCase) < 0) {
286 filter.addIndexCondition(IndexCondition.get(
287 Comparison.SMALLER, l,
288 ValueExpression.get(ValueVarchar.get(end))));
289 break;
290 }
291 }
292 }
293 }
294 }
295
296 @Override
297 public Value getValue(SessionLocal session) {
298 return getValue(session, left.getValue(session));
299 }
300
301 @Override
302 public boolean getWhenValue(SessionLocal session, Value left) {
303 if (!whenOperand) {
304 return super.getWhenValue(session, left);
305 }
306 return getValue(session, left).isTrue();
307 }
308
309 private Value getValue(SessionLocal session, Value left) {
310 if (left == ValueNull.INSTANCE) {
311 return ValueNull.INSTANCE;
312 }
313 if (!isInit) {
314 Value r = right.getValue(session);
315 if (r == ValueNull.INSTANCE) {
316 return ValueNull.INSTANCE;
317 }
318 String p = r.getString();
319 Value e = escape == null ? null : escape.getValue(session);
320 if (e == ValueNull.INSTANCE) {
321 return ValueNull.INSTANCE;
322 }
323 initPattern(p, getEscapeChar(e));
324 }
325 if (invalidPattern) {
326 return ValueNull.INSTANCE;
327 }
328 String value = left.getString();
329 boolean result;
330 if (likeType == LikeType.REGEXP) {
331 result = patternRegexp.matcher(value).find();
332 } else if (shortcutToStartsWith) {
333 result = value.regionMatches(ignoreCase, 0, patternString, 0, patternLength - 1);
334 } else if (shortcutToEndsWith) {
335 result = value.regionMatches(ignoreCase, value.length() -
336 patternLength + 1, patternString, 1, patternLength - 1);
337 } else if (shortcutToContains) {
338 String p = patternString.substring(1, patternString.length() - 1);
339 if (ignoreCase) {
340 result = containsIgnoreCase(value, p);
341 } else {
342 result = value.contains(p);
343 }
344 } else {
345 result = compareAt(value, 0, 0, value.length(), patternChars, patternTypes);
346 }
347 return ValueBoolean.get(not ^ result);
348 }
349
350 private static boolean containsIgnoreCase(String src, String what) {
351 final int length = what.length();
352 if (length == 0) {
353 // Empty string is contained
354 return true;
355 }
356
357 final char firstLo = Character.toLowerCase(what.charAt(0));
358 final char firstUp = Character.toUpperCase(what.charAt(0));
359
360 for (int i = src.length() - length; i >= 0; i--) {
361 // Quick check before calling the more expensive regionMatches()
362 final char ch = src.charAt(i);
363 if (ch != firstLo && ch != firstUp) {
364 continue;
365 }
366 if (src.regionMatches(true, i, what, 0, length)) {
367 return true;
368 }
369 }
370
371 return false;
372 }
373
374 private boolean compareAt(String s, int pi, int si, int sLen,
375 char[] pattern, int[] types) {
376 for (; pi < patternLength; pi++) {
377 switch (types[pi]) {
378 case MATCH:
379 if ((si >= sLen) || !compare(pattern, s, pi, si++)) {
380 return false;
381 }
382 break;
383 case ONE:
384 if (si++ >= sLen) {
385 return false;
386 }
387 break;
388 case ANY:
389 if (++pi >= patternLength) {
390 return true;
391 }
392 while (si < sLen) {
393 if (compare(pattern, s, pi, si) &&
394 compareAt(s, pi, si, sLen, pattern, types)) {
395 return true;
396 }
397 si++;
398 }
399 return false;
400 default:
401 throw DbException.getInternalError(Integer.toString(types[pi]));
402 }
403 }
404 return si == sLen;
405 }
406
407 private boolean compare(char[] pattern, String s, int pi, int si) {
408 return pattern[pi] == s.charAt(si) ||
409 (!fastCompare && compareMode.equalsChars(patternString, pi, s,
410 si, ignoreCase));
411 }
412
413 @Override
414 public boolean isWhenConditionOperand() {
415 return whenOperand;
416 }
417
418 /**
419 * Test if the value matches the pattern.
420 *
421 * @param testPattern the pattern
422 * @param value the value
423 * @param escapeChar the escape character
424 * @return true if the value matches
425 */
426 public boolean test(String testPattern, String value, char escapeChar) {
427 initPattern(testPattern, escapeChar);
428 return test(value);
429 }
430
431 /**
432 * Test if the value matches the initialized pattern.
433 *
434 * @param value the value
435 * @return true if the value matches
436 */
437 public boolean test(String value) {
438 if (invalidPattern) {
439 return false;
440 }
441 return compareAt(value, 0, 0, value.length(), patternChars, patternTypes);
442 }
443
444 /**
445 * Initializes the pattern.
446 *
447 * @param p the pattern
448 * @param escapeChar the escape character
449 */
450 public void initPattern(String p, Character escapeChar) {
451 if (compareMode.getName().equals(CompareMode.OFF) && !ignoreCase) {
452 fastCompare = true;
453 }
454 if (likeType == LikeType.REGEXP) {
455 patternString = p;
456 try {
457 if (ignoreCase) {
458 patternRegexp = Pattern.compile(p, Pattern.CASE_INSENSITIVE);
459 } else {
460 patternRegexp = Pattern.compile(p);
461 }
462 } catch (PatternSyntaxException e) {
463 throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, p);
464 }
465 return;
466 }
467 patternLength = 0;
468 if (p == null) {
469 patternTypes = null;
470 patternChars = null;
471 return;
472 }
473 int len = p.length();
474 patternChars = new char[len];
475 patternTypes = new int[len];
476 boolean lastAny = false;
477 for (int i = 0; i < len; i++) {
478 char c = p.charAt(i);
479 int type;
480 if (escapeChar != null && escapeChar == c) {
481 if (i >= len - 1) {
482 invalidPattern = true;
483 return;
484 }
485 c = p.charAt(++i);
486 type = MATCH;
487 lastAny = false;
488 } else if (c == '%') {
489 if (lastAny) {
490 continue;
491 }
492 type = ANY;
493 lastAny = true;
494 } else if (c == '_') {
495 type = ONE;
496 } else {
497 type = MATCH;
498 lastAny = false;
499 }
500 patternTypes[patternLength] = type;
501 patternChars[patternLength++] = c;
502 }
503 for (int i = 0; i < patternLength - 1; i++) {
504 if ((patternTypes[i] == ANY) && (patternTypes[i + 1] == ONE)) {
505 patternTypes[i] = ONE;
506 patternTypes[i + 1] = ANY;
507 }
508 }
509 patternString = new String(patternChars, 0, patternLength);
510
511 // Clear optimizations
512 shortcutToStartsWith = false;
513 shortcutToEndsWith = false;
514 shortcutToContains = false;
515
516 // optimizes the common case of LIKE 'foo%'
517 if (compareMode.getName().equals(CompareMode.OFF) && patternLength > 1) {
518 int maxMatch = 0;
519 while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
520 maxMatch++;
521 }
522 if (maxMatch == patternLength - 1 && patternTypes[patternLength - 1] == ANY) {
523 shortcutToStartsWith = true;
524 return;
525 }
526 }
527 // optimizes the common case of LIKE '%foo'
528 if (compareMode.getName().equals(CompareMode.OFF) && patternLength > 1) {
529 if (patternTypes[0] == ANY) {
530 int maxMatch = 1;
531 while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
532 maxMatch++;
533 }
534 if (maxMatch == patternLength) {
535 shortcutToEndsWith = true;
536 return;
537 }
538 }
539 }
540 // optimizes the common case of LIKE '%foo%'
541 if (compareMode.getName().equals(CompareMode.OFF) && patternLength > 2) {
542 if (patternTypes[0] == ANY) {
543 int maxMatch = 1;
544 while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
545 maxMatch++;
546 }
547 if (maxMatch == patternLength - 1 && patternTypes[patternLength - 1] == ANY) {
548 shortcutToContains = true;
549 }
550 }
551 }
552 }
553
554 private boolean isFullMatch() {
555 if (patternTypes == null) {
556 return false;
557 }
558 for (int type : patternTypes) {
559 if (type != MATCH) {
560 return false;
561 }
562 }
563 return true;
564 }
565
566 @Override
567 public Expression getNotIfPossible(SessionLocal session) {
568 if (whenOperand) {
569 return null;
570 }
571 return new CompareLike(compareMode, defaultEscape, left, !not, false, right, escape, likeType);
572 }
573
574 @Override
575 public void mapColumns(ColumnResolver resolver, int level, int state) {
576 left.mapColumns(resolver, level, state);
577 right.mapColumns(resolver, level, state);
578 if (escape != null) {
579 escape.mapColumns(resolver, level, state);
580 }
581 }
582
583 @Override
584 public void setEvaluatable(TableFilter tableFilter, boolean b) {
585 left.setEvaluatable(tableFilter, b);
586 right.setEvaluatable(tableFilter, b);
587 if (escape != null) {
588 escape.setEvaluatable(tableFilter, b);
589 }
590 }
591
592 @Override
593 public void updateAggregate(SessionLocal session, int stage) {
594 left.updateAggregate(session, stage);
595 right.updateAggregate(session, stage);
596 if (escape != null) {
597 escape.updateAggregate(session, stage);
598 }
599 }
600
601 @Override
602 public boolean isEverything(ExpressionVisitor visitor) {
603 return left.isEverything(visitor) && right.isEverything(visitor)
604 && (escape == null || escape.isEverything(visitor));
605 }
606
607 @Override
608 public int getCost() {
609 return left.getCost() + right.getCost() + 3;
610 }
611
612 @Override
613 public int getSubexpressionCount() {
614 return escape == null ? 2 : 3;
615 }
616
617 @Override
618 public Expression getSubexpression(int index) {
619 switch (index) {
620 case 0:
621 return left;
622 case 1:
623 return right;
624 case 2:
625 if (escape != null) {
626 return escape;
627 }
628 //$FALL-THROUGH$
629 default:
630 throw new IndexOutOfBoundsException();
631 }
632 }
633
634 }