Debian Codegraph @

src/main/org/h2/expression/function/RegexpFunction.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.function;
7
8 import java.util.regex.Matcher;
9 import java.util.regex.Pattern;
10 import java.util.regex.PatternSyntaxException;
11
12 import org.h2.api.ErrorCode;
13 import org.h2.engine.Mode;
14 import org.h2.engine.Mode.ModeEnum;
15 import org.h2.engine.SessionLocal;
16 import org.h2.expression.Expression;
17 import org.h2.expression.TypedValueExpression;
18 import org.h2.message.DbException;
19 import org.h2.value.TypeInfo;
20 import org.h2.value.Value;
21 import org.h2.value.ValueBoolean;
22 import org.h2.value.ValueNull;
23 import org.h2.value.ValueVarchar;
24
25 /**
26 * A regular expression function.
27 */
28 public final class RegexpFunction extends FunctionN {
29
30 /**
31 * REGEXP_LIKE() (non-standard).
32 */
33 public static final int REGEXP_LIKE = 0;
34
35 /**
36 * REGEXP_REPLACE() (non-standard).
37 */
38 public static final int REGEXP_REPLACE = REGEXP_LIKE + 1;
39
40 /**
41 * REGEXP_SUBSTR() (non-standard).
42 */
43 public static final int REGEXP_SUBSTR = REGEXP_REPLACE + 1;
44
45 private static final String[] NAMES = { //
46 "REGEXP_LIKE", "REGEXP_REPLACE", "REGEXP_SUBSTR" //
47 };
48
49 private final int function;
50
51 public RegexpFunction(int function) {
52 super(new Expression[function == REGEXP_LIKE ? 3 : 6]);
53 this.function = function;
54 }
55
56 @Override
57 public Value getValue(SessionLocal session) {
58 Value v1 = args[0].getValue(session);
59 Value v2 = args[1].getValue(session);
60 int length = args.length;
61 switch (function) {
62 case REGEXP_LIKE: {
63 Value v3 = length >= 3 ? args[2].getValue(session) : null;
64 if (v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE || v3 == ValueNull.INSTANCE) {
65 return ValueNull.INSTANCE;
66 }
67 String regexp = v2.getString();
68 String regexpMode = v3 != null ? v3.getString() : null;
69 int flags = makeRegexpFlags(regexpMode, false);
70 try {
71 v1 = ValueBoolean.get(Pattern.compile(regexp, flags).matcher(v1.getString()).find());
72 } catch (PatternSyntaxException e) {
73 throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
74 }
75 break;
76 }
77 case REGEXP_REPLACE: {
78 String input = v1.getString();
79 if (session.getMode().getEnum() == ModeEnum.Oracle) {
80 String replacement = args[2].getValue(session).getString();
81 int position = length >= 4 ? args[3].getValue(session).getInt() : 1;
82 int occurrence = length >= 5 ? args[4].getValue(session).getInt() : 0;
83 String regexpMode = length >= 6 ? args[5].getValue(session).getString() : null;
84 if (input == null) {
85 v1 = ValueNull.INSTANCE;
86 } else {
87 String regexp = v2.getString();
88 v1 = regexpReplace(session, input, regexp != null ? regexp : "",
89 replacement != null ? replacement : "", position, occurrence, regexpMode);
90 }
91 } else {
92 if (length > 4) {
93 throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, getName(), "3..4");
94 }
95 Value v3 = args[2].getValue(session);
96 Value v4 = length == 4 ? args[3].getValue(session) : null;
97 if (v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE || v3 == ValueNull.INSTANCE
98 || v4 == ValueNull.INSTANCE) {
99 v1 = ValueNull.INSTANCE;
100 } else {
101 v1 = regexpReplace(session, input, v2.getString(), v3.getString(), 1, 0,
102 v4 != null ? v4.getString() : null);
103 }
104 }
105 break;
106 }
107 case REGEXP_SUBSTR: {
108 Value v3 = length >= 3 ? args[2].getValue(session) : null;
109 Value v4 = length >= 4 ? args[3].getValue(session) : null;
110 Value v5 = length >= 5 ? args[4].getValue(session) : null;
111 Value v6 = length >= 6 ? args[5].getValue(session) : null;
112 v1 = regexpSubstr(v1, v2, v3, v4, v5, v6, session);
113 break;
114 }
115 default:
116 throw DbException.getInternalError("function=" + function);
117 }
118 return v1;
119 }
120
121 private static Value regexpReplace(SessionLocal session, String input, String regexp, String replacement,
122 int position, int occurrence, String regexpMode) {
123 Mode mode = session.getMode();
124 if (mode.regexpReplaceBackslashReferences) {
125 if ((replacement.indexOf('\\') >= 0) || (replacement.indexOf('$') >= 0)) {
126 StringBuilder sb = new StringBuilder();
127 for (int i = 0; i < replacement.length(); i++) {
128 char c = replacement.charAt(i);
129 if (c == '$') {
130 sb.append('\\');
131 } else if (c == '\\' && ++i < replacement.length()) {
132 c = replacement.charAt(i);
133 sb.append(c >= '0' && c <= '9' ? '$' : '\\');
134 }
135 sb.append(c);
136 }
137 replacement = sb.toString();
138 }
139 }
140 boolean isInPostgreSqlMode = mode.getEnum() == ModeEnum.PostgreSQL;
141 int flags = makeRegexpFlags(regexpMode, isInPostgreSqlMode);
142 if (isInPostgreSqlMode && (regexpMode == null || regexpMode.isEmpty() || !regexpMode.contains("g"))) {
143 occurrence = 1;
144 }
145 try {
146 Matcher matcher = Pattern.compile(regexp, flags).matcher(input).region(position - 1, input.length());
147 if (occurrence == 0) {
148 return ValueVarchar.get(matcher.replaceAll(replacement), session);
149 } else {
150 StringBuffer sb = new StringBuffer();
151 int index = 1;
152 while (matcher.find()) {
153 if (index == occurrence) {
154 matcher.appendReplacement(sb, replacement);
155 break;
156 }
157 index++;
158 }
159 matcher.appendTail(sb);
160 return ValueVarchar.get(sb.toString(), session);
161 }
162 } catch (PatternSyntaxException e) {
163 throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
164 } catch (StringIndexOutOfBoundsException | IllegalArgumentException e) {
165 throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, replacement);
166 }
167 }
168
169 private static Value regexpSubstr(Value inputString, Value regexpArg, Value positionArg, Value occurrenceArg,
170 Value regexpModeArg, Value subexpressionArg, SessionLocal session) {
171 if (inputString == ValueNull.INSTANCE || regexpArg == ValueNull.INSTANCE || positionArg == ValueNull.INSTANCE
172 || occurrenceArg == ValueNull.INSTANCE || subexpressionArg == ValueNull.INSTANCE) {
173 return ValueNull.INSTANCE;
174 }
175 String regexp = regexpArg.getString();
176
177 int position = positionArg != null ? positionArg.getInt() - 1 : 0;
178 int requestedOccurrence = occurrenceArg != null ? occurrenceArg.getInt() : 1;
179 String regexpMode = regexpModeArg != null ? regexpModeArg.getString() : null;
180 int subexpression = subexpressionArg != null ? subexpressionArg.getInt() : 0;
181 int flags = makeRegexpFlags(regexpMode, false);
182 try {
183 Matcher m = Pattern.compile(regexp, flags).matcher(inputString.getString());
184
185 boolean found = m.find(position);
186 for (int occurrence = 1; occurrence < requestedOccurrence && found; occurrence++) {
187 found = m.find();
188 }
189
190 if (!found) {
191 return ValueNull.INSTANCE;
192 } else {
193 return ValueVarchar.get(m.group(subexpression), session);
194 }
195 } catch (PatternSyntaxException e) {
196 throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
197 } catch (IndexOutOfBoundsException e) {
198 return ValueNull.INSTANCE;
199 }
200 }
201
202 private static int makeRegexpFlags(String stringFlags, boolean ignoreGlobalFlag) {
203 int flags = Pattern.UNICODE_CASE;
204 if (stringFlags != null) {
205 for (int i = 0; i < stringFlags.length(); ++i) {
206 switch (stringFlags.charAt(i)) {
207 case 'i':
208 flags |= Pattern.CASE_INSENSITIVE;
209 break;
210 case 'c':
211 flags &= ~Pattern.CASE_INSENSITIVE;
212 break;
213 case 'n':
214 flags |= Pattern.DOTALL;
215 break;
216 case 'm':
217 flags |= Pattern.MULTILINE;
218 break;
219 case 'g':
220 if (ignoreGlobalFlag) {
221 break;
222 }
223 //$FALL-THROUGH$
224 default:
225 throw DbException.get(ErrorCode.INVALID_VALUE_2, stringFlags);
226 }
227 }
228 }
229 return flags;
230 }
231
232 @Override
233 public Expression optimize(SessionLocal session) {
234 boolean allConst = optimizeArguments(session, true);
235 int min, max;
236 switch (function) {
237 case REGEXP_LIKE:
238 min = 2;
239 max = 3;
240 type = TypeInfo.TYPE_BOOLEAN;
241 break;
242 case REGEXP_REPLACE:
243 min = 3;
244 max = 6;
245 type = TypeInfo.TYPE_VARCHAR;
246 break;
247 case REGEXP_SUBSTR:
248 min = 2;
249 max = 6;
250 type = TypeInfo.TYPE_VARCHAR;
251 break;
252 default:
253 throw DbException.getInternalError("function=" + function);
254 }
255 int len = args.length;
256 if (len < min || len > max) {
257 throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, getName(), min + ".." + max);
258 }
259 if (allConst) {
260 return TypedValueExpression.getTypedIfNull(getValue(session), type);
261 }
262 return this;
263 }
264
265 @Override
266 public String getName() {
267 return NAMES[function];
268 }
269
270 }