PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 * A growable array of trigrams
71 *
72 * The actual array of trigrams is in 'datum'. Note that the other fields in
73 * 'datum', i.e. datum->flags and the varlena length, are not kept up to date
74 * when items are added to the growable array. We merely reserve the space
75 * for them here. You must fill those other fields before using 'datum' as a
76 * proper TRGM datum.
77 */
78typedef struct
80 TRGM *datum; /* trigram array */
81 int length; /* number of trigrams in the array */
82 int allocated; /* allocated size of 'datum' (# of trigrams) */
84
85/*
86 * Allocate a new growable array.
87 *
88 * 'slen' is the size of the source string that we're extracting the trigrams
89 * from. It is used to choose the initial size of the array.
90 */
91static void
93{
94 size_t init_size;
95
96 /*
97 * In the extreme case, the input string consists entirely of one
98 * character words, like "a b c", where each word is expanded to two
99 * trigrams. This is not a strict upper bound though, because when
100 * IGNORECASE is defined, we convert the input string to lowercase before
101 * extracting the trigrams, which in rare cases can expand one input
102 * character into multiple characters.
103 */
104 init_size = (size_t) slen + 1;
105
106 /*
107 * Guard against possible overflow in the palloc request. (We don't worry
108 * about the additive constants, since palloc can detect requests that are
109 * a little above MaxAllocSize --- we just need to prevent integer
110 * overflow in the multiplications.)
111 */
112 if (init_size > MaxAllocSize / sizeof(trgm))
115 errmsg("out of memory")));
116
118 arr->allocated = init_size;
119 arr->length = 0;
120}
121
122/* Make sure the array can hold at least 'needed' more trigrams */
123static void
125{
126 size_t new_needed = (size_t) arr->length + needed;
127
128 if (new_needed > arr->allocated)
129 {
130 /* Guard against possible overflow, like in init_trgm_array */
131 if (new_needed > MaxAllocSize / sizeof(trgm))
134 errmsg("out of memory")));
135
137 arr->allocated = new_needed;
138 }
139}
140
141/*
142 * Module load callback
143 */
144void
145_PG_init(void)
146{
147 /* Define custom GUC variables. */
148 DefineCustomRealVariable("pg_trgm.similarity_threshold",
149 "Sets the threshold used by the % operator.",
150 "Valid range is 0.0 .. 1.0.",
152 0.3f,
153 0.0,
154 1.0,
156 0,
157 NULL,
158 NULL,
159 NULL);
160 DefineCustomRealVariable("pg_trgm.word_similarity_threshold",
161 "Sets the threshold used by the <% operator.",
162 "Valid range is 0.0 .. 1.0.",
164 0.6f,
165 0.0,
166 1.0,
168 0,
169 NULL,
170 NULL,
171 NULL);
172 DefineCustomRealVariable("pg_trgm.strict_word_similarity_threshold",
173 "Sets the threshold used by the <<% operator.",
174 "Valid range is 0.0 .. 1.0.",
176 0.5f,
177 0.0,
178 1.0,
180 0,
181 NULL,
182 NULL,
183 NULL);
184
185 MarkGUCPrefixReserved("pg_trgm");
187
188#define CMPCHAR(a,b) ( ((a)==(b)) ? 0 : ( ((a)<(b)) ? -1 : 1 ) )
189
190/*
191 * Functions for comparing two trgms while treating each char as "signed char" or
192 * "unsigned char".
193 */
194static inline int
195CMPTRGM_SIGNED(const void *a, const void *b)
196{
197#define CMPPCHAR_S(a,b,i) CMPCHAR( *(((const signed char*)(a))+i), *(((const signed char*)(b))+i) )
198
199 return CMPPCHAR_S(a, b, 0) ? CMPPCHAR_S(a, b, 0)
200 : (CMPPCHAR_S(a, b, 1) ? CMPPCHAR_S(a, b, 1)
201 : CMPPCHAR_S(a, b, 2));
202}
204static inline int
205CMPTRGM_UNSIGNED(const void *a, const void *b)
206{
207#define CMPPCHAR_UNS(a,b,i) CMPCHAR( *(((const unsigned char*)(a))+i), *(((const unsigned char*)(b))+i) )
208
209 return CMPPCHAR_UNS(a, b, 0) ? CMPPCHAR_UNS(a, b, 0)
210 : (CMPPCHAR_UNS(a, b, 1) ? CMPPCHAR_UNS(a, b, 1)
211 : CMPPCHAR_UNS(a, b, 2));
212}
213
214/*
215 * This gets called on the first call. It replaces the function pointer so
216 * that subsequent calls are routed directly to the chosen implementation.
217 */
218static int
219CMPTRGM_CHOOSE(const void *a, const void *b)
220{
223 else
225
226 return CMPTRGM(a, b);
227}
228
229/*
230 * Deprecated function.
231 * Use "pg_trgm.similarity_threshold" GUC variable instead of this function.
249}
250
251
252/*
253 * Get similarity threshold for given index scan strategy number.
254 */
255double
257{
258 switch (strategy)
259 {
266 default:
267 elog(ERROR, "unrecognized strategy number: %d", strategy);
268 break;
269 }
270
271 return 0.0; /* keep compiler quiet */
272}
273
274/*
275 * Deprecated function.
276 * Use "pg_trgm.similarity_threshold" GUC variable instead of this function.
282}
284static int
285comp_trgm(const void *a, const void *b)
286{
287 return CMPTRGM(a, b);
288}
289
290/*
291 * Finds first word in string, returns pointer to the word,
292 * endword points to the character after word
293 */
294static char *
295find_word(char *str, int lenstr, char **endword)
296{
297 char *beginword = str;
298 const char *endstr = str + lenstr;
299
300 while (beginword < endstr)
301 {
303
305 break;
306 beginword += clen;
307 }
308
309 if (beginword >= endstr)
310 return NULL;
311
313 while (*endword < endstr)
314 {
316
317 if (!ISWORDCHR(*endword, clen))
318 break;
319 *endword += clen;
320 }
321
322 return beginword;
323}
324
325/*
326 * Reduce a trigram (three possibly multi-byte characters) to a trgm,
327 * which is always exactly three bytes. If we have three single-byte
328 * characters, we just use them as-is; otherwise we form a hash value.
329 */
330void
331compact_trigram(trgm *tptr, char *str, int bytelen)
332{
333 if (bytelen == 3)
334 {
335 CPTRGM(tptr, str);
336 }
337 else
338 {
340
344
345 /*
346 * use only 3 upper bytes from crc, hope, it's good enough hashing
347 */
348 CPTRGM(tptr, &crc);
349 }
350}
351
352/*
353 * Adds trigrams from the word in 'str' (already padded if necessary).
354 */
355static void
357{
358 trgm *tptr;
359 char *ptr = str;
360
361 if (bytelen < 3)
362 return;
363
364 /* max number of trigrams = strlen - 2 */
366 tptr = GETARR(dst->datum) + dst->length;
367
369 {
370 while (ptr < str + bytelen - 2)
371 {
372 CPTRGM(tptr, ptr);
373 ptr++;
374 tptr++;
375 }
376 }
377 else
378 {
379 int lenfirst,
380 lenmiddle,
381 lenlast;
382 char *endptr;
383
384 /*
385 * Fast path as long as there are no multibyte characters
386 */
387 if (!IS_HIGHBIT_SET(ptr[0]) && !IS_HIGHBIT_SET(ptr[1]))
388 {
389 while (!IS_HIGHBIT_SET(ptr[2]))
390 {
391 CPTRGM(tptr, ptr);
392 ptr++;
393 tptr++;
394
395 if (ptr == str + bytelen - 2)
396 goto done;
397 }
398
399 lenfirst = 1;
400 lenmiddle = 1;
401 lenlast = pg_mblen_unbounded(ptr + 2);
402 }
403 else
404 {
406 if (ptr + lenfirst >= str + bytelen)
407 goto done;
409 if (ptr + lenfirst + lenmiddle >= str + bytelen)
410 goto done;
412 }
413
414 /*
415 * Slow path to handle any remaining multibyte characters
416 *
417 * As we go, 'ptr' points to the beginning of the current
418 * three-character string and 'endptr' points to just past it.
419 */
420 endptr = ptr + lenfirst + lenmiddle + lenlast;
421 while (endptr <= str + bytelen)
422 {
423 compact_trigram(tptr, ptr, endptr - ptr);
424 tptr++;
425
426 /* Advance to the next character */
427 if (endptr == str + bytelen)
428 break;
429 ptr += lenfirst;
432 lenlast = pg_mblen_unbounded(endptr);
433 endptr += lenlast;
434 }
435 }
436
437done:
438 dst->length = tptr - GETARR(dst->datum);
439 Assert(dst->length <= dst->allocated);
440}
441
442/*
443 * Make array of trigrams without sorting and removing duplicate items.
444 *
445 * dst: where to return the array of trigrams.
446 * str: source string, of length slen bytes.
447 * bounds_p: where to return bounds of trigrams (if needed).
448 */
449static void
451{
452 size_t buflen;
453 char *buf;
454 int bytelen;
455 char *bword,
456 *eword;
458 int bounds_allocated = 0;
459
461
462 /*
463 * If requested, allocate an array for the bounds, with the same size as
464 * the trigram array.
465 */
466 if (bounds_p)
467 {
468 bounds_allocated = dst->allocated;
470 }
471
472 if (slen + LPADDING + RPADDING < 3 || slen == 0)
473 return;
474
475 /*
476 * Allocate a buffer for case-folded, blank-padded words.
477 *
478 * As an initial guess, allocate a buffer large enough to hold the
479 * original string with padding, which is always enough when compiled with
480 * !IGNORECASE. If the case-folding produces a string longer than the
481 * original, we'll grow the buffer.
482 */
483 buflen = (size_t) slen + 4;
484 buf = (char *) palloc(buflen);
485 if (LPADDING > 0)
486 {
487 *buf = ' ';
488 if (LPADDING > 1)
489 *(buf + 1) = ' ';
490 }
491
492 eword = str;
493 while ((bword = find_word(eword, slen - (eword - str), &eword)) != NULL)
494 {
495 int oldlen;
496
497 /* Convert word to lower case before extracting trigrams from it */
498#ifdef IGNORECASE
499 {
500 char *lowered;
501
504
505 /* grow the buffer if necessary */
506 if (bytelen > buflen - 4)
507 {
508 pfree(buf);
509 buflen = (size_t) bytelen + 4;
510 buf = (char *) palloc(buflen);
511 if (LPADDING > 0)
512 {
513 *buf = ' ';
514 if (LPADDING > 1)
515 *(buf + 1) = ' ';
516 }
517 }
519 pfree(lowered);
520 }
521#else
522 bytelen = eword - bword;
524#endif
525
526 buf[LPADDING + bytelen] = ' ';
527 buf[LPADDING + bytelen + 1] = ' ';
528
529 /* Calculate trigrams marking their bounds if needed */
530 oldlen = dst->length;
532 if (bounds)
533 {
534 if (bounds_allocated < dst->length)
535 {
537 bounds_allocated = dst->allocated;
538 }
539
541 bounds[dst->length - 1] |= TRGM_BOUND_RIGHT;
542 }
543 }
544
545 pfree(buf);
546}
547
548/*
549 * Make array of trigrams with sorting and removing duplicate items.
550 *
551 * str: source string, of length slen bytes.
552 *
553 * Returns the sorted array of unique trigrams.
554 */
555TRGM *
556generate_trgm(char *str, int slen)
557{
558 TRGM *trg;
560 int len;
561
563 len = arr.length;
564 trg = arr.datum;
565 trg->flag = ARRKEY;
566
567 /*
568 * Make trigrams unique.
569 */
570 if (len > 1)
571 {
572 qsort(GETARR(trg), len, sizeof(trgm), comp_trgm);
573 len = qunique(GETARR(trg), len, sizeof(trgm), comp_trgm);
574 }
575
577
578 return trg;
579}
580
581/*
582 * Make array of positional trigrams from two trigram arrays trg1 and trg2.
583 *
584 * trg1: trigram array of search pattern, of length len1. trg1 is required
585 * word which positions don't matter and replaced with -1.
586 * trg2: trigram array of text, of length len2. trg2 is haystack where we
587 * search and have to store its positions.
588 *
589 * Returns concatenated trigram array.
590 */
591static pos_trgm *
592make_positional_trgm(trgm *trg1, int len1, trgm *trg2, int len2)
593{
594 pos_trgm *result;
595 int i,
596 len = len1 + len2;
597
598 result = palloc_array(pos_trgm, len);
599
600 for (i = 0; i < len1; i++)
601 {
602 memcpy(&result[i].trg, &trg1[i], sizeof(trgm));
603 result[i].index = -1;
604 }
605
606 for (i = 0; i < len2; i++)
607 {
608 memcpy(&result[i + len1].trg, &trg2[i], sizeof(trgm));
609 result[i + len1].index = i;
610 }
611
612 return result;
613}
614
615/*
616 * Compare position trigrams: compare trigrams first and position second.
617 */
618static int
619comp_ptrgm(const void *v1, const void *v2)
620{
621 const pos_trgm *p1 = (const pos_trgm *) v1;
622 const pos_trgm *p2 = (const pos_trgm *) v2;
623 int cmp;
624
625 cmp = CMPTRGM(p1->trg, p2->trg);
626 if (cmp != 0)
627 return cmp;
628
629 return pg_cmp_s32(p1->index, p2->index);
630}
631
632/*
633 * Iterative search function which calculates maximum similarity with word in
634 * the string. Maximum similarity is only calculated only if the flag
635 * WORD_SIMILARITY_CHECK_ONLY isn't set.
636 *
637 * trg2indexes: array which stores indexes of the array "found".
638 * found: array which stores true of false values.
639 * ulen1: count of unique trigrams of array "trg1".
640 * len2: length of array "trg2" and array "trg2indexes".
641 * len: length of the array "found".
642 * flags: set of boolean flags parameterizing similarity calculation.
643 * bounds: whether each trigram is left/right bound of word.
644 *
645 * Returns word similarity.
646 */
647static float4
649 bool *found,
650 int ulen1,
651 int len2,
652 int len,
653 uint8 flags,
655{
656 int *lastpos,
657 i,
658 ulen2 = 0,
659 count = 0,
660 upper = -1,
661 lower;
663 smlr_max = 0.0f;
664 double threshold;
665
666 Assert(bounds || !(flags & WORD_SIMILARITY_STRICT));
667
668 /* Select appropriate threshold */
672
673 /*
674 * Consider first trigram as initial lower bound for strict word
675 * similarity, or initialize it later with first trigram present for plain
676 * word similarity.
677 */
678 lower = (flags & WORD_SIMILARITY_STRICT) ? 0 : -1;
679
680 /* Memorise last position of each trigram */
681 lastpos = palloc_array(int, len);
682 memset(lastpos, -1, sizeof(int) * len);
683
684 for (i = 0; i < len2; i++)
685 {
686 int trgindex;
687
689
690 /* Get index of next trigram */
692
693 /* Update last position of this trigram */
694 if (lower >= 0 || found[trgindex])
695 {
696 if (lastpos[trgindex] < 0)
697 {
698 ulen2++;
699 if (found[trgindex])
700 count++;
701 }
702 lastpos[trgindex] = i;
703 }
704
705 /*
706 * Adjust upper bound if trigram is upper bound of word for strict
707 * word similarity, or if trigram is present in required substring for
708 * plain word similarity
709 */
711 : found[trgindex])
712 {
713 int prev_lower,
714 tmp_ulen2,
715 tmp_lower,
716 tmp_count;
717
718 upper = i;
719 if (lower == -1)
720 {
721 lower = i;
722 ulen2 = 1;
723 }
724
725 smlr_cur = CALCSML(count, ulen1, ulen2);
726
727 /* Also try to adjust lower bound for greater similarity */
728 tmp_count = count;
732 {
733 float smlr_tmp;
734 int tmp_trgindex;
735
736 /*
737 * Adjust lower bound only if trigram is lower bound of word
738 * for strict word similarity, or consider every trigram as
739 * lower bound for plain word similarity.
740 */
741 if (!(flags & WORD_SIMILARITY_STRICT)
743 {
745 if (smlr_tmp > smlr_cur)
746 {
750 count = tmp_count;
751 }
752
753 /*
754 * If we only check that word similarity is greater than
755 * threshold we do not need to calculate a maximum
756 * similarity.
757 */
758 if ((flags & WORD_SIMILARITY_CHECK_ONLY)
759 && smlr_cur >= threshold)
760 break;
761 }
762
765 {
766 tmp_ulen2--;
767 if (found[tmp_trgindex])
768 tmp_count--;
769 }
770 }
771
773
774 /*
775 * if we only check that word similarity is greater than threshold
776 * we do not need to calculate a maximum similarity.
777 */
779 break;
780
782 {
783 int tmp_trgindex;
784
787 lastpos[tmp_trgindex] = -1;
788 }
789 }
790 }
791
792 pfree(lastpos);
793
794 return smlr_max;
795}
796
797/*
798 * Calculate word similarity.
799 * This function prepare two arrays: "trg2indexes" and "found". Then this arrays
800 * are used to calculate word similarity using iterate_word_similarity().
801 *
802 * "trg2indexes" is array which stores indexes of the array "found".
803 * In other words:
804 * trg2indexes[j] = i;
805 * found[i] = true (or false);
806 * If found[i] == true then there is trigram trg2[j] in array "trg1".
807 * If found[i] == false then there is not trigram trg2[j] in array "trg1".
808 *
809 * str1: search pattern string, of length slen1 bytes.
810 * str2: text in which we are looking for a word, of length slen2 bytes.
811 * flags: set of boolean flags parameterizing similarity calculation.
812 *
813 * Returns word similarity.
814 */
815static float4
816calc_word_similarity(char *str1, int slen1, char *str2, int slen2,
817 uint8 flags)
818{
819 bool *found;
820 pos_trgm *ptrg;
823 int len1,
824 len2,
825 len,
826 i,
827 j,
828 ulen1;
829 int *trg2indexes;
830 float4 result;
832
833 /* Make positional trigrams */
834
836 len1 = trg1.length;
838 len2 = trg2.length;
839
840 ptrg = make_positional_trgm(GETARR(trg1.datum), len1, GETARR(trg2.datum), len2);
841 len = len1 + len2;
842 qsort(ptrg, len, sizeof(pos_trgm), comp_ptrgm);
843
844 pfree(trg1.datum);
845 pfree(trg2.datum);
846
847 /*
848 * Merge positional trigrams array: enumerate each trigram and find its
849 * presence in required word.
850 */
851 trg2indexes = palloc_array(int, len2);
852 found = palloc0_array(bool, len);
853
854 ulen1 = 0;
855 j = 0;
856 for (i = 0; i < len; i++)
857 {
858 if (i > 0)
859 {
860 int cmp = CMPTRGM(ptrg[i - 1].trg, ptrg[i].trg);
861
862 if (cmp != 0)
863 {
864 if (found[j])
865 ulen1++;
866 j++;
867 }
868 }
869
870 if (ptrg[i].index >= 0)
871 {
872 trg2indexes[ptrg[i].index] = j;
873 }
874 else
875 {
876 found[j] = true;
877 }
878 }
879 if (found[j])
880 ulen1++;
881
882 /* Run iterative procedure to find maximum similarity with word */
883 result = iterate_word_similarity(trg2indexes, found, ulen1, len2, len,
884 flags, bounds);
885
887 pfree(found);
888 pfree(ptrg);
889
890 return result;
891}
892
893
894/*
895 * Extract the next non-wildcard part of a search string, i.e. a word bounded
896 * by '_' or '%' meta-characters, non-word characters or string end.
897 *
898 * str: source string, of length lenstr bytes (need not be null-terminated)
899 * buf: where to return the substring (must be long enough)
900 * *bytelen: receives byte length of the found substring
901 *
902 * Returns pointer to end+1 of the found substring in the source string.
903 * Returns NULL if no word found (in which case buf, bytelen is not set)
904 *
905 * If the found word is bounded by non-word characters or string boundaries
906 * then this function will include corresponding padding spaces into buf.
907 */
908static const char *
909get_wildcard_part(const char *str, int lenstr,
910 char *buf, int *bytelen)
911{
912 const char *beginword = str;
913 const char *endword;
914 const char *endstr = str + lenstr;
915 char *s = buf;
916 bool in_leading_wildcard_meta = false;
917 bool in_trailing_wildcard_meta = false;
918 bool in_escape = false;
919 int clen;
920
921 /*
922 * Find the first word character, remembering whether preceding character
923 * was wildcard meta-character. Note that the in_escape state persists
924 * from this loop to the next one, since we may exit at a word character
925 * that is in_escape.
926 */
927 while (beginword < endstr)
928 {
930
931 if (in_escape)
932 {
934 break;
935 in_escape = false;
937 }
938 else
939 {
941 in_escape = true;
942 else if (ISWILDCARDCHAR(beginword))
944 else if (ISWORDCHR(beginword, clen))
945 break;
946 else
948 }
949 beginword += clen;
950 }
951
952 /*
953 * Handle string end.
954 */
955 if (beginword - str >= lenstr)
956 return NULL;
957
958 /*
959 * Add left padding spaces if preceding character wasn't wildcard
960 * meta-character.
961 */
963 {
964 if (LPADDING > 0)
965 {
966 *s++ = ' ';
967 if (LPADDING > 1)
968 *s++ = ' ';
969 }
970 }
971
972 /*
973 * Copy data into buf until wildcard meta-character, non-word character or
974 * string boundary. Strip escapes during copy.
975 */
977 while (endword < endstr)
978 {
980 if (in_escape)
981 {
982 if (ISWORDCHR(endword, clen))
983 {
984 memcpy(s, endword, clen);
985 s += clen;
986 }
987 else
988 {
989 /*
990 * Back up endword to the escape character when stopping at an
991 * escaped char, so that subsequent get_wildcard_part will
992 * restart from the escape character. We assume here that
993 * escape chars are single-byte.
994 */
995 endword--;
996 break;
997 }
998 in_escape = false;
999 }
1000 else
1001 {
1002 if (ISESCAPECHAR(endword))
1003 in_escape = true;
1004 else if (ISWILDCARDCHAR(endword))
1005 {
1007 break;
1008 }
1009 else if (ISWORDCHR(endword, clen))
1010 {
1011 memcpy(s, endword, clen);
1012 s += clen;
1013 }
1014 else
1015 break;
1016 }
1017 endword += clen;
1018 }
1019
1020 /*
1021 * Add right padding spaces if next character isn't wildcard
1022 * meta-character.
1023 */
1025 {
1026 if (RPADDING > 0)
1027 {
1028 *s++ = ' ';
1029 if (RPADDING > 1)
1030 *s++ = ' ';
1031 }
1032 }
1033
1034 *bytelen = s - buf;
1035 return endword;
1036}
1037
1038/*
1039 * Generates trigrams for wildcard search string.
1040 *
1041 * Returns array of trigrams that must occur in any string that matches the
1042 * wildcard string. For example, given pattern "a%bcd%" the trigrams
1043 * " a", "bcd" would be extracted.
1045TRGM *
1046generate_wildcard_trgm(const char *str, int slen)
1047{
1048 TRGM *trg;
1050 char *buf;
1051 int len,
1052 bytelen;
1053 const char *eword;
1054
1055 if (slen + LPADDING + RPADDING < 3 || slen == 0)
1056 {
1057 trg = (TRGM *) palloc(TRGMHDRSIZE);
1058 trg->flag = ARRKEY;
1060 return trg;
1061 }
1062
1063 init_trgm_array(&arr, slen);
1064
1065 /* Allocate a buffer for blank-padded, but not yet case-folded, words */
1066 buf = palloc_array(char, slen + 4);
1067
1068 /*
1069 * Extract trigrams from each substring extracted by get_wildcard_part.
1070 */
1071 eword = str;
1072 while ((eword = get_wildcard_part(eword, slen - (eword - str),
1073 buf, &bytelen)) != NULL)
1074 {
1075 char *word;
1076
1077#ifdef IGNORECASE
1079 bytelen = strlen(word);
1080#else
1081 word = buf;
1082#endif
1083
1084 /*
1085 * count trigrams
1086 */
1087 make_trigrams(&arr, word, bytelen);
1088
1089#ifdef IGNORECASE
1090 pfree(word);
1091#endif
1092 }
1093
1094 pfree(buf);
1095
1096 /*
1097 * Make trigrams unique.
1098 */
1099 trg = arr.datum;
1100 len = arr.length;
1101 if (len > 1)
1102 {
1103 qsort(GETARR(trg), len, sizeof(trgm), comp_trgm);
1104 len = qunique(GETARR(trg), len, sizeof(trgm), comp_trgm);
1105 }
1106
1107 trg->flag = ARRKEY;
1109
1110 return trg;
1111}
1113uint32
1114trgm2int(trgm *ptr)
1115{
1116 uint32 val = 0;
1117
1118 val |= *(((unsigned char *) ptr));
1119 val <<= 8;
1120 val |= *(((unsigned char *) ptr) + 1);
1121 val <<= 8;
1122 val |= *(((unsigned char *) ptr) + 2);
1123
1124 return val;
1125}
1127Datum
1129{
1130 text *in = PG_GETARG_TEXT_PP(0);
1131 TRGM *trg;
1132 Datum *d;
1133 ArrayType *a;
1134 trgm *ptr;
1135 int i;
1136
1138 d = palloc_array(Datum, 1 + ARRNELEM(trg));
1139
1140 for (i = 0, ptr = GETARR(trg); i < ARRNELEM(trg); i++, ptr++)
1141 {
1142 text *item = (text *) palloc(VARHDRSZ + Max(12, pg_database_encoding_max_length() * 3));
1143
1145 {
1146 snprintf(VARDATA(item), 12, "0x%06x", trgm2int(ptr));
1147 SET_VARSIZE(item, VARHDRSZ + strlen(VARDATA(item)));
1148 }
1149 else
1150 {
1151 SET_VARSIZE(item, VARHDRSZ + 3);
1152 CPTRGM(VARDATA(item), ptr);
1153 }
1154 d[i] = PointerGetDatum(item);
1155 }
1156
1158
1159 for (i = 0; i < ARRNELEM(trg); i++)
1160 pfree(DatumGetPointer(d[i]));
1161
1162 pfree(d);
1163 pfree(trg);
1164 PG_FREE_IF_COPY(in, 0);
1165
1167}
1169float4
1170cnt_sml(TRGM *trg1, TRGM *trg2, bool inexact)
1171{
1172 trgm *ptr1,
1173 *ptr2;
1174 int count = 0;
1175 int len1,
1176 len2;
1177
1178 ptr1 = GETARR(trg1);
1179 ptr2 = GETARR(trg2);
1180
1181 len1 = ARRNELEM(trg1);
1182 len2 = ARRNELEM(trg2);
1183
1184 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
1185 if (len1 <= 0 || len2 <= 0)
1186 return (float4) 0.0;
1187
1188 while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
1189 {
1190 int res = CMPTRGM(ptr1, ptr2);
1191
1192 if (res < 0)
1193 ptr1++;
1194 else if (res > 0)
1195 ptr2++;
1196 else
1197 {
1198 ptr1++;
1199 ptr2++;
1200 count++;
1201 }
1202 }
1203
1204 /*
1205 * If inexact then len2 is equal to count, because we don't know actual
1206 * length of second string in inexact search and we can assume that count
1207 * is a lower bound of len2.
1208 */
1209 return CALCSML(count, len1, inexact ? count : len2);
1210}
1211
1212
1213/*
1214 * Returns whether trg2 contains all trigrams in trg1.
1215 * This relies on the trigram arrays being sorted.
1217bool
1219{
1220 trgm *ptr1,
1221 *ptr2;
1222 int len1,
1223 len2;
1224
1225 ptr1 = GETARR(trg1);
1226 ptr2 = GETARR(trg2);
1227
1228 len1 = ARRNELEM(trg1);
1229 len2 = ARRNELEM(trg2);
1230
1231 while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
1232 {
1233 int res = CMPTRGM(ptr1, ptr2);
1234
1235 if (res < 0)
1236 return false;
1237 else if (res > 0)
1238 ptr2++;
1239 else
1240 {
1241 ptr1++;
1242 ptr2++;
1243 }
1244 }
1245 if (ptr1 - GETARR(trg1) < len1)
1246 return false;
1247 else
1248 return true;
1249}
1250
1251/*
1252 * Return a palloc'd boolean array showing, for each trigram in "query",
1253 * whether it is present in the trigram array "key".
1254 * This relies on the "key" array being sorted, but "query" need not be.
1256bool *
1257trgm_presence_map(TRGM *query, TRGM *key)
1258{
1259 bool *result;
1260 trgm *ptrq = GETARR(query),
1261 *ptrk = GETARR(key);
1262 int lenq = ARRNELEM(query),
1263 lenk = ARRNELEM(key),
1264 i;
1265
1266 result = palloc0_array(bool, lenq);
1267
1268 /* for each query trigram, do a binary search in the key array */
1269 for (i = 0; i < lenq; i++)
1270 {
1271 int lo = 0;
1272 int hi = lenk;
1273
1274 while (lo < hi)
1275 {
1276 int mid = (lo + hi) / 2;
1277 int res = CMPTRGM(ptrq, ptrk + mid);
1278
1279 if (res < 0)
1280 hi = mid;
1281 else if (res > 0)
1282 lo = mid + 1;
1283 else
1284 {
1285 result[i] = true;
1286 break;
1287 }
1288 }
1289 ptrq++;
1290 }
1291
1292 return result;
1293}
1295Datum
1297{
1300 TRGM *trg1,
1301 *trg2;
1302 float4 res;
1303
1306
1307 res = cnt_sml(trg1, trg2, false);
1308
1309 pfree(trg1);
1310 pfree(trg2);
1311 PG_FREE_IF_COPY(in1, 0);
1312 PG_FREE_IF_COPY(in2, 1);
1313
1314 PG_RETURN_FLOAT4(res);
1315}
1330 PG_RETURN_FLOAT4(res);
1331}
1346 PG_RETURN_FLOAT4(res);
1347}
1356 PG_RETURN_FLOAT4(1.0 - res);
1357}
1367}
1383}
1399}
1414 PG_RETURN_FLOAT4(1.0 - res);
1415}
1430 PG_RETURN_FLOAT4(1.0 - res);
1431}
1447}
1463}
1478 PG_RETURN_FLOAT4(1.0 - res);
1479}
1494 PG_RETURN_FLOAT4(1.0 - res);
1495}
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
uint8_t uint8
Definition c.h:556
#define IS_HIGHBIT_SET(ch)
Definition c.h:1172
#define Max(x, y)
Definition c.h:1013
#define VARHDRSZ
Definition c.h:723
#define Assert(condition)
Definition c.h:885
uint32_t uint32
Definition c.h:558
float float4
Definition c.h:655
int errcode(int sqlerrcode)
Definition elog.c:864
int errmsg(const char *fmt,...)
Definition elog.c:1081
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
#define MaxAllocSize
Definition fe_memutils.h:22
#define palloc_array(type, count)
Definition fe_memutils.h:76
#define palloc0_array(type, count)
Definition fe_memutils.h:77
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:310
#define DirectFunctionCall2(func, arg1, arg2)
Definition fmgr.h:686
#define PG_MODULE_MAGIC_EXT(...)
Definition fmgr.h:540
#define PG_GETARG_DATUM(n)
Definition fmgr.h:268
#define PG_FUNCTION_INFO_V1(funcname)
Definition fmgr.h:417
#define PG_GETARG_FLOAT4(n)
Definition fmgr.h:282
#define PG_RETURN_POINTER(x)
Definition fmgr.h:363
#define PG_RETURN_FLOAT4(x)
Definition fmgr.h:368
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
#define PG_RETURN_BOOL(x)
Definition fmgr.h:360
char * str_tolower(const char *buff, size_t nbytes, Oid collid)
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:5063
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4196
void MarkGUCPrefixReserved(const char *className)
Definition guc.c:5148
@ PGC_S_SESSION
Definition guc.h:126
@ PGC_USERSET
Definition guc.h:79
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:713
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:3059
int GetDatabaseEncoding(void)
Definition mbutils.c:1389
int pg_mblen_unbounded(const char *mbstr)
Definition mbutils.c:1137
int pg_mblen_range(const char *mbstr, const char *end)
Definition mbutils.c:1084
int pg_database_encoding_max_length(void)
Definition mbutils.c:1674
void * repalloc(void *pointer, Size size)
Definition mcxt.c:1632
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc(Size size)
Definition mcxt.c:1387
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
Datum lower(PG_FUNCTION_ARGS)
Datum upper(PG_FUNCTION_ARGS)
#define repalloc0_array(pointer, type, oldcount, count)
Definition palloc.h:109
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[DEFAULT_XLOG_SEG_SIZE]
#define snprintf
Definition port.h:260
#define qsort(a, b, c, d)
Definition port.h:495
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
static Datum Float4GetDatum(float4 X)
Definition postgres.h:478
static float4 DatumGetFloat4(Datum X)
Definition postgres.h:461
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
unsigned int Oid
static int fb(int x)
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)
static void word(struct vars *v, int dir, struct state *lp, struct state *rp)
Definition regcomp.c:1476
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:718
#define CALCSML(count, len1, len2)
Definition trgm.h:107
#define ISWORDCHR(c, len)
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:646
uint8 TrgmBound
Definition trgm_op.c:59
Datum strict_word_similarity_commutator_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1448
static int CMPTRGM_UNSIGNED(const void *a, const void *b)
Definition trgm_op.c:203
void _PG_init(void)
Definition trgm_op.c:143
Datum set_limit(PG_FUNCTION_ARGS)
Definition trgm_op.c:232
static int comp_trgm(const void *a, const void *b)
Definition trgm_op.c:283
double strict_word_similarity_threshold
Definition trgm_op.c:29
TRGM * generate_trgm(char *str, int slen)
Definition trgm_op.c:554
static void init_trgm_array(growable_trgm_array *arr, int slen)
Definition trgm_op.c:90
uint32 trgm2int(trgm *ptr)
Definition trgm_op.c:1112
static int CMPTRGM_CHOOSE(const void *a, const void *b)
Definition trgm_op.c:217
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 make_trigrams(growable_trgm_array *dst, char *str, int bytelen)
Definition trgm_op.c:354
Datum word_similarity(PG_FUNCTION_ARGS)
Definition trgm_op.c:1316
Datum strict_word_similarity_dist_commutator_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1480
void compact_trigram(trgm *tptr, char *str, int bytelen)
Definition trgm_op.c:329
bool * trgm_presence_map(TRGM *query, TRGM *key)
Definition trgm_op.c:1255
static float4 calc_word_similarity(char *str1, int slen1, char *str2, int slen2, uint8 flags)
Definition trgm_op.c:814
double word_similarity_threshold
Definition trgm_op.c:28
Datum word_similarity_dist_commutator_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1416
double index_strategy_get_limit(StrategyNumber strategy)
Definition trgm_op.c:254
Datum similarity(PG_FUNCTION_ARGS)
Definition trgm_op.c:1294
static pos_trgm * make_positional_trgm(trgm *trg1, int len1, trgm *trg2, int len2)
Definition trgm_op.c:590
double similarity_threshold
Definition trgm_op.c:27
static int CMPTRGM_SIGNED(const void *a, const void *b)
Definition trgm_op.c:193
static int comp_ptrgm(const void *v1, const void *v2)
Definition trgm_op.c:617
Datum show_trgm(PG_FUNCTION_ARGS)
Definition trgm_op.c:1126
bool trgm_contained_by(TRGM *trg1, TRGM *trg2)
Definition trgm_op.c:1216
static void generate_trgm_only(growable_trgm_array *dst, char *str, int slen, TrgmBound **bounds_p)
Definition trgm_op.c:448
#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:277
#define CMPPCHAR_UNS(a, b, i)
Datum strict_word_similarity_dist_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1464
static char * find_word(char *str, int lenstr, char **endword)
Definition trgm_op.c:293
static const char * get_wildcard_part(const char *str, int lenstr, char *buf, int *bytelen)
Definition trgm_op.c:907
static void enlarge_trgm_array(growable_trgm_array *arr, int needed)
Definition trgm_op.c:122
Datum word_similarity_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1368
Datum word_similarity_commutator_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1384
#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:1044
float4 cnt_sml(TRGM *trg1, TRGM *trg2, bool inexact)
Definition trgm_op.c:1168
Datum similarity_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1358
Datum word_similarity_dist_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1400
Datum strict_word_similarity(PG_FUNCTION_ARGS)
Definition trgm_op.c:1332
Datum similarity_dist(PG_FUNCTION_ARGS)
Definition trgm_op.c:1348
Datum strict_word_similarity_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1432
static Size VARSIZE_ANY_EXHDR(const void *PTR)
Definition varatt.h:472
static char * VARDATA(const void *PTR)
Definition varatt.h:305
static char * VARDATA_ANY(const void *PTR)
Definition varatt.h:486
static void SET_VARSIZE(void *PTR, Size len)
Definition varatt.h:432
const char * name
int pg_encoding_max_length(int encoding)
Definition wchar.c:2235
bool GetDefaultCharSignedness(void)
Definition xlog.c:4661