Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * tsvector_op.c
4 : : * operations over tsvector
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : *
8 : : *
9 : : * IDENTIFICATION
10 : : * src/backend/utils/adt/tsvector_op.c
11 : : *
12 : : *-------------------------------------------------------------------------
13 : : */
14 : : #include "postgres.h"
15 : :
16 : : #include <limits.h>
17 : :
18 : : #include "access/htup_details.h"
19 : : #include "catalog/namespace.h"
20 : : #include "catalog/pg_type.h"
21 : : #include "commands/trigger.h"
22 : : #include "common/int.h"
23 : : #include "executor/spi.h"
24 : : #include "funcapi.h"
25 : : #include "lib/qunique.h"
26 : : #include "mb/pg_wchar.h"
27 : : #include "miscadmin.h"
28 : : #include "parser/parse_coerce.h"
29 : : #include "tsearch/ts_utils.h"
30 : : #include "utils/array.h"
31 : : #include "utils/builtins.h"
32 : : #include "utils/regproc.h"
33 : : #include "utils/rel.h"
34 : :
35 : :
36 : : typedef struct
37 : : {
38 : : WordEntry *arrb;
39 : : WordEntry *arre;
40 : : char *values;
41 : : char *operand;
42 : : } CHKVAL;
43 : :
44 : :
45 : : typedef struct StatEntry
46 : : {
47 : : uint32 ndoc; /* zero indicates that we were already here
48 : : * while walking through the tree */
49 : : uint32 nentry;
50 : : struct StatEntry *left;
51 : : struct StatEntry *right;
52 : : uint32 lenlexeme;
53 : : 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
86 : 233 : silly_cmp_tsvector(const TSVectorData *a, const TSVectorData *b)
87 : : {
88 [ - + ]: 233 : if (VARSIZE(a) < VARSIZE(b))
89 : 0 : return -1;
90 [ - + ]: 233 : else if (VARSIZE(a) > VARSIZE(b))
91 : 0 : return 1;
92 [ - + ]: 233 : else if (a->size < b->size)
93 : 0 : return -1;
94 [ - + ]: 233 : else if (a->size > b->size)
95 : 0 : return 1;
96 : : else
97 : : {
98 : 233 : const WordEntry *aptr = ARRPTR(a);
99 : 233 : const WordEntry *bptr = ARRPTR(b);
100 : 233 : int i = 0;
101 : : int res;
102 : :
103 : :
104 [ + + ]: 268 : for (i = 0; i < a->size; i++)
105 : : {
106 [ - + ]: 235 : if (aptr->haspos != bptr->haspos)
107 : : {
108 [ # # ]: 0 : return (aptr->haspos > bptr->haspos) ? -1 : 1;
109 : : }
110 [ + + ]: 235 : else if ((res = tsCompareString(STRPTR(a) + aptr->pos, aptr->len, STRPTR(b) + bptr->pos, bptr->len, false)) != 0)
111 : : {
112 : 200 : return res;
113 : : }
114 [ + + ]: 35 : else if (aptr->haspos)
115 : : {
116 : 32 : WordEntryPos *ap = POSDATAPTR(a, aptr);
117 : 32 : WordEntryPos *bp = POSDATAPTR(b, bptr);
118 : : int j;
119 : :
120 [ + - + - : 32 : if (POSDATALEN(a, aptr) != POSDATALEN(b, bptr))
- + ]
121 [ # # # # : 0 : return (POSDATALEN(a, aptr) > POSDATALEN(b, bptr)) ? -1 : 1;
# # ]
122 : :
123 [ + - + + ]: 64 : for (j = 0; j < POSDATALEN(a, aptr); j++)
124 : : {
125 [ - + ]: 32 : if (WEP_GETPOS(*ap) != WEP_GETPOS(*bp))
126 : : {
127 [ # # ]: 0 : return (WEP_GETPOS(*ap) > WEP_GETPOS(*bp)) ? -1 : 1;
128 : : }
129 [ - + ]: 32 : else if (WEP_GETWEIGHT(*ap) != WEP_GETWEIGHT(*bp))
130 : : {
131 [ # # ]: 0 : return (WEP_GETWEIGHT(*ap) > WEP_GETWEIGHT(*bp)) ? -1 : 1;
132 : : }
133 : 32 : ap++, bp++;
134 : : }
135 : : }
136 : :
137 : 35 : aptr++;
138 : 35 : bptr++;
139 : : }
140 : : }
141 : :
142 : 33 : return 0;
143 : : }
144 : :
145 : : #define TSVECTORCMPFUNC( type, action, ret ) \
146 : : Datum \
147 : : tsvector_##type(PG_FUNCTION_ARGS) \
148 : : { \
149 : : TSVector a = PG_GETARG_TSVECTOR(0); \
150 : : TSVector b = PG_GETARG_TSVECTOR(1); \
151 : : int res = silly_cmp_tsvector(a, b); \
152 : : PG_FREE_IF_COPY(a,0); \
153 : : PG_FREE_IF_COPY(b,1); \
154 : : PG_RETURN_##ret( res action 0 ); \
155 : : } \
156 : : /* keep compiler quiet - no extra ; */ \
157 : : extern int no_such_variable
158 : :
159 [ # # # # ]: 0 : TSVECTORCMPFUNC(lt, <, BOOL);
160 [ # # # # ]: 0 : TSVECTORCMPFUNC(le, <=, BOOL);
161 [ - + - + ]: 1 : TSVECTORCMPFUNC(eq, ==, BOOL);
162 [ # # # # ]: 0 : TSVECTORCMPFUNC(ge, >=, BOOL);
163 [ # # # # ]: 0 : TSVECTORCMPFUNC(gt, >, BOOL);
164 [ # # # # ]: 0 : TSVECTORCMPFUNC(ne, !=, BOOL);
165 [ - + - + ]: 232 : TSVECTORCMPFUNC(cmp, +, INT32);
166 : :
167 : : Datum
168 : 73 : tsvector_strip(PG_FUNCTION_ARGS)
169 : : {
170 : 73 : TSVector in = PG_GETARG_TSVECTOR(0);
171 : : TSVector out;
172 : : int i,
173 : 73 : len = 0;
174 : 73 : WordEntry *arrin = ARRPTR(in),
175 : : *arrout;
176 : : char *cur;
177 : :
178 : : /* Output can't be bigger than input, so no need for overflow checks */
179 [ + + ]: 261 : for (i = 0; i < in->size; i++)
180 : 188 : len += arrin[i].len;
181 : :
182 : 73 : len = CALCDATASIZE(in->size, len);
183 : 73 : out = (TSVector) palloc0(len);
184 : 73 : SET_VARSIZE(out, len);
185 : 73 : out->size = in->size;
186 : 73 : arrout = ARRPTR(out);
187 : 73 : cur = STRPTR(out);
188 [ + + ]: 261 : for (i = 0; i < in->size; i++)
189 : : {
190 : 188 : memcpy(cur, STRPTR(in) + arrin[i].pos, arrin[i].len);
191 : 188 : arrout[i].haspos = 0;
192 : 188 : arrout[i].len = arrin[i].len;
193 : 188 : arrout[i].pos = cur - STRPTR(out);
194 : 188 : cur += arrout[i].len;
195 : : }
196 : :
197 [ - + ]: 73 : PG_FREE_IF_COPY(in, 0);
198 : 73 : PG_RETURN_POINTER(out);
199 : : }
200 : :
201 : : Datum
202 : 7 : tsvector_length(PG_FUNCTION_ARGS)
203 : : {
204 : 7 : TSVector in = PG_GETARG_TSVECTOR(0);
205 : 7 : int32 ret = in->size;
206 : :
207 [ - + ]: 7 : PG_FREE_IF_COPY(in, 0);
208 : 7 : PG_RETURN_INT32(ret);
209 : : }
210 : :
211 : : static int
212 : 48 : parse_weight(char cw)
213 : : {
214 : : int w;
215 : :
216 [ + + + - : 48 : switch (cw)
- ]
217 : : {
218 : 14 : case 'A':
219 : : case 'a':
220 : 14 : w = 3;
221 : 14 : break;
222 : 4 : case 'B':
223 : : case 'b':
224 : 4 : w = 2;
225 : 4 : break;
226 : 30 : case 'C':
227 : : case 'c':
228 : 30 : w = 1;
229 : 30 : break;
230 : 0 : case 'D':
231 : : case 'd':
232 : 0 : w = 0;
233 : 0 : break;
234 : 0 : default:
235 : : /* Avoid printing non-ASCII bytes, else we have encoding issues */
236 [ # # # # ]: 0 : if (cw >= ' ' && cw < 0x7f)
237 [ # # ]: 0 : ereport(ERROR,
238 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
239 : : errmsg("unrecognized weight: \"%c\"", cw)));
240 : : else /* use \ooo format, like charout() */
241 [ # # ]: 0 : ereport(ERROR,
242 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
243 : : errmsg("unrecognized weight: \"\\%03o\"",
244 : : (unsigned char) cw)));
245 : : }
246 : 48 : return w;
247 : : }
248 : :
249 : :
250 : : Datum
251 : 10 : tsvector_setweight(PG_FUNCTION_ARGS)
252 : : {
253 : 10 : TSVector in = PG_GETARG_TSVECTOR(0);
254 : 10 : char cw = PG_GETARG_CHAR(1);
255 : : TSVector out;
256 : : int i,
257 : : j;
258 : : WordEntry *entry;
259 : : WordEntryPos *p;
260 : 10 : int w = parse_weight(cw);
261 : :
262 : 10 : out = (TSVector) palloc(VARSIZE(in));
263 : 10 : memcpy(out, in, VARSIZE(in));
264 : 10 : entry = ARRPTR(out);
265 : 10 : i = out->size;
266 [ + + ]: 50 : while (i--)
267 : : {
268 [ + - + - ]: 40 : if ((j = POSDATALEN(out, entry)) != 0)
269 : : {
270 : 40 : p = POSDATAPTR(out, entry);
271 [ + + ]: 140 : while (j--)
272 : : {
273 : 100 : WEP_SETWEIGHT(*p, w);
274 : 100 : p++;
275 : : }
276 : : }
277 : 40 : entry++;
278 : : }
279 : :
280 [ - + ]: 10 : PG_FREE_IF_COPY(in, 0);
281 : 10 : PG_RETURN_POINTER(out);
282 : : }
283 : :
284 : : /*
285 : : * setweight(tsin tsvector, char_weight "char", lexemes "text"[])
286 : : *
287 : : * Assign weight w to elements of tsin that are listed in lexemes.
288 : : */
289 : : Datum
290 : 20 : tsvector_setweight_by_filter(PG_FUNCTION_ARGS)
291 : : {
292 : 20 : TSVector tsin = PG_GETARG_TSVECTOR(0);
293 : 20 : char char_weight = PG_GETARG_CHAR(1);
294 : 20 : ArrayType *lexemes = PG_GETARG_ARRAYTYPE_P(2);
295 : :
296 : : TSVector tsout;
297 : : int i,
298 : : j,
299 : : nlexemes,
300 : : weight;
301 : : WordEntry *entry;
302 : : Datum *dlexemes;
303 : : bool *nulls;
304 : :
305 : 20 : weight = parse_weight(char_weight);
306 : :
307 : 20 : tsout = (TSVector) palloc(VARSIZE(tsin));
308 : 20 : memcpy(tsout, tsin, VARSIZE(tsin));
309 : 20 : entry = ARRPTR(tsout);
310 : :
311 : 20 : deconstruct_array_builtin(lexemes, TEXTOID, &dlexemes, &nulls, &nlexemes);
312 : :
313 : : /*
314 : : * Assuming that lexemes array is significantly shorter than tsvector we
315 : : * can iterate through lexemes performing binary search of each lexeme
316 : : * from lexemes in tsvector.
317 : : */
318 [ + + ]: 60 : for (i = 0; i < nlexemes; i++)
319 : : {
320 : : char *lex;
321 : : int lex_len,
322 : : lex_pos;
323 : :
324 : : /* Ignore null array elements, they surely don't match */
325 [ + + ]: 40 : if (nulls[i])
326 : 5 : continue;
327 : :
328 : 35 : lex = VARDATA(DatumGetPointer(dlexemes[i]));
329 : 35 : lex_len = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
330 : 35 : lex_pos = tsvector_bsearch(tsout, lex, lex_len);
331 : :
332 [ + + + + : 35 : if (lex_pos >= 0 && (j = POSDATALEN(tsout, entry + lex_pos)) != 0)
+ + ]
333 : : {
334 : 20 : WordEntryPos *p = POSDATAPTR(tsout, entry + lex_pos);
335 : :
336 [ + + ]: 65 : while (j--)
337 : : {
338 : 45 : WEP_SETWEIGHT(*p, weight);
339 : 45 : p++;
340 : : }
341 : : }
342 : : }
343 : :
344 [ - + ]: 20 : PG_FREE_IF_COPY(tsin, 0);
345 [ - + ]: 20 : PG_FREE_IF_COPY(lexemes, 2);
346 : :
347 : 20 : PG_RETURN_POINTER(tsout);
348 : : }
349 : :
350 : : #define compareEntry(pa, a, pb, b) \
351 : : tsCompareString((pa) + (a)->pos, (a)->len, \
352 : : (pb) + (b)->pos, (b)->len, \
353 : : false)
354 : :
355 : : /*
356 : : * Add positions from src to dest after offsetting them by maxpos.
357 : : * Return the number added (might be less than expected due to overflow)
358 : : */
359 : : static int32
360 : 10 : add_pos(TSVector src, WordEntry *srcptr,
361 : : TSVector dest, WordEntry *destptr,
362 : : int32 maxpos)
363 : : {
364 : 10 : uint16 *clen = &_POSVECPTR(dest, destptr)->npos;
365 : : int i;
366 [ + - ]: 10 : uint16 slen = POSDATALEN(src, srcptr),
367 : : startlen;
368 : 10 : WordEntryPos *spos = POSDATAPTR(src, srcptr),
369 : 10 : *dpos = POSDATAPTR(dest, destptr);
370 : :
371 [ - + ]: 10 : if (!destptr->haspos)
372 : 0 : *clen = 0;
373 : :
374 : 10 : startlen = *clen;
375 : 10 : for (i = 0;
376 [ + + + - ]: 20 : i < slen && *clen < MAXNUMPOS &&
377 [ + + + - ]: 10 : (*clen == 0 || WEP_GETPOS(dpos[*clen - 1]) != MAXENTRYPOS - 1);
378 : 10 : i++)
379 : : {
380 : 10 : WEP_SETWEIGHT(dpos[*clen], WEP_GETWEIGHT(spos[i]));
381 : 10 : WEP_SETPOS(dpos[*clen], LIMITPOS(WEP_GETPOS(spos[i]) + maxpos));
382 : 10 : (*clen)++;
383 : : }
384 : :
385 [ + - ]: 10 : if (*clen != startlen)
386 : 10 : destptr->haspos = 1;
387 : 10 : return *clen - startlen;
388 : : }
389 : :
390 : : /*
391 : : * Perform binary search of given lexeme in TSVector.
392 : : * Returns lexeme position in TSVector's entry array or -1 if lexeme wasn't
393 : : * found.
394 : : */
395 : : static int
396 : 165 : tsvector_bsearch(const TSVectorData *tsv, char *lexeme, int lexeme_len)
397 : : {
398 : 165 : const WordEntry *arrin = ARRPTR(tsv);
399 : 165 : int StopLow = 0,
400 : 165 : StopHigh = tsv->size,
401 : : StopMiddle,
402 : : cmp;
403 : :
404 [ + + ]: 435 : while (StopLow < StopHigh)
405 : : {
406 : 385 : StopMiddle = (StopLow + StopHigh) / 2;
407 : :
408 : 385 : cmp = tsCompareString(lexeme, lexeme_len,
409 : 385 : STRPTR(tsv) + arrin[StopMiddle].pos,
410 : 385 : arrin[StopMiddle].len,
411 : : false);
412 : :
413 [ + + ]: 385 : if (cmp < 0)
414 : 180 : StopHigh = StopMiddle;
415 [ + + ]: 205 : else if (cmp > 0)
416 : 90 : StopLow = StopMiddle + 1;
417 : : else /* found it */
418 : 115 : return StopMiddle;
419 : : }
420 : :
421 : 50 : return -1;
422 : : }
423 : :
424 : : /*
425 : : * qsort comparator functions
426 : : */
427 : :
428 : : static int
429 : 65 : compare_int(const void *va, const void *vb)
430 : : {
431 : 65 : int a = *((const int *) va);
432 : 65 : int b = *((const int *) vb);
433 : :
434 : 65 : return pg_cmp_s32(a, b);
435 : : }
436 : :
437 : : static int
438 : 85 : compare_text_lexemes(const void *va, const void *vb)
439 : : {
440 : 85 : Datum a = *((const Datum *) va);
441 : 85 : Datum b = *((const Datum *) vb);
442 : 85 : char *alex = VARDATA_ANY(DatumGetPointer(a));
443 : 85 : int alex_len = VARSIZE_ANY_EXHDR(DatumGetPointer(a));
444 : 85 : char *blex = VARDATA_ANY(DatumGetPointer(b));
445 : 85 : int blex_len = VARSIZE_ANY_EXHDR(DatumGetPointer(b));
446 : :
447 : 85 : return tsCompareString(alex, alex_len, blex, blex_len, false);
448 : : }
449 : :
450 : : /*
451 : : * Internal routine to delete lexemes from TSVector by array of offsets.
452 : : *
453 : : * int *indices_to_delete -- array of lexeme offsets to delete (modified here!)
454 : : * int indices_count -- size of that array
455 : : *
456 : : * Returns new TSVector without given lexemes along with their positions
457 : : * and weights.
458 : : */
459 : : static TSVector
460 : 55 : tsvector_delete_by_indices(TSVector tsv, int *indices_to_delete,
461 : : int indices_count)
462 : : {
463 : : TSVector tsout;
464 : 55 : WordEntry *arrin = ARRPTR(tsv),
465 : : *arrout;
466 : 55 : char *data = STRPTR(tsv),
467 : : *dataout;
468 : : int i, /* index in arrin */
469 : : j, /* index in arrout */
470 : : k, /* index in indices_to_delete */
471 : : curoff; /* index in dataout area */
472 : :
473 : : /*
474 : : * Sort the filter array to simplify membership checks below. Also, get
475 : : * rid of any duplicate entries, so that we can assume that indices_count
476 : : * is exactly equal to the number of lexemes that will be removed.
477 : : */
478 [ + + ]: 55 : if (indices_count > 1)
479 : : {
480 : 25 : qsort(indices_to_delete, indices_count, sizeof(int), compare_int);
481 : 25 : indices_count = qunique(indices_to_delete, indices_count, sizeof(int),
482 : : compare_int);
483 : : }
484 : :
485 : : /*
486 : : * Here we overestimate tsout size, since we don't know how much space is
487 : : * used by the deleted lexeme(s). We will set exact size below.
488 : : *
489 : : * 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 : : */
499 : 55 : tsout = (TSVector) palloc0(VARSIZE(tsv) + tsv->size - indices_count);
500 : :
501 : : /* This count must be correct because STRPTR(tsout) relies on it. */
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);
508 : 55 : dataout = STRPTR(tsout);
509 : 55 : curoff = 0;
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 : : */
517 [ + + + + ]: 275 : if (k < indices_count && i == indices_to_delete[k])
518 : : {
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 : : {
531 [ + - ]: 130 : int len = POSDATALEN(tsv, arrin + i) * sizeof(WordEntryPos)
532 : 130 : + sizeof(uint16);
533 : :
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 : : 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 : : */
555 [ - + ]: 55 : if (curoff > MAXSTRPOS)
556 [ # # ]: 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 : :
561 : 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;
574 : 30 : text *tlexeme = PG_GETARG_TEXT_PP(1);
575 : 30 : char *lexeme = VARDATA_ANY(tlexeme);
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 : :
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 : : */
613 : 35 : skip_indices = palloc0_array(int, nlex);
614 [ + + ]: 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])
622 : 5 : continue;
623 : :
624 : 100 : lex = VARDATA(DatumGetPointer(dlexemes[i]));
625 : 100 : lex_len = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
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 : :
661 : 20 : tupdesc = CreateTemplateTupleDesc(3);
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);
668 [ - + ]: 20 : if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
669 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
670 : 20 : TupleDescFinalize(tupdesc);
671 : 20 : funcctx->tuple_desc = tupdesc;
672 : :
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 : :
691 : 100 : values[0] = PointerGetDatum(cstring_to_text_with_len(data + arrin[i].pos, arrin[i].len));
692 : :
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);
706 : 60 : positions = palloc_array(Datum, posv->npos);
707 : 60 : weights = palloc_array(Datum, posv->npos);
708 [ + + ]: 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]);
712 : 108 : weights[j] = PointerGetDatum(cstring_to_text_with_len(&weight,
713 : : 1));
714 : : }
715 : :
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 : : {
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 : : {
739 : 10 : TSVector tsin = PG_GETARG_TSVECTOR(0);
740 : 10 : WordEntry *arrin = ARRPTR(tsin);
741 : : Datum *elements;
742 : : int i;
743 : : ArrayType *array;
744 : :
745 : 10 : elements = palloc_array(Datum, tsin->size);
746 : :
747 [ + + ]: 60 : for (i = 0; i < tsin->size; i++)
748 : : {
749 : 50 : elements[i] = PointerGetDatum(cstring_to_text_with_len(STRPTR(tsin) + arrin[i].pos,
750 : : arrin[i].len));
751 : : }
752 : :
753 : 10 : array = construct_array_builtin(elements, tsin->size, TEXTOID);
754 : :
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 : :
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 : : */
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 : :
792 : 81 : toklen = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
793 [ + + ]: 81 : if (toklen == 0)
794 [ + - ]: 4 : ereport(ERROR,
795 : : (errcode(ERRCODE_ZERO_LENGTH_CHARACTER_STRING),
796 : : errmsg("lexeme array may not contain empty strings")));
797 [ - + ]: 77 : if (toklen > MAXSTRLEN)
798 [ # # ]: 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. */
806 [ + - ]: 10 : if (nitems > 1)
807 : : {
808 : 10 : qsort(dlexemes, nitems, sizeof(Datum), compare_text_lexemes);
809 : 10 : nitems = qunique(dlexemes, nitems, sizeof(Datum),
810 : : compare_text_lexemes);
811 : : }
812 : :
813 : : /* Calculate space needed for surviving lexemes. */
814 [ + + ]: 50 : for (i = 0; i < nitems; i++)
815 : 40 : datalen += VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
816 [ - + ]: 10 : if (datalen > MAXSTRPOS)
817 [ # # ]: 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)));
821 : 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 : : {
832 : 40 : char *lex = VARDATA(DatumGetPointer(dlexemes[i]));
833 : 40 : int lex_len = VARSIZE(DatumGetPointer(dlexemes[i])) - VARHDRSZ;
834 : :
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;
864 : 14 : int cur_pos = 0;
865 : 14 : char mask = 0;
866 : :
867 : 14 : deconstruct_array_builtin(weights, CHAROID, &dweights, &nulls, &nweights);
868 : :
869 [ + + ]: 32 : for (i = 0; i < nweights; i++)
870 : : {
871 : : char char_weight;
872 : :
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]);
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 : : */
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;
897 : 80 : int npos = 0;
898 : : int k;
899 : :
900 [ + + ]: 80 : if (!arrin[i].haspos)
901 : 25 : continue;
902 : :
903 : 55 : posvin = _POSVECPTR(tsin, arrin + i);
904 : 55 : posvout = (WordEntryPosVector *)
905 : 55 : (dataout + SHORTALIGN(cur_pos + arrin[i].len));
906 : :
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 */
914 [ + + ]: 55 : if (!npos)
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);
924 [ + - ]: 25 : cur_pos += POSDATALEN(tsout, arrout + j) * sizeof(WordEntryPos) +
925 : : sizeof(uint16);
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
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 : : */
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 : : */
1006 : 9 : out->size = in1->size + in2->size;
1007 : :
1008 : 9 : ptr = ARRPTR(out);
1009 : 9 : data = STRPTR(out);
1010 : 9 : dataoff = 0;
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;
1019 : 5 : memcpy(data + dataoff, data1 + ptr1->pos, ptr1->len);
1020 : 5 : ptr->pos = dataoff;
1021 : 5 : dataoff += ptr1->len;
1022 [ + - ]: 5 : if (ptr->haspos)
1023 : : {
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 : :
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;
1037 : 4 : memcpy(data + dataoff, data2 + ptr2->pos, ptr2->len);
1038 : 4 : ptr->pos = dataoff;
1039 : 4 : dataoff += ptr2->len;
1040 [ - + ]: 4 : if (ptr->haspos)
1041 : : {
1042 : 0 : int addlen = add_pos(in2, ptr2, out, ptr, maxpos);
1043 : :
1044 [ # # ]: 0 : if (addlen == 0)
1045 : 0 : ptr->haspos = 0;
1046 : : else
1047 : : {
1048 : 0 : dataoff = SHORTALIGN(dataoff);
1049 : 0 : dataoff += addlen * sizeof(WordEntryPos) + sizeof(uint16);
1050 : : }
1051 : : }
1052 : :
1053 : 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;
1061 : 5 : memcpy(data + dataoff, data1 + ptr1->pos, ptr1->len);
1062 : 5 : ptr->pos = dataoff;
1063 : 5 : dataoff += ptr1->len;
1064 [ + - ]: 5 : if (ptr->haspos)
1065 : : {
1066 [ + - ]: 5 : if (ptr1->haspos)
1067 : : {
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);
1071 [ + - ]: 5 : if (ptr2->haspos)
1072 : 5 : dataoff += add_pos(in2, ptr2, out, ptr, maxpos) * sizeof(WordEntryPos);
1073 : : }
1074 : : else /* must have ptr2->haspos */
1075 : : {
1076 : 0 : int addlen = add_pos(in2, ptr2, out, ptr, maxpos);
1077 : :
1078 [ # # ]: 0 : if (addlen == 0)
1079 : 0 : ptr->haspos = 0;
1080 : : else
1081 : : {
1082 : 0 : dataoff = SHORTALIGN(dataoff);
1083 : 0 : dataoff += addlen * sizeof(WordEntryPos) + sizeof(uint16);
1084 : : }
1085 : : }
1086 : : }
1087 : :
1088 : 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;
1100 : 4 : memcpy(data + dataoff, data1 + ptr1->pos, ptr1->len);
1101 : 4 : ptr->pos = dataoff;
1102 : 4 : dataoff += ptr1->len;
1103 [ + - ]: 4 : if (ptr->haspos)
1104 : : {
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 : :
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;
1119 : 5 : memcpy(data + dataoff, data2 + ptr2->pos, ptr2->len);
1120 : 5 : ptr->pos = dataoff;
1121 : 5 : dataoff += ptr2->len;
1122 [ + - ]: 5 : if (ptr->haspos)
1123 : : {
1124 : 5 : int addlen = add_pos(in2, ptr2, out, ptr, maxpos);
1125 : :
1126 [ - + ]: 5 : if (addlen == 0)
1127 : 0 : ptr->haspos = 0;
1128 : : else
1129 : : {
1130 : 5 : dataoff = SHORTALIGN(dataoff);
1131 : 5 : dataoff += addlen * sizeof(WordEntryPos) + sizeof(uint16);
1132 : : }
1133 : : }
1134 : :
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 : : */
1144 [ - + ]: 9 : if (dataoff > MAXSTRPOS)
1145 [ # # ]: 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 : : */
1154 : 9 : output_size = ptr - ARRPTR(out);
1155 : : Assert(output_size <= out->size);
1156 : 9 : out->size = output_size;
1157 [ + + ]: 9 : if (data != STRPTR(out))
1158 : 5 : memmove(STRPTR(out), data, dataoff);
1159 : 9 : output_bytes = CALCDATASIZE(out->size, dataoff);
1160 : : Assert(output_bytes <= VARSIZE(out));
1161 : 9 : SET_VARSIZE(out, output_bytes);
1162 : :
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
1174 : 4197080 : tsCompareString(char *a, int lena, char *b, int lenb, bool prefix)
1175 : : {
1176 : : int cmp;
1177 : :
1178 [ + + ]: 4197080 : if (lena == 0)
1179 : : {
1180 [ - + ]: 30 : if (prefix)
1181 : 0 : cmp = 0; /* empty string is prefix of anything */
1182 : : else
1183 [ + - ]: 30 : cmp = (lenb > 0) ? -1 : 0;
1184 : : }
1185 [ - + ]: 4197050 : else if (lenb == 0)
1186 : : {
1187 : 0 : cmp = (lena > 0) ? 1 : 0;
1188 : : }
1189 : : else
1190 : : {
1191 : 4197050 : cmp = memcmp(a, b, Min((unsigned int) lena, (unsigned int) lenb));
1192 : :
1193 [ + + ]: 4197050 : if (prefix)
1194 : : {
1195 [ + + - + ]: 11021 : if (cmp == 0 && lena > lenb)
1196 : 0 : cmp = 1; /* a is longer, so not a prefix of b */
1197 : : }
1198 [ + + + + ]: 4186029 : else if (cmp == 0 && lena != lenb)
1199 : : {
1200 [ + + ]: 21676 : cmp = (lena < lenb) ? -1 : 1;
1201 : : }
1202 : : }
1203 : :
1204 : 4197080 : return cmp;
1205 : : }
1206 : :
1207 : : /*
1208 : : * Check weight info or/and fill 'data' with the required positions
1209 : : */
1210 : : static TSTernaryValue
1211 : 45580 : checkclass_str(CHKVAL *chkval, WordEntry *entry, QueryOperand *val,
1212 : : ExecPhraseData *data)
1213 : : {
1214 : 45580 : TSTernaryValue result = TS_NO;
1215 : :
1216 : : 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 : : */
1226 : 3160 : posvec = (WordEntryPosVector *)
1227 : 3160 : (chkval->values + SHORTALIGN(entry->pos + entry->len));
1228 : :
1229 [ + + + + ]: 3160 : if (val->weight && data)
1230 : 40 : {
1231 : 40 : WordEntryPos *posvec_iter = posvec->pos;
1232 : : WordEntryPos *dptr;
1233 : :
1234 : : /*
1235 : : * Filter position information by weights
1236 : : */
1237 : 40 : dptr = data->pos = palloc_array(WordEntryPos, posvec->npos);
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)
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 : : }
1264 [ + + ]: 3120 : else if (val->weight)
1265 : : {
1266 : 332 : WordEntryPos *posvec_iter = posvec->pos;
1267 : :
1268 : : /* Is there a position with a matching weight? */
1269 [ + + ]: 503 : while (posvec_iter < posvec->pos + posvec->npos)
1270 : : {
1271 [ + + ]: 372 : if (val->weight & (1 << WEP_GETWEIGHT(*posvec_iter)))
1272 : : {
1273 : 201 : result = TS_YES;
1274 : 201 : break; /* no need to go further */
1275 : : }
1276 : :
1277 : 171 : posvec_iter++;
1278 : : }
1279 : : }
1280 [ + + ]: 2788 : else if (data)
1281 : : {
1282 : 1645 : data->npos = posvec->npos;
1283 : 1645 : data->pos = posvec->pos;
1284 : 1645 : data->allocated = false;
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 : :
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 : : {
1319 : 189558 : CHKVAL *chkval = (CHKVAL *) checkval;
1320 : 189558 : WordEntry *StopLow = chkval->arrb;
1321 : 189558 : WordEntry *StopHigh = chkval->arre;
1322 : 189558 : WordEntry *StopMiddle = StopHigh;
1323 : 189558 : TSTernaryValue res = TS_NO;
1324 : :
1325 : : /* Loop invariant: StopLow <= val < StopHigh */
1326 [ + + ]: 1191602 : while (StopLow < StopHigh)
1327 : : {
1328 : : int difference;
1329 : :
1330 : 1037568 : StopMiddle = StopLow + (StopHigh - StopLow) / 2;
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 : :
1337 [ + + ]: 1037568 : if (difference == 0)
1338 : : {
1339 : : /* Check weight info & fill 'data' with positions */
1340 : 35524 : res = checkclass_str(chkval, StopMiddle, val, data);
1341 : 35524 : break;
1342 : : }
1343 [ + + ]: 1002044 : else if (difference > 0)
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 : : */
1356 [ + + + + : 189558 : if (val->prefix && (res != TS_YES || data))
+ - ]
1357 : : {
1358 : 11040 : WordEntryPos *allpos = NULL;
1359 : 11040 : int npos = 0,
1360 : 11040 : totalpos = 0;
1361 : :
1362 : : /* adjust start position for corner case */
1363 [ + + ]: 11040 : if (StopLow >= StopHigh)
1364 : 11030 : StopMiddle = StopHigh;
1365 : :
1366 : : /* we don't try to re-use any data from the initial match */
1367 [ + + ]: 11040 : if (data)
1368 : : {
1369 [ - + ]: 30 : if (data->allocated)
1370 : 0 : pfree(data->pos);
1371 : 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 &&
+ + ]
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 : :
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 : : */
1402 : 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 : :
1411 [ + + ]: 65 : while (npos + data->npos > totalpos)
1412 : : {
1413 [ + - ]: 30 : if (totalpos == 0)
1414 : : {
1415 : 30 : totalpos = 256;
1416 : 30 : allpos = palloc_array(WordEntryPos, totalpos);
1417 : : }
1418 : : else
1419 : : {
1420 : 0 : totalpos *= 2;
1421 : 0 : allpos = repalloc_array(allpos, WordEntryPos, totalpos);
1422 : : }
1423 : : }
1424 : :
1425 : 35 : memcpy(allpos + npos, data->pos, sizeof(WordEntryPos) * data->npos);
1426 : 35 : npos += data->npos;
1427 : :
1428 : : /* don't leak storage from individual matches */
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 : :
1444 : 10056 : StopMiddle++;
1445 : : }
1446 : :
1447 [ + + + - ]: 11040 : if (data && npos > 0)
1448 : : {
1449 : : /* Sort and make unique array of found positions */
1450 : 30 : data->pos = allpos;
1451 : 30 : qsort(data->pos, npos, sizeof(WordEntryPos), compareWordEntryPos);
1452 : 30 : data->npos = qunique(data->pos, npos, sizeof(WordEntryPos),
1453 : : compareWordEntryPos);
1454 : 30 : data->allocated = true;
1455 : 30 : res = TS_YES;
1456 : : }
1457 : : }
1458 : :
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
1490 : 20111 : 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 : 20111 : Lindex = Rindex = 0;
1503 [ + + + + ]: 20903 : 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 : : {
1563 : 261 : data->pos = palloc_array(WordEntryPos, max_npos);
1564 : 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 : : */
1574 : 721 : return TS_YES;
1575 : : }
1576 : : }
1577 : : }
1578 : :
1579 [ + + + + ]: 19390 : if (data && data->npos > 0)
1580 : : {
1581 : : /* Let's assert we didn't overrun the array */
1582 : : Assert(data->npos <= max_npos);
1583 : 261 : return TS_YES;
1584 : : }
1585 : 19129 : 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
1630 : 467128 : 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 */
1643 : 467128 : check_stack_depth();
1644 : :
1645 : : /* ... and let's check for query cancel while we're at it */
1646 [ - + ]: 467128 : CHECK_FOR_INTERRUPTS();
1647 : :
1648 [ + + ]: 467128 : if (curitem->type == QI_VAL)
1649 : 229814 : return chkcond(arg, (QueryOperand *) curitem, data);
1650 : :
1651 [ + + + - ]: 237314 : switch (curitem->qoperator.oper)
1652 : : {
1653 : 80411 : case OP_NOT:
1654 : :
1655 : : /*
1656 : : * We need not touch data->width, since a NOT operation does not
1657 : : * change the match width.
1658 : : */
1659 [ - + ]: 80411 : if (flags & TS_EXEC_SKIP_NOT)
1660 : : {
1661 : : /* with SKIP_NOT, report NOT as "match everywhere" */
1662 : : Assert(data->npos == 0 && !data->negate);
1663 : 0 : data->negate = true;
1664 : 0 : return TS_YES;
1665 : : }
1666 [ + + + - ]: 80411 : switch (TS_phrase_execute(curitem + 1, arg, flags, chkcond, data))
1667 : : {
1668 : 70255 : case TS_NO:
1669 : : /* change "match nowhere" to "match everywhere" */
1670 : : Assert(data->npos == 0 && !data->negate);
1671 : 70255 : data->negate = true;
1672 : 70255 : 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 */
1687 : : Assert(false);
1688 : 0 : break;
1689 : 9883 : case TS_MAYBE:
1690 : : /* match positions are, and remain, uncertain */
1691 : 9883 : return TS_MAYBE;
1692 : : }
1693 : 0 : break;
1694 : :
1695 : 156777 : case OP_PHRASE:
1696 : : case OP_AND:
1697 : 156777 : memset(&Ldata, 0, sizeof(Ldata));
1698 : 156777 : memset(&Rdata, 0, sizeof(Rdata));
1699 : :
1700 : 156777 : lmatch = TS_phrase_execute(curitem + curitem->qoperator.left,
1701 : : arg, flags, chkcond, &Ldata);
1702 [ + + ]: 156777 : if (lmatch == TS_NO)
1703 : 83656 : return TS_NO;
1704 : :
1705 : 73121 : rmatch = TS_phrase_execute(curitem + 1,
1706 : : arg, flags, chkcond, &Rdata);
1707 [ + + ]: 73121 : if (rmatch == TS_NO)
1708 : 35961 : 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 [ + + + + ]: 37160 : if (lmatch == TS_MAYBE || rmatch == TS_MAYBE)
1715 : 17175 : return TS_MAYBE;
1716 : :
1717 [ + + ]: 19985 : 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 : 19980 : Loffset = curitem->qoperator.distance + Rdata.width;
1724 : 19980 : Roffset = 0;
1725 [ + + ]: 19980 : 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 [ + + + + ]: 19985 : if (Ldata.negate && Rdata.negate)
1743 : : {
1744 : : /* !L & !R: treat as !(L | R) */
1745 : 18957 : (void) TS_phrase_output(data, &Ldata, &Rdata,
1746 : : TSPO_BOTH | TSPO_L_ONLY | TSPO_R_ONLY,
1747 : : Loffset, Roffset,
1748 : 18957 : Ldata.npos + Rdata.npos);
1749 [ - + ]: 18957 : if (data)
1750 : 0 : data->negate = true;
1751 : 18957 : return TS_YES;
1752 : : }
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 : :
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)
1795 : 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 : : */
1802 [ + + ]: 116 : if (lmatch == TS_NO)
1803 : 15 : Ldata.width = 0;
1804 [ + + ]: 116 : if (rmatch == TS_NO)
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;
1826 : 5 : return TS_YES;
1827 : : }
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;
1836 : 25 : return TS_YES;
1837 : : }
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;
1846 : 5 : return TS_YES;
1847 : : }
1848 : : else
1849 : : {
1850 : : /* straight OR */
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 : :
1857 : 0 : default:
1858 [ # # ]: 0 : elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
1859 : : }
1860 : :
1861 : : /* not reachable, but keep compiler quiet */
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
1875 : 346619 : 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 : : */
1883 : 346619 : 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
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
1904 : 703288 : 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 */
1910 : 703288 : check_stack_depth();
1911 : :
1912 : : /* ... and let's check for query cancel while we're at it */
1913 [ - + ]: 703288 : CHECK_FOR_INTERRUPTS();
1914 : :
1915 [ + + ]: 703288 : if (curitem->type == QI_VAL)
1916 : 282754 : return chkcond(arg, (QueryOperand *) curitem,
1917 : : NULL /* don't need position info */ );
1918 : :
1919 [ + + + + : 420534 : switch (curitem->qoperator.oper)
- ]
1920 : : {
1921 : 135509 : case OP_NOT:
1922 [ - + ]: 135509 : if (flags & TS_EXEC_SKIP_NOT)
1923 : 0 : return TS_YES;
1924 [ + + + - ]: 135509 : switch (TS_execute_recurse(curitem + 1, arg, flags, chkcond))
1925 : : {
1926 : 127852 : case TS_NO:
1927 : 127852 : return TS_YES;
1928 : 3264 : case TS_YES:
1929 : 3264 : return TS_NO;
1930 : 4393 : case TS_MAYBE:
1931 : 4393 : return TS_MAYBE;
1932 : : }
1933 : 0 : break;
1934 : :
1935 : 55846 : case OP_AND:
1936 : 55846 : lmatch = TS_execute_recurse(curitem + curitem->qoperator.left, arg,
1937 : : flags, chkcond);
1938 [ + + ]: 55846 : if (lmatch == TS_NO)
1939 : 44340 : return TS_NO;
1940 [ + + + - ]: 11506 : switch (TS_execute_recurse(curitem + 1, arg, flags, chkcond))
1941 : : {
1942 : 6745 : case TS_NO:
1943 : 6745 : return TS_NO;
1944 : 2236 : case TS_YES:
1945 : 2236 : return lmatch;
1946 : 2525 : case TS_MAYBE:
1947 : 2525 : return TS_MAYBE;
1948 : : }
1949 : 0 : break;
1950 : :
1951 : 72662 : case OP_OR:
1952 : 72662 : lmatch = TS_execute_recurse(curitem + curitem->qoperator.left, arg,
1953 : : flags, chkcond);
1954 [ + + ]: 72662 : if (lmatch == TS_YES)
1955 : 16144 : return TS_YES;
1956 [ + + + - ]: 56518 : switch (TS_execute_recurse(curitem + 1, arg, flags, chkcond))
1957 : : {
1958 : 38322 : case TS_NO:
1959 : 38322 : return lmatch;
1960 : 4962 : case TS_YES:
1961 : 4962 : return TS_YES;
1962 : 13234 : case TS_MAYBE:
1963 : 13234 : return TS_MAYBE;
1964 : : }
1965 : 0 : break;
1966 : :
1967 : 156517 : 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 : : */
1978 [ + + + - ]: 156517 : switch (TS_phrase_execute(curitem, arg, flags, chkcond, NULL))
1979 : : {
1980 : 119746 : case TS_NO:
1981 : 119746 : return TS_NO;
1982 : 19601 : case TS_YES:
1983 : 19601 : return TS_YES;
1984 : 17170 : case TS_MAYBE:
1985 : 17170 : return (flags & TS_EXEC_PHRASE_NO_POS) ? TS_MAYBE : TS_NO;
1986 : : }
1987 : 0 : break;
1988 : :
1989 : 0 : default:
1990 [ # # ]: 0 : elog(ERROR, "unrecognized operator: %d", curitem->qoperator.oper);
1991 : : }
1992 : :
1993 : : /* not reachable, but keep compiler quiet */
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 *
2028 : 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 : : 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))
2082 : 0 : return true; /* we don't pass back any locations */
2083 : 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)
2115 : 0 : *locations = rlocations;
2116 [ + + ]: 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 : : }
2145 : 0 : return false;
2146 : :
2147 : 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 : : }
2157 : 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
2177 : 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 : :
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 */
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
2213 : 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
2227 : 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 */
2243 [ - + ]: 146812 : if (!query->size)
2244 : : {
2245 [ # # ]: 0 : PG_FREE_IF_COPY(val, 0);
2246 [ # # ]: 0 : PG_FREE_IF_COPY(query, 1);
2247 : 0 : PG_RETURN_BOOL(false);
2248 : : }
2249 : :
2250 : 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);
2254 : 146812 : result = TS_execute(GETQUERY(query),
2255 : : &chkval,
2256 : : TS_EXEC_EMPTY,
2257 : : checkcondition_str);
2258 : :
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
2265 : 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
2316 : 5452 : check_weight(TSVector txt, WordEntry *wptr, int8 weight)
2317 : : {
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
2337 : 230416 : insertStatEntry(MemoryContext persistentContext, TSVectorStat *stat, TSVector txt, uint32 off)
2338 : : {
2339 : 230416 : WordEntry *we = ARRPTR(txt) + off;
2340 : 230416 : StatEntry *node = stat->root,
2341 : 230416 : *pnode = NULL;
2342 : : int n,
2343 : 230416 : res = 0;
2344 : 230416 : uint32 depth = 1;
2345 : :
2346 [ + + ]: 230416 : if (stat->weight == 0)
2347 [ + + ]: 115208 : n = (we->haspos) ? POSDATALEN(txt, we) : 1;
2348 : : else
2349 [ + + ]: 115208 : n = (we->haspos) ? check_weight(txt, we, stat->weight) : 0;
2350 : :
2351 [ + + ]: 230416 : if (n == 0)
2352 : 115204 : return; /* nothing to insert */
2353 : :
2354 [ + + ]: 1163592 : while (node)
2355 : : {
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;
2365 [ + + ]: 1048380 : node = (res < 0) ? node->left : node->right;
2366 : : }
2367 : 1048380 : depth++;
2368 : : }
2369 : :
2370 [ + + ]: 115212 : if (depth > stat->maxdepth)
2371 : 84 : stat->maxdepth = depth;
2372 : :
2373 [ + + ]: 115212 : if (node == NULL)
2374 : : {
2375 : 4576 : node = MemoryContextAlloc(persistentContext, STATENTRYHDRSZ + we->len);
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 : :
2382 [ + + ]: 4576 : if (pnode == NULL)
2383 : : {
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
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 : :
2408 : 330256 : pos = (low + middle) >> 1;
2409 [ + + + + : 330256 : if (low != middle && pos >= offset && pos - offset < txt->size)
+ + ]
2410 : 113552 : insertStatEntry(persistentContext, stat, txt, pos - offset);
2411 : 330256 : pos = (high + middle + 1) >> 1;
2412 [ + + + + : 330256 : if (middle + 1 != high && pos >= offset && pos - offset < txt->size)
+ + ]
2413 : 112856 : insertStatEntry(persistentContext, stat, txt, pos - offset);
2414 : :
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);
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 *
2434 : 4072 : ts_accum(MemoryContext persistentContext, TSVectorStat *stat, Datum data)
2435 : : {
2436 : 4072 : TSVector txt = DatumGetTSVector(data);
2437 : : uint32 i,
2438 : 4072 : nbit = 0,
2439 : : offset;
2440 : :
2441 [ - + ]: 4072 : if (stat == NULL)
2442 : : { /* Init in first */
2443 : 0 : stat = MemoryContextAllocZero(persistentContext, sizeof(TSVectorStat));
2444 : 0 : stat->maxdepth = 1;
2445 : : }
2446 : :
2447 : : /* simple check of correctness */
2448 [ + - + + ]: 4072 : if (txt == NULL || txt->size == 0)
2449 : : {
2450 [ + - + - ]: 64 : if (txt && txt != (TSVector) DatumGetPointer(data))
2451 : 64 : pfree(txt);
2452 : 64 : return stat;
2453 : : }
2454 : :
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 : :
2462 : 4008 : insertStatEntry(persistentContext, stat, txt, (nbit >> 1) - offset);
2463 : 4008 : chooseNextStatEntry(persistentContext, stat, txt, 0, nbit, offset);
2464 : :
2465 : 4008 : return stat;
2466 : : }
2467 : :
2468 : : static void
2469 : 8 : ts_setup_firstcall(FunctionCallInfo fcinfo, FuncCallContext *funcctx,
2470 : : TSVectorStat *stat)
2471 : : {
2472 : : TupleDesc tupdesc;
2473 : : MemoryContext oldcontext;
2474 : : StatEntry *node;
2475 : :
2476 : 8 : funcctx->user_fctx = stat;
2477 : :
2478 : 8 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
2479 : :
2480 : 8 : stat->stack = palloc0_array(StatEntry *, stat->maxdepth + 1);
2481 : 8 : stat->stackpos = 0;
2482 : :
2483 : 8 : node = stat->root;
2484 : : /* find leftmost value */
2485 [ - + ]: 8 : if (node == NULL)
2486 : 0 : stat->stack[stat->stackpos] = NULL;
2487 : : else
2488 : : for (;;)
2489 : : {
2490 : 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 : : Assert(stat->stackpos <= stat->maxdepth);
2500 : :
2501 [ - + ]: 8 : if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
2502 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
2503 : 8 : funcctx->tuple_desc = tupdesc;
2504 : 8 : funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
2505 : :
2506 : 8 : MemoryContextSwitchTo(oldcontext);
2507 : 8 : }
2508 : :
2509 : : static StatEntry *
2510 : 9152 : walkStatEntryTree(TSVectorStat *stat)
2511 : : {
2512 : 9152 : StatEntry *node = stat->stack[stat->stackpos];
2513 : :
2514 [ - + ]: 9152 : if (node == NULL)
2515 : 0 : return NULL;
2516 : :
2517 [ + + ]: 9152 : if (node->ndoc != 0)
2518 : : {
2519 : : /* return entry itself: we already was at left sublink */
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 : : }
2540 : 2314 : Assert(stat->stackpos <= stat->maxdepth);
2541 : : }
2542 : : else
2543 : : {
2544 : : /* we already return all left subtree, itself and right subtree */
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
2556 : 4584 : ts_process_call(FuncCallContext *funcctx)
2557 : : {
2558 : : TSVectorStat *st;
2559 : : StatEntry *entry;
2560 : :
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';
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 */
2587 : 4576 : entry->ndoc = 0;
2588 : :
2589 : 4576 : return result;
2590 : : }
2591 : :
2592 : 8 : return (Datum) 0;
2593 : : }
2594 : :
2595 : : static TSVectorStat *
2596 : 8 : ts_stat_sql(MemoryContext persistentContext, text *txt, text *ws)
2597 : : {
2598 : 8 : char *query = text_to_cstring(txt);
2599 : : TSVectorStat *stat;
2600 : : bool isnull;
2601 : : Portal portal;
2602 : : SPIPlanPtr plan;
2603 : :
2604 [ - + ]: 8 : if ((plan = SPI_prepare(query, 0, NULL)) == NULL)
2605 : : /* internal error */
2606 [ # # ]: 0 : elog(ERROR, "SPI_prepare(\"%s\") failed", query);
2607 : :
2608 [ - + ]: 8 : if ((portal = SPI_cursor_open(NULL, plan, NULL, NULL, true)) == NULL)
2609 : : /* internal error */
2610 [ # # ]: 0 : elog(ERROR, "SPI_cursor_open(\"%s\") failed", query);
2611 : :
2612 : 8 : SPI_cursor_fetch(portal, true, 100);
2613 : :
2614 [ + - ]: 8 : if (SPI_tuptable == NULL ||
2615 [ + - ]: 8 : SPI_tuptable->tupdesc->natts != 1 ||
2616 [ - + ]: 8 : !IsBinaryCoercible(SPI_gettypeid(SPI_tuptable->tupdesc, 1),
2617 : : TSVECTOROID))
2618 [ # # ]: 0 : ereport(ERROR,
2619 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2620 : : errmsg("ts_stat query must return one tsvector column")));
2621 : :
2622 : 8 : stat = MemoryContextAllocZero(persistentContext, sizeof(TSVectorStat));
2623 : 8 : stat->maxdepth = 1;
2624 : :
2625 [ + + ]: 8 : if (ws)
2626 : : {
2627 : : char *buf;
2628 : : const char *end;
2629 : :
2630 : 4 : buf = VARDATA_ANY(ws);
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 : : {
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;
2648 : 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 : : }
2660 : 8 : buf += len;
2661 : : }
2662 : : }
2663 : :
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)
2673 : 4072 : stat = ts_accum(persistentContext, stat, data);
2674 : : }
2675 : :
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;
2697 : 4 : text *txt = PG_GETARG_TEXT_PP(0);
2698 : :
2699 : 4 : funcctx = SRF_FIRSTCALL_INIT();
2700 : 4 : SPI_connect();
2701 : 4 : stat = ts_stat_sql(funcctx->multi_call_memory_ctx, txt, NULL);
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;
2722 : 4 : text *txt = PG_GETARG_TEXT_PP(0);
2723 : 4 : text *ws = PG_GETARG_TEXT_PP(1);
2724 : :
2725 : 4 : funcctx = SRF_FIRSTCALL_INIT();
2726 : 4 : SPI_connect();
2727 : 4 : stat = ts_stat_sql(funcctx->multi_call_memory_ctx, txt, ws);
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
2758 : 0 : tsvector_update_trigger_bycolumn(PG_FUNCTION_ARGS)
2759 : : {
2760 : 0 : return tsvector_update_trigger(fcinfo, true);
2761 : : }
2762 : :
2763 : : static Datum
2764 : 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 */
2780 [ + - - + ]: 12 : if (!CALLED_AS_TRIGGER(fcinfo)) /* internal error */
2781 [ # # ]: 0 : elog(ERROR, "tsvector_update_trigger: not fired by trigger manager");
2782 : :
2783 : 12 : trigdata = (TriggerData *) fcinfo->context;
2784 [ - + ]: 12 : if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2785 [ # # ]: 0 : elog(ERROR, "tsvector_update_trigger: must be fired for row");
2786 [ - + ]: 12 : if (!TRIGGER_FIRED_BEFORE(trigdata->tg_event))
2787 [ # # ]: 0 : elog(ERROR, "tsvector_update_trigger: must be fired BEFORE event");
2788 : :
2789 [ + + ]: 12 : if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2790 : : {
2791 : 8 : rettuple = trigdata->tg_trigtuple;
2792 : 8 : update_needed = true;
2793 : : }
2794 [ + - ]: 4 : else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2795 : : {
2796 : 4 : rettuple = trigdata->tg_newtuple;
2797 : 4 : update_needed = false; /* computed below */
2798 : : }
2799 : : else
2800 [ # # ]: 0 : elog(ERROR, "tsvector_update_trigger: must be fired for INSERT or UPDATE");
2801 : :
2802 : 12 : trigger = trigdata->tg_trigger;
2803 : 12 : rel = trigdata->tg_relation;
2804 : :
2805 [ - + ]: 12 : if (trigger->tgnargs < 3)
2806 [ # # ]: 0 : elog(ERROR, "tsvector_update_trigger: arguments must be tsvector_field, ts_config, text_field1, ...)");
2807 : :
2808 : : /* Find the target tsvector column */
2809 : 12 : tsvector_attr_num = SPI_fnumber(rel->rd_att, trigger->tgargs[0]);
2810 [ - + ]: 12 : if (tsvector_attr_num == SPI_ERROR_NOATTRIBUTE)
2811 [ # # ]: 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: */
2816 [ - + ]: 12 : if (!IsBinaryCoercible(SPI_gettypeid(rel->rd_att, tsvector_attr_num),
2817 : : TSVECTOROID))
2818 [ # # ]: 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 */
2824 [ - + ]: 12 : if (config_column)
2825 : : {
2826 : : int config_attr_num;
2827 : :
2828 : 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])));
2834 [ # # ]: 0 : if (!IsBinaryCoercible(SPI_gettypeid(rel->rd_att, config_attr_num),
2835 : : REGCONFIGOID))
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 : :
2853 : 12 : names = stringToQualifiedNameList(trigger->tgargs[1], NULL);
2854 : : /* require a schema so that results are not search path dependent */
2855 [ - + ]: 12 : if (list_length(names) < 2)
2856 [ # # ]: 0 : ereport(ERROR,
2857 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2858 : : errmsg("text search configuration name \"%s\" must be schema-qualified",
2859 : : trigger->tgargs[1])));
2860 : 12 : cfgId = get_ts_config_oid(names, false);
2861 : : }
2862 : :
2863 : : /* initialize parse state */
2864 : 12 : prs.lenwords = 32;
2865 : 12 : prs.curwords = 0;
2866 : 12 : prs.pos = 0;
2867 : 12 : prs.words = palloc_array(ParsedWord, prs.lenwords);
2868 : :
2869 : : /* find all words in indexable column(s) */
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)
2876 [ # # ]: 0 : ereport(ERROR,
2877 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
2878 : : errmsg("column \"%s\" does not exist",
2879 : : trigger->tgargs[i])));
2880 [ - + ]: 12 : if (!IsBinaryCoercible(SPI_gettypeid(rel->rd_att, numattr), TEXTOID))
2881 [ # # ]: 0 : ereport(ERROR,
2882 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
2883 : : errmsg("column \"%s\" is not of a character type",
2884 : : trigger->tgargs[i])));
2885 : :
2886 [ + + ]: 12 : if (bms_is_member(numattr - FirstLowInvalidHeapAttributeNumber, trigdata->tg_updatedcols))
2887 : 4 : update_needed = true;
2888 : :
2889 : 12 : datum = SPI_getbinval(rettuple, rel->rd_att, numattr, &isnull);
2890 [ + + ]: 12 : if (isnull)
2891 : 4 : continue;
2892 : :
2893 : 8 : txt = DatumGetTextPP(datum);
2894 : :
2895 : 8 : parsetext(cfgId, &prs, VARDATA_ANY(txt), VARSIZE_ANY_EXHDR(txt));
2896 : :
2897 [ - + ]: 8 : if (txt != (text *) DatumGetPointer(datum))
2898 : 0 : pfree(txt);
2899 : : }
2900 : :
2901 [ + - ]: 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 : :
2915 : 12 : return PointerGetDatum(rettuple);
2916 : : }
|