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"
22 #include "utils/memutils.h"
26 /* Last update date of pg_bigm */
27 #define BIGM_LAST_UPDATE "2013.11.22"
30 bool bigm_enable_recheck = false;
31 int bigm_gin_key_limit = 0;
32 double bigm_similarity_limit = 0.3;
33 char *bigm_last_update = NULL;
35 PG_FUNCTION_INFO_V1(show_bigm);
36 PG_FUNCTION_INFO_V1(bigmtextcmp);
37 PG_FUNCTION_INFO_V1(likequery);
38 PG_FUNCTION_INFO_V1(bigm_similarity);
39 PG_FUNCTION_INFO_V1(bigm_similarity_op);
47 /* Define custom GUC variables */
48 DefineCustomBoolVariable("pg_bigm.enable_recheck",
49 "Recheck that heap tuples fetched from index "
60 DefineCustomIntVariable("pg_bigm.gin_key_limit",
61 "Sets the maximum number of bi-gram keys allowed to "
62 "use for GIN index search.",
63 "Zero means no limit.",
73 DefineCustomRealVariable("pg_bigm.similarity_limit",
74 "Sets the similarity threshold used by the "
77 &bigm_similarity_limit,
86 /* Can't be set in postgresql.conf */
87 DefineCustomStringVariable("pg_bigm.last_update",
88 "Shows the last update date of pg_bigm.",
93 GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
98 EmitWarningsOnPlaceholders("pg_bigm");
107 comp_bigm(const void *a, const void *b, void *arg)
110 bool *haveDups = (bool *) arg;
121 unique_array(bigm *a, int len)
127 while (tmp - a < len)
128 if (CMPBIGM(tmp, curend))
132 memcpy(curend, tmp, BIGMSIZE);
138 return curend + 1 - a;
141 #define iswordchr(c) (!t_isspace(c))
144 * Finds first word in string, returns pointer to the word,
145 * endword points to the character after word
148 find_word(char *str, int lenstr, char **endword, int *charlen)
150 char *beginword = str;
152 while (beginword - str < lenstr && !iswordchr(beginword))
153 beginword += pg_mblen(beginword);
155 if (beginword - str >= lenstr)
158 *endword = beginword;
160 while (*endword - str < lenstr && iswordchr(*endword))
162 *endword += pg_mblen(*endword);
170 * The function is named compact_bigram to maintain consistency with pg_trgm,
171 * though it does not reduce multibyte characters to hash values like in
175 compact_bigram(bigm *bptr, char *str, int bytelen)
177 CPBIGM(bptr, str, bytelen);
181 * Adds bigrams from words (already padded).
184 make_bigrams(bigm *bptr, char *str, int bytelen, int charlen)
190 compact_bigram(bptr, ptr, pg_mblen(str));
196 if (bytelen > charlen)
198 /* Find multibyte character boundaries and call compact_bigram */
199 int lenfirst = pg_mblen(str),
200 lenlast = pg_mblen(str + lenfirst);
202 while ((ptr - str) + lenfirst + lenlast <= bytelen)
204 compact_bigram(bptr, ptr, lenfirst + lenlast);
210 lenlast = pg_mblen(ptr + lenfirst);
215 /* Fast path when there are no multibyte characters */
216 Assert(bytelen == charlen);
218 while (ptr - str < bytelen - 1 /* number of bigrams = strlen - 1 */ )
220 CPBIGM(bptr, ptr, 2);
230 generate_bigm(char *str, int slen)
242 * Guard against possible overflow in the palloc requests below.
243 * We need to prevent integer overflow in the multiplications here.
245 if ((Size) slen > (MaxAllocSize - VARHDRSZ) / sizeof(bigm) - 1 ||
246 (Size) slen > MaxAllocSize - 4)
248 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
249 errmsg("out of memory")));
251 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen + 1));
252 SET_VARSIZE(bgm, VARHDRSZ);
254 if (slen + LPADDING + RPADDING < 2 || slen == 0)
259 buf = palloc(sizeof(char) * (slen + 4));
269 while ((bword = find_word(eword, slen - (eword - str), &eword, &charlen)) != NULL)
271 bytelen = eword - bword;
272 memcpy(buf + LPADDING, bword, bytelen);
274 buf[LPADDING + bytelen] = ' ';
275 buf[LPADDING + bytelen + 1] = ' ';
280 bptr = make_bigrams(bptr, buf, bytelen + LPADDING + RPADDING,
281 charlen + LPADDING + RPADDING);
286 if ((len = bptr - GETARR(bgm)) == 0)
290 * Make bigrams unique.
294 bool haveDups = false;
296 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
298 len = unique_array(GETARR(bgm), len);
301 SET_VARSIZE(bgm, CALCGTSIZE(len));
307 * Extract the next non-wildcard part of a search string, ie, a word bounded
308 * by '_' or '%' meta-characters, non-word characters or string end.
310 * str: source string, of length lenstr bytes (need not be null-terminated)
311 * buf: where to return the substring (must be long enough)
312 * *bytelen: receives byte length of the found substring
313 * *charlen: receives character length of the found substring
315 * Returns pointer to end+1 of the found substring in the source string.
316 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
318 * If the found word is bounded by non-word characters or string boundaries
319 * then this function will include corresponding padding spaces into buf.
322 get_wildcard_part(const char *str, int lenstr,
323 char *buf, int *bytelen, int *charlen)
325 const char *beginword = str;
328 bool in_leading_wildcard_meta = false;
329 bool in_trailing_wildcard_meta = false;
330 bool in_escape = false;
334 * Find the first word character, remembering whether preceding character
335 * was wildcard meta-character. Note that the in_escape state persists
336 * from this loop to the next one, since we may exit at a word character
339 while (beginword - str < lenstr)
343 if (iswordchr(beginword))
346 in_leading_wildcard_meta = false;
350 if (ISESCAPECHAR(beginword))
352 else if (ISWILDCARDCHAR(beginword))
353 in_leading_wildcard_meta = true;
354 else if (iswordchr(beginword))
357 in_leading_wildcard_meta = false;
359 beginword += pg_mblen(beginword);
365 if (beginword - str >= lenstr)
369 * Add left padding spaces if preceding character wasn't wildcard
373 if (!in_leading_wildcard_meta)
388 * Copy data into buf until wildcard meta-character, non-word character or
389 * string boundary. Strip escapes during copy.
392 while (endword - str < lenstr)
394 clen = pg_mblen(endword);
397 if (iswordchr(endword))
399 memcpy(s, endword, clen);
406 * Back up endword to the escape character when stopping at an
407 * escaped char, so that subsequent get_wildcard_part will
408 * restart from the escape character. We assume here that
409 * escape chars are single-byte.
418 if (ISESCAPECHAR(endword))
420 else if (ISWILDCARDCHAR(endword))
422 in_trailing_wildcard_meta = true;
425 else if (iswordchr(endword))
427 memcpy(s, endword, clen);
438 * Add right padding spaces if next character isn't wildcard
441 if (!in_trailing_wildcard_meta)
460 * Generates bigrams for wildcard search string.
462 * Returns array of bigrams that must occur in any string that matches the
463 * wildcard string. For example, given pattern "a%bcd%" the bigrams
464 * " a", "bcd" would be extracted.
466 * Set 'removeDups' to true if duplicate bigrams are removed.
469 generate_wildcard_bigm(const char *str, int slen, bool *removeDups)
482 * Guard against possible overflow in the palloc requests below.
483 * We need to prevent integer overflow in the multiplications here.
485 if ((Size) slen > (MaxAllocSize - VARHDRSZ) / sizeof(bigm) - 1 ||
486 (Size) slen > MaxAllocSize - 4)
488 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
489 errmsg("out of memory")));
491 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen + 1));
492 SET_VARSIZE(bgm, VARHDRSZ);
494 if (slen + LPADDING + RPADDING < 2 || slen == 0)
499 buf = palloc(sizeof(char) * (slen + 4));
502 * Extract bigrams from each substring extracted by get_wildcard_part.
505 while ((eword = get_wildcard_part(eword, slen - (eword - str),
506 buf, &bytelen, &charlen)) != NULL)
511 bptr = make_bigrams(bptr, buf, bytelen, charlen);
516 if ((len = bptr - GETARR(bgm)) == 0)
520 * Make bigrams unique.
524 bool haveDups = false;
526 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
530 len = unique_array(GETARR(bgm), len);
534 SET_VARSIZE(bgm, CALCGTSIZE(len));
540 show_bigm(PG_FUNCTION_ARGS)
542 text *in = PG_GETARG_TEXT_P(0);
549 bgm = generate_bigm(VARDATA(in), VARSIZE(in) - VARHDRSZ);
550 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(bgm)));
552 for (i = 0, ptr = GETARR(bgm); i < ARRNELEM(bgm); i++, ptr++)
554 text *item = cstring_to_text_with_len(ptr->str, ptr->bytelen);
556 d[i] = PointerGetDatum(item);
568 for (i = 0; i < ARRNELEM(bgm); i++)
569 pfree(DatumGetPointer(d[i]));
573 PG_FREE_IF_COPY(in, 0);
575 PG_RETURN_POINTER(a);
579 cnt_sml_bigm(BIGM *bgm1, BIGM *bgm2)
590 len1 = ARRNELEM(bgm1);
591 len2 = ARRNELEM(bgm2);
593 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
594 if (len1 <= 0 || len2 <= 0)
597 while (ptr1 - GETARR(bgm1) < len1 && ptr2 - GETARR(bgm2) < len2)
599 int res = CMPBIGM(ptr1, ptr2);
614 return ((float4) count) / ((float4) (len1 + len2 - count));
616 return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
621 bigm_similarity(PG_FUNCTION_ARGS)
623 text *in1 = PG_GETARG_TEXT_P(0);
624 text *in2 = PG_GETARG_TEXT_P(1);
629 bgm1 = generate_bigm(VARDATA(in1), VARSIZE(in1) - VARHDRSZ);
630 bgm2 = generate_bigm(VARDATA(in2), VARSIZE(in2) - VARHDRSZ);
632 res = cnt_sml_bigm(bgm1, bgm2);
636 PG_FREE_IF_COPY(in1, 0);
637 PG_FREE_IF_COPY(in2, 1);
639 PG_RETURN_FLOAT4(res);
643 bigm_similarity_op(PG_FUNCTION_ARGS)
645 float4 res = DatumGetFloat4(DirectFunctionCall2(bigm_similarity,
647 PG_GETARG_DATUM(1)));
649 PG_RETURN_BOOL(res >= (float4) bigm_similarity_limit);
653 likequery(PG_FUNCTION_ARGS)
655 text *query = PG_GETARG_TEXT_PP(0);
663 str = VARDATA_ANY(query);
664 len = VARSIZE_ANY_EXHDR(query);
669 result = (text *) palloc((Size) len * 2 + 2 + VARHDRSZ);
670 rp = VARDATA(result);
673 for (sp = str; (sp - str) < len;)
675 if (ISWILDCARDCHAR(sp) || ISESCAPECHAR(sp))
680 else if (IS_HIGHBIT_SET(*sp))
682 mblen = pg_mblen(sp);
683 memcpy(rp, sp, mblen);
692 SET_VARSIZE(result, rp - VARDATA(result) + VARHDRSZ);
694 PG_RETURN_TEXT_P(result);
698 bigmstrcmp(char *arg1, int len1, char *arg2, int len2)
701 int len = Min(len1, len2);
703 for (i = 0; i < len; i++, arg1++, arg2++)
713 return (len1 == len2) ? 0 : ((len1 < len2) ? -1 : 1);
717 bigmtextcmp(PG_FUNCTION_ARGS)
719 text *arg1 = PG_GETARG_TEXT_PP(0);
720 text *arg2 = PG_GETARG_TEXT_PP(1);
721 char *a1p = VARDATA_ANY(arg1);
722 char *a2p = VARDATA_ANY(arg2);
723 int len1 = VARSIZE_ANY_EXHDR(arg1);
724 int len2 = VARSIZE_ANY_EXHDR(arg2);
726 PG_RETURN_INT32(bigmstrcmp(a1p, len1, a2p, len2));