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