LCOV - code coverage report
Current view: top level - src/backend/utils/adt - like_support.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 80.6 % 475 383
Test Date: 2026-11-28 07:16:06 Functions: 76.3 % 38 29
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 69.7 % 238 166

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

Generated by: LCOV version 2.0-1