Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * like_match.c
4 : : * LIKE pattern matching internal code.
5 : : *
6 : : * This file is included by like.c four times, to provide matching code for
7 : : * (1) single-byte encodings, (2) UTF8, (3) other multi-byte encodings,
8 : : * and (4) case insensitive matches in single-byte encodings.
9 : : * (UTF8 is a special case because we can use a much more efficient version
10 : : * of NextChar than can be used for general multi-byte encodings.)
11 : : *
12 : : * Before the inclusion, we need to define the following macros:
13 : : *
14 : : * NextChar
15 : : * MatchText - to name of function wanted
16 : : * do_like_escape - name of function if wanted - needs CHAREQ and CopyAdvChar
17 : : * MATCH_LOWER - define for case (4) to specify case folding for 1-byte chars
18 : : *
19 : : * Copyright (c) 1996-2026, PostgreSQL Global Development Group
20 : : *
21 : : * IDENTIFICATION
22 : : * src/backend/utils/adt/like_match.c
23 : : *
24 : : *-------------------------------------------------------------------------
25 : : */
26 : :
27 : : /*
28 : : * Originally written by Rich $alz, mirror!rs, Wed Nov 26 19:03:17 EST 1986.
29 : : * Rich $alz is now <rsalz@bbn.com>.
30 : : * Special thanks to Lars Mathiesen <thorinn@diku.dk> for the
31 : : * LIKE_ABORT code.
32 : : *
33 : : * This code was shamelessly stolen from the "pql" code by myself and
34 : : * slightly modified :)
35 : : *
36 : : * All references to the word "star" were replaced by "percent"
37 : : * All references to the word "wild" were replaced by "like"
38 : : *
39 : : * All the nice shell RE matching stuff was replaced by just "_" and "%"
40 : : *
41 : : * As I don't have a copy of the SQL standard handy I wasn't sure whether
42 : : * to leave in the '\' escape character handling.
43 : : *
44 : : * Keith Parks. <keith@mtcc.demon.co.uk>
45 : : *
46 : : * SQL lets you specify the escape character by saying
47 : : * LIKE <pattern> ESCAPE <escape character>. We are a small operation
48 : : * so we force you to use '\'. - ay 7/95
49 : : *
50 : : * Now we have the like_escape() function that converts patterns with
51 : : * any specified escape character (or none at all) to the internal
52 : : * default escape character, which is still '\'. - tgl 9/2000
53 : : *
54 : : * The code is rewritten to avoid requiring null-terminated strings,
55 : : * which in turn allows us to leave out some memcpy() operations.
56 : : * This code should be faster and take less memory, but no promises...
57 : : * - thomas 2000-08-06
58 : : */
59 : :
60 : :
61 : : /*--------------------
62 : : * Match text and pattern, return LIKE_TRUE, LIKE_FALSE, or LIKE_ABORT.
63 : : *
64 : : * LIKE_TRUE: they match
65 : : * LIKE_FALSE: they don't match
66 : : * LIKE_ABORT: not only don't they match, but the text is too short.
67 : : *
68 : : * If LIKE_ABORT is returned, then no suffix of the text can match the
69 : : * pattern either, so an upper-level % scan can stop scanning now.
70 : : *--------------------
71 : : */
72 : :
73 : : /*
74 : : * MATCH_LOWER is defined for ILIKE in the C locale as an optimization. Other
75 : : * locales must casefold the inputs before matching.
76 : : */
77 : : #ifdef MATCH_LOWER
78 : : /* cast to char to match data types in caller */
79 : : #define GETCHAR(t) ((char) pg_ascii_tolower(t))
80 : : #else
81 : : #define GETCHAR(t) (t)
82 : : #endif
83 : :
84 : : static int
783 peter@eisentraut.org 85 :CBC 826957 : MatchText(const char *t, int tlen, const char *p, int plen, pg_locale_t locale)
86 : : {
122 tgl@sss.pgh.pa.us 87 [ + + + + ]: 826957 : bool nondeterministic = (locale && !locale->deterministic);
88 : :
89 : : /* Fast path for match-everything pattern */
6374 90 [ + + + + ]: 826957 : if (plen == 1 && *p == '%')
9163 ishii@postgresql.org 91 : 146 : return LIKE_TRUE;
92 : :
93 : : /* Since this function recurses, it could be driven to stack overflow */
4052 tgl@sss.pgh.pa.us 94 : 826811 : check_stack_depth();
95 : :
96 : : /*
97 : : * In this loop, we advance by char when matching wildcards (and thus on
98 : : * recursive entry to this function we are properly char-synced). On other
99 : : * occasions it is safe to advance by byte, as the text and pattern will
100 : : * be in lockstep. This allows us to perform all comparisons between the
101 : : * text and pattern on a byte by byte basis, even for multi-byte
102 : : * encodings. (But that doesn't work in a nondeterministic locale, so the
103 : : * nondeterministic case below has to advance the text by chars.)
104 : : */
6374 105 [ + + + + ]: 1212727 : while (tlen > 0 && plen > 0)
106 : : {
107 : : /*
108 : : * At the top of this loop, we are not positioned immediately after an
109 : : * escape, so we may take wildcards at face value.
110 : : */
122 111 [ + + ]: 1204996 : if (*p == '%')
112 : : {
113 : : char firstpat;
114 : :
115 : : /*
116 : : * % processing is essentially a search for a text position at
117 : : * which the remainder of the text matches the remainder of the
118 : : * pattern, using a recursive call to check each potential match.
119 : : *
120 : : * If there are wildcards immediately following the %, we can skip
121 : : * over them first, using the idea that any sequence of N _'s and
122 : : * one or more %'s is equivalent to N _'s and one % (ie, it will
123 : : * match any sequence of at least N text characters). In this way
124 : : * we will always run the recursive search loop using a pattern
125 : : * fragment that begins with a literal character-to-match, thereby
126 : : * not recursing more than we have to.
127 : : */
6005 128 : 93737 : NextByte(p, plen);
129 : :
130 [ + + ]: 94091 : while (plen > 0)
131 : : {
132 [ + + ]: 73164 : if (*p == '%')
133 : 15 : NextByte(p, plen);
134 [ + + ]: 73149 : else if (*p == '_')
135 : : {
136 : : /* If not enough text left to match the pattern, ABORT */
137 [ + + ]: 344 : if (tlen <= 0)
138 : 5 : return LIKE_ABORT;
139 [ + + - + ]: 339 : NextChar(t, tlen);
140 : 339 : NextByte(p, plen);
141 : : }
142 : : else
143 : 72805 : break; /* Reached a non-wildcard pattern char */
144 : : }
145 : :
146 : : /*
147 : : * If we're at end of pattern, match: we have a trailing % which
148 : : * matches any remaining text string.
149 : : */
9163 ishii@postgresql.org 150 [ + + ]: 93732 : if (plen <= 0)
151 : 20927 : return LIKE_TRUE;
152 : :
153 : : /*
154 : : * Otherwise, scan for a text position at which we can match the
155 : : * rest of the pattern. The first remaining pattern char is known
156 : : * to be a regular or escaped literal character, so we can compare
157 : : * the first pattern byte to each text byte to avoid recursing
158 : : * more than we have to. This fact also guarantees that we don't
159 : : * have to consider a match to the zero-length substring at the
160 : : * end of the text. But with a nondeterministic locale, we can't
161 : : * rely on the first byte of a match being equal, so we have to
162 : : * recurse in any case.
163 : : */
6005 tgl@sss.pgh.pa.us 164 [ + + ]: 72805 : if (*p == '\\')
165 : : {
166 [ - + ]: 2 : if (plen < 2)
6005 tgl@sss.pgh.pa.us 167 [ # # ]:UBC 0 : ereport(ERROR,
168 : : (errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE),
169 : : errmsg("LIKE pattern must not end with escape character")));
330 jdavis@postgresql.or 170 :CBC 2 : firstpat = GETCHAR(p[1]);
171 : : }
172 : : else
173 : 72803 : firstpat = GETCHAR(*p);
174 : :
6005 tgl@sss.pgh.pa.us 175 [ + + ]: 2130223 : while (tlen > 0)
176 : : {
122 177 [ + + + + ]: 2073595 : if (GETCHAR(*t) == firstpat || nondeterministic)
178 : : {
783 peter@eisentraut.org 179 : 57891 : int matched = MatchText(t, tlen, p, plen, locale);
180 : :
7096 andrew@dunslane.net 181 [ + + ]: 57891 : if (matched != LIKE_FALSE)
5966 bruce@momjian.us 182 : 16177 : return matched; /* TRUE or ABORT */
183 : : }
184 : :
6005 tgl@sss.pgh.pa.us 185 [ + + + + ]: 2057456 : NextChar(t, tlen);
186 : : }
187 : :
188 : : /*
189 : : * End of text with no match, so no point in trying later places
190 : : * to start matching this pattern.
191 : : */
9163 ishii@postgresql.org 192 : 56628 : return LIKE_ABORT;
193 : : }
7096 andrew@dunslane.net 194 [ + + ]: 1111259 : else if (*p == '_')
195 : : {
196 : : /* _ matches any single character, and we know there is one */
197 [ + + + + ]: 9910 : NextChar(t, tlen);
198 : 9890 : NextByte(p, plen);
199 : 9890 : continue;
200 : : }
122 tgl@sss.pgh.pa.us 201 [ + + ]: 1101369 : else if (nondeterministic)
202 : : {
203 : : /*
204 : : * For nondeterministic locales, we find the next substring of the
205 : : * pattern that does not contain wildcards and try to find a
206 : : * matching substring in the text. Crucially, we cannot do this
207 : : * character by character, as in the normal case, but must do it
208 : : * substring by substring, partitioned by the wildcard characters.
209 : : * (This is per SQL standard.)
210 : : */
211 : : const char *p1;
212 : : size_t p1len;
213 : : const char *t1;
214 : : size_t t1len;
215 : : bool found_escape;
216 : : const char *subpat;
217 : : size_t subpatlen;
708 peter@eisentraut.org 218 : 277 : char *buf = NULL;
219 : :
220 : : /*
221 : : * Determine length of substring of pattern without wildcards. p
222 : : * is the start of the subpattern, p1 will advance to one past its
223 : : * last byte. Also track if we found an escape character.
224 : : */
225 : 277 : p1 = p;
226 : 277 : p1len = plen;
227 : 277 : found_escape = false;
228 [ + + ]: 923 : while (p1len > 0)
229 : : {
230 [ + + ]: 776 : if (*p1 == '\\')
231 : : {
232 : 64 : found_escape = true;
233 : 64 : NextByte(p1, p1len);
234 [ + + ]: 64 : if (p1len == 0)
235 [ + - ]: 4 : ereport(ERROR,
236 : : (errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE),
237 : : errmsg("LIKE pattern must not end with escape character")));
238 : : }
239 [ + + + + ]: 712 : else if (*p1 == '_' || *p1 == '%')
240 : : break;
241 : : /* Advance over regular or escaped character */
242 : 646 : NextByte(p1, p1len);
243 : : }
244 : :
245 : : /*
246 : : * If we found an escape character, then make a de-escaped copy of
247 : : * the subpattern that we can use to match literally. Otherwise
248 : : * we can use the subpattern in-place. (buf holds the de-escaped
249 : : * copy; be sure to pfree it before returning.)
250 : : */
251 [ + + ]: 273 : if (found_escape)
252 : : {
253 : : char *b;
254 : :
255 : 50 : b = buf = palloc(p1 - p);
256 [ + + ]: 265 : for (const char *c = p; c < p1; c++)
257 : : {
258 [ + + ]: 215 : if (*c == '\\')
122 tgl@sss.pgh.pa.us 259 : 60 : c++; /* we already checked this isn't the end */
260 : 215 : *(b++) = *c;
261 : : }
262 : :
708 peter@eisentraut.org 263 : 50 : subpat = buf;
264 : 50 : subpatlen = b - buf;
265 : : }
266 : : else
267 : : {
268 : 223 : subpat = p;
269 : 223 : subpatlen = p1 - p;
270 : : }
271 : :
272 : : /*
273 : : * Shortcut: If this is the end of the pattern, then the rest of
274 : : * the text has to match the rest of the pattern.
275 : : */
276 [ + + ]: 273 : if (p1len == 0)
277 : : {
278 : : int cmp;
279 : :
280 : 147 : cmp = pg_strncoll(subpat, subpatlen, t, tlen, locale);
281 : :
282 [ + + ]: 147 : if (buf)
283 : 25 : pfree(buf);
284 [ + + ]: 147 : if (cmp == 0)
285 : 97 : return LIKE_TRUE;
286 : : else
287 : 50 : return LIKE_FALSE;
288 : : }
289 : :
290 : : /*
291 : : * Consider each successively-longer substring of the remaining
292 : : * text and try to match it against the subpattern. t is the
293 : : * start of the substring, t1 is one past its last byte. We start
294 : : * with a zero-length substring.
295 : : */
296 : 126 : t1 = t;
297 : 126 : t1len = tlen;
298 : : for (;;)
299 : 336 : {
300 : : int cmp;
301 : :
302 : : /* This could be slow, so allow interrupts */
303 [ - + ]: 462 : CHECK_FOR_INTERRUPTS();
304 : :
305 : 462 : cmp = pg_strncoll(subpat, subpatlen, t, (t1 - t), locale);
306 : :
307 : : /*
308 : : * If we found a match, we have to test if the rest of pattern
309 : : * can match against the rest of the text. If not, we have to
310 : : * continue and try the next longer substring. (This is
311 : : * similar to the recursion for the '%' wildcard above.)
312 : : *
313 : : * Note that we can't just wind forward p and t and continue
314 : : * with the main loop. This would fail for example with
315 : : *
316 : : * U&'\0061\0308bc' LIKE U&'\00E4_c' COLLATE ignore_accents
317 : : *
318 : : * You'd find that t=\0061 matches p=\00E4, but then the rest
319 : : * won't match; but t=\0061\0308 also matches p=\00E4, and
320 : : * then the rest will match.
321 : : */
322 [ + + ]: 462 : if (cmp == 0)
323 : : {
324 : 100 : int matched = MatchText(t1, t1len, p1, p1len, locale);
325 : :
326 [ + + ]: 100 : if (matched == LIKE_TRUE)
327 : : {
328 [ + + ]: 90 : if (buf)
329 : 20 : pfree(buf);
330 : 90 : return matched;
331 : : }
332 : : }
333 : :
334 : : /*
335 : : * Didn't match. If we used up the whole text, then the match
336 : : * fails. Otherwise, try again with a longer substring.
337 : : */
338 [ + + ]: 372 : if (t1len == 0)
339 : : {
701 340 [ + + ]: 36 : if (buf)
341 : 5 : pfree(buf);
708 342 : 36 : return LIKE_FALSE;
343 : : }
344 : : else
345 [ + + + + ]: 366 : NextChar(t1, t1len);
346 : : } /* end loop over substrings starting at t */
347 : : }
348 : : /* the rest of this loop considers only deterministic cases */
122 tgl@sss.pgh.pa.us 349 [ + + ]: 1101092 : else if (*p == '\\')
350 : : {
351 : : /* Next pattern byte must match literally, whatever it is */
352 : 8882 : NextByte(p, plen);
353 : : /* ... and there had better be one, per SQL standard */
354 [ - + ]: 8882 : if (plen <= 0)
122 tgl@sss.pgh.pa.us 355 [ # # ]:UBC 0 : ereport(ERROR,
356 : : (errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE),
357 : : errmsg("LIKE pattern must not end with escape character")));
122 tgl@sss.pgh.pa.us 358 [ + + ]:CBC 8882 : if (GETCHAR(*p) != GETCHAR(*t))
359 : 2399 : return LIKE_FALSE;
360 : : }
330 jdavis@postgresql.or 361 [ + + ]: 1092210 : else if (GETCHAR(*p) != GETCHAR(*t))
362 : : {
363 : : /* non-wildcard pattern char fails to match text char */
9163 ishii@postgresql.org 364 : 722667 : return LIKE_FALSE;
365 : : }
366 : :
367 : : /*
368 : : * Pattern and text match, so advance.
369 : : *
370 : : * It is safe to use NextByte instead of NextChar here, even for
371 : : * multi-byte character sets, because we are not following immediately
372 : : * after a wildcard character. If we are in the middle of a multibyte
373 : : * character, we must already have matched at least one byte of the
374 : : * character from both text and pattern; so we cannot get out-of-sync
375 : : * on character boundaries. And we know that no backend-legal
376 : : * encoding allows ASCII characters such as '%' to appear as non-first
377 : : * bytes of characters, so we won't mistakenly detect a new wildcard.
378 : : */
7096 andrew@dunslane.net 379 : 376026 : NextByte(t, tlen);
380 : 376026 : NextByte(p, plen);
381 : : }
382 : :
9163 ishii@postgresql.org 383 [ + + ]: 7731 : if (tlen > 0)
384 : 255 : return LIKE_FALSE; /* end of pattern, but not of text */
385 : :
386 : : /*
387 : : * End of text, but perhaps not of pattern. Match iff the remaining
388 : : * pattern can match a zero-length string, ie, it's zero or more %'s.
389 : : */
6005 tgl@sss.pgh.pa.us 390 [ + + + + ]: 7893 : while (plen > 0 && *p == '%')
7096 andrew@dunslane.net 391 : 417 : NextByte(p, plen);
9163 ishii@postgresql.org 392 [ + + ]: 7476 : if (plen <= 0)
393 : 3387 : return LIKE_TRUE;
394 : :
395 : : /*
396 : : * End of text with no match, so no point in trying later places to start
397 : : * matching this pattern.
398 : : */
399 : 4089 : return LIKE_ABORT;
400 : : } /* MatchText() */
401 : :
402 : : /*
403 : : * like_escape() --- given a pattern and an ESCAPE string,
404 : : * convert the pattern to use Postgres' standard backslash escape convention.
405 : : */
406 : : #ifdef do_like_escape
407 : :
408 : : static text *
409 : 196 : do_like_escape(text *pat, text *esc)
410 : : {
411 : : text *result;
412 : : char *p,
413 : : *e,
414 : : *r;
415 : : int plen,
416 : : elen;
417 : : bool afterescape;
418 : :
6985 tgl@sss.pgh.pa.us 419 : 196 : p = VARDATA_ANY(pat);
420 : 196 : plen = VARSIZE_ANY_EXHDR(pat);
421 : 196 : e = VARDATA_ANY(esc);
422 : 196 : elen = VARSIZE_ANY_EXHDR(esc);
423 : :
424 : : /*
425 : : * Worst-case pattern growth is 2x --- unlikely, but it's hardly worth
426 : : * trying to calculate the size more accurately than that.
427 : : */
9163 ishii@postgresql.org 428 : 196 : result = (text *) palloc(plen * 2 + VARHDRSZ);
429 : 196 : r = VARDATA(result);
430 : :
431 [ + + ]: 196 : if (elen == 0)
432 : : {
433 : : /*
434 : : * No escape character is wanted. Double any backslashes in the
435 : : * pattern to make them act like ordinary characters.
436 : : */
437 [ + + ]: 64 : while (plen > 0)
438 : : {
439 [ - + ]: 48 : if (*p == '\\')
9163 ishii@postgresql.org 440 :UBC 0 : *r++ = '\\';
9163 ishii@postgresql.org 441 [ + + ]:CBC 96 : CopyAdvChar(r, p, plen);
442 : : }
443 : : }
444 : : else
445 : : {
446 : : /*
447 : : * The specified escape must be only a single character.
448 : : */
449 : 180 : NextChar(e, elen);
450 [ - + ]: 180 : if (elen != 0)
8502 tgl@sss.pgh.pa.us 451 [ # # ]:UBC 0 : ereport(ERROR,
452 : : (errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE),
453 : : errmsg("invalid escape string"),
454 : : errhint("Escape string must be empty or one character.")));
455 : :
6985 tgl@sss.pgh.pa.us 456 :CBC 180 : e = VARDATA_ANY(esc);
302 tmunro@postgresql.or 457 : 180 : elen = VARSIZE_ANY_EXHDR(esc);
458 : :
459 : : /*
460 : : * If specified escape is '\', just copy the pattern as-is.
461 : : */
9163 ishii@postgresql.org 462 [ - + ]: 180 : if (*e == '\\')
463 : : {
6985 tgl@sss.pgh.pa.us 464 :UBC 0 : memcpy(result, pat, VARSIZE_ANY(pat));
9163 ishii@postgresql.org 465 : 0 : return result;
466 : : }
467 : :
468 : : /*
469 : : * Otherwise, convert occurrences of the specified escape character to
470 : : * '\', and double occurrences of '\' --- unless they immediately
471 : : * follow an escape character!
472 : : */
9163 ishii@postgresql.org 473 :CBC 180 : afterescape = false;
474 [ + + ]: 1130 : while (plen > 0)
475 : : {
302 tmunro@postgresql.or 476 [ + + + + ]: 950 : if (CHAREQ(p, plen, e, elen) && !afterescape)
477 : : {
9163 ishii@postgresql.org 478 : 175 : *r++ = '\\';
479 : 175 : NextChar(p, plen);
480 : 175 : afterescape = true;
481 : : }
482 [ + + ]: 775 : else if (*p == '\\')
483 : : {
484 : 15 : *r++ = '\\';
485 [ + + ]: 15 : if (!afterescape)
486 : 10 : *r++ = '\\';
487 : 15 : NextChar(p, plen);
488 : 15 : afterescape = false;
489 : : }
490 : : else
491 : : {
492 [ + + ]: 1500 : CopyAdvChar(r, p, plen);
493 : 760 : afterescape = false;
494 : : }
495 : : }
496 : : }
497 : :
7191 tgl@sss.pgh.pa.us 498 : 196 : SET_VARSIZE(result, r - ((char *) result));
499 : :
9163 ishii@postgresql.org 500 : 196 : return result;
501 : : }
502 : : #endif /* do_like_escape */
503 : :
504 : : #ifdef CHAREQ
505 : : #undef CHAREQ
506 : : #endif
507 : :
508 : : #undef NextChar
509 : : #undef CopyAdvChar
510 : : #undef MatchText
511 : :
512 : : #ifdef do_like_escape
513 : : #undef do_like_escape
514 : : #endif
515 : :
516 : : #undef GETCHAR
517 : :
518 : : #ifdef MATCH_LOWER
519 : : #undef MATCH_LOWER
520 : :
521 : : #endif
|