1 29 30 package com.caucho.db.sql; 31 32 import com.caucho.log.Log; 33 34 import java.sql.SQLException ; 35 import java.util.ArrayList ; 36 import java.util.logging.Level ; 37 import java.util.logging.Logger ; 38 import java.util.regex.Pattern ; 39 40 class LikeExpr extends Expr { 41 private static final Logger log = Log.open(LikeExpr.class); 42 43 private Expr _expr; 44 private String _pattern; 45 private Pattern _regexp; 46 private boolean _isNot; 47 48 LikeExpr(Expr expr, String pattern, boolean isNot) 49 { 50 _expr = expr; 51 _pattern = pattern; 52 _isNot = isNot; 53 54 StringBuilder sb = new StringBuilder (); 55 for (int i = 0; i < pattern.length(); i++) { 56 char ch = pattern.charAt(i); 57 58 switch (ch) { 59 case '%': 60 sb.append(".*"); 61 break; 62 case '_': 63 sb.append("."); 64 break; 65 case '.': case '\\': case '*': case '+': case '(': case ')': 66 case '[': case ']': case '?': case '^': case '$': case '|': 67 sb.append("\\"); 68 sb.append(ch); 69 break; 70 default: 71 sb.append(ch); 72 } 73 } 74 75 try { 76 _regexp = Pattern.compile(sb.toString()); 77 } catch (Exception e) { 78 log.log(Level.WARNING, e.toString(), e); 79 } 80 } 81 82 protected Expr bind(Query query) 83 throws SQLException 84 { 85 _expr = _expr.bind(query); 86 87 return this; 88 } 89 90 93 public Class getType() 94 { 95 return boolean.class; 96 } 97 98 101 public long subCost(ArrayList <FromItem> fromList) 102 { 103 return (_expr.subCost(fromList)); 104 } 105 106 109 public int evalBoolean(QueryContext context) 110 throws SQLException 111 { 112 if (_expr.isNull(context)) 113 return UNKNOWN; 114 115 String value = _expr.evalString(context); 116 117 if (_regexp.matcher(value).matches()) 118 return _isNot ? FALSE : TRUE; 119 else 120 return _isNot ? TRUE : FALSE; 121 } 122 123 public String evalString(QueryContext context) 124 throws SQLException 125 { 126 throw new SQLException ("can't convert string to boolean"); 127 } 128 129 134 public void evalGroup(QueryContext context) 135 throws SQLException 136 { 137 _expr.evalGroup(context); 138 } 139 140 public String toString() 141 { 142 return "(" + _expr + " LIKE " + _pattern + ")"; 143 } 144 } 145 | Popular Tags |