2 * contrib/pg_trgm/trgm_op.c
10 #include "catalog/pg_type.h"
11 #include "tsearch/ts_locale.h"
12 #include "utils/array.h"
17 float4 trgm_limit = 0.3f;
19 PG_FUNCTION_INFO_V1(set_limit);
20 Datum set_limit(PG_FUNCTION_ARGS);
22 PG_FUNCTION_INFO_V1(show_limit);
23 Datum show_limit(PG_FUNCTION_ARGS);
25 PG_FUNCTION_INFO_V1(show_trgm);
26 Datum show_trgm(PG_FUNCTION_ARGS);
28 PG_FUNCTION_INFO_V1(similarity);
29 Datum similarity(PG_FUNCTION_ARGS);
31 PG_FUNCTION_INFO_V1(similarity_dist);
32 Datum similarity_dist(PG_FUNCTION_ARGS);
34 PG_FUNCTION_INFO_V1(similarity_op);
35 Datum similarity_op(PG_FUNCTION_ARGS);
39 set_limit(PG_FUNCTION_ARGS)
41 float4 nlimit = PG_GETARG_FLOAT4(0);
43 if (nlimit < 0 || nlimit > 1.0)
44 elog(ERROR, "wrong limit, should be between 0 and 1");
46 PG_RETURN_FLOAT4(trgm_limit);
50 show_limit(PG_FUNCTION_ARGS)
52 PG_RETURN_FLOAT4(trgm_limit);
56 comp_trgm(const void *a, const void *b)
62 unique_array(trgm *a, int len)
69 if (CMPTRGM(tmp, curend))
78 return curend + 1 - a;
82 #define iswordchr(c) (t_isalpha(c) || t_isdigit(c))
84 #define iswordchr(c) (!t_isspace(c))
88 * Finds first word in string, returns pointer to the word,
89 * endword points to the character after word
92 find_word(char *str, int lenstr, char **endword, int *charlen)
94 char *beginword = str;
96 while (beginword - str < lenstr && !iswordchr(beginword))
97 beginword += pg_mblen(beginword);
99 if (beginword - str >= lenstr)
102 *endword = beginword;
104 while (*endword - str < lenstr && iswordchr(*endword))
106 *endword += pg_mblen(*endword);
113 #ifdef USE_WIDE_UPPER_LOWER
115 cnt_trigram(trgm *tptr, char *str, int bytelen)
126 COMP_CRC32(crc, str, bytelen);
130 * use only 3 upper bytes from crc, hope, it's good enough hashing
138 * Adds trigrams from words (already padded).
141 make_trigrams(trgm *tptr, char *str, int bytelen, int charlen)
148 #ifdef USE_WIDE_UPPER_LOWER
149 if (pg_database_encoding_max_length() > 1)
151 int lenfirst = pg_mblen(str),
152 lenmiddle = pg_mblen(str + lenfirst),
153 lenlast = pg_mblen(str + lenfirst + lenmiddle);
155 while ((ptr - str) + lenfirst + lenmiddle + lenlast <= bytelen)
157 cnt_trigram(tptr, ptr, lenfirst + lenmiddle + lenlast);
162 lenfirst = lenmiddle;
164 lenlast = pg_mblen(ptr + lenfirst + lenmiddle);
170 Assert(bytelen == charlen);
172 while (ptr - str < bytelen - 2 /* number of trigrams = strlen - 2 */ )
184 generate_trgm(char *str, int slen)
195 trg = (TRGM *) palloc(TRGMHDRSIZE + sizeof(trgm) * (slen / 2 + 1) *3);
197 SET_VARSIZE(trg, TRGMHDRSIZE);
199 if (slen + LPADDING + RPADDING < 3 || slen == 0)
204 buf = palloc(sizeof(char) * (slen + 4));
214 while ((bword = find_word(eword, slen - (eword - str), &eword, &charlen)) != NULL)
217 bword = lowerstr_with_len(bword, eword - bword);
218 bytelen = strlen(bword);
220 bytelen = eword - bword;
223 memcpy(buf + LPADDING, bword, bytelen);
228 buf[LPADDING + bytelen] = ' ';
229 buf[LPADDING + bytelen + 1] = ' ';
234 tptr = make_trigrams(tptr, buf, bytelen + LPADDING + RPADDING,
235 charlen + LPADDING + RPADDING);
240 if ((len = tptr - GETARR(trg)) == 0)
245 qsort((void *) GETARR(trg), len, sizeof(trgm), comp_trgm);
246 len = unique_array(GETARR(trg), len);
249 SET_VARSIZE(trg, CALCGTSIZE(ARRKEY, len));
255 * Extract the next non-wildcard part of a search string, ie, a word bounded
256 * by '_' or '%' meta-characters, non-word characters or string end.
258 * str: source string, of length lenstr bytes (need not be null-terminated)
259 * buf: where to return the substring (must be long enough)
260 * *bytelen: receives byte length of the found substring
261 * *charlen: receives character length of the found substring
263 * Returns pointer to end+1 of the found substring in the source string.
264 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
266 * If the found word is bounded by non-word characters or string boundaries
267 * then this function will include corresponding padding spaces into buf.
270 get_wildcard_part(const char *str, int lenstr,
271 char *buf, int *bytelen, int *charlen)
273 const char *beginword = str;
276 bool in_wildcard_meta = false;
277 bool in_escape = false;
281 * Find the first word character remembering whether last character was
282 * wildcard meta-character.
284 while (beginword - str < lenstr)
289 in_wildcard_meta = false;
290 if (iswordchr(beginword))
295 if (ISESCAPECHAR(beginword))
297 else if (ISWILDCARDCHAR(beginword))
298 in_wildcard_meta = true;
299 else if (iswordchr(beginword))
302 in_wildcard_meta = false;
304 beginword += pg_mblen(beginword);
310 if (beginword - str >= lenstr)
314 * Add left padding spaces if last character wasn't wildcard
318 if (!in_wildcard_meta)
333 * Copy data into buf until wildcard meta-character, non-word character or
334 * string boundary. Strip escapes during copy.
337 in_wildcard_meta = false;
339 while (endword - str < lenstr)
341 clen = pg_mblen(endword);
345 in_wildcard_meta = false;
346 if (iswordchr(endword))
348 memcpy(s, endword, clen);
357 if (ISESCAPECHAR(endword))
359 else if (ISWILDCARDCHAR(endword))
361 in_wildcard_meta = true;
364 else if (iswordchr(endword))
366 memcpy(s, endword, clen);
372 in_wildcard_meta = false;
380 * Add right padding spaces if last character wasn't wildcard
383 if (!in_wildcard_meta)
402 * Generates trigrams for wildcard search string.
404 * Returns array of trigrams that must occur in any string that matches the
405 * wildcard string. For example, given pattern "a%bcd%" the trigrams
406 * " a", "bcd" would be extracted.
409 generate_wildcard_trgm(const char *str, int slen)
420 trg = (TRGM *) palloc(TRGMHDRSIZE + sizeof(trgm) * (slen / 2 + 1) * 3);
422 SET_VARSIZE(trg, TRGMHDRSIZE);
424 if (slen + LPADDING + RPADDING < 3 || slen == 0)
429 buf = palloc(sizeof(char) * (slen + 4));
432 * Extract trigrams from each substring extracted by get_wildcard_part.
435 while ((eword = get_wildcard_part(eword, slen - (eword - str),
436 buf, &bytelen, &charlen)) != NULL)
439 buf2 = lowerstr_with_len(buf, bytelen);
440 bytelen = strlen(buf2);
448 tptr = make_trigrams(tptr, buf2, bytelen, charlen);
456 if ((len = tptr - GETARR(trg)) == 0)
460 * Make trigrams unique.
464 qsort((void *) GETARR(trg), len, sizeof(trgm), comp_trgm);
465 len = unique_array(GETARR(trg), len);
468 SET_VARSIZE(trg, CALCGTSIZE(ARRKEY, len));
478 val |= *(((unsigned char *) ptr));
480 val |= *(((unsigned char *) ptr) + 1);
482 val |= *(((unsigned char *) ptr) + 2);
488 show_trgm(PG_FUNCTION_ARGS)
490 text *in = PG_GETARG_TEXT_P(0);
497 trg = generate_trgm(VARDATA(in), VARSIZE(in) - VARHDRSZ);
498 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(trg)));
500 for (i = 0, ptr = GETARR(trg); i < ARRNELEM(trg); i++, ptr++)
502 text *item = (text *) palloc(VARHDRSZ + Max(12, pg_database_encoding_max_length() * 3));
504 if (pg_database_encoding_max_length() > 1 && !ISPRINTABLETRGM(ptr))
506 snprintf(VARDATA(item), 12, "0x%06x", trgm2int(ptr));
507 SET_VARSIZE(item, VARHDRSZ + strlen(VARDATA(item)));
511 SET_VARSIZE(item, VARHDRSZ + 3);
512 CPTRGM(VARDATA(item), ptr);
514 d[i] = PointerGetDatum(item);
526 for (i = 0; i < ARRNELEM(trg); i++)
527 pfree(DatumGetPointer(d[i]));
531 PG_FREE_IF_COPY(in, 0);
533 PG_RETURN_POINTER(a);
537 cnt_sml(TRGM *trg1, TRGM *trg2)
548 len1 = ARRNELEM(trg1);
549 len2 = ARRNELEM(trg2);
551 while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
553 int res = CMPTRGM(ptr1, ptr2);
568 return ((((float4) count) / ((float4) (len1 + len2 - count))));
570 return (((float) count) / ((float) ((len1 > len2) ? len1 : len2)));
576 * Returns whether trg2 contains all trigrams in trg1.
577 * This relies on the trigram arrays being sorted.
580 trgm_contained_by(TRGM *trg1, TRGM *trg2)
590 len1 = ARRNELEM(trg1);
591 len2 = ARRNELEM(trg2);
593 while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
595 int res = CMPTRGM(ptr1, ptr2);
607 if (ptr1 - GETARR(trg1) < len1)
614 similarity(PG_FUNCTION_ARGS)
616 text *in1 = PG_GETARG_TEXT_P(0);
617 text *in2 = PG_GETARG_TEXT_P(1);
622 trg1 = generate_trgm(VARDATA(in1), VARSIZE(in1) - VARHDRSZ);
623 trg2 = generate_trgm(VARDATA(in2), VARSIZE(in2) - VARHDRSZ);
625 res = cnt_sml(trg1, trg2);
629 PG_FREE_IF_COPY(in1, 0);
630 PG_FREE_IF_COPY(in2, 1);
632 PG_RETURN_FLOAT4(res);
636 similarity_dist(PG_FUNCTION_ARGS)
638 float4 res = DatumGetFloat4(DirectFunctionCall2(similarity,
640 PG_GETARG_DATUM(1)));
641 PG_RETURN_FLOAT4(1.0 - res);
645 similarity_op(PG_FUNCTION_ARGS)
647 float4 res = DatumGetFloat4(DirectFunctionCall2(similarity,
649 PG_GETARG_DATUM(1)));
651 PG_RETURN_BOOL(res >= trgm_limit);