LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - tsvector_op.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 88.8 % 1162 1032 130 4 1028 5
Current Date: 2026-08-27 14:31:44 +0300 Functions: 84.9 % 53 45 8 3 42
Baseline: lcov-20260827-baseline Branches: 66.8 % 800 534 266 534
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 81.8 % 11 9 2 4 5
(30,360] days: 85.2 % 27 23 4 23
(360..) days: 89.0 % 1124 1000 124 1000
Function coverage date bins:
(30,360] days: 100.0 % 4 4 4
(360..) days: 83.7 % 49 41 8 3 38
Branch coverage date bins:
(7,30] days: 40.0 % 10 4 6 4
(30,360] days: 25.0 % 12 3 9 3
(360..) days: 67.7 % 778 527 251 527

 Age         Owner                    Branch data    TLA  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
  301 peter@eisentraut.org       86                 :CBC         261 : silly_cmp_tsvector(const TSVectorData *a, const TSVectorData *b)
                                 87                 :                : {
 6946 tgl@sss.pgh.pa.us          88         [ -  + ]:            261 :     if (VARSIZE(a) < VARSIZE(b))
 6946 tgl@sss.pgh.pa.us          89                 :UBC           0 :         return -1;
 6946 tgl@sss.pgh.pa.us          90         [ -  + ]:CBC         261 :     else if (VARSIZE(a) > VARSIZE(b))
 6946 tgl@sss.pgh.pa.us          91                 :UBC           0 :         return 1;
 6946 tgl@sss.pgh.pa.us          92         [ -  + ]:CBC         261 :     else if (a->size < b->size)
 6946 tgl@sss.pgh.pa.us          93                 :UBC           0 :         return -1;
 6946 tgl@sss.pgh.pa.us          94         [ -  + ]:CBC         261 :     else if (a->size > b->size)
 6946 tgl@sss.pgh.pa.us          95                 :UBC           0 :         return 1;
                                 96                 :                :     else
                                 97                 :                :     {
  301 peter@eisentraut.org       98                 :CBC         261 :         const WordEntry *aptr = ARRPTR(a);
                                 99                 :            261 :         const WordEntry *bptr = ARRPTR(b);
 6946 tgl@sss.pgh.pa.us         100                 :            261 :         int         i = 0;
                                101                 :                :         int         res;
                                102                 :                : 
                                103                 :                : 
                                104         [ +  + ]:            296 :         for (i = 0; i < a->size; i++)
                                105                 :                :         {
                                106         [ -  + ]:            263 :             if (aptr->haspos != bptr->haspos)
                                107                 :                :             {
 6946 tgl@sss.pgh.pa.us         108         [ #  # ]:UBC           0 :                 return (aptr->haspos > bptr->haspos) ? -1 : 1;
                                109                 :                :             }
 6286 bruce@momjian.us          110         [ +  + ]:CBC         263 :             else if ((res = tsCompareString(STRPTR(a) + aptr->pos, aptr->len, STRPTR(b) + bptr->pos, bptr->len, false)) != 0)
                                111                 :                :             {
 6946 tgl@sss.pgh.pa.us         112                 :            228 :                 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))
                                              -  + ]
 6946 tgl@sss.pgh.pa.us         121   [ #  #  #  #  :UBC           0 :                     return (POSDATALEN(a, aptr) > POSDATALEN(b, bptr)) ? -1 : 1;
                                              #  # ]
                                122                 :                : 
 6946 tgl@sss.pgh.pa.us         123   [ +  -  +  + ]:CBC          64 :                 for (j = 0; j < POSDATALEN(a, aptr); j++)
                                124                 :                :                 {
                                125         [ -  + ]:             32 :                     if (WEP_GETPOS(*ap) != WEP_GETPOS(*bp))
                                126                 :                :                     {
 6946 tgl@sss.pgh.pa.us         127         [ #  # ]:UBC           0 :                         return (WEP_GETPOS(*ap) > WEP_GETPOS(*bp)) ? -1 : 1;
                                128                 :                :                     }
 6946 tgl@sss.pgh.pa.us         129         [ -  + ]:CBC          32 :                     else if (WEP_GETWEIGHT(*ap) != WEP_GETWEIGHT(*bp))
                                130                 :                :                     {
 6946 tgl@sss.pgh.pa.us         131         [ #  # ]:UBC           0 :                         return (WEP_GETWEIGHT(*ap) > WEP_GETWEIGHT(*bp)) ? -1 : 1;
                                132                 :                :                     }
 6946 tgl@sss.pgh.pa.us         133                 :CBC          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                 :                : 
 6946 tgl@sss.pgh.pa.us         159   [ #  #  #  # ]:UBC           0 : TSVECTORCMPFUNC(lt, <, BOOL);
                                160   [ #  #  #  # ]:              0 : TSVECTORCMPFUNC(le, <=, BOOL);
 6946 tgl@sss.pgh.pa.us         161   [ -  +  -  + ]:CBC           1 : TSVECTORCMPFUNC(eq, ==, BOOL);
 6946 tgl@sss.pgh.pa.us         162   [ #  #  #  # ]:UBC           0 : TSVECTORCMPFUNC(ge, >=, BOOL);
                                163   [ #  #  #  # ]:              0 : TSVECTORCMPFUNC(gt, >, BOOL);
                                164   [ #  #  #  # ]:              0 : TSVECTORCMPFUNC(ne, !=, BOOL);
 6946 tgl@sss.pgh.pa.us         165   [ -  +  -  + ]:CBC         260 : 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++)
 6929 teodor@sigaev.ru          180                 :            188 :         len += arrin[i].len;
                                181                 :                : 
 6946 tgl@sss.pgh.pa.us         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);
 6929 teodor@sigaev.ru          194                 :            188 :         cur += arrout[i].len;
                                195                 :                :     }
                                196                 :                : 
 6946 tgl@sss.pgh.pa.us         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);
 5176 peter_e@gmx.net           205                 :              7 :     int32       ret = in->size;
                                206                 :                : 
 6946 tgl@sss.pgh.pa.us         207         [ -  + ]:              7 :     PG_FREE_IF_COPY(in, 0);
                                208                 :              7 :     PG_RETURN_INT32(ret);
                                209                 :                : }
                                210                 :                : 
                                211                 :                : static int
   84                           212                 :             48 : parse_weight(char cw)
                                213                 :                : {
                                214                 :                :     int         w;
                                215                 :                : 
 6946                           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;
 6946 tgl@sss.pgh.pa.us         230                 :UBC           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 */
   84                           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                 :                :     }
   84 tgl@sss.pgh.pa.us         246                 :CBC          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                 :                : 
 6946                           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
 3821 teodor@sigaev.ru          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                 :                : 
   84 tgl@sss.pgh.pa.us         305                 :             20 :     weight = parse_weight(char_weight);
                                306                 :                : 
 3821 teodor@sigaev.ru          307                 :             20 :     tsout = (TSVector) palloc(VARSIZE(tsin));
                                308                 :             20 :     memcpy(tsout, tsin, VARSIZE(tsin));
                                309                 :             20 :     entry = ARRPTR(tsout);
                                310                 :                : 
 1518 peter@eisentraut.org      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                 :                :      */
 3821 teodor@sigaev.ru          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])
 1755 tgl@sss.pgh.pa.us         326                 :              5 :             continue;
                                327                 :                : 
  387 peter@eisentraut.org      328                 :             35 :         lex = VARDATA(DatumGetPointer(dlexemes[i]));
                                329                 :             35 :         lex_len = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
 3821 teodor@sigaev.ru          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
 6860 bruce@momjian.us          360                 :             10 : add_pos(TSVector src, WordEntry *srcptr,
                                361                 :                :         TSVector dest, WordEntry *destptr,
                                362                 :                :         int32 maxpos)
                                363                 :                : {
 6925 teodor@sigaev.ru          364                 :             10 :     uint16     *clen = &_POSVECPTR(dest, destptr)->npos;
                                365                 :                :     int         i;
 6946 tgl@sss.pgh.pa.us         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)
 6946 tgl@sss.pgh.pa.us         372                 :UBC           0 :         *clen = 0;
                                373                 :                : 
 6946 tgl@sss.pgh.pa.us         374                 :CBC          10 :     startlen = *clen;
 6883                           375                 :             10 :     for (i = 0;
                                376   [ +  +  +  - ]:             20 :          i < slen && *clen < MAXNUMPOS &&
 6860 bruce@momjian.us          377   [ +  +  +  - ]:             10 :          (*clen == 0 || WEP_GETPOS(dpos[*clen - 1]) != MAXENTRYPOS - 1);
 6883 tgl@sss.pgh.pa.us         378                 :             10 :          i++)
                                379                 :                :     {
 6946                           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
  301 peter@eisentraut.org      396                 :            165 : tsvector_bsearch(const TSVectorData *tsv, char *lexeme, int lexeme_len)
                                397                 :                : {
                                398                 :            165 :     const WordEntry *arrin = ARRPTR(tsv);
 3821 teodor@sigaev.ru          399                 :            165 :     int         StopLow = 0,
                                400                 :            165 :                 StopHigh = tsv->size,
                                401                 :                :                 StopMiddle,
                                402                 :                :                 cmp;
                                403                 :                : 
                                404         [ +  + ]:            435 :     while (StopLow < StopHigh)
                                405                 :                :     {
 3731 rhaas@postgresql.org      406                 :            385 :         StopMiddle = (StopLow + StopHigh) / 2;
                                407                 :                : 
 3821 teodor@sigaev.ru          408                 :            385 :         cmp = tsCompareString(lexeme, lexeme_len,
 3731 rhaas@postgresql.org      409                 :            385 :                               STRPTR(tsv) + arrin[StopMiddle].pos,
                                410                 :            385 :                               arrin[StopMiddle].len,
                                411                 :                :                               false);
                                412                 :                : 
 3821 teodor@sigaev.ru          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
 3674 tgl@sss.pgh.pa.us         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                 :                : 
  923 nathan@postgresql.or      434                 :             65 :     return pg_cmp_s32(a, b);
                                435                 :                : }
                                436                 :                : 
                                437                 :                : static int
 3674 tgl@sss.pgh.pa.us         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);
  387 peter@eisentraut.org      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                 :                : 
 3674 tgl@sss.pgh.pa.us         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
 3821 teodor@sigaev.ru          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                 :                :     {
 3674 tgl@sss.pgh.pa.us         480                 :             25 :         qsort(indices_to_delete, indices_count, sizeof(int), compare_int);
 2485 tmunro@postgresql.or      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                 :                :      */
 3674 tgl@sss.pgh.pa.us         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);
 3821 teodor@sigaev.ru          500                 :             55 :     dataout = STRPTR(tsout);
 3674 tgl@sss.pgh.pa.us         501                 :             55 :     curoff = 0;
 3821 teodor@sigaev.ru          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                 :                :          */
 3731 rhaas@postgresql.org      509   [ +  +  +  + ]:            275 :         if (k < indices_count && i == indices_to_delete[k])
                                510                 :                :         {
 3821 teodor@sigaev.ru          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                 :                :         {
 3674 tgl@sss.pgh.pa.us         523         [ +  - ]:            130 :             int         len = POSDATALEN(tsv, arrin + i) * sizeof(WordEntryPos)
 1196                           524                 :            130 :                 + sizeof(uint16);
                                525                 :                : 
 3821 teodor@sigaev.ru          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         [ -  + ]:             55 :     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;
 3455 noah@leadboat.com         556                 :             30 :     text       *tlexeme = PG_GETARG_TEXT_PP(1);
                                557                 :             30 :     char       *lexeme = VARDATA_ANY(tlexeme);
 3821 teodor@sigaev.ru          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                 :                : 
 1518 peter@eisentraut.org      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                 :                :      */
   10 michael@paquier.xyz       595                 :GNC          35 :     skip_indices = palloc0_array(int, nlex);
 3821 teodor@sigaev.ru          596         [ +  + ]:CBC         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])
 1755 tgl@sss.pgh.pa.us         604                 :              5 :             continue;
                                605                 :                : 
  387 peter@eisentraut.org      606                 :            100 :         lex = VARDATA(DatumGetPointer(dlexemes[i]));
                                607                 :            100 :         lex_len = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
 3821 teodor@sigaev.ru          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                 :                : 
 2837 andres@anarazel.de        643                 :             20 :         tupdesc = CreateTemplateTupleDesc(3);
 3821 teodor@sigaev.ru          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);
 1345 michael@paquier.xyz       650         [ -  + ]:             20 :         if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
 1345 michael@paquier.xyz       651         [ #  # ]:UBC           0 :             elog(ERROR, "return type must be a row type");
  164 drowley@postgresql.o      652                 :CBC          20 :         TupleDescFinalize(tupdesc);
 1345 michael@paquier.xyz       653                 :             20 :         funcctx->tuple_desc = tupdesc;
                                654                 :                : 
 3821 teodor@sigaev.ru          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                 :                : 
 2401 alvherre@alvh.no-ip.      673                 :            100 :         values[0] = PointerGetDatum(cstring_to_text_with_len(data + arrin[i].pos, arrin[i].len));
                                674                 :                : 
 3821 teodor@sigaev.ru          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);
   10 michael@paquier.xyz       688                 :GNC          60 :             positions = palloc_array(Datum, posv->npos);
                                689                 :             60 :             weights = palloc_array(Datum, posv->npos);
 3821 teodor@sigaev.ru          690         [ +  + ]:CBC         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]);
 2401 alvherre@alvh.no-ip.      694                 :            108 :                 weights[j] = PointerGetDatum(cstring_to_text_with_len(&weight,
                                695                 :                :                                                                       1));
                                696                 :                :             }
                                697                 :                : 
 1518 peter@eisentraut.org      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                 :                :         {
 3821 teodor@sigaev.ru          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                 :                : {
 3731 rhaas@postgresql.org      721                 :             10 :     TSVector    tsin = PG_GETARG_TSVECTOR(0);
                                722                 :             10 :     WordEntry  *arrin = ARRPTR(tsin);
                                723                 :                :     Datum      *elements;
                                724                 :                :     int         i;
                                725                 :                :     ArrayType  *array;
                                726                 :                : 
   17 tgl@sss.pgh.pa.us         727                 :             10 :     elements = palloc_array(Datum, tsin->size);
                                728                 :                : 
 3821 teodor@sigaev.ru          729         [ +  + ]:             60 :     for (i = 0; i < tsin->size; i++)
                                730                 :                :     {
 2401 alvherre@alvh.no-ip.      731                 :             50 :         elements[i] = PointerGetDatum(cstring_to_text_with_len(STRPTR(tsin) + arrin[i].pos,
                                732                 :                :                                                                arrin[i].len));
                                733                 :                :     }
                                734                 :                : 
 1518 peter@eisentraut.org      735                 :             10 :     array = construct_array_builtin(elements, tsin->size, TEXTOID);
                                736                 :                : 
 3821 teodor@sigaev.ru          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                 :                : 
 1518 peter@eisentraut.org      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                 :                :      */
 3821 teodor@sigaev.ru          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                 :                : 
   17 tgl@sss.pgh.pa.us         774                 :             81 :         toklen = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
                                775         [ +  + ]:             81 :         if (toklen == 0)
 1755                           776         [ +  - ]:              4 :             ereport(ERROR,
                                777                 :                :                     (errcode(ERRCODE_ZERO_LENGTH_CHARACTER_STRING),
                                778                 :                :                      errmsg("lexeme array may not contain empty strings")));
   14                           779         [ -  + ]:             77 :         if (toklen > MAXSTRLEN)
   17 tgl@sss.pgh.pa.us         780         [ #  # ]:UBC           0 :             ereport(ERROR,
                                781                 :                :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                782                 :                :                      errmsg("word is too long (%d bytes, max %d bytes)",
                                783                 :                :                             toklen,
                                784                 :                :                             MAXSTRLEN)));
                                785                 :                :     }
                                786                 :                : 
                                787                 :                :     /* Sort and de-dup, because this is required for a valid tsvector. */
 3674 tgl@sss.pgh.pa.us         788         [ +  - ]:CBC          10 :     if (nitems > 1)
                                789                 :                :     {
                                790                 :             10 :         qsort(dlexemes, nitems, sizeof(Datum), compare_text_lexemes);
 2485 tmunro@postgresql.or      791                 :             10 :         nitems = qunique(dlexemes, nitems, sizeof(Datum),
                                792                 :                :                          compare_text_lexemes);
                                793                 :                :     }
                                794                 :                : 
                                795                 :                :     /* Calculate space needed for surviving lexemes. */
 3674 tgl@sss.pgh.pa.us         796         [ +  + ]:             50 :     for (i = 0; i < nitems; i++)
  387 peter@eisentraut.org      797                 :             40 :         datalen += VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
   17 tgl@sss.pgh.pa.us         798         [ -  + ]:             10 :     if (datalen > MAXSTRPOS)
   17 tgl@sss.pgh.pa.us         799         [ #  # ]:UBC           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)));
 3821 teodor@sigaev.ru          803                 :CBC          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                 :                :     {
  387 peter@eisentraut.org      814                 :             40 :         char       *lex = VARDATA(DatumGetPointer(dlexemes[i]));
                                815                 :             40 :         int         lex_len = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
                                816                 :                : 
 3821 teodor@sigaev.ru          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;
 3767                           846                 :             14 :     int         cur_pos = 0;
                                847                 :             14 :     char        mask = 0;
                                848                 :                : 
 1518 peter@eisentraut.org      849                 :             14 :     deconstruct_array_builtin(weights, CHAROID, &dweights, &nulls, &nweights);
                                850                 :                : 
 3766 tgl@sss.pgh.pa.us         851         [ +  + ]:             32 :     for (i = 0; i < nweights; i++)
                                852                 :                :     {
                                853                 :                :         char        char_weight;
                                854                 :                : 
 3821 teodor@sigaev.ru          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]);
   84 tgl@sss.pgh.pa.us         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                 :                :      */
 3821 teodor@sigaev.ru          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;
 3731 rhaas@postgresql.org      879                 :             80 :         int         npos = 0;
                                880                 :                :         int         k;
                                881                 :                : 
 3821 teodor@sigaev.ru          882         [ +  + ]:             80 :         if (!arrin[i].haspos)
                                883                 :             25 :             continue;
                                884                 :                : 
 3731 rhaas@postgresql.org      885                 :             55 :         posvin = _POSVECPTR(tsin, arrin + i);
 3821 teodor@sigaev.ru          886                 :             55 :         posvout = (WordEntryPosVector *)
 3731 rhaas@postgresql.org      887                 :             55 :             (dataout + SHORTALIGN(cur_pos + arrin[i].len));
                                888                 :                : 
 3821 teodor@sigaev.ru          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 */
 3768 rhaas@postgresql.org      896         [ +  + ]:             55 :         if (!npos)
 3821 teodor@sigaev.ru          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);
 3731 rhaas@postgresql.org      906         [ +  - ]:             25 :         cur_pos += POSDATALEN(tsout, arrout + j) * sizeof(WordEntryPos) +
                                907                 :                :             sizeof(uint16);
 3821 teodor@sigaev.ru          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
 6946 tgl@sss.pgh.pa.us         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                 :                :      */
 5480                           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                 :                :      */
 6946                           988                 :              9 :     out->size = in1->size + in2->size;
                                989                 :                : 
                                990                 :              9 :     ptr = ARRPTR(out);
 6883                           991                 :              9 :     data = STRPTR(out);
                                992                 :              9 :     dataoff = 0;
 6946                           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;
 6883                          1001                 :              5 :             memcpy(data + dataoff, data1 + ptr1->pos, ptr1->len);
                               1002                 :              5 :             ptr->pos = dataoff;
                               1003                 :              5 :             dataoff += ptr1->len;
 6946                          1004         [ +  - ]:              5 :             if (ptr->haspos)
                               1005                 :                :             {
 6883                          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                 :                : 
 6946                          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;
 6883                          1019                 :              4 :             memcpy(data + dataoff, data2 + ptr2->pos, ptr2->len);
                               1020                 :              4 :             ptr->pos = dataoff;
                               1021                 :              4 :             dataoff += ptr2->len;
 6946                          1022         [ -  + ]:              4 :             if (ptr->haspos)
                               1023                 :                :             {
 6946 tgl@sss.pgh.pa.us        1024                 :UBC           0 :                 int         addlen = add_pos(in2, ptr2, out, ptr, maxpos);
                               1025                 :                : 
                               1026         [ #  # ]:              0 :                 if (addlen == 0)
                               1027                 :              0 :                     ptr->haspos = 0;
                               1028                 :                :                 else
                               1029                 :                :                 {
 6883                          1030                 :              0 :                     dataoff = SHORTALIGN(dataoff);
                               1031                 :              0 :                     dataoff += addlen * sizeof(WordEntryPos) + sizeof(uint16);
                               1032                 :                :                 }
                               1033                 :                :             }
                               1034                 :                : 
 6946 tgl@sss.pgh.pa.us        1035                 :CBC           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;
 6883                          1043                 :              5 :             memcpy(data + dataoff, data1 + ptr1->pos, ptr1->len);
                               1044                 :              5 :             ptr->pos = dataoff;
                               1045                 :              5 :             dataoff += ptr1->len;
 6946                          1046         [ +  - ]:              5 :             if (ptr->haspos)
                               1047                 :                :             {
                               1048         [ +  - ]:              5 :                 if (ptr1->haspos)
                               1049                 :                :                 {
 6883                          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);
 6946                          1053         [ +  - ]:              5 :                     if (ptr2->haspos)
 6883                          1054                 :              5 :                         dataoff += add_pos(in2, ptr2, out, ptr, maxpos) * sizeof(WordEntryPos);
                               1055                 :                :                 }
                               1056                 :                :                 else            /* must have ptr2->haspos */
                               1057                 :                :                 {
 6946 tgl@sss.pgh.pa.us        1058                 :UBC           0 :                     int         addlen = add_pos(in2, ptr2, out, ptr, maxpos);
                               1059                 :                : 
                               1060         [ #  # ]:              0 :                     if (addlen == 0)
                               1061                 :              0 :                         ptr->haspos = 0;
                               1062                 :                :                     else
                               1063                 :                :                     {
 6883                          1064                 :              0 :                         dataoff = SHORTALIGN(dataoff);
                               1065                 :              0 :                         dataoff += addlen * sizeof(WordEntryPos) + sizeof(uint16);
                               1066                 :                :                     }
                               1067                 :                :                 }
                               1068                 :                :             }
                               1069                 :                : 
 6946 tgl@sss.pgh.pa.us        1070                 :CBC           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;
 6883                          1082                 :              4 :         memcpy(data + dataoff, data1 + ptr1->pos, ptr1->len);
                               1083                 :              4 :         ptr->pos = dataoff;
                               1084                 :              4 :         dataoff += ptr1->len;
 6946                          1085         [ +  - ]:              4 :         if (ptr->haspos)
                               1086                 :                :         {
 6883                          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                 :                : 
 6946                          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;
 6883                          1101                 :              5 :         memcpy(data + dataoff, data2 + ptr2->pos, ptr2->len);
                               1102                 :              5 :         ptr->pos = dataoff;
                               1103                 :              5 :         dataoff += ptr2->len;
 6946                          1104         [ +  - ]:              5 :         if (ptr->haspos)
                               1105                 :                :         {
                               1106                 :              5 :             int         addlen = add_pos(in2, ptr2, out, ptr, maxpos);
                               1107                 :                : 
                               1108         [ -  + ]:              5 :             if (addlen == 0)
 6946 tgl@sss.pgh.pa.us        1109                 :UBC           0 :                 ptr->haspos = 0;
                               1110                 :                :             else
                               1111                 :                :             {
 6883 tgl@sss.pgh.pa.us        1112                 :CBC           5 :                 dataoff = SHORTALIGN(dataoff);
                               1113                 :              5 :                 dataoff += addlen * sizeof(WordEntryPos) + sizeof(uint16);
                               1114                 :                :             }
                               1115                 :                :         }
                               1116                 :                : 
 6946                          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                 :                :      */
 6883                          1126         [ -  + ]:              9 :     if (dataoff > MAXSTRPOS)
 6883 tgl@sss.pgh.pa.us        1127         [ #  # ]:UBC           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                 :                :      */
 5480 tgl@sss.pgh.pa.us        1136                 :CBC           9 :     output_size = ptr - ARRPTR(out);
                               1137         [ -  + ]:              9 :     Assert(output_size <= out->size);
                               1138                 :              9 :     out->size = output_size;
 6946                          1139         [ +  + ]:              9 :     if (data != STRPTR(out))
 6883                          1140                 :              5 :         memmove(STRPTR(out), data, dataoff);
 5480                          1141                 :              9 :     output_bytes = CALCDATASIZE(out->size, dataoff);
                               1142         [ -  + ]:              9 :     Assert(output_bytes <= VARSIZE(out));
                               1143                 :              9 :     SET_VARSIZE(out, output_bytes);
                               1144                 :                : 
 6946                          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
 6677                          1156                 :        4200965 : tsCompareString(char *a, int lena, char *b, int lenb, bool prefix)
                               1157                 :                : {
                               1158                 :                :     int         cmp;
                               1159                 :                : 
 6286 bruce@momjian.us         1160         [ +  + ]:        4200965 :     if (lena == 0)
                               1161                 :                :     {
                               1162         [ -  + ]:             30 :         if (prefix)
 5709 tgl@sss.pgh.pa.us        1163                 :UBC           0 :             cmp = 0;            /* empty string is prefix of anything */
                               1164                 :                :         else
 6286 bruce@momjian.us         1165         [ +  - ]:CBC          30 :             cmp = (lenb > 0) ? -1 : 0;
                               1166                 :                :     }
                               1167         [ -  + ]:        4200935 :     else if (lenb == 0)
                               1168                 :                :     {
 6286 bruce@momjian.us         1169                 :UBC           0 :         cmp = (lena > 0) ? 1 : 0;
                               1170                 :                :     }
                               1171                 :                :     else
                               1172                 :                :     {
 1654 tgl@sss.pgh.pa.us        1173                 :CBC     4200935 :         cmp = memcmp(a, b, Min((unsigned int) lena, (unsigned int) lenb));
                               1174                 :                : 
 6286 bruce@momjian.us         1175         [ +  + ]:        4200935 :         if (prefix)
                               1176                 :                :         {
                               1177   [ +  +  -  + ]:          11021 :             if (cmp == 0 && lena > lenb)
 5709 tgl@sss.pgh.pa.us        1178                 :UBC           0 :                 cmp = 1;        /* a is longer, so not a prefix of b */
                               1179                 :                :         }
 5709 tgl@sss.pgh.pa.us        1180   [ +  +  +  + ]:CBC     4189914 :         else if (cmp == 0 && lena != lenb)
                               1181                 :                :         {
 6677                          1182         [ +  + ]:          21678 :             cmp = (lena < lenb) ? -1 : 1;
                               1183                 :                :         }
                               1184                 :                :     }
                               1185                 :                : 
                               1186                 :        4200965 :     return cmp;
                               1187                 :                : }
                               1188                 :                : 
                               1189                 :                : /*
                               1190                 :                :  * Check weight info or/and fill 'data' with the required positions
                               1191                 :                :  */
                               1192                 :                : static TSTernaryValue
 3794 teodor@sigaev.ru         1193                 :          45576 : checkclass_str(CHKVAL *chkval, WordEntry *entry, QueryOperand *val,
                               1194                 :                :                ExecPhraseData *data)
                               1195                 :                : {
 2225 tgl@sss.pgh.pa.us        1196                 :          45576 :     TSTernaryValue result = TS_NO;
                               1197                 :                : 
                               1198   [ +  +  -  + ]:          45576 :     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                 :                :          */
 3794 teodor@sigaev.ru         1208                 :           3160 :         posvec = (WordEntryPosVector *)
                               1209                 :           3160 :             (chkval->values + SHORTALIGN(entry->pos + entry->len));
                               1210                 :                : 
                               1211   [ +  +  +  + ]:           3160 :         if (val->weight && data)
                               1212                 :             40 :         {
 3731 rhaas@postgresql.org     1213                 :             40 :             WordEntryPos *posvec_iter = posvec->pos;
                               1214                 :                :             WordEntryPos *dptr;
                               1215                 :                : 
                               1216                 :                :             /*
                               1217                 :                :              * Filter position information by weights
                               1218                 :                :              */
  260 michael@paquier.xyz      1219                 :             40 :             dptr = data->pos = palloc_array(WordEntryPos, posvec->npos);
 3794 teodor@sigaev.ru         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)
 2225 tgl@sss.pgh.pa.us        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                 :                :         }
 3794 teodor@sigaev.ru         1246         [ +  + ]:           3120 :         else if (val->weight)
                               1247                 :                :         {
 3731 rhaas@postgresql.org     1248                 :            332 :             WordEntryPos *posvec_iter = posvec->pos;
                               1249                 :                : 
                               1250                 :                :             /* Is there a position with a matching weight? */
 3794 teodor@sigaev.ru         1251         [ +  + ]:            503 :             while (posvec_iter < posvec->pos + posvec->npos)
                               1252                 :                :             {
                               1253         [ +  + ]:            372 :                 if (val->weight & (1 << WEP_GETWEIGHT(*posvec_iter)))
                               1254                 :                :                 {
 2225 tgl@sss.pgh.pa.us        1255                 :            201 :                     result = TS_YES;
 3731 rhaas@postgresql.org     1256                 :            201 :                     break;      /* no need to go further */
                               1257                 :                :                 }
                               1258                 :                : 
 3794 teodor@sigaev.ru         1259                 :            171 :                 posvec_iter++;
                               1260                 :                :             }
                               1261                 :                :         }
 2225 tgl@sss.pgh.pa.us        1262         [ +  + ]:           2788 :         else if (data)
                               1263                 :                :         {
 3794 teodor@sigaev.ru         1264                 :           1645 :             data->npos = posvec->npos;
 3731 rhaas@postgresql.org     1265                 :           1645 :             data->pos = posvec->pos;
 3794 teodor@sigaev.ru         1266                 :           1645 :             data->allocated = false;
 2225 tgl@sss.pgh.pa.us        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                 :                : 
 3794 teodor@sigaev.ru         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                 :                : {
 6860 bruce@momjian.us         1301                 :         189554 :     CHKVAL     *chkval = (CHKVAL *) checkval;
 6929 teodor@sigaev.ru         1302                 :         189554 :     WordEntry  *StopLow = chkval->arrb;
                               1303                 :         189554 :     WordEntry  *StopHigh = chkval->arre;
 6677 tgl@sss.pgh.pa.us        1304                 :         189554 :     WordEntry  *StopMiddle = StopHigh;
 2225                          1305                 :         189554 :     TSTernaryValue res = TS_NO;
                               1306                 :                : 
                               1307                 :                :     /* Loop invariant: StopLow <= val < StopHigh */
 6946                          1308         [ +  + ]:        1191598 :     while (StopLow < StopHigh)
                               1309                 :                :     {
                               1310                 :                :         int         difference;
                               1311                 :                : 
                               1312                 :        1037564 :         StopMiddle = StopLow + (StopHigh - StopLow) / 2;
 3794 teodor@sigaev.ru         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                 :                : 
 6946 tgl@sss.pgh.pa.us        1319         [ +  + ]:        1037564 :         if (difference == 0)
                               1320                 :                :         {
                               1321                 :                :             /* Check weight info & fill 'data' with positions */
 3794 teodor@sigaev.ru         1322                 :          35520 :             res = checkclass_str(chkval, StopMiddle, val, data);
 6677 tgl@sss.pgh.pa.us        1323                 :          35520 :             break;
                               1324                 :                :         }
                               1325         [ +  + ]:        1002044 :         else if (difference > 0)
 6946                          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                 :                :      */
 2225                          1338   [ +  +  +  +  :         189554 :     if (val->prefix && (res != TS_YES || data))
                                              +  - ]
                               1339                 :                :     {
 3731 rhaas@postgresql.org     1340                 :          11040 :         WordEntryPos *allpos = NULL;
                               1341                 :          11040 :         int         npos = 0,
                               1342                 :          11040 :                     totalpos = 0;
                               1343                 :                : 
                               1344                 :                :         /* adjust start position for corner case */
 6286 bruce@momjian.us         1345         [ +  + ]:          11040 :         if (StopLow >= StopHigh)
 6677 tgl@sss.pgh.pa.us        1346                 :          11030 :             StopMiddle = StopHigh;
                               1347                 :                : 
                               1348                 :                :         /* we don't try to re-use any data from the initial match */
 2225                          1349         [ +  + ]:          11040 :         if (data)
                               1350                 :                :         {
                               1351         [ -  + ]:             30 :             if (data->allocated)
 2225 tgl@sss.pgh.pa.us        1352                 :UBC           0 :                 pfree(data->pos);
 2225 tgl@sss.pgh.pa.us        1353                 :CBC          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 &&
                                              +  + ]
 3794 teodor@sigaev.ru         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                 :                : 
 2225 tgl@sss.pgh.pa.us        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                 :                :                          */
 2225 tgl@sss.pgh.pa.us        1384                 :UBC           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                 :                : 
 2225 tgl@sss.pgh.pa.us        1393         [ +  + ]:CBC          65 :                     while (npos + data->npos > totalpos)
                               1394                 :                :                     {
 3794 teodor@sigaev.ru         1395         [ +  - ]:             30 :                         if (totalpos == 0)
                               1396                 :                :                         {
                               1397                 :             30 :                             totalpos = 256;
  260 michael@paquier.xyz      1398                 :             30 :                             allpos = palloc_array(WordEntryPos, totalpos);
                               1399                 :                :                         }
                               1400                 :                :                         else
                               1401                 :                :                         {
 3794 teodor@sigaev.ru         1402                 :UBC           0 :                             totalpos *= 2;
  260 michael@paquier.xyz      1403                 :              0 :                             allpos = repalloc_array(allpos, WordEntryPos, totalpos);
                               1404                 :                :                         }
                               1405                 :                :                     }
                               1406                 :                : 
 3794 teodor@sigaev.ru         1407                 :CBC          35 :                     memcpy(allpos + npos, data->pos, sizeof(WordEntryPos) * data->npos);
                               1408                 :             35 :                     npos += data->npos;
                               1409                 :                : 
                               1410                 :                :                     /* don't leak storage from individual matches */
 2225 tgl@sss.pgh.pa.us        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                 :                : 
 6677                          1426                 :          10056 :             StopMiddle++;
                               1427                 :                :         }
                               1428                 :                : 
 2225                          1429   [ +  +  +  - ]:          11040 :         if (data && npos > 0)
                               1430                 :                :         {
                               1431                 :                :             /* Sort and make unique array of found positions */
 3794 teodor@sigaev.ru         1432                 :             30 :             data->pos = allpos;
 2485 tmunro@postgresql.or     1433                 :             30 :             qsort(data->pos, npos, sizeof(WordEntryPos), compareWordEntryPos);
                               1434                 :             30 :             data->npos = qunique(data->pos, npos, sizeof(WordEntryPos),
                               1435                 :                :                                  compareWordEntryPos);
 3794 teodor@sigaev.ru         1436                 :             30 :             data->allocated = true;
 2225 tgl@sss.pgh.pa.us        1437                 :             30 :             res = TS_YES;
                               1438                 :                :         }
                               1439                 :                :     }
                               1440                 :                : 
 6286 bruce@momjian.us         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
 3536 tgl@sss.pgh.pa.us        1472                 :          20111 : 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                 :          20111 :     Lindex = Rindex = 0;
                               1485   [ +  +  +  + ]:          20903 :     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                 :                :                 {
   10 michael@paquier.xyz      1545                 :GNC         261 :                     data->pos = palloc_array(WordEntryPos, max_npos);
 3536 tgl@sss.pgh.pa.us        1546                 :CBC         261 :                     data->allocated = true;
                               1547                 :                :                 }
                               1548                 :            324 :                 data->pos[data->npos++] = output_pos;
                               1549                 :                :             }
                               1550                 :                :             else
                               1551                 :                :             {
                               1552                 :                :                 /*
                               1553                 :                :                  * Exact positions not needed, so return TS_YES as soon as we
                               1554                 :                :                  * know there is at least one.
                               1555                 :                :                  */
 2313                          1556                 :            721 :                 return TS_YES;
                               1557                 :                :             }
                               1558                 :                :         }
                               1559                 :                :     }
                               1560                 :                : 
 3536                          1561   [ +  +  +  + ]:          19390 :     if (data && data->npos > 0)
                               1562                 :                :     {
                               1563                 :                :         /* Let's assert we didn't overrun the array */
                               1564         [ -  + ]:            261 :         Assert(data->npos <= max_npos);
 2313                          1565                 :            261 :         return TS_YES;
                               1566                 :                :     }
                               1567                 :          19129 :     return TS_NO;
                               1568                 :                : }
                               1569                 :                : 
                               1570                 :                : /*
                               1571                 :                :  * Execute tsquery at or below an OP_PHRASE operator.
                               1572                 :                :  *
                               1573                 :                :  * This handles tsquery execution at recursion levels where we need to care
                               1574                 :                :  * about match locations.
                               1575                 :                :  *
                               1576                 :                :  * In addition to the same arguments used for TS_execute, the caller may pass
                               1577                 :                :  * a preinitialized-to-zeroes ExecPhraseData struct, to be filled with lexeme
                               1578                 :                :  * match position info on success.  data == NULL if no position data need be
                               1579                 :                :  * returned.
                               1580                 :                :  * Note: the function assumes data != NULL for operators other than OP_PHRASE.
                               1581                 :                :  * This is OK because an outside call always starts from an OP_PHRASE node,
                               1582                 :                :  * and all internal recursion cases pass data != NULL.
                               1583                 :                :  *
                               1584                 :                :  * The detailed semantics of the match data, given that the function returned
                               1585                 :                :  * TS_YES (successful match), are:
                               1586                 :                :  *
                               1587                 :                :  * npos > 0, negate = false:
                               1588                 :                :  *   query is matched at specified position(s) (and only those positions)
                               1589                 :                :  * npos > 0, negate = true:
                               1590                 :                :  *   query is matched at all positions *except* specified position(s)
                               1591                 :                :  * npos = 0, negate = true:
                               1592                 :                :  *   query is matched at all positions
                               1593                 :                :  * npos = 0, negate = false:
                               1594                 :                :  *   disallowed (this should result in TS_NO or TS_MAYBE, as appropriate)
                               1595                 :                :  *
                               1596                 :                :  * Successful matches also return a "width" value which is the match width in
                               1597                 :                :  * lexemes, less one.  Hence, "width" is zero for simple one-lexeme matches,
                               1598                 :                :  * and is the sum of the phrase operator distances for phrase matches.  Note
                               1599                 :                :  * that when width > 0, the listed positions represent the ends of matches not
                               1600                 :                :  * the starts.  (This unintuitive rule is needed to avoid possibly generating
                               1601                 :                :  * negative positions, which wouldn't fit into the WordEntryPos arrays.)
                               1602                 :                :  *
                               1603                 :                :  * If the TSExecuteCallback function reports that an operand is present
                               1604                 :                :  * but fails to provide position(s) for it, we will return TS_MAYBE when
                               1605                 :                :  * it is possible but not certain that the query is matched.
                               1606                 :                :  *
                               1607                 :                :  * When the function returns TS_NO or TS_MAYBE, it must return npos = 0,
                               1608                 :                :  * negate = false (which is the state initialized by the caller); but the
                               1609                 :                :  * "width" output in such cases is undefined.
                               1610                 :                :  */
                               1611                 :                : static TSTernaryValue
 3541                          1612                 :         469496 : TS_phrase_execute(QueryItem *curitem, void *arg, uint32 flags,
                               1613                 :                :                   TSExecuteCallback chkcond,
                               1614                 :                :                   ExecPhraseData *data)
                               1615                 :                : {
                               1616                 :                :     ExecPhraseData Ldata,
                               1617                 :                :                 Rdata;
                               1618                 :                :     TSTernaryValue lmatch,
                               1619                 :                :                 rmatch;
                               1620                 :                :     int         Loffset,
                               1621                 :                :                 Roffset,
                               1622                 :                :                 maxwidth;
                               1623                 :                : 
                               1624                 :                :     /* since this function recurses, it could be driven to stack overflow */
 3794 teodor@sigaev.ru         1625                 :         469496 :     check_stack_depth();
                               1626                 :                : 
                               1627                 :                :     /* ... and let's check for query cancel while we're at it */
 1375 tgl@sss.pgh.pa.us        1628         [ -  + ]:         469496 :     CHECK_FOR_INTERRUPTS();
                               1629                 :                : 
 3794 teodor@sigaev.ru         1630         [ +  + ]:         469496 :     if (curitem->type == QI_VAL)
 2225 tgl@sss.pgh.pa.us        1631                 :         230995 :         return chkcond(arg, (QueryOperand *) curitem, data);
                               1632                 :                : 
 3536                          1633   [ +  +  +  - ]:         238501 :     switch (curitem->qoperator.oper)
                               1634                 :                :     {
                               1635                 :          80719 :         case OP_NOT:
                               1636                 :                : 
                               1637                 :                :             /*
                               1638                 :                :              * We need not touch data->width, since a NOT operation does not
                               1639                 :                :              * change the match width.
                               1640                 :                :              */
 2225                          1641         [ -  + ]:          80719 :             if (flags & TS_EXEC_SKIP_NOT)
                               1642                 :                :             {
                               1643                 :                :                 /* with SKIP_NOT, report NOT as "match everywhere" */
 3536 tgl@sss.pgh.pa.us        1644   [ #  #  #  # ]:UBC           0 :                 Assert(data->npos == 0 && !data->negate);
                               1645                 :              0 :                 data->negate = true;
 2313                          1646                 :              0 :                 return TS_YES;
                               1647                 :                :             }
 2313 tgl@sss.pgh.pa.us        1648   [ +  +  +  - ]:CBC       80719 :             switch (TS_phrase_execute(curitem + 1, arg, flags, chkcond, data))
                               1649                 :                :             {
                               1650                 :          70568 :                 case TS_NO:
                               1651                 :                :                     /* change "match nowhere" to "match everywhere" */
                               1652   [ +  -  -  + ]:          70568 :                     Assert(data->npos == 0 && !data->negate);
                               1653                 :          70568 :                     data->negate = true;
                               1654                 :          70568 :                     return TS_YES;
                               1655                 :            273 :                 case TS_YES:
                               1656         [ +  + ]:            273 :                     if (data->npos > 0)
                               1657                 :                :                     {
                               1658                 :                :                         /* we have some positions, invert negate flag */
                               1659                 :            268 :                         data->negate = !data->negate;
                               1660                 :            268 :                         return TS_YES;
                               1661                 :                :                     }
                               1662         [ +  - ]:              5 :                     else if (data->negate)
                               1663                 :                :                     {
                               1664                 :                :                         /* change "match everywhere" to "match nowhere" */
                               1665                 :              5 :                         data->negate = false;
                               1666                 :              5 :                         return TS_NO;
                               1667                 :                :                     }
                               1668                 :                :                     /* Should not get here if result was TS_YES */
 2313 tgl@sss.pgh.pa.us        1669                 :UBC           0 :                     Assert(false);
                               1670                 :                :                     break;
 2313 tgl@sss.pgh.pa.us        1671                 :CBC        9878 :                 case TS_MAYBE:
                               1672                 :                :                     /* match positions are, and remain, uncertain */
                               1673                 :           9878 :                     return TS_MAYBE;
                               1674                 :                :             }
 2313 tgl@sss.pgh.pa.us        1675                 :UBC           0 :             break;
                               1676                 :                : 
 3536 tgl@sss.pgh.pa.us        1677                 :CBC      157656 :         case OP_PHRASE:
                               1678                 :                :         case OP_AND:
                               1679                 :         157656 :             memset(&Ldata, 0, sizeof(Ldata));
                               1680                 :         157656 :             memset(&Rdata, 0, sizeof(Rdata));
                               1681                 :                : 
 2313                          1682                 :         157656 :             lmatch = TS_phrase_execute(curitem + curitem->qoperator.left,
                               1683                 :                :                                        arg, flags, chkcond, &Ldata);
                               1684         [ +  + ]:         157656 :             if (lmatch == TS_NO)
                               1685                 :          84233 :                 return TS_NO;
                               1686                 :                : 
                               1687                 :          73423 :             rmatch = TS_phrase_execute(curitem + 1,
                               1688                 :                :                                        arg, flags, chkcond, &Rdata);
                               1689         [ +  + ]:          73423 :             if (rmatch == TS_NO)
                               1690                 :          36237 :                 return TS_NO;
                               1691                 :                : 
                               1692                 :                :             /*
                               1693                 :                :              * If either operand has no position information, then we can't
                               1694                 :                :              * return reliable position data, only a MAYBE result.
                               1695                 :                :              */
                               1696   [ +  +  +  + ]:          37186 :             if (lmatch == TS_MAYBE || rmatch == TS_MAYBE)
                               1697                 :          17201 :                 return TS_MAYBE;
                               1698                 :                : 
 3536                          1699         [ +  + ]:          19985 :             if (curitem->qoperator.oper == OP_PHRASE)
                               1700                 :                :             {
                               1701                 :                :                 /*
                               1702                 :                :                  * Compute Loffset and Roffset suitable for phrase match, and
                               1703                 :                :                  * compute overall width of whole phrase match.
                               1704                 :                :                  */
                               1705                 :          19980 :                 Loffset = curitem->qoperator.distance + Rdata.width;
                               1706                 :          19980 :                 Roffset = 0;
                               1707         [ +  + ]:          19980 :                 if (data)
                               1708                 :            155 :                     data->width = curitem->qoperator.distance +
                               1709                 :            155 :                         Ldata.width + Rdata.width;
                               1710                 :                :             }
                               1711                 :                :             else
                               1712                 :                :             {
                               1713                 :                :                 /*
                               1714                 :                :                  * For OP_AND, set output width and alignment like OP_OR (see
                               1715                 :                :                  * comment below)
                               1716                 :                :                  */
                               1717                 :              5 :                 maxwidth = Max(Ldata.width, Rdata.width);
                               1718                 :              5 :                 Loffset = maxwidth - Ldata.width;
                               1719                 :              5 :                 Roffset = maxwidth - Rdata.width;
                               1720         [ +  - ]:              5 :                 if (data)
                               1721                 :              5 :                     data->width = maxwidth;
                               1722                 :                :             }
                               1723                 :                : 
                               1724   [ +  +  +  + ]:          19985 :             if (Ldata.negate && Rdata.negate)
                               1725                 :                :             {
                               1726                 :                :                 /* !L & !R: treat as !(L | R) */
                               1727                 :          18957 :                 (void) TS_phrase_output(data, &Ldata, &Rdata,
                               1728                 :                :                                         TSPO_BOTH | TSPO_L_ONLY | TSPO_R_ONLY,
                               1729                 :                :                                         Loffset, Roffset,
                               1730                 :          18957 :                                         Ldata.npos + Rdata.npos);
                               1731         [ -  + ]:          18957 :                 if (data)
 3536 tgl@sss.pgh.pa.us        1732                 :UBC           0 :                     data->negate = true;
 2313 tgl@sss.pgh.pa.us        1733                 :CBC       18957 :                 return TS_YES;
                               1734                 :                :             }
 3536                          1735         [ +  + ]:           1028 :             else if (Ldata.negate)
                               1736                 :                :             {
                               1737                 :                :                 /* !L & R */
                               1738                 :            309 :                 return TS_phrase_output(data, &Ldata, &Rdata,
                               1739                 :                :                                         TSPO_R_ONLY,
                               1740                 :                :                                         Loffset, Roffset,
                               1741                 :                :                                         Rdata.npos);
                               1742                 :                :             }
                               1743         [ +  + ]:            719 :             else if (Rdata.negate)
                               1744                 :                :             {
                               1745                 :                :                 /* L & !R */
                               1746                 :              5 :                 return TS_phrase_output(data, &Ldata, &Rdata,
                               1747                 :                :                                         TSPO_L_ONLY,
                               1748                 :                :                                         Loffset, Roffset,
                               1749                 :                :                                         Ldata.npos);
                               1750                 :                :             }
                               1751                 :                :             else
                               1752                 :                :             {
                               1753                 :                :                 /* straight AND */
                               1754                 :            714 :                 return TS_phrase_output(data, &Ldata, &Rdata,
                               1755                 :                :                                         TSPO_BOTH,
                               1756                 :                :                                         Loffset, Roffset,
                               1757                 :            714 :                                         Min(Ldata.npos, Rdata.npos));
                               1758                 :                :             }
                               1759                 :                : 
                               1760                 :            126 :         case OP_OR:
                               1761                 :            126 :             memset(&Ldata, 0, sizeof(Ldata));
                               1762                 :            126 :             memset(&Rdata, 0, sizeof(Rdata));
                               1763                 :                : 
                               1764                 :            126 :             lmatch = TS_phrase_execute(curitem + curitem->qoperator.left,
                               1765                 :                :                                        arg, flags, chkcond, &Ldata);
                               1766                 :            126 :             rmatch = TS_phrase_execute(curitem + 1,
                               1767                 :                :                                        arg, flags, chkcond, &Rdata);
                               1768                 :                : 
 2313                          1769   [ +  +  +  + ]:            126 :             if (lmatch == TS_NO && rmatch == TS_NO)
                               1770                 :             10 :                 return TS_NO;
                               1771                 :                : 
                               1772                 :                :             /*
                               1773                 :                :              * If either operand has no position information, then we can't
                               1774                 :                :              * return reliable position data, only a MAYBE result.
                               1775                 :                :              */
                               1776   [ +  -  -  + ]:            116 :             if (lmatch == TS_MAYBE || rmatch == TS_MAYBE)
 2313 tgl@sss.pgh.pa.us        1777                 :UBC           0 :                 return TS_MAYBE;
                               1778                 :                : 
                               1779                 :                :             /*
                               1780                 :                :              * Cope with undefined output width from failed submatch.  (This
                               1781                 :                :              * takes less code than trying to ensure that all failure returns
                               1782                 :                :              * set data->width to zero.)
                               1783                 :                :              */
 2313 tgl@sss.pgh.pa.us        1784         [ +  + ]:CBC         116 :             if (lmatch == TS_NO)
 3536                          1785                 :             15 :                 Ldata.width = 0;
 2313                          1786         [ +  + ]:            116 :             if (rmatch == TS_NO)
 3536                          1787                 :             68 :                 Rdata.width = 0;
                               1788                 :                : 
                               1789                 :                :             /*
                               1790                 :                :              * For OP_AND and OP_OR, report the width of the wider of the two
                               1791                 :                :              * inputs, and align the narrower input's positions to the right
                               1792                 :                :              * end of that width.  This rule deals at least somewhat
                               1793                 :                :              * reasonably with cases like "x <-> (y | z <-> q)".
                               1794                 :                :              */
                               1795                 :            116 :             maxwidth = Max(Ldata.width, Rdata.width);
                               1796                 :            116 :             Loffset = maxwidth - Ldata.width;
                               1797                 :            116 :             Roffset = maxwidth - Rdata.width;
                               1798                 :            116 :             data->width = maxwidth;
                               1799                 :                : 
                               1800   [ +  +  +  + ]:            116 :             if (Ldata.negate && Rdata.negate)
                               1801                 :                :             {
                               1802                 :                :                 /* !L | !R: treat as !(L & R) */
                               1803                 :              5 :                 (void) TS_phrase_output(data, &Ldata, &Rdata,
                               1804                 :                :                                         TSPO_BOTH,
                               1805                 :                :                                         Loffset, Roffset,
                               1806                 :              5 :                                         Min(Ldata.npos, Rdata.npos));
                               1807                 :              5 :                 data->negate = true;
 2313                          1808                 :              5 :                 return TS_YES;
                               1809                 :                :             }
 3536                          1810         [ +  + ]:            111 :             else if (Ldata.negate)
                               1811                 :                :             {
                               1812                 :                :                 /* !L | R: treat as !(L & !R) */
                               1813                 :             25 :                 (void) TS_phrase_output(data, &Ldata, &Rdata,
                               1814                 :                :                                         TSPO_L_ONLY,
                               1815                 :                :                                         Loffset, Roffset,
                               1816                 :                :                                         Ldata.npos);
                               1817                 :             25 :                 data->negate = true;
 2313                          1818                 :             25 :                 return TS_YES;
                               1819                 :                :             }
 3536                          1820         [ +  + ]:             86 :             else if (Rdata.negate)
                               1821                 :                :             {
                               1822                 :                :                 /* L | !R: treat as !(!L & R) */
                               1823                 :              5 :                 (void) TS_phrase_output(data, &Ldata, &Rdata,
                               1824                 :                :                                         TSPO_R_ONLY,
                               1825                 :                :                                         Loffset, Roffset,
                               1826                 :                :                                         Rdata.npos);
                               1827                 :              5 :                 data->negate = true;
 2313                          1828                 :              5 :                 return TS_YES;
                               1829                 :                :             }
                               1830                 :                :             else
                               1831                 :                :             {
                               1832                 :                :                 /* straight OR */
 3536                          1833                 :             81 :                 return TS_phrase_output(data, &Ldata, &Rdata,
                               1834                 :                :                                         TSPO_BOTH | TSPO_L_ONLY | TSPO_R_ONLY,
                               1835                 :                :                                         Loffset, Roffset,
                               1836                 :             81 :                                         Ldata.npos + Rdata.npos);
                               1837                 :                :             }
                               1838                 :                : 
 3536 tgl@sss.pgh.pa.us        1839                 :UBC           0 :         default:
                               1840         [ #  # ]:              0 :             elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
                               1841                 :                :     }
                               1842                 :                : 
                               1843                 :                :     /* not reachable, but keep compiler quiet */
 2313                          1844                 :              0 :     return TS_NO;
                               1845                 :                : }
                               1846                 :                : 
                               1847                 :                : 
                               1848                 :                : /*
                               1849                 :                :  * Evaluate tsquery boolean expression.
                               1850                 :                :  *
                               1851                 :                :  * curitem: current tsquery item (initially, the first one)
                               1852                 :                :  * arg: opaque value to pass through to callback function
                               1853                 :                :  * flags: bitmask of flag bits shown in ts_utils.h
                               1854                 :                :  * chkcond: callback function to check whether a primitive value is present
                               1855                 :                :  */
                               1856                 :                : bool
 3541 tgl@sss.pgh.pa.us        1857                 :CBC      347528 : TS_execute(QueryItem *curitem, void *arg, uint32 flags,
                               1858                 :                :            TSExecuteCallback chkcond)
                               1859                 :                : {
                               1860                 :                :     /*
                               1861                 :                :      * If we get TS_MAYBE from the recursion, return true.  We could only see
                               1862                 :                :      * that result if the caller passed TS_EXEC_PHRASE_NO_POS, so there's no
                               1863                 :                :      * need to check again.
                               1864                 :                :      */
 2313                          1865                 :         347528 :     return TS_execute_recurse(curitem, arg, flags, chkcond) != TS_NO;
                               1866                 :                : }
                               1867                 :                : 
                               1868                 :                : /*
                               1869                 :                :  * Evaluate tsquery boolean expression.
                               1870                 :                :  *
                               1871                 :                :  * This is the same as TS_execute except that TS_MAYBE is returned as-is.
                               1872                 :                :  */
                               1873                 :                : TSTernaryValue
 2018                          1874                 :          24628 : TS_execute_ternary(QueryItem *curitem, void *arg, uint32 flags,
                               1875                 :                :                    TSExecuteCallback chkcond)
                               1876                 :                : {
                               1877                 :          24628 :     return TS_execute_recurse(curitem, arg, flags, chkcond);
                               1878                 :                : }
                               1879                 :                : 
                               1880                 :                : /*
                               1881                 :                :  * TS_execute recursion for operators above any phrase operator.  Here we do
                               1882                 :                :  * not need to worry about lexeme positions.  As soon as we hit an OP_PHRASE
                               1883                 :                :  * operator, we pass it off to TS_phrase_execute which does worry.
                               1884                 :                :  */
                               1885                 :                : static TSTernaryValue
 2313                          1886                 :         704180 : TS_execute_recurse(QueryItem *curitem, void *arg, uint32 flags,
                               1887                 :                :                    TSExecuteCallback chkcond)
                               1888                 :                : {
                               1889                 :                :     TSTernaryValue lmatch;
                               1890                 :                : 
                               1891                 :                :     /* since this function recurses, it could be driven to stack overflow */
 6936                          1892                 :         704180 :     check_stack_depth();
                               1893                 :                : 
                               1894                 :                :     /* ... and let's check for query cancel while we're at it */
 2218                          1895         [ -  + ]:         704180 :     CHECK_FOR_INTERRUPTS();
                               1896                 :                : 
 6929 teodor@sigaev.ru         1897         [ +  + ]:         704180 :     if (curitem->type == QI_VAL)
 3541 tgl@sss.pgh.pa.us        1898                 :         282777 :         return chkcond(arg, (QueryOperand *) curitem,
                               1899                 :                :                        NULL /* don't need position info */ );
                               1900                 :                : 
 6251 peter_e@gmx.net          1901   [ +  +  +  +  :         421403 :     switch (curitem->qoperator.oper)
                                                 - ]
                               1902                 :                :     {
 6929 teodor@sigaev.ru         1903                 :         135491 :         case OP_NOT:
 2225 tgl@sss.pgh.pa.us        1904         [ -  + ]:         135491 :             if (flags & TS_EXEC_SKIP_NOT)
 2313 tgl@sss.pgh.pa.us        1905                 :UBC           0 :                 return TS_YES;
 2313 tgl@sss.pgh.pa.us        1906   [ +  +  +  - ]:CBC      135491 :             switch (TS_execute_recurse(curitem + 1, arg, flags, chkcond))
                               1907                 :                :             {
                               1908                 :         127821 :                 case TS_NO:
                               1909                 :         127821 :                     return TS_YES;
                               1910                 :           3264 :                 case TS_YES:
                               1911                 :           3264 :                     return TS_NO;
                               1912                 :           4406 :                 case TS_MAYBE:
                               1913                 :           4406 :                     return TS_MAYBE;
                               1914                 :                :             }
 2313 tgl@sss.pgh.pa.us        1915                 :UBC           0 :             break;
                               1916                 :                : 
 6929 teodor@sigaev.ru         1917                 :CBC       55853 :         case OP_AND:
 2313 tgl@sss.pgh.pa.us        1918                 :          55853 :             lmatch = TS_execute_recurse(curitem + curitem->qoperator.left, arg,
                               1919                 :                :                                         flags, chkcond);
                               1920         [ +  + ]:          55853 :             if (lmatch == TS_NO)
                               1921                 :          44355 :                 return TS_NO;
                               1922   [ +  +  +  - ]:          11498 :             switch (TS_execute_recurse(curitem + 1, arg, flags, chkcond))
                               1923                 :                :             {
                               1924                 :           6752 :                 case TS_NO:
                               1925                 :           6752 :                     return TS_NO;
                               1926                 :           2236 :                 case TS_YES:
                               1927                 :           2236 :                     return lmatch;
                               1928                 :           2510 :                 case TS_MAYBE:
                               1929                 :           2510 :                     return TS_MAYBE;
                               1930                 :                :             }
 2313 tgl@sss.pgh.pa.us        1931                 :UBC           0 :             break;
                               1932                 :                : 
 6929 teodor@sigaev.ru         1933                 :CBC       72663 :         case OP_OR:
 2313 tgl@sss.pgh.pa.us        1934                 :          72663 :             lmatch = TS_execute_recurse(curitem + curitem->qoperator.left, arg,
                               1935                 :                :                                         flags, chkcond);
                               1936         [ +  + ]:          72663 :             if (lmatch == TS_YES)
                               1937                 :          16144 :                 return TS_YES;
                               1938   [ +  +  +  - ]:          56519 :             switch (TS_execute_recurse(curitem + 1, arg, flags, chkcond))
                               1939                 :                :             {
                               1940                 :          38334 :                 case TS_NO:
                               1941                 :          38334 :                     return lmatch;
                               1942                 :           4962 :                 case TS_YES:
                               1943                 :           4962 :                     return TS_YES;
                               1944                 :          13223 :                 case TS_MAYBE:
                               1945                 :          13223 :                     return TS_MAYBE;
                               1946                 :                :             }
 2313 tgl@sss.pgh.pa.us        1947                 :UBC           0 :             break;
                               1948                 :                : 
 3794 teodor@sigaev.ru         1949                 :CBC      157396 :         case OP_PHRASE:
                               1950                 :                : 
                               1951                 :                :             /*
                               1952                 :                :              * If we get a MAYBE result, and the caller doesn't want that,
                               1953                 :                :              * convert it to NO.  It would be more consistent, perhaps, to
                               1954                 :                :              * return the result of TS_phrase_execute() verbatim and then
                               1955                 :                :              * convert MAYBE results at the top of the recursion.  But
                               1956                 :                :              * converting at the topmost phrase operator gives results that
                               1957                 :                :              * are bug-compatible with the old implementation, so do it like
                               1958                 :                :              * this for now.
                               1959                 :                :              */
 2313 tgl@sss.pgh.pa.us        1960   [ +  +  +  - ]:         157396 :             switch (TS_phrase_execute(curitem, arg, flags, chkcond, NULL))
                               1961                 :                :             {
                               1962                 :         120599 :                 case TS_NO:
                               1963                 :         120599 :                     return TS_NO;
                               1964                 :          19601 :                 case TS_YES:
                               1965                 :          19601 :                     return TS_YES;
                               1966                 :          17196 :                 case TS_MAYBE:
                               1967                 :          17196 :                     return (flags & TS_EXEC_PHRASE_NO_POS) ? TS_MAYBE : TS_NO;
                               1968                 :                :             }
 2313 tgl@sss.pgh.pa.us        1969                 :UBC           0 :             break;
                               1970                 :                : 
 6929 teodor@sigaev.ru         1971                 :              0 :         default:
 6251 peter_e@gmx.net          1972         [ #  # ]:              0 :             elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
                               1973                 :                :     }
                               1974                 :                : 
                               1975                 :                :     /* not reachable, but keep compiler quiet */
 2313 tgl@sss.pgh.pa.us        1976                 :              0 :     return TS_NO;
                               1977                 :                : }
                               1978                 :                : 
                               1979                 :                : /*
                               1980                 :                :  * Evaluate tsquery and report locations of matching terms.
                               1981                 :                :  *
                               1982                 :                :  * This is like TS_execute except that it returns match locations not just
                               1983                 :                :  * success/failure status.  The callback function is required to provide
                               1984                 :                :  * position data (we report failure if it doesn't).
                               1985                 :                :  *
                               1986                 :                :  * On successful match, the result is a List of ExecPhraseData structs, one
                               1987                 :                :  * for each AND'ed term or phrase operator in the query.  Each struct includes
                               1988                 :                :  * a sorted array of lexeme positions matching that term.  (Recall that for
                               1989                 :                :  * phrase operators, the match includes width+1 lexemes, and the recorded
                               1990                 :                :  * position is that of the rightmost lexeme.)
                               1991                 :                :  *
                               1992                 :                :  * OR subexpressions are handled by union'ing their match locations into a
                               1993                 :                :  * single List element, which is valid since any of those locations contains
                               1994                 :                :  * a match.  However, when some of the OR'ed terms are phrase operators, we
                               1995                 :                :  * report the maximum width of any of the OR'ed terms, making such cases
                               1996                 :                :  * slightly imprecise in the conservative direction.  (For example, if the
                               1997                 :                :  * tsquery is "(A <-> B) | C", an occurrence of C in the data would be
                               1998                 :                :  * reported as though it includes the lexeme to the left of C.)
                               1999                 :                :  *
                               2000                 :                :  * Locations of NOT subexpressions are not reported.  (Obviously, there can
                               2001                 :                :  * be no successful NOT matches at top level, or the match would have failed.
                               2002                 :                :  * So this amounts to ignoring NOTs underneath ORs.)
                               2003                 :                :  *
                               2004                 :                :  * The result is NIL if no match, or if position data was not returned.
                               2005                 :                :  *
                               2006                 :                :  * Arguments are the same as for TS_execute, although flags is currently
                               2007                 :                :  * vestigial since none of the defined bits are sensible here.
                               2008                 :                :  */
                               2009                 :                : List *
 1316 tgl@sss.pgh.pa.us        2010                 :CBC         293 : TS_execute_locations(QueryItem *curitem, void *arg,
                               2011                 :                :                      uint32 flags,
                               2012                 :                :                      TSExecuteCallback chkcond)
                               2013                 :                : {
                               2014                 :                :     List       *result;
                               2015                 :                : 
                               2016                 :                :     /* No flags supported, as yet */
                               2017         [ -  + ]:            293 :     Assert(flags == TS_EXEC_EMPTY);
                               2018         [ +  + ]:            293 :     if (TS_execute_locations_recurse(curitem, arg, chkcond, &result))
                               2019                 :            118 :         return result;
                               2020                 :            175 :     return NIL;
                               2021                 :                : }
                               2022                 :                : 
                               2023                 :                : /*
                               2024                 :                :  * TS_execute_locations recursion for operators above any phrase operator.
                               2025                 :                :  * OP_PHRASE subexpressions can be passed off to TS_phrase_execute.
                               2026                 :                :  */
                               2027                 :                : static bool
                               2028                 :            839 : TS_execute_locations_recurse(QueryItem *curitem, void *arg,
                               2029                 :                :                              TSExecuteCallback chkcond,
                               2030                 :                :                              List **locations)
                               2031                 :                : {
                               2032                 :                :     bool        lmatch,
                               2033                 :                :                 rmatch;
                               2034                 :                :     List       *llocations,
                               2035                 :                :                *rlocations;
                               2036                 :                :     ExecPhraseData *data;
                               2037                 :                : 
                               2038                 :                :     /* since this function recurses, it could be driven to stack overflow */
                               2039                 :            839 :     check_stack_depth();
                               2040                 :                : 
                               2041                 :                :     /* ... and let's check for query cancel while we're at it */
                               2042         [ -  + ]:            839 :     CHECK_FOR_INTERRUPTS();
                               2043                 :                : 
                               2044                 :                :     /* Default locations result is empty */
                               2045                 :            839 :     *locations = NIL;
                               2046                 :                : 
                               2047         [ +  + ]:            839 :     if (curitem->type == QI_VAL)
                               2048                 :                :     {
                               2049                 :            359 :         data = palloc0_object(ExecPhraseData);
                               2050         [ +  + ]:            359 :         if (chkcond(arg, (QueryOperand *) curitem, data) == TS_YES)
                               2051                 :                :         {
                               2052                 :            184 :             *locations = list_make1(data);
                               2053                 :            184 :             return true;
                               2054                 :                :         }
                               2055                 :            175 :         pfree(data);
                               2056                 :            175 :         return false;
                               2057                 :                :     }
                               2058                 :                : 
                               2059   [ +  +  +  +  :            480 :     switch (curitem->qoperator.oper)
                                                 - ]
                               2060                 :                :     {
                               2061                 :             10 :         case OP_NOT:
                               2062         [ -  + ]:             10 :             if (!TS_execute_locations_recurse(curitem + 1, arg, chkcond,
                               2063                 :                :                                               &llocations))
 1316 tgl@sss.pgh.pa.us        2064                 :UBC           0 :                 return true;    /* we don't pass back any locations */
 1316 tgl@sss.pgh.pa.us        2065                 :CBC          10 :             return false;
                               2066                 :                : 
                               2067                 :            400 :         case OP_AND:
                               2068         [ +  + ]:            400 :             if (!TS_execute_locations_recurse(curitem + curitem->qoperator.left,
                               2069                 :                :                                               arg, chkcond,
                               2070                 :                :                                               &llocations))
                               2071                 :            304 :                 return false;
                               2072         [ +  + ]:             96 :             if (!TS_execute_locations_recurse(curitem + 1,
                               2073                 :                :                                               arg, chkcond,
                               2074                 :                :                                               &rlocations))
                               2075                 :             41 :                 return false;
                               2076                 :             55 :             *locations = list_concat(llocations, rlocations);
                               2077                 :             55 :             return true;
                               2078                 :                : 
                               2079                 :             20 :         case OP_OR:
                               2080                 :             20 :             lmatch = TS_execute_locations_recurse(curitem + curitem->qoperator.left,
                               2081                 :                :                                                   arg, chkcond,
                               2082                 :                :                                                   &llocations);
                               2083                 :             20 :             rmatch = TS_execute_locations_recurse(curitem + 1,
                               2084                 :                :                                                   arg, chkcond,
                               2085                 :                :                                                   &rlocations);
                               2086   [ -  +  -  - ]:             20 :             if (lmatch || rmatch)
                               2087                 :                :             {
                               2088                 :                :                 /*
                               2089                 :                :                  * We generate an AND'able location struct from each
                               2090                 :                :                  * combination of sub-matches, following the disjunctive law
                               2091                 :                :                  * (A & B) | (C & D) = (A | C) & (A | D) & (B | C) & (B | D).
                               2092                 :                :                  *
                               2093                 :                :                  * However, if either input didn't produce locations (i.e., it
                               2094                 :                :                  * failed or was a NOT), we must just return the other list.
                               2095                 :                :                  */
                               2096         [ -  + ]:             20 :                 if (llocations == NIL)
 1316 tgl@sss.pgh.pa.us        2097                 :UBC           0 :                     *locations = rlocations;
 1316 tgl@sss.pgh.pa.us        2098         [ +  + ]:CBC          20 :                 else if (rlocations == NIL)
                               2099                 :             10 :                     *locations = llocations;
                               2100                 :                :                 else
                               2101                 :                :                 {
                               2102                 :                :                     ListCell   *ll;
                               2103                 :                : 
                               2104   [ +  -  +  +  :             20 :                     foreach(ll, llocations)
                                              +  + ]
                               2105                 :                :                     {
                               2106                 :             10 :                         ExecPhraseData *ldata = (ExecPhraseData *) lfirst(ll);
                               2107                 :                :                         ListCell   *lr;
                               2108                 :                : 
                               2109   [ +  -  +  +  :             20 :                         foreach(lr, rlocations)
                                              +  + ]
                               2110                 :                :                         {
                               2111                 :             10 :                             ExecPhraseData *rdata = (ExecPhraseData *) lfirst(lr);
                               2112                 :                : 
                               2113                 :             10 :                             data = palloc0_object(ExecPhraseData);
                               2114                 :             10 :                             (void) TS_phrase_output(data, ldata, rdata,
                               2115                 :                :                                                     TSPO_BOTH | TSPO_L_ONLY | TSPO_R_ONLY,
                               2116                 :                :                                                     0, 0,
                               2117                 :             10 :                                                     ldata->npos + rdata->npos);
                               2118                 :                :                             /* Report the larger width, as explained above. */
                               2119                 :             10 :                             data->width = Max(ldata->width, rdata->width);
                               2120                 :             10 :                             *locations = lappend(*locations, data);
                               2121                 :                :                         }
                               2122                 :                :                     }
                               2123                 :                :                 }
                               2124                 :                : 
                               2125                 :             20 :                 return true;
                               2126                 :                :             }
 1316 tgl@sss.pgh.pa.us        2127                 :UBC           0 :             return false;
                               2128                 :                : 
 1316 tgl@sss.pgh.pa.us        2129                 :CBC          50 :         case OP_PHRASE:
                               2130                 :                :             /* We can hand this off to TS_phrase_execute */
                               2131                 :             50 :             data = palloc0_object(ExecPhraseData);
                               2132         [ +  - ]:             50 :             if (TS_phrase_execute(curitem, arg, TS_EXEC_EMPTY, chkcond,
                               2133                 :                :                                   data) == TS_YES)
                               2134                 :                :             {
                               2135         [ +  - ]:             50 :                 if (!data->negate)
                               2136                 :             50 :                     *locations = list_make1(data);
                               2137                 :             50 :                 return true;
                               2138                 :                :             }
 1316 tgl@sss.pgh.pa.us        2139                 :UBC           0 :             pfree(data);
                               2140                 :              0 :             return false;
                               2141                 :                : 
                               2142                 :              0 :         default:
                               2143         [ #  # ]:              0 :             elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
                               2144                 :                :     }
                               2145                 :                : 
                               2146                 :                :     /* not reachable, but keep compiler quiet */
                               2147                 :                :     return false;
                               2148                 :                : }
                               2149                 :                : 
                               2150                 :                : /*
                               2151                 :                :  * Detect whether a tsquery boolean expression requires any positive matches
                               2152                 :                :  * to values shown in the tsquery.
                               2153                 :                :  *
                               2154                 :                :  * This is needed to know whether a GIN index search requires full index scan.
                               2155                 :                :  * For example, 'x & !y' requires a match of x, so it's sufficient to scan
                               2156                 :                :  * entries for x; but 'x | !y' could match rows containing neither x nor y.
                               2157                 :                :  */
                               2158                 :                : bool
 5709 tgl@sss.pgh.pa.us        2159                 :CBC         631 : tsquery_requires_match(QueryItem *curitem)
                               2160                 :                : {
                               2161                 :                :     /* since this function recurses, it could be driven to stack overflow */
                               2162                 :            631 :     check_stack_depth();
                               2163                 :                : 
                               2164         [ +  + ]:            631 :     if (curitem->type == QI_VAL)
                               2165                 :            301 :         return true;
                               2166                 :                : 
                               2167   [ +  +  +  - ]:            330 :     switch (curitem->qoperator.oper)
                               2168                 :                :     {
                               2169                 :            127 :         case OP_NOT:
                               2170                 :                : 
                               2171                 :                :             /*
                               2172                 :                :              * Assume there are no required matches underneath a NOT.  For
                               2173                 :                :              * some cases with nested NOTs, we could prove there's a required
                               2174                 :                :              * match, but it seems unlikely to be worth the trouble.
                               2175                 :                :              */
                               2176                 :            127 :             return false;
                               2177                 :                : 
 3794 teodor@sigaev.ru         2178                 :            153 :         case OP_PHRASE:
                               2179                 :                : 
                               2180                 :                :             /*
                               2181                 :                :              * Treat OP_PHRASE as OP_AND here
                               2182                 :                :              */
                               2183                 :                :         case OP_AND:
                               2184                 :                :             /* If either side requires a match, we're good */
 5709 tgl@sss.pgh.pa.us        2185         [ +  + ]:            153 :             if (tsquery_requires_match(curitem + curitem->qoperator.left))
                               2186                 :            117 :                 return true;
                               2187                 :                :             else
                               2188                 :             36 :                 return tsquery_requires_match(curitem + 1);
                               2189                 :                : 
                               2190                 :             50 :         case OP_OR:
                               2191                 :                :             /* Both sides must require a match */
                               2192         [ +  - ]:             50 :             if (tsquery_requires_match(curitem + curitem->qoperator.left))
                               2193                 :             50 :                 return tsquery_requires_match(curitem + 1);
                               2194                 :                :             else
 5709 tgl@sss.pgh.pa.us        2195                 :UBC           0 :                 return false;
                               2196                 :                : 
                               2197                 :              0 :         default:
                               2198         [ #  # ]:              0 :             elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
                               2199                 :                :     }
                               2200                 :                : 
                               2201                 :                :     /* not reachable, but keep compiler quiet */
                               2202                 :                :     return false;
                               2203                 :                : }
                               2204                 :                : 
                               2205                 :                : /*
                               2206                 :                :  * boolean operations
                               2207                 :                :  */
                               2208                 :                : Datum
 6946 tgl@sss.pgh.pa.us        2209                 :CBC          40 : ts_match_qv(PG_FUNCTION_ARGS)
                               2210                 :                : {
                               2211                 :             40 :     PG_RETURN_DATUM(DirectFunctionCall2(ts_match_vq,
                               2212                 :                :                                         PG_GETARG_DATUM(1),
                               2213                 :                :                                         PG_GETARG_DATUM(0)));
                               2214                 :                : }
                               2215                 :                : 
                               2216                 :                : Datum
                               2217                 :         146808 : ts_match_vq(PG_FUNCTION_ARGS)
                               2218                 :                : {
                               2219                 :         146808 :     TSVector    val = PG_GETARG_TSVECTOR(0);
                               2220                 :         146808 :     TSQuery     query = PG_GETARG_TSQUERY(1);
                               2221                 :                :     CHKVAL      chkval;
                               2222                 :                :     bool        result;
                               2223                 :                : 
                               2224                 :                :     /* empty query matches nothing */
 3500                          2225         [ -  + ]:         146808 :     if (!query->size)
                               2226                 :                :     {
 6946 tgl@sss.pgh.pa.us        2227         [ #  # ]:UBC           0 :         PG_FREE_IF_COPY(val, 0);
                               2228         [ #  # ]:              0 :         PG_FREE_IF_COPY(query, 1);
                               2229                 :              0 :         PG_RETURN_BOOL(false);
                               2230                 :                :     }
                               2231                 :                : 
 6946 tgl@sss.pgh.pa.us        2232                 :CBC      146808 :     chkval.arrb = ARRPTR(val);
                               2233                 :         146808 :     chkval.arre = chkval.arrb + val->size;
                               2234                 :         146808 :     chkval.values = STRPTR(val);
                               2235                 :         146808 :     chkval.operand = GETOPERAND(query);
 3541                          2236                 :         146808 :     result = TS_execute(GETQUERY(query),
                               2237                 :                :                         &chkval,
                               2238                 :                :                         TS_EXEC_EMPTY,
                               2239                 :                :                         checkcondition_str);
                               2240                 :                : 
 6946                          2241         [ +  + ]:         146808 :     PG_FREE_IF_COPY(val, 0);
                               2242         [ -  + ]:         146808 :     PG_FREE_IF_COPY(query, 1);
                               2243                 :         146808 :     PG_RETURN_BOOL(result);
                               2244                 :                : }
                               2245                 :                : 
                               2246                 :                : Datum
 6946 tgl@sss.pgh.pa.us        2247                 :UBC           0 : ts_match_tt(PG_FUNCTION_ARGS)
                               2248                 :                : {
                               2249                 :                :     TSVector    vector;
                               2250                 :                :     TSQuery     query;
                               2251                 :                :     bool        res;
                               2252                 :                : 
                               2253                 :              0 :     vector = DatumGetTSVector(DirectFunctionCall1(to_tsvector,
                               2254                 :                :                                                   PG_GETARG_DATUM(0)));
                               2255                 :              0 :     query = DatumGetTSQuery(DirectFunctionCall1(plainto_tsquery,
                               2256                 :                :                                                 PG_GETARG_DATUM(1)));
                               2257                 :                : 
                               2258                 :              0 :     res = DatumGetBool(DirectFunctionCall2(ts_match_vq,
                               2259                 :                :                                            TSVectorGetDatum(vector),
                               2260                 :                :                                            TSQueryGetDatum(query)));
                               2261                 :                : 
                               2262                 :              0 :     pfree(vector);
                               2263                 :              0 :     pfree(query);
                               2264                 :                : 
                               2265                 :              0 :     PG_RETURN_BOOL(res);
                               2266                 :                : }
                               2267                 :                : 
                               2268                 :                : Datum
                               2269                 :              0 : ts_match_tq(PG_FUNCTION_ARGS)
                               2270                 :                : {
                               2271                 :                :     TSVector    vector;
                               2272                 :              0 :     TSQuery     query = PG_GETARG_TSQUERY(1);
                               2273                 :                :     bool        res;
                               2274                 :                : 
                               2275                 :              0 :     vector = DatumGetTSVector(DirectFunctionCall1(to_tsvector,
                               2276                 :                :                                                   PG_GETARG_DATUM(0)));
                               2277                 :                : 
                               2278                 :              0 :     res = DatumGetBool(DirectFunctionCall2(ts_match_vq,
                               2279                 :                :                                            TSVectorGetDatum(vector),
                               2280                 :                :                                            TSQueryGetDatum(query)));
                               2281                 :                : 
                               2282                 :              0 :     pfree(vector);
                               2283         [ #  # ]:              0 :     PG_FREE_IF_COPY(query, 1);
                               2284                 :                : 
                               2285                 :              0 :     PG_RETURN_BOOL(res);
                               2286                 :                : }
                               2287                 :                : 
                               2288                 :                : /*
                               2289                 :                :  * ts_stat statistic function support
                               2290                 :                :  */
                               2291                 :                : 
                               2292                 :                : 
                               2293                 :                : /*
                               2294                 :                :  * Returns the number of positions in value 'wptr' within tsvector 'txt',
                               2295                 :                :  * that have a weight equal to one of the weights in 'weight' bitmask.
                               2296                 :                :  */
                               2297                 :                : static int
 6860 bruce@momjian.us         2298                 :CBC        5452 : check_weight(TSVector txt, WordEntry *wptr, int8 weight)
                               2299                 :                : {
 6946 tgl@sss.pgh.pa.us        2300         [ +  - ]:           5452 :     int         len = POSDATALEN(txt, wptr);
                               2301                 :           5452 :     int         num = 0;
                               2302                 :           5452 :     WordEntryPos *ptr = POSDATAPTR(txt, wptr);
                               2303                 :                : 
                               2304         [ +  + ]:          11100 :     while (len--)
                               2305                 :                :     {
                               2306         [ +  + ]:           5648 :         if (weight & (1 << WEP_GETWEIGHT(*ptr)))
                               2307                 :              8 :             num++;
                               2308                 :           5648 :         ptr++;
                               2309                 :                :     }
                               2310                 :           5452 :     return num;
                               2311                 :                : }
                               2312                 :                : 
                               2313                 :                : #define compareStatWord(a,e,t)                          \
                               2314                 :                :     tsCompareString((a)->lexeme, (a)->lenlexeme,      \
                               2315                 :                :                     STRPTR(t) + (e)->pos, (e)->len,       \
                               2316                 :                :                     false)
                               2317                 :                : 
                               2318                 :                : static void
 6492 teodor@sigaev.ru         2319                 :         230416 : insertStatEntry(MemoryContext persistentContext, TSVectorStat *stat, TSVector txt, uint32 off)
                               2320                 :                : {
 6286 bruce@momjian.us         2321                 :         230416 :     WordEntry  *we = ARRPTR(txt) + off;
                               2322                 :         230416 :     StatEntry  *node = stat->root,
                               2323                 :         230416 :                *pnode = NULL;
                               2324                 :                :     int         n,
 6490 teodor@sigaev.ru         2325                 :         230416 :                 res = 0;
 6286 bruce@momjian.us         2326                 :         230416 :     uint32      depth = 1;
                               2327                 :                : 
                               2328         [ +  + ]:         230416 :     if (stat->weight == 0)
 6492 teodor@sigaev.ru         2329         [ +  + ]:         115208 :         n = (we->haspos) ? POSDATALEN(txt, we) : 1;
                               2330                 :                :     else
                               2331         [ +  + ]:         115208 :         n = (we->haspos) ? check_weight(txt, we, stat->weight) : 0;
                               2332                 :                : 
 6286 bruce@momjian.us         2333         [ +  + ]:         230416 :     if (n == 0)
                               2334                 :         115204 :         return;                 /* nothing to insert */
                               2335                 :                : 
                               2336         [ +  + ]:        1163592 :     while (node)
                               2337                 :                :     {
 6492 teodor@sigaev.ru         2338                 :        1159016 :         res = compareStatWord(node, we, txt);
                               2339                 :                : 
                               2340         [ +  + ]:        1159016 :         if (res == 0)
                               2341                 :                :         {
                               2342                 :         110636 :             break;
                               2343                 :                :         }
                               2344                 :                :         else
                               2345                 :                :         {
                               2346                 :        1048380 :             pnode = node;
 6286 bruce@momjian.us         2347         [ +  + ]:        1048380 :             node = (res < 0) ? node->left : node->right;
                               2348                 :                :         }
 6492 teodor@sigaev.ru         2349                 :        1048380 :         depth++;
                               2350                 :                :     }
                               2351                 :                : 
                               2352         [ +  + ]:         115212 :     if (depth > stat->maxdepth)
                               2353                 :             84 :         stat->maxdepth = depth;
                               2354                 :                : 
                               2355         [ +  + ]:         115212 :     if (node == NULL)
                               2356                 :                :     {
 6286 bruce@momjian.us         2357                 :           4576 :         node = MemoryContextAlloc(persistentContext, STATENTRYHDRSZ + we->len);
 6492 teodor@sigaev.ru         2358                 :           4576 :         node->left = node->right = NULL;
                               2359                 :           4576 :         node->ndoc = 1;
                               2360                 :           4576 :         node->nentry = n;
                               2361                 :           4576 :         node->lenlexeme = we->len;
                               2362                 :           4576 :         memcpy(node->lexeme, STRPTR(txt) + we->pos, node->lenlexeme);
                               2363                 :                : 
 6286 bruce@momjian.us         2364         [ +  + ]:           4576 :         if (pnode == NULL)
                               2365                 :                :         {
 6492 teodor@sigaev.ru         2366                 :              8 :             stat->root = node;
                               2367                 :                :         }
                               2368                 :                :         else
                               2369                 :                :         {
                               2370         [ +  + ]:           4568 :             if (res < 0)
                               2371                 :           2254 :                 pnode->left = node;
                               2372                 :                :             else
                               2373                 :           2314 :                 pnode->right = node;
                               2374                 :                :         }
                               2375                 :                :     }
                               2376                 :                :     else
                               2377                 :                :     {
                               2378                 :         110636 :         node->ndoc++;
                               2379                 :         110636 :         node->nentry += n;
                               2380                 :                :     }
                               2381                 :                : }
                               2382                 :                : 
                               2383                 :                : static void
 6286 bruce@momjian.us         2384                 :         330256 : chooseNextStatEntry(MemoryContext persistentContext, TSVectorStat *stat, TSVector txt,
                               2385                 :                :                     uint32 low, uint32 high, uint32 offset)
                               2386                 :                : {
                               2387                 :                :     uint32      pos;
                               2388                 :         330256 :     uint32      middle = (low + high) >> 1;
                               2389                 :                : 
 6492 teodor@sigaev.ru         2390                 :         330256 :     pos = (low + middle) >> 1;
                               2391   [ +  +  +  +  :         330256 :     if (low != middle && pos >= offset && pos - offset < txt->size)
                                              +  + ]
 6286 bruce@momjian.us         2392                 :         113552 :         insertStatEntry(persistentContext, stat, txt, pos - offset);
 6492 teodor@sigaev.ru         2393                 :         330256 :     pos = (high + middle + 1) >> 1;
                               2394   [ +  +  +  +  :         330256 :     if (middle + 1 != high && pos >= offset && pos - offset < txt->size)
                                              +  + ]
 6286 bruce@momjian.us         2395                 :         112856 :         insertStatEntry(persistentContext, stat, txt, pos - offset);
                               2396                 :                : 
 6492 teodor@sigaev.ru         2397         [ +  + ]:         330256 :     if (low != middle)
                               2398                 :         165128 :         chooseNextStatEntry(persistentContext, stat, txt, low, middle, offset);
                               2399         [ +  + ]:         330256 :     if (high != middle + 1)
                               2400                 :         161120 :         chooseNextStatEntry(persistentContext, stat, txt, middle + 1, high, offset);
 6946 tgl@sss.pgh.pa.us        2401                 :         330256 : }
                               2402                 :                : 
                               2403                 :                : /*
                               2404                 :                :  * This is written like a custom aggregate function, because the
                               2405                 :                :  * original plan was to do just that. Unfortunately, an aggregate function
                               2406                 :                :  * can't return a set, so that plan was abandoned. If that limitation is
                               2407                 :                :  * lifted in the future, ts_stat could be a real aggregate function so that
                               2408                 :                :  * you could use it like this:
                               2409                 :                :  *
                               2410                 :                :  *   SELECT ts_stat(vector_column) FROM vector_table;
                               2411                 :                :  *
                               2412                 :                :  *  where vector_column is a tsvector-type column in vector_table.
                               2413                 :                :  */
                               2414                 :                : 
                               2415                 :                : static TSVectorStat *
 6492 teodor@sigaev.ru         2416                 :           4072 : ts_accum(MemoryContext persistentContext, TSVectorStat *stat, Datum data)
                               2417                 :                : {
 6286 bruce@momjian.us         2418                 :           4072 :     TSVector    txt = DatumGetTSVector(data);
                               2419                 :                :     uint32      i,
                               2420                 :           4072 :                 nbit = 0,
                               2421                 :                :                 offset;
                               2422                 :                : 
 6946 tgl@sss.pgh.pa.us        2423         [ -  + ]:           4072 :     if (stat == NULL)
                               2424                 :                :     {                           /* Init in first */
 6492 teodor@sigaev.ru         2425                 :UBC           0 :         stat = MemoryContextAllocZero(persistentContext, sizeof(TSVectorStat));
                               2426                 :              0 :         stat->maxdepth = 1;
                               2427                 :                :     }
                               2428                 :                : 
                               2429                 :                :     /* simple check of correctness */
 6946 tgl@sss.pgh.pa.us        2430   [ +  -  +  + ]:CBC        4072 :     if (txt == NULL || txt->size == 0)
                               2431                 :                :     {
 6492 teodor@sigaev.ru         2432   [ +  -  +  - ]:             64 :         if (txt && txt != (TSVector) DatumGetPointer(data))
 6946 tgl@sss.pgh.pa.us        2433                 :             64 :             pfree(txt);
                               2434                 :             64 :         return stat;
                               2435                 :                :     }
                               2436                 :                : 
 6492 teodor@sigaev.ru         2437                 :           4008 :     i = txt->size - 1;
                               2438         [ +  + ]:          28480 :     for (; i > 0; i >>= 1)
                               2439                 :          24472 :         nbit++;
                               2440                 :                : 
                               2441                 :           4008 :     nbit = 1 << nbit;
                               2442                 :           4008 :     offset = (nbit - txt->size) / 2;
                               2443                 :                : 
 6286 bruce@momjian.us         2444                 :           4008 :     insertStatEntry(persistentContext, stat, txt, (nbit >> 1) - offset);
 6492 teodor@sigaev.ru         2445                 :           4008 :     chooseNextStatEntry(persistentContext, stat, txt, 0, nbit, offset);
                               2446                 :                : 
                               2447                 :           4008 :     return stat;
                               2448                 :                : }
                               2449                 :                : 
                               2450                 :                : static void
 6946 tgl@sss.pgh.pa.us        2451                 :              8 : ts_setup_firstcall(FunctionCallInfo fcinfo, FuncCallContext *funcctx,
                               2452                 :                :                    TSVectorStat *stat)
                               2453                 :                : {
                               2454                 :                :     TupleDesc   tupdesc;
                               2455                 :                :     MemoryContext oldcontext;
                               2456                 :                :     StatEntry  *node;
                               2457                 :                : 
  637 peter@eisentraut.org     2458                 :              8 :     funcctx->user_fctx = stat;
                               2459                 :                : 
 6946 tgl@sss.pgh.pa.us        2460                 :              8 :     oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
                               2461                 :                : 
  260 michael@paquier.xyz      2462                 :              8 :     stat->stack = palloc0_array(StatEntry *, stat->maxdepth + 1);
 6286 bruce@momjian.us         2463                 :              8 :     stat->stackpos = 0;
                               2464                 :                : 
 6492 teodor@sigaev.ru         2465                 :              8 :     node = stat->root;
                               2466                 :                :     /* find leftmost value */
 6162 tgl@sss.pgh.pa.us        2467         [ +  - ]:              8 :     if (node == NULL)
 6162 tgl@sss.pgh.pa.us        2468                 :UBC           0 :         stat->stack[stat->stackpos] = NULL;
                               2469                 :                :     else
                               2470                 :                :         for (;;)
                               2471                 :                :         {
 6162 tgl@sss.pgh.pa.us        2472                 :CBC          32 :             stat->stack[stat->stackpos] = node;
                               2473         [ +  + ]:             32 :             if (node->left)
                               2474                 :                :             {
                               2475                 :             24 :                 stat->stackpos++;
                               2476                 :             24 :                 node = node->left;
                               2477                 :                :             }
                               2478                 :                :             else
                               2479                 :              8 :                 break;
                               2480                 :                :         }
                               2481         [ -  + ]:              8 :     Assert(stat->stackpos <= stat->maxdepth);
                               2482                 :                : 
 1345 michael@paquier.xyz      2483         [ -  + ]:              8 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
 1345 michael@paquier.xyz      2484         [ #  # ]:UBC           0 :         elog(ERROR, "return type must be a row type");
 1345 michael@paquier.xyz      2485                 :CBC           8 :     funcctx->tuple_desc = tupdesc;
 6946 tgl@sss.pgh.pa.us        2486                 :              8 :     funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
                               2487                 :                : 
                               2488                 :              8 :     MemoryContextSwitchTo(oldcontext);
                               2489                 :              8 : }
                               2490                 :                : 
                               2491                 :                : static StatEntry *
 6286 bruce@momjian.us         2492                 :           9152 : walkStatEntryTree(TSVectorStat *stat)
                               2493                 :                : {
                               2494                 :           9152 :     StatEntry  *node = stat->stack[stat->stackpos];
                               2495                 :                : 
                               2496         [ -  + ]:           9152 :     if (node == NULL)
 6492 teodor@sigaev.ru         2497                 :UBC           0 :         return NULL;
                               2498                 :                : 
 6286 bruce@momjian.us         2499         [ +  + ]:CBC        9152 :     if (node->ndoc != 0)
                               2500                 :                :     {
                               2501                 :                :         /* return entry itself: we already was at left sublink */
 6492 teodor@sigaev.ru         2502                 :           2262 :         return node;
                               2503                 :                :     }
                               2504   [ +  +  +  + ]:           6890 :     else if (node->right && node->right != stat->stack[stat->stackpos + 1])
                               2505                 :                :     {
                               2506                 :                :         /* go on right sublink */
                               2507                 :           2314 :         stat->stackpos++;
                               2508                 :           2314 :         node = node->right;
                               2509                 :                : 
                               2510                 :                :         /* find most-left value */
                               2511                 :                :         for (;;)
                               2512                 :                :         {
                               2513                 :           4544 :             stat->stack[stat->stackpos] = node;
                               2514         [ +  + ]:           4544 :             if (node->left)
                               2515                 :                :             {
                               2516                 :           2230 :                 stat->stackpos++;
                               2517                 :           2230 :                 node = node->left;
                               2518                 :                :             }
                               2519                 :                :             else
                               2520                 :           2314 :                 break;
                               2521                 :                :         }
 6162 tgl@sss.pgh.pa.us        2522         [ -  + ]:           2314 :         Assert(stat->stackpos <= stat->maxdepth);
                               2523                 :                :     }
                               2524                 :                :     else
                               2525                 :                :     {
                               2526                 :                :         /* we already return all left subtree, itself and  right subtree */
 6492 teodor@sigaev.ru         2527         [ +  + ]:           4576 :         if (stat->stackpos == 0)
                               2528                 :              8 :             return NULL;
                               2529                 :                : 
                               2530                 :           4568 :         stat->stackpos--;
                               2531                 :           4568 :         return walkStatEntryTree(stat);
                               2532                 :                :     }
                               2533                 :                : 
                               2534                 :           2314 :     return node;
                               2535                 :                : }
                               2536                 :                : 
                               2537                 :                : static Datum
 6946 tgl@sss.pgh.pa.us        2538                 :           4584 : ts_process_call(FuncCallContext *funcctx)
                               2539                 :                : {
                               2540                 :                :     TSVectorStat *st;
                               2541                 :                :     StatEntry  *entry;
                               2542                 :                : 
 6492 teodor@sigaev.ru         2543                 :           4584 :     st = (TSVectorStat *) funcctx->user_fctx;
                               2544                 :                : 
                               2545                 :           4584 :     entry = walkStatEntryTree(st);
                               2546                 :                : 
                               2547         [ +  + ]:           4584 :     if (entry != NULL)
                               2548                 :                :     {
                               2549                 :                :         Datum       result;
                               2550                 :                :         char       *values[3];
                               2551                 :                :         char        ndoc[16];
                               2552                 :                :         char        nentry[16];
                               2553                 :                :         HeapTuple   tuple;
                               2554                 :                : 
                               2555                 :           4576 :         values[0] = palloc(entry->lenlexeme + 1);
                               2556                 :           4576 :         memcpy(values[0], entry->lexeme, entry->lenlexeme);
                               2557                 :           4576 :         (values[0])[entry->lenlexeme] = '\0';
 6946 tgl@sss.pgh.pa.us        2558                 :           4576 :         sprintf(ndoc, "%d", entry->ndoc);
                               2559                 :           4576 :         values[1] = ndoc;
                               2560                 :           4576 :         sprintf(nentry, "%d", entry->nentry);
                               2561                 :           4576 :         values[2] = nentry;
                               2562                 :                : 
                               2563                 :           4576 :         tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
                               2564                 :           4576 :         result = HeapTupleGetDatum(tuple);
                               2565                 :                : 
                               2566                 :           4576 :         pfree(values[0]);
                               2567                 :                : 
                               2568                 :                :         /* mark entry as already visited */
 6492 teodor@sigaev.ru         2569                 :           4576 :         entry->ndoc = 0;
                               2570                 :                : 
 6946 tgl@sss.pgh.pa.us        2571                 :           4576 :         return result;
                               2572                 :                :     }
                               2573                 :                : 
                               2574                 :              8 :     return (Datum) 0;
                               2575                 :                : }
                               2576                 :                : 
                               2577                 :                : static TSVectorStat *
 6492 teodor@sigaev.ru         2578                 :              8 : ts_stat_sql(MemoryContext persistentContext, text *txt, text *ws)
                               2579                 :                : {
 6729 tgl@sss.pgh.pa.us        2580                 :              8 :     char       *query = text_to_cstring(txt);
                               2581                 :                :     TSVectorStat *stat;
                               2582                 :                :     bool        isnull;
                               2583                 :                :     Portal      portal;
                               2584                 :                :     SPIPlanPtr  plan;
                               2585                 :                : 
 6946                          2586         [ -  + ]:              8 :     if ((plan = SPI_prepare(query, 0, NULL)) == NULL)
                               2587                 :                :         /* internal error */
 6946 tgl@sss.pgh.pa.us        2588         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_prepare(\"%s\") failed", query);
                               2589                 :                : 
 6882 tgl@sss.pgh.pa.us        2590         [ -  + ]:CBC           8 :     if ((portal = SPI_cursor_open(NULL, plan, NULL, NULL, true)) == NULL)
                               2591                 :                :         /* internal error */
 6946 tgl@sss.pgh.pa.us        2592         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_cursor_open(\"%s\") failed", query);
                               2593                 :                : 
 6946 tgl@sss.pgh.pa.us        2594                 :CBC           8 :     SPI_cursor_fetch(portal, true, 100);
                               2595                 :                : 
 6882                          2596         [ +  - ]:              8 :     if (SPI_tuptable == NULL ||
                               2597         [ +  - ]:              8 :         SPI_tuptable->tupdesc->natts != 1 ||
 3997 teodor@sigaev.ru         2598         [ -  + ]:              8 :         !IsBinaryCoercible(SPI_gettypeid(SPI_tuptable->tupdesc, 1),
                               2599                 :                :                            TSVECTOROID))
 6946 tgl@sss.pgh.pa.us        2600         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2601                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2602                 :                :                  errmsg("ts_stat query must return one tsvector column")));
                               2603                 :                : 
 6492 teodor@sigaev.ru         2604                 :CBC           8 :     stat = MemoryContextAllocZero(persistentContext, sizeof(TSVectorStat));
                               2605                 :              8 :     stat->maxdepth = 1;
                               2606                 :                : 
 6946 tgl@sss.pgh.pa.us        2607         [ +  + ]:              8 :     if (ws)
                               2608                 :                :     {
                               2609                 :                :         char       *buf;
                               2610                 :                :         const char *end;
                               2611                 :                : 
 3455 noah@leadboat.com        2612                 :              4 :         buf = VARDATA_ANY(ws);
  232 tmunro@postgresql.or     2613                 :              4 :         end = buf + VARSIZE_ANY_EXHDR(ws);
                               2614         [ +  + ]:             12 :         while (buf < end)
                               2615                 :                :         {
                               2616                 :              8 :             int         len = pg_mblen_range(buf, end);
                               2617                 :                : 
                               2618         [ +  - ]:              8 :             if (len == 1)
                               2619                 :                :             {
 6946 tgl@sss.pgh.pa.us        2620   [ +  +  -  -  :              8 :                 switch (*buf)
                                                 - ]
                               2621                 :                :                 {
                               2622                 :              4 :                     case 'A':
                               2623                 :                :                     case 'a':
                               2624                 :              4 :                         stat->weight |= 1 << 3;
                               2625                 :              4 :                         break;
                               2626                 :              4 :                     case 'B':
                               2627                 :                :                     case 'b':
                               2628                 :              4 :                         stat->weight |= 1 << 2;
                               2629                 :              4 :                         break;
 6946 tgl@sss.pgh.pa.us        2630                 :UBC           0 :                     case 'C':
                               2631                 :                :                     case 'c':
                               2632                 :              0 :                         stat->weight |= 1 << 1;
                               2633                 :              0 :                         break;
                               2634                 :              0 :                     case 'D':
                               2635                 :                :                     case 'd':
                               2636                 :              0 :                         stat->weight |= 1;
                               2637                 :              0 :                         break;
                               2638                 :              0 :                     default:
                               2639                 :              0 :                         stat->weight |= 0;
                               2640                 :                :                 }
                               2641                 :                :             }
  232 tmunro@postgresql.or     2642                 :CBC           8 :             buf += len;
                               2643                 :                :         }
                               2644                 :                :     }
                               2645                 :                : 
 6946 tgl@sss.pgh.pa.us        2646         [ +  + ]:             56 :     while (SPI_processed > 0)
                               2647                 :                :     {
                               2648                 :                :         uint64      i;
                               2649                 :                : 
                               2650         [ +  + ]:           4120 :         for (i = 0; i < SPI_processed; i++)
                               2651                 :                :         {
                               2652                 :           4072 :             Datum       data = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull);
                               2653                 :                : 
                               2654         [ +  - ]:           4072 :             if (!isnull)
 6492 teodor@sigaev.ru         2655                 :           4072 :                 stat = ts_accum(persistentContext, stat, data);
                               2656                 :                :         }
                               2657                 :                : 
 6946 tgl@sss.pgh.pa.us        2658                 :             48 :         SPI_freetuptable(SPI_tuptable);
                               2659                 :             48 :         SPI_cursor_fetch(portal, true, 100);
                               2660                 :                :     }
                               2661                 :                : 
                               2662                 :              8 :     SPI_freetuptable(SPI_tuptable);
                               2663                 :              8 :     SPI_cursor_close(portal);
                               2664                 :              8 :     SPI_freeplan(plan);
                               2665                 :              8 :     pfree(query);
                               2666                 :                : 
                               2667                 :              8 :     return stat;
                               2668                 :                : }
                               2669                 :                : 
                               2670                 :                : Datum
                               2671                 :           4576 : ts_stat1(PG_FUNCTION_ARGS)
                               2672                 :                : {
                               2673                 :                :     FuncCallContext *funcctx;
                               2674                 :                :     Datum       result;
                               2675                 :                : 
                               2676         [ +  + ]:           4576 :     if (SRF_IS_FIRSTCALL())
                               2677                 :                :     {
                               2678                 :                :         TSVectorStat *stat;
 3455 noah@leadboat.com        2679                 :              4 :         text       *txt = PG_GETARG_TEXT_PP(0);
                               2680                 :                : 
 6946 tgl@sss.pgh.pa.us        2681                 :              4 :         funcctx = SRF_FIRSTCALL_INIT();
                               2682                 :              4 :         SPI_connect();
 6492 teodor@sigaev.ru         2683                 :              4 :         stat = ts_stat_sql(funcctx->multi_call_memory_ctx, txt, NULL);
 6946 tgl@sss.pgh.pa.us        2684         [ -  + ]:              4 :         PG_FREE_IF_COPY(txt, 0);
                               2685                 :              4 :         ts_setup_firstcall(fcinfo, funcctx, stat);
                               2686                 :              4 :         SPI_finish();
                               2687                 :                :     }
                               2688                 :                : 
                               2689                 :           4576 :     funcctx = SRF_PERCALL_SETUP();
                               2690         [ +  + ]:           4576 :     if ((result = ts_process_call(funcctx)) != (Datum) 0)
                               2691                 :           4572 :         SRF_RETURN_NEXT(funcctx, result);
                               2692                 :              4 :     SRF_RETURN_DONE(funcctx);
                               2693                 :                : }
                               2694                 :                : 
                               2695                 :                : Datum
                               2696                 :              8 : ts_stat2(PG_FUNCTION_ARGS)
                               2697                 :                : {
                               2698                 :                :     FuncCallContext *funcctx;
                               2699                 :                :     Datum       result;
                               2700                 :                : 
                               2701         [ +  + ]:              8 :     if (SRF_IS_FIRSTCALL())
                               2702                 :                :     {
                               2703                 :                :         TSVectorStat *stat;
 3455 noah@leadboat.com        2704                 :              4 :         text       *txt = PG_GETARG_TEXT_PP(0);
                               2705                 :              4 :         text       *ws = PG_GETARG_TEXT_PP(1);
                               2706                 :                : 
 6946 tgl@sss.pgh.pa.us        2707                 :              4 :         funcctx = SRF_FIRSTCALL_INIT();
                               2708                 :              4 :         SPI_connect();
 6492 teodor@sigaev.ru         2709                 :              4 :         stat = ts_stat_sql(funcctx->multi_call_memory_ctx, txt, ws);
 6946 tgl@sss.pgh.pa.us        2710         [ -  + ]:              4 :         PG_FREE_IF_COPY(txt, 0);
                               2711         [ -  + ]:              4 :         PG_FREE_IF_COPY(ws, 1);
                               2712                 :              4 :         ts_setup_firstcall(fcinfo, funcctx, stat);
                               2713                 :              4 :         SPI_finish();
                               2714                 :                :     }
                               2715                 :                : 
                               2716                 :              8 :     funcctx = SRF_PERCALL_SETUP();
                               2717         [ +  + ]:              8 :     if ((result = ts_process_call(funcctx)) != (Datum) 0)
                               2718                 :              4 :         SRF_RETURN_NEXT(funcctx, result);
                               2719                 :              4 :     SRF_RETURN_DONE(funcctx);
                               2720                 :                : }
                               2721                 :                : 
                               2722                 :                : 
                               2723                 :                : /*
                               2724                 :                :  * Triggers for automatic update of a tsvector column from text column(s)
                               2725                 :                :  *
                               2726                 :                :  * Trigger arguments are either
                               2727                 :                :  *      name of tsvector col, name of tsconfig to use, name(s) of text col(s)
                               2728                 :                :  *      name of tsvector col, name of regconfig col, name(s) of text col(s)
                               2729                 :                :  * ie, tsconfig can either be specified by name, or indirectly as the
                               2730                 :                :  * contents of a regconfig field in the row.  If the name is used, it must
                               2731                 :                :  * be explicitly schema-qualified.
                               2732                 :                :  */
                               2733                 :                : Datum
                               2734                 :             12 : tsvector_update_trigger_byid(PG_FUNCTION_ARGS)
                               2735                 :                : {
                               2736                 :             12 :     return tsvector_update_trigger(fcinfo, false);
                               2737                 :                : }
                               2738                 :                : 
                               2739                 :                : Datum
 6946 tgl@sss.pgh.pa.us        2740                 :UBC           0 : tsvector_update_trigger_bycolumn(PG_FUNCTION_ARGS)
                               2741                 :                : {
                               2742                 :              0 :     return tsvector_update_trigger(fcinfo, true);
                               2743                 :                : }
                               2744                 :                : 
                               2745                 :                : static Datum
 6946 tgl@sss.pgh.pa.us        2746                 :CBC          12 : tsvector_update_trigger(PG_FUNCTION_ARGS, bool config_column)
                               2747                 :                : {
                               2748                 :                :     TriggerData *trigdata;
                               2749                 :                :     Trigger    *trigger;
                               2750                 :                :     Relation    rel;
                               2751                 :             12 :     HeapTuple   rettuple = NULL;
                               2752                 :                :     int         tsvector_attr_num,
                               2753                 :                :                 i;
                               2754                 :                :     ParsedText  prs;
                               2755                 :                :     Datum       datum;
                               2756                 :                :     bool        isnull;
                               2757                 :                :     text       *txt;
                               2758                 :                :     Oid         cfgId;
                               2759                 :                :     bool        update_needed;
                               2760                 :                : 
                               2761                 :                :     /* Check call context */
 3354                          2762   [ +  -  -  + ]:             12 :     if (!CALLED_AS_TRIGGER(fcinfo)) /* internal error */
 6946 tgl@sss.pgh.pa.us        2763         [ #  # ]:UBC           0 :         elog(ERROR, "tsvector_update_trigger: not fired by trigger manager");
                               2764                 :                : 
 6946 tgl@sss.pgh.pa.us        2765                 :CBC          12 :     trigdata = (TriggerData *) fcinfo->context;
 5802                          2766         [ -  + ]:             12 :     if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
 5802 tgl@sss.pgh.pa.us        2767         [ #  # ]:UBC           0 :         elog(ERROR, "tsvector_update_trigger: must be fired for row");
 5802 tgl@sss.pgh.pa.us        2768         [ -  + ]:CBC          12 :     if (!TRIGGER_FIRED_BEFORE(trigdata->tg_event))
 6946 tgl@sss.pgh.pa.us        2769         [ #  # ]:UBC           0 :         elog(ERROR, "tsvector_update_trigger: must be fired BEFORE event");
                               2770                 :                : 
 6946 tgl@sss.pgh.pa.us        2771         [ +  + ]:CBC          12 :     if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
                               2772                 :                :     {
                               2773                 :              8 :         rettuple = trigdata->tg_trigtuple;
 2362 peter@eisentraut.org     2774                 :              8 :         update_needed = true;
                               2775                 :                :     }
 6946 tgl@sss.pgh.pa.us        2776         [ +  - ]:              4 :     else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
                               2777                 :                :     {
                               2778                 :              4 :         rettuple = trigdata->tg_newtuple;
 2362 peter@eisentraut.org     2779                 :              4 :         update_needed = false;  /* computed below */
                               2780                 :                :     }
                               2781                 :                :     else
 6946 tgl@sss.pgh.pa.us        2782         [ #  # ]:UBC           0 :         elog(ERROR, "tsvector_update_trigger: must be fired for INSERT or UPDATE");
                               2783                 :                : 
 6946 tgl@sss.pgh.pa.us        2784                 :CBC          12 :     trigger = trigdata->tg_trigger;
                               2785                 :             12 :     rel = trigdata->tg_relation;
                               2786                 :                : 
                               2787         [ -  + ]:             12 :     if (trigger->tgnargs < 3)
 6946 tgl@sss.pgh.pa.us        2788         [ #  # ]:UBC           0 :         elog(ERROR, "tsvector_update_trigger: arguments must be tsvector_field, ts_config, text_field1, ...)");
                               2789                 :                : 
                               2790                 :                :     /* Find the target tsvector column */
 6946 tgl@sss.pgh.pa.us        2791                 :CBC          12 :     tsvector_attr_num = SPI_fnumber(rel->rd_att, trigger->tgargs[0]);
                               2792         [ -  + ]:             12 :     if (tsvector_attr_num == SPI_ERROR_NOATTRIBUTE)
 6946 tgl@sss.pgh.pa.us        2793         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2794                 :                :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
                               2795                 :                :                  errmsg("tsvector column \"%s\" does not exist",
                               2796                 :                :                         trigger->tgargs[0])));
                               2797                 :                :     /* This will effectively reject system columns, so no separate test: */
 3997 teodor@sigaev.ru         2798         [ -  + ]:CBC          12 :     if (!IsBinaryCoercible(SPI_gettypeid(rel->rd_att, tsvector_attr_num),
                               2799                 :                :                            TSVECTOROID))
 6946 tgl@sss.pgh.pa.us        2800         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2801                 :                :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
                               2802                 :                :                  errmsg("column \"%s\" is not of type %s",
                               2803                 :                :                         trigger->tgargs[0], "tsvector")));
                               2804                 :                : 
                               2805                 :                :     /* Find the configuration to use */
 6946 tgl@sss.pgh.pa.us        2806         [ -  + ]:CBC          12 :     if (config_column)
                               2807                 :                :     {
                               2808                 :                :         int         config_attr_num;
                               2809                 :                : 
 6946 tgl@sss.pgh.pa.us        2810                 :UBC           0 :         config_attr_num = SPI_fnumber(rel->rd_att, trigger->tgargs[1]);
                               2811         [ #  # ]:              0 :         if (config_attr_num == SPI_ERROR_NOATTRIBUTE)
                               2812         [ #  # ]:              0 :             ereport(ERROR,
                               2813                 :                :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
                               2814                 :                :                      errmsg("configuration column \"%s\" does not exist",
                               2815                 :                :                             trigger->tgargs[1])));
 3997 teodor@sigaev.ru         2816         [ #  # ]:              0 :         if (!IsBinaryCoercible(SPI_gettypeid(rel->rd_att, config_attr_num),
                               2817                 :                :                                REGCONFIGOID))
 6946 tgl@sss.pgh.pa.us        2818         [ #  # ]:              0 :             ereport(ERROR,
                               2819                 :                :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
                               2820                 :                :                      errmsg("column \"%s\" is not of type %s",
                               2821                 :                :                             trigger->tgargs[1], "regconfig")));
                               2822                 :                : 
                               2823                 :              0 :         datum = SPI_getbinval(rettuple, rel->rd_att, config_attr_num, &isnull);
                               2824         [ #  # ]:              0 :         if (isnull)
                               2825         [ #  # ]:              0 :             ereport(ERROR,
                               2826                 :                :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                               2827                 :                :                      errmsg("configuration column \"%s\" must not be null",
                               2828                 :                :                             trigger->tgargs[1])));
                               2829                 :              0 :         cfgId = DatumGetObjectId(datum);
                               2830                 :                :     }
                               2831                 :                :     else
                               2832                 :                :     {
                               2833                 :                :         List       *names;
                               2834                 :                : 
 1339 tgl@sss.pgh.pa.us        2835                 :CBC          12 :         names = stringToQualifiedNameList(trigger->tgargs[1], NULL);
                               2836                 :                :         /* require a schema so that results are not search path dependent */
 6946                          2837         [ -  + ]:             12 :         if (list_length(names) < 2)
 6946 tgl@sss.pgh.pa.us        2838         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2839                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2840                 :                :                      errmsg("text search configuration name \"%s\" must be schema-qualified",
                               2841                 :                :                             trigger->tgargs[1])));
 5866 rhaas@postgresql.org     2842                 :CBC          12 :         cfgId = get_ts_config_oid(names, false);
                               2843                 :                :     }
                               2844                 :                : 
                               2845                 :                :     /* initialize parse state */
 6946 tgl@sss.pgh.pa.us        2846                 :             12 :     prs.lenwords = 32;
                               2847                 :             12 :     prs.curwords = 0;
                               2848                 :             12 :     prs.pos = 0;
  260 michael@paquier.xyz      2849                 :             12 :     prs.words = palloc_array(ParsedWord, prs.lenwords);
                               2850                 :                : 
                               2851                 :                :     /* find all words in indexable column(s) */
 6946 tgl@sss.pgh.pa.us        2852         [ +  + ]:             24 :     for (i = 2; i < trigger->tgnargs; i++)
                               2853                 :                :     {
                               2854                 :                :         int         numattr;
                               2855                 :                : 
                               2856                 :             12 :         numattr = SPI_fnumber(rel->rd_att, trigger->tgargs[i]);
                               2857         [ -  + ]:             12 :         if (numattr == SPI_ERROR_NOATTRIBUTE)
 6946 tgl@sss.pgh.pa.us        2858         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2859                 :                :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
                               2860                 :                :                      errmsg("column \"%s\" does not exist",
                               2861                 :                :                             trigger->tgargs[i])));
 3997 teodor@sigaev.ru         2862         [ -  + ]:CBC          12 :         if (!IsBinaryCoercible(SPI_gettypeid(rel->rd_att, numattr), TEXTOID))
 6946 tgl@sss.pgh.pa.us        2863         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2864                 :                :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
                               2865                 :                :                      errmsg("column \"%s\" is not of a character type",
                               2866                 :                :                             trigger->tgargs[i])));
                               2867                 :                : 
 2362 peter@eisentraut.org     2868         [ +  + ]:CBC          12 :         if (bms_is_member(numattr - FirstLowInvalidHeapAttributeNumber, trigdata->tg_updatedcols))
                               2869                 :              4 :             update_needed = true;
                               2870                 :                : 
 6946 tgl@sss.pgh.pa.us        2871                 :             12 :         datum = SPI_getbinval(rettuple, rel->rd_att, numattr, &isnull);
                               2872         [ +  + ]:             12 :         if (isnull)
                               2873                 :              4 :             continue;
                               2874                 :                : 
 3455 noah@leadboat.com        2875                 :              8 :         txt = DatumGetTextPP(datum);
                               2876                 :                : 
                               2877                 :              8 :         parsetext(cfgId, &prs, VARDATA_ANY(txt), VARSIZE_ANY_EXHDR(txt));
                               2878                 :                : 
 6946 tgl@sss.pgh.pa.us        2879         [ -  + ]:              8 :         if (txt != (text *) DatumGetPointer(datum))
 6946 tgl@sss.pgh.pa.us        2880                 :UBC           0 :             pfree(txt);
                               2881                 :                :     }
                               2882                 :                : 
 2362 peter@eisentraut.org     2883         [ +  - ]:CBC          12 :     if (update_needed)
                               2884                 :                :     {
                               2885                 :                :         /* make tsvector value */
                               2886                 :             12 :         datum = TSVectorGetDatum(make_tsvector(&prs));
                               2887                 :             12 :         isnull = false;
                               2888                 :                : 
                               2889                 :                :         /* and insert it into tuple */
                               2890                 :             12 :         rettuple = heap_modify_tuple_by_cols(rettuple, rel->rd_att,
                               2891                 :                :                                              1, &tsvector_attr_num,
                               2892                 :                :                                              &datum, &isnull);
                               2893                 :                : 
                               2894                 :             12 :         pfree(DatumGetPointer(datum));
                               2895                 :                :     }
                               2896                 :                : 
 6946 tgl@sss.pgh.pa.us        2897                 :             12 :     return PointerGetDatum(rettuple);
                               2898                 :                : }
        

Generated by: LCOV version 2.0-1