PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
trgm_op.c
Go to the documentation of this file.
1/*
2 * contrib/pg_trgm/trgm_op.c
3 */
4#include "postgres.h"
5
6#include <ctype.h>
7
8#include "catalog/pg_collation_d.h"
9#include "catalog/pg_type.h"
10#include "common/int.h"
11#include "lib/qunique.h"
12#include "miscadmin.h"
13#include "trgm.h"
14#include "tsearch/ts_locale.h"
15#include "utils/formatting.h"
16#include "utils/guc.h"
17#include "utils/lsyscache.h"
18#include "utils/memutils.h"
19#include "utils/pg_crc.h"
20
22 .name = "pg_trgm",
23 .version = PG_VERSION
24);
25
26/* GUC variables */
30
47
48static int CMPTRGM_CHOOSE(const void *a, const void *b);
49int (*CMPTRGM) (const void *a, const void *b) = CMPTRGM_CHOOSE;
50
51/* Trigram with position */
52typedef struct
53{
55 int index;
56} pos_trgm;
57
58/* Trigram bound type */
60#define TRGM_BOUND_LEFT 0x01 /* trigram is left bound of word */
61#define TRGM_BOUND_RIGHT 0x02 /* trigram is right bound of word */
62
63/* Word similarity flags */
64#define WORD_SIMILARITY_CHECK_ONLY 0x01 /* only check existence of similar
65 * search pattern in text */
66#define WORD_SIMILARITY_STRICT 0x02 /* force bounds of extent to match
67 * word bounds */
68
69/*
70 * Module load callback
71 */
72void
73_PG_init(void)
74{
75 /* Define custom GUC variables. */
76 DefineCustomRealVariable("pg_trgm.similarity_threshold",
77 "Sets the threshold used by the % operator.",
78 "Valid range is 0.0 .. 1.0.",
80 0.3f,
81 0.0,
82 1.0,
84 0,
85 NULL,
86 NULL,
87 NULL);
88 DefineCustomRealVariable("pg_trgm.word_similarity_threshold",
89 "Sets the threshold used by the <% operator.",
90 "Valid range is 0.0 .. 1.0.",
92 0.6f,
93 0.0,
94 1.0,
96 0,
97 NULL,
98 NULL,
99 NULL);
100 DefineCustomRealVariable("pg_trgm.strict_word_similarity_threshold",
101 "Sets the threshold used by the <<% operator.",
102 "Valid range is 0.0 .. 1.0.",
104 0.5f,
105 0.0,
106 1.0,
108 0,
109 NULL,
110 NULL,
111 NULL);
112
113 MarkGUCPrefixReserved("pg_trgm");
115
116#define CMPCHAR(a,b) ( ((a)==(b)) ? 0 : ( ((a)<(b)) ? -1 : 1 ) )
117
118/*
119 * Functions for comparing two trgms while treating each char as "signed char" or
120 * "unsigned char".
121 */
122static inline int
123CMPTRGM_SIGNED(const void *a, const void *b)
124{
125#define CMPPCHAR_S(a,b,i) CMPCHAR( *(((const signed char*)(a))+i), *(((const signed char*)(b))+i) )
126
127 return CMPPCHAR_S(a, b, 0) ? CMPPCHAR_S(a, b, 0)
128 : (CMPPCHAR_S(a, b, 1) ? CMPPCHAR_S(a, b, 1)
129 : CMPPCHAR_S(a, b, 2));
130}
132static inline int
133CMPTRGM_UNSIGNED(const void *a, const void *b)
134{
135#define CMPPCHAR_UNS(a,b,i) CMPCHAR( *(((const unsigned char*)(a))+i), *(((const unsigned char*)(b))+i) )
136
137 return CMPPCHAR_UNS(a, b, 0) ? CMPPCHAR_UNS(a, b, 0)
138 : (CMPPCHAR_UNS(a, b, 1) ? CMPPCHAR_UNS(a, b, 1)
139 : CMPPCHAR_UNS(a, b, 2));
140}
141
142/*
143 * This gets called on the first call. It replaces the function pointer so
144 * that subsequent calls are routed directly to the chosen implementation.
145 */
146static int
147CMPTRGM_CHOOSE(const void *a, const void *b)
148{
151 else
153
154 return CMPTRGM(a, b);
155}
156
157/*
158 * Deprecated function.
159 * Use "pg_trgm.similarity_threshold" GUC variable instead of this function.
160 */
161Datum
163{
164 float4 nlimit = PG_GETARG_FLOAT4(0);
165 char *nlimit_str;
166 Oid func_out_oid;
167 bool is_varlena;
168
169 getTypeOutputInfo(FLOAT4OID, &func_out_oid, &is_varlena);
170
171 nlimit_str = OidOutputFunctionCall(func_out_oid, Float4GetDatum(nlimit));
172
173 SetConfigOption("pg_trgm.similarity_threshold", nlimit_str,
175
177}
178
179
180/*
181 * Get similarity threshold for given index scan strategy number.
182 */
183double
185{
186 switch (strategy)
187 {
194 default:
195 elog(ERROR, "unrecognized strategy number: %d", strategy);
196 break;
197 }
198
199 return 0.0; /* keep compiler quiet */
200}
201
202/*
203 * Deprecated function.
204 * Use "pg_trgm.similarity_threshold" GUC variable instead of this function.
205 */
206Datum
208{
210}
212static int
213comp_trgm(const void *a, const void *b)
214{
215 return CMPTRGM(a, b);
216}
217
218/*
219 * Finds first word in string, returns pointer to the word,
220 * endword points to the character after word
221 */
222static char *
223find_word(char *str, int lenstr, char **endword, int *charlen)
224{
225 char *beginword = str;
226
227 while (beginword - str < lenstr && !ISWORDCHR(beginword))
228 beginword += pg_mblen(beginword);
229
230 if (beginword - str >= lenstr)
231 return NULL;
232
233 *endword = beginword;
234 *charlen = 0;
235 while (*endword - str < lenstr && ISWORDCHR(*endword))
236 {
237 *endword += pg_mblen(*endword);
238 (*charlen)++;
239 }
240
241 return beginword;
242}
243
244/*
245 * Reduce a trigram (three possibly multi-byte characters) to a trgm,
246 * which is always exactly three bytes. If we have three single-byte
247 * characters, we just use them as-is; otherwise we form a hash value.
248 */
249void
250compact_trigram(trgm *tptr, char *str, int bytelen)
251{
252 if (bytelen == 3)
253 {
254 CPTRGM(tptr, str);
255 }
256 else
257 {
259
261 COMP_LEGACY_CRC32(crc, str, bytelen);
263
264 /*
265 * use only 3 upper bytes from crc, hope, it's good enough hashing
266 */
267 CPTRGM(tptr, &crc);
268 }
269}
270
271/*
272 * Adds trigrams from words (already padded).
273 */
274static trgm *
275make_trigrams(trgm *tptr, char *str, int bytelen, int charlen)
276{
277 char *ptr = str;
278
279 if (charlen < 3)
280 return tptr;
281
282 if (bytelen > charlen)
283 {
284 /* Find multibyte character boundaries and apply compact_trigram */
285 int lenfirst = pg_mblen(str),
286 lenmiddle = pg_mblen(str + lenfirst),
287 lenlast = pg_mblen(str + lenfirst + lenmiddle);
288
289 while ((ptr - str) + lenfirst + lenmiddle + lenlast <= bytelen)
290 {
291 compact_trigram(tptr, ptr, lenfirst + lenmiddle + lenlast);
292
293 ptr += lenfirst;
294 tptr++;
295
296 lenfirst = lenmiddle;
297 lenmiddle = lenlast;
298 lenlast = pg_mblen(ptr + lenfirst + lenmiddle);
299 }
300 }
301 else
302 {
303 /* Fast path when there are no multibyte characters */
304 Assert(bytelen == charlen);
305
306 while (ptr - str < bytelen - 2 /* number of trigrams = strlen - 2 */ )
307 {
308 CPTRGM(tptr, ptr);
309 ptr++;
310 tptr++;
311 }
312 }
313
314 return tptr;
315}
316
317/*
318 * Make array of trigrams without sorting and removing duplicate items.
319 *
320 * trg: where to return the array of trigrams.
321 * str: source string, of length slen bytes.
322 * bounds: where to return bounds of trigrams (if needed).
323 *
324 * Returns length of the generated array.
325 */
326static int
327generate_trgm_only(trgm *trg, char *str, int slen, TrgmBound *bounds)
328{
329 trgm *tptr;
330 char *buf;
331 int charlen,
332 bytelen;
333 char *bword,
334 *eword;
335
336 if (slen + LPADDING + RPADDING < 3 || slen == 0)
337 return 0;
338
339 tptr = trg;
340
341 /* Allocate a buffer for case-folded, blank-padded words */
342 buf = (char *) palloc(slen * pg_database_encoding_max_length() + 4);
343
344 if (LPADDING > 0)
345 {
346 *buf = ' ';
347 if (LPADDING > 1)
348 *(buf + 1) = ' ';
349 }
350
351 eword = str;
352 while ((bword = find_word(eword, slen - (eword - str), &eword, &charlen)) != NULL)
353 {
354#ifdef IGNORECASE
355 bword = str_tolower(bword, eword - bword, DEFAULT_COLLATION_OID);
356 bytelen = strlen(bword);
357#else
358 bytelen = eword - bword;
359#endif
360
361 memcpy(buf + LPADDING, bword, bytelen);
362
363#ifdef IGNORECASE
364 pfree(bword);
365#endif
366
367 buf[LPADDING + bytelen] = ' ';
368 buf[LPADDING + bytelen + 1] = ' ';
369
370 /* Calculate trigrams marking their bounds if needed */
371 if (bounds)
372 bounds[tptr - trg] |= TRGM_BOUND_LEFT;
373 tptr = make_trigrams(tptr, buf, bytelen + LPADDING + RPADDING,
374 charlen + LPADDING + RPADDING);
375 if (bounds)
376 bounds[tptr - trg - 1] |= TRGM_BOUND_RIGHT;
377 }
378
379 pfree(buf);
380
381 return tptr - trg;
382}
383
384/*
385 * Guard against possible overflow in the palloc requests below. (We
386 * don't worry about the additive constants, since palloc can detect
387 * requests that are a little above MaxAllocSize --- we just need to
388 * prevent integer overflow in the multiplications.)
389 */
390static void
391protect_out_of_mem(int slen)
392{
393 if ((Size) (slen / 2) >= (MaxAllocSize / (sizeof(trgm) * 3)) ||
396 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
397 errmsg("out of memory")));
398}
399
400/*
401 * Make array of trigrams with sorting and removing duplicate items.
402 *
403 * str: source string, of length slen bytes.
404 *
405 * Returns the sorted array of unique trigrams.
406 */
407TRGM *
408generate_trgm(char *str, int slen)
409{
410 TRGM *trg;
411 int len;
412
413 protect_out_of_mem(slen);
414
415 trg = (TRGM *) palloc(TRGMHDRSIZE + sizeof(trgm) * (slen / 2 + 1) * 3);
416 trg->flag = ARRKEY;
417
418 len = generate_trgm_only(GETARR(trg), str, slen, NULL);
420
421 if (len == 0)
422 return trg;
423
424 /*
425 * Make trigrams unique.
426 */
427 if (len > 1)
428 {
429 qsort(GETARR(trg), len, sizeof(trgm), comp_trgm);
430 len = qunique(GETARR(trg), len, sizeof(trgm), comp_trgm);
431 }
432
434
435 return trg;
436}
437
438/*
439 * Make array of positional trigrams from two trigram arrays trg1 and trg2.
440 *
441 * trg1: trigram array of search pattern, of length len1. trg1 is required
442 * word which positions don't matter and replaced with -1.
443 * trg2: trigram array of text, of length len2. trg2 is haystack where we
444 * search and have to store its positions.
445 *
446 * Returns concatenated trigram array.
447 */
448static pos_trgm *
449make_positional_trgm(trgm *trg1, int len1, trgm *trg2, int len2)
450{
451 pos_trgm *result;
452 int i,
453 len = len1 + len2;
454
455 result = (pos_trgm *) palloc(sizeof(pos_trgm) * len);
456
457 for (i = 0; i < len1; i++)
458 {
459 memcpy(&result[i].trg, &trg1[i], sizeof(trgm));
460 result[i].index = -1;
461 }
462
463 for (i = 0; i < len2; i++)
464 {
465 memcpy(&result[i + len1].trg, &trg2[i], sizeof(trgm));
466 result[i + len1].index = i;
467 }
468
469 return result;
470}
471
472/*
473 * Compare position trigrams: compare trigrams first and position second.
474 */
475static int
476comp_ptrgm(const void *v1, const void *v2)
477{
478 const pos_trgm *p1 = (const pos_trgm *) v1;
479 const pos_trgm *p2 = (const pos_trgm *) v2;
480 int cmp;
481
482 cmp = CMPTRGM(p1->trg, p2->trg);
483 if (cmp != 0)
484 return cmp;
485
486 return pg_cmp_s32(p1->index, p2->index);
487}
488
489/*
490 * Iterative search function which calculates maximum similarity with word in
491 * the string. Maximum similarity is only calculated only if the flag
492 * WORD_SIMILARITY_CHECK_ONLY isn't set.
493 *
494 * trg2indexes: array which stores indexes of the array "found".
495 * found: array which stores true of false values.
496 * ulen1: count of unique trigrams of array "trg1".
497 * len2: length of array "trg2" and array "trg2indexes".
498 * len: length of the array "found".
499 * flags: set of boolean flags parameterizing similarity calculation.
500 * bounds: whether each trigram is left/right bound of word.
501 *
502 * Returns word similarity.
503 */
504static float4
505iterate_word_similarity(int *trg2indexes,
506 bool *found,
507 int ulen1,
508 int len2,
509 int len,
510 uint8 flags,
511 TrgmBound *bounds)
512{
513 int *lastpos,
514 i,
515 ulen2 = 0,
516 count = 0,
517 upper = -1,
518 lower;
519 float4 smlr_cur,
520 smlr_max = 0.0f;
521 double threshold;
522
523 Assert(bounds || !(flags & WORD_SIMILARITY_STRICT));
524
525 /* Select appropriate threshold */
526 threshold = (flags & WORD_SIMILARITY_STRICT) ?
529
530 /*
531 * Consider first trigram as initial lower bound for strict word
532 * similarity, or initialize it later with first trigram present for plain
533 * word similarity.
534 */
535 lower = (flags & WORD_SIMILARITY_STRICT) ? 0 : -1;
536
537 /* Memorise last position of each trigram */
538 lastpos = (int *) palloc(sizeof(int) * len);
539 memset(lastpos, -1, sizeof(int) * len);
540
541 for (i = 0; i < len2; i++)
542 {
543 int trgindex;
544
546
547 /* Get index of next trigram */
548 trgindex = trg2indexes[i];
549
550 /* Update last position of this trigram */
551 if (lower >= 0 || found[trgindex])
552 {
553 if (lastpos[trgindex] < 0)
554 {
555 ulen2++;
556 if (found[trgindex])
557 count++;
558 }
559 lastpos[trgindex] = i;
560 }
561
562 /*
563 * Adjust upper bound if trigram is upper bound of word for strict
564 * word similarity, or if trigram is present in required substring for
565 * plain word similarity
566 */
567 if ((flags & WORD_SIMILARITY_STRICT) ? (bounds[i] & TRGM_BOUND_RIGHT)
568 : found[trgindex])
569 {
570 int prev_lower,
571 tmp_ulen2,
572 tmp_lower,
573 tmp_count;
574
575 upper = i;
576 if (lower == -1)
577 {
578 lower = i;
579 ulen2 = 1;
580 }
581
582 smlr_cur = CALCSML(count, ulen1, ulen2);
583
584 /* Also try to adjust lower bound for greater similarity */
585 tmp_count = count;
586 tmp_ulen2 = ulen2;
587 prev_lower = lower;
588 for (tmp_lower = lower; tmp_lower <= upper; tmp_lower++)
589 {
590 float smlr_tmp;
591 int tmp_trgindex;
592
593 /*
594 * Adjust lower bound only if trigram is lower bound of word
595 * for strict word similarity, or consider every trigram as
596 * lower bound for plain word similarity.
597 */
598 if (!(flags & WORD_SIMILARITY_STRICT)
599 || (bounds[tmp_lower] & TRGM_BOUND_LEFT))
600 {
601 smlr_tmp = CALCSML(tmp_count, ulen1, tmp_ulen2);
602 if (smlr_tmp > smlr_cur)
603 {
604 smlr_cur = smlr_tmp;
605 ulen2 = tmp_ulen2;
606 lower = tmp_lower;
607 count = tmp_count;
608 }
609
610 /*
611 * If we only check that word similarity is greater than
612 * threshold we do not need to calculate a maximum
613 * similarity.
614 */
615 if ((flags & WORD_SIMILARITY_CHECK_ONLY)
616 && smlr_cur >= threshold)
617 break;
618 }
619
620 tmp_trgindex = trg2indexes[tmp_lower];
621 if (lastpos[tmp_trgindex] == tmp_lower)
622 {
623 tmp_ulen2--;
624 if (found[tmp_trgindex])
625 tmp_count--;
626 }
627 }
628
629 smlr_max = Max(smlr_max, smlr_cur);
630
631 /*
632 * if we only check that word similarity is greater than threshold
633 * we do not need to calculate a maximum similarity.
634 */
635 if ((flags & WORD_SIMILARITY_CHECK_ONLY) && smlr_max >= threshold)
636 break;
637
638 for (tmp_lower = prev_lower; tmp_lower < lower; tmp_lower++)
639 {
640 int tmp_trgindex;
641
642 tmp_trgindex = trg2indexes[tmp_lower];
643 if (lastpos[tmp_trgindex] == tmp_lower)
644 lastpos[tmp_trgindex] = -1;
645 }
646 }
647 }
648
649 pfree(lastpos);
650
651 return smlr_max;
652}
653
654/*
655 * Calculate word similarity.
656 * This function prepare two arrays: "trg2indexes" and "found". Then this arrays
657 * are used to calculate word similarity using iterate_word_similarity().
658 *
659 * "trg2indexes" is array which stores indexes of the array "found".
660 * In other words:
661 * trg2indexes[j] = i;
662 * found[i] = true (or false);
663 * If found[i] == true then there is trigram trg2[j] in array "trg1".
664 * If found[i] == false then there is not trigram trg2[j] in array "trg1".
665 *
666 * str1: search pattern string, of length slen1 bytes.
667 * str2: text in which we are looking for a word, of length slen2 bytes.
668 * flags: set of boolean flags parameterizing similarity calculation.
669 *
670 * Returns word similarity.
671 */
672static float4
673calc_word_similarity(char *str1, int slen1, char *str2, int slen2,
674 uint8 flags)
675{
676 bool *found;
677 pos_trgm *ptrg;
678 trgm *trg1;
679 trgm *trg2;
680 int len1,
681 len2,
682 len,
683 i,
684 j,
685 ulen1;
686 int *trg2indexes;
687 float4 result;
688 TrgmBound *bounds;
689
690 protect_out_of_mem(slen1 + slen2);
691
692 /* Make positional trigrams */
693 trg1 = (trgm *) palloc(sizeof(trgm) * (slen1 / 2 + 1) * 3);
694 trg2 = (trgm *) palloc(sizeof(trgm) * (slen2 / 2 + 1) * 3);
695 if (flags & WORD_SIMILARITY_STRICT)
696 bounds = (TrgmBound *) palloc0(sizeof(TrgmBound) * (slen2 / 2 + 1) * 3);
697 else
698 bounds = NULL;
699
700 len1 = generate_trgm_only(trg1, str1, slen1, NULL);
701 len2 = generate_trgm_only(trg2, str2, slen2, bounds);
702
703 ptrg = make_positional_trgm(trg1, len1, trg2, len2);
704 len = len1 + len2;
705 qsort(ptrg, len, sizeof(pos_trgm), comp_ptrgm);
706
707 pfree(trg1);
708 pfree(trg2);
709
710 /*
711 * Merge positional trigrams array: enumerate each trigram and find its
712 * presence in required word.
713 */
714 trg2indexes = (int *) palloc(sizeof(int) * len2);
715 found = (bool *) palloc0(sizeof(bool) * len);
716
717 ulen1 = 0;
718 j = 0;
719 for (i = 0; i < len; i++)
720 {
721 if (i > 0)
722 {
723 int cmp = CMPTRGM(ptrg[i - 1].trg, ptrg[i].trg);
724
725 if (cmp != 0)
726 {
727 if (found[j])
728 ulen1++;
729 j++;
730 }
731 }
732
733 if (ptrg[i].index >= 0)
734 {
735 trg2indexes[ptrg[i].index] = j;
736 }
737 else
738 {
739 found[j] = true;
740 }
741 }
742 if (found[j])
743 ulen1++;
744
745 /* Run iterative procedure to find maximum similarity with word */
746 result = iterate_word_similarity(trg2indexes, found, ulen1, len2, len,
747 flags, bounds);
748
749 pfree(trg2indexes);
750 pfree(found);
751 pfree(ptrg);
752
753 return result;
754}
755
756
757/*
758 * Extract the next non-wildcard part of a search string, i.e. a word bounded
759 * by '_' or '%' meta-characters, non-word characters or string end.
760 *
761 * str: source string, of length lenstr bytes (need not be null-terminated)
762 * buf: where to return the substring (must be long enough)
763 * *bytelen: receives byte length of the found substring
764 * *charlen: receives character length of the found substring
765 *
766 * Returns pointer to end+1 of the found substring in the source string.
767 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
768 *
769 * If the found word is bounded by non-word characters or string boundaries
770 * then this function will include corresponding padding spaces into buf.
771 */
772static const char *
773get_wildcard_part(const char *str, int lenstr,
774 char *buf, int *bytelen, int *charlen)
775{
776 const char *beginword = str;
777 const char *endword;
778 char *s = buf;
779 bool in_leading_wildcard_meta = false;
780 bool in_trailing_wildcard_meta = false;
781 bool in_escape = false;
782 int clen;
783
784 /*
785 * Find the first word character, remembering whether preceding character
786 * was wildcard meta-character. Note that the in_escape state persists
787 * from this loop to the next one, since we may exit at a word character
788 * that is in_escape.
789 */
790 while (beginword - str < lenstr)
791 {
792 if (in_escape)
793 {
794 if (ISWORDCHR(beginword))
795 break;
796 in_escape = false;
797 in_leading_wildcard_meta = false;
798 }
799 else
800 {
801 if (ISESCAPECHAR(beginword))
802 in_escape = true;
803 else if (ISWILDCARDCHAR(beginword))
804 in_leading_wildcard_meta = true;
805 else if (ISWORDCHR(beginword))
806 break;
807 else
808 in_leading_wildcard_meta = false;
809 }
810 beginword += pg_mblen(beginword);
811 }
812
813 /*
814 * Handle string end.
815 */
816 if (beginword - str >= lenstr)
817 return NULL;
818
819 /*
820 * Add left padding spaces if preceding character wasn't wildcard
821 * meta-character.
822 */
823 *charlen = 0;
824 if (!in_leading_wildcard_meta)
825 {
826 if (LPADDING > 0)
827 {
828 *s++ = ' ';
829 (*charlen)++;
830 if (LPADDING > 1)
831 {
832 *s++ = ' ';
833 (*charlen)++;
834 }
835 }
836 }
837
838 /*
839 * Copy data into buf until wildcard meta-character, non-word character or
840 * string boundary. Strip escapes during copy.
841 */
842 endword = beginword;
843 while (endword - str < lenstr)
844 {
845 clen = pg_mblen(endword);
846 if (in_escape)
847 {
848 if (ISWORDCHR(endword))
849 {
850 memcpy(s, endword, clen);
851 (*charlen)++;
852 s += clen;
853 }
854 else
855 {
856 /*
857 * Back up endword to the escape character when stopping at an
858 * escaped char, so that subsequent get_wildcard_part will
859 * restart from the escape character. We assume here that
860 * escape chars are single-byte.
861 */
862 endword--;
863 break;
864 }
865 in_escape = false;
866 }
867 else
868 {
869 if (ISESCAPECHAR(endword))
870 in_escape = true;
871 else if (ISWILDCARDCHAR(endword))
872 {
873 in_trailing_wildcard_meta = true;
874 break;
875 }
876 else if (ISWORDCHR(endword))
877 {
878 memcpy(s, endword, clen);
879 (*charlen)++;
880 s += clen;
881 }
882 else
883 break;
884 }
885 endword += clen;
886 }
887
888 /*
889 * Add right padding spaces if next character isn't wildcard
890 * meta-character.
891 */
892 if (!in_trailing_wildcard_meta)
893 {
894 if (RPADDING > 0)
895 {
896 *s++ = ' ';
897 (*charlen)++;
898 if (RPADDING > 1)
899 {
900 *s++ = ' ';
901 (*charlen)++;
902 }
903 }
904 }
905
906 *bytelen = s - buf;
907 return endword;
908}
909
910/*
911 * Generates trigrams for wildcard search string.
912 *
913 * Returns array of trigrams that must occur in any string that matches the
914 * wildcard string. For example, given pattern "a%bcd%" the trigrams
915 * " a", "bcd" would be extracted.
916 */
917TRGM *
918generate_wildcard_trgm(const char *str, int slen)
919{
920 TRGM *trg;
921 char *buf,
922 *buf2;
923 trgm *tptr;
924 int len,
925 charlen,
926 bytelen;
927 const char *eword;
928
929 protect_out_of_mem(slen);
930
931 trg = (TRGM *) palloc(TRGMHDRSIZE + sizeof(trgm) * (slen / 2 + 1) * 3);
932 trg->flag = ARRKEY;
934
935 if (slen + LPADDING + RPADDING < 3 || slen == 0)
936 return trg;
937
938 tptr = GETARR(trg);
939
940 /* Allocate a buffer for blank-padded, but not yet case-folded, words */
941 buf = palloc(sizeof(char) * (slen + 4));
942
943 /*
944 * Extract trigrams from each substring extracted by get_wildcard_part.
945 */
946 eword = str;
947 while ((eword = get_wildcard_part(eword, slen - (eword - str),
948 buf, &bytelen, &charlen)) != NULL)
949 {
950#ifdef IGNORECASE
951 buf2 = str_tolower(buf, bytelen, DEFAULT_COLLATION_OID);
952 bytelen = strlen(buf2);
953#else
954 buf2 = buf;
955#endif
956
957 /*
958 * count trigrams
959 */
960 tptr = make_trigrams(tptr, buf2, bytelen, charlen);
961
962#ifdef IGNORECASE
963 pfree(buf2);
964#endif
965 }
966
967 pfree(buf);
968
969 if ((len = tptr - GETARR(trg)) == 0)
970 return trg;
971
972 /*
973 * Make trigrams unique.
974 */
975 if (len > 1)
976 {
977 qsort(GETARR(trg), len, sizeof(trgm), comp_trgm);
978 len = qunique(GETARR(trg), len, sizeof(trgm), comp_trgm);
979 }
980
982
983 return trg;
984}
986uint32
987trgm2int(trgm *ptr)
988{
989 uint32 val = 0;
990
991 val |= *(((unsigned char *) ptr));
992 val <<= 8;
993 val |= *(((unsigned char *) ptr) + 1);
994 val <<= 8;
995 val |= *(((unsigned char *) ptr) + 2);
996
997 return val;
998}
1000Datum
1002{
1003 text *in = PG_GETARG_TEXT_PP(0);
1004 TRGM *trg;
1005 Datum *d;
1006 ArrayType *a;
1007 trgm *ptr;
1008 int i;
1009
1011 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(trg)));
1012
1013 for (i = 0, ptr = GETARR(trg); i < ARRNELEM(trg); i++, ptr++)
1014 {
1015 text *item = (text *) palloc(VARHDRSZ + Max(12, pg_database_encoding_max_length() * 3));
1016
1018 {
1019 snprintf(VARDATA(item), 12, "0x%06x", trgm2int(ptr));
1020 SET_VARSIZE(item, VARHDRSZ + strlen(VARDATA(item)));
1021 }
1022 else
1023 {
1024 SET_VARSIZE(item, VARHDRSZ + 3);
1025 CPTRGM(VARDATA(item), ptr);
1026 }
1027 d[i] = PointerGetDatum(item);
1028 }
1029
1030 a = construct_array_builtin(d, ARRNELEM(trg), TEXTOID);
1031
1032 for (i = 0; i < ARRNELEM(trg); i++)
1033 pfree(DatumGetPointer(d[i]));
1034
1035 pfree(d);
1036 pfree(trg);
1037 PG_FREE_IF_COPY(in, 0);
1038
1040}
1042float4
1043cnt_sml(TRGM *trg1, TRGM *trg2, bool inexact)
1044{
1045 trgm *ptr1,
1046 *ptr2;
1047 int count = 0;
1048 int len1,
1049 len2;
1050
1051 ptr1 = GETARR(trg1);
1052 ptr2 = GETARR(trg2);
1053
1054 len1 = ARRNELEM(trg1);
1055 len2 = ARRNELEM(trg2);
1056
1057 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
1058 if (len1 <= 0 || len2 <= 0)
1059 return (float4) 0.0;
1060
1061 while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
1062 {
1063 int res = CMPTRGM(ptr1, ptr2);
1064
1065 if (res < 0)
1066 ptr1++;
1067 else if (res > 0)
1068 ptr2++;
1069 else
1070 {
1071 ptr1++;
1072 ptr2++;
1073 count++;
1074 }
1075 }
1076
1077 /*
1078 * If inexact then len2 is equal to count, because we don't know actual
1079 * length of second string in inexact search and we can assume that count
1080 * is a lower bound of len2.
1081 */
1082 return CALCSML(count, len1, inexact ? count : len2);
1083}
1084
1085
1086/*
1087 * Returns whether trg2 contains all trigrams in trg1.
1088 * This relies on the trigram arrays being sorted.
1090bool
1091trgm_contained_by(TRGM *trg1, TRGM *trg2)
1092{
1093 trgm *ptr1,
1094 *ptr2;
1095 int len1,
1096 len2;
1097
1098 ptr1 = GETARR(trg1);
1099 ptr2 = GETARR(trg2);
1100
1101 len1 = ARRNELEM(trg1);
1102 len2 = ARRNELEM(trg2);
1103
1104 while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
1105 {
1106 int res = CMPTRGM(ptr1, ptr2);
1107
1108 if (res < 0)
1109 return false;
1110 else if (res > 0)
1111 ptr2++;
1112 else
1113 {
1114 ptr1++;
1115 ptr2++;
1116 }
1117 }
1118 if (ptr1 - GETARR(trg1) < len1)
1119 return false;
1120 else
1121 return true;
1122}
1123
1124/*
1125 * Return a palloc'd boolean array showing, for each trigram in "query",
1126 * whether it is present in the trigram array "key".
1127 * This relies on the "key" array being sorted, but "query" need not be.
1129bool *
1131{
1132 bool *result;
1133 trgm *ptrq = GETARR(query),
1134 *ptrk = GETARR(key);
1135 int lenq = ARRNELEM(query),
1136 lenk = ARRNELEM(key),
1137 i;
1138
1139 result = (bool *) palloc0(lenq * sizeof(bool));
1140
1141 /* for each query trigram, do a binary search in the key array */
1142 for (i = 0; i < lenq; i++)
1143 {
1144 int lo = 0;
1145 int hi = lenk;
1146
1147 while (lo < hi)
1148 {
1149 int mid = (lo + hi) / 2;
1150 int res = CMPTRGM(ptrq, ptrk + mid);
1151
1152 if (res < 0)
1153 hi = mid;
1154 else if (res > 0)
1155 lo = mid + 1;
1156 else
1157 {
1158 result[i] = true;
1159 break;
1160 }
1161 }
1162 ptrq++;
1163 }
1164
1165 return result;
1166}
1168Datum
1170{
1171 text *in1 = PG_GETARG_TEXT_PP(0);
1172 text *in2 = PG_GETARG_TEXT_PP(1);
1173 TRGM *trg1,
1174 *trg2;
1175 float4 res;
1176
1177 trg1 = generate_trgm(VARDATA_ANY(in1), VARSIZE_ANY_EXHDR(in1));
1178 trg2 = generate_trgm(VARDATA_ANY(in2), VARSIZE_ANY_EXHDR(in2));
1179
1180 res = cnt_sml(trg1, trg2, false);
1181
1182 pfree(trg1);
1183 pfree(trg2);
1184 PG_FREE_IF_COPY(in1, 0);
1185 PG_FREE_IF_COPY(in2, 1);
1186
1187 PG_RETURN_FLOAT4(res);
1188}
1190Datum
1192{
1193 text *in1 = PG_GETARG_TEXT_PP(0);
1194 text *in2 = PG_GETARG_TEXT_PP(1);
1195 float4 res;
1196
1198 VARDATA_ANY(in2), VARSIZE_ANY_EXHDR(in2),
1199 0);
1200
1201 PG_FREE_IF_COPY(in1, 0);
1202 PG_FREE_IF_COPY(in2, 1);
1203 PG_RETURN_FLOAT4(res);
1204}
1206Datum
1208{
1209 text *in1 = PG_GETARG_TEXT_PP(0);
1210 text *in2 = PG_GETARG_TEXT_PP(1);
1211 float4 res;
1212
1214 VARDATA_ANY(in2), VARSIZE_ANY_EXHDR(in2),
1216
1217 PG_FREE_IF_COPY(in1, 0);
1218 PG_FREE_IF_COPY(in2, 1);
1219 PG_RETURN_FLOAT4(res);
1220}
1222Datum
1224{
1226 PG_GETARG_DATUM(0),
1227 PG_GETARG_DATUM(1)));
1228
1229 PG_RETURN_FLOAT4(1.0 - res);
1230}
1232Datum
1234{
1236 PG_GETARG_DATUM(0),
1237 PG_GETARG_DATUM(1)));
1238
1240}
1242Datum
1244{
1245 text *in1 = PG_GETARG_TEXT_PP(0);
1246 text *in2 = PG_GETARG_TEXT_PP(1);
1247 float4 res;
1248
1250 VARDATA_ANY(in2), VARSIZE_ANY_EXHDR(in2),
1252
1253 PG_FREE_IF_COPY(in1, 0);
1254 PG_FREE_IF_COPY(in2, 1);
1256}
1258Datum
1260{
1261 text *in1 = PG_GETARG_TEXT_PP(0);
1262 text *in2 = PG_GETARG_TEXT_PP(1);
1263 float4 res;
1264
1266 VARDATA_ANY(in1), VARSIZE_ANY_EXHDR(in1),
1268
1269 PG_FREE_IF_COPY(in1, 0);
1270 PG_FREE_IF_COPY(in2, 1);
1272}
1274Datum
1276{
1277 text *in1 = PG_GETARG_TEXT_PP(0);
1278 text *in2 = PG_GETARG_TEXT_PP(1);
1279 float4 res;
1280
1282 VARDATA_ANY(in2), VARSIZE_ANY_EXHDR(in2),
1283 0);
1284
1285 PG_FREE_IF_COPY(in1, 0);
1286 PG_FREE_IF_COPY(in2, 1);
1287 PG_RETURN_FLOAT4(1.0 - res);
1288}
1290Datum
1292{
1293 text *in1 = PG_GETARG_TEXT_PP(0);
1294 text *in2 = PG_GETARG_TEXT_PP(1);
1295 float4 res;
1296
1298 VARDATA_ANY(in1), VARSIZE_ANY_EXHDR(in1),
1299 0);
1300
1301 PG_FREE_IF_COPY(in1, 0);
1302 PG_FREE_IF_COPY(in2, 1);
1303 PG_RETURN_FLOAT4(1.0 - res);
1304}
1306Datum
1308{
1309 text *in1 = PG_GETARG_TEXT_PP(0);
1310 text *in2 = PG_GETARG_TEXT_PP(1);
1311 float4 res;
1312
1314 VARDATA_ANY(in2), VARSIZE_ANY_EXHDR(in2),
1316
1317 PG_FREE_IF_COPY(in1, 0);
1318 PG_FREE_IF_COPY(in2, 1);
1320}
1322Datum
1324{
1325 text *in1 = PG_GETARG_TEXT_PP(0);
1326 text *in2 = PG_GETARG_TEXT_PP(1);
1327 float4 res;
1328
1330 VARDATA_ANY(in1), VARSIZE_ANY_EXHDR(in1),
1332
1333 PG_FREE_IF_COPY(in1, 0);
1334 PG_FREE_IF_COPY(in2, 1);
1336}
1338Datum
1340{
1341 text *in1 = PG_GETARG_TEXT_PP(0);
1342 text *in2 = PG_GETARG_TEXT_PP(1);
1343 float4 res;
1344
1346 VARDATA_ANY(in2), VARSIZE_ANY_EXHDR(in2),
1348
1349 PG_FREE_IF_COPY(in1, 0);
1350 PG_FREE_IF_COPY(in2, 1);
1351 PG_RETURN_FLOAT4(1.0 - res);
1352}
1354Datum
1356{
1357 text *in1 = PG_GETARG_TEXT_PP(0);
1358 text *in2 = PG_GETARG_TEXT_PP(1);
1359 float4 res;
1360
1362 VARDATA_ANY(in1), VARSIZE_ANY_EXHDR(in1),
1364
1365 PG_FREE_IF_COPY(in1, 0);
1366 PG_FREE_IF_COPY(in2, 1);
1367 PG_RETURN_FLOAT4(1.0 - res);
1368}
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3381
uint8_t uint8
Definition: c.h:500
#define Max(x, y)
Definition: c.h:969
#define VARHDRSZ
Definition: c.h:663
uint32_t uint32
Definition: c.h:502
float float4
Definition: c.h:600
size_t Size
Definition: c.h:576
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:149
#define MaxAllocSize
Definition: fe_memutils.h:22
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1763
#define PG_FREE_IF_COPY(ptr, n)
Definition: fmgr.h:260
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:684
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define PG_GETARG_FLOAT4(n)
Definition: fmgr.h:281
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
#define PG_RETURN_FLOAT4(x)
Definition: fmgr.h:366
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
char * str_tolower(const char *buff, size_t nbytes, Oid collid)
Definition: formatting.c:1637
void DefineCustomRealVariable(const char *name, const char *short_desc, const char *long_desc, double *valueAddr, double bootValue, double minValue, double maxValue, GucContext context, int flags, GucRealCheckHook check_hook, GucRealAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5189
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4332
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5280
@ PGC_S_SESSION
Definition: guc.h:126
@ PGC_USERSET
Definition: guc.h:79
Assert(PointerIsAligned(start, uint64))
const char * str
#define CALCGTSIZE(flag, siglen)
Definition: hstore_gist.c:60
long val
Definition: informix.c:689
static int pg_cmp_s32(int32 a, int32 b)
Definition: int.h:646
int b
Definition: isn.c:74
int a
Definition: isn.c:73
int j
Definition: isn.c:78
int i
Definition: isn.c:77
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:3047
int pg_database_encoding_max_length(void)
Definition: mbutils.c:1546
int pg_mblen(const char *mbstr)
Definition: mbutils.c:1023
void pfree(void *pointer)
Definition: mcxt.c:2147
void * palloc0(Size size)
Definition: mcxt.c:1970
void * palloc(Size size)
Definition: mcxt.c:1940
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:123
Datum lower(PG_FUNCTION_ARGS)
Definition: oracle_compat.c:49
Datum upper(PG_FUNCTION_ARGS)
Definition: oracle_compat.c:80
const void size_t len
return crc
uint32 pg_crc32
Definition: pg_crc.h:37
#define INIT_LEGACY_CRC32(crc)
Definition: pg_crc.h:79
#define COMP_LEGACY_CRC32(crc, data, len)
Definition: pg_crc.h:81
#define FIN_LEGACY_CRC32(crc)
Definition: pg_crc.h:80
static char * buf
Definition: pg_test_fsync.c:72
#define snprintf
Definition: port.h:239
#define qsort(a, b, c, d)
Definition: port.h:479
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:327
static Datum Float4GetDatum(float4 X)
Definition: postgres.h:480
uintptr_t Datum
Definition: postgres.h:69
static float4 DatumGetFloat4(Datum X)
Definition: postgres.h:463
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
unsigned int Oid
Definition: postgres_ext.h:30
static size_t qunique(void *array, size_t elements, size_t width, int(*compare)(const void *, const void *))
Definition: qunique.h:21
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:743
uint16 StrategyNumber
Definition: stratnum.h:22
Definition: trgm.h:58
uint8 flag
Definition: trgm.h:60
Definition: type.h:96
int index
Definition: trgm_op.c:55
trgm trg
Definition: trgm_op.c:54
Definition: c.h:658
#define CALCSML(count, len1, len2)
Definition: trgm.h:107
#define ISWORDCHR(c)
Definition: trgm.h:50
#define WordSimilarityStrategyNumber
Definition: trgm.h:35
#define StrictWordSimilarityStrategyNumber
Definition: trgm.h:37
#define ISESCAPECHAR(x)
Definition: trgm.h:54
#define ARRNELEM(x)
Definition: trgm.h:98
#define RPADDING
Definition: trgm.h:17
#define LPADDING
Definition: trgm.h:16
#define SimilarityStrategyNumber
Definition: trgm.h:29
#define ISWILDCARDCHAR(x)
Definition: trgm.h:55
char trgm[3]
Definition: trgm.h:41
#define CPTRGM(a, b)
Definition: trgm.h:43
#define ISPRINTABLETRGM(t)
Definition: trgm.h:52
#define GETARR(x)
Definition: trgm.h:97
#define ARRKEY
Definition: trgm.h:87
#define TRGMHDRSIZE
Definition: trgm.h:64
static float4 iterate_word_similarity(int *trg2indexes, bool *found, int ulen1, int len2, int len, uint8 flags, TrgmBound *bounds)
Definition: trgm_op.c:503
uint8 TrgmBound
Definition: trgm_op.c:59
Datum strict_word_similarity_commutator_op(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1321
static int CMPTRGM_UNSIGNED(const void *a, const void *b)
Definition: trgm_op.c:131
void _PG_init(void)
Definition: trgm_op.c:71
Datum set_limit(PG_FUNCTION_ARGS)
Definition: trgm_op.c:160
static int comp_trgm(const void *a, const void *b)
Definition: trgm_op.c:211
double strict_word_similarity_threshold
Definition: trgm_op.c:29
TRGM * generate_trgm(char *str, int slen)
Definition: trgm_op.c:406
uint32 trgm2int(trgm *ptr)
Definition: trgm_op.c:985
PG_MODULE_MAGIC_EXT(.name="pg_trgm",.version=PG_VERSION)
static int CMPTRGM_CHOOSE(const void *a, const void *b)
Definition: trgm_op.c:145
int(* CMPTRGM)(const void *a, const void *b)
Definition: trgm_op.c:49
#define WORD_SIMILARITY_CHECK_ONLY
Definition: trgm_op.c:64
static void protect_out_of_mem(int slen)
Definition: trgm_op.c:389
Datum word_similarity(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1189
Datum strict_word_similarity_dist_commutator_op(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1353
void compact_trigram(trgm *tptr, char *str, int bytelen)
Definition: trgm_op.c:248
bool * trgm_presence_map(TRGM *query, TRGM *key)
Definition: trgm_op.c:1128
PG_FUNCTION_INFO_V1(set_limit)
static float4 calc_word_similarity(char *str1, int slen1, char *str2, int slen2, uint8 flags)
Definition: trgm_op.c:671
double word_similarity_threshold
Definition: trgm_op.c:28
Datum word_similarity_dist_commutator_op(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1289
double index_strategy_get_limit(StrategyNumber strategy)
Definition: trgm_op.c:182
Datum similarity(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1167
static pos_trgm * make_positional_trgm(trgm *trg1, int len1, trgm *trg2, int len2)
Definition: trgm_op.c:447
double similarity_threshold
Definition: trgm_op.c:27
static int CMPTRGM_SIGNED(const void *a, const void *b)
Definition: trgm_op.c:121
static int comp_ptrgm(const void *v1, const void *v2)
Definition: trgm_op.c:474
static char * find_word(char *str, int lenstr, char **endword, int *charlen)
Definition: trgm_op.c:221
Datum show_trgm(PG_FUNCTION_ARGS)
Definition: trgm_op.c:999
bool trgm_contained_by(TRGM *trg1, TRGM *trg2)
Definition: trgm_op.c:1089
#define CMPPCHAR_S(a, b, i)
#define TRGM_BOUND_RIGHT
Definition: trgm_op.c:61
Datum show_limit(PG_FUNCTION_ARGS)
Definition: trgm_op.c:205
#define CMPPCHAR_UNS(a, b, i)
Datum strict_word_similarity_dist_op(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1337
Datum word_similarity_op(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1241
Datum word_similarity_commutator_op(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1257
#define WORD_SIMILARITY_STRICT
Definition: trgm_op.c:65
#define TRGM_BOUND_LEFT
Definition: trgm_op.c:60
TRGM * generate_wildcard_trgm(const char *str, int slen)
Definition: trgm_op.c:916
static trgm * make_trigrams(trgm *tptr, char *str, int bytelen, int charlen)
Definition: trgm_op.c:273
float4 cnt_sml(TRGM *trg1, TRGM *trg2, bool inexact)
Definition: trgm_op.c:1041
static int generate_trgm_only(trgm *trg, char *str, int slen, TrgmBound *bounds)
Definition: trgm_op.c:325
Datum similarity_op(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1231
Datum word_similarity_dist_op(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1273
static const char * get_wildcard_part(const char *str, int lenstr, char *buf, int *bytelen, int *charlen)
Definition: trgm_op.c:771
Datum strict_word_similarity(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1205
Datum similarity_dist(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1221
Datum strict_word_similarity_op(PG_FUNCTION_ARGS)
Definition: trgm_op.c:1305
#define VARDATA(PTR)
Definition: varatt.h:278
#define VARDATA_ANY(PTR)
Definition: varatt.h:324
#define SET_VARSIZE(PTR, len)
Definition: varatt.h:305
#define VARSIZE_ANY_EXHDR(PTR)
Definition: varatt.h:317
const char * name
bool GetDefaultCharSignedness(void)
Definition: xlog.c:4768