1 /*-------------------------------------------------------------------------
3 * Portions Copyright (c) 2017-2020, pg_bigm Development Group
4 * Portions Copyright (c) 2013-2016, NTT DATA Corporation
5 * Portions Copyright (c) 2004-2012, PostgreSQL Global Development Group
9 * Support full text search using bigrams.
10 * Author: NTT DATA Corporation
12 *-------------------------------------------------------------------------
20 #include "catalog/pg_type.h"
21 #include "tsearch/ts_locale.h"
22 #include "utils/array.h"
23 #include "utils/memutils.h"
27 /* Last update date of pg_bigm */
28 #define BIGM_LAST_UPDATE "2019.10.03"
31 bool bigm_enable_recheck = false;
32 int bigm_gin_key_limit = 0;
33 double bigm_similarity_limit = 0.3;
34 char *bigm_last_update = NULL;
36 PG_FUNCTION_INFO_V1(show_bigm);
37 PG_FUNCTION_INFO_V1(bigmtextcmp);
38 PG_FUNCTION_INFO_V1(likequery);
39 PG_FUNCTION_INFO_V1(bigm_similarity);
40 PG_FUNCTION_INFO_V1(bigm_similarity_op);
43 * The function prototypes are created as a part of PG_FUNCTION_INFO_V1
44 * macro since 9.4, and hence the declaration of the function prototypes
45 * here is necessary only for 9.3 or before.
47 #if PG_VERSION_NUM < 90400
48 Datum show_bigm(PG_FUNCTION_ARGS);
49 Datum bigmtextcmp(PG_FUNCTION_ARGS);
50 Datum likequery(PG_FUNCTION_ARGS);
51 Datum bigm_similarity(PG_FUNCTION_ARGS);
52 Datum bigm_similarity_op(PG_FUNCTION_ARGS);
61 /* Define custom GUC variables */
62 DefineCustomBoolVariable("pg_bigm.enable_recheck",
63 "Recheck that heap tuples fetched from index "
74 DefineCustomIntVariable("pg_bigm.gin_key_limit",
75 "Sets the maximum number of bi-gram keys allowed to "
76 "use for GIN index search.",
77 "Zero means no limit.",
87 DefineCustomRealVariable("pg_bigm.similarity_limit",
88 "Sets the similarity threshold used by the "
91 &bigm_similarity_limit,
100 /* Can't be set in postgresql.conf */
101 DefineCustomStringVariable("pg_bigm.last_update",
102 "Shows the last update date of pg_bigm.",
107 GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
112 EmitWarningsOnPlaceholders("pg_bigm");
121 comp_bigm(const void *a, const void *b, void *arg)
124 bool *haveDups = (bool *) arg;
135 unique_array(bigm *a, int len)
141 while (tmp - a < len)
142 if (CMPBIGM(tmp, curend))
146 memcpy(curend, tmp, BIGMSIZE);
152 return curend + 1 - a;
155 #define iswordchr(c) (!t_isspace(c))
158 * Finds first word in string, returns pointer to the word,
159 * endword points to the character after word
162 find_word(char *str, int lenstr, char **endword, int *charlen)
164 char *beginword = str;
166 while (beginword - str < lenstr && !iswordchr(beginword))
167 beginword += pg_mblen(beginword);
169 if (beginword - str >= lenstr)
172 *endword = beginword;
174 while (*endword - str < lenstr && iswordchr(*endword))
176 *endword += pg_mblen(*endword);
184 * The function is named compact_bigram to maintain consistency with pg_trgm,
185 * though it does not reduce multibyte characters to hash values like in
189 compact_bigram(bigm *bptr, char *str, int bytelen)
191 CPBIGM(bptr, str, bytelen);
195 * Adds bigrams from words (already padded).
198 make_bigrams(bigm *bptr, char *str, int bytelen, int charlen)
204 compact_bigram(bptr, ptr, pg_mblen(str));
210 if (bytelen > charlen)
212 /* Find multibyte character boundaries and call compact_bigram */
213 int lenfirst = pg_mblen(str),
214 lenlast = pg_mblen(str + lenfirst);
216 while ((ptr - str) + lenfirst + lenlast <= bytelen)
218 compact_bigram(bptr, ptr, lenfirst + lenlast);
224 lenlast = pg_mblen(ptr + lenfirst);
229 /* Fast path when there are no multibyte characters */
230 Assert(bytelen == charlen);
232 while (ptr - str < bytelen - 1 /* number of bigrams = strlen - 1 */ )
234 CPBIGM(bptr, ptr, 2);
244 generate_bigm(char *str, int slen)
256 * Guard against possible overflow in the palloc requests below.
257 * We need to prevent integer overflow in the multiplications here.
259 if ((Size) slen > (MaxAllocSize - VARHDRSZ) / sizeof(bigm) - 1 ||
260 (Size) slen > MaxAllocSize - 4)
262 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
263 errmsg("out of memory")));
265 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen + 1));
266 SET_VARSIZE(bgm, VARHDRSZ);
268 if (slen + LPADDING + RPADDING < 2 || slen == 0)
273 buf = palloc(sizeof(char) * (slen + 4));
283 while ((bword = find_word(eword, slen - (eword - str), &eword, &charlen)) != NULL)
285 bytelen = eword - bword;
286 memcpy(buf + LPADDING, bword, bytelen);
288 buf[LPADDING + bytelen] = ' ';
289 buf[LPADDING + bytelen + 1] = ' ';
294 bptr = make_bigrams(bptr, buf, bytelen + LPADDING + RPADDING,
295 charlen + LPADDING + RPADDING);
300 if ((len = bptr - GETARR(bgm)) == 0)
304 * Make bigrams unique.
308 bool haveDups = false;
310 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
312 len = unique_array(GETARR(bgm), len);
315 SET_VARSIZE(bgm, CALCGTSIZE(len));
321 * Extract the next non-wildcard part of a search string, i.e. a word bounded
322 * by '_' or '%' meta-characters, non-word characters or string end.
324 * str: source string, of length lenstr bytes (need not be null-terminated)
325 * buf: where to return the substring (must be long enough)
326 * *bytelen: receives byte length of the found substring
327 * *charlen: receives character length of the found substring
329 * Returns pointer to end+1 of the found substring in the source string.
330 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
332 * If the found word is bounded by non-word characters or string boundaries
333 * then this function will include corresponding padding spaces into buf.
336 get_wildcard_part(const char *str, int lenstr,
337 char *buf, int *bytelen, int *charlen)
339 const char *beginword = str;
342 bool in_leading_wildcard_meta = false;
343 bool in_trailing_wildcard_meta = false;
344 bool in_escape = false;
348 * Find the first word character, remembering whether preceding character
349 * was wildcard meta-character. Note that the in_escape state persists
350 * from this loop to the next one, since we may exit at a word character
353 while (beginword - str < lenstr)
357 if (iswordchr(beginword))
360 in_leading_wildcard_meta = false;
364 if (ISESCAPECHAR(beginword))
366 else if (ISWILDCARDCHAR(beginword))
367 in_leading_wildcard_meta = true;
368 else if (iswordchr(beginword))
371 in_leading_wildcard_meta = false;
373 beginword += pg_mblen(beginword);
379 if (beginword - str >= lenstr)
383 * Add left padding spaces if preceding character wasn't wildcard
387 if (!in_leading_wildcard_meta)
402 * Copy data into buf until wildcard meta-character, non-word character or
403 * string boundary. Strip escapes during copy.
406 while (endword - str < lenstr)
408 clen = pg_mblen(endword);
411 if (iswordchr(endword))
413 memcpy(s, endword, clen);
420 * Back up endword to the escape character when stopping at an
421 * escaped char, so that subsequent get_wildcard_part will
422 * restart from the escape character. We assume here that
423 * escape chars are single-byte.
432 if (ISESCAPECHAR(endword))
434 else if (ISWILDCARDCHAR(endword))
436 in_trailing_wildcard_meta = true;
439 else if (iswordchr(endword))
441 memcpy(s, endword, clen);
452 * Add right padding spaces if next character isn't wildcard
455 if (!in_trailing_wildcard_meta)
474 * Generates bigrams for wildcard search string.
476 * Returns array of bigrams that must occur in any string that matches the
477 * wildcard string. For example, given pattern "a%bcd%" the bigrams
478 * " a", "bcd" would be extracted.
480 * Set 'removeDups' to true if duplicate bigrams are removed.
483 generate_wildcard_bigm(const char *str, int slen, bool *removeDups)
496 * Guard against possible overflow in the palloc requests below.
497 * We need to prevent integer overflow in the multiplications here.
499 if ((Size) slen > (MaxAllocSize - VARHDRSZ) / sizeof(bigm) - 1 ||
500 (Size) slen > MaxAllocSize - 4)
502 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
503 errmsg("out of memory")));
505 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen + 1));
506 SET_VARSIZE(bgm, VARHDRSZ);
508 if (slen + LPADDING + RPADDING < 2 || slen == 0)
513 buf = palloc(sizeof(char) * (slen + 4));
516 * Extract bigrams from each substring extracted by get_wildcard_part.
519 while ((eword = get_wildcard_part(eword, slen - (eword - str),
520 buf, &bytelen, &charlen)) != NULL)
525 bptr = make_bigrams(bptr, buf, bytelen, charlen);
530 if ((len = bptr - GETARR(bgm)) == 0)
534 * Make bigrams unique.
538 bool haveDups = false;
540 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
544 len = unique_array(GETARR(bgm), len);
548 SET_VARSIZE(bgm, CALCGTSIZE(len));
554 show_bigm(PG_FUNCTION_ARGS)
556 text *in = PG_GETARG_TEXT_P(0);
563 bgm = generate_bigm(VARDATA(in), VARSIZE(in) - VARHDRSZ);
564 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(bgm)));
566 for (i = 0, ptr = GETARR(bgm); i < ARRNELEM(bgm); i++, ptr++)
568 text *item = cstring_to_text_with_len(ptr->str, ptr->bytelen);
570 d[i] = PointerGetDatum(item);
582 for (i = 0; i < ARRNELEM(bgm); i++)
583 pfree(DatumGetPointer(d[i]));
587 PG_FREE_IF_COPY(in, 0);
589 PG_RETURN_POINTER(a);
593 cnt_sml_bigm(BIGM *bgm1, BIGM *bgm2)
604 len1 = ARRNELEM(bgm1);
605 len2 = ARRNELEM(bgm2);
607 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
608 if (len1 <= 0 || len2 <= 0)
611 while (ptr1 - GETARR(bgm1) < len1 && ptr2 - GETARR(bgm2) < len2)
613 int res = CMPBIGM(ptr1, ptr2);
628 return ((float4) count) / ((float4) (len1 + len2 - count));
630 return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
635 bigm_similarity(PG_FUNCTION_ARGS)
637 text *in1 = PG_GETARG_TEXT_P(0);
638 text *in2 = PG_GETARG_TEXT_P(1);
643 bgm1 = generate_bigm(VARDATA(in1), VARSIZE(in1) - VARHDRSZ);
644 bgm2 = generate_bigm(VARDATA(in2), VARSIZE(in2) - VARHDRSZ);
646 res = cnt_sml_bigm(bgm1, bgm2);
650 PG_FREE_IF_COPY(in1, 0);
651 PG_FREE_IF_COPY(in2, 1);
653 PG_RETURN_FLOAT4(res);
657 bigm_similarity_op(PG_FUNCTION_ARGS)
659 float4 res = DatumGetFloat4(DirectFunctionCall2(bigm_similarity,
661 PG_GETARG_DATUM(1)));
663 PG_RETURN_BOOL(res >= (float4) bigm_similarity_limit);
667 likequery(PG_FUNCTION_ARGS)
669 text *query = PG_GETARG_TEXT_PP(0);
677 str = VARDATA_ANY(query);
678 len = VARSIZE_ANY_EXHDR(query);
683 result = (text *) palloc((Size) len * 2 + 2 + VARHDRSZ);
684 rp = VARDATA(result);
687 for (sp = str; (sp - str) < len;)
689 if (ISWILDCARDCHAR(sp) || ISESCAPECHAR(sp))
694 else if (IS_HIGHBIT_SET(*sp))
696 mblen = pg_mblen(sp);
697 memcpy(rp, sp, mblen);
706 SET_VARSIZE(result, rp - VARDATA(result) + VARHDRSZ);
708 PG_RETURN_TEXT_P(result);
712 bigmtextcmp(PG_FUNCTION_ARGS)
714 text *arg1 = PG_GETARG_TEXT_PP(0);
715 text *arg2 = PG_GETARG_TEXT_PP(1);
716 char *a1p = VARDATA_ANY(arg1);
717 char *a2p = VARDATA_ANY(arg2);
718 int len1 = VARSIZE_ANY_EXHDR(arg1);
719 int len2 = VARSIZE_ANY_EXHDR(arg2);
721 PG_RETURN_INT32(bigmstrcmp(a1p, len1, a2p, len2));