Skip to content

Commit f79889e

Browse files
JelteFhackorum
authored andcommitted
Treat exact-match LIKE pattern as non-lossy in certain cases
1 parent 31878cc commit f79889e

5 files changed

Lines changed: 180 additions & 21 deletions

File tree

‎src/backend/utils/adt/like_support.c‎

Lines changed: 95 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,10 @@ typedef enum
6464

6565
typedef enum
6666
{
67-
Pattern_Prefix_None, Pattern_Prefix_Partial, Pattern_Prefix_Exact,
67+
Pattern_Prefix_None, /* cannot produce an indexqual */
68+
Pattern_Prefix_Partial, /* maps to an index range restriction */
69+
Pattern_Prefix_Exact, /* maps to a simple equality test */
70+
Pattern_Prefix_Exact_Lossy, /* maps to an equality test, but recheck */
6871
} Pattern_Prefix_Status;
6972

7073
/* non-collatable comparisons, eg for bytea, are always deterministic */
@@ -77,7 +80,8 @@ static List *match_pattern_prefix(Node *leftop,
7780
Pattern_Type ptype,
7881
Oid expr_coll,
7982
Oid opfamily,
80-
Oid indexcollation);
83+
Oid indexcollation,
84+
bool *lossy);
8185
static double patternsel_common(PlannerInfo *root,
8286
Oid oprid,
8387
Oid opfuncid,
@@ -207,7 +211,8 @@ like_regex_support(Node *rawreq, Pattern_Type ptype)
207211
ptype,
208212
clause->inputcollid,
209213
req->opfamily,
210-
req->indexcollation);
214+
req->indexcollation,
215+
&req->lossy);
211216
}
212217
else if (is_funcclause(req->node)) /* be paranoid */
213218
{
@@ -220,7 +225,8 @@ like_regex_support(Node *rawreq, Pattern_Type ptype)
220225
ptype,
221226
clause->inputcollid,
222227
req->opfamily,
223-
req->indexcollation);
228+
req->indexcollation,
229+
&req->lossy);
224230
}
225231
}
226232

@@ -230,14 +236,19 @@ like_regex_support(Node *rawreq, Pattern_Type ptype)
230236
/*
231237
* match_pattern_prefix
232238
* Try to generate an indexqual for a LIKE or regex operator.
239+
*
240+
* We return a list of indexqual expressions on success, or NIL on failure.
241+
* On success, *lossy is changed to false (from its initial state of true)
242+
* if the indexqual expression(s) can fully replace the operator.
233243
*/
234244
static List *
235245
match_pattern_prefix(Node *leftop,
236246
Node *rightop,
237247
Pattern_Type ptype,
238248
Oid expr_coll,
239249
Oid opfamily,
240-
Oid indexcollation)
250+
Oid indexcollation,
251+
bool *lossy)
241252
{
242253
List *result;
243254
Const *patt;
@@ -388,7 +399,8 @@ match_pattern_prefix(Node *leftop,
388399
* apply the LIKE/regex operator as a recheck, and that will filter out
389400
* any non-matching entries.
390401
*/
391-
if (pstatus == Pattern_Prefix_Exact)
402+
if (pstatus == Pattern_Prefix_Exact ||
403+
pstatus == Pattern_Prefix_Exact_Lossy)
392404
{
393405
if (!op_in_opfamily(eqopr, opfamily))
394406
return NIL;
@@ -397,14 +409,51 @@ match_pattern_prefix(Node *leftop,
397409
expr = make_opclause(eqopr, BOOLOID, false,
398410
(Expr *) leftop, (Expr *) prefix,
399411
InvalidOid, indexcollation);
412+
413+
/*
414+
* We can even drop the recheck (mark the indexqual non-lossy) when
415+
* "=" means exactly what the exact-match pattern means. That
416+
* requires all of the following:
417+
*
418+
* - The pattern is Pattern_Prefix_Exact.
419+
*
420+
* - The left-hand type is not bpchar. bpchar's "=" ignores trailing
421+
* blanks while LIKE does not, so "= 'abc'" matches a stored 'abc '
422+
* that "LIKE 'abc'" rejects; the recheck is what removes it.
423+
*
424+
* - The index and expression collations agree on equality. That
425+
* holds when they're the same collation, or (having passed the guard
426+
* above, which rejected a nondeterministic expression collation that
427+
* differs from the index's) when the index collation is
428+
* deterministic: a deterministic collation treats two strings as
429+
* equal iff they're bytewise equal, so it can't disagree with the
430+
* expression's equality. A nondeterministic index collation that
431+
* differs from the expression's makes "=" match a superset of the
432+
* pattern, so the recheck stays.
433+
*
434+
* - The expression actually has a collation whenever the index does.
435+
* A collatable expression with an indeterminate collation (e.g. a
436+
* concatenation of differently-collated columns) carries InvalidOid,
437+
* and the pattern match is supposed to fail at runtime with "could
438+
* not determine which collation to use". Dropping the recheck would
439+
* instead let the "=" indexqual silently resolve the comparison under
440+
* the index's collation. A genuinely non-collatable type (bytea)
441+
* also carries InvalidOid, but then the index collation is InvalidOid
442+
* too, so indexcollation == expr_coll and we still optimize.
443+
*/
444+
if (pstatus == Pattern_Prefix_Exact &&
445+
ldatatype != BPCHAROID &&
446+
(indexcollation == expr_coll ||
447+
(OidIsValid(expr_coll) && !NONDETERMINISTIC(indexcollation))))
448+
*lossy = false;
400449
result = list_make1(expr);
401450
return result;
402451
}
403452

404453
/*
405-
* Anything other than Pattern_Prefix_Exact is not supported if the
406-
* expression collation is nondeterministic. The optimized equality or
407-
* prefix tests use bytewise comparisons, which is not consistent with
454+
* Anything other than Pattern_Prefix_Exact[_Lossy] is not supported if
455+
* the expression collation is nondeterministic. The optimized equality
456+
* or prefix tests use bytewise comparisons, which is not consistent with
408457
* nondeterministic collations.
409458
*/
410459
if (NONDETERMINISTIC(expr_coll))
@@ -635,7 +684,8 @@ patternsel_common(PlannerInfo *root,
635684
prefix->consttype = rdatatype;
636685
}
637686

638-
if (pstatus == Pattern_Prefix_Exact)
687+
if (pstatus == Pattern_Prefix_Exact ||
688+
pstatus == Pattern_Prefix_Exact_Lossy)
639689
{
640690
/*
641691
* Pattern specifies an exact match, so estimate as for '='
@@ -976,7 +1026,7 @@ icnlikejoinsel(PG_FUNCTION_ARGS)
9761026
/*
9771027
* Extract the fixed prefix, if any, for a pattern.
9781028
*
979-
* *prefix is set to a palloc'd prefix string (in the form of a Const node),
1029+
* *prefix_const is set to a palloc'd string (in the form of a Const node),
9801030
* or to NULL if no fixed prefix exists for the pattern.
9811031
* The prefix Const has the same type (TEXT or BYTEA) as the input pattern.
9821032
*
@@ -993,6 +1043,7 @@ like_fixed_prefix(Const *patt_const, Const **prefix_const)
9931043
Oid typeid = patt_const->consttype;
9941044
int pos,
9951045
match_pos;
1046+
bool badpattern = false;
9961047

9971048
/* the right-hand const is type text or bytea */
9981049
Assert(typeid == BYTEAOID || typeid == TEXTOID);
@@ -1026,7 +1077,10 @@ like_fixed_prefix(Const *patt_const, Const **prefix_const)
10261077
{
10271078
pos++;
10281079
if (pos >= pattlen)
1080+
{
1081+
badpattern = true;
10291082
break;
1083+
}
10301084
}
10311085

10321086
match[match_pos++] = patt[pos];
@@ -1044,7 +1098,16 @@ like_fixed_prefix(Const *patt_const, Const **prefix_const)
10441098

10451099
/* in LIKE, an empty pattern is an exact match! */
10461100
if (pos == pattlen)
1047-
return Pattern_Prefix_Exact; /* reached end of pattern, so exact */
1101+
{
1102+
/*
1103+
* Reached end of pattern, so exact -- unless the operator would throw
1104+
* an error at runtime. In that case our representation is lossy,
1105+
* since we don't want to throw that error here.
1106+
*/
1107+
if (badpattern)
1108+
return Pattern_Prefix_Exact_Lossy;
1109+
return Pattern_Prefix_Exact;
1110+
}
10481111

10491112
if (match_pos > 0)
10501113
return Pattern_Prefix_Partial;
@@ -1070,6 +1133,7 @@ like_fixed_prefix_ci(Const *patt_const, Oid collation, Const **prefix_const)
10701133
char *match;
10711134
int match_mblen;
10721135
pg_locale_t locale = 0;
1136+
bool badpattern = false;
10731137

10741138
/* the right-hand const is type text or bytea */
10751139
Assert(typeid == BYTEAOID || typeid == TEXTOID);
@@ -1109,7 +1173,10 @@ like_fixed_prefix_ci(Const *patt_const, Oid collation, Const **prefix_const)
11091173
{
11101174
wpos++;
11111175
if (wpos >= wpattlen)
1176+
{
1177+
badpattern = true;
11121178
break;
1179+
}
11131180
}
11141181

11151182
/*
@@ -1136,7 +1203,16 @@ like_fixed_prefix_ci(Const *patt_const, Oid collation, Const **prefix_const)
11361203

11371204
/* in LIKE, an empty pattern is an exact match! */
11381205
if (wpos == wpattlen)
1139-
return Pattern_Prefix_Exact; /* reached end of pattern, so exact */
1206+
{
1207+
/*
1208+
* Reached end of pattern, so exact -- unless the operator would throw
1209+
* an error at runtime. In that case our representation is lossy,
1210+
* since we don't want to throw that error here.
1211+
*/
1212+
if (badpattern)
1213+
return Pattern_Prefix_Exact_Lossy;
1214+
return Pattern_Prefix_Exact;
1215+
}
11401216

11411217
if (wmatch_pos > 0)
11421218
return Pattern_Prefix_Partial;
@@ -1177,8 +1253,13 @@ regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
11771253

11781254
pfree(prefix);
11791255

1256+
/*
1257+
* Because regexp_fixed_prefix() doesn't analyze the regexp fully, even an
1258+
* "exact" match is lossy: we know that a match must be this string, but
1259+
* it could still fail to match.
1260+
*/
11801261
if (exact)
1181-
return Pattern_Prefix_Exact; /* pattern specifies exact match */
1262+
return Pattern_Prefix_Exact_Lossy;
11821263
else
11831264
return Pattern_Prefix_Partial;
11841265
}

‎src/test/regress/expected/collate.icu.utf8.out‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2310,12 +2310,11 @@ SELECT * FROM test1ci WHERE x ~ '^abc$' COLLATE "C";
23102310

23112311
EXPLAIN (COSTS OFF)
23122312
SELECT * FROM test1ci WHERE x LIKE 'abc' COLLATE case_insensitive;
2313-
QUERY PLAN
2314-
-------------------------------------------------------
2313+
QUERY PLAN
2314+
-------------------------------------------
23152315
Index Scan using test1ci_x_idx on test1ci
23162316
Index Cond: (x = 'abc'::text)
2317-
Filter: (x ~~ 'abc'::text COLLATE case_insensitive)
2318-
(3 rows)
2317+
(2 rows)
23192318

23202319
RESET enable_seqscan;
23212320
RESET enable_indexonlyscan;
@@ -3016,6 +3015,30 @@ SELECT x FROM test4c WHERE x LIKE 'ABC%' COLLATE case_insensitive; -- ok
30163015
abc
30173016
(1 row)
30183017

3018+
RESET enable_seqscan;
3019+
-- For text (test4c above) an exact-match LIKE with the index and expression
3020+
-- sharing the collation is non-lossy, so the recheck is dropped. bpchar is
3021+
-- different: its "=" ignores trailing blanks while LIKE does not, so the
3022+
-- recheck must stay to reject a padded 'abc ' that "=" would treat as equal
3023+
-- to 'abc'. The Index Cond therefore still carries a "~~" Filter here.
3024+
SET enable_seqscan = off;
3025+
EXPLAIN (COSTS OFF)
3026+
SELECT x FROM test4c WHERE x LIKE 'abc' COLLATE case_insensitive;
3027+
QUERY PLAN
3028+
----------------------------------------------
3029+
Index Only Scan using test4c_x_idx on test4c
3030+
Index Cond: (x = 'abc'::text)
3031+
(2 rows)
3032+
3033+
EXPLAIN (COSTS OFF)
3034+
SELECT x FROM test1bpci WHERE x LIKE 'abc' COLLATE case_insensitive;
3035+
QUERY PLAN
3036+
-------------------------------------------------------
3037+
Index Only Scan using test1bpci_x_idx on test1bpci
3038+
Index Cond: (x = 'abc'::bpchar)
3039+
Filter: (x ~~ 'abc'::text COLLATE case_insensitive)
3040+
(3 rows)
3041+
30193042
RESET enable_seqscan;
30203043
-- Unicode special case: different variants of Greek lower case sigma.
30213044
-- A naive implementation like citext that just does lower(x) =

‎src/test/regress/expected/collate.out‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -784,13 +784,38 @@ SELECT * FROM pg_class WHERE relname ~ '^pg_class$' COLLATE "POSIX";
784784

785785
EXPLAIN (COSTS OFF)
786786
SELECT * FROM pg_class WHERE relname LIKE 'pg\_class' COLLATE "POSIX";
787-
QUERY PLAN
788-
----------------------------------------------------------
787+
QUERY PLAN
788+
---------------------------------------------------------
789789
Index Scan using pg_class_relname_nsp_index on pg_class
790790
Index Cond: (relname = 'pg_class'::text)
791-
Filter: (relname ~~ 'pg\_class'::text COLLATE "POSIX")
791+
(2 rows)
792+
793+
-- Conversely, when the expression's collation is indeterminate (here a
794+
-- concatenation of a "C" and a "POSIX" column) but the index pins a collation,
795+
-- the exact-match "=" indexqual must stay lossy so the LIKE recheck still runs.
796+
-- Otherwise the query would silently resolve the comparison under the index's
797+
-- collation instead of failing with "could not determine which collation to
798+
-- use", making the result depend on whether an index scan is chosen.
799+
CREATE INDEX collate_test10_expr_idx ON collate_test10 ((x || y) COLLATE "C");
800+
SET enable_seqscan = off;
801+
SET enable_bitmapscan = off;
802+
EXPLAIN (COSTS OFF)
803+
SELECT a FROM collate_test10 WHERE (x || y) LIKE 'hijhij';
804+
QUERY PLAN
805+
------------------------------------------------------------
806+
Index Scan using collate_test10_expr_idx on collate_test10
807+
Index Cond: ((x || y) = 'hijhij'::text)
808+
Filter: ((x || y) ~~ 'hijhij'::text)
792809
(3 rows)
793810

811+
-- must error (rather than silently return a row via the index) so that the
812+
-- outcome does not depend on the chosen plan
813+
SELECT a FROM collate_test10 WHERE (x || y) LIKE 'hijhij';
814+
ERROR: could not determine which collation to use for LIKE
815+
HINT: Use the COLLATE clause to set the collation explicitly.
816+
RESET enable_seqscan;
817+
RESET enable_bitmapscan;
818+
DROP INDEX collate_test10_expr_idx;
794819
--
795820
-- Clean up. Many of these table names will be re-used if the user is
796821
-- trying to run any platform-specific collation tests later, so we

‎src/test/regress/sql/collate.icu.utf8.sql‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,6 +1122,18 @@ SELECT x FROM test4c WHERE x LIKE 'ABC' COLLATE case_insensitive; -- ok
11221122
SELECT x FROM test4c WHERE x LIKE 'ABC%' COLLATE case_insensitive; -- ok
11231123
RESET enable_seqscan;
11241124

1125+
-- For text (test4c above) an exact-match LIKE with the index and expression
1126+
-- sharing the collation is non-lossy, so the recheck is dropped. bpchar is
1127+
-- different: its "=" ignores trailing blanks while LIKE does not, so the
1128+
-- recheck must stay to reject a padded 'abc ' that "=" would treat as equal
1129+
-- to 'abc'. The Index Cond therefore still carries a "~~" Filter here.
1130+
SET enable_seqscan = off;
1131+
EXPLAIN (COSTS OFF)
1132+
SELECT x FROM test4c WHERE x LIKE 'abc' COLLATE case_insensitive;
1133+
EXPLAIN (COSTS OFF)
1134+
SELECT x FROM test1bpci WHERE x LIKE 'abc' COLLATE case_insensitive;
1135+
RESET enable_seqscan;
1136+
11251137
-- Unicode special case: different variants of Greek lower case sigma.
11261138
-- A naive implementation like citext that just does lower(x) =
11271139
-- lower(y) will do the wrong thing here, because lower('Σ') is 'σ'

‎src/test/regress/sql/collate.sql‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,24 @@ SELECT * FROM pg_class WHERE relname ~ '^pg_class$' COLLATE "POSIX";
312312
EXPLAIN (COSTS OFF)
313313
SELECT * FROM pg_class WHERE relname LIKE 'pg\_class' COLLATE "POSIX";
314314

315+
-- Conversely, when the expression's collation is indeterminate (here a
316+
-- concatenation of a "C" and a "POSIX" column) but the index pins a collation,
317+
-- the exact-match "=" indexqual must stay lossy so the LIKE recheck still runs.
318+
-- Otherwise the query would silently resolve the comparison under the index's
319+
-- collation instead of failing with "could not determine which collation to
320+
-- use", making the result depend on whether an index scan is chosen.
321+
CREATE INDEX collate_test10_expr_idx ON collate_test10 ((x || y) COLLATE "C");
322+
SET enable_seqscan = off;
323+
SET enable_bitmapscan = off;
324+
EXPLAIN (COSTS OFF)
325+
SELECT a FROM collate_test10 WHERE (x || y) LIKE 'hijhij';
326+
-- must error (rather than silently return a row via the index) so that the
327+
-- outcome does not depend on the chosen plan
328+
SELECT a FROM collate_test10 WHERE (x || y) LIKE 'hijhij';
329+
RESET enable_seqscan;
330+
RESET enable_bitmapscan;
331+
DROP INDEX collate_test10_expr_idx;
332+
315333
--
316334
-- Clean up. Many of these table names will be re-used if the user is
317335
-- trying to run any platform-specific collation tests later, so we

0 commit comments

Comments
 (0)