1 /*-------------------------------------------------------------------------
3 * Portions Copyright (c) 2004-2012, PostgreSQL Global Development Group
4 * Portions Copyright (c) 2013-2016, 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 "2015.09.10"
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);
42 * The function prototypes are created as a part of PG_FUNCTION_INFO_V1
43 * macro since 9.4, and hence the declaration of the function prototypes
44 * here is necessary only for 9.3 or before.
46 #if PG_VERSION_NUM < 90400
47 Datum show_bigm(PG_FUNCTION_ARGS);
48 Datum bigmtextcmp(PG_FUNCTION_ARGS);
49 Datum likequery(PG_FUNCTION_ARGS);
50 Datum bigm_similarity(PG_FUNCTION_ARGS);
51 Datum bigm_similarity_op(PG_FUNCTION_ARGS);
60 /* Define custom GUC variables */
61 DefineCustomBoolVariable("pg_bigm.enable_recheck",
62 "Recheck that heap tuples fetched from index "
73 DefineCustomIntVariable("pg_bigm.gin_key_limit",
74 "Sets the maximum number of bi-gram keys allowed to "
75 "use for GIN index search.",
76 "Zero means no limit.",
86 DefineCustomRealVariable("pg_bigm.similarity_limit",
87 "Sets the similarity threshold used by the "
90 &bigm_similarity_limit,
99 /* Can't be set in postgresql.conf */
100 DefineCustomStringVariable("pg_bigm.last_update",
101 "Shows the last update date of pg_bigm.",
106 GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
111 EmitWarningsOnPlaceholders("pg_bigm");
120 comp_bigm(const void *a, const void *b, void *arg)
123 bool *haveDups = (bool *) arg;
134 unique_array(bigm *a, int len)
140 while (tmp - a < len)
141 if (CMPBIGM(tmp, curend))
145 memcpy(curend, tmp, BIGMSIZE);
151 return curend + 1 - a;
154 #define iswordchr(c) (!t_isspace(c))
157 * Finds first word in string, returns pointer to the word,
158 * endword points to the character after word
161 find_word(char *str, int lenstr, char **endword, int *charlen)
163 char *beginword = str;
165 while (beginword - str < lenstr && !iswordchr(beginword))
166 beginword += pg_mblen(beginword);
168 if (beginword - str >= lenstr)
171 *endword = beginword;
173 while (*endword - str < lenstr && iswordchr(*endword))
175 *endword += pg_mblen(*endword);
183 * The function is named compact_bigram to maintain consistency with pg_trgm,
184 * though it does not reduce multibyte characters to hash values like in
188 compact_bigram(bigm *bptr, char *str, int bytelen)
190 CPBIGM(bptr, str, bytelen);
194 * Adds bigrams from words (already padded).
197 make_bigrams(bigm *bptr, char *str, int bytelen, int charlen)
203 compact_bigram(bptr, ptr, pg_mblen(str));
209 if (bytelen > charlen)
211 /* Find multibyte character boundaries and call compact_bigram */
212 int lenfirst = pg_mblen(str),
213 lenlast = pg_mblen(str + lenfirst);
215 while ((ptr - str) + lenfirst + lenlast <= bytelen)
217 compact_bigram(bptr, ptr, lenfirst + lenlast);
223 lenlast = pg_mblen(ptr + lenfirst);
228 /* Fast path when there are no multibyte characters */
229 Assert(bytelen == charlen);
231 while (ptr - str < bytelen - 1 /* number of bigrams = strlen - 1 */ )
233 CPBIGM(bptr, ptr, 2);
243 generate_bigm(char *str, int slen)
255 * Guard against possible overflow in the palloc requests below.
256 * We need to prevent integer overflow in the multiplications here.
258 if ((Size) slen > (MaxAllocSize - VARHDRSZ) / sizeof(bigm) - 1 ||
259 (Size) slen > MaxAllocSize - 4)
261 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
262 errmsg("out of memory")));
264 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen + 1));
265 SET_VARSIZE(bgm, VARHDRSZ);
267 if (slen + LPADDING + RPADDING < 2 || slen == 0)
272 buf = palloc(sizeof(char) * (slen + 4));
282 while ((bword = find_word(eword, slen - (eword - str), &eword, &charlen)) != NULL)
284 bytelen = eword - bword;
285 memcpy(buf + LPADDING, bword, bytelen);
287 buf[LPADDING + bytelen] = ' ';
288 buf[LPADDING + bytelen + 1] = ' ';
293 bptr = make_bigrams(bptr, buf, bytelen + LPADDING + RPADDING,
294 charlen + LPADDING + RPADDING);
299 if ((len = bptr - GETARR(bgm)) == 0)
303 * Make bigrams unique.
307 bool haveDups = false;
309 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
311 len = unique_array(GETARR(bgm), len);
314 SET_VARSIZE(bgm, CALCGTSIZE(len));
320 * Extract the next non-wildcard part of a search string, ie, a word bounded
321 * by '_' or '%' meta-characters, non-word characters or string end.
323 * str: source string, of length lenstr bytes (need not be null-terminated)
324 * buf: where to return the substring (must be long enough)
325 * *bytelen: receives byte length of the found substring
326 * *charlen: receives character length of the found substring
328 * Returns pointer to end+1 of the found substring in the source string.
329 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
331 * If the found word is bounded by non-word characters or string boundaries
332 * then this function will include corresponding padding spaces into buf.
335 get_wildcard_part(const char *str, int lenstr,
336 char *buf, int *bytelen, int *charlen)
338 const char *beginword = str;
341 bool in_leading_wildcard_meta = false;
342 bool in_trailing_wildcard_meta = false;
343 bool in_escape = false;
347 * Find the first word character, remembering whether preceding character
348 * was wildcard meta-character. Note that the in_escape state persists
349 * from this loop to the next one, since we may exit at a word character
352 while (beginword - str < lenstr)
356 if (iswordchr(beginword))
359 in_leading_wildcard_meta = false;
363 if (ISESCAPECHAR(beginword))
365 else if (ISWILDCARDCHAR(beginword))
366 in_leading_wildcard_meta = true;
367 else if (iswordchr(beginword))
370 in_leading_wildcard_meta = false;
372 beginword += pg_mblen(beginword);
378 if (beginword - str >= lenstr)
382 * Add left padding spaces if preceding character wasn't wildcard
386 if (!in_leading_wildcard_meta)
401 * Copy data into buf until wildcard meta-character, non-word character or
402 * string boundary. Strip escapes during copy.
405 while (endword - str < lenstr)
407 clen = pg_mblen(endword);
410 if (iswordchr(endword))
412 memcpy(s, endword, clen);
419 * Back up endword to the escape character when stopping at an
420 * escaped char, so that subsequent get_wildcard_part will
421 * restart from the escape character. We assume here that
422 * escape chars are single-byte.
431 if (ISESCAPECHAR(endword))
433 else if (ISWILDCARDCHAR(endword))
435 in_trailing_wildcard_meta = true;
438 else if (iswordchr(endword))
440 memcpy(s, endword, clen);
451 * Add right padding spaces if next character isn't wildcard
454 if (!in_trailing_wildcard_meta)
473 * Generates bigrams for wildcard search string.
475 * Returns array of bigrams that must occur in any string that matches the
476 * wildcard string. For example, given pattern "a%bcd%" the bigrams
477 * " a", "bcd" would be extracted.
479 * Set 'removeDups' to true if duplicate bigrams are removed.
482 generate_wildcard_bigm(const char *str, int slen, bool *removeDups)
495 * Guard against possible overflow in the palloc requests below.
496 * We need to prevent integer overflow in the multiplications here.
498 if ((Size) slen > (MaxAllocSize - VARHDRSZ) / sizeof(bigm) - 1 ||
499 (Size) slen > MaxAllocSize - 4)
501 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
502 errmsg("out of memory")));
504 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen + 1));
505 SET_VARSIZE(bgm, VARHDRSZ);
507 if (slen + LPADDING + RPADDING < 2 || slen == 0)
512 buf = palloc(sizeof(char) * (slen + 4));
515 * Extract bigrams from each substring extracted by get_wildcard_part.
518 while ((eword = get_wildcard_part(eword, slen - (eword - str),
519 buf, &bytelen, &charlen)) != NULL)
524 bptr = make_bigrams(bptr, buf, bytelen, charlen);
529 if ((len = bptr - GETARR(bgm)) == 0)
533 * Make bigrams unique.
537 bool haveDups = false;
539 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
543 len = unique_array(GETARR(bgm), len);
547 SET_VARSIZE(bgm, CALCGTSIZE(len));
553 show_bigm(PG_FUNCTION_ARGS)
555 text *in = PG_GETARG_TEXT_P(0);
562 bgm = generate_bigm(VARDATA(in), VARSIZE(in) - VARHDRSZ);
563 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(bgm)));
565 for (i = 0, ptr = GETARR(bgm); i < ARRNELEM(bgm); i++, ptr++)
567 text *item = cstring_to_text_with_len(ptr->str, ptr->bytelen);
569 d[i] = PointerGetDatum(item);
581 for (i = 0; i < ARRNELEM(bgm); i++)
582 pfree(DatumGetPointer(d[i]));
586 PG_FREE_IF_COPY(in, 0);
588 PG_RETURN_POINTER(a);
592 cnt_sml_bigm(BIGM *bgm1, BIGM *bgm2)
603 len1 = ARRNELEM(bgm1);
604 len2 = ARRNELEM(bgm2);
606 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
607 if (len1 <= 0 || len2 <= 0)
610 while (ptr1 - GETARR(bgm1) < len1 && ptr2 - GETARR(bgm2) < len2)
612 int res = CMPBIGM(ptr1, ptr2);
627 return ((float4) count) / ((float4) (len1 + len2 - count));
629 return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
634 bigm_similarity(PG_FUNCTION_ARGS)
636 text *in1 = PG_GETARG_TEXT_P(0);
637 text *in2 = PG_GETARG_TEXT_P(1);
642 bgm1 = generate_bigm(VARDATA(in1), VARSIZE(in1) - VARHDRSZ);
643 bgm2 = generate_bigm(VARDATA(in2), VARSIZE(in2) - VARHDRSZ);
645 res = cnt_sml_bigm(bgm1, bgm2);
649 PG_FREE_IF_COPY(in1, 0);
650 PG_FREE_IF_COPY(in2, 1);
652 PG_RETURN_FLOAT4(res);
656 bigm_similarity_op(PG_FUNCTION_ARGS)
658 float4 res = DatumGetFloat4(DirectFunctionCall2(bigm_similarity,
660 PG_GETARG_DATUM(1)));
662 PG_RETURN_BOOL(res >= (float4) bigm_similarity_limit);
666 likequery(PG_FUNCTION_ARGS)
668 text *query = PG_GETARG_TEXT_PP(0);
676 str = VARDATA_ANY(query);
677 len = VARSIZE_ANY_EXHDR(query);
682 result = (text *) palloc((Size) len * 2 + 2 + VARHDRSZ);
683 rp = VARDATA(result);
686 for (sp = str; (sp - str) < len;)
688 if (ISWILDCARDCHAR(sp) || ISESCAPECHAR(sp))
693 else if (IS_HIGHBIT_SET(*sp))
695 mblen = pg_mblen(sp);
696 memcpy(rp, sp, mblen);
705 SET_VARSIZE(result, rp - VARDATA(result) + VARHDRSZ);
707 PG_RETURN_TEXT_P(result);
711 bigmstrcmp(char *arg1, int len1, char *arg2, int len2)
714 int len = Min(len1, len2);
716 for (i = 0; i < len; i++, arg1++, arg2++)
726 return (len1 == len2) ? 0 : ((len1 < len2) ? -1 : 1);
730 bigmtextcmp(PG_FUNCTION_ARGS)
732 text *arg1 = PG_GETARG_TEXT_PP(0);
733 text *arg2 = PG_GETARG_TEXT_PP(1);
734 char *a1p = VARDATA_ANY(arg1);
735 char *a2p = VARDATA_ANY(arg2);
736 int len1 = VARSIZE_ANY_EXHDR(arg1);
737 int len2 = VARSIZE_ANY_EXHDR(arg2);
739 PG_RETURN_INT32(bigmstrcmp(a1p, len1, a2p, len2));