LCOV - code coverage report
Current view: top level - src/backend/utils/adt - tsvector_op.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 88.8 % 1154 1025
Test Date: 2026-08-11 19:15:50 Functions: 84.9 % 53 45
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 67.4 % 774 522

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * tsvector_op.c
       4                 :             :  *    operations over tsvector
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  *
       8                 :             :  *
       9                 :             :  * IDENTIFICATION
      10                 :             :  *    src/backend/utils/adt/tsvector_op.c
      11                 :             :  *
      12                 :             :  *-------------------------------------------------------------------------
      13                 :             :  */
      14                 :             : #include "postgres.h"
      15                 :             : 
      16                 :             : #include <limits.h>
      17                 :             : 
      18                 :             : #include "access/htup_details.h"
      19                 :             : #include "catalog/namespace.h"
      20                 :             : #include "catalog/pg_type.h"
      21                 :             : #include "commands/trigger.h"
      22                 :             : #include "common/int.h"
      23                 :             : #include "executor/spi.h"
      24                 :             : #include "funcapi.h"
      25                 :             : #include "lib/qunique.h"
      26                 :             : #include "mb/pg_wchar.h"
      27                 :             : #include "miscadmin.h"
      28                 :             : #include "parser/parse_coerce.h"
      29                 :             : #include "tsearch/ts_utils.h"
      30                 :             : #include "utils/array.h"
      31                 :             : #include "utils/builtins.h"
      32                 :             : #include "utils/regproc.h"
      33                 :             : #include "utils/rel.h"
      34                 :             : 
      35                 :             : 
      36                 :             : typedef struct
      37                 :             : {
      38                 :             :     WordEntry  *arrb;
      39                 :             :     WordEntry  *arre;
      40                 :             :     char       *values;
      41                 :             :     char       *operand;
      42                 :             : } CHKVAL;
      43                 :             : 
      44                 :             : 
      45                 :             : typedef struct StatEntry
      46                 :             : {
      47                 :             :     uint32      ndoc;           /* zero indicates that we were already here
      48                 :             :                                  * while walking through the tree */
      49                 :             :     uint32      nentry;
      50                 :             :     struct StatEntry *left;
      51                 :             :     struct StatEntry *right;
      52                 :             :     uint32      lenlexeme;
      53                 :             :     char        lexeme[FLEXIBLE_ARRAY_MEMBER];
      54                 :             : } StatEntry;
      55                 :             : 
      56                 :             : #define STATENTRYHDRSZ  (offsetof(StatEntry, lexeme))
      57                 :             : 
      58                 :             : typedef struct
      59                 :             : {
      60                 :             :     int32       weight;
      61                 :             : 
      62                 :             :     uint32      maxdepth;
      63                 :             : 
      64                 :             :     StatEntry **stack;
      65                 :             :     uint32      stackpos;
      66                 :             : 
      67                 :             :     StatEntry  *root;
      68                 :             : } TSVectorStat;
      69                 :             : 
      70                 :             : 
      71                 :             : static TSTernaryValue TS_execute_recurse(QueryItem *curitem, void *arg,
      72                 :             :                                          uint32 flags,
      73                 :             :                                          TSExecuteCallback chkcond);
      74                 :             : static bool TS_execute_locations_recurse(QueryItem *curitem,
      75                 :             :                                          void *arg,
      76                 :             :                                          TSExecuteCallback chkcond,
      77                 :             :                                          List **locations);
      78                 :             : static int  tsvector_bsearch(const TSVectorData *tsv, char *lexeme, int lexeme_len);
      79                 :             : static Datum tsvector_update_trigger(PG_FUNCTION_ARGS, bool config_column);
      80                 :             : 
      81                 :             : 
      82                 :             : /*
      83                 :             :  * Order: haspos, len, word, for all positions (pos, weight)
      84                 :             :  */
      85                 :             : static int
      86                 :         233 : silly_cmp_tsvector(const TSVectorData *a, const TSVectorData *b)
      87                 :             : {
      88         [ -  + ]:         233 :     if (VARSIZE(a) < VARSIZE(b))
      89                 :           0 :         return -1;
      90         [ -  + ]:         233 :     else if (VARSIZE(a) > VARSIZE(b))
      91                 :           0 :         return 1;
      92         [ -  + ]:         233 :     else if (a->size < b->size)
      93                 :           0 :         return -1;
      94         [ -  + ]:         233 :     else if (a->size > b->size)
      95                 :           0 :         return 1;
      96                 :             :     else
      97                 :             :     {
      98                 :         233 :         const WordEntry *aptr = ARRPTR(a);
      99                 :         233 :         const WordEntry *bptr = ARRPTR(b);
     100                 :         233 :         int         i = 0;
     101                 :             :         int         res;
     102                 :             : 
     103                 :             : 
     104         [ +  + ]:         268 :         for (i = 0; i < a->size; i++)
     105                 :             :         {
     106         [ -  + ]:         235 :             if (aptr->haspos != bptr->haspos)
     107                 :             :             {
     108         [ #  # ]:           0 :                 return (aptr->haspos > bptr->haspos) ? -1 : 1;
     109                 :             :             }
     110         [ +  + ]:         235 :             else if ((res = tsCompareString(STRPTR(a) + aptr->pos, aptr->len, STRPTR(b) + bptr->pos, bptr->len, false)) != 0)
     111                 :             :             {
     112                 :         200 :                 return res;
     113                 :             :             }
     114         [ +  + ]:          35 :             else if (aptr->haspos)
     115                 :             :             {
     116                 :          32 :                 WordEntryPos *ap = POSDATAPTR(a, aptr);
     117                 :          32 :                 WordEntryPos *bp = POSDATAPTR(b, bptr);
     118                 :             :                 int         j;
     119                 :             : 
     120   [ +  -  +  -  :          32 :                 if (POSDATALEN(a, aptr) != POSDATALEN(b, bptr))
                   -  + ]
     121   [ #  #  #  #  :           0 :                     return (POSDATALEN(a, aptr) > POSDATALEN(b, bptr)) ? -1 : 1;
                   #  # ]
     122                 :             : 
     123   [ +  -  +  + ]:          64 :                 for (j = 0; j < POSDATALEN(a, aptr); j++)
     124                 :             :                 {
     125         [ -  + ]:          32 :                     if (WEP_GETPOS(*ap) != WEP_GETPOS(*bp))
     126                 :             :                     {
     127         [ #  # ]:           0 :                         return (WEP_GETPOS(*ap) > WEP_GETPOS(*bp)) ? -1 : 1;
     128                 :             :                     }
     129         [ -  + ]:          32 :                     else if (WEP_GETWEIGHT(*ap) != WEP_GETWEIGHT(*bp))
     130                 :             :                     {
     131         [ #  # ]:           0 :                         return (WEP_GETWEIGHT(*ap) > WEP_GETWEIGHT(*bp)) ? -1 : 1;
     132                 :             :                     }
     133                 :          32 :                     ap++, bp++;
     134                 :             :                 }
     135                 :             :             }
     136                 :             : 
     137                 :          35 :             aptr++;
     138                 :          35 :             bptr++;
     139                 :             :         }
     140                 :             :     }
     141                 :             : 
     142                 :          33 :     return 0;
     143                 :             : }
     144                 :             : 
     145                 :             : #define TSVECTORCMPFUNC( type, action, ret )            \
     146                 :             : Datum                                                   \
     147                 :             : tsvector_##type(PG_FUNCTION_ARGS)                       \
     148                 :             : {                                                       \
     149                 :             :     TSVector    a = PG_GETARG_TSVECTOR(0);              \
     150                 :             :     TSVector    b = PG_GETARG_TSVECTOR(1);              \
     151                 :             :     int         res = silly_cmp_tsvector(a, b);         \
     152                 :             :     PG_FREE_IF_COPY(a,0);                               \
     153                 :             :     PG_FREE_IF_COPY(b,1);                               \
     154                 :             :     PG_RETURN_##ret( res action 0 );                    \
     155                 :             : }   \
     156                 :             : /* keep compiler quiet - no extra ; */                  \
     157                 :             : extern int no_such_variable
     158                 :             : 
     159   [ #  #  #  # ]:           0 : TSVECTORCMPFUNC(lt, <, BOOL);
     160   [ #  #  #  # ]:           0 : TSVECTORCMPFUNC(le, <=, BOOL);
     161   [ -  +  -  + ]:           1 : TSVECTORCMPFUNC(eq, ==, BOOL);
     162   [ #  #  #  # ]:           0 : TSVECTORCMPFUNC(ge, >=, BOOL);
     163   [ #  #  #  # ]:           0 : TSVECTORCMPFUNC(gt, >, BOOL);
     164   [ #  #  #  # ]:           0 : TSVECTORCMPFUNC(ne, !=, BOOL);
     165   [ -  +  -  + ]:         232 : TSVECTORCMPFUNC(cmp, +, INT32);
     166                 :             : 
     167                 :             : Datum
     168                 :          73 : tsvector_strip(PG_FUNCTION_ARGS)
     169                 :             : {
     170                 :          73 :     TSVector    in = PG_GETARG_TSVECTOR(0);
     171                 :             :     TSVector    out;
     172                 :             :     int         i,
     173                 :          73 :                 len = 0;
     174                 :          73 :     WordEntry  *arrin = ARRPTR(in),
     175                 :             :                *arrout;
     176                 :             :     char       *cur;
     177                 :             : 
     178                 :             :     /* Output can't be bigger than input, so no need for overflow checks */
     179         [ +  + ]:         261 :     for (i = 0; i < in->size; i++)
     180                 :         188 :         len += arrin[i].len;
     181                 :             : 
     182                 :          73 :     len = CALCDATASIZE(in->size, len);
     183                 :          73 :     out = (TSVector) palloc0(len);
     184                 :          73 :     SET_VARSIZE(out, len);
     185                 :          73 :     out->size = in->size;
     186                 :          73 :     arrout = ARRPTR(out);
     187                 :          73 :     cur = STRPTR(out);
     188         [ +  + ]:         261 :     for (i = 0; i < in->size; i++)
     189                 :             :     {
     190                 :         188 :         memcpy(cur, STRPTR(in) + arrin[i].pos, arrin[i].len);
     191                 :         188 :         arrout[i].haspos = 0;
     192                 :         188 :         arrout[i].len = arrin[i].len;
     193                 :         188 :         arrout[i].pos = cur - STRPTR(out);
     194                 :         188 :         cur += arrout[i].len;
     195                 :             :     }
     196                 :             : 
     197         [ -  + ]:          73 :     PG_FREE_IF_COPY(in, 0);
     198                 :          73 :     PG_RETURN_POINTER(out);
     199                 :             : }
     200                 :             : 
     201                 :             : Datum
     202                 :           7 : tsvector_length(PG_FUNCTION_ARGS)
     203                 :             : {
     204                 :           7 :     TSVector    in = PG_GETARG_TSVECTOR(0);
     205                 :           7 :     int32       ret = in->size;
     206                 :             : 
     207         [ -  + ]:           7 :     PG_FREE_IF_COPY(in, 0);
     208                 :           7 :     PG_RETURN_INT32(ret);
     209                 :             : }
     210                 :             : 
     211                 :             : static int
     212                 :          48 : parse_weight(char cw)
     213                 :             : {
     214                 :             :     int         w;
     215                 :             : 
     216   [ +  +  +  -  :          48 :     switch (cw)
                      - ]
     217                 :             :     {
     218                 :          14 :         case 'A':
     219                 :             :         case 'a':
     220                 :          14 :             w = 3;
     221                 :          14 :             break;
     222                 :           4 :         case 'B':
     223                 :             :         case 'b':
     224                 :           4 :             w = 2;
     225                 :           4 :             break;
     226                 :          30 :         case 'C':
     227                 :             :         case 'c':
     228                 :          30 :             w = 1;
     229                 :          30 :             break;
     230                 :           0 :         case 'D':
     231                 :             :         case 'd':
     232                 :           0 :             w = 0;
     233                 :           0 :             break;
     234                 :           0 :         default:
     235                 :             :             /* Avoid printing non-ASCII bytes, else we have encoding issues */
     236   [ #  #  #  # ]:           0 :             if (cw >= ' ' && cw < 0x7f)
     237         [ #  # ]:           0 :                 ereport(ERROR,
     238                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     239                 :             :                          errmsg("unrecognized weight: \"%c\"", cw)));
     240                 :             :             else                /* use \ooo format, like charout() */
     241         [ #  # ]:           0 :                 ereport(ERROR,
     242                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     243                 :             :                          errmsg("unrecognized weight: \"\\%03o\"",
     244                 :             :                                 (unsigned char) cw)));
     245                 :             :     }
     246                 :          48 :     return w;
     247                 :             : }
     248                 :             : 
     249                 :             : 
     250                 :             : Datum
     251                 :          10 : tsvector_setweight(PG_FUNCTION_ARGS)
     252                 :             : {
     253                 :          10 :     TSVector    in = PG_GETARG_TSVECTOR(0);
     254                 :          10 :     char        cw = PG_GETARG_CHAR(1);
     255                 :             :     TSVector    out;
     256                 :             :     int         i,
     257                 :             :                 j;
     258                 :             :     WordEntry  *entry;
     259                 :             :     WordEntryPos *p;
     260                 :          10 :     int         w = parse_weight(cw);
     261                 :             : 
     262                 :          10 :     out = (TSVector) palloc(VARSIZE(in));
     263                 :          10 :     memcpy(out, in, VARSIZE(in));
     264                 :          10 :     entry = ARRPTR(out);
     265                 :          10 :     i = out->size;
     266         [ +  + ]:          50 :     while (i--)
     267                 :             :     {
     268   [ +  -  +  - ]:          40 :         if ((j = POSDATALEN(out, entry)) != 0)
     269                 :             :         {
     270                 :          40 :             p = POSDATAPTR(out, entry);
     271         [ +  + ]:         140 :             while (j--)
     272                 :             :             {
     273                 :         100 :                 WEP_SETWEIGHT(*p, w);
     274                 :         100 :                 p++;
     275                 :             :             }
     276                 :             :         }
     277                 :          40 :         entry++;
     278                 :             :     }
     279                 :             : 
     280         [ -  + ]:          10 :     PG_FREE_IF_COPY(in, 0);
     281                 :          10 :     PG_RETURN_POINTER(out);
     282                 :             : }
     283                 :             : 
     284                 :             : /*
     285                 :             :  * setweight(tsin tsvector, char_weight "char", lexemes "text"[])
     286                 :             :  *
     287                 :             :  * Assign weight w to elements of tsin that are listed in lexemes.
     288                 :             :  */
     289                 :             : Datum
     290                 :          20 : tsvector_setweight_by_filter(PG_FUNCTION_ARGS)
     291                 :             : {
     292                 :          20 :     TSVector    tsin = PG_GETARG_TSVECTOR(0);
     293                 :          20 :     char        char_weight = PG_GETARG_CHAR(1);
     294                 :          20 :     ArrayType  *lexemes = PG_GETARG_ARRAYTYPE_P(2);
     295                 :             : 
     296                 :             :     TSVector    tsout;
     297                 :             :     int         i,
     298                 :             :                 j,
     299                 :             :                 nlexemes,
     300                 :             :                 weight;
     301                 :             :     WordEntry  *entry;
     302                 :             :     Datum      *dlexemes;
     303                 :             :     bool       *nulls;
     304                 :             : 
     305                 :          20 :     weight = parse_weight(char_weight);
     306                 :             : 
     307                 :          20 :     tsout = (TSVector) palloc(VARSIZE(tsin));
     308                 :          20 :     memcpy(tsout, tsin, VARSIZE(tsin));
     309                 :          20 :     entry = ARRPTR(tsout);
     310                 :             : 
     311                 :          20 :     deconstruct_array_builtin(lexemes, TEXTOID, &dlexemes, &nulls, &nlexemes);
     312                 :             : 
     313                 :             :     /*
     314                 :             :      * Assuming that lexemes array is significantly shorter than tsvector we
     315                 :             :      * can iterate through lexemes performing binary search of each lexeme
     316                 :             :      * from lexemes in tsvector.
     317                 :             :      */
     318         [ +  + ]:          60 :     for (i = 0; i < nlexemes; i++)
     319                 :             :     {
     320                 :             :         char       *lex;
     321                 :             :         int         lex_len,
     322                 :             :                     lex_pos;
     323                 :             : 
     324                 :             :         /* Ignore null array elements, they surely don't match */
     325         [ +  + ]:          40 :         if (nulls[i])
     326                 :           5 :             continue;
     327                 :             : 
     328                 :          35 :         lex = VARDATA(DatumGetPointer(dlexemes[i]));
     329                 :          35 :         lex_len = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
     330                 :          35 :         lex_pos = tsvector_bsearch(tsout, lex, lex_len);
     331                 :             : 
     332   [ +  +  +  +  :          35 :         if (lex_pos >= 0 && (j = POSDATALEN(tsout, entry + lex_pos)) != 0)
                   +  + ]
     333                 :             :         {
     334                 :          20 :             WordEntryPos *p = POSDATAPTR(tsout, entry + lex_pos);
     335                 :             : 
     336         [ +  + ]:          65 :             while (j--)
     337                 :             :             {
     338                 :          45 :                 WEP_SETWEIGHT(*p, weight);
     339                 :          45 :                 p++;
     340                 :             :             }
     341                 :             :         }
     342                 :             :     }
     343                 :             : 
     344         [ -  + ]:          20 :     PG_FREE_IF_COPY(tsin, 0);
     345         [ -  + ]:          20 :     PG_FREE_IF_COPY(lexemes, 2);
     346                 :             : 
     347                 :          20 :     PG_RETURN_POINTER(tsout);
     348                 :             : }
     349                 :             : 
     350                 :             : #define compareEntry(pa, a, pb, b) \
     351                 :             :     tsCompareString((pa) + (a)->pos, (a)->len,    \
     352                 :             :                     (pb) + (b)->pos, (b)->len,    \
     353                 :             :                     false)
     354                 :             : 
     355                 :             : /*
     356                 :             :  * Add positions from src to dest after offsetting them by maxpos.
     357                 :             :  * Return the number added (might be less than expected due to overflow)
     358                 :             :  */
     359                 :             : static int32
     360                 :          10 : add_pos(TSVector src, WordEntry *srcptr,
     361                 :             :         TSVector dest, WordEntry *destptr,
     362                 :             :         int32 maxpos)
     363                 :             : {
     364                 :          10 :     uint16     *clen = &_POSVECPTR(dest, destptr)->npos;
     365                 :             :     int         i;
     366         [ +  - ]:          10 :     uint16      slen = POSDATALEN(src, srcptr),
     367                 :             :                 startlen;
     368                 :          10 :     WordEntryPos *spos = POSDATAPTR(src, srcptr),
     369                 :          10 :                *dpos = POSDATAPTR(dest, destptr);
     370                 :             : 
     371         [ -  + ]:          10 :     if (!destptr->haspos)
     372                 :           0 :         *clen = 0;
     373                 :             : 
     374                 :          10 :     startlen = *clen;
     375                 :          10 :     for (i = 0;
     376   [ +  +  +  - ]:          20 :          i < slen && *clen < MAXNUMPOS &&
     377   [ +  +  +  - ]:          10 :          (*clen == 0 || WEP_GETPOS(dpos[*clen - 1]) != MAXENTRYPOS - 1);
     378                 :          10 :          i++)
     379                 :             :     {
     380                 :          10 :         WEP_SETWEIGHT(dpos[*clen], WEP_GETWEIGHT(spos[i]));
     381                 :          10 :         WEP_SETPOS(dpos[*clen], LIMITPOS(WEP_GETPOS(spos[i]) + maxpos));
     382                 :          10 :         (*clen)++;
     383                 :             :     }
     384                 :             : 
     385         [ +  - ]:          10 :     if (*clen != startlen)
     386                 :          10 :         destptr->haspos = 1;
     387                 :          10 :     return *clen - startlen;
     388                 :             : }
     389                 :             : 
     390                 :             : /*
     391                 :             :  * Perform binary search of given lexeme in TSVector.
     392                 :             :  * Returns lexeme position in TSVector's entry array or -1 if lexeme wasn't
     393                 :             :  * found.
     394                 :             :  */
     395                 :             : static int
     396                 :         165 : tsvector_bsearch(const TSVectorData *tsv, char *lexeme, int lexeme_len)
     397                 :             : {
     398                 :         165 :     const WordEntry *arrin = ARRPTR(tsv);
     399                 :         165 :     int         StopLow = 0,
     400                 :         165 :                 StopHigh = tsv->size,
     401                 :             :                 StopMiddle,
     402                 :             :                 cmp;
     403                 :             : 
     404         [ +  + ]:         435 :     while (StopLow < StopHigh)
     405                 :             :     {
     406                 :         385 :         StopMiddle = (StopLow + StopHigh) / 2;
     407                 :             : 
     408                 :         385 :         cmp = tsCompareString(lexeme, lexeme_len,
     409                 :         385 :                               STRPTR(tsv) + arrin[StopMiddle].pos,
     410                 :         385 :                               arrin[StopMiddle].len,
     411                 :             :                               false);
     412                 :             : 
     413         [ +  + ]:         385 :         if (cmp < 0)
     414                 :         180 :             StopHigh = StopMiddle;
     415         [ +  + ]:         205 :         else if (cmp > 0)
     416                 :          90 :             StopLow = StopMiddle + 1;
     417                 :             :         else                    /* found it */
     418                 :         115 :             return StopMiddle;
     419                 :             :     }
     420                 :             : 
     421                 :          50 :     return -1;
     422                 :             : }
     423                 :             : 
     424                 :             : /*
     425                 :             :  * qsort comparator functions
     426                 :             :  */
     427                 :             : 
     428                 :             : static int
     429                 :          65 : compare_int(const void *va, const void *vb)
     430                 :             : {
     431                 :          65 :     int         a = *((const int *) va);
     432                 :          65 :     int         b = *((const int *) vb);
     433                 :             : 
     434                 :          65 :     return pg_cmp_s32(a, b);
     435                 :             : }
     436                 :             : 
     437                 :             : static int
     438                 :          85 : compare_text_lexemes(const void *va, const void *vb)
     439                 :             : {
     440                 :          85 :     Datum       a = *((const Datum *) va);
     441                 :          85 :     Datum       b = *((const Datum *) vb);
     442                 :          85 :     char       *alex = VARDATA_ANY(DatumGetPointer(a));
     443                 :          85 :     int         alex_len = VARSIZE_ANY_EXHDR(DatumGetPointer(a));
     444                 :          85 :     char       *blex = VARDATA_ANY(DatumGetPointer(b));
     445                 :          85 :     int         blex_len = VARSIZE_ANY_EXHDR(DatumGetPointer(b));
     446                 :             : 
     447                 :          85 :     return tsCompareString(alex, alex_len, blex, blex_len, false);
     448                 :             : }
     449                 :             : 
     450                 :             : /*
     451                 :             :  * Internal routine to delete lexemes from TSVector by array of offsets.
     452                 :             :  *
     453                 :             :  * int *indices_to_delete -- array of lexeme offsets to delete (modified here!)
     454                 :             :  * int indices_count -- size of that array
     455                 :             :  *
     456                 :             :  * Returns new TSVector without given lexemes along with their positions
     457                 :             :  * and weights.
     458                 :             :  */
     459                 :             : static TSVector
     460                 :          55 : tsvector_delete_by_indices(TSVector tsv, int *indices_to_delete,
     461                 :             :                            int indices_count)
     462                 :             : {
     463                 :             :     TSVector    tsout;
     464                 :          55 :     WordEntry  *arrin = ARRPTR(tsv),
     465                 :             :                *arrout;
     466                 :          55 :     char       *data = STRPTR(tsv),
     467                 :             :                *dataout;
     468                 :             :     int         i,              /* index in arrin */
     469                 :             :                 j,              /* index in arrout */
     470                 :             :                 k,              /* index in indices_to_delete */
     471                 :             :                 curoff;         /* index in dataout area */
     472                 :             : 
     473                 :             :     /*
     474                 :             :      * Sort the filter array to simplify membership checks below.  Also, get
     475                 :             :      * rid of any duplicate entries, so that we can assume that indices_count
     476                 :             :      * is exactly equal to the number of lexemes that will be removed.
     477                 :             :      */
     478         [ +  + ]:          55 :     if (indices_count > 1)
     479                 :             :     {
     480                 :          25 :         qsort(indices_to_delete, indices_count, sizeof(int), compare_int);
     481                 :          25 :         indices_count = qunique(indices_to_delete, indices_count, sizeof(int),
     482                 :             :                                 compare_int);
     483                 :             :     }
     484                 :             : 
     485                 :             :     /*
     486                 :             :      * Here we overestimate tsout size, since we don't know how much space is
     487                 :             :      * used by the deleted lexeme(s).  We will set exact size below.
     488                 :             :      */
     489                 :          55 :     tsout = (TSVector) palloc0(VARSIZE(tsv));
     490                 :             : 
     491                 :             :     /* This count must be correct because STRPTR(tsout) relies on it. */
     492                 :          55 :     tsout->size = tsv->size - indices_count;
     493                 :             : 
     494                 :             :     /*
     495                 :             :      * Copy tsv to tsout, skipping lexemes listed in indices_to_delete.
     496                 :             :      *
     497                 :             :      * Output can't be bigger than input, so no need for overflow checks.
     498                 :             :      */
     499                 :          55 :     arrout = ARRPTR(tsout);
     500                 :          55 :     dataout = STRPTR(tsout);
     501                 :          55 :     curoff = 0;
     502         [ +  + ]:         330 :     for (i = j = k = 0; i < tsv->size; i++)
     503                 :             :     {
     504                 :             :         /*
     505                 :             :          * If current i is present in indices_to_delete, skip this lexeme.
     506                 :             :          * Since indices_to_delete is already sorted, we only need to check
     507                 :             :          * the current (k'th) entry.
     508                 :             :          */
     509   [ +  +  +  + ]:         275 :         if (k < indices_count && i == indices_to_delete[k])
     510                 :             :         {
     511                 :          80 :             k++;
     512                 :          80 :             continue;
     513                 :             :         }
     514                 :             : 
     515                 :             :         /* Copy lexeme and its positions and weights */
     516                 :         195 :         memcpy(dataout + curoff, data + arrin[i].pos, arrin[i].len);
     517                 :         195 :         arrout[j].haspos = arrin[i].haspos;
     518                 :         195 :         arrout[j].len = arrin[i].len;
     519                 :         195 :         arrout[j].pos = curoff;
     520                 :         195 :         curoff += arrin[i].len;
     521         [ +  + ]:         195 :         if (arrin[i].haspos)
     522                 :             :         {
     523         [ +  - ]:         130 :             int         len = POSDATALEN(tsv, arrin + i) * sizeof(WordEntryPos)
     524                 :         130 :                 + sizeof(uint16);
     525                 :             : 
     526                 :         130 :             curoff = SHORTALIGN(curoff);
     527                 :         130 :             memcpy(dataout + curoff,
     528                 :         130 :                    STRPTR(tsv) + SHORTALIGN(arrin[i].pos + arrin[i].len),
     529                 :             :                    len);
     530                 :         130 :             curoff += len;
     531                 :             :         }
     532                 :             : 
     533                 :         195 :         j++;
     534                 :             :     }
     535                 :             : 
     536                 :             :     /*
     537                 :             :      * k should now be exactly equal to indices_count. If it isn't then the
     538                 :             :      * caller provided us with indices outside of [0, tsv->size) range and
     539                 :             :      * estimation of tsout's size is wrong.
     540                 :             :      */
     541                 :             :     Assert(k == indices_count);
     542                 :             : 
     543                 :          55 :     SET_VARSIZE(tsout, CALCDATASIZE(tsout->size, curoff));
     544                 :          55 :     return tsout;
     545                 :             : }
     546                 :             : 
     547                 :             : /*
     548                 :             :  * Delete given lexeme from tsvector.
     549                 :             :  * Implementation of user-level ts_delete(tsvector, text).
     550                 :             :  */
     551                 :             : Datum
     552                 :          30 : tsvector_delete_str(PG_FUNCTION_ARGS)
     553                 :             : {
     554                 :          30 :     TSVector    tsin = PG_GETARG_TSVECTOR(0),
     555                 :             :                 tsout;
     556                 :          30 :     text       *tlexeme = PG_GETARG_TEXT_PP(1);
     557                 :          30 :     char       *lexeme = VARDATA_ANY(tlexeme);
     558                 :          30 :     int         lexeme_len = VARSIZE_ANY_EXHDR(tlexeme),
     559                 :             :                 skip_index;
     560                 :             : 
     561         [ +  + ]:          30 :     if ((skip_index = tsvector_bsearch(tsin, lexeme, lexeme_len)) == -1)
     562                 :          10 :         PG_RETURN_POINTER(tsin);
     563                 :             : 
     564                 :          20 :     tsout = tsvector_delete_by_indices(tsin, &skip_index, 1);
     565                 :             : 
     566         [ -  + ]:          20 :     PG_FREE_IF_COPY(tsin, 0);
     567         [ -  + ]:          20 :     PG_FREE_IF_COPY(tlexeme, 1);
     568                 :          20 :     PG_RETURN_POINTER(tsout);
     569                 :             : }
     570                 :             : 
     571                 :             : /*
     572                 :             :  * Delete given array of lexemes from tsvector.
     573                 :             :  * Implementation of user-level ts_delete(tsvector, text[]).
     574                 :             :  */
     575                 :             : Datum
     576                 :          35 : tsvector_delete_arr(PG_FUNCTION_ARGS)
     577                 :             : {
     578                 :          35 :     TSVector    tsin = PG_GETARG_TSVECTOR(0),
     579                 :             :                 tsout;
     580                 :          35 :     ArrayType  *lexemes = PG_GETARG_ARRAYTYPE_P(1);
     581                 :             :     int         i,
     582                 :             :                 nlex,
     583                 :             :                 skip_count,
     584                 :             :                *skip_indices;
     585                 :             :     Datum      *dlexemes;
     586                 :             :     bool       *nulls;
     587                 :             : 
     588                 :          35 :     deconstruct_array_builtin(lexemes, TEXTOID, &dlexemes, &nulls, &nlex);
     589                 :             : 
     590                 :             :     /*
     591                 :             :      * In typical use case array of lexemes to delete is relatively small. So
     592                 :             :      * here we optimize things for that scenario: iterate through lexarr
     593                 :             :      * performing binary search of each lexeme from lexarr in tsvector.
     594                 :             :      */
     595                 :          35 :     skip_indices = palloc0(nlex * sizeof(int));
     596         [ +  + ]:         140 :     for (i = skip_count = 0; i < nlex; i++)
     597                 :             :     {
     598                 :             :         char       *lex;
     599                 :             :         int         lex_len,
     600                 :             :                     lex_pos;
     601                 :             : 
     602                 :             :         /* Ignore null array elements, they surely don't match */
     603         [ +  + ]:         105 :         if (nulls[i])
     604                 :           5 :             continue;
     605                 :             : 
     606                 :         100 :         lex = VARDATA(DatumGetPointer(dlexemes[i]));
     607                 :         100 :         lex_len = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
     608                 :         100 :         lex_pos = tsvector_bsearch(tsin, lex, lex_len);
     609                 :             : 
     610         [ +  + ]:         100 :         if (lex_pos >= 0)
     611                 :          65 :             skip_indices[skip_count++] = lex_pos;
     612                 :             :     }
     613                 :             : 
     614                 :          35 :     tsout = tsvector_delete_by_indices(tsin, skip_indices, skip_count);
     615                 :             : 
     616                 :          35 :     pfree(skip_indices);
     617         [ -  + ]:          35 :     PG_FREE_IF_COPY(tsin, 0);
     618         [ -  + ]:          35 :     PG_FREE_IF_COPY(lexemes, 1);
     619                 :             : 
     620                 :          35 :     PG_RETURN_POINTER(tsout);
     621                 :             : }
     622                 :             : 
     623                 :             : /*
     624                 :             :  * Expand tsvector as table with following columns:
     625                 :             :  *     lexeme: lexeme text
     626                 :             :  *     positions: integer array of lexeme positions
     627                 :             :  *     weights: char array of weights corresponding to positions
     628                 :             :  */
     629                 :             : Datum
     630                 :         120 : tsvector_unnest(PG_FUNCTION_ARGS)
     631                 :             : {
     632                 :             :     FuncCallContext *funcctx;
     633                 :             :     TSVector    tsin;
     634                 :             : 
     635         [ +  + ]:         120 :     if (SRF_IS_FIRSTCALL())
     636                 :             :     {
     637                 :             :         MemoryContext oldcontext;
     638                 :             :         TupleDesc   tupdesc;
     639                 :             : 
     640                 :          20 :         funcctx = SRF_FIRSTCALL_INIT();
     641                 :          20 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
     642                 :             : 
     643                 :          20 :         tupdesc = CreateTemplateTupleDesc(3);
     644                 :          20 :         TupleDescInitEntry(tupdesc, (AttrNumber) 1, "lexeme",
     645                 :             :                            TEXTOID, -1, 0);
     646                 :          20 :         TupleDescInitEntry(tupdesc, (AttrNumber) 2, "positions",
     647                 :             :                            INT2ARRAYOID, -1, 0);
     648                 :          20 :         TupleDescInitEntry(tupdesc, (AttrNumber) 3, "weights",
     649                 :             :                            TEXTARRAYOID, -1, 0);
     650         [ -  + ]:          20 :         if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     651         [ #  # ]:           0 :             elog(ERROR, "return type must be a row type");
     652                 :          20 :         TupleDescFinalize(tupdesc);
     653                 :          20 :         funcctx->tuple_desc = tupdesc;
     654                 :             : 
     655                 :          20 :         funcctx->user_fctx = PG_GETARG_TSVECTOR_COPY(0);
     656                 :             : 
     657                 :          20 :         MemoryContextSwitchTo(oldcontext);
     658                 :             :     }
     659                 :             : 
     660                 :         120 :     funcctx = SRF_PERCALL_SETUP();
     661                 :         120 :     tsin = (TSVector) funcctx->user_fctx;
     662                 :             : 
     663         [ +  + ]:         120 :     if (funcctx->call_cntr < tsin->size)
     664                 :             :     {
     665                 :         100 :         WordEntry  *arrin = ARRPTR(tsin);
     666                 :         100 :         char       *data = STRPTR(tsin);
     667                 :             :         HeapTuple   tuple;
     668                 :             :         int         j,
     669                 :         100 :                     i = funcctx->call_cntr;
     670                 :         100 :         bool        nulls[] = {false, false, false};
     671                 :             :         Datum       values[3];
     672                 :             : 
     673                 :         100 :         values[0] = PointerGetDatum(cstring_to_text_with_len(data + arrin[i].pos, arrin[i].len));
     674                 :             : 
     675         [ +  + ]:         100 :         if (arrin[i].haspos)
     676                 :             :         {
     677                 :             :             WordEntryPosVector *posv;
     678                 :             :             Datum      *positions;
     679                 :             :             Datum      *weights;
     680                 :             :             char        weight;
     681                 :             : 
     682                 :             :             /*
     683                 :             :              * Internally tsvector stores position and weight in the same
     684                 :             :              * uint16 (2 bits for weight, 14 for position). Here we extract
     685                 :             :              * that in two separate arrays.
     686                 :             :              */
     687                 :          60 :             posv = _POSVECPTR(tsin, arrin + i);
     688                 :          60 :             positions = palloc(posv->npos * sizeof(Datum));
     689                 :          60 :             weights = palloc(posv->npos * sizeof(Datum));
     690         [ +  + ]:         168 :             for (j = 0; j < posv->npos; j++)
     691                 :             :             {
     692                 :         108 :                 positions[j] = Int16GetDatum(WEP_GETPOS(posv->pos[j]));
     693                 :         108 :                 weight = 'D' - WEP_GETWEIGHT(posv->pos[j]);
     694                 :         108 :                 weights[j] = PointerGetDatum(cstring_to_text_with_len(&weight,
     695                 :             :                                                                       1));
     696                 :             :             }
     697                 :             : 
     698                 :          60 :             values[1] = PointerGetDatum(construct_array_builtin(positions, posv->npos, INT2OID));
     699                 :          60 :             values[2] = PointerGetDatum(construct_array_builtin(weights, posv->npos, TEXTOID));
     700                 :             :         }
     701                 :             :         else
     702                 :             :         {
     703                 :          40 :             nulls[1] = nulls[2] = true;
     704                 :             :         }
     705                 :             : 
     706                 :         100 :         tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
     707                 :         100 :         SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
     708                 :             :     }
     709                 :             :     else
     710                 :             :     {
     711                 :          20 :         SRF_RETURN_DONE(funcctx);
     712                 :             :     }
     713                 :             : }
     714                 :             : 
     715                 :             : /*
     716                 :             :  * Convert tsvector to array of lexemes.
     717                 :             :  */
     718                 :             : Datum
     719                 :          10 : tsvector_to_array(PG_FUNCTION_ARGS)
     720                 :             : {
     721                 :          10 :     TSVector    tsin = PG_GETARG_TSVECTOR(0);
     722                 :          10 :     WordEntry  *arrin = ARRPTR(tsin);
     723                 :             :     Datum      *elements;
     724                 :             :     int         i;
     725                 :             :     ArrayType  *array;
     726                 :             : 
     727                 :          10 :     elements = palloc_array(Datum, tsin->size);
     728                 :             : 
     729         [ +  + ]:          60 :     for (i = 0; i < tsin->size; i++)
     730                 :             :     {
     731                 :          50 :         elements[i] = PointerGetDatum(cstring_to_text_with_len(STRPTR(tsin) + arrin[i].pos,
     732                 :             :                                                                arrin[i].len));
     733                 :             :     }
     734                 :             : 
     735                 :          10 :     array = construct_array_builtin(elements, tsin->size, TEXTOID);
     736                 :             : 
     737                 :          10 :     pfree(elements);
     738         [ -  + ]:          10 :     PG_FREE_IF_COPY(tsin, 0);
     739                 :          10 :     PG_RETURN_POINTER(array);
     740                 :             : }
     741                 :             : 
     742                 :             : /*
     743                 :             :  * Build tsvector from array of lexemes.
     744                 :             :  */
     745                 :             : Datum
     746                 :          18 : array_to_tsvector(PG_FUNCTION_ARGS)
     747                 :             : {
     748                 :          18 :     ArrayType  *v = PG_GETARG_ARRAYTYPE_P(0);
     749                 :             :     TSVector    tsout;
     750                 :             :     Datum      *dlexemes;
     751                 :             :     WordEntry  *arrout;
     752                 :             :     bool       *nulls;
     753                 :             :     int         nitems,
     754                 :             :                 i,
     755                 :             :                 tslen,
     756                 :          18 :                 datalen = 0;
     757                 :             :     char       *cur;
     758                 :             : 
     759                 :          18 :     deconstruct_array_builtin(v, TEXTOID, &dlexemes, &nulls, &nitems);
     760                 :             : 
     761                 :             :     /*
     762                 :             :      * Reject nulls and zero-length or over-length strings (maybe we should
     763                 :             :      * just ignore them, instead?)
     764                 :             :      */
     765         [ +  + ]:          95 :     for (i = 0; i < nitems; i++)
     766                 :             :     {
     767                 :             :         int         toklen;
     768                 :             : 
     769         [ +  + ]:          85 :         if (nulls[i])
     770         [ +  - ]:           4 :             ereport(ERROR,
     771                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
     772                 :             :                      errmsg("lexeme array may not contain nulls")));
     773                 :             : 
     774                 :          81 :         toklen = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
     775         [ +  + ]:          81 :         if (toklen == 0)
     776         [ +  - ]:           4 :             ereport(ERROR,
     777                 :             :                     (errcode(ERRCODE_ZERO_LENGTH_CHARACTER_STRING),
     778                 :             :                      errmsg("lexeme array may not contain empty strings")));
     779         [ -  + ]:          77 :         if (toklen >= MAXSTRLEN)
     780         [ #  # ]:           0 :             ereport(ERROR,
     781                 :             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     782                 :             :                      errmsg("word is too long (%d bytes, max %d bytes)",
     783                 :             :                             toklen,
     784                 :             :                             MAXSTRLEN - 1)));
     785                 :             :     }
     786                 :             : 
     787                 :             :     /* Sort and de-dup, because this is required for a valid tsvector. */
     788         [ +  - ]:          10 :     if (nitems > 1)
     789                 :             :     {
     790                 :          10 :         qsort(dlexemes, nitems, sizeof(Datum), compare_text_lexemes);
     791                 :          10 :         nitems = qunique(dlexemes, nitems, sizeof(Datum),
     792                 :             :                          compare_text_lexemes);
     793                 :             :     }
     794                 :             : 
     795                 :             :     /* Calculate space needed for surviving lexemes. */
     796         [ +  + ]:          50 :     for (i = 0; i < nitems; i++)
     797                 :          40 :         datalen += VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
     798         [ -  + ]:          10 :     if (datalen > MAXSTRPOS)
     799         [ #  # ]:           0 :         ereport(ERROR,
     800                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     801                 :             :                  errmsg("string is too long for tsvector (%zu bytes, max %zu bytes)",
     802                 :             :                         (size_t) datalen, (size_t) MAXSTRPOS)));
     803                 :          10 :     tslen = CALCDATASIZE(nitems, datalen);
     804                 :             : 
     805                 :             :     /* Allocate and fill tsvector. */
     806                 :          10 :     tsout = (TSVector) palloc0(tslen);
     807                 :          10 :     SET_VARSIZE(tsout, tslen);
     808                 :          10 :     tsout->size = nitems;
     809                 :             : 
     810                 :          10 :     arrout = ARRPTR(tsout);
     811                 :          10 :     cur = STRPTR(tsout);
     812         [ +  + ]:          50 :     for (i = 0; i < nitems; i++)
     813                 :             :     {
     814                 :          40 :         char       *lex = VARDATA(DatumGetPointer(dlexemes[i]));
     815                 :          40 :         int         lex_len = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
     816                 :             : 
     817                 :          40 :         memcpy(cur, lex, lex_len);
     818                 :          40 :         arrout[i].haspos = 0;
     819                 :          40 :         arrout[i].len = lex_len;
     820                 :          40 :         arrout[i].pos = cur - STRPTR(tsout);
     821                 :          40 :         cur += lex_len;
     822                 :             :     }
     823                 :             : 
     824         [ -  + ]:          10 :     PG_FREE_IF_COPY(v, 0);
     825                 :          10 :     PG_RETURN_POINTER(tsout);
     826                 :             : }
     827                 :             : 
     828                 :             : /*
     829                 :             :  * ts_filter(): keep only lexemes with given weights in tsvector.
     830                 :             :  */
     831                 :             : Datum
     832                 :          14 : tsvector_filter(PG_FUNCTION_ARGS)
     833                 :             : {
     834                 :          14 :     TSVector    tsin = PG_GETARG_TSVECTOR(0),
     835                 :             :                 tsout;
     836                 :          14 :     ArrayType  *weights = PG_GETARG_ARRAYTYPE_P(1);
     837                 :          14 :     WordEntry  *arrin = ARRPTR(tsin),
     838                 :             :                *arrout;
     839                 :          14 :     char       *datain = STRPTR(tsin),
     840                 :             :                *dataout;
     841                 :             :     Datum      *dweights;
     842                 :             :     bool       *nulls;
     843                 :             :     int         nweights;
     844                 :             :     int         i,
     845                 :             :                 j;
     846                 :          14 :     int         cur_pos = 0;
     847                 :          14 :     char        mask = 0;
     848                 :             : 
     849                 :          14 :     deconstruct_array_builtin(weights, CHAROID, &dweights, &nulls, &nweights);
     850                 :             : 
     851         [ +  + ]:          32 :     for (i = 0; i < nweights; i++)
     852                 :             :     {
     853                 :             :         char        char_weight;
     854                 :             : 
     855         [ +  + ]:          22 :         if (nulls[i])
     856         [ +  - ]:           4 :             ereport(ERROR,
     857                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
     858                 :             :                      errmsg("weight array may not contain nulls")));
     859                 :             : 
     860                 :          18 :         char_weight = DatumGetChar(dweights[i]);
     861                 :          18 :         mask |= 1 << parse_weight(char_weight);
     862                 :             :     }
     863                 :             : 
     864                 :             :     /*
     865                 :             :      * The output tsvector might be smaller than the input, but it can't be
     866                 :             :      * bigger, so VARSIZE(tsin) is surely enough space.  Also, we don't need
     867                 :             :      * to worry about overflows below.
     868                 :             :      */
     869                 :          10 :     tsout = (TSVector) palloc0(VARSIZE(tsin));
     870                 :          10 :     tsout->size = tsin->size;
     871                 :          10 :     arrout = ARRPTR(tsout);
     872                 :             :     /* worst-case location of output's lexemes; we may need to adjust below */
     873                 :          10 :     dataout = STRPTR(tsout);
     874                 :             : 
     875         [ +  + ]:          90 :     for (i = j = 0; i < tsin->size; i++)
     876                 :             :     {
     877                 :             :         WordEntryPosVector *posvin,
     878                 :             :                    *posvout;
     879                 :          80 :         int         npos = 0;
     880                 :             :         int         k;
     881                 :             : 
     882         [ +  + ]:          80 :         if (!arrin[i].haspos)
     883                 :          25 :             continue;
     884                 :             : 
     885                 :          55 :         posvin = _POSVECPTR(tsin, arrin + i);
     886                 :          55 :         posvout = (WordEntryPosVector *)
     887                 :          55 :             (dataout + SHORTALIGN(cur_pos + arrin[i].len));
     888                 :             : 
     889         [ +  + ]:         110 :         for (k = 0; k < posvin->npos; k++)
     890                 :             :         {
     891         [ +  + ]:          55 :             if (mask & (1 << WEP_GETWEIGHT(posvin->pos[k])))
     892                 :          25 :                 posvout->pos[npos++] = posvin->pos[k];
     893                 :             :         }
     894                 :             : 
     895                 :             :         /* if no satisfactory positions found, skip lexeme */
     896         [ +  + ]:          55 :         if (!npos)
     897                 :          30 :             continue;
     898                 :             : 
     899                 :          25 :         arrout[j].haspos = true;
     900                 :          25 :         arrout[j].len = arrin[i].len;
     901                 :          25 :         arrout[j].pos = cur_pos;
     902                 :             : 
     903                 :          25 :         memcpy(dataout + cur_pos, datain + arrin[i].pos, arrin[i].len);
     904                 :          25 :         posvout->npos = npos;
     905                 :          25 :         cur_pos += SHORTALIGN(arrin[i].len);
     906         [ +  - ]:          25 :         cur_pos += POSDATALEN(tsout, arrout + j) * sizeof(WordEntryPos) +
     907                 :             :             sizeof(uint16);
     908                 :          25 :         j++;
     909                 :             :     }
     910                 :             : 
     911                 :          10 :     tsout->size = j;
     912         [ +  - ]:          10 :     if (dataout != STRPTR(tsout))
     913                 :          10 :         memmove(STRPTR(tsout), dataout, cur_pos);
     914                 :             : 
     915                 :          10 :     SET_VARSIZE(tsout, CALCDATASIZE(tsout->size, cur_pos));
     916                 :             : 
     917         [ -  + ]:          10 :     PG_FREE_IF_COPY(tsin, 0);
     918                 :          10 :     PG_RETURN_POINTER(tsout);
     919                 :             : }
     920                 :             : 
     921                 :             : Datum
     922                 :           9 : tsvector_concat(PG_FUNCTION_ARGS)
     923                 :             : {
     924                 :           9 :     TSVector    in1 = PG_GETARG_TSVECTOR(0);
     925                 :           9 :     TSVector    in2 = PG_GETARG_TSVECTOR(1);
     926                 :             :     TSVector    out;
     927                 :             :     WordEntry  *ptr;
     928                 :             :     WordEntry  *ptr1,
     929                 :             :                *ptr2;
     930                 :             :     WordEntryPos *p;
     931                 :           9 :     int         maxpos = 0,
     932                 :             :                 i,
     933                 :             :                 j,
     934                 :             :                 i1,
     935                 :             :                 i2,
     936                 :             :                 dataoff,
     937                 :             :                 output_bytes,
     938                 :             :                 output_size;
     939                 :             :     char       *data,
     940                 :             :                *data1,
     941                 :             :                *data2;
     942                 :             : 
     943                 :             :     /* Get max position in in1; we'll need this to offset in2's positions */
     944                 :           9 :     ptr = ARRPTR(in1);
     945                 :           9 :     i = in1->size;
     946         [ +  + ]:          23 :     while (i--)
     947                 :             :     {
     948   [ +  -  +  - ]:          14 :         if ((j = POSDATALEN(in1, ptr)) != 0)
     949                 :             :         {
     950                 :          14 :             p = POSDATAPTR(in1, ptr);
     951         [ +  + ]:          28 :             while (j--)
     952                 :             :             {
     953         [ +  + ]:          14 :                 if (WEP_GETPOS(*p) > maxpos)
     954                 :           9 :                     maxpos = WEP_GETPOS(*p);
     955                 :          14 :                 p++;
     956                 :             :             }
     957                 :             :         }
     958                 :          14 :         ptr++;
     959                 :             :     }
     960                 :             : 
     961                 :           9 :     ptr1 = ARRPTR(in1);
     962                 :           9 :     ptr2 = ARRPTR(in2);
     963                 :           9 :     data1 = STRPTR(in1);
     964                 :           9 :     data2 = STRPTR(in2);
     965                 :           9 :     i1 = in1->size;
     966                 :           9 :     i2 = in2->size;
     967                 :             : 
     968                 :             :     /*
     969                 :             :      * Conservative estimate of space needed.  We might need all the data in
     970                 :             :      * both inputs, and conceivably add a pad byte before position data for
     971                 :             :      * each item where there was none before.
     972                 :             :      *
     973                 :             :      * Note: since the MAXSTRPOS limit constrains each input tsvector to be
     974                 :             :      * considerably less than MaxAllocSize, we don't need to worry about
     975                 :             :      * integer overflow here, nor in the data-copying steps below.  We do need
     976                 :             :      * to enforce that the result meets the MAXSTRPOS limit, but we check that
     977                 :             :      * once at the end.
     978                 :             :      */
     979                 :           9 :     output_bytes = VARSIZE(in1) + VARSIZE(in2) + i1 + i2;
     980                 :             : 
     981                 :           9 :     out = (TSVector) palloc0(output_bytes);
     982                 :           9 :     SET_VARSIZE(out, output_bytes);
     983                 :             : 
     984                 :             :     /*
     985                 :             :      * We must make out->size valid so that STRPTR(out) is sensible.  We'll
     986                 :             :      * collapse out any unused space at the end.
     987                 :             :      */
     988                 :           9 :     out->size = in1->size + in2->size;
     989                 :             : 
     990                 :           9 :     ptr = ARRPTR(out);
     991                 :           9 :     data = STRPTR(out);
     992                 :           9 :     dataoff = 0;
     993   [ +  +  +  + ]:          23 :     while (i1 && i2)
     994                 :             :     {
     995                 :          14 :         int         cmp = compareEntry(data1, ptr1, data2, ptr2);
     996                 :             : 
     997         [ +  + ]:          14 :         if (cmp < 0)
     998                 :             :         {                       /* in1 first */
     999                 :           5 :             ptr->haspos = ptr1->haspos;
    1000                 :           5 :             ptr->len = ptr1->len;
    1001                 :           5 :             memcpy(data + dataoff, data1 + ptr1->pos, ptr1->len);
    1002                 :           5 :             ptr->pos = dataoff;
    1003                 :           5 :             dataoff += ptr1->len;
    1004         [ +  - ]:           5 :             if (ptr->haspos)
    1005                 :             :             {
    1006                 :           5 :                 dataoff = SHORTALIGN(dataoff);
    1007         [ +  - ]:           5 :                 memcpy(data + dataoff, _POSVECPTR(in1, ptr1), POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16));
    1008         [ +  - ]:           5 :                 dataoff += POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16);
    1009                 :             :             }
    1010                 :             : 
    1011                 :           5 :             ptr++;
    1012                 :           5 :             ptr1++;
    1013                 :           5 :             i1--;
    1014                 :             :         }
    1015         [ +  + ]:           9 :         else if (cmp > 0)
    1016                 :             :         {                       /* in2 first */
    1017                 :           4 :             ptr->haspos = ptr2->haspos;
    1018                 :           4 :             ptr->len = ptr2->len;
    1019                 :           4 :             memcpy(data + dataoff, data2 + ptr2->pos, ptr2->len);
    1020                 :           4 :             ptr->pos = dataoff;
    1021                 :           4 :             dataoff += ptr2->len;
    1022         [ -  + ]:           4 :             if (ptr->haspos)
    1023                 :             :             {
    1024                 :           0 :                 int         addlen = add_pos(in2, ptr2, out, ptr, maxpos);
    1025                 :             : 
    1026         [ #  # ]:           0 :                 if (addlen == 0)
    1027                 :           0 :                     ptr->haspos = 0;
    1028                 :             :                 else
    1029                 :             :                 {
    1030                 :           0 :                     dataoff = SHORTALIGN(dataoff);
    1031                 :           0 :                     dataoff += addlen * sizeof(WordEntryPos) + sizeof(uint16);
    1032                 :             :                 }
    1033                 :             :             }
    1034                 :             : 
    1035                 :           4 :             ptr++;
    1036                 :           4 :             ptr2++;
    1037                 :           4 :             i2--;
    1038                 :             :         }
    1039                 :             :         else
    1040                 :             :         {
    1041                 :           5 :             ptr->haspos = ptr1->haspos | ptr2->haspos;
    1042                 :           5 :             ptr->len = ptr1->len;
    1043                 :           5 :             memcpy(data + dataoff, data1 + ptr1->pos, ptr1->len);
    1044                 :           5 :             ptr->pos = dataoff;
    1045                 :           5 :             dataoff += ptr1->len;
    1046         [ +  - ]:           5 :             if (ptr->haspos)
    1047                 :             :             {
    1048         [ +  - ]:           5 :                 if (ptr1->haspos)
    1049                 :             :                 {
    1050                 :           5 :                     dataoff = SHORTALIGN(dataoff);
    1051         [ +  - ]:           5 :                     memcpy(data + dataoff, _POSVECPTR(in1, ptr1), POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16));
    1052         [ +  - ]:           5 :                     dataoff += POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16);
    1053         [ +  - ]:           5 :                     if (ptr2->haspos)
    1054                 :           5 :                         dataoff += add_pos(in2, ptr2, out, ptr, maxpos) * sizeof(WordEntryPos);
    1055                 :             :                 }
    1056                 :             :                 else            /* must have ptr2->haspos */
    1057                 :             :                 {
    1058                 :           0 :                     int         addlen = add_pos(in2, ptr2, out, ptr, maxpos);
    1059                 :             : 
    1060         [ #  # ]:           0 :                     if (addlen == 0)
    1061                 :           0 :                         ptr->haspos = 0;
    1062                 :             :                     else
    1063                 :             :                     {
    1064                 :           0 :                         dataoff = SHORTALIGN(dataoff);
    1065                 :           0 :                         dataoff += addlen * sizeof(WordEntryPos) + sizeof(uint16);
    1066                 :             :                     }
    1067                 :             :                 }
    1068                 :             :             }
    1069                 :             : 
    1070                 :           5 :             ptr++;
    1071                 :           5 :             ptr1++;
    1072                 :           5 :             ptr2++;
    1073                 :           5 :             i1--;
    1074                 :           5 :             i2--;
    1075                 :             :         }
    1076                 :             :     }
    1077                 :             : 
    1078         [ +  + ]:          13 :     while (i1)
    1079                 :             :     {
    1080                 :           4 :         ptr->haspos = ptr1->haspos;
    1081                 :           4 :         ptr->len = ptr1->len;
    1082                 :           4 :         memcpy(data + dataoff, data1 + ptr1->pos, ptr1->len);
    1083                 :           4 :         ptr->pos = dataoff;
    1084                 :           4 :         dataoff += ptr1->len;
    1085         [ +  - ]:           4 :         if (ptr->haspos)
    1086                 :             :         {
    1087                 :           4 :             dataoff = SHORTALIGN(dataoff);
    1088         [ +  - ]:           4 :             memcpy(data + dataoff, _POSVECPTR(in1, ptr1), POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16));
    1089         [ +  - ]:           4 :             dataoff += POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16);
    1090                 :             :         }
    1091                 :             : 
    1092                 :           4 :         ptr++;
    1093                 :           4 :         ptr1++;
    1094                 :           4 :         i1--;
    1095                 :             :     }
    1096                 :             : 
    1097         [ +  + ]:          14 :     while (i2)
    1098                 :             :     {
    1099                 :           5 :         ptr->haspos = ptr2->haspos;
    1100                 :           5 :         ptr->len = ptr2->len;
    1101                 :           5 :         memcpy(data + dataoff, data2 + ptr2->pos, ptr2->len);
    1102                 :           5 :         ptr->pos = dataoff;
    1103                 :           5 :         dataoff += ptr2->len;
    1104         [ +  - ]:           5 :         if (ptr->haspos)
    1105                 :             :         {
    1106                 :           5 :             int         addlen = add_pos(in2, ptr2, out, ptr, maxpos);
    1107                 :             : 
    1108         [ -  + ]:           5 :             if (addlen == 0)
    1109                 :           0 :                 ptr->haspos = 0;
    1110                 :             :             else
    1111                 :             :             {
    1112                 :           5 :                 dataoff = SHORTALIGN(dataoff);
    1113                 :           5 :                 dataoff += addlen * sizeof(WordEntryPos) + sizeof(uint16);
    1114                 :             :             }
    1115                 :             :         }
    1116                 :             : 
    1117                 :           5 :         ptr++;
    1118                 :           5 :         ptr2++;
    1119                 :           5 :         i2--;
    1120                 :             :     }
    1121                 :             : 
    1122                 :             :     /*
    1123                 :             :      * Instead of checking each offset individually, we check for overflow of
    1124                 :             :      * pos fields once at the end.
    1125                 :             :      */
    1126         [ -  + ]:           9 :     if (dataoff > MAXSTRPOS)
    1127         [ #  # ]:           0 :         ereport(ERROR,
    1128                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1129                 :             :                  errmsg("string is too long for tsvector (%zu bytes, max %zu bytes)",
    1130                 :             :                         (size_t) dataoff, (size_t) MAXSTRPOS)));
    1131                 :             : 
    1132                 :             :     /*
    1133                 :             :      * Adjust sizes (asserting that we didn't overrun the original estimates)
    1134                 :             :      * and collapse out any unused array entries.
    1135                 :             :      */
    1136                 :           9 :     output_size = ptr - ARRPTR(out);
    1137                 :             :     Assert(output_size <= out->size);
    1138                 :           9 :     out->size = output_size;
    1139         [ +  + ]:           9 :     if (data != STRPTR(out))
    1140                 :           5 :         memmove(STRPTR(out), data, dataoff);
    1141                 :           9 :     output_bytes = CALCDATASIZE(out->size, dataoff);
    1142                 :             :     Assert(output_bytes <= VARSIZE(out));
    1143                 :           9 :     SET_VARSIZE(out, output_bytes);
    1144                 :             : 
    1145         [ -  + ]:           9 :     PG_FREE_IF_COPY(in1, 0);
    1146         [ -  + ]:           9 :     PG_FREE_IF_COPY(in2, 1);
    1147                 :           9 :     PG_RETURN_POINTER(out);
    1148                 :             : }
    1149                 :             : 
    1150                 :             : /*
    1151                 :             :  * Compare two strings by tsvector rules.
    1152                 :             :  *
    1153                 :             :  * if prefix = true then it returns zero value iff b has prefix a
    1154                 :             :  */
    1155                 :             : int32
    1156                 :     4193040 : tsCompareString(char *a, int lena, char *b, int lenb, bool prefix)
    1157                 :             : {
    1158                 :             :     int         cmp;
    1159                 :             : 
    1160         [ +  + ]:     4193040 :     if (lena == 0)
    1161                 :             :     {
    1162         [ -  + ]:          30 :         if (prefix)
    1163                 :           0 :             cmp = 0;            /* empty string is prefix of anything */
    1164                 :             :         else
    1165         [ +  - ]:          30 :             cmp = (lenb > 0) ? -1 : 0;
    1166                 :             :     }
    1167         [ -  + ]:     4193010 :     else if (lenb == 0)
    1168                 :             :     {
    1169                 :           0 :         cmp = (lena > 0) ? 1 : 0;
    1170                 :             :     }
    1171                 :             :     else
    1172                 :             :     {
    1173                 :     4193010 :         cmp = memcmp(a, b, Min((unsigned int) lena, (unsigned int) lenb));
    1174                 :             : 
    1175         [ +  + ]:     4193010 :         if (prefix)
    1176                 :             :         {
    1177   [ +  +  -  + ]:       11021 :             if (cmp == 0 && lena > lenb)
    1178                 :           0 :                 cmp = 1;        /* a is longer, so not a prefix of b */
    1179                 :             :         }
    1180   [ +  +  +  + ]:     4181989 :         else if (cmp == 0 && lena != lenb)
    1181                 :             :         {
    1182         [ +  + ]:       21676 :             cmp = (lena < lenb) ? -1 : 1;
    1183                 :             :         }
    1184                 :             :     }
    1185                 :             : 
    1186                 :     4193040 :     return cmp;
    1187                 :             : }
    1188                 :             : 
    1189                 :             : /*
    1190                 :             :  * Check weight info or/and fill 'data' with the required positions
    1191                 :             :  */
    1192                 :             : static TSTernaryValue
    1193                 :       45576 : checkclass_str(CHKVAL *chkval, WordEntry *entry, QueryOperand *val,
    1194                 :             :                ExecPhraseData *data)
    1195                 :             : {
    1196                 :       45576 :     TSTernaryValue result = TS_NO;
    1197                 :             : 
    1198                 :             :     Assert(data == NULL || data->npos == 0);
    1199                 :             : 
    1200         [ +  + ]:       45576 :     if (entry->haspos)
    1201                 :             :     {
    1202                 :             :         WordEntryPosVector *posvec;
    1203                 :             : 
    1204                 :             :         /*
    1205                 :             :          * We can't use the _POSVECPTR macro here because the pointer to the
    1206                 :             :          * tsvector's lexeme storage is already contained in chkval->values.
    1207                 :             :          */
    1208                 :        3160 :         posvec = (WordEntryPosVector *)
    1209                 :        3160 :             (chkval->values + SHORTALIGN(entry->pos + entry->len));
    1210                 :             : 
    1211   [ +  +  +  + ]:        3160 :         if (val->weight && data)
    1212                 :          40 :         {
    1213                 :          40 :             WordEntryPos *posvec_iter = posvec->pos;
    1214                 :             :             WordEntryPos *dptr;
    1215                 :             : 
    1216                 :             :             /*
    1217                 :             :              * Filter position information by weights
    1218                 :             :              */
    1219                 :          40 :             dptr = data->pos = palloc_array(WordEntryPos, posvec->npos);
    1220                 :          40 :             data->allocated = true;
    1221                 :             : 
    1222                 :             :             /* Is there a position with a matching weight? */
    1223         [ +  + ]:          80 :             while (posvec_iter < posvec->pos + posvec->npos)
    1224                 :             :             {
    1225                 :             :                 /* If true, append this position to the data->pos */
    1226         [ +  + ]:          40 :                 if (val->weight & (1 << WEP_GETWEIGHT(*posvec_iter)))
    1227                 :             :                 {
    1228                 :          20 :                     *dptr = WEP_GETPOS(*posvec_iter);
    1229                 :          20 :                     dptr++;
    1230                 :             :                 }
    1231                 :             : 
    1232                 :          40 :                 posvec_iter++;
    1233                 :             :             }
    1234                 :             : 
    1235                 :          40 :             data->npos = dptr - data->pos;
    1236                 :             : 
    1237         [ +  + ]:          40 :             if (data->npos > 0)
    1238                 :          20 :                 result = TS_YES;
    1239                 :             :             else
    1240                 :             :             {
    1241                 :          20 :                 pfree(data->pos);
    1242                 :          20 :                 data->pos = NULL;
    1243                 :          20 :                 data->allocated = false;
    1244                 :             :             }
    1245                 :             :         }
    1246         [ +  + ]:        3120 :         else if (val->weight)
    1247                 :             :         {
    1248                 :         332 :             WordEntryPos *posvec_iter = posvec->pos;
    1249                 :             : 
    1250                 :             :             /* Is there a position with a matching weight? */
    1251         [ +  + ]:         503 :             while (posvec_iter < posvec->pos + posvec->npos)
    1252                 :             :             {
    1253         [ +  + ]:         372 :                 if (val->weight & (1 << WEP_GETWEIGHT(*posvec_iter)))
    1254                 :             :                 {
    1255                 :         201 :                     result = TS_YES;
    1256                 :         201 :                     break;      /* no need to go further */
    1257                 :             :                 }
    1258                 :             : 
    1259                 :         171 :                 posvec_iter++;
    1260                 :             :             }
    1261                 :             :         }
    1262         [ +  + ]:        2788 :         else if (data)
    1263                 :             :         {
    1264                 :        1645 :             data->npos = posvec->npos;
    1265                 :        1645 :             data->pos = posvec->pos;
    1266                 :        1645 :             data->allocated = false;
    1267                 :        1645 :             result = TS_YES;
    1268                 :             :         }
    1269                 :             :         else
    1270                 :             :         {
    1271                 :             :             /* simplest case: no weight check, positions not needed */
    1272                 :        1143 :             result = TS_YES;
    1273                 :             :         }
    1274                 :             :     }
    1275                 :             :     else
    1276                 :             :     {
    1277                 :             :         /*
    1278                 :             :          * Position info is lacking, so if the caller requires it, we can only
    1279                 :             :          * say that maybe there is a match.
    1280                 :             :          *
    1281                 :             :          * Notice, however, that we *don't* check val->weight here.
    1282                 :             :          * Historically, stripped tsvectors are considered to match queries
    1283                 :             :          * whether or not the query has a weight restriction; that's a little
    1284                 :             :          * dubious but we'll preserve the behavior.
    1285                 :             :          */
    1286         [ +  + ]:       42416 :         if (data)
    1287                 :       15385 :             result = TS_MAYBE;
    1288                 :             :         else
    1289                 :       27031 :             result = TS_YES;
    1290                 :             :     }
    1291                 :             : 
    1292                 :       45576 :     return result;
    1293                 :             : }
    1294                 :             : 
    1295                 :             : /*
    1296                 :             :  * TS_execute callback for matching a tsquery operand to plain tsvector data
    1297                 :             :  */
    1298                 :             : static TSTernaryValue
    1299                 :      189554 : checkcondition_str(void *checkval, QueryOperand *val, ExecPhraseData *data)
    1300                 :             : {
    1301                 :      189554 :     CHKVAL     *chkval = (CHKVAL *) checkval;
    1302                 :      189554 :     WordEntry  *StopLow = chkval->arrb;
    1303                 :      189554 :     WordEntry  *StopHigh = chkval->arre;
    1304                 :      189554 :     WordEntry  *StopMiddle = StopHigh;
    1305                 :      189554 :     TSTernaryValue res = TS_NO;
    1306                 :             : 
    1307                 :             :     /* Loop invariant: StopLow <= val < StopHigh */
    1308         [ +  + ]:     1191598 :     while (StopLow < StopHigh)
    1309                 :             :     {
    1310                 :             :         int         difference;
    1311                 :             : 
    1312                 :     1037564 :         StopMiddle = StopLow + (StopHigh - StopLow) / 2;
    1313                 :     1037564 :         difference = tsCompareString(chkval->operand + val->distance,
    1314                 :     1037564 :                                      val->length,
    1315                 :     1037564 :                                      chkval->values + StopMiddle->pos,
    1316                 :     1037564 :                                      StopMiddle->len,
    1317                 :             :                                      false);
    1318                 :             : 
    1319         [ +  + ]:     1037564 :         if (difference == 0)
    1320                 :             :         {
    1321                 :             :             /* Check weight info & fill 'data' with positions */
    1322                 :       35520 :             res = checkclass_str(chkval, StopMiddle, val, data);
    1323                 :       35520 :             break;
    1324                 :             :         }
    1325         [ +  + ]:     1002044 :         else if (difference > 0)
    1326                 :      565083 :             StopLow = StopMiddle + 1;
    1327                 :             :         else
    1328                 :      436961 :             StopHigh = StopMiddle;
    1329                 :             :     }
    1330                 :             : 
    1331                 :             :     /*
    1332                 :             :      * If it's a prefix search, we should also consider lexemes that the
    1333                 :             :      * search term is a prefix of (which will necessarily immediately follow
    1334                 :             :      * the place we found in the above loop).  But we can skip them if there
    1335                 :             :      * was a definite match on the exact term AND the caller doesn't need
    1336                 :             :      * position info.
    1337                 :             :      */
    1338   [ +  +  +  +  :      189554 :     if (val->prefix && (res != TS_YES || data))
                   +  - ]
    1339                 :             :     {
    1340                 :       11040 :         WordEntryPos *allpos = NULL;
    1341                 :       11040 :         int         npos = 0,
    1342                 :       11040 :                     totalpos = 0;
    1343                 :             : 
    1344                 :             :         /* adjust start position for corner case */
    1345         [ +  + ]:       11040 :         if (StopLow >= StopHigh)
    1346                 :       11030 :             StopMiddle = StopHigh;
    1347                 :             : 
    1348                 :             :         /* we don't try to re-use any data from the initial match */
    1349         [ +  + ]:       11040 :         if (data)
    1350                 :             :         {
    1351         [ -  + ]:          30 :             if (data->allocated)
    1352                 :           0 :                 pfree(data->pos);
    1353                 :          30 :             data->pos = NULL;
    1354                 :          30 :             data->allocated = false;
    1355                 :          30 :             data->npos = 0;
    1356                 :             :         }
    1357                 :       11040 :         res = TS_NO;
    1358                 :             : 
    1359         [ -  + ]:       21011 :         while ((res != TS_YES || data) &&
    1360   [ +  +  +  +  :       31751 :                StopMiddle < chkval->arre &&
                   +  + ]
    1361                 :       10655 :                tsCompareString(chkval->operand + val->distance,
    1362                 :       10655 :                                val->length,
    1363                 :       10655 :                                chkval->values + StopMiddle->pos,
    1364                 :       10655 :                                StopMiddle->len,
    1365                 :             :                                true) == 0)
    1366                 :             :         {
    1367                 :             :             TSTernaryValue subres;
    1368                 :             : 
    1369                 :       10056 :             subres = checkclass_str(chkval, StopMiddle, val, data);
    1370                 :             : 
    1371         [ +  + ]:       10056 :             if (subres != TS_NO)
    1372                 :             :             {
    1373         [ +  + ]:       10006 :                 if (data)
    1374                 :             :                 {
    1375                 :             :                     /*
    1376                 :             :                      * We need to join position information
    1377                 :             :                      */
    1378         [ -  + ]:          35 :                     if (subres == TS_MAYBE)
    1379                 :             :                     {
    1380                 :             :                         /*
    1381                 :             :                          * No position info for this match, so we must report
    1382                 :             :                          * MAYBE overall.
    1383                 :             :                          */
    1384                 :           0 :                         res = TS_MAYBE;
    1385                 :             :                         /* forget any previous positions */
    1386                 :           0 :                         npos = 0;
    1387                 :             :                         /* don't leak storage */
    1388         [ #  # ]:           0 :                         if (allpos)
    1389                 :           0 :                             pfree(allpos);
    1390                 :           0 :                         break;
    1391                 :             :                     }
    1392                 :             : 
    1393         [ +  + ]:          65 :                     while (npos + data->npos > totalpos)
    1394                 :             :                     {
    1395         [ +  - ]:          30 :                         if (totalpos == 0)
    1396                 :             :                         {
    1397                 :          30 :                             totalpos = 256;
    1398                 :          30 :                             allpos = palloc_array(WordEntryPos, totalpos);
    1399                 :             :                         }
    1400                 :             :                         else
    1401                 :             :                         {
    1402                 :           0 :                             totalpos *= 2;
    1403                 :           0 :                             allpos = repalloc_array(allpos, WordEntryPos, totalpos);
    1404                 :             :                         }
    1405                 :             :                     }
    1406                 :             : 
    1407                 :          35 :                     memcpy(allpos + npos, data->pos, sizeof(WordEntryPos) * data->npos);
    1408                 :          35 :                     npos += data->npos;
    1409                 :             : 
    1410                 :             :                     /* don't leak storage from individual matches */
    1411         [ +  + ]:          35 :                     if (data->allocated)
    1412                 :          20 :                         pfree(data->pos);
    1413                 :          35 :                     data->pos = NULL;
    1414                 :          35 :                     data->allocated = false;
    1415                 :             :                     /* it's important to reset data->npos before next loop */
    1416                 :          35 :                     data->npos = 0;
    1417                 :             :                 }
    1418                 :             :                 else
    1419                 :             :                 {
    1420                 :             :                     /* Don't need positions, just handle YES/MAYBE */
    1421   [ -  +  -  - ]:        9971 :                     if (subres == TS_YES || res == TS_NO)
    1422                 :        9971 :                         res = subres;
    1423                 :             :                 }
    1424                 :             :             }
    1425                 :             : 
    1426                 :       10056 :             StopMiddle++;
    1427                 :             :         }
    1428                 :             : 
    1429   [ +  +  +  - ]:       11040 :         if (data && npos > 0)
    1430                 :             :         {
    1431                 :             :             /* Sort and make unique array of found positions */
    1432                 :          30 :             data->pos = allpos;
    1433                 :          30 :             qsort(data->pos, npos, sizeof(WordEntryPos), compareWordEntryPos);
    1434                 :          30 :             data->npos = qunique(data->pos, npos, sizeof(WordEntryPos),
    1435                 :             :                                  compareWordEntryPos);
    1436                 :          30 :             data->allocated = true;
    1437                 :          30 :             res = TS_YES;
    1438                 :             :         }
    1439                 :             :     }
    1440                 :             : 
    1441                 :      189554 :     return res;
    1442                 :             : }
    1443                 :             : 
    1444                 :             : /*
    1445                 :             :  * Compute output position list for a tsquery operator in phrase mode.
    1446                 :             :  *
    1447                 :             :  * Merge the position lists in Ldata and Rdata as specified by "emit",
    1448                 :             :  * returning the result list into *data.  The input position lists must be
    1449                 :             :  * sorted and unique, and the output will be as well.
    1450                 :             :  *
    1451                 :             :  * data: pointer to initially-all-zeroes output struct, or NULL
    1452                 :             :  * Ldata, Rdata: input position lists
    1453                 :             :  * emit: bitmask of TSPO_XXX flags
    1454                 :             :  * Loffset: offset to be added to Ldata positions before comparing/outputting
    1455                 :             :  * Roffset: offset to be added to Rdata positions before comparing/outputting
    1456                 :             :  * max_npos: maximum possible required size of output position array
    1457                 :             :  *
    1458                 :             :  * Loffset and Roffset should not be negative, else we risk trying to output
    1459                 :             :  * negative positions, which won't fit into WordEntryPos.
    1460                 :             :  *
    1461                 :             :  * The result is boolean (TS_YES or TS_NO), but for the caller's convenience
    1462                 :             :  * we return it as TSTernaryValue.
    1463                 :             :  *
    1464                 :             :  * Returns TS_YES if any positions were emitted to *data; or if data is NULL,
    1465                 :             :  * returns TS_YES if any positions would have been emitted.
    1466                 :             :  */
    1467                 :             : #define TSPO_L_ONLY     0x01    /* emit positions appearing only in L */
    1468                 :             : #define TSPO_R_ONLY     0x02    /* emit positions appearing only in R */
    1469                 :             : #define TSPO_BOTH       0x04    /* emit positions appearing in both L&R */
    1470                 :             : 
    1471                 :             : static TSTernaryValue
    1472                 :       20114 : TS_phrase_output(ExecPhraseData *data,
    1473                 :             :                  ExecPhraseData *Ldata,
    1474                 :             :                  ExecPhraseData *Rdata,
    1475                 :             :                  int emit,
    1476                 :             :                  int Loffset,
    1477                 :             :                  int Roffset,
    1478                 :             :                  int max_npos)
    1479                 :             : {
    1480                 :             :     int         Lindex,
    1481                 :             :                 Rindex;
    1482                 :             : 
    1483                 :             :     /* Loop until both inputs are exhausted */
    1484                 :       20114 :     Lindex = Rindex = 0;
    1485   [ +  +  +  + ]:       20906 :     while (Lindex < Ldata->npos || Rindex < Rdata->npos)
    1486                 :             :     {
    1487                 :             :         int         Lpos,
    1488                 :             :                     Rpos;
    1489                 :        1748 :         int         output_pos = 0;
    1490                 :             : 
    1491                 :             :         /*
    1492                 :             :          * Fetch current values to compare.  WEP_GETPOS() is needed because
    1493                 :             :          * ExecPhraseData->data can point to a tsvector's WordEntryPosVector.
    1494                 :             :          */
    1495         [ +  + ]:        1748 :         if (Lindex < Ldata->npos)
    1496                 :        1288 :             Lpos = WEP_GETPOS(Ldata->pos[Lindex]) + Loffset;
    1497                 :             :         else
    1498                 :             :         {
    1499                 :             :             /* L array exhausted, so we're done if R_ONLY isn't set */
    1500         [ +  + ]:         460 :             if (!(emit & TSPO_R_ONLY))
    1501                 :         113 :                 break;
    1502                 :         347 :             Lpos = INT_MAX;
    1503                 :             :         }
    1504         [ +  + ]:        1635 :         if (Rindex < Rdata->npos)
    1505                 :        1445 :             Rpos = WEP_GETPOS(Rdata->pos[Rindex]) + Roffset;
    1506                 :             :         else
    1507                 :             :         {
    1508                 :             :             /* R array exhausted, so we're done if L_ONLY isn't set */
    1509         [ +  + ]:         190 :             if (!(emit & TSPO_L_ONLY))
    1510                 :         122 :                 break;
    1511                 :          68 :             Rpos = INT_MAX;
    1512                 :             :         }
    1513                 :             : 
    1514                 :             :         /* Merge-join the two input lists */
    1515         [ +  + ]:        1513 :         if (Lpos < Rpos)
    1516                 :             :         {
    1517                 :             :             /* Lpos is not matched in Rdata, should we output it? */
    1518         [ +  + ]:         365 :             if (emit & TSPO_L_ONLY)
    1519                 :         116 :                 output_pos = Lpos;
    1520                 :         365 :             Lindex++;
    1521                 :             :         }
    1522         [ +  + ]:        1148 :         else if (Lpos == Rpos)
    1523                 :             :         {
    1524                 :             :             /* Lpos and Rpos match ... should we output it? */
    1525         [ +  + ]:         621 :             if (emit & TSPO_BOTH)
    1526                 :         553 :                 output_pos = Rpos;
    1527                 :         621 :             Lindex++;
    1528                 :         621 :             Rindex++;
    1529                 :             :         }
    1530                 :             :         else                    /* Lpos > Rpos */
    1531                 :             :         {
    1532                 :             :             /* Rpos is not matched in Ldata, should we output it? */
    1533         [ +  + ]:         527 :             if (emit & TSPO_R_ONLY)
    1534                 :         376 :                 output_pos = Rpos;
    1535                 :         527 :             Rindex++;
    1536                 :             :         }
    1537                 :             : 
    1538         [ +  + ]:        1513 :         if (output_pos > 0)
    1539                 :             :         {
    1540         [ +  + ]:        1045 :             if (data)
    1541                 :             :             {
    1542                 :             :                 /* Store position, first allocating output array if needed */
    1543         [ +  + ]:         324 :                 if (data->pos == NULL)
    1544                 :             :                 {
    1545                 :         261 :                     data->pos = (WordEntryPos *)
    1546                 :         261 :                         palloc(max_npos * sizeof(WordEntryPos));
    1547                 :         261 :                     data->allocated = true;
    1548                 :             :                 }
    1549                 :         324 :                 data->pos[data->npos++] = output_pos;
    1550                 :             :             }
    1551                 :             :             else
    1552                 :             :             {
    1553                 :             :                 /*
    1554                 :             :                  * Exact positions not needed, so return TS_YES as soon as we
    1555                 :             :                  * know there is at least one.
    1556                 :             :                  */
    1557                 :         721 :                 return TS_YES;
    1558                 :             :             }
    1559                 :             :         }
    1560                 :             :     }
    1561                 :             : 
    1562   [ +  +  +  + ]:       19393 :     if (data && data->npos > 0)
    1563                 :             :     {
    1564                 :             :         /* Let's assert we didn't overrun the array */
    1565                 :             :         Assert(data->npos <= max_npos);
    1566                 :         261 :         return TS_YES;
    1567                 :             :     }
    1568                 :       19132 :     return TS_NO;
    1569                 :             : }
    1570                 :             : 
    1571                 :             : /*
    1572                 :             :  * Execute tsquery at or below an OP_PHRASE operator.
    1573                 :             :  *
    1574                 :             :  * This handles tsquery execution at recursion levels where we need to care
    1575                 :             :  * about match locations.
    1576                 :             :  *
    1577                 :             :  * In addition to the same arguments used for TS_execute, the caller may pass
    1578                 :             :  * a preinitialized-to-zeroes ExecPhraseData struct, to be filled with lexeme
    1579                 :             :  * match position info on success.  data == NULL if no position data need be
    1580                 :             :  * returned.
    1581                 :             :  * Note: the function assumes data != NULL for operators other than OP_PHRASE.
    1582                 :             :  * This is OK because an outside call always starts from an OP_PHRASE node,
    1583                 :             :  * and all internal recursion cases pass data != NULL.
    1584                 :             :  *
    1585                 :             :  * The detailed semantics of the match data, given that the function returned
    1586                 :             :  * TS_YES (successful match), are:
    1587                 :             :  *
    1588                 :             :  * npos > 0, negate = false:
    1589                 :             :  *   query is matched at specified position(s) (and only those positions)
    1590                 :             :  * npos > 0, negate = true:
    1591                 :             :  *   query is matched at all positions *except* specified position(s)
    1592                 :             :  * npos = 0, negate = true:
    1593                 :             :  *   query is matched at all positions
    1594                 :             :  * npos = 0, negate = false:
    1595                 :             :  *   disallowed (this should result in TS_NO or TS_MAYBE, as appropriate)
    1596                 :             :  *
    1597                 :             :  * Successful matches also return a "width" value which is the match width in
    1598                 :             :  * lexemes, less one.  Hence, "width" is zero for simple one-lexeme matches,
    1599                 :             :  * and is the sum of the phrase operator distances for phrase matches.  Note
    1600                 :             :  * that when width > 0, the listed positions represent the ends of matches not
    1601                 :             :  * the starts.  (This unintuitive rule is needed to avoid possibly generating
    1602                 :             :  * negative positions, which wouldn't fit into the WordEntryPos arrays.)
    1603                 :             :  *
    1604                 :             :  * If the TSExecuteCallback function reports that an operand is present
    1605                 :             :  * but fails to provide position(s) for it, we will return TS_MAYBE when
    1606                 :             :  * it is possible but not certain that the query is matched.
    1607                 :             :  *
    1608                 :             :  * When the function returns TS_NO or TS_MAYBE, it must return npos = 0,
    1609                 :             :  * negate = false (which is the state initialized by the caller); but the
    1610                 :             :  * "width" output in such cases is undefined.
    1611                 :             :  */
    1612                 :             : static TSTernaryValue
    1613                 :      467742 : TS_phrase_execute(QueryItem *curitem, void *arg, uint32 flags,
    1614                 :             :                   TSExecuteCallback chkcond,
    1615                 :             :                   ExecPhraseData *data)
    1616                 :             : {
    1617                 :             :     ExecPhraseData Ldata,
    1618                 :             :                 Rdata;
    1619                 :             :     TSTernaryValue lmatch,
    1620                 :             :                 rmatch;
    1621                 :             :     int         Loffset,
    1622                 :             :                 Roffset,
    1623                 :             :                 maxwidth;
    1624                 :             : 
    1625                 :             :     /* since this function recurses, it could be driven to stack overflow */
    1626                 :      467742 :     check_stack_depth();
    1627                 :             : 
    1628                 :             :     /* ... and let's check for query cancel while we're at it */
    1629         [ -  + ]:      467742 :     CHECK_FOR_INTERRUPTS();
    1630                 :             : 
    1631         [ +  + ]:      467742 :     if (curitem->type == QI_VAL)
    1632                 :      230116 :         return chkcond(arg, (QueryOperand *) curitem, data);
    1633                 :             : 
    1634   [ +  +  +  - ]:      237626 :     switch (curitem->qoperator.oper)
    1635                 :             :     {
    1636                 :       80466 :         case OP_NOT:
    1637                 :             : 
    1638                 :             :             /*
    1639                 :             :              * We need not touch data->width, since a NOT operation does not
    1640                 :             :              * change the match width.
    1641                 :             :              */
    1642         [ -  + ]:       80466 :             if (flags & TS_EXEC_SKIP_NOT)
    1643                 :             :             {
    1644                 :             :                 /* with SKIP_NOT, report NOT as "match everywhere" */
    1645                 :             :                 Assert(data->npos == 0 && !data->negate);
    1646                 :           0 :                 data->negate = true;
    1647                 :           0 :                 return TS_YES;
    1648                 :             :             }
    1649   [ +  +  +  - ]:       80466 :             switch (TS_phrase_execute(curitem + 1, arg, flags, chkcond, data))
    1650                 :             :             {
    1651                 :       70320 :                 case TS_NO:
    1652                 :             :                     /* change "match nowhere" to "match everywhere" */
    1653                 :             :                     Assert(data->npos == 0 && !data->negate);
    1654                 :       70320 :                     data->negate = true;
    1655                 :       70320 :                     return TS_YES;
    1656                 :         273 :                 case TS_YES:
    1657         [ +  + ]:         273 :                     if (data->npos > 0)
    1658                 :             :                     {
    1659                 :             :                         /* we have some positions, invert negate flag */
    1660                 :         268 :                         data->negate = !data->negate;
    1661                 :         268 :                         return TS_YES;
    1662                 :             :                     }
    1663         [ +  - ]:           5 :                     else if (data->negate)
    1664                 :             :                     {
    1665                 :             :                         /* change "match everywhere" to "match nowhere" */
    1666                 :           5 :                         data->negate = false;
    1667                 :           5 :                         return TS_NO;
    1668                 :             :                     }
    1669                 :             :                     /* Should not get here if result was TS_YES */
    1670                 :             :                     Assert(false);
    1671                 :           0 :                     break;
    1672                 :        9873 :                 case TS_MAYBE:
    1673                 :             :                     /* match positions are, and remain, uncertain */
    1674                 :        9873 :                     return TS_MAYBE;
    1675                 :             :             }
    1676                 :           0 :             break;
    1677                 :             : 
    1678                 :      157034 :         case OP_PHRASE:
    1679                 :             :         case OP_AND:
    1680                 :      157034 :             memset(&Ldata, 0, sizeof(Ldata));
    1681                 :      157034 :             memset(&Rdata, 0, sizeof(Rdata));
    1682                 :             : 
    1683                 :      157034 :             lmatch = TS_phrase_execute(curitem + curitem->qoperator.left,
    1684                 :             :                                        arg, flags, chkcond, &Ldata);
    1685         [ +  + ]:      157034 :             if (lmatch == TS_NO)
    1686                 :       83868 :                 return TS_NO;
    1687                 :             : 
    1688                 :       73166 :             rmatch = TS_phrase_execute(curitem + 1,
    1689                 :             :                                        arg, flags, chkcond, &Rdata);
    1690         [ +  + ]:       73166 :             if (rmatch == TS_NO)
    1691                 :       36005 :                 return TS_NO;
    1692                 :             : 
    1693                 :             :             /*
    1694                 :             :              * If either operand has no position information, then we can't
    1695                 :             :              * return reliable position data, only a MAYBE result.
    1696                 :             :              */
    1697   [ +  +  +  + ]:       37161 :             if (lmatch == TS_MAYBE || rmatch == TS_MAYBE)
    1698                 :       17173 :                 return TS_MAYBE;
    1699                 :             : 
    1700         [ +  + ]:       19988 :             if (curitem->qoperator.oper == OP_PHRASE)
    1701                 :             :             {
    1702                 :             :                 /*
    1703                 :             :                  * Compute Loffset and Roffset suitable for phrase match, and
    1704                 :             :                  * compute overall width of whole phrase match.
    1705                 :             :                  */
    1706                 :       19983 :                 Loffset = curitem->qoperator.distance + Rdata.width;
    1707                 :       19983 :                 Roffset = 0;
    1708         [ +  + ]:       19983 :                 if (data)
    1709                 :         155 :                     data->width = curitem->qoperator.distance +
    1710                 :         155 :                         Ldata.width + Rdata.width;
    1711                 :             :             }
    1712                 :             :             else
    1713                 :             :             {
    1714                 :             :                 /*
    1715                 :             :                  * For OP_AND, set output width and alignment like OP_OR (see
    1716                 :             :                  * comment below)
    1717                 :             :                  */
    1718                 :           5 :                 maxwidth = Max(Ldata.width, Rdata.width);
    1719                 :           5 :                 Loffset = maxwidth - Ldata.width;
    1720                 :           5 :                 Roffset = maxwidth - Rdata.width;
    1721         [ +  - ]:           5 :                 if (data)
    1722                 :           5 :                     data->width = maxwidth;
    1723                 :             :             }
    1724                 :             : 
    1725   [ +  +  +  + ]:       19988 :             if (Ldata.negate && Rdata.negate)
    1726                 :             :             {
    1727                 :             :                 /* !L & !R: treat as !(L | R) */
    1728                 :       18960 :                 (void) TS_phrase_output(data, &Ldata, &Rdata,
    1729                 :             :                                         TSPO_BOTH | TSPO_L_ONLY | TSPO_R_ONLY,
    1730                 :             :                                         Loffset, Roffset,
    1731                 :       18960 :                                         Ldata.npos + Rdata.npos);
    1732         [ -  + ]:       18960 :                 if (data)
    1733                 :           0 :                     data->negate = true;
    1734                 :       18960 :                 return TS_YES;
    1735                 :             :             }
    1736         [ +  + ]:        1028 :             else if (Ldata.negate)
    1737                 :             :             {
    1738                 :             :                 /* !L & R */
    1739                 :         309 :                 return TS_phrase_output(data, &Ldata, &Rdata,
    1740                 :             :                                         TSPO_R_ONLY,
    1741                 :             :                                         Loffset, Roffset,
    1742                 :             :                                         Rdata.npos);
    1743                 :             :             }
    1744         [ +  + ]:         719 :             else if (Rdata.negate)
    1745                 :             :             {
    1746                 :             :                 /* L & !R */
    1747                 :           5 :                 return TS_phrase_output(data, &Ldata, &Rdata,
    1748                 :             :                                         TSPO_L_ONLY,
    1749                 :             :                                         Loffset, Roffset,
    1750                 :             :                                         Ldata.npos);
    1751                 :             :             }
    1752                 :             :             else
    1753                 :             :             {
    1754                 :             :                 /* straight AND */
    1755                 :         714 :                 return TS_phrase_output(data, &Ldata, &Rdata,
    1756                 :             :                                         TSPO_BOTH,
    1757                 :             :                                         Loffset, Roffset,
    1758                 :         714 :                                         Min(Ldata.npos, Rdata.npos));
    1759                 :             :             }
    1760                 :             : 
    1761                 :         126 :         case OP_OR:
    1762                 :         126 :             memset(&Ldata, 0, sizeof(Ldata));
    1763                 :         126 :             memset(&Rdata, 0, sizeof(Rdata));
    1764                 :             : 
    1765                 :         126 :             lmatch = TS_phrase_execute(curitem + curitem->qoperator.left,
    1766                 :             :                                        arg, flags, chkcond, &Ldata);
    1767                 :         126 :             rmatch = TS_phrase_execute(curitem + 1,
    1768                 :             :                                        arg, flags, chkcond, &Rdata);
    1769                 :             : 
    1770   [ +  +  +  + ]:         126 :             if (lmatch == TS_NO && rmatch == TS_NO)
    1771                 :          10 :                 return TS_NO;
    1772                 :             : 
    1773                 :             :             /*
    1774                 :             :              * If either operand has no position information, then we can't
    1775                 :             :              * return reliable position data, only a MAYBE result.
    1776                 :             :              */
    1777   [ +  -  -  + ]:         116 :             if (lmatch == TS_MAYBE || rmatch == TS_MAYBE)
    1778                 :           0 :                 return TS_MAYBE;
    1779                 :             : 
    1780                 :             :             /*
    1781                 :             :              * Cope with undefined output width from failed submatch.  (This
    1782                 :             :              * takes less code than trying to ensure that all failure returns
    1783                 :             :              * set data->width to zero.)
    1784                 :             :              */
    1785         [ +  + ]:         116 :             if (lmatch == TS_NO)
    1786                 :          15 :                 Ldata.width = 0;
    1787         [ +  + ]:         116 :             if (rmatch == TS_NO)
    1788                 :          68 :                 Rdata.width = 0;
    1789                 :             : 
    1790                 :             :             /*
    1791                 :             :              * For OP_AND and OP_OR, report the width of the wider of the two
    1792                 :             :              * inputs, and align the narrower input's positions to the right
    1793                 :             :              * end of that width.  This rule deals at least somewhat
    1794                 :             :              * reasonably with cases like "x <-> (y | z <-> q)".
    1795                 :             :              */
    1796                 :         116 :             maxwidth = Max(Ldata.width, Rdata.width);
    1797                 :         116 :             Loffset = maxwidth - Ldata.width;
    1798                 :         116 :             Roffset = maxwidth - Rdata.width;
    1799                 :         116 :             data->width = maxwidth;
    1800                 :             : 
    1801   [ +  +  +  + ]:         116 :             if (Ldata.negate && Rdata.negate)
    1802                 :             :             {
    1803                 :             :                 /* !L | !R: treat as !(L & R) */
    1804                 :           5 :                 (void) TS_phrase_output(data, &Ldata, &Rdata,
    1805                 :             :                                         TSPO_BOTH,
    1806                 :             :                                         Loffset, Roffset,
    1807                 :           5 :                                         Min(Ldata.npos, Rdata.npos));
    1808                 :           5 :                 data->negate = true;
    1809                 :           5 :                 return TS_YES;
    1810                 :             :             }
    1811         [ +  + ]:         111 :             else if (Ldata.negate)
    1812                 :             :             {
    1813                 :             :                 /* !L | R: treat as !(L & !R) */
    1814                 :          25 :                 (void) TS_phrase_output(data, &Ldata, &Rdata,
    1815                 :             :                                         TSPO_L_ONLY,
    1816                 :             :                                         Loffset, Roffset,
    1817                 :             :                                         Ldata.npos);
    1818                 :          25 :                 data->negate = true;
    1819                 :          25 :                 return TS_YES;
    1820                 :             :             }
    1821         [ +  + ]:          86 :             else if (Rdata.negate)
    1822                 :             :             {
    1823                 :             :                 /* L | !R: treat as !(!L & R) */
    1824                 :           5 :                 (void) TS_phrase_output(data, &Ldata, &Rdata,
    1825                 :             :                                         TSPO_R_ONLY,
    1826                 :             :                                         Loffset, Roffset,
    1827                 :             :                                         Rdata.npos);
    1828                 :           5 :                 data->negate = true;
    1829                 :           5 :                 return TS_YES;
    1830                 :             :             }
    1831                 :             :             else
    1832                 :             :             {
    1833                 :             :                 /* straight OR */
    1834                 :          81 :                 return TS_phrase_output(data, &Ldata, &Rdata,
    1835                 :             :                                         TSPO_BOTH | TSPO_L_ONLY | TSPO_R_ONLY,
    1836                 :             :                                         Loffset, Roffset,
    1837                 :          81 :                                         Ldata.npos + Rdata.npos);
    1838                 :             :             }
    1839                 :             : 
    1840                 :           0 :         default:
    1841         [ #  # ]:           0 :             elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
    1842                 :             :     }
    1843                 :             : 
    1844                 :             :     /* not reachable, but keep compiler quiet */
    1845                 :           0 :     return TS_NO;
    1846                 :             : }
    1847                 :             : 
    1848                 :             : 
    1849                 :             : /*
    1850                 :             :  * Evaluate tsquery boolean expression.
    1851                 :             :  *
    1852                 :             :  * curitem: current tsquery item (initially, the first one)
    1853                 :             :  * arg: opaque value to pass through to callback function
    1854                 :             :  * flags: bitmask of flag bits shown in ts_utils.h
    1855                 :             :  * chkcond: callback function to check whether a primitive value is present
    1856                 :             :  */
    1857                 :             : bool
    1858                 :      346749 : TS_execute(QueryItem *curitem, void *arg, uint32 flags,
    1859                 :             :            TSExecuteCallback chkcond)
    1860                 :             : {
    1861                 :             :     /*
    1862                 :             :      * If we get TS_MAYBE from the recursion, return true.  We could only see
    1863                 :             :      * that result if the caller passed TS_EXEC_PHRASE_NO_POS, so there's no
    1864                 :             :      * need to check again.
    1865                 :             :      */
    1866                 :      346749 :     return TS_execute_recurse(curitem, arg, flags, chkcond) != TS_NO;
    1867                 :             : }
    1868                 :             : 
    1869                 :             : /*
    1870                 :             :  * Evaluate tsquery boolean expression.
    1871                 :             :  *
    1872                 :             :  * This is the same as TS_execute except that TS_MAYBE is returned as-is.
    1873                 :             :  */
    1874                 :             : TSTernaryValue
    1875                 :       24628 : TS_execute_ternary(QueryItem *curitem, void *arg, uint32 flags,
    1876                 :             :                    TSExecuteCallback chkcond)
    1877                 :             : {
    1878                 :       24628 :     return TS_execute_recurse(curitem, arg, flags, chkcond);
    1879                 :             : }
    1880                 :             : 
    1881                 :             : /*
    1882                 :             :  * TS_execute recursion for operators above any phrase operator.  Here we do
    1883                 :             :  * not need to worry about lexeme positions.  As soon as we hit an OP_PHRASE
    1884                 :             :  * operator, we pass it off to TS_phrase_execute which does worry.
    1885                 :             :  */
    1886                 :             : static TSTernaryValue
    1887                 :      703262 : TS_execute_recurse(QueryItem *curitem, void *arg, uint32 flags,
    1888                 :             :                    TSExecuteCallback chkcond)
    1889                 :             : {
    1890                 :             :     TSTernaryValue lmatch;
    1891                 :             : 
    1892                 :             :     /* since this function recurses, it could be driven to stack overflow */
    1893                 :      703262 :     check_stack_depth();
    1894                 :             : 
    1895                 :             :     /* ... and let's check for query cancel while we're at it */
    1896         [ -  + ]:      703262 :     CHECK_FOR_INTERRUPTS();
    1897                 :             : 
    1898         [ +  + ]:      703262 :     if (curitem->type == QI_VAL)
    1899                 :      282573 :         return chkcond(arg, (QueryOperand *) curitem,
    1900                 :             :                        NULL /* don't need position info */ );
    1901                 :             : 
    1902   [ +  +  +  +  :      420689 :     switch (curitem->qoperator.oper)
                      - ]
    1903                 :             :     {
    1904                 :      135497 :         case OP_NOT:
    1905         [ -  + ]:      135497 :             if (flags & TS_EXEC_SKIP_NOT)
    1906                 :           0 :                 return TS_YES;
    1907   [ +  +  +  - ]:      135497 :             switch (TS_execute_recurse(curitem + 1, arg, flags, chkcond))
    1908                 :             :             {
    1909                 :      127837 :                 case TS_NO:
    1910                 :      127837 :                     return TS_YES;
    1911                 :        3264 :                 case TS_YES:
    1912                 :        3264 :                     return TS_NO;
    1913                 :        4396 :                 case TS_MAYBE:
    1914                 :        4396 :                     return TS_MAYBE;
    1915                 :             :             }
    1916                 :           0 :             break;
    1917                 :             : 
    1918                 :       55804 :         case OP_AND:
    1919                 :       55804 :             lmatch = TS_execute_recurse(curitem + curitem->qoperator.left, arg,
    1920                 :             :                                         flags, chkcond);
    1921         [ +  + ]:       55804 :             if (lmatch == TS_NO)
    1922                 :       44304 :                 return TS_NO;
    1923   [ +  +  +  - ]:       11500 :             switch (TS_execute_recurse(curitem + 1, arg, flags, chkcond))
    1924                 :             :             {
    1925                 :        6754 :                 case TS_NO:
    1926                 :        6754 :                     return TS_NO;
    1927                 :        2236 :                 case TS_YES:
    1928                 :        2236 :                     return lmatch;
    1929                 :        2510 :                 case TS_MAYBE:
    1930                 :        2510 :                     return TS_MAYBE;
    1931                 :             :             }
    1932                 :           0 :             break;
    1933                 :             : 
    1934                 :       72614 :         case OP_OR:
    1935                 :       72614 :             lmatch = TS_execute_recurse(curitem + curitem->qoperator.left, arg,
    1936                 :             :                                         flags, chkcond);
    1937         [ +  + ]:       72614 :             if (lmatch == TS_YES)
    1938                 :       16144 :                 return TS_YES;
    1939   [ +  +  +  - ]:       56470 :             switch (TS_execute_recurse(curitem + 1, arg, flags, chkcond))
    1940                 :             :             {
    1941                 :       38294 :                 case TS_NO:
    1942                 :       38294 :                     return lmatch;
    1943                 :        4962 :                 case TS_YES:
    1944                 :        4962 :                     return TS_YES;
    1945                 :       13214 :                 case TS_MAYBE:
    1946                 :       13214 :                     return TS_MAYBE;
    1947                 :             :             }
    1948                 :           0 :             break;
    1949                 :             : 
    1950                 :      156774 :         case OP_PHRASE:
    1951                 :             : 
    1952                 :             :             /*
    1953                 :             :              * If we get a MAYBE result, and the caller doesn't want that,
    1954                 :             :              * convert it to NO.  It would be more consistent, perhaps, to
    1955                 :             :              * return the result of TS_phrase_execute() verbatim and then
    1956                 :             :              * convert MAYBE results at the top of the recursion.  But
    1957                 :             :              * converting at the topmost phrase operator gives results that
    1958                 :             :              * are bug-compatible with the old implementation, so do it like
    1959                 :             :              * this for now.
    1960                 :             :              */
    1961   [ +  +  +  - ]:      156774 :             switch (TS_phrase_execute(curitem, arg, flags, chkcond, NULL))
    1962                 :             :             {
    1963                 :      120002 :                 case TS_NO:
    1964                 :      120002 :                     return TS_NO;
    1965                 :       19604 :                 case TS_YES:
    1966                 :       19604 :                     return TS_YES;
    1967                 :       17168 :                 case TS_MAYBE:
    1968                 :       17168 :                     return (flags & TS_EXEC_PHRASE_NO_POS) ? TS_MAYBE : TS_NO;
    1969                 :             :             }
    1970                 :           0 :             break;
    1971                 :             : 
    1972                 :           0 :         default:
    1973         [ #  # ]:           0 :             elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
    1974                 :             :     }
    1975                 :             : 
    1976                 :             :     /* not reachable, but keep compiler quiet */
    1977                 :           0 :     return TS_NO;
    1978                 :             : }
    1979                 :             : 
    1980                 :             : /*
    1981                 :             :  * Evaluate tsquery and report locations of matching terms.
    1982                 :             :  *
    1983                 :             :  * This is like TS_execute except that it returns match locations not just
    1984                 :             :  * success/failure status.  The callback function is required to provide
    1985                 :             :  * position data (we report failure if it doesn't).
    1986                 :             :  *
    1987                 :             :  * On successful match, the result is a List of ExecPhraseData structs, one
    1988                 :             :  * for each AND'ed term or phrase operator in the query.  Each struct includes
    1989                 :             :  * a sorted array of lexeme positions matching that term.  (Recall that for
    1990                 :             :  * phrase operators, the match includes width+1 lexemes, and the recorded
    1991                 :             :  * position is that of the rightmost lexeme.)
    1992                 :             :  *
    1993                 :             :  * OR subexpressions are handled by union'ing their match locations into a
    1994                 :             :  * single List element, which is valid since any of those locations contains
    1995                 :             :  * a match.  However, when some of the OR'ed terms are phrase operators, we
    1996                 :             :  * report the maximum width of any of the OR'ed terms, making such cases
    1997                 :             :  * slightly imprecise in the conservative direction.  (For example, if the
    1998                 :             :  * tsquery is "(A <-> B) | C", an occurrence of C in the data would be
    1999                 :             :  * reported as though it includes the lexeme to the left of C.)
    2000                 :             :  *
    2001                 :             :  * Locations of NOT subexpressions are not reported.  (Obviously, there can
    2002                 :             :  * be no successful NOT matches at top level, or the match would have failed.
    2003                 :             :  * So this amounts to ignoring NOTs underneath ORs.)
    2004                 :             :  *
    2005                 :             :  * The result is NIL if no match, or if position data was not returned.
    2006                 :             :  *
    2007                 :             :  * Arguments are the same as for TS_execute, although flags is currently
    2008                 :             :  * vestigial since none of the defined bits are sensible here.
    2009                 :             :  */
    2010                 :             : List *
    2011                 :         293 : TS_execute_locations(QueryItem *curitem, void *arg,
    2012                 :             :                      uint32 flags,
    2013                 :             :                      TSExecuteCallback chkcond)
    2014                 :             : {
    2015                 :             :     List       *result;
    2016                 :             : 
    2017                 :             :     /* No flags supported, as yet */
    2018                 :             :     Assert(flags == TS_EXEC_EMPTY);
    2019         [ +  + ]:         293 :     if (TS_execute_locations_recurse(curitem, arg, chkcond, &result))
    2020                 :         118 :         return result;
    2021                 :         175 :     return NIL;
    2022                 :             : }
    2023                 :             : 
    2024                 :             : /*
    2025                 :             :  * TS_execute_locations recursion for operators above any phrase operator.
    2026                 :             :  * OP_PHRASE subexpressions can be passed off to TS_phrase_execute.
    2027                 :             :  */
    2028                 :             : static bool
    2029                 :         839 : TS_execute_locations_recurse(QueryItem *curitem, void *arg,
    2030                 :             :                              TSExecuteCallback chkcond,
    2031                 :             :                              List **locations)
    2032                 :             : {
    2033                 :             :     bool        lmatch,
    2034                 :             :                 rmatch;
    2035                 :             :     List       *llocations,
    2036                 :             :                *rlocations;
    2037                 :             :     ExecPhraseData *data;
    2038                 :             : 
    2039                 :             :     /* since this function recurses, it could be driven to stack overflow */
    2040                 :         839 :     check_stack_depth();
    2041                 :             : 
    2042                 :             :     /* ... and let's check for query cancel while we're at it */
    2043         [ -  + ]:         839 :     CHECK_FOR_INTERRUPTS();
    2044                 :             : 
    2045                 :             :     /* Default locations result is empty */
    2046                 :         839 :     *locations = NIL;
    2047                 :             : 
    2048         [ +  + ]:         839 :     if (curitem->type == QI_VAL)
    2049                 :             :     {
    2050                 :         359 :         data = palloc0_object(ExecPhraseData);
    2051         [ +  + ]:         359 :         if (chkcond(arg, (QueryOperand *) curitem, data) == TS_YES)
    2052                 :             :         {
    2053                 :         184 :             *locations = list_make1(data);
    2054                 :         184 :             return true;
    2055                 :             :         }
    2056                 :         175 :         pfree(data);
    2057                 :         175 :         return false;
    2058                 :             :     }
    2059                 :             : 
    2060   [ +  +  +  +  :         480 :     switch (curitem->qoperator.oper)
                      - ]
    2061                 :             :     {
    2062                 :          10 :         case OP_NOT:
    2063         [ -  + ]:          10 :             if (!TS_execute_locations_recurse(curitem + 1, arg, chkcond,
    2064                 :             :                                               &llocations))
    2065                 :           0 :                 return true;    /* we don't pass back any locations */
    2066                 :          10 :             return false;
    2067                 :             : 
    2068                 :         400 :         case OP_AND:
    2069         [ +  + ]:         400 :             if (!TS_execute_locations_recurse(curitem + curitem->qoperator.left,
    2070                 :             :                                               arg, chkcond,
    2071                 :             :                                               &llocations))
    2072                 :         304 :                 return false;
    2073         [ +  + ]:          96 :             if (!TS_execute_locations_recurse(curitem + 1,
    2074                 :             :                                               arg, chkcond,
    2075                 :             :                                               &rlocations))
    2076                 :          41 :                 return false;
    2077                 :          55 :             *locations = list_concat(llocations, rlocations);
    2078                 :          55 :             return true;
    2079                 :             : 
    2080                 :          20 :         case OP_OR:
    2081                 :          20 :             lmatch = TS_execute_locations_recurse(curitem + curitem->qoperator.left,
    2082                 :             :                                                   arg, chkcond,
    2083                 :             :                                                   &llocations);
    2084                 :          20 :             rmatch = TS_execute_locations_recurse(curitem + 1,
    2085                 :             :                                                   arg, chkcond,
    2086                 :             :                                                   &rlocations);
    2087   [ -  +  -  - ]:          20 :             if (lmatch || rmatch)
    2088                 :             :             {
    2089                 :             :                 /*
    2090                 :             :                  * We generate an AND'able location struct from each
    2091                 :             :                  * combination of sub-matches, following the disjunctive law
    2092                 :             :                  * (A & B) | (C & D) = (A | C) & (A | D) & (B | C) & (B | D).
    2093                 :             :                  *
    2094                 :             :                  * However, if either input didn't produce locations (i.e., it
    2095                 :             :                  * failed or was a NOT), we must just return the other list.
    2096                 :             :                  */
    2097         [ -  + ]:          20 :                 if (llocations == NIL)
    2098                 :           0 :                     *locations = rlocations;
    2099         [ +  + ]:          20 :                 else if (rlocations == NIL)
    2100                 :          10 :                     *locations = llocations;
    2101                 :             :                 else
    2102                 :             :                 {
    2103                 :             :                     ListCell   *ll;
    2104                 :             : 
    2105   [ +  -  +  +  :          20 :                     foreach(ll, llocations)
                   +  + ]
    2106                 :             :                     {
    2107                 :          10 :                         ExecPhraseData *ldata = (ExecPhraseData *) lfirst(ll);
    2108                 :             :                         ListCell   *lr;
    2109                 :             : 
    2110   [ +  -  +  +  :          20 :                         foreach(lr, rlocations)
                   +  + ]
    2111                 :             :                         {
    2112                 :          10 :                             ExecPhraseData *rdata = (ExecPhraseData *) lfirst(lr);
    2113                 :             : 
    2114                 :          10 :                             data = palloc0_object(ExecPhraseData);
    2115                 :          10 :                             (void) TS_phrase_output(data, ldata, rdata,
    2116                 :             :                                                     TSPO_BOTH | TSPO_L_ONLY | TSPO_R_ONLY,
    2117                 :             :                                                     0, 0,
    2118                 :          10 :                                                     ldata->npos + rdata->npos);
    2119                 :             :                             /* Report the larger width, as explained above. */
    2120                 :          10 :                             data->width = Max(ldata->width, rdata->width);
    2121                 :          10 :                             *locations = lappend(*locations, data);
    2122                 :             :                         }
    2123                 :             :                     }
    2124                 :             :                 }
    2125                 :             : 
    2126                 :          20 :                 return true;
    2127                 :             :             }
    2128                 :           0 :             return false;
    2129                 :             : 
    2130                 :          50 :         case OP_PHRASE:
    2131                 :             :             /* We can hand this off to TS_phrase_execute */
    2132                 :          50 :             data = palloc0_object(ExecPhraseData);
    2133         [ +  - ]:          50 :             if (TS_phrase_execute(curitem, arg, TS_EXEC_EMPTY, chkcond,
    2134                 :             :                                   data) == TS_YES)
    2135                 :             :             {
    2136         [ +  - ]:          50 :                 if (!data->negate)
    2137                 :          50 :                     *locations = list_make1(data);
    2138                 :          50 :                 return true;
    2139                 :             :             }
    2140                 :           0 :             pfree(data);
    2141                 :           0 :             return false;
    2142                 :             : 
    2143                 :           0 :         default:
    2144         [ #  # ]:           0 :             elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
    2145                 :             :     }
    2146                 :             : 
    2147                 :             :     /* not reachable, but keep compiler quiet */
    2148                 :             :     return false;
    2149                 :             : }
    2150                 :             : 
    2151                 :             : /*
    2152                 :             :  * Detect whether a tsquery boolean expression requires any positive matches
    2153                 :             :  * to values shown in the tsquery.
    2154                 :             :  *
    2155                 :             :  * This is needed to know whether a GIN index search requires full index scan.
    2156                 :             :  * For example, 'x & !y' requires a match of x, so it's sufficient to scan
    2157                 :             :  * entries for x; but 'x | !y' could match rows containing neither x nor y.
    2158                 :             :  */
    2159                 :             : bool
    2160                 :         631 : tsquery_requires_match(QueryItem *curitem)
    2161                 :             : {
    2162                 :             :     /* since this function recurses, it could be driven to stack overflow */
    2163                 :         631 :     check_stack_depth();
    2164                 :             : 
    2165         [ +  + ]:         631 :     if (curitem->type == QI_VAL)
    2166                 :         301 :         return true;
    2167                 :             : 
    2168   [ +  +  +  - ]:         330 :     switch (curitem->qoperator.oper)
    2169                 :             :     {
    2170                 :         127 :         case OP_NOT:
    2171                 :             : 
    2172                 :             :             /*
    2173                 :             :              * Assume there are no required matches underneath a NOT.  For
    2174                 :             :              * some cases with nested NOTs, we could prove there's a required
    2175                 :             :              * match, but it seems unlikely to be worth the trouble.
    2176                 :             :              */
    2177                 :         127 :             return false;
    2178                 :             : 
    2179                 :         153 :         case OP_PHRASE:
    2180                 :             : 
    2181                 :             :             /*
    2182                 :             :              * Treat OP_PHRASE as OP_AND here
    2183                 :             :              */
    2184                 :             :         case OP_AND:
    2185                 :             :             /* If either side requires a match, we're good */
    2186         [ +  + ]:         153 :             if (tsquery_requires_match(curitem + curitem->qoperator.left))
    2187                 :         117 :                 return true;
    2188                 :             :             else
    2189                 :          36 :                 return tsquery_requires_match(curitem + 1);
    2190                 :             : 
    2191                 :          50 :         case OP_OR:
    2192                 :             :             /* Both sides must require a match */
    2193         [ +  - ]:          50 :             if (tsquery_requires_match(curitem + curitem->qoperator.left))
    2194                 :          50 :                 return tsquery_requires_match(curitem + 1);
    2195                 :             :             else
    2196                 :           0 :                 return false;
    2197                 :             : 
    2198                 :           0 :         default:
    2199         [ #  # ]:           0 :             elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
    2200                 :             :     }
    2201                 :             : 
    2202                 :             :     /* not reachable, but keep compiler quiet */
    2203                 :             :     return false;
    2204                 :             : }
    2205                 :             : 
    2206                 :             : /*
    2207                 :             :  * boolean operations
    2208                 :             :  */
    2209                 :             : Datum
    2210                 :          40 : ts_match_qv(PG_FUNCTION_ARGS)
    2211                 :             : {
    2212                 :          40 :     PG_RETURN_DATUM(DirectFunctionCall2(ts_match_vq,
    2213                 :             :                                         PG_GETARG_DATUM(1),
    2214                 :             :                                         PG_GETARG_DATUM(0)));
    2215                 :             : }
    2216                 :             : 
    2217                 :             : Datum
    2218                 :      146808 : ts_match_vq(PG_FUNCTION_ARGS)
    2219                 :             : {
    2220                 :      146808 :     TSVector    val = PG_GETARG_TSVECTOR(0);
    2221                 :      146808 :     TSQuery     query = PG_GETARG_TSQUERY(1);
    2222                 :             :     CHKVAL      chkval;
    2223                 :             :     bool        result;
    2224                 :             : 
    2225                 :             :     /* empty query matches nothing */
    2226         [ -  + ]:      146808 :     if (!query->size)
    2227                 :             :     {
    2228         [ #  # ]:           0 :         PG_FREE_IF_COPY(val, 0);
    2229         [ #  # ]:           0 :         PG_FREE_IF_COPY(query, 1);
    2230                 :           0 :         PG_RETURN_BOOL(false);
    2231                 :             :     }
    2232                 :             : 
    2233                 :      146808 :     chkval.arrb = ARRPTR(val);
    2234                 :      146808 :     chkval.arre = chkval.arrb + val->size;
    2235                 :      146808 :     chkval.values = STRPTR(val);
    2236                 :      146808 :     chkval.operand = GETOPERAND(query);
    2237                 :      146808 :     result = TS_execute(GETQUERY(query),
    2238                 :             :                         &chkval,
    2239                 :             :                         TS_EXEC_EMPTY,
    2240                 :             :                         checkcondition_str);
    2241                 :             : 
    2242         [ +  + ]:      146808 :     PG_FREE_IF_COPY(val, 0);
    2243         [ -  + ]:      146808 :     PG_FREE_IF_COPY(query, 1);
    2244                 :      146808 :     PG_RETURN_BOOL(result);
    2245                 :             : }
    2246                 :             : 
    2247                 :             : Datum
    2248                 :           0 : ts_match_tt(PG_FUNCTION_ARGS)
    2249                 :             : {
    2250                 :             :     TSVector    vector;
    2251                 :             :     TSQuery     query;
    2252                 :             :     bool        res;
    2253                 :             : 
    2254                 :           0 :     vector = DatumGetTSVector(DirectFunctionCall1(to_tsvector,
    2255                 :             :                                                   PG_GETARG_DATUM(0)));
    2256                 :           0 :     query = DatumGetTSQuery(DirectFunctionCall1(plainto_tsquery,
    2257                 :             :                                                 PG_GETARG_DATUM(1)));
    2258                 :             : 
    2259                 :           0 :     res = DatumGetBool(DirectFunctionCall2(ts_match_vq,
    2260                 :             :                                            TSVectorGetDatum(vector),
    2261                 :             :                                            TSQueryGetDatum(query)));
    2262                 :             : 
    2263                 :           0 :     pfree(vector);
    2264                 :           0 :     pfree(query);
    2265                 :             : 
    2266                 :           0 :     PG_RETURN_BOOL(res);
    2267                 :             : }
    2268                 :             : 
    2269                 :             : Datum
    2270                 :           0 : ts_match_tq(PG_FUNCTION_ARGS)
    2271                 :             : {
    2272                 :             :     TSVector    vector;
    2273                 :           0 :     TSQuery     query = PG_GETARG_TSQUERY(1);
    2274                 :             :     bool        res;
    2275                 :             : 
    2276                 :           0 :     vector = DatumGetTSVector(DirectFunctionCall1(to_tsvector,
    2277                 :             :                                                   PG_GETARG_DATUM(0)));
    2278                 :             : 
    2279                 :           0 :     res = DatumGetBool(DirectFunctionCall2(ts_match_vq,
    2280                 :             :                                            TSVectorGetDatum(vector),
    2281                 :             :                                            TSQueryGetDatum(query)));
    2282                 :             : 
    2283                 :           0 :     pfree(vector);
    2284         [ #  # ]:           0 :     PG_FREE_IF_COPY(query, 1);
    2285                 :             : 
    2286                 :           0 :     PG_RETURN_BOOL(res);
    2287                 :             : }
    2288                 :             : 
    2289                 :             : /*
    2290                 :             :  * ts_stat statistic function support
    2291                 :             :  */
    2292                 :             : 
    2293                 :             : 
    2294                 :             : /*
    2295                 :             :  * Returns the number of positions in value 'wptr' within tsvector 'txt',
    2296                 :             :  * that have a weight equal to one of the weights in 'weight' bitmask.
    2297                 :             :  */
    2298                 :             : static int
    2299                 :        5452 : check_weight(TSVector txt, WordEntry *wptr, int8 weight)
    2300                 :             : {
    2301         [ +  - ]:        5452 :     int         len = POSDATALEN(txt, wptr);
    2302                 :        5452 :     int         num = 0;
    2303                 :        5452 :     WordEntryPos *ptr = POSDATAPTR(txt, wptr);
    2304                 :             : 
    2305         [ +  + ]:       11100 :     while (len--)
    2306                 :             :     {
    2307         [ +  + ]:        5648 :         if (weight & (1 << WEP_GETWEIGHT(*ptr)))
    2308                 :           8 :             num++;
    2309                 :        5648 :         ptr++;
    2310                 :             :     }
    2311                 :        5452 :     return num;
    2312                 :             : }
    2313                 :             : 
    2314                 :             : #define compareStatWord(a,e,t)                          \
    2315                 :             :     tsCompareString((a)->lexeme, (a)->lenlexeme,      \
    2316                 :             :                     STRPTR(t) + (e)->pos, (e)->len,       \
    2317                 :             :                     false)
    2318                 :             : 
    2319                 :             : static void
    2320                 :      230416 : insertStatEntry(MemoryContext persistentContext, TSVectorStat *stat, TSVector txt, uint32 off)
    2321                 :             : {
    2322                 :      230416 :     WordEntry  *we = ARRPTR(txt) + off;
    2323                 :      230416 :     StatEntry  *node = stat->root,
    2324                 :      230416 :                *pnode = NULL;
    2325                 :             :     int         n,
    2326                 :      230416 :                 res = 0;
    2327                 :      230416 :     uint32      depth = 1;
    2328                 :             : 
    2329         [ +  + ]:      230416 :     if (stat->weight == 0)
    2330         [ +  + ]:      115208 :         n = (we->haspos) ? POSDATALEN(txt, we) : 1;
    2331                 :             :     else
    2332         [ +  + ]:      115208 :         n = (we->haspos) ? check_weight(txt, we, stat->weight) : 0;
    2333                 :             : 
    2334         [ +  + ]:      230416 :     if (n == 0)
    2335                 :      115204 :         return;                 /* nothing to insert */
    2336                 :             : 
    2337         [ +  + ]:     1163592 :     while (node)
    2338                 :             :     {
    2339                 :     1159016 :         res = compareStatWord(node, we, txt);
    2340                 :             : 
    2341         [ +  + ]:     1159016 :         if (res == 0)
    2342                 :             :         {
    2343                 :      110636 :             break;
    2344                 :             :         }
    2345                 :             :         else
    2346                 :             :         {
    2347                 :     1048380 :             pnode = node;
    2348         [ +  + ]:     1048380 :             node = (res < 0) ? node->left : node->right;
    2349                 :             :         }
    2350                 :     1048380 :         depth++;
    2351                 :             :     }
    2352                 :             : 
    2353         [ +  + ]:      115212 :     if (depth > stat->maxdepth)
    2354                 :          84 :         stat->maxdepth = depth;
    2355                 :             : 
    2356         [ +  + ]:      115212 :     if (node == NULL)
    2357                 :             :     {
    2358                 :        4576 :         node = MemoryContextAlloc(persistentContext, STATENTRYHDRSZ + we->len);
    2359                 :        4576 :         node->left = node->right = NULL;
    2360                 :        4576 :         node->ndoc = 1;
    2361                 :        4576 :         node->nentry = n;
    2362                 :        4576 :         node->lenlexeme = we->len;
    2363                 :        4576 :         memcpy(node->lexeme, STRPTR(txt) + we->pos, node->lenlexeme);
    2364                 :             : 
    2365         [ +  + ]:        4576 :         if (pnode == NULL)
    2366                 :             :         {
    2367                 :           8 :             stat->root = node;
    2368                 :             :         }
    2369                 :             :         else
    2370                 :             :         {
    2371         [ +  + ]:        4568 :             if (res < 0)
    2372                 :        2254 :                 pnode->left = node;
    2373                 :             :             else
    2374                 :        2314 :                 pnode->right = node;
    2375                 :             :         }
    2376                 :             :     }
    2377                 :             :     else
    2378                 :             :     {
    2379                 :      110636 :         node->ndoc++;
    2380                 :      110636 :         node->nentry += n;
    2381                 :             :     }
    2382                 :             : }
    2383                 :             : 
    2384                 :             : static void
    2385                 :      330256 : chooseNextStatEntry(MemoryContext persistentContext, TSVectorStat *stat, TSVector txt,
    2386                 :             :                     uint32 low, uint32 high, uint32 offset)
    2387                 :             : {
    2388                 :             :     uint32      pos;
    2389                 :      330256 :     uint32      middle = (low + high) >> 1;
    2390                 :             : 
    2391                 :      330256 :     pos = (low + middle) >> 1;
    2392   [ +  +  +  +  :      330256 :     if (low != middle && pos >= offset && pos - offset < txt->size)
                   +  + ]
    2393                 :      113552 :         insertStatEntry(persistentContext, stat, txt, pos - offset);
    2394                 :      330256 :     pos = (high + middle + 1) >> 1;
    2395   [ +  +  +  +  :      330256 :     if (middle + 1 != high && pos >= offset && pos - offset < txt->size)
                   +  + ]
    2396                 :      112856 :         insertStatEntry(persistentContext, stat, txt, pos - offset);
    2397                 :             : 
    2398         [ +  + ]:      330256 :     if (low != middle)
    2399                 :      165128 :         chooseNextStatEntry(persistentContext, stat, txt, low, middle, offset);
    2400         [ +  + ]:      330256 :     if (high != middle + 1)
    2401                 :      161120 :         chooseNextStatEntry(persistentContext, stat, txt, middle + 1, high, offset);
    2402                 :      330256 : }
    2403                 :             : 
    2404                 :             : /*
    2405                 :             :  * This is written like a custom aggregate function, because the
    2406                 :             :  * original plan was to do just that. Unfortunately, an aggregate function
    2407                 :             :  * can't return a set, so that plan was abandoned. If that limitation is
    2408                 :             :  * lifted in the future, ts_stat could be a real aggregate function so that
    2409                 :             :  * you could use it like this:
    2410                 :             :  *
    2411                 :             :  *   SELECT ts_stat(vector_column) FROM vector_table;
    2412                 :             :  *
    2413                 :             :  *  where vector_column is a tsvector-type column in vector_table.
    2414                 :             :  */
    2415                 :             : 
    2416                 :             : static TSVectorStat *
    2417                 :        4072 : ts_accum(MemoryContext persistentContext, TSVectorStat *stat, Datum data)
    2418                 :             : {
    2419                 :        4072 :     TSVector    txt = DatumGetTSVector(data);
    2420                 :             :     uint32      i,
    2421                 :        4072 :                 nbit = 0,
    2422                 :             :                 offset;
    2423                 :             : 
    2424         [ -  + ]:        4072 :     if (stat == NULL)
    2425                 :             :     {                           /* Init in first */
    2426                 :           0 :         stat = MemoryContextAllocZero(persistentContext, sizeof(TSVectorStat));
    2427                 :           0 :         stat->maxdepth = 1;
    2428                 :             :     }
    2429                 :             : 
    2430                 :             :     /* simple check of correctness */
    2431   [ +  -  +  + ]:        4072 :     if (txt == NULL || txt->size == 0)
    2432                 :             :     {
    2433   [ +  -  +  - ]:          64 :         if (txt && txt != (TSVector) DatumGetPointer(data))
    2434                 :          64 :             pfree(txt);
    2435                 :          64 :         return stat;
    2436                 :             :     }
    2437                 :             : 
    2438                 :        4008 :     i = txt->size - 1;
    2439         [ +  + ]:       28480 :     for (; i > 0; i >>= 1)
    2440                 :       24472 :         nbit++;
    2441                 :             : 
    2442                 :        4008 :     nbit = 1 << nbit;
    2443                 :        4008 :     offset = (nbit - txt->size) / 2;
    2444                 :             : 
    2445                 :        4008 :     insertStatEntry(persistentContext, stat, txt, (nbit >> 1) - offset);
    2446                 :        4008 :     chooseNextStatEntry(persistentContext, stat, txt, 0, nbit, offset);
    2447                 :             : 
    2448                 :        4008 :     return stat;
    2449                 :             : }
    2450                 :             : 
    2451                 :             : static void
    2452                 :           8 : ts_setup_firstcall(FunctionCallInfo fcinfo, FuncCallContext *funcctx,
    2453                 :             :                    TSVectorStat *stat)
    2454                 :             : {
    2455                 :             :     TupleDesc   tupdesc;
    2456                 :             :     MemoryContext oldcontext;
    2457                 :             :     StatEntry  *node;
    2458                 :             : 
    2459                 :           8 :     funcctx->user_fctx = stat;
    2460                 :             : 
    2461                 :           8 :     oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
    2462                 :             : 
    2463                 :           8 :     stat->stack = palloc0_array(StatEntry *, stat->maxdepth + 1);
    2464                 :           8 :     stat->stackpos = 0;
    2465                 :             : 
    2466                 :           8 :     node = stat->root;
    2467                 :             :     /* find leftmost value */
    2468         [ -  + ]:           8 :     if (node == NULL)
    2469                 :           0 :         stat->stack[stat->stackpos] = NULL;
    2470                 :             :     else
    2471                 :             :         for (;;)
    2472                 :             :         {
    2473                 :          32 :             stat->stack[stat->stackpos] = node;
    2474         [ +  + ]:          32 :             if (node->left)
    2475                 :             :             {
    2476                 :          24 :                 stat->stackpos++;
    2477                 :          24 :                 node = node->left;
    2478                 :             :             }
    2479                 :             :             else
    2480                 :           8 :                 break;
    2481                 :             :         }
    2482                 :             :     Assert(stat->stackpos <= stat->maxdepth);
    2483                 :             : 
    2484         [ -  + ]:           8 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
    2485         [ #  # ]:           0 :         elog(ERROR, "return type must be a row type");
    2486                 :           8 :     funcctx->tuple_desc = tupdesc;
    2487                 :           8 :     funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
    2488                 :             : 
    2489                 :           8 :     MemoryContextSwitchTo(oldcontext);
    2490                 :           8 : }
    2491                 :             : 
    2492                 :             : static StatEntry *
    2493                 :        9152 : walkStatEntryTree(TSVectorStat *stat)
    2494                 :             : {
    2495                 :        9152 :     StatEntry  *node = stat->stack[stat->stackpos];
    2496                 :             : 
    2497         [ -  + ]:        9152 :     if (node == NULL)
    2498                 :           0 :         return NULL;
    2499                 :             : 
    2500         [ +  + ]:        9152 :     if (node->ndoc != 0)
    2501                 :             :     {
    2502                 :             :         /* return entry itself: we already was at left sublink */
    2503                 :        2262 :         return node;
    2504                 :             :     }
    2505   [ +  +  +  + ]:        6890 :     else if (node->right && node->right != stat->stack[stat->stackpos + 1])
    2506                 :             :     {
    2507                 :             :         /* go on right sublink */
    2508                 :        2314 :         stat->stackpos++;
    2509                 :        2314 :         node = node->right;
    2510                 :             : 
    2511                 :             :         /* find most-left value */
    2512                 :             :         for (;;)
    2513                 :             :         {
    2514                 :        4544 :             stat->stack[stat->stackpos] = node;
    2515         [ +  + ]:        4544 :             if (node->left)
    2516                 :             :             {
    2517                 :        2230 :                 stat->stackpos++;
    2518                 :        2230 :                 node = node->left;
    2519                 :             :             }
    2520                 :             :             else
    2521                 :        2314 :                 break;
    2522                 :             :         }
    2523                 :        2314 :         Assert(stat->stackpos <= stat->maxdepth);
    2524                 :             :     }
    2525                 :             :     else
    2526                 :             :     {
    2527                 :             :         /* we already return all left subtree, itself and  right subtree */
    2528         [ +  + ]:        4576 :         if (stat->stackpos == 0)
    2529                 :           8 :             return NULL;
    2530                 :             : 
    2531                 :        4568 :         stat->stackpos--;
    2532                 :        4568 :         return walkStatEntryTree(stat);
    2533                 :             :     }
    2534                 :             : 
    2535                 :        2314 :     return node;
    2536                 :             : }
    2537                 :             : 
    2538                 :             : static Datum
    2539                 :        4584 : ts_process_call(FuncCallContext *funcctx)
    2540                 :             : {
    2541                 :             :     TSVectorStat *st;
    2542                 :             :     StatEntry  *entry;
    2543                 :             : 
    2544                 :        4584 :     st = (TSVectorStat *) funcctx->user_fctx;
    2545                 :             : 
    2546                 :        4584 :     entry = walkStatEntryTree(st);
    2547                 :             : 
    2548         [ +  + ]:        4584 :     if (entry != NULL)
    2549                 :             :     {
    2550                 :             :         Datum       result;
    2551                 :             :         char       *values[3];
    2552                 :             :         char        ndoc[16];
    2553                 :             :         char        nentry[16];
    2554                 :             :         HeapTuple   tuple;
    2555                 :             : 
    2556                 :        4576 :         values[0] = palloc(entry->lenlexeme + 1);
    2557                 :        4576 :         memcpy(values[0], entry->lexeme, entry->lenlexeme);
    2558                 :        4576 :         (values[0])[entry->lenlexeme] = '\0';
    2559                 :        4576 :         sprintf(ndoc, "%d", entry->ndoc);
    2560                 :        4576 :         values[1] = ndoc;
    2561                 :        4576 :         sprintf(nentry, "%d", entry->nentry);
    2562                 :        4576 :         values[2] = nentry;
    2563                 :             : 
    2564                 :        4576 :         tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
    2565                 :        4576 :         result = HeapTupleGetDatum(tuple);
    2566                 :             : 
    2567                 :        4576 :         pfree(values[0]);
    2568                 :             : 
    2569                 :             :         /* mark entry as already visited */
    2570                 :        4576 :         entry->ndoc = 0;
    2571                 :             : 
    2572                 :        4576 :         return result;
    2573                 :             :     }
    2574                 :             : 
    2575                 :           8 :     return (Datum) 0;
    2576                 :             : }
    2577                 :             : 
    2578                 :             : static TSVectorStat *
    2579                 :           8 : ts_stat_sql(MemoryContext persistentContext, text *txt, text *ws)
    2580                 :             : {
    2581                 :           8 :     char       *query = text_to_cstring(txt);
    2582                 :             :     TSVectorStat *stat;
    2583                 :             :     bool        isnull;
    2584                 :             :     Portal      portal;
    2585                 :             :     SPIPlanPtr  plan;
    2586                 :             : 
    2587         [ -  + ]:           8 :     if ((plan = SPI_prepare(query, 0, NULL)) == NULL)
    2588                 :             :         /* internal error */
    2589         [ #  # ]:           0 :         elog(ERROR, "SPI_prepare(\"%s\") failed", query);
    2590                 :             : 
    2591         [ -  + ]:           8 :     if ((portal = SPI_cursor_open(NULL, plan, NULL, NULL, true)) == NULL)
    2592                 :             :         /* internal error */
    2593         [ #  # ]:           0 :         elog(ERROR, "SPI_cursor_open(\"%s\") failed", query);
    2594                 :             : 
    2595                 :           8 :     SPI_cursor_fetch(portal, true, 100);
    2596                 :             : 
    2597         [ +  - ]:           8 :     if (SPI_tuptable == NULL ||
    2598         [ +  - ]:           8 :         SPI_tuptable->tupdesc->natts != 1 ||
    2599         [ -  + ]:           8 :         !IsBinaryCoercible(SPI_gettypeid(SPI_tuptable->tupdesc, 1),
    2600                 :             :                            TSVECTOROID))
    2601         [ #  # ]:           0 :         ereport(ERROR,
    2602                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    2603                 :             :                  errmsg("ts_stat query must return one tsvector column")));
    2604                 :             : 
    2605                 :           8 :     stat = MemoryContextAllocZero(persistentContext, sizeof(TSVectorStat));
    2606                 :           8 :     stat->maxdepth = 1;
    2607                 :             : 
    2608         [ +  + ]:           8 :     if (ws)
    2609                 :             :     {
    2610                 :             :         char       *buf;
    2611                 :             :         const char *end;
    2612                 :             : 
    2613                 :           4 :         buf = VARDATA_ANY(ws);
    2614                 :           4 :         end = buf + VARSIZE_ANY_EXHDR(ws);
    2615         [ +  + ]:          12 :         while (buf < end)
    2616                 :             :         {
    2617                 :           8 :             int         len = pg_mblen_range(buf, end);
    2618                 :             : 
    2619         [ +  - ]:           8 :             if (len == 1)
    2620                 :             :             {
    2621   [ +  +  -  -  :           8 :                 switch (*buf)
                      - ]
    2622                 :             :                 {
    2623                 :           4 :                     case 'A':
    2624                 :             :                     case 'a':
    2625                 :           4 :                         stat->weight |= 1 << 3;
    2626                 :           4 :                         break;
    2627                 :           4 :                     case 'B':
    2628                 :             :                     case 'b':
    2629                 :           4 :                         stat->weight |= 1 << 2;
    2630                 :           4 :                         break;
    2631                 :           0 :                     case 'C':
    2632                 :             :                     case 'c':
    2633                 :           0 :                         stat->weight |= 1 << 1;
    2634                 :           0 :                         break;
    2635                 :           0 :                     case 'D':
    2636                 :             :                     case 'd':
    2637                 :           0 :                         stat->weight |= 1;
    2638                 :           0 :                         break;
    2639                 :           0 :                     default:
    2640                 :           0 :                         stat->weight |= 0;
    2641                 :             :                 }
    2642                 :             :             }
    2643                 :           8 :             buf += len;
    2644                 :             :         }
    2645                 :             :     }
    2646                 :             : 
    2647         [ +  + ]:          56 :     while (SPI_processed > 0)
    2648                 :             :     {
    2649                 :             :         uint64      i;
    2650                 :             : 
    2651         [ +  + ]:        4120 :         for (i = 0; i < SPI_processed; i++)
    2652                 :             :         {
    2653                 :        4072 :             Datum       data = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull);
    2654                 :             : 
    2655         [ +  - ]:        4072 :             if (!isnull)
    2656                 :        4072 :                 stat = ts_accum(persistentContext, stat, data);
    2657                 :             :         }
    2658                 :             : 
    2659                 :          48 :         SPI_freetuptable(SPI_tuptable);
    2660                 :          48 :         SPI_cursor_fetch(portal, true, 100);
    2661                 :             :     }
    2662                 :             : 
    2663                 :           8 :     SPI_freetuptable(SPI_tuptable);
    2664                 :           8 :     SPI_cursor_close(portal);
    2665                 :           8 :     SPI_freeplan(plan);
    2666                 :           8 :     pfree(query);
    2667                 :             : 
    2668                 :           8 :     return stat;
    2669                 :             : }
    2670                 :             : 
    2671                 :             : Datum
    2672                 :        4576 : ts_stat1(PG_FUNCTION_ARGS)
    2673                 :             : {
    2674                 :             :     FuncCallContext *funcctx;
    2675                 :             :     Datum       result;
    2676                 :             : 
    2677         [ +  + ]:        4576 :     if (SRF_IS_FIRSTCALL())
    2678                 :             :     {
    2679                 :             :         TSVectorStat *stat;
    2680                 :           4 :         text       *txt = PG_GETARG_TEXT_PP(0);
    2681                 :             : 
    2682                 :           4 :         funcctx = SRF_FIRSTCALL_INIT();
    2683                 :           4 :         SPI_connect();
    2684                 :           4 :         stat = ts_stat_sql(funcctx->multi_call_memory_ctx, txt, NULL);
    2685         [ -  + ]:           4 :         PG_FREE_IF_COPY(txt, 0);
    2686                 :           4 :         ts_setup_firstcall(fcinfo, funcctx, stat);
    2687                 :           4 :         SPI_finish();
    2688                 :             :     }
    2689                 :             : 
    2690                 :        4576 :     funcctx = SRF_PERCALL_SETUP();
    2691         [ +  + ]:        4576 :     if ((result = ts_process_call(funcctx)) != (Datum) 0)
    2692                 :        4572 :         SRF_RETURN_NEXT(funcctx, result);
    2693                 :           4 :     SRF_RETURN_DONE(funcctx);
    2694                 :             : }
    2695                 :             : 
    2696                 :             : Datum
    2697                 :           8 : ts_stat2(PG_FUNCTION_ARGS)
    2698                 :             : {
    2699                 :             :     FuncCallContext *funcctx;
    2700                 :             :     Datum       result;
    2701                 :             : 
    2702         [ +  + ]:           8 :     if (SRF_IS_FIRSTCALL())
    2703                 :             :     {
    2704                 :             :         TSVectorStat *stat;
    2705                 :           4 :         text       *txt = PG_GETARG_TEXT_PP(0);
    2706                 :           4 :         text       *ws = PG_GETARG_TEXT_PP(1);
    2707                 :             : 
    2708                 :           4 :         funcctx = SRF_FIRSTCALL_INIT();
    2709                 :           4 :         SPI_connect();
    2710                 :           4 :         stat = ts_stat_sql(funcctx->multi_call_memory_ctx, txt, ws);
    2711         [ -  + ]:           4 :         PG_FREE_IF_COPY(txt, 0);
    2712         [ -  + ]:           4 :         PG_FREE_IF_COPY(ws, 1);
    2713                 :           4 :         ts_setup_firstcall(fcinfo, funcctx, stat);
    2714                 :           4 :         SPI_finish();
    2715                 :             :     }
    2716                 :             : 
    2717                 :           8 :     funcctx = SRF_PERCALL_SETUP();
    2718         [ +  + ]:           8 :     if ((result = ts_process_call(funcctx)) != (Datum) 0)
    2719                 :           4 :         SRF_RETURN_NEXT(funcctx, result);
    2720                 :           4 :     SRF_RETURN_DONE(funcctx);
    2721                 :             : }
    2722                 :             : 
    2723                 :             : 
    2724                 :             : /*
    2725                 :             :  * Triggers for automatic update of a tsvector column from text column(s)
    2726                 :             :  *
    2727                 :             :  * Trigger arguments are either
    2728                 :             :  *      name of tsvector col, name of tsconfig to use, name(s) of text col(s)
    2729                 :             :  *      name of tsvector col, name of regconfig col, name(s) of text col(s)
    2730                 :             :  * ie, tsconfig can either be specified by name, or indirectly as the
    2731                 :             :  * contents of a regconfig field in the row.  If the name is used, it must
    2732                 :             :  * be explicitly schema-qualified.
    2733                 :             :  */
    2734                 :             : Datum
    2735                 :          12 : tsvector_update_trigger_byid(PG_FUNCTION_ARGS)
    2736                 :             : {
    2737                 :          12 :     return tsvector_update_trigger(fcinfo, false);
    2738                 :             : }
    2739                 :             : 
    2740                 :             : Datum
    2741                 :           0 : tsvector_update_trigger_bycolumn(PG_FUNCTION_ARGS)
    2742                 :             : {
    2743                 :           0 :     return tsvector_update_trigger(fcinfo, true);
    2744                 :             : }
    2745                 :             : 
    2746                 :             : static Datum
    2747                 :          12 : tsvector_update_trigger(PG_FUNCTION_ARGS, bool config_column)
    2748                 :             : {
    2749                 :             :     TriggerData *trigdata;
    2750                 :             :     Trigger    *trigger;
    2751                 :             :     Relation    rel;
    2752                 :          12 :     HeapTuple   rettuple = NULL;
    2753                 :             :     int         tsvector_attr_num,
    2754                 :             :                 i;
    2755                 :             :     ParsedText  prs;
    2756                 :             :     Datum       datum;
    2757                 :             :     bool        isnull;
    2758                 :             :     text       *txt;
    2759                 :             :     Oid         cfgId;
    2760                 :             :     bool        update_needed;
    2761                 :             : 
    2762                 :             :     /* Check call context */
    2763   [ +  -  -  + ]:          12 :     if (!CALLED_AS_TRIGGER(fcinfo)) /* internal error */
    2764         [ #  # ]:           0 :         elog(ERROR, "tsvector_update_trigger: not fired by trigger manager");
    2765                 :             : 
    2766                 :          12 :     trigdata = (TriggerData *) fcinfo->context;
    2767         [ -  + ]:          12 :     if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
    2768         [ #  # ]:           0 :         elog(ERROR, "tsvector_update_trigger: must be fired for row");
    2769         [ -  + ]:          12 :     if (!TRIGGER_FIRED_BEFORE(trigdata->tg_event))
    2770         [ #  # ]:           0 :         elog(ERROR, "tsvector_update_trigger: must be fired BEFORE event");
    2771                 :             : 
    2772         [ +  + ]:          12 :     if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
    2773                 :             :     {
    2774                 :           8 :         rettuple = trigdata->tg_trigtuple;
    2775                 :           8 :         update_needed = true;
    2776                 :             :     }
    2777         [ +  - ]:           4 :     else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
    2778                 :             :     {
    2779                 :           4 :         rettuple = trigdata->tg_newtuple;
    2780                 :           4 :         update_needed = false;  /* computed below */
    2781                 :             :     }
    2782                 :             :     else
    2783         [ #  # ]:           0 :         elog(ERROR, "tsvector_update_trigger: must be fired for INSERT or UPDATE");
    2784                 :             : 
    2785                 :          12 :     trigger = trigdata->tg_trigger;
    2786                 :          12 :     rel = trigdata->tg_relation;
    2787                 :             : 
    2788         [ -  + ]:          12 :     if (trigger->tgnargs < 3)
    2789         [ #  # ]:           0 :         elog(ERROR, "tsvector_update_trigger: arguments must be tsvector_field, ts_config, text_field1, ...)");
    2790                 :             : 
    2791                 :             :     /* Find the target tsvector column */
    2792                 :          12 :     tsvector_attr_num = SPI_fnumber(rel->rd_att, trigger->tgargs[0]);
    2793         [ -  + ]:          12 :     if (tsvector_attr_num == SPI_ERROR_NOATTRIBUTE)
    2794         [ #  # ]:           0 :         ereport(ERROR,
    2795                 :             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    2796                 :             :                  errmsg("tsvector column \"%s\" does not exist",
    2797                 :             :                         trigger->tgargs[0])));
    2798                 :             :     /* This will effectively reject system columns, so no separate test: */
    2799         [ -  + ]:          12 :     if (!IsBinaryCoercible(SPI_gettypeid(rel->rd_att, tsvector_attr_num),
    2800                 :             :                            TSVECTOROID))
    2801         [ #  # ]:           0 :         ereport(ERROR,
    2802                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    2803                 :             :                  errmsg("column \"%s\" is not of type %s",
    2804                 :             :                         trigger->tgargs[0], "tsvector")));
    2805                 :             : 
    2806                 :             :     /* Find the configuration to use */
    2807         [ -  + ]:          12 :     if (config_column)
    2808                 :             :     {
    2809                 :             :         int         config_attr_num;
    2810                 :             : 
    2811                 :           0 :         config_attr_num = SPI_fnumber(rel->rd_att, trigger->tgargs[1]);
    2812         [ #  # ]:           0 :         if (config_attr_num == SPI_ERROR_NOATTRIBUTE)
    2813         [ #  # ]:           0 :             ereport(ERROR,
    2814                 :             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    2815                 :             :                      errmsg("configuration column \"%s\" does not exist",
    2816                 :             :                             trigger->tgargs[1])));
    2817         [ #  # ]:           0 :         if (!IsBinaryCoercible(SPI_gettypeid(rel->rd_att, config_attr_num),
    2818                 :             :                                REGCONFIGOID))
    2819         [ #  # ]:           0 :             ereport(ERROR,
    2820                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2821                 :             :                      errmsg("column \"%s\" is not of type %s",
    2822                 :             :                             trigger->tgargs[1], "regconfig")));
    2823                 :             : 
    2824                 :           0 :         datum = SPI_getbinval(rettuple, rel->rd_att, config_attr_num, &isnull);
    2825         [ #  # ]:           0 :         if (isnull)
    2826         [ #  # ]:           0 :             ereport(ERROR,
    2827                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    2828                 :             :                      errmsg("configuration column \"%s\" must not be null",
    2829                 :             :                             trigger->tgargs[1])));
    2830                 :           0 :         cfgId = DatumGetObjectId(datum);
    2831                 :             :     }
    2832                 :             :     else
    2833                 :             :     {
    2834                 :             :         List       *names;
    2835                 :             : 
    2836                 :          12 :         names = stringToQualifiedNameList(trigger->tgargs[1], NULL);
    2837                 :             :         /* require a schema so that results are not search path dependent */
    2838         [ -  + ]:          12 :         if (list_length(names) < 2)
    2839         [ #  # ]:           0 :             ereport(ERROR,
    2840                 :             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    2841                 :             :                      errmsg("text search configuration name \"%s\" must be schema-qualified",
    2842                 :             :                             trigger->tgargs[1])));
    2843                 :          12 :         cfgId = get_ts_config_oid(names, false);
    2844                 :             :     }
    2845                 :             : 
    2846                 :             :     /* initialize parse state */
    2847                 :          12 :     prs.lenwords = 32;
    2848                 :          12 :     prs.curwords = 0;
    2849                 :          12 :     prs.pos = 0;
    2850                 :          12 :     prs.words = palloc_array(ParsedWord, prs.lenwords);
    2851                 :             : 
    2852                 :             :     /* find all words in indexable column(s) */
    2853         [ +  + ]:          24 :     for (i = 2; i < trigger->tgnargs; i++)
    2854                 :             :     {
    2855                 :             :         int         numattr;
    2856                 :             : 
    2857                 :          12 :         numattr = SPI_fnumber(rel->rd_att, trigger->tgargs[i]);
    2858         [ -  + ]:          12 :         if (numattr == SPI_ERROR_NOATTRIBUTE)
    2859         [ #  # ]:           0 :             ereport(ERROR,
    2860                 :             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    2861                 :             :                      errmsg("column \"%s\" does not exist",
    2862                 :             :                             trigger->tgargs[i])));
    2863         [ -  + ]:          12 :         if (!IsBinaryCoercible(SPI_gettypeid(rel->rd_att, numattr), TEXTOID))
    2864         [ #  # ]:           0 :             ereport(ERROR,
    2865                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2866                 :             :                      errmsg("column \"%s\" is not of a character type",
    2867                 :             :                             trigger->tgargs[i])));
    2868                 :             : 
    2869         [ +  + ]:          12 :         if (bms_is_member(numattr - FirstLowInvalidHeapAttributeNumber, trigdata->tg_updatedcols))
    2870                 :           4 :             update_needed = true;
    2871                 :             : 
    2872                 :          12 :         datum = SPI_getbinval(rettuple, rel->rd_att, numattr, &isnull);
    2873         [ +  + ]:          12 :         if (isnull)
    2874                 :           4 :             continue;
    2875                 :             : 
    2876                 :           8 :         txt = DatumGetTextPP(datum);
    2877                 :             : 
    2878                 :           8 :         parsetext(cfgId, &prs, VARDATA_ANY(txt), VARSIZE_ANY_EXHDR(txt));
    2879                 :             : 
    2880         [ -  + ]:           8 :         if (txt != (text *) DatumGetPointer(datum))
    2881                 :           0 :             pfree(txt);
    2882                 :             :     }
    2883                 :             : 
    2884         [ +  - ]:          12 :     if (update_needed)
    2885                 :             :     {
    2886                 :             :         /* make tsvector value */
    2887                 :          12 :         datum = TSVectorGetDatum(make_tsvector(&prs));
    2888                 :          12 :         isnull = false;
    2889                 :             : 
    2890                 :             :         /* and insert it into tuple */
    2891                 :          12 :         rettuple = heap_modify_tuple_by_cols(rettuple, rel->rd_att,
    2892                 :             :                                              1, &tsvector_attr_num,
    2893                 :             :                                              &datum, &isnull);
    2894                 :             : 
    2895                 :          12 :         pfree(DatumGetPointer(datum));
    2896                 :             :     }
    2897                 :             : 
    2898                 :          12 :     return PointerGetDatum(rettuple);
    2899                 :             : }
        

Generated by: LCOV version 2.0-1