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);
229#define ST_SORT trigram_qsort_signed
230#define ST_ELEMENT_TYPE_VOID
231#define ST_COMPARE(a, b) CMPTRGM_SIGNED(a, b)
232#define ST_SCOPE static
233#define ST_DEFINE
234#define ST_DECLARE
235#include "lib/sort_template.h"
236
237#define ST_SORT trigram_qsort_unsigned
238#define ST_ELEMENT_TYPE_VOID
239#define ST_COMPARE(a, b) CMPTRGM_UNSIGNED(a, b)
240#define ST_SCOPE static
241#define ST_DEFINE
242#define ST_DECLARE
243#include "lib/sort_template.h"
244
245/* Sort an array of trigrams, handling signedness correctly */
246static void
247trigram_qsort(trgm *array, size_t n)
248{
250 trigram_qsort_signed(array, n, sizeof(trgm));
251 else
252 trigram_qsort_unsigned(array, n, sizeof(trgm));
253}
254
255
256/*
257 * Compare two trigrams for equality. This has the same signature as
258 * comparison functions used for sorting, so that this can be used with
259 * qunique(). This doesn't need separate versions for "signed char" and "
260 * unsigned char" because equality is the same for both.
261 */
262static inline int
263CMPTRGM_EQ(const void *a, const void *b)
264{
265 char *aa = (char *) a;
266 char *bb = (char *) b;
267
268 return aa[0] != bb[0] || aa[1] != bb[1] || aa[2] != bb[2] ? 1 : 0;
269}
270
271/* Deduplicate an array of trigrams */
272static size_t
273trigram_qunique(trgm *array, size_t n)
274{
275 return qunique(array, n, sizeof(trgm), CMPTRGM_EQ);
276}
277
278/*
279 * Deprecated function.
280 * Use "pg_trgm.similarity_threshold" GUC variable instead of this function.
298}
299
300
301/*
302 * Get similarity threshold for given index scan strategy number.
303 */
304double
306{
307 switch (strategy)
308 {
315 default:
316 elog(ERROR, "unrecognized strategy number: %d", strategy);
317 break;
318 }
319
320 return 0.0; /* keep compiler quiet */
321}
322
323/*
324 * Deprecated function.
325 * Use "pg_trgm.similarity_threshold" GUC variable instead of this function.
331}
332
333/*
334 * Finds first word in string, returns pointer to the word,
335 * endword points to the character after word
336 */
337static char *
338find_word(char *str, int lenstr, char **endword)
339{
340 char *beginword = str;
341 const char *endstr = str + lenstr;
342
343 while (beginword < endstr)
344 {
346
348 break;
349 beginword += clen;
350 }
351
352 if (beginword >= endstr)
353 return NULL;
354
356 while (*endword < endstr)
357 {
359
360 if (!ISWORDCHR(*endword, clen))
361 break;
362 *endword += clen;
363 }
364
365 return beginword;
366}
367
368/*
369 * Reduce a trigram (three possibly multi-byte characters) to a trgm,
370 * which is always exactly three bytes. If we have three single-byte
371 * characters, we just use them as-is; otherwise we form a hash value.
372 */
373void
374compact_trigram(trgm *tptr, char *str, int bytelen)
375{
376 if (bytelen == 3)
377 {
378 CPTRGM(tptr, str);
379 }
380 else
381 {
383
387
388 /*
389 * use only 3 upper bytes from crc, hope, it's good enough hashing
390 */
391 CPTRGM(tptr, &crc);
392 }
393}
394
395/*
396 * Adds trigrams from the word in 'str' (already padded if necessary).
397 */
398static void
400{
401 trgm *tptr;
402 char *ptr = str;
403
404 if (bytelen < 3)
405 return;
406
407 /* max number of trigrams = strlen - 2 */
409 tptr = GETARR(dst->datum) + dst->length;
410
412 {
413 while (ptr < str + bytelen - 2)
414 {
415 CPTRGM(tptr, ptr);
416 ptr++;
417 tptr++;
418 }
419 }
420 else
421 {
422 int lenfirst,
423 lenmiddle,
424 lenlast;
425 char *endptr;
426
427 /*
428 * Fast path as long as there are no multibyte characters
429 */
430 if (!IS_HIGHBIT_SET(ptr[0]) && !IS_HIGHBIT_SET(ptr[1]))
431 {
432 while (!IS_HIGHBIT_SET(ptr[2]))
433 {
434 CPTRGM(tptr, ptr);
435 ptr++;
436 tptr++;
437
438 if (ptr == str + bytelen - 2)
439 goto done;
440 }
441
442 lenfirst = 1;
443 lenmiddle = 1;
444 lenlast = pg_mblen_unbounded(ptr + 2);
445 }
446 else
447 {
449 if (ptr + lenfirst >= str + bytelen)
450 goto done;
452 if (ptr + lenfirst + lenmiddle >= str + bytelen)
453 goto done;
455 }
456
457 /*
458 * Slow path to handle any remaining multibyte characters
459 *
460 * As we go, 'ptr' points to the beginning of the current
461 * three-character string and 'endptr' points to just past it.
462 */
463 endptr = ptr + lenfirst + lenmiddle + lenlast;
464 while (endptr <= str + bytelen)
465 {
466 compact_trigram(tptr, ptr, endptr - ptr);
467 tptr++;
468
469 /* Advance to the next character */
470 if (endptr == str + bytelen)
471 break;
472 ptr += lenfirst;
475 lenlast = pg_mblen_unbounded(endptr);
476 endptr += lenlast;
477 }
478 }
479
480done:
481 dst->length = tptr - GETARR(dst->datum);
482 Assert(dst->length <= dst->allocated);
483}
484
485/*
486 * Make array of trigrams without sorting and removing duplicate items.
487 *
488 * dst: where to return the array of trigrams.
489 * str: source string, of length slen bytes.
490 * bounds_p: where to return bounds of trigrams (if needed).
491 */
492static void
494{
495 size_t buflen;
496 char *buf;
497 int bytelen;
498 char *bword,
499 *eword;
501 int bounds_allocated = 0;
502
504
505 /*
506 * If requested, allocate an array for the bounds, with the same size as
507 * the trigram array.
508 */
509 if (bounds_p)
510 {
511 bounds_allocated = dst->allocated;
513 }
514
515 if (slen + LPADDING + RPADDING < 3 || slen == 0)
516 return;
517
518 /*
519 * Allocate a buffer for case-folded, blank-padded words.
520 *
521 * As an initial guess, allocate a buffer large enough to hold the
522 * original string with padding, which is always enough when compiled with
523 * !IGNORECASE. If the case-folding produces a string longer than the
524 * original, we'll grow the buffer.
525 */
526 buflen = (size_t) slen + 4;
527 buf = (char *) palloc(buflen);
528 if (LPADDING > 0)
529 {
530 *buf = ' ';
531 if (LPADDING > 1)
532 *(buf + 1) = ' ';
533 }
534
535 eword = str;
536 while ((bword = find_word(eword, slen - (eword - str), &eword)) != NULL)
537 {
538 int oldlen;
539
540 /* Convert word to lower case before extracting trigrams from it */
541#ifdef IGNORECASE
542 {
543 char *lowered;
544
547
548 /* grow the buffer if necessary */
549 if (bytelen > buflen - 4)
550 {
551 pfree(buf);
552 buflen = (size_t) bytelen + 4;
553 buf = (char *) palloc(buflen);
554 if (LPADDING > 0)
555 {
556 *buf = ' ';
557 if (LPADDING > 1)
558 *(buf + 1) = ' ';
559 }
560 }
562 pfree(lowered);
563 }
564#else
565 bytelen = eword - bword;
567#endif
568
569 buf[LPADDING + bytelen] = ' ';
570 buf[LPADDING + bytelen + 1] = ' ';
571
572 /* Calculate trigrams marking their bounds if needed */
573 oldlen = dst->length;
575 if (bounds)
576 {
577 if (bounds_allocated < dst->length)
578 {
580 bounds_allocated = dst->allocated;
581 }
582
584 bounds[dst->length - 1] |= TRGM_BOUND_RIGHT;
585 }
586 }
587
588 pfree(buf);
589}
590
591/*
592 * Make array of trigrams with sorting and removing duplicate items.
593 *
594 * str: source string, of length slen bytes.
595 *
596 * Returns the sorted array of unique trigrams.
597 */
598TRGM *
599generate_trgm(char *str, int slen)
600{
601 TRGM *trg;
603 int len;
604
606 len = arr.length;
607 trg = arr.datum;
608 trg->flag = ARRKEY;
609
610 /*
611 * Make trigrams unique.
612 */
613 if (len > 1)
614 {
615 trigram_qsort(GETARR(trg), len);
616 len = trigram_qunique(GETARR(trg), len);
617 }
618
620
621 return trg;
622}
623
624/*
625 * Make array of positional trigrams from two trigram arrays trg1 and trg2.
626 *
627 * trg1: trigram array of search pattern, of length len1. trg1 is required
628 * word which positions don't matter and replaced with -1.
629 * trg2: trigram array of text, of length len2. trg2 is haystack where we
630 * search and have to store its positions.
631 *
632 * Returns concatenated trigram array.
633 */
634static pos_trgm *
635make_positional_trgm(trgm *trg1, int len1, trgm *trg2, int len2)
636{
638 int i,
639 len = len1 + len2;
640
642
643 for (i = 0; i < len1; i++)
644 {
645 memcpy(&result[i].trg, &trg1[i], sizeof(trgm));
646 result[i].index = -1;
647 }
648
649 for (i = 0; i < len2; i++)
650 {
651 memcpy(&result[i + len1].trg, &trg2[i], sizeof(trgm));
652 result[i + len1].index = i;
653 }
654
655 return result;
656}
657
658/*
659 * Compare position trigrams: compare trigrams first and position second.
660 */
661static int
662comp_ptrgm(const void *v1, const void *v2)
663{
664 const pos_trgm *p1 = (const pos_trgm *) v1;
665 const pos_trgm *p2 = (const pos_trgm *) v2;
666 int cmp;
667
668 cmp = CMPTRGM(p1->trg, p2->trg);
669 if (cmp != 0)
670 return cmp;
671
672 return pg_cmp_s32(p1->index, p2->index);
673}
674
675/*
676 * Iterative search function which calculates maximum similarity with word in
677 * the string. Maximum similarity is only calculated only if the flag
678 * WORD_SIMILARITY_CHECK_ONLY isn't set.
679 *
680 * trg2indexes: array which stores indexes of the array "found".
681 * found: array which stores true of false values.
682 * ulen1: count of unique trigrams of array "trg1".
683 * len2: length of array "trg2" and array "trg2indexes".
684 * len: length of the array "found".
685 * flags: set of boolean flags parameterizing similarity calculation.
686 * bounds: whether each trigram is left/right bound of word.
687 *
688 * Returns word similarity.
689 */
690static float4
692 bool *found,
693 int ulen1,
694 int len2,
695 int len,
696 uint8 flags,
698{
699 int *lastpos,
700 i,
701 ulen2 = 0,
702 count = 0,
703 upper = -1,
704 lower;
706 smlr_max = 0.0f;
707 double threshold;
708
709 Assert(bounds || !(flags & WORD_SIMILARITY_STRICT));
710
711 /* Select appropriate threshold */
715
716 /*
717 * Consider first trigram as initial lower bound for strict word
718 * similarity, or initialize it later with first trigram present for plain
719 * word similarity.
720 */
721 lower = (flags & WORD_SIMILARITY_STRICT) ? 0 : -1;
722
723 /* Memorise last position of each trigram */
724 lastpos = palloc_array(int, len);
725 memset(lastpos, -1, sizeof(int) * len);
726
727 for (i = 0; i < len2; i++)
728 {
729 int trgindex;
730
732
733 /* Get index of next trigram */
735
736 /* Update last position of this trigram */
737 if (lower >= 0 || found[trgindex])
738 {
739 if (lastpos[trgindex] < 0)
740 {
741 ulen2++;
742 if (found[trgindex])
743 count++;
744 }
745 lastpos[trgindex] = i;
746 }
747
748 /*
749 * Adjust upper bound if trigram is upper bound of word for strict
750 * word similarity, or if trigram is present in required substring for
751 * plain word similarity
752 */
754 : found[trgindex])
755 {
756 int prev_lower,
757 tmp_ulen2,
758 tmp_lower,
759 tmp_count;
760
761 upper = i;
762 if (lower == -1)
763 {
764 lower = i;
765 ulen2 = 1;
766 }
767
768 smlr_cur = CALCSML(count, ulen1, ulen2);
769
770 /* Also try to adjust lower bound for greater similarity */
771 tmp_count = count;
775 {
776 float smlr_tmp;
777 int tmp_trgindex;
778
779 /*
780 * Adjust lower bound only if trigram is lower bound of word
781 * for strict word similarity, or consider every trigram as
782 * lower bound for plain word similarity.
783 */
784 if (!(flags & WORD_SIMILARITY_STRICT)
786 {
788 if (smlr_tmp > smlr_cur)
789 {
793 count = tmp_count;
794 }
795
796 /*
797 * If we only check that word similarity is greater than
798 * threshold we do not need to calculate a maximum
799 * similarity.
800 */
801 if ((flags & WORD_SIMILARITY_CHECK_ONLY)
802 && smlr_cur >= threshold)
803 break;
804 }
805
808 {
809 tmp_ulen2--;
810 if (found[tmp_trgindex])
811 tmp_count--;
812 }
813 }
814
816
817 /*
818 * if we only check that word similarity is greater than threshold
819 * we do not need to calculate a maximum similarity.
820 */
822 break;
823
825 {
826 int tmp_trgindex;
827
830 lastpos[tmp_trgindex] = -1;
831 }
832 }
833 }
834
835 pfree(lastpos);
836
837 return smlr_max;
838}
839
840/*
841 * Calculate word similarity.
842 * This function prepare two arrays: "trg2indexes" and "found". Then this arrays
843 * are used to calculate word similarity using iterate_word_similarity().
844 *
845 * "trg2indexes" is array which stores indexes of the array "found".
846 * In other words:
847 * trg2indexes[j] = i;
848 * found[i] = true (or false);
849 * If found[i] == true then there is trigram trg2[j] in array "trg1".
850 * If found[i] == false then there is not trigram trg2[j] in array "trg1".
851 *
852 * str1: search pattern string, of length slen1 bytes.
853 * str2: text in which we are looking for a word, of length slen2 bytes.
854 * flags: set of boolean flags parameterizing similarity calculation.
855 *
856 * Returns word similarity.
857 */
858static float4
859calc_word_similarity(char *str1, int slen1, char *str2, int slen2,
860 uint8 flags)
861{
862 bool *found;
863 pos_trgm *ptrg;
866 int len1,
867 len2,
868 len,
869 i,
870 j,
871 ulen1;
872 int *trg2indexes;
875
876 /* Make positional trigrams */
877
879 len1 = trg1.length;
881 len2 = trg2.length;
882
883 ptrg = make_positional_trgm(GETARR(trg1.datum), len1, GETARR(trg2.datum), len2);
884 len = len1 + len2;
885 qsort(ptrg, len, sizeof(pos_trgm), comp_ptrgm);
886
887 pfree(trg1.datum);
888 pfree(trg2.datum);
889
890 /*
891 * Merge positional trigrams array: enumerate each trigram and find its
892 * presence in required word.
893 */
894 trg2indexes = palloc_array(int, len2);
895 found = palloc0_array(bool, len);
896
897 ulen1 = 0;
898 j = 0;
899 for (i = 0; i < len; i++)
900 {
901 if (i > 0)
902 {
903 int cmp = CMPTRGM(ptrg[i - 1].trg, ptrg[i].trg);
904
905 if (cmp != 0)
906 {
907 if (found[j])
908 ulen1++;
909 j++;
910 }
911 }
912
913 if (ptrg[i].index >= 0)
914 {
915 trg2indexes[ptrg[i].index] = j;
916 }
917 else
918 {
919 found[j] = true;
920 }
921 }
922 if (found[j])
923 ulen1++;
924
925 /* Run iterative procedure to find maximum similarity with word */
927 flags, bounds);
928
930 pfree(found);
931 pfree(ptrg);
932
933 return result;
934}
935
936
937/*
938 * Extract the next non-wildcard part of a search string, i.e. a word bounded
939 * by '_' or '%' meta-characters, non-word characters or string end.
940 *
941 * str: source string, of length lenstr bytes (need not be null-terminated)
942 * buf: where to return the substring (must be long enough)
943 * *bytelen: receives byte length of the found substring
944 *
945 * Returns pointer to end+1 of the found substring in the source string.
946 * Returns NULL if no word found (in which case buf, bytelen is not set)
947 *
948 * If the found word is bounded by non-word characters or string boundaries
949 * then this function will include corresponding padding spaces into buf.
950 */
951static const char *
952get_wildcard_part(const char *str, int lenstr,
953 char *buf, int *bytelen)
954{
955 const char *beginword = str;
956 const char *endword;
957 const char *endstr = str + lenstr;
958 char *s = buf;
959 bool in_leading_wildcard_meta = false;
960 bool in_trailing_wildcard_meta = false;
961 bool in_escape = false;
962 int clen;
963
964 /*
965 * Find the first word character, remembering whether preceding character
966 * was wildcard meta-character. Note that the in_escape state persists
967 * from this loop to the next one, since we may exit at a word character
968 * that is in_escape.
969 */
970 while (beginword < endstr)
971 {
973
974 if (in_escape)
975 {
977 break;
978 in_escape = false;
980 }
981 else
982 {
984 in_escape = true;
985 else if (ISWILDCARDCHAR(beginword))
987 else if (ISWORDCHR(beginword, clen))
988 break;
989 else
991 }
992 beginword += clen;
993 }
994
995 /*
996 * Handle string end.
997 */
998 if (beginword - str >= lenstr)
999 return NULL;
1000
1001 /*
1002 * Add left padding spaces if preceding character wasn't wildcard
1003 * meta-character.
1004 */
1006 {
1007 if (LPADDING > 0)
1008 {
1009 *s++ = ' ';
1010 if (LPADDING > 1)
1011 *s++ = ' ';
1012 }
1013 }
1014
1015 /*
1016 * Copy data into buf until wildcard meta-character, non-word character or
1017 * string boundary. Strip escapes during copy.
1018 */
1020 while (endword < endstr)
1021 {
1023 if (in_escape)
1024 {
1025 if (ISWORDCHR(endword, clen))
1026 {
1027 memcpy(s, endword, clen);
1028 s += clen;
1029 }
1030 else
1031 {
1032 /*
1033 * Back up endword to the escape character when stopping at an
1034 * escaped char, so that subsequent get_wildcard_part will
1035 * restart from the escape character. We assume here that
1036 * escape chars are single-byte.
1037 */
1038 endword--;
1039 break;
1040 }
1041 in_escape = false;
1042 }
1043 else
1044 {
1045 if (ISESCAPECHAR(endword))
1046 in_escape = true;
1047 else if (ISWILDCARDCHAR(endword))
1048 {
1050 break;
1051 }
1052 else if (ISWORDCHR(endword, clen))
1053 {
1054 memcpy(s, endword, clen);
1055 s += clen;
1056 }
1057 else
1058 break;
1059 }
1060 endword += clen;
1061 }
1062
1063 /*
1064 * Add right padding spaces if next character isn't wildcard
1065 * meta-character.
1066 */
1068 {
1069 if (RPADDING > 0)
1070 {
1071 *s++ = ' ';
1072 if (RPADDING > 1)
1073 *s++ = ' ';
1074 }
1075 }
1076
1077 *bytelen = s - buf;
1078 return endword;
1079}
1080
1081/*
1082 * Generates trigrams for wildcard search string.
1083 *
1084 * Returns array of trigrams that must occur in any string that matches the
1085 * wildcard string. For example, given pattern "a%bcd%" the trigrams
1086 * " a", "bcd" would be extracted.
1088TRGM *
1089generate_wildcard_trgm(const char *str, int slen)
1090{
1091 TRGM *trg;
1093 char *buf;
1094 int len,
1095 bytelen;
1096 const char *eword;
1097
1098 if (slen + LPADDING + RPADDING < 3 || slen == 0)
1099 {
1100 trg = (TRGM *) palloc(TRGMHDRSIZE);
1101 trg->flag = ARRKEY;
1103 return trg;
1104 }
1105
1106 init_trgm_array(&arr, slen);
1107
1108 /* Allocate a buffer for blank-padded, but not yet case-folded, words */
1109 buf = palloc_array(char, slen + 4);
1110
1111 /*
1112 * Extract trigrams from each substring extracted by get_wildcard_part.
1113 */
1114 eword = str;
1115 while ((eword = get_wildcard_part(eword, slen - (eword - str),
1116 buf, &bytelen)) != NULL)
1117 {
1118 char *word;
1119
1120#ifdef IGNORECASE
1122 bytelen = strlen(word);
1123#else
1124 word = buf;
1125#endif
1126
1127 /*
1128 * count trigrams
1129 */
1130 make_trigrams(&arr, word, bytelen);
1131
1132#ifdef IGNORECASE
1133 pfree(word);
1134#endif
1135 }
1136
1137 pfree(buf);
1138
1139 /*
1140 * Make trigrams unique.
1141 */
1142 trg = arr.datum;
1143 len = arr.length;
1144 if (len > 1)
1145 {
1146 trigram_qsort(GETARR(trg), len);
1147 len = trigram_qunique(GETARR(trg), len);
1148 }
1149
1150 trg->flag = ARRKEY;
1152
1153 return trg;
1154}
1156uint32
1157trgm2int(trgm *ptr)
1158{
1159 uint32 val = 0;
1160
1161 val |= *(((unsigned char *) ptr));
1162 val <<= 8;
1163 val |= *(((unsigned char *) ptr) + 1);
1164 val <<= 8;
1165 val |= *(((unsigned char *) ptr) + 2);
1166
1167 return val;
1168}
1170Datum
1172{
1173 text *in = PG_GETARG_TEXT_PP(0);
1174 TRGM *trg;
1175 Datum *d;
1176 ArrayType *a;
1177 trgm *ptr;
1178 int i;
1179
1181 d = palloc_array(Datum, 1 + ARRNELEM(trg));
1182
1183 for (i = 0, ptr = GETARR(trg); i < ARRNELEM(trg); i++, ptr++)
1184 {
1185 text *item = (text *) palloc(VARHDRSZ + Max(12, pg_database_encoding_max_length() * 3));
1186
1188 {
1189 snprintf(VARDATA(item), 12, "0x%06x", trgm2int(ptr));
1190 SET_VARSIZE(item, VARHDRSZ + strlen(VARDATA(item)));
1191 }
1192 else
1193 {
1194 SET_VARSIZE(item, VARHDRSZ + 3);
1195 CPTRGM(VARDATA(item), ptr);
1196 }
1197 d[i] = PointerGetDatum(item);
1198 }
1199
1201
1202 for (i = 0; i < ARRNELEM(trg); i++)
1203 pfree(DatumGetPointer(d[i]));
1204
1205 pfree(d);
1206 pfree(trg);
1207 PG_FREE_IF_COPY(in, 0);
1208
1210}
1212float4
1213cnt_sml(TRGM *trg1, TRGM *trg2, bool inexact)
1214{
1215 trgm *ptr1,
1216 *ptr2;
1217 int count = 0;
1218 int len1,
1219 len2;
1220
1221 ptr1 = GETARR(trg1);
1222 ptr2 = GETARR(trg2);
1223
1224 len1 = ARRNELEM(trg1);
1225 len2 = ARRNELEM(trg2);
1226
1227 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
1228 if (len1 <= 0 || len2 <= 0)
1229 return (float4) 0.0;
1230
1231 while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
1232 {
1233 int res = CMPTRGM(ptr1, ptr2);
1234
1235 if (res < 0)
1236 ptr1++;
1237 else if (res > 0)
1238 ptr2++;
1239 else
1240 {
1241 ptr1++;
1242 ptr2++;
1243 count++;
1244 }
1245 }
1246
1247 /*
1248 * If inexact then len2 is equal to count, because we don't know actual
1249 * length of second string in inexact search and we can assume that count
1250 * is a lower bound of len2.
1251 */
1252 return CALCSML(count, len1, inexact ? count : len2);
1253}
1254
1255
1256/*
1257 * Returns whether trg2 contains all trigrams in trg1.
1258 * This relies on the trigram arrays being sorted.
1260bool
1262{
1263 trgm *ptr1,
1264 *ptr2;
1265 int len1,
1266 len2;
1267
1268 ptr1 = GETARR(trg1);
1269 ptr2 = GETARR(trg2);
1270
1271 len1 = ARRNELEM(trg1);
1272 len2 = ARRNELEM(trg2);
1273
1274 while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
1275 {
1276 int res = CMPTRGM(ptr1, ptr2);
1277
1278 if (res < 0)
1279 return false;
1280 else if (res > 0)
1281 ptr2++;
1282 else
1283 {
1284 ptr1++;
1285 ptr2++;
1286 }
1287 }
1288 if (ptr1 - GETARR(trg1) < len1)
1289 return false;
1290 else
1291 return true;
1292}
1293
1294/*
1295 * Return a palloc'd boolean array showing, for each trigram in "query",
1296 * whether it is present in the trigram array "key".
1297 * This relies on the "key" array being sorted, but "query" need not be.
1299bool *
1300trgm_presence_map(TRGM *query, TRGM *key)
1301{
1302 bool *result;
1303 trgm *ptrq = GETARR(query),
1304 *ptrk = GETARR(key);
1305 int lenq = ARRNELEM(query),
1306 lenk = ARRNELEM(key),
1307 i;
1308
1309 result = palloc0_array(bool, lenq);
1310
1311 /* for each query trigram, do a binary search in the key array */
1312 for (i = 0; i < lenq; i++)
1313 {
1314 int lo = 0;
1315 int hi = lenk;
1316
1317 while (lo < hi)
1318 {
1319 int mid = (lo + hi) / 2;
1320 int res = CMPTRGM(ptrq, ptrk + mid);
1321
1322 if (res < 0)
1323 hi = mid;
1324 else if (res > 0)
1325 lo = mid + 1;
1326 else
1327 {
1328 result[i] = true;
1329 break;
1330 }
1331 }
1332 ptrq++;
1333 }
1334
1335 return result;
1336}
1338Datum
1340{
1343 TRGM *trg1,
1344 *trg2;
1345 float4 res;
1346
1349
1350 res = cnt_sml(trg1, trg2, false);
1351
1352 pfree(trg1);
1353 pfree(trg2);
1354 PG_FREE_IF_COPY(in1, 0);
1355 PG_FREE_IF_COPY(in2, 1);
1356
1357 PG_RETURN_FLOAT4(res);
1358}
1373 PG_RETURN_FLOAT4(res);
1374}
1389 PG_RETURN_FLOAT4(res);
1390}
1399 PG_RETURN_FLOAT4(1.0 - res);
1400}
1410}
1426}
1442}
1457 PG_RETURN_FLOAT4(1.0 - res);
1458}
1473 PG_RETURN_FLOAT4(1.0 - res);
1474}
1490}
1506}
1521 PG_RETURN_FLOAT4(1.0 - res);
1522}
1537 PG_RETURN_FLOAT4(1.0 - res);
1538}
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
uint8_t uint8
Definition c.h:622
#define IS_HIGHBIT_SET(ch)
Definition c.h:1244
#define Max(x, y)
Definition c.h:1085
#define VARHDRSZ
Definition c.h:781
#define Assert(condition)
Definition c.h:943
uint32_t uint32
Definition c.h:624
float float4
Definition c.h:713
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
int errcode(int sqlerrcode)
Definition elog.c:875
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
#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:1764
#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:5101
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4234
void MarkGUCPrefixReserved(const char *className)
Definition guc.c:5186
@ 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:3102
int GetDatabaseEncoding(void)
Definition mbutils.c:1388
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:1672
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:125
static char * errmsg
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 Float4GetDatum(float4 X)
Definition postgres.h:481
static float4 DatumGetFloat4(Datum X)
Definition postgres.h:464
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
#define PointerGetDatum(X)
Definition postgres.h:354
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:776
#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:689
uint8 TrgmBound
Definition trgm_op.c:59
Datum strict_word_similarity_commutator_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1491
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:281
static void trigram_qsort(trgm *array, size_t n)
Definition trgm_op.c:245
double strict_word_similarity_threshold
Definition trgm_op.c:29
TRGM * generate_trgm(char *str, int slen)
Definition trgm_op.c:597
static void init_trgm_array(growable_trgm_array *arr, int slen)
Definition trgm_op.c:90
uint32 trgm2int(trgm *ptr)
Definition trgm_op.c:1155
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:397
Datum word_similarity(PG_FUNCTION_ARGS)
Definition trgm_op.c:1359
Datum strict_word_similarity_dist_commutator_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1523
void compact_trigram(trgm *tptr, char *str, int bytelen)
Definition trgm_op.c:372
bool * trgm_presence_map(TRGM *query, TRGM *key)
Definition trgm_op.c:1298
static float4 calc_word_similarity(char *str1, int slen1, char *str2, int slen2, uint8 flags)
Definition trgm_op.c:857
double word_similarity_threshold
Definition trgm_op.c:28
Datum word_similarity_dist_commutator_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1459
double index_strategy_get_limit(StrategyNumber strategy)
Definition trgm_op.c:303
Datum similarity(PG_FUNCTION_ARGS)
Definition trgm_op.c:1337
static pos_trgm * make_positional_trgm(trgm *trg1, int len1, trgm *trg2, int len2)
Definition trgm_op.c:633
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:660
Datum show_trgm(PG_FUNCTION_ARGS)
Definition trgm_op.c:1169
bool trgm_contained_by(TRGM *trg1, TRGM *trg2)
Definition trgm_op.c:1259
static void generate_trgm_only(growable_trgm_array *dst, char *str, int slen, TrgmBound **bounds_p)
Definition trgm_op.c:491
#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:326
#define CMPPCHAR_UNS(a, b, i)
Datum strict_word_similarity_dist_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1507
static char * find_word(char *str, int lenstr, char **endword)
Definition trgm_op.c:336
static const char * get_wildcard_part(const char *str, int lenstr, char *buf, int *bytelen)
Definition trgm_op.c:950
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:1411
static size_t trigram_qunique(trgm *array, size_t n)
Definition trgm_op.c:271
Datum word_similarity_commutator_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1427
#define WORD_SIMILARITY_STRICT
Definition trgm_op.c:65
static int CMPTRGM_EQ(const void *a, const void *b)
Definition trgm_op.c:261
#define TRGM_BOUND_LEFT
Definition trgm_op.c:60
TRGM * generate_wildcard_trgm(const char *str, int slen)
Definition trgm_op.c:1087
float4 cnt_sml(TRGM *trg1, TRGM *trg2, bool inexact)
Definition trgm_op.c:1211
Datum similarity_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1401
Datum word_similarity_dist_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1443
Datum strict_word_similarity(PG_FUNCTION_ARGS)
Definition trgm_op.c:1375
Datum similarity_dist(PG_FUNCTION_ARGS)
Definition trgm_op.c:1391
Datum strict_word_similarity_op(PG_FUNCTION_ARGS)
Definition trgm_op.c:1475
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:2012
bool GetDefaultCharSignedness(void)
Definition xlog.c:4991