1 /*-------------------------------------------------------------------------
3 * Portions Copyright (c) 2004-2012, PostgreSQL Global Development Group
4 * Portions Copyright (c) 2013-2015, NTT DATA Corporation
8 * Support full text search using bigrams.
9 * Author: NTT DATA Corporation
11 *-------------------------------------------------------------------------
19 #include "catalog/pg_type.h"
20 #include "tsearch/ts_locale.h"
21 #include "utils/array.h"
25 /* Last update date of pg_bigm */
26 #define BIGM_LAST_UPDATE "2013.11.22"
29 bool bigm_enable_recheck = false;
30 int bigm_gin_key_limit = 0;
31 double bigm_similarity_limit = 0.3;
32 char *bigm_last_update = NULL;
34 PG_FUNCTION_INFO_V1(show_bigm);
35 PG_FUNCTION_INFO_V1(bigmtextcmp);
36 PG_FUNCTION_INFO_V1(likequery);
37 PG_FUNCTION_INFO_V1(bigm_similarity);
38 PG_FUNCTION_INFO_V1(bigm_similarity_op);
41 * The function prototypes are created as a part of PG_FUNCTION_INFO_V1
42 * macro since 9.4, and hence the declaration of the function prototypes
43 * here is necessary only for 9.3 or before.
45 #if PG_VERSION_NUM < 90400
46 Datum show_bigm(PG_FUNCTION_ARGS);
47 Datum bigmtextcmp(PG_FUNCTION_ARGS);
48 Datum likequery(PG_FUNCTION_ARGS);
49 Datum bigm_similarity(PG_FUNCTION_ARGS);
50 Datum bigm_similarity_op(PG_FUNCTION_ARGS);
59 /* Define custom GUC variables */
60 DefineCustomBoolVariable("pg_bigm.enable_recheck",
61 "Recheck that heap tuples fetched from index "
72 DefineCustomIntVariable("pg_bigm.gin_key_limit",
73 "Sets the maximum number of bi-gram keys allowed to "
74 "use for GIN index search.",
75 "Zero means no limit.",
85 DefineCustomRealVariable("pg_bigm.similarity_limit",
86 "Sets the similarity threshold used by the "
89 &bigm_similarity_limit,
98 /* Can't be set in postgresql.conf */
99 DefineCustomStringVariable("pg_bigm.last_update",
100 "Shows the last update date of pg_bigm.",
105 GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
110 EmitWarningsOnPlaceholders("pg_bigm");
119 comp_bigm(const void *a, const void *b, void *arg)
122 bool *haveDups = (bool *) arg;
133 unique_array(bigm *a, int len)
139 while (tmp - a < len)
140 if (CMPBIGM(tmp, curend))
144 memcpy(curend, tmp, BIGMSIZE);
150 return curend + 1 - a;
153 #define iswordchr(c) (!t_isspace(c))
156 * Finds first word in string, returns pointer to the word,
157 * endword points to the character after word
160 find_word(char *str, int lenstr, char **endword, int *charlen)
162 char *beginword = str;
164 while (beginword - str < lenstr && !iswordchr(beginword))
165 beginword += pg_mblen(beginword);
167 if (beginword - str >= lenstr)
170 *endword = beginword;
172 while (*endword - str < lenstr && iswordchr(*endword))
174 *endword += pg_mblen(*endword);
182 * The function is named compact_bigram to maintain consistency with pg_trgm,
183 * though it does not reduce multibyte characters to hash values like in
187 compact_bigram(bigm *bptr, char *str, int bytelen)
189 CPBIGM(bptr, str, bytelen);
193 * Adds bigrams from words (already padded).
196 make_bigrams(bigm *bptr, char *str, int bytelen, int charlen)
202 compact_bigram(bptr, ptr, pg_mblen(str));
208 if (bytelen > charlen)
210 /* Find multibyte character boundaries and call compact_bigram */
211 int lenfirst = pg_mblen(str),
212 lenlast = pg_mblen(str + lenfirst);
214 while ((ptr - str) + lenfirst + lenlast <= bytelen)
216 compact_bigram(bptr, ptr, lenfirst + lenlast);
222 lenlast = pg_mblen(ptr + lenfirst);
227 /* Fast path when there are no multibyte characters */
228 Assert(bytelen == charlen);
230 while (ptr - str < bytelen - 1 /* number of bigrams = strlen - 1 */ )
232 CPBIGM(bptr, ptr, 2);
242 generate_bigm(char *str, int slen)
253 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (Size) (slen / 2 + 1) * 3);
254 SET_VARSIZE(bgm, VARHDRSZ);
256 if (slen + LPADDING + RPADDING < 2 || slen == 0)
261 buf = palloc(sizeof(char) * (slen + 4));
271 while ((bword = find_word(eword, slen - (eword - str), &eword, &charlen)) != NULL)
273 bytelen = eword - bword;
274 memcpy(buf + LPADDING, bword, bytelen);
276 buf[LPADDING + bytelen] = ' ';
277 buf[LPADDING + bytelen + 1] = ' ';
282 bptr = make_bigrams(bptr, buf, bytelen + LPADDING + RPADDING,
283 charlen + LPADDING + RPADDING);
288 if ((len = bptr - GETARR(bgm)) == 0)
292 * Make bigrams unique.
296 bool haveDups = false;
298 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
300 len = unique_array(GETARR(bgm), len);
303 SET_VARSIZE(bgm, CALCGTSIZE(len));
309 * Extract the next non-wildcard part of a search string, ie, a word bounded
310 * by '_' or '%' meta-characters, non-word characters or string end.
312 * str: source string, of length lenstr bytes (need not be null-terminated)
313 * buf: where to return the substring (must be long enough)
314 * *bytelen: receives byte length of the found substring
315 * *charlen: receives character length of the found substring
317 * Returns pointer to end+1 of the found substring in the source string.
318 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
320 * If the found word is bounded by non-word characters or string boundaries
321 * then this function will include corresponding padding spaces into buf.
324 get_wildcard_part(const char *str, int lenstr,
325 char *buf, int *bytelen, int *charlen)
327 const char *beginword = str;
330 bool in_leading_wildcard_meta = false;
331 bool in_trailing_wildcard_meta = false;
332 bool in_escape = false;
336 * Find the first word character, remembering whether preceding character
337 * was wildcard meta-character. Note that the in_escape state persists
338 * from this loop to the next one, since we may exit at a word character
341 while (beginword - str < lenstr)
345 if (iswordchr(beginword))
348 in_leading_wildcard_meta = false;
352 if (ISESCAPECHAR(beginword))
354 else if (ISWILDCARDCHAR(beginword))
355 in_leading_wildcard_meta = true;
356 else if (iswordchr(beginword))
359 in_leading_wildcard_meta = false;
361 beginword += pg_mblen(beginword);
367 if (beginword - str >= lenstr)
371 * Add left padding spaces if preceding character wasn't wildcard
375 if (!in_leading_wildcard_meta)
390 * Copy data into buf until wildcard meta-character, non-word character or
391 * string boundary. Strip escapes during copy.
394 while (endword - str < lenstr)
396 clen = pg_mblen(endword);
399 if (iswordchr(endword))
401 memcpy(s, endword, clen);
408 * Back up endword to the escape character when stopping at an
409 * escaped char, so that subsequent get_wildcard_part will
410 * restart from the escape character. We assume here that
411 * escape chars are single-byte.
420 if (ISESCAPECHAR(endword))
422 else if (ISWILDCARDCHAR(endword))
424 in_trailing_wildcard_meta = true;
427 else if (iswordchr(endword))
429 memcpy(s, endword, clen);
440 * Add right padding spaces if next character isn't wildcard
443 if (!in_trailing_wildcard_meta)
462 * Generates bigrams for wildcard search string.
464 * Returns array of bigrams that must occur in any string that matches the
465 * wildcard string. For example, given pattern "a%bcd%" the bigrams
466 * " a", "bcd" would be extracted.
468 * Set 'removeDups' to true if duplicate bigrams are removed.
471 generate_wildcard_bigm(const char *str, int slen, bool *removeDups)
483 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (Size) (slen / 2 + 1) * 3);
484 SET_VARSIZE(bgm, VARHDRSZ);
486 if (slen + LPADDING + RPADDING < 2 || slen == 0)
491 buf = palloc(sizeof(char) * (slen + 4));
494 * Extract bigrams from each substring extracted by get_wildcard_part.
497 while ((eword = get_wildcard_part(eword, slen - (eword - str),
498 buf, &bytelen, &charlen)) != NULL)
503 bptr = make_bigrams(bptr, buf, bytelen, charlen);
508 if ((len = bptr - GETARR(bgm)) == 0)
512 * Make bigrams unique.
516 bool haveDups = false;
518 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
522 len = unique_array(GETARR(bgm), len);
526 SET_VARSIZE(bgm, CALCGTSIZE(len));
532 show_bigm(PG_FUNCTION_ARGS)
534 text *in = PG_GETARG_TEXT_P(0);
541 bgm = generate_bigm(VARDATA(in), VARSIZE(in) - VARHDRSZ);
542 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(bgm)));
544 for (i = 0, ptr = GETARR(bgm); i < ARRNELEM(bgm); i++, ptr++)
546 text *item = cstring_to_text_with_len(ptr->str, ptr->bytelen);
548 d[i] = PointerGetDatum(item);
560 for (i = 0; i < ARRNELEM(bgm); i++)
561 pfree(DatumGetPointer(d[i]));
565 PG_FREE_IF_COPY(in, 0);
567 PG_RETURN_POINTER(a);
571 cnt_sml_bigm(BIGM *bgm1, BIGM *bgm2)
582 len1 = ARRNELEM(bgm1);
583 len2 = ARRNELEM(bgm2);
585 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
586 if (len1 <= 0 || len2 <= 0)
589 while (ptr1 - GETARR(bgm1) < len1 && ptr2 - GETARR(bgm2) < len2)
591 int res = CMPBIGM(ptr1, ptr2);
606 return ((float4) count) / ((float4) (len1 + len2 - count));
608 return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
613 bigm_similarity(PG_FUNCTION_ARGS)
615 text *in1 = PG_GETARG_TEXT_P(0);
616 text *in2 = PG_GETARG_TEXT_P(1);
621 bgm1 = generate_bigm(VARDATA(in1), VARSIZE(in1) - VARHDRSZ);
622 bgm2 = generate_bigm(VARDATA(in2), VARSIZE(in2) - VARHDRSZ);
624 res = cnt_sml_bigm(bgm1, bgm2);
628 PG_FREE_IF_COPY(in1, 0);
629 PG_FREE_IF_COPY(in2, 1);
631 PG_RETURN_FLOAT4(res);
635 bigm_similarity_op(PG_FUNCTION_ARGS)
637 float4 res = DatumGetFloat4(DirectFunctionCall2(bigm_similarity,
639 PG_GETARG_DATUM(1)));
641 PG_RETURN_BOOL(res >= (float4) bigm_similarity_limit);
645 likequery(PG_FUNCTION_ARGS)
647 text *query = PG_GETARG_TEXT_PP(0);
655 str = VARDATA_ANY(query);
656 len = VARSIZE_ANY_EXHDR(query);
661 result = (text *) palloc((Size) len * 2 + 2 + VARHDRSZ);
662 rp = VARDATA(result);
665 for (sp = str; (sp - str) < len;)
667 if (ISWILDCARDCHAR(sp) || ISESCAPECHAR(sp))
672 else if (IS_HIGHBIT_SET(*sp))
674 mblen = pg_mblen(sp);
675 memcpy(rp, sp, mblen);
684 SET_VARSIZE(result, rp - VARDATA(result) + VARHDRSZ);
686 PG_RETURN_TEXT_P(result);
690 bigmstrcmp(char *arg1, int len1, char *arg2, int len2)
693 int len = Min(len1, len2);
695 for (i = 0; i < len; i++, arg1++, arg2++)
705 return (len1 == len2) ? 0 : ((len1 < len2) ? -1 : 1);
709 bigmtextcmp(PG_FUNCTION_ARGS)
711 text *arg1 = PG_GETARG_TEXT_PP(0);
712 text *arg2 = PG_GETARG_TEXT_PP(1);
713 char *a1p = VARDATA_ANY(arg1);
714 char *a2p = VARDATA_ANY(arg2);
715 int len1 = VARSIZE_ANY_EXHDR(arg1);
716 int len2 = VARSIZE_ANY_EXHDR(arg2);
718 PG_RETURN_INT32(bigmstrcmp(a1p, len1, a2p, len2));