Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * like_support.c
4 : * Planner support functions for LIKE, regex, and related operators.
5 : *
6 : * These routines handle special optimization of operators that can be
7 : * used with index scans even though they are not known to the executor's
8 : * indexscan machinery. The key idea is that these operators allow us
9 : * to derive approximate indexscan qual clauses, such that any tuples
10 : * that pass the operator clause itself must also satisfy the simpler
11 : * indexscan condition(s). Then we can use the indexscan machinery
12 : * to avoid scanning as much of the table as we'd otherwise have to,
13 : * while applying the original operator as a qpqual condition to ensure
14 : * we deliver only the tuples we want. (In essence, we're using a regular
15 : * index as if it were a lossy index.)
16 : *
17 : * An example of what we're doing is
18 : * textfield LIKE 'abc%def'
19 : * from which we can generate the indexscanable conditions
20 : * textfield >= 'abc' AND textfield < 'abd'
21 : * which allow efficient scanning of an index on textfield.
22 : * (In reality, character set and collation issues make the transformation
23 : * from LIKE to indexscan limits rather harder than one might think ...
24 : * but that's the basic idea.)
25 : *
26 : * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
27 : * Portions Copyright (c) 1994, Regents of the University of California
28 : *
29 : *
30 : * IDENTIFICATION
31 : * src/backend/utils/adt/like_support.c
32 : *
33 : *-------------------------------------------------------------------------
34 : */
35 : #include "postgres.h"
36 :
37 : #include <math.h>
38 :
39 : #include "access/htup_details.h"
40 : #include "catalog/pg_collation.h"
41 : #include "catalog/pg_operator.h"
42 : #include "catalog/pg_opfamily.h"
43 : #include "catalog/pg_statistic.h"
44 : #include "catalog/pg_type.h"
45 : #include "mb/pg_wchar.h"
46 : #include "miscadmin.h"
47 : #include "nodes/makefuncs.h"
48 : #include "nodes/nodeFuncs.h"
49 : #include "nodes/supportnodes.h"
50 : #include "utils/builtins.h"
51 : #include "utils/datum.h"
52 : #include "utils/lsyscache.h"
53 : #include "utils/pg_locale.h"
54 : #include "utils/selfuncs.h"
55 : #include "utils/varlena.h"
56 :
57 :
58 : typedef enum
59 : {
60 : Pattern_Type_Like,
61 : Pattern_Type_Like_IC,
62 : Pattern_Type_Regex,
63 : Pattern_Type_Regex_IC,
64 : Pattern_Type_Prefix,
65 : } Pattern_Type;
66 :
67 : typedef enum
68 : {
69 : Pattern_Prefix_None, Pattern_Prefix_Partial, Pattern_Prefix_Exact,
70 : } Pattern_Prefix_Status;
71 :
72 : static Node *like_regex_support(Node *rawreq, Pattern_Type ptype);
73 : static List *match_pattern_prefix(Node *leftop,
74 : Node *rightop,
75 : Pattern_Type ptype,
76 : Oid expr_coll,
77 : Oid opfamily,
78 : Oid indexcollation);
79 : static double patternsel_common(PlannerInfo *root,
80 : Oid oprid,
81 : Oid opfuncid,
82 : List *args,
83 : int varRelid,
84 : Oid collation,
85 : Pattern_Type ptype,
86 : bool negate);
87 : static Pattern_Prefix_Status pattern_fixed_prefix(Const *patt,
88 : Pattern_Type ptype,
89 : Oid collation,
90 : Const **prefix,
91 : Selectivity *rest_selec);
92 : static Selectivity prefix_selectivity(PlannerInfo *root,
93 : VariableStatData *vardata,
94 : Oid eqopr, Oid ltopr, Oid geopr,
95 : Oid collation,
96 : Const *prefixcon);
97 : static Selectivity like_selectivity(const char *patt, int pattlen,
98 : bool case_insensitive);
99 : static Selectivity regex_selectivity(const char *patt, int pattlen,
100 : bool case_insensitive,
101 : int fixed_prefix_len);
102 : static int pattern_char_isalpha(char c, bool is_multibyte,
103 : pg_locale_t locale);
104 : static Const *make_greater_string(const Const *str_const, FmgrInfo *ltproc,
105 : Oid collation);
106 : static Datum string_to_datum(const char *str, Oid datatype);
107 : static Const *string_to_const(const char *str, Oid datatype);
108 : static Const *string_to_bytea_const(const char *str, size_t str_len);
109 :
110 :
111 : /*
112 : * Planner support functions for LIKE, regex, and related operators
113 : */
114 : Datum
115 5054 : textlike_support(PG_FUNCTION_ARGS)
116 : {
117 5054 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
118 :
119 5054 : PG_RETURN_POINTER(like_regex_support(rawreq, Pattern_Type_Like));
120 : }
121 :
122 : Datum
123 352 : texticlike_support(PG_FUNCTION_ARGS)
124 : {
125 352 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
126 :
127 352 : PG_RETURN_POINTER(like_regex_support(rawreq, Pattern_Type_Like_IC));
128 : }
129 :
130 : Datum
131 21656 : textregexeq_support(PG_FUNCTION_ARGS)
132 : {
133 21656 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
134 :
135 21656 : PG_RETURN_POINTER(like_regex_support(rawreq, Pattern_Type_Regex));
136 : }
137 :
138 : Datum
139 118 : texticregexeq_support(PG_FUNCTION_ARGS)
140 : {
141 118 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
142 :
143 118 : PG_RETURN_POINTER(like_regex_support(rawreq, Pattern_Type_Regex_IC));
144 : }
145 :
146 : Datum
147 156 : text_starts_with_support(PG_FUNCTION_ARGS)
148 : {
149 156 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
150 :
151 156 : PG_RETURN_POINTER(like_regex_support(rawreq, Pattern_Type_Prefix));
152 : }
153 :
154 : /* Common code for the above */
155 : static Node *
156 27336 : like_regex_support(Node *rawreq, Pattern_Type ptype)
157 : {
158 27336 : Node *ret = NULL;
159 :
160 27336 : if (IsA(rawreq, SupportRequestSelectivity))
161 : {
162 : /*
163 : * Make a selectivity estimate for a function call, just as we'd do if
164 : * the call was via the corresponding operator.
165 : */
166 24 : SupportRequestSelectivity *req = (SupportRequestSelectivity *) rawreq;
167 : Selectivity s1;
168 :
169 24 : if (req->is_join)
170 : {
171 : /*
172 : * For the moment we just punt. If patternjoinsel is ever
173 : * improved to do better, this should be made to call it.
174 : */
175 0 : s1 = DEFAULT_MATCH_SEL;
176 : }
177 : else
178 : {
179 : /* Share code with operator restriction selectivity functions */
180 24 : s1 = patternsel_common(req->root,
181 : InvalidOid,
182 : req->funcid,
183 : req->args,
184 : req->varRelid,
185 : req->inputcollid,
186 : ptype,
187 : false);
188 : }
189 24 : req->selectivity = s1;
190 24 : ret = (Node *) req;
191 : }
192 27312 : else if (IsA(rawreq, SupportRequestIndexCondition))
193 : {
194 : /* Try to convert operator/function call to index conditions */
195 7784 : SupportRequestIndexCondition *req = (SupportRequestIndexCondition *) rawreq;
196 :
197 : /*
198 : * Currently we have no "reverse" match operators with the pattern on
199 : * the left, so we only need consider cases with the indexkey on the
200 : * left.
201 : */
202 7784 : if (req->indexarg != 0)
203 0 : return NULL;
204 :
205 7784 : if (is_opclause(req->node))
206 : {
207 7760 : OpExpr *clause = (OpExpr *) req->node;
208 :
209 : Assert(list_length(clause->args) == 2);
210 : ret = (Node *)
211 7760 : match_pattern_prefix((Node *) linitial(clause->args),
212 7760 : (Node *) lsecond(clause->args),
213 : ptype,
214 : clause->inputcollid,
215 : req->opfamily,
216 : req->indexcollation);
217 : }
218 24 : else if (is_funcclause(req->node)) /* be paranoid */
219 : {
220 24 : FuncExpr *clause = (FuncExpr *) req->node;
221 :
222 : Assert(list_length(clause->args) == 2);
223 : ret = (Node *)
224 24 : match_pattern_prefix((Node *) linitial(clause->args),
225 24 : (Node *) lsecond(clause->args),
226 : ptype,
227 : clause->inputcollid,
228 : req->opfamily,
229 : req->indexcollation);
230 : }
231 : }
232 :
233 27336 : return ret;
234 : }
235 :
236 : /*
237 : * match_pattern_prefix
238 : * Try to generate an indexqual for a LIKE or regex operator.
239 : */
240 : static List *
241 7784 : match_pattern_prefix(Node *leftop,
242 : Node *rightop,
243 : Pattern_Type ptype,
244 : Oid expr_coll,
245 : Oid opfamily,
246 : Oid indexcollation)
247 : {
248 : List *result;
249 : Const *patt;
250 : Const *prefix;
251 : Pattern_Prefix_Status pstatus;
252 : Oid ldatatype;
253 : Oid rdatatype;
254 : Oid eqopr;
255 : Oid ltopr;
256 : Oid geopr;
257 7784 : Oid preopr = InvalidOid;
258 : bool collation_aware;
259 : Expr *expr;
260 : FmgrInfo ltproc;
261 : Const *greaterstr;
262 :
263 : /*
264 : * Can't do anything with a non-constant or NULL pattern argument.
265 : *
266 : * Note that since we restrict ourselves to cases with a hard constant on
267 : * the RHS, it's a-fortiori a pseudoconstant, and we don't need to worry
268 : * about verifying that.
269 : */
270 7784 : if (!IsA(rightop, Const) ||
271 7664 : ((Const *) rightop)->constisnull)
272 120 : return NIL;
273 7664 : patt = (Const *) rightop;
274 :
275 : /*
276 : * Not supported if the expression collation is nondeterministic. The
277 : * optimized equality or prefix tests use bytewise comparisons, which is
278 : * not consistent with nondeterministic collations. The actual
279 : * pattern-matching implementation functions will later error out that
280 : * pattern-matching is not supported with nondeterministic collations. (We
281 : * could also error out here, but by doing it later we get more precise
282 : * error messages.) (It should be possible to support at least
283 : * Pattern_Prefix_Exact, but no point as long as the actual
284 : * pattern-matching implementations don't support it.)
285 : *
286 : * expr_coll is not set for a non-collation-aware data type such as bytea.
287 : */
288 7664 : if (expr_coll && !get_collation_isdeterministic(expr_coll))
289 12 : return NIL;
290 :
291 : /*
292 : * Try to extract a fixed prefix from the pattern.
293 : */
294 7652 : pstatus = pattern_fixed_prefix(patt, ptype, expr_coll,
295 : &prefix, NULL);
296 :
297 : /* fail if no fixed prefix */
298 7652 : if (pstatus == Pattern_Prefix_None)
299 294 : return NIL;
300 :
301 : /*
302 : * Identify the operators we want to use, based on the type of the
303 : * left-hand argument. Usually these are just the type's regular
304 : * comparison operators, but if we are considering one of the semi-legacy
305 : * "pattern" opclasses, use the "pattern" operators instead. Those are
306 : * not collation-sensitive but always use C collation, as we want. The
307 : * selected operators also determine the needed type of the prefix
308 : * constant.
309 : */
310 7358 : ldatatype = exprType(leftop);
311 7358 : switch (ldatatype)
312 : {
313 68 : case TEXTOID:
314 68 : if (opfamily == TEXT_PATTERN_BTREE_FAM_OID)
315 : {
316 0 : eqopr = TextEqualOperator;
317 0 : ltopr = TextPatternLessOperator;
318 0 : geopr = TextPatternGreaterEqualOperator;
319 0 : collation_aware = false;
320 : }
321 68 : else if (opfamily == TEXT_SPGIST_FAM_OID)
322 : {
323 24 : eqopr = TextEqualOperator;
324 24 : ltopr = TextPatternLessOperator;
325 24 : geopr = TextPatternGreaterEqualOperator;
326 : /* This opfamily has direct support for prefixing */
327 24 : preopr = TextPrefixOperator;
328 24 : collation_aware = false;
329 : }
330 : else
331 : {
332 44 : eqopr = TextEqualOperator;
333 44 : ltopr = TextLessOperator;
334 44 : geopr = TextGreaterEqualOperator;
335 44 : collation_aware = true;
336 : }
337 68 : rdatatype = TEXTOID;
338 68 : break;
339 7266 : case NAMEOID:
340 :
341 : /*
342 : * Note that here, we need the RHS type to be text, so that the
343 : * comparison value isn't improperly truncated to NAMEDATALEN.
344 : */
345 7266 : eqopr = NameEqualTextOperator;
346 7266 : ltopr = NameLessTextOperator;
347 7266 : geopr = NameGreaterEqualTextOperator;
348 7266 : collation_aware = true;
349 7266 : rdatatype = TEXTOID;
350 7266 : break;
351 24 : case BPCHAROID:
352 24 : if (opfamily == BPCHAR_PATTERN_BTREE_FAM_OID)
353 : {
354 0 : eqopr = BpcharEqualOperator;
355 0 : ltopr = BpcharPatternLessOperator;
356 0 : geopr = BpcharPatternGreaterEqualOperator;
357 0 : collation_aware = false;
358 : }
359 : else
360 : {
361 24 : eqopr = BpcharEqualOperator;
362 24 : ltopr = BpcharLessOperator;
363 24 : geopr = BpcharGreaterEqualOperator;
364 24 : collation_aware = true;
365 : }
366 24 : rdatatype = BPCHAROID;
367 24 : break;
368 0 : case BYTEAOID:
369 0 : eqopr = ByteaEqualOperator;
370 0 : ltopr = ByteaLessOperator;
371 0 : geopr = ByteaGreaterEqualOperator;
372 0 : collation_aware = false;
373 0 : rdatatype = BYTEAOID;
374 0 : break;
375 0 : default:
376 : /* Can't get here unless we're attached to the wrong operator */
377 0 : return NIL;
378 : }
379 :
380 : /*
381 : * If necessary, coerce the prefix constant to the right type. The given
382 : * prefix constant is either text or bytea type, therefore the only case
383 : * where we need to do anything is when converting text to bpchar. Those
384 : * two types are binary-compatible, so relabeling the Const node is
385 : * sufficient.
386 : */
387 7358 : if (prefix->consttype != rdatatype)
388 : {
389 : Assert(prefix->consttype == TEXTOID &&
390 : rdatatype == BPCHAROID);
391 24 : prefix->consttype = rdatatype;
392 : }
393 :
394 : /*
395 : * If we found an exact-match pattern, generate an "=" indexqual.
396 : *
397 : * Here and below, check to see whether the desired operator is actually
398 : * supported by the index opclass, and fail quietly if not. This allows
399 : * us to not be concerned with specific opclasses (except for the legacy
400 : * "pattern" cases); any index that correctly implements the operators
401 : * will work.
402 : */
403 7358 : if (pstatus == Pattern_Prefix_Exact)
404 : {
405 6054 : if (!op_in_opfamily(eqopr, opfamily))
406 12 : return NIL;
407 6042 : expr = make_opclause(eqopr, BOOLOID, false,
408 : (Expr *) leftop, (Expr *) prefix,
409 : InvalidOid, indexcollation);
410 6042 : result = list_make1(expr);
411 6042 : return result;
412 : }
413 :
414 : /*
415 : * Otherwise, we have a nonempty required prefix of the values. Some
416 : * opclasses support prefix checks directly, otherwise we'll try to
417 : * generate a range constraint.
418 : */
419 1304 : if (OidIsValid(preopr) && op_in_opfamily(preopr, opfamily))
420 : {
421 24 : expr = make_opclause(preopr, BOOLOID, false,
422 : (Expr *) leftop, (Expr *) prefix,
423 : InvalidOid, indexcollation);
424 24 : result = list_make1(expr);
425 24 : return result;
426 : }
427 :
428 : /*
429 : * Since we need a range constraint, it's only going to work reliably if
430 : * the index is collation-insensitive or has "C" collation. Note that
431 : * here we are looking at the index's collation, not the expression's
432 : * collation -- this test is *not* dependent on the LIKE/regex operator's
433 : * collation.
434 : */
435 1280 : if (collation_aware &&
436 1280 : !pg_newlocale_from_collation(indexcollation)->collate_is_c)
437 8 : return NIL;
438 :
439 : /*
440 : * We can always say "x >= prefix".
441 : */
442 1272 : if (!op_in_opfamily(geopr, opfamily))
443 12 : return NIL;
444 1260 : expr = make_opclause(geopr, BOOLOID, false,
445 : (Expr *) leftop, (Expr *) prefix,
446 : InvalidOid, indexcollation);
447 1260 : result = list_make1(expr);
448 :
449 : /*-------
450 : * If we can create a string larger than the prefix, we can say
451 : * "x < greaterstr". NB: we rely on make_greater_string() to generate
452 : * a guaranteed-greater string, not just a probably-greater string.
453 : * In general this is only guaranteed in C locale, so we'd better be
454 : * using a C-locale index collation.
455 : *-------
456 : */
457 1260 : if (!op_in_opfamily(ltopr, opfamily))
458 0 : return result;
459 1260 : fmgr_info(get_opcode(ltopr), <proc);
460 1260 : greaterstr = make_greater_string(prefix, <proc, indexcollation);
461 1260 : if (greaterstr)
462 : {
463 1260 : expr = make_opclause(ltopr, BOOLOID, false,
464 : (Expr *) leftop, (Expr *) greaterstr,
465 : InvalidOid, indexcollation);
466 1260 : result = lappend(result, expr);
467 : }
468 :
469 1260 : return result;
470 : }
471 :
472 :
473 : /*
474 : * patternsel_common - generic code for pattern-match restriction selectivity.
475 : *
476 : * To support using this from either the operator or function paths, caller
477 : * may pass either operator OID or underlying function OID; we look up the
478 : * latter from the former if needed. (We could just have patternsel() call
479 : * get_opcode(), but the work would be wasted if we don't have a need to
480 : * compare a fixed prefix to the pg_statistic data.)
481 : *
482 : * Note that oprid and/or opfuncid should be for the positive-match operator
483 : * even when negate is true.
484 : */
485 : static double
486 10504 : patternsel_common(PlannerInfo *root,
487 : Oid oprid,
488 : Oid opfuncid,
489 : List *args,
490 : int varRelid,
491 : Oid collation,
492 : Pattern_Type ptype,
493 : bool negate)
494 : {
495 : VariableStatData vardata;
496 : Node *other;
497 : bool varonleft;
498 : Datum constval;
499 : Oid consttype;
500 : Oid vartype;
501 : Oid rdatatype;
502 : Oid eqopr;
503 : Oid ltopr;
504 : Oid geopr;
505 : Pattern_Prefix_Status pstatus;
506 : Const *patt;
507 10504 : Const *prefix = NULL;
508 10504 : Selectivity rest_selec = 0;
509 10504 : double nullfrac = 0.0;
510 : double result;
511 :
512 : /*
513 : * Initialize result to the appropriate default estimate depending on
514 : * whether it's a match or not-match operator.
515 : */
516 10504 : if (negate)
517 1516 : result = 1.0 - DEFAULT_MATCH_SEL;
518 : else
519 8988 : result = DEFAULT_MATCH_SEL;
520 :
521 : /*
522 : * If expression is not variable op constant, then punt and return the
523 : * default estimate.
524 : */
525 10504 : if (!get_restriction_variable(root, args, varRelid,
526 : &vardata, &other, &varonleft))
527 232 : return result;
528 10272 : if (!varonleft || !IsA(other, Const))
529 : {
530 50 : ReleaseVariableStats(vardata);
531 50 : return result;
532 : }
533 :
534 : /*
535 : * If the constant is NULL, assume operator is strict and return zero, ie,
536 : * operator will never return TRUE. (It's zero even for a negator op.)
537 : */
538 10222 : if (((Const *) other)->constisnull)
539 : {
540 0 : ReleaseVariableStats(vardata);
541 0 : return 0.0;
542 : }
543 10222 : constval = ((Const *) other)->constvalue;
544 10222 : consttype = ((Const *) other)->consttype;
545 :
546 : /*
547 : * The right-hand const is type text or bytea for all supported operators.
548 : * We do not expect to see binary-compatible types here, since
549 : * const-folding should have relabeled the const to exactly match the
550 : * operator's declared type.
551 : */
552 10222 : if (consttype != TEXTOID && consttype != BYTEAOID)
553 : {
554 24 : ReleaseVariableStats(vardata);
555 24 : return result;
556 : }
557 :
558 : /*
559 : * Similarly, the exposed type of the left-hand side should be one of
560 : * those we know. (Do not look at vardata.atttype, which might be
561 : * something binary-compatible but different.) We can use it to identify
562 : * the comparison operators and the required type of the comparison
563 : * constant, much as in match_pattern_prefix().
564 : */
565 10198 : vartype = vardata.vartype;
566 :
567 10198 : switch (vartype)
568 : {
569 1454 : case TEXTOID:
570 1454 : eqopr = TextEqualOperator;
571 1454 : ltopr = TextLessOperator;
572 1454 : geopr = TextGreaterEqualOperator;
573 1454 : rdatatype = TEXTOID;
574 1454 : break;
575 8650 : case NAMEOID:
576 :
577 : /*
578 : * Note that here, we need the RHS type to be text, so that the
579 : * comparison value isn't improperly truncated to NAMEDATALEN.
580 : */
581 8650 : eqopr = NameEqualTextOperator;
582 8650 : ltopr = NameLessTextOperator;
583 8650 : geopr = NameGreaterEqualTextOperator;
584 8650 : rdatatype = TEXTOID;
585 8650 : break;
586 84 : case BPCHAROID:
587 84 : eqopr = BpcharEqualOperator;
588 84 : ltopr = BpcharLessOperator;
589 84 : geopr = BpcharGreaterEqualOperator;
590 84 : rdatatype = BPCHAROID;
591 84 : break;
592 6 : case BYTEAOID:
593 6 : eqopr = ByteaEqualOperator;
594 6 : ltopr = ByteaLessOperator;
595 6 : geopr = ByteaGreaterEqualOperator;
596 6 : rdatatype = BYTEAOID;
597 6 : break;
598 4 : default:
599 : /* Can't get here unless we're attached to the wrong operator */
600 4 : ReleaseVariableStats(vardata);
601 4 : return result;
602 : }
603 :
604 : /*
605 : * Grab the nullfrac for use below.
606 : */
607 10194 : if (HeapTupleIsValid(vardata.statsTuple))
608 : {
609 : Form_pg_statistic stats;
610 :
611 8250 : stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
612 8250 : nullfrac = stats->stanullfrac;
613 : }
614 :
615 : /*
616 : * Pull out any fixed prefix implied by the pattern, and estimate the
617 : * fractional selectivity of the remainder of the pattern. Unlike many
618 : * other selectivity estimators, we use the pattern operator's actual
619 : * collation for this step. This is not because we expect the collation
620 : * to make a big difference in the selectivity estimate (it seldom would),
621 : * but because we want to be sure we cache compiled regexps under the
622 : * right cache key, so that they can be re-used at runtime.
623 : */
624 10194 : patt = (Const *) other;
625 10194 : pstatus = pattern_fixed_prefix(patt, ptype, collation,
626 : &prefix, &rest_selec);
627 :
628 : /*
629 : * If necessary, coerce the prefix constant to the right type. The only
630 : * case where we need to do anything is when converting text to bpchar.
631 : * Those two types are binary-compatible, so relabeling the Const node is
632 : * sufficient.
633 : */
634 10170 : if (prefix && prefix->consttype != rdatatype)
635 : {
636 : Assert(prefix->consttype == TEXTOID &&
637 : rdatatype == BPCHAROID);
638 36 : prefix->consttype = rdatatype;
639 : }
640 :
641 10170 : if (pstatus == Pattern_Prefix_Exact)
642 : {
643 : /*
644 : * Pattern specifies an exact match, so estimate as for '='
645 : */
646 6220 : result = var_eq_const(&vardata, eqopr, collation, prefix->constvalue,
647 : false, true, false);
648 : }
649 : else
650 : {
651 : /*
652 : * Not exact-match pattern. If we have a sufficiently large
653 : * histogram, estimate selectivity for the histogram part of the
654 : * population by counting matches in the histogram. If not, estimate
655 : * selectivity of the fixed prefix and remainder of pattern
656 : * separately, then combine the two to get an estimate of the
657 : * selectivity for the part of the column population represented by
658 : * the histogram. (For small histograms, we combine these
659 : * approaches.)
660 : *
661 : * We then add up data for any most-common-values values; these are
662 : * not in the histogram population, and we can get exact answers for
663 : * them by applying the pattern operator, so there's no reason to
664 : * approximate. (If the MCVs cover a significant part of the total
665 : * population, this gives us a big leg up in accuracy.)
666 : */
667 : Selectivity selec;
668 : int hist_size;
669 : FmgrInfo opproc;
670 : double mcv_selec,
671 : sumcommon;
672 :
673 : /* Try to use the histogram entries to get selectivity */
674 3950 : if (!OidIsValid(opfuncid))
675 3926 : opfuncid = get_opcode(oprid);
676 3950 : fmgr_info(opfuncid, &opproc);
677 :
678 3950 : selec = histogram_selectivity(&vardata, &opproc, collation,
679 : constval, true,
680 : 10, 1, &hist_size);
681 :
682 : /* If not at least 100 entries, use the heuristic method */
683 3950 : if (hist_size < 100)
684 : {
685 : Selectivity heursel;
686 : Selectivity prefixsel;
687 :
688 2640 : if (pstatus == Pattern_Prefix_Partial)
689 1900 : prefixsel = prefix_selectivity(root, &vardata,
690 : eqopr, ltopr, geopr,
691 : collation,
692 : prefix);
693 : else
694 740 : prefixsel = 1.0;
695 2640 : heursel = prefixsel * rest_selec;
696 :
697 2640 : if (selec < 0) /* fewer than 10 histogram entries? */
698 2384 : selec = heursel;
699 : else
700 : {
701 : /*
702 : * For histogram sizes from 10 to 100, we combine the
703 : * histogram and heuristic selectivities, putting increasingly
704 : * more trust in the histogram for larger sizes.
705 : */
706 256 : double hist_weight = hist_size / 100.0;
707 :
708 256 : selec = selec * hist_weight + heursel * (1.0 - hist_weight);
709 : }
710 : }
711 :
712 : /* In any case, don't believe extremely small or large estimates. */
713 3950 : if (selec < 0.0001)
714 1420 : selec = 0.0001;
715 2530 : else if (selec > 0.9999)
716 124 : selec = 0.9999;
717 :
718 : /*
719 : * If we have most-common-values info, add up the fractions of the MCV
720 : * entries that satisfy MCV OP PATTERN. These fractions contribute
721 : * directly to the result selectivity. Also add up the total fraction
722 : * represented by MCV entries.
723 : */
724 3950 : mcv_selec = mcv_selectivity(&vardata, &opproc, collation,
725 : constval, true,
726 : &sumcommon);
727 :
728 : /*
729 : * Now merge the results from the MCV and histogram calculations,
730 : * realizing that the histogram covers only the non-null values that
731 : * are not listed in MCV.
732 : */
733 3950 : selec *= 1.0 - nullfrac - sumcommon;
734 3950 : selec += mcv_selec;
735 3950 : result = selec;
736 : }
737 :
738 : /* now adjust if we wanted not-match rather than match */
739 10170 : if (negate)
740 1308 : result = 1.0 - result - nullfrac;
741 :
742 : /* result should be in range, but make sure... */
743 10170 : CLAMP_PROBABILITY(result);
744 :
745 10170 : if (prefix)
746 : {
747 9576 : pfree(DatumGetPointer(prefix->constvalue));
748 9576 : pfree(prefix);
749 : }
750 :
751 10170 : ReleaseVariableStats(vardata);
752 :
753 10170 : return result;
754 : }
755 :
756 : /*
757 : * Fix impedance mismatch between SQL-callable functions and patternsel_common
758 : */
759 : static double
760 10480 : patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
761 : {
762 10480 : PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
763 10480 : Oid operator = PG_GETARG_OID(1);
764 10480 : List *args = (List *) PG_GETARG_POINTER(2);
765 10480 : int varRelid = PG_GETARG_INT32(3);
766 10480 : Oid collation = PG_GET_COLLATION();
767 :
768 : /*
769 : * If this is for a NOT LIKE or similar operator, get the corresponding
770 : * positive-match operator and work with that.
771 : */
772 10480 : if (negate)
773 : {
774 1516 : operator = get_negator(operator);
775 1516 : if (!OidIsValid(operator))
776 0 : elog(ERROR, "patternsel called for operator without a negator");
777 : }
778 :
779 10480 : return patternsel_common(root,
780 : operator,
781 : InvalidOid,
782 : args,
783 : varRelid,
784 : collation,
785 : ptype,
786 : negate);
787 : }
788 :
789 : /*
790 : * regexeqsel - Selectivity of regular-expression pattern match.
791 : */
792 : Datum
793 7204 : regexeqsel(PG_FUNCTION_ARGS)
794 : {
795 7204 : PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, false));
796 : }
797 :
798 : /*
799 : * icregexeqsel - Selectivity of case-insensitive regex match.
800 : */
801 : Datum
802 64 : icregexeqsel(PG_FUNCTION_ARGS)
803 : {
804 64 : PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, false));
805 : }
806 :
807 : /*
808 : * likesel - Selectivity of LIKE pattern match.
809 : */
810 : Datum
811 1516 : likesel(PG_FUNCTION_ARGS)
812 : {
813 1516 : PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, false));
814 : }
815 :
816 : /*
817 : * prefixsel - selectivity of prefix operator
818 : */
819 : Datum
820 54 : prefixsel(PG_FUNCTION_ARGS)
821 : {
822 54 : PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Prefix, false));
823 : }
824 :
825 : /*
826 : *
827 : * iclikesel - Selectivity of ILIKE pattern match.
828 : */
829 : Datum
830 126 : iclikesel(PG_FUNCTION_ARGS)
831 : {
832 126 : PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, false));
833 : }
834 :
835 : /*
836 : * regexnesel - Selectivity of regular-expression pattern non-match.
837 : */
838 : Datum
839 1356 : regexnesel(PG_FUNCTION_ARGS)
840 : {
841 1356 : PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, true));
842 : }
843 :
844 : /*
845 : * icregexnesel - Selectivity of case-insensitive regex non-match.
846 : */
847 : Datum
848 16 : icregexnesel(PG_FUNCTION_ARGS)
849 : {
850 16 : PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, true));
851 : }
852 :
853 : /*
854 : * nlikesel - Selectivity of LIKE pattern non-match.
855 : */
856 : Datum
857 136 : nlikesel(PG_FUNCTION_ARGS)
858 : {
859 136 : PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, true));
860 : }
861 :
862 : /*
863 : * icnlikesel - Selectivity of ILIKE pattern non-match.
864 : */
865 : Datum
866 8 : icnlikesel(PG_FUNCTION_ARGS)
867 : {
868 8 : PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, true));
869 : }
870 :
871 : /*
872 : * patternjoinsel - Generic code for pattern-match join selectivity.
873 : */
874 : static double
875 236 : patternjoinsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
876 : {
877 : /* For the moment we just punt. */
878 236 : return negate ? (1.0 - DEFAULT_MATCH_SEL) : DEFAULT_MATCH_SEL;
879 : }
880 :
881 : /*
882 : * regexeqjoinsel - Join selectivity of regular-expression pattern match.
883 : */
884 : Datum
885 236 : regexeqjoinsel(PG_FUNCTION_ARGS)
886 : {
887 236 : PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, false));
888 : }
889 :
890 : /*
891 : * icregexeqjoinsel - Join selectivity of case-insensitive regex match.
892 : */
893 : Datum
894 0 : icregexeqjoinsel(PG_FUNCTION_ARGS)
895 : {
896 0 : PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, false));
897 : }
898 :
899 : /*
900 : * likejoinsel - Join selectivity of LIKE pattern match.
901 : */
902 : Datum
903 0 : likejoinsel(PG_FUNCTION_ARGS)
904 : {
905 0 : PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, false));
906 : }
907 :
908 : /*
909 : * prefixjoinsel - Join selectivity of prefix operator
910 : */
911 : Datum
912 0 : prefixjoinsel(PG_FUNCTION_ARGS)
913 : {
914 0 : PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Prefix, false));
915 : }
916 :
917 : /*
918 : * iclikejoinsel - Join selectivity of ILIKE pattern match.
919 : */
920 : Datum
921 0 : iclikejoinsel(PG_FUNCTION_ARGS)
922 : {
923 0 : PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, false));
924 : }
925 :
926 : /*
927 : * regexnejoinsel - Join selectivity of regex non-match.
928 : */
929 : Datum
930 0 : regexnejoinsel(PG_FUNCTION_ARGS)
931 : {
932 0 : PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, true));
933 : }
934 :
935 : /*
936 : * icregexnejoinsel - Join selectivity of case-insensitive regex non-match.
937 : */
938 : Datum
939 0 : icregexnejoinsel(PG_FUNCTION_ARGS)
940 : {
941 0 : PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, true));
942 : }
943 :
944 : /*
945 : * nlikejoinsel - Join selectivity of LIKE pattern non-match.
946 : */
947 : Datum
948 0 : nlikejoinsel(PG_FUNCTION_ARGS)
949 : {
950 0 : PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, true));
951 : }
952 :
953 : /*
954 : * icnlikejoinsel - Join selectivity of ILIKE pattern non-match.
955 : */
956 : Datum
957 0 : icnlikejoinsel(PG_FUNCTION_ARGS)
958 : {
959 0 : PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, true));
960 : }
961 :
962 :
963 : /*-------------------------------------------------------------------------
964 : *
965 : * Pattern analysis functions
966 : *
967 : * These routines support analysis of LIKE and regular-expression patterns
968 : * by the planner/optimizer. It's important that they agree with the
969 : * regular-expression code in backend/regex/ and the LIKE code in
970 : * backend/utils/adt/like.c. Also, the computation of the fixed prefix
971 : * must be conservative: if we report a string longer than the true fixed
972 : * prefix, the query may produce actually wrong answers, rather than just
973 : * getting a bad selectivity estimate!
974 : *
975 : *-------------------------------------------------------------------------
976 : */
977 :
978 : /*
979 : * Extract the fixed prefix, if any, for a pattern.
980 : *
981 : * *prefix is set to a palloc'd prefix string (in the form of a Const node),
982 : * or to NULL if no fixed prefix exists for the pattern.
983 : * If rest_selec is not NULL, *rest_selec is set to an estimate of the
984 : * selectivity of the remainder of the pattern (without any fixed prefix).
985 : * The prefix Const has the same type (TEXT or BYTEA) as the input pattern.
986 : *
987 : * The return value distinguishes no fixed prefix, a partial prefix,
988 : * or an exact-match-only pattern.
989 : */
990 :
991 : static Pattern_Prefix_Status
992 2898 : like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
993 : Const **prefix_const, Selectivity *rest_selec)
994 : {
995 : char *match;
996 : char *patt;
997 : int pattlen;
998 2898 : Oid typeid = patt_const->consttype;
999 : int pos,
1000 : match_pos;
1001 2898 : bool is_multibyte = (pg_database_encoding_max_length() > 1);
1002 2898 : pg_locale_t locale = 0;
1003 :
1004 : /* the right-hand const is type text or bytea */
1005 : Assert(typeid == BYTEAOID || typeid == TEXTOID);
1006 :
1007 2898 : if (case_insensitive)
1008 : {
1009 234 : if (typeid == BYTEAOID)
1010 0 : ereport(ERROR,
1011 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1012 : errmsg("case insensitive matching not supported on type bytea")));
1013 :
1014 234 : if (!OidIsValid(collation))
1015 : {
1016 : /*
1017 : * This typically means that the parser could not resolve a
1018 : * conflict of implicit collations, so report it that way.
1019 : */
1020 0 : ereport(ERROR,
1021 : (errcode(ERRCODE_INDETERMINATE_COLLATION),
1022 : errmsg("could not determine which collation to use for ILIKE"),
1023 : errhint("Use the COLLATE clause to set the collation explicitly.")));
1024 : }
1025 :
1026 234 : locale = pg_newlocale_from_collation(collation);
1027 : }
1028 :
1029 2898 : if (typeid != BYTEAOID)
1030 : {
1031 2886 : patt = TextDatumGetCString(patt_const->constvalue);
1032 2886 : pattlen = strlen(patt);
1033 : }
1034 : else
1035 : {
1036 12 : bytea *bstr = DatumGetByteaPP(patt_const->constvalue);
1037 :
1038 12 : pattlen = VARSIZE_ANY_EXHDR(bstr);
1039 12 : patt = (char *) palloc(pattlen);
1040 12 : memcpy(patt, VARDATA_ANY(bstr), pattlen);
1041 : Assert((Pointer) bstr == DatumGetPointer(patt_const->constvalue));
1042 : }
1043 :
1044 2898 : match = palloc(pattlen + 1);
1045 2898 : match_pos = 0;
1046 15542 : for (pos = 0; pos < pattlen; pos++)
1047 : {
1048 : /* % and _ are wildcard characters in LIKE */
1049 15454 : if (patt[pos] == '%' ||
1050 13864 : patt[pos] == '_')
1051 : break;
1052 :
1053 : /* Backslash escapes the next character */
1054 12814 : if (patt[pos] == '\\')
1055 : {
1056 274 : pos++;
1057 274 : if (pos >= pattlen)
1058 0 : break;
1059 : }
1060 :
1061 : /* Stop if case-varying character (it's sort of a wildcard) */
1062 13080 : if (case_insensitive &&
1063 266 : pattern_char_isalpha(patt[pos], is_multibyte, locale))
1064 170 : break;
1065 :
1066 12644 : match[match_pos++] = patt[pos];
1067 : }
1068 :
1069 2898 : match[match_pos] = '\0';
1070 :
1071 2898 : if (typeid != BYTEAOID)
1072 2886 : *prefix_const = string_to_const(match, typeid);
1073 : else
1074 12 : *prefix_const = string_to_bytea_const(match, match_pos);
1075 :
1076 2898 : if (rest_selec != NULL)
1077 1770 : *rest_selec = like_selectivity(&patt[pos], pattlen - pos,
1078 : case_insensitive);
1079 :
1080 2898 : pfree(patt);
1081 2898 : pfree(match);
1082 :
1083 : /* in LIKE, an empty pattern is an exact match! */
1084 2898 : if (pos == pattlen)
1085 88 : return Pattern_Prefix_Exact; /* reached end of pattern, so exact */
1086 :
1087 2810 : if (match_pos > 0)
1088 2294 : return Pattern_Prefix_Partial;
1089 :
1090 516 : return Pattern_Prefix_None;
1091 : }
1092 :
1093 : static Pattern_Prefix_Status
1094 14846 : regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
1095 : Const **prefix_const, Selectivity *rest_selec)
1096 : {
1097 14846 : Oid typeid = patt_const->consttype;
1098 : char *prefix;
1099 : bool exact;
1100 :
1101 : /*
1102 : * Should be unnecessary, there are no bytea regex operators defined. As
1103 : * such, it should be noted that the rest of this function has *not* been
1104 : * made safe for binary (possibly NULL containing) strings.
1105 : */
1106 14846 : if (typeid == BYTEAOID)
1107 0 : ereport(ERROR,
1108 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1109 : errmsg("regular-expression matching not supported on type bytea")));
1110 :
1111 : /* Use the regexp machinery to extract the prefix, if any */
1112 14846 : prefix = regexp_fixed_prefix(DatumGetTextPP(patt_const->constvalue),
1113 : case_insensitive, collation,
1114 : &exact);
1115 :
1116 14822 : if (prefix == NULL)
1117 : {
1118 726 : *prefix_const = NULL;
1119 :
1120 726 : if (rest_selec != NULL)
1121 : {
1122 594 : char *patt = TextDatumGetCString(patt_const->constvalue);
1123 :
1124 594 : *rest_selec = regex_selectivity(patt, strlen(patt),
1125 : case_insensitive,
1126 : 0);
1127 594 : pfree(patt);
1128 : }
1129 :
1130 726 : return Pattern_Prefix_None;
1131 : }
1132 :
1133 14096 : *prefix_const = string_to_const(prefix, typeid);
1134 :
1135 14096 : if (rest_selec != NULL)
1136 : {
1137 7728 : if (exact)
1138 : {
1139 : /* Exact match, so there's no additional selectivity */
1140 6168 : *rest_selec = 1.0;
1141 : }
1142 : else
1143 : {
1144 1560 : char *patt = TextDatumGetCString(patt_const->constvalue);
1145 :
1146 3120 : *rest_selec = regex_selectivity(patt, strlen(patt),
1147 : case_insensitive,
1148 1560 : strlen(prefix));
1149 1560 : pfree(patt);
1150 : }
1151 : }
1152 :
1153 14096 : pfree(prefix);
1154 :
1155 14096 : if (exact)
1156 12186 : return Pattern_Prefix_Exact; /* pattern specifies exact match */
1157 : else
1158 1910 : return Pattern_Prefix_Partial;
1159 : }
1160 :
1161 : static Pattern_Prefix_Status
1162 17846 : pattern_fixed_prefix(Const *patt, Pattern_Type ptype, Oid collation,
1163 : Const **prefix, Selectivity *rest_selec)
1164 : {
1165 : Pattern_Prefix_Status result;
1166 :
1167 17846 : switch (ptype)
1168 : {
1169 2664 : case Pattern_Type_Like:
1170 2664 : result = like_fixed_prefix(patt, false, collation,
1171 : prefix, rest_selec);
1172 2664 : break;
1173 234 : case Pattern_Type_Like_IC:
1174 234 : result = like_fixed_prefix(patt, true, collation,
1175 : prefix, rest_selec);
1176 234 : break;
1177 14784 : case Pattern_Type_Regex:
1178 14784 : result = regex_fixed_prefix(patt, false, collation,
1179 : prefix, rest_selec);
1180 14760 : break;
1181 62 : case Pattern_Type_Regex_IC:
1182 62 : result = regex_fixed_prefix(patt, true, collation,
1183 : prefix, rest_selec);
1184 62 : break;
1185 102 : case Pattern_Type_Prefix:
1186 : /* Prefix type work is trivial. */
1187 102 : result = Pattern_Prefix_Partial;
1188 102 : *prefix = makeConst(patt->consttype,
1189 : patt->consttypmod,
1190 : patt->constcollid,
1191 : patt->constlen,
1192 : datumCopy(patt->constvalue,
1193 102 : patt->constbyval,
1194 : patt->constlen),
1195 102 : patt->constisnull,
1196 102 : patt->constbyval);
1197 102 : if (rest_selec != NULL)
1198 78 : *rest_selec = 1.0; /* all */
1199 102 : break;
1200 0 : default:
1201 0 : elog(ERROR, "unrecognized ptype: %d", (int) ptype);
1202 : result = Pattern_Prefix_None; /* keep compiler quiet */
1203 : break;
1204 : }
1205 17822 : return result;
1206 : }
1207 :
1208 : /*
1209 : * Estimate the selectivity of a fixed prefix for a pattern match.
1210 : *
1211 : * A fixed prefix "foo" is estimated as the selectivity of the expression
1212 : * "variable >= 'foo' AND variable < 'fop'".
1213 : *
1214 : * The selectivity estimate is with respect to the portion of the column
1215 : * population represented by the histogram --- the caller must fold this
1216 : * together with info about MCVs and NULLs.
1217 : *
1218 : * We use the given comparison operators and collation to do the estimation.
1219 : * The given variable and Const must be of the associated datatype(s).
1220 : *
1221 : * XXX Note: we make use of the upper bound to estimate operator selectivity
1222 : * even if the locale is such that we cannot rely on the upper-bound string.
1223 : * The selectivity only needs to be approximately right anyway, so it seems
1224 : * more useful to use the upper-bound code than not.
1225 : */
1226 : static Selectivity
1227 1900 : prefix_selectivity(PlannerInfo *root, VariableStatData *vardata,
1228 : Oid eqopr, Oid ltopr, Oid geopr,
1229 : Oid collation,
1230 : Const *prefixcon)
1231 : {
1232 : Selectivity prefixsel;
1233 : FmgrInfo opproc;
1234 : Const *greaterstrcon;
1235 : Selectivity eq_sel;
1236 :
1237 : /* Estimate the selectivity of "x >= prefix" */
1238 1900 : fmgr_info(get_opcode(geopr), &opproc);
1239 :
1240 1900 : prefixsel = ineq_histogram_selectivity(root, vardata,
1241 : geopr, &opproc, true, true,
1242 : collation,
1243 : prefixcon->constvalue,
1244 : prefixcon->consttype);
1245 :
1246 1900 : if (prefixsel < 0.0)
1247 : {
1248 : /* No histogram is present ... return a suitable default estimate */
1249 634 : return DEFAULT_MATCH_SEL;
1250 : }
1251 :
1252 : /*
1253 : * If we can create a string larger than the prefix, say "x < greaterstr".
1254 : */
1255 1266 : fmgr_info(get_opcode(ltopr), &opproc);
1256 1266 : greaterstrcon = make_greater_string(prefixcon, &opproc, collation);
1257 1266 : if (greaterstrcon)
1258 : {
1259 : Selectivity topsel;
1260 :
1261 1266 : topsel = ineq_histogram_selectivity(root, vardata,
1262 : ltopr, &opproc, false, false,
1263 : collation,
1264 : greaterstrcon->constvalue,
1265 : greaterstrcon->consttype);
1266 :
1267 : /* ineq_histogram_selectivity worked before, it shouldn't fail now */
1268 : Assert(topsel >= 0.0);
1269 :
1270 : /*
1271 : * Merge the two selectivities in the same way as for a range query
1272 : * (see clauselist_selectivity()). Note that we don't need to worry
1273 : * about double-exclusion of nulls, since ineq_histogram_selectivity
1274 : * doesn't count those anyway.
1275 : */
1276 1266 : prefixsel = topsel + prefixsel - 1.0;
1277 : }
1278 :
1279 : /*
1280 : * If the prefix is long then the two bounding values might be too close
1281 : * together for the histogram to distinguish them usefully, resulting in a
1282 : * zero estimate (plus or minus roundoff error). To avoid returning a
1283 : * ridiculously small estimate, compute the estimated selectivity for
1284 : * "variable = 'foo'", and clamp to that. (Obviously, the resultant
1285 : * estimate should be at least that.)
1286 : *
1287 : * We apply this even if we couldn't make a greater string. That case
1288 : * suggests that the prefix is near the maximum possible, and thus
1289 : * probably off the end of the histogram, and thus we probably got a very
1290 : * small estimate from the >= condition; so we still need to clamp.
1291 : */
1292 1266 : eq_sel = var_eq_const(vardata, eqopr, collation, prefixcon->constvalue,
1293 : false, true, false);
1294 :
1295 1266 : prefixsel = Max(prefixsel, eq_sel);
1296 :
1297 1266 : return prefixsel;
1298 : }
1299 :
1300 :
1301 : /*
1302 : * Estimate the selectivity of a pattern of the specified type.
1303 : * Note that any fixed prefix of the pattern will have been removed already,
1304 : * so actually we may be looking at just a fragment of the pattern.
1305 : *
1306 : * For now, we use a very simplistic approach: fixed characters reduce the
1307 : * selectivity a good deal, character ranges reduce it a little,
1308 : * wildcards (such as % for LIKE or .* for regex) increase it.
1309 : */
1310 :
1311 : #define FIXED_CHAR_SEL 0.20 /* about 1/5 */
1312 : #define CHAR_RANGE_SEL 0.25
1313 : #define ANY_CHAR_SEL 0.9 /* not 1, since it won't match end-of-string */
1314 : #define FULL_WILDCARD_SEL 5.0
1315 : #define PARTIAL_WILDCARD_SEL 2.0
1316 :
1317 : static Selectivity
1318 1770 : like_selectivity(const char *patt, int pattlen, bool case_insensitive)
1319 : {
1320 1770 : Selectivity sel = 1.0;
1321 : int pos;
1322 :
1323 : /* Skip any leading wildcard; it's already factored into initial sel */
1324 3428 : for (pos = 0; pos < pattlen; pos++)
1325 : {
1326 2510 : if (patt[pos] != '%' && patt[pos] != '_')
1327 852 : break;
1328 : }
1329 :
1330 6808 : for (; pos < pattlen; pos++)
1331 : {
1332 : /* % and _ are wildcard characters in LIKE */
1333 5038 : if (patt[pos] == '%')
1334 748 : sel *= FULL_WILDCARD_SEL;
1335 4290 : else if (patt[pos] == '_')
1336 166 : sel *= ANY_CHAR_SEL;
1337 4124 : else if (patt[pos] == '\\')
1338 : {
1339 : /* Backslash quotes the next character */
1340 40 : pos++;
1341 40 : if (pos >= pattlen)
1342 0 : break;
1343 40 : sel *= FIXED_CHAR_SEL;
1344 : }
1345 : else
1346 4084 : sel *= FIXED_CHAR_SEL;
1347 : }
1348 : /* Could get sel > 1 if multiple wildcards */
1349 1770 : if (sel > 1.0)
1350 0 : sel = 1.0;
1351 1770 : return sel;
1352 : }
1353 :
1354 : static Selectivity
1355 2508 : regex_selectivity_sub(const char *patt, int pattlen, bool case_insensitive)
1356 : {
1357 2508 : Selectivity sel = 1.0;
1358 2508 : int paren_depth = 0;
1359 2508 : int paren_pos = 0; /* dummy init to keep compiler quiet */
1360 : int pos;
1361 :
1362 : /* since this function recurses, it could be driven to stack overflow */
1363 2508 : check_stack_depth();
1364 :
1365 25864 : for (pos = 0; pos < pattlen; pos++)
1366 : {
1367 23374 : if (patt[pos] == '(')
1368 : {
1369 342 : if (paren_depth == 0)
1370 336 : paren_pos = pos; /* remember start of parenthesized item */
1371 342 : paren_depth++;
1372 : }
1373 23032 : else if (patt[pos] == ')' && paren_depth > 0)
1374 : {
1375 342 : paren_depth--;
1376 342 : if (paren_depth == 0)
1377 336 : sel *= regex_selectivity_sub(patt + (paren_pos + 1),
1378 336 : pos - (paren_pos + 1),
1379 : case_insensitive);
1380 : }
1381 22690 : else if (patt[pos] == '|' && paren_depth == 0)
1382 : {
1383 : /*
1384 : * If unquoted | is present at paren level 0 in pattern, we have
1385 : * multiple alternatives; sum their probabilities.
1386 : */
1387 36 : sel += regex_selectivity_sub(patt + (pos + 1),
1388 18 : pattlen - (pos + 1),
1389 : case_insensitive);
1390 18 : break; /* rest of pattern is now processed */
1391 : }
1392 22672 : else if (patt[pos] == '[')
1393 : {
1394 78 : bool negclass = false;
1395 :
1396 78 : if (patt[++pos] == '^')
1397 : {
1398 0 : negclass = true;
1399 0 : pos++;
1400 : }
1401 78 : if (patt[pos] == ']') /* ']' at start of class is not special */
1402 0 : pos++;
1403 380 : while (pos < pattlen && patt[pos] != ']')
1404 302 : pos++;
1405 78 : if (paren_depth == 0)
1406 78 : sel *= (negclass ? (1.0 - CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
1407 : }
1408 22594 : else if (patt[pos] == '.')
1409 : {
1410 806 : if (paren_depth == 0)
1411 466 : sel *= ANY_CHAR_SEL;
1412 : }
1413 21788 : else if (patt[pos] == '*' ||
1414 21060 : patt[pos] == '?' ||
1415 21008 : patt[pos] == '+')
1416 : {
1417 : /* Ought to be smarter about quantifiers... */
1418 794 : if (paren_depth == 0)
1419 444 : sel *= PARTIAL_WILDCARD_SEL;
1420 : }
1421 20994 : else if (patt[pos] == '{')
1422 : {
1423 264 : while (pos < pattlen && patt[pos] != '}')
1424 188 : pos++;
1425 76 : if (paren_depth == 0)
1426 64 : sel *= PARTIAL_WILDCARD_SEL;
1427 : }
1428 20918 : else if (patt[pos] == '\\')
1429 : {
1430 : /* backslash quotes the next character */
1431 200 : pos++;
1432 200 : if (pos >= pattlen)
1433 0 : break;
1434 200 : if (paren_depth == 0)
1435 104 : sel *= FIXED_CHAR_SEL;
1436 : }
1437 : else
1438 : {
1439 20718 : if (paren_depth == 0)
1440 18332 : sel *= FIXED_CHAR_SEL;
1441 : }
1442 : }
1443 : /* Could get sel > 1 if multiple wildcards */
1444 2508 : if (sel > 1.0)
1445 26 : sel = 1.0;
1446 2508 : return sel;
1447 : }
1448 :
1449 : static Selectivity
1450 2154 : regex_selectivity(const char *patt, int pattlen, bool case_insensitive,
1451 : int fixed_prefix_len)
1452 : {
1453 : Selectivity sel;
1454 :
1455 : /* If patt doesn't end with $, consider it to have a trailing wildcard */
1456 2154 : if (pattlen > 0 && patt[pattlen - 1] == '$' &&
1457 336 : (pattlen == 1 || patt[pattlen - 2] != '\\'))
1458 : {
1459 : /* has trailing $ */
1460 336 : sel = regex_selectivity_sub(patt, pattlen - 1, case_insensitive);
1461 : }
1462 : else
1463 : {
1464 : /* no trailing $ */
1465 1818 : sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
1466 1818 : sel *= FULL_WILDCARD_SEL;
1467 : }
1468 :
1469 : /*
1470 : * If there's a fixed prefix, discount its selectivity. We have to be
1471 : * careful here since a very long prefix could result in pow's result
1472 : * underflowing to zero (in which case "sel" probably has as well).
1473 : */
1474 2154 : if (fixed_prefix_len > 0)
1475 : {
1476 1560 : double prefixsel = pow(FIXED_CHAR_SEL, fixed_prefix_len);
1477 :
1478 1560 : if (prefixsel > 0.0)
1479 1560 : sel /= prefixsel;
1480 : }
1481 :
1482 : /* Make sure result stays in range */
1483 2154 : CLAMP_PROBABILITY(sel);
1484 2154 : return sel;
1485 : }
1486 :
1487 : /*
1488 : * Check whether char is a letter (and, hence, subject to case-folding)
1489 : *
1490 : * In multibyte character sets or with ICU, we can't use isalpha, and it does
1491 : * not seem worth trying to convert to wchar_t to use iswalpha or u_isalpha.
1492 : * Instead, just assume any non-ASCII char is potentially case-varying, and
1493 : * hard-wire knowledge of which ASCII chars are letters.
1494 : */
1495 : static int
1496 266 : pattern_char_isalpha(char c, bool is_multibyte,
1497 : pg_locale_t locale)
1498 : {
1499 266 : if (locale->ctype_is_c)
1500 140 : return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
1501 126 : else if (is_multibyte && IS_HIGHBIT_SET(c))
1502 0 : return true;
1503 126 : else if (locale->provider != COLLPROVIDER_LIBC)
1504 126 : return IS_HIGHBIT_SET(c) ||
1505 252 : (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
1506 : else
1507 0 : return isalpha_l((unsigned char) c, locale->info.lt);
1508 : }
1509 :
1510 :
1511 : /*
1512 : * For bytea, the increment function need only increment the current byte
1513 : * (there are no multibyte characters to worry about).
1514 : */
1515 : static bool
1516 0 : byte_increment(unsigned char *ptr, int len)
1517 : {
1518 0 : if (*ptr >= 255)
1519 0 : return false;
1520 0 : (*ptr)++;
1521 0 : return true;
1522 : }
1523 :
1524 : /*
1525 : * Try to generate a string greater than the given string or any
1526 : * string it is a prefix of. If successful, return a palloc'd string
1527 : * in the form of a Const node; else return NULL.
1528 : *
1529 : * The caller must provide the appropriate "less than" comparison function
1530 : * for testing the strings, along with the collation to use.
1531 : *
1532 : * The key requirement here is that given a prefix string, say "foo",
1533 : * we must be able to generate another string "fop" that is greater than
1534 : * all strings "foobar" starting with "foo". We can test that we have
1535 : * generated a string greater than the prefix string, but in non-C collations
1536 : * that is not a bulletproof guarantee that an extension of the string might
1537 : * not sort after it; an example is that "foo " is less than "foo!", but it
1538 : * is not clear that a "dictionary" sort ordering will consider "foo!" less
1539 : * than "foo bar". CAUTION: Therefore, this function should be used only for
1540 : * estimation purposes when working in a non-C collation.
1541 : *
1542 : * To try to catch most cases where an extended string might otherwise sort
1543 : * before the result value, we determine which of the strings "Z", "z", "y",
1544 : * and "9" is seen as largest by the collation, and append that to the given
1545 : * prefix before trying to find a string that compares as larger.
1546 : *
1547 : * To search for a greater string, we repeatedly "increment" the rightmost
1548 : * character, using an encoding-specific character incrementer function.
1549 : * When it's no longer possible to increment the last character, we truncate
1550 : * off that character and start incrementing the next-to-rightmost.
1551 : * For example, if "z" were the last character in the sort order, then we
1552 : * could produce "foo" as a string greater than "fonz".
1553 : *
1554 : * This could be rather slow in the worst case, but in most cases we
1555 : * won't have to try more than one or two strings before succeeding.
1556 : *
1557 : * Note that it's important for the character incrementer not to be too anal
1558 : * about producing every possible character code, since in some cases the only
1559 : * way to get a larger string is to increment a previous character position.
1560 : * So we don't want to spend too much time trying every possible character
1561 : * code at the last position. A good rule of thumb is to be sure that we
1562 : * don't try more than 256*K values for a K-byte character (and definitely
1563 : * not 256^K, which is what an exhaustive search would approach).
1564 : */
1565 : static Const *
1566 2526 : make_greater_string(const Const *str_const, FmgrInfo *ltproc, Oid collation)
1567 : {
1568 2526 : Oid datatype = str_const->consttype;
1569 : char *workstr;
1570 : int len;
1571 : Datum cmpstr;
1572 2526 : char *cmptxt = NULL;
1573 : mbcharacter_incrementer charinc;
1574 :
1575 : /*
1576 : * Get a modifiable copy of the prefix string in C-string format, and set
1577 : * up the string we will compare to as a Datum. In C locale this can just
1578 : * be the given prefix string, otherwise we need to add a suffix. Type
1579 : * BYTEA sorts bytewise so it never needs a suffix either.
1580 : */
1581 2526 : if (datatype == BYTEAOID)
1582 : {
1583 0 : bytea *bstr = DatumGetByteaPP(str_const->constvalue);
1584 :
1585 0 : len = VARSIZE_ANY_EXHDR(bstr);
1586 0 : workstr = (char *) palloc(len);
1587 0 : memcpy(workstr, VARDATA_ANY(bstr), len);
1588 : Assert((Pointer) bstr == DatumGetPointer(str_const->constvalue));
1589 0 : cmpstr = str_const->constvalue;
1590 : }
1591 : else
1592 : {
1593 2526 : if (datatype == NAMEOID)
1594 0 : workstr = DatumGetCString(DirectFunctionCall1(nameout,
1595 : str_const->constvalue));
1596 : else
1597 2526 : workstr = TextDatumGetCString(str_const->constvalue);
1598 2526 : len = strlen(workstr);
1599 2526 : if (len == 0 || pg_newlocale_from_collation(collation)->collate_is_c)
1600 2500 : cmpstr = str_const->constvalue;
1601 : else
1602 : {
1603 : /* If first time through, determine the suffix to use */
1604 : static char suffixchar = 0;
1605 : static Oid suffixcollation = 0;
1606 :
1607 26 : if (!suffixchar || suffixcollation != collation)
1608 : {
1609 : char *best;
1610 :
1611 6 : best = "Z";
1612 6 : if (varstr_cmp(best, 1, "z", 1, collation) < 0)
1613 0 : best = "z";
1614 6 : if (varstr_cmp(best, 1, "y", 1, collation) < 0)
1615 0 : best = "y";
1616 6 : if (varstr_cmp(best, 1, "9", 1, collation) < 0)
1617 0 : best = "9";
1618 6 : suffixchar = *best;
1619 6 : suffixcollation = collation;
1620 : }
1621 :
1622 : /* And build the string to compare to */
1623 26 : if (datatype == NAMEOID)
1624 : {
1625 0 : cmptxt = palloc(len + 2);
1626 0 : memcpy(cmptxt, workstr, len);
1627 0 : cmptxt[len] = suffixchar;
1628 0 : cmptxt[len + 1] = '\0';
1629 0 : cmpstr = PointerGetDatum(cmptxt);
1630 : }
1631 : else
1632 : {
1633 26 : cmptxt = palloc(VARHDRSZ + len + 1);
1634 26 : SET_VARSIZE(cmptxt, VARHDRSZ + len + 1);
1635 26 : memcpy(VARDATA(cmptxt), workstr, len);
1636 26 : *(VARDATA(cmptxt) + len) = suffixchar;
1637 26 : cmpstr = PointerGetDatum(cmptxt);
1638 : }
1639 : }
1640 : }
1641 :
1642 : /* Select appropriate character-incrementer function */
1643 2526 : if (datatype == BYTEAOID)
1644 0 : charinc = byte_increment;
1645 : else
1646 2526 : charinc = pg_database_encoding_character_incrementer();
1647 :
1648 : /* And search ... */
1649 2526 : while (len > 0)
1650 : {
1651 : int charlen;
1652 : unsigned char *lastchar;
1653 :
1654 : /* Identify the last character --- for bytea, just the last byte */
1655 2526 : if (datatype == BYTEAOID)
1656 0 : charlen = 1;
1657 : else
1658 2526 : charlen = len - pg_mbcliplen(workstr, len, len - 1);
1659 2526 : lastchar = (unsigned char *) (workstr + len - charlen);
1660 :
1661 : /*
1662 : * Try to generate a larger string by incrementing the last character
1663 : * (for BYTEA, we treat each byte as a character).
1664 : *
1665 : * Note: the incrementer function is expected to return true if it's
1666 : * generated a valid-per-the-encoding new character, otherwise false.
1667 : * The contents of the character on false return are unspecified.
1668 : */
1669 2526 : while (charinc(lastchar, charlen))
1670 : {
1671 : Const *workstr_const;
1672 :
1673 2526 : if (datatype == BYTEAOID)
1674 0 : workstr_const = string_to_bytea_const(workstr, len);
1675 : else
1676 2526 : workstr_const = string_to_const(workstr, datatype);
1677 :
1678 2526 : if (DatumGetBool(FunctionCall2Coll(ltproc,
1679 : collation,
1680 : cmpstr,
1681 : workstr_const->constvalue)))
1682 : {
1683 : /* Successfully made a string larger than cmpstr */
1684 2526 : if (cmptxt)
1685 26 : pfree(cmptxt);
1686 2526 : pfree(workstr);
1687 2526 : return workstr_const;
1688 : }
1689 :
1690 : /* No good, release unusable value and try again */
1691 0 : pfree(DatumGetPointer(workstr_const->constvalue));
1692 0 : pfree(workstr_const);
1693 : }
1694 :
1695 : /*
1696 : * No luck here, so truncate off the last character and try to
1697 : * increment the next one.
1698 : */
1699 0 : len -= charlen;
1700 0 : workstr[len] = '\0';
1701 : }
1702 :
1703 : /* Failed... */
1704 0 : if (cmptxt)
1705 0 : pfree(cmptxt);
1706 0 : pfree(workstr);
1707 :
1708 0 : return NULL;
1709 : }
1710 :
1711 : /*
1712 : * Generate a Datum of the appropriate type from a C string.
1713 : * Note that all of the supported types are pass-by-ref, so the
1714 : * returned value should be pfree'd if no longer needed.
1715 : */
1716 : static Datum
1717 19508 : string_to_datum(const char *str, Oid datatype)
1718 : {
1719 : Assert(str != NULL);
1720 :
1721 : /*
1722 : * We cheat a little by assuming that CStringGetTextDatum() will do for
1723 : * bpchar and varchar constants too...
1724 : */
1725 19508 : if (datatype == NAMEOID)
1726 0 : return DirectFunctionCall1(namein, CStringGetDatum(str));
1727 19508 : else if (datatype == BYTEAOID)
1728 0 : return DirectFunctionCall1(byteain, CStringGetDatum(str));
1729 : else
1730 19508 : return CStringGetTextDatum(str);
1731 : }
1732 :
1733 : /*
1734 : * Generate a Const node of the appropriate type from a C string.
1735 : */
1736 : static Const *
1737 19508 : string_to_const(const char *str, Oid datatype)
1738 : {
1739 19508 : Datum conval = string_to_datum(str, datatype);
1740 : Oid collation;
1741 : int constlen;
1742 :
1743 : /*
1744 : * We only need to support a few datatypes here, so hard-wire properties
1745 : * instead of incurring the expense of catalog lookups.
1746 : */
1747 19508 : switch (datatype)
1748 : {
1749 19508 : case TEXTOID:
1750 : case VARCHAROID:
1751 : case BPCHAROID:
1752 19508 : collation = DEFAULT_COLLATION_OID;
1753 19508 : constlen = -1;
1754 19508 : break;
1755 :
1756 0 : case NAMEOID:
1757 0 : collation = C_COLLATION_OID;
1758 0 : constlen = NAMEDATALEN;
1759 0 : break;
1760 :
1761 0 : case BYTEAOID:
1762 0 : collation = InvalidOid;
1763 0 : constlen = -1;
1764 0 : break;
1765 :
1766 0 : default:
1767 0 : elog(ERROR, "unexpected datatype in string_to_const: %u",
1768 : datatype);
1769 : return NULL;
1770 : }
1771 :
1772 19508 : return makeConst(datatype, -1, collation, constlen,
1773 : conval, false, false);
1774 : }
1775 :
1776 : /*
1777 : * Generate a Const node of bytea type from a binary C string and a length.
1778 : */
1779 : static Const *
1780 12 : string_to_bytea_const(const char *str, size_t str_len)
1781 : {
1782 12 : bytea *bstr = palloc(VARHDRSZ + str_len);
1783 : Datum conval;
1784 :
1785 12 : memcpy(VARDATA(bstr), str, str_len);
1786 12 : SET_VARSIZE(bstr, VARHDRSZ + str_len);
1787 12 : conval = PointerGetDatum(bstr);
1788 :
1789 12 : return makeConst(BYTEAOID, -1, InvalidOid, -1, conval, false, false);
1790 : }
|