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

Generated by: LCOV version 2.0-1