1 /*-------------------------------------------------------------------------
3 * Portions Copyright (c) 2004-2012, PostgreSQL Global Development Group
7 * Support full text search using bigrams.
8 * Author: NTT DATA Corporation
10 *-------------------------------------------------------------------------
18 #include "catalog/pg_type.h"
19 #include "tsearch/ts_locale.h"
20 #include "utils/array.h"
25 /* Last update date of pg_bigm */
26 #define BIGM_LAST_UPDATE "2013.04.05"
29 bool bigm_enable_recheck = false;
30 int bigm_gin_key_limit = 0;
31 char *bigm_last_update = NULL;
33 PG_FUNCTION_INFO_V1(show_bigm);
34 Datum show_bigm(PG_FUNCTION_ARGS);
36 PG_FUNCTION_INFO_V1(bigmtextcmp);
37 Datum bigmtextcmp(PG_FUNCTION_ARGS);
39 PG_FUNCTION_INFO_V1(likequery);
40 Datum likequery(PG_FUNCTION_ARGS);
42 PG_FUNCTION_INFO_V1(bigm_similarity);
43 Datum bigm_similarity(PG_FUNCTION_ARGS);
51 /* Define custom GUC variables */
52 DefineCustomBoolVariable("pg_bigm.enable_recheck",
53 "Recheck that heap tuples fetched from index "
64 DefineCustomIntVariable("pg_bigm.gin_key_limit",
65 "Sets the maximum number of bi-gram keys allowed to "
66 "use for GIN index search.",
67 "Zero means no limit.",
77 /* Can't be set in postgresql.conf */
78 DefineCustomStringVariable("pg_bigm.last_update",
79 "Shows the last update date of pg_bigm.",
84 GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
89 EmitWarningsOnPlaceholders("pg_bigm");
98 comp_bigm(const void *a, const void *b, void *arg)
101 bool *haveDups = (bool *) arg;
112 unique_array(bigm *a, int len)
118 while (tmp - a < len)
119 if (CMPBIGM(tmp, curend))
123 memcpy(curend, tmp, BIGMSIZE);
129 return curend + 1 - a;
132 #define iswordchr(c) (!t_isspace(c))
135 * Finds first word in string, returns pointer to the word,
136 * endword points to the character after word
139 find_word(char *str, int lenstr, char **endword, int *charlen)
141 char *beginword = str;
143 while (beginword - str < lenstr && !iswordchr(beginword))
144 beginword += pg_mblen(beginword);
146 if (beginword - str >= lenstr)
149 *endword = beginword;
151 while (*endword - str < lenstr && iswordchr(*endword))
153 *endword += pg_mblen(*endword);
161 * The function is named compact_bigram to maintain consistency with pg_trgm,
162 * though it does not reduce multibyte characters to hash values like in
166 compact_bigram(bigm *bptr, char *str, int bytelen)
168 CPBIGM(bptr, str, bytelen);
172 * Adds bigrams from words (already padded).
175 make_bigrams(bigm *bptr, char *str, int bytelen, int charlen)
181 compact_bigram(bptr, ptr, pg_mblen(str));
187 if (bytelen > charlen)
189 /* Find multibyte character boundaries and call compact_bigram */
190 int lenfirst = pg_mblen(str),
191 lenlast = pg_mblen(str + lenfirst);
193 while ((ptr - str) + lenfirst + lenlast <= bytelen)
195 compact_bigram(bptr, ptr, lenfirst + lenlast);
201 lenlast = pg_mblen(ptr + lenfirst);
206 /* Fast path when there are no multibyte characters */
207 Assert(bytelen == charlen);
209 while (ptr - str < bytelen - 1 /* number of bigrams = strlen - 1 */ )
211 CPBIGM(bptr, ptr, 2);
221 generate_bigm(char *str, int slen)
232 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen / 2 + 1) *3);
233 SET_VARSIZE(bgm, VARHDRSZ);
235 if (slen + LPADDING + RPADDING < 2 || slen == 0)
240 buf = palloc(sizeof(char) * (slen + 4));
250 while ((bword = find_word(eword, slen - (eword - str), &eword, &charlen)) != NULL)
252 bytelen = eword - bword;
253 memcpy(buf + LPADDING, bword, bytelen);
255 buf[LPADDING + bytelen] = ' ';
256 buf[LPADDING + bytelen + 1] = ' ';
261 bptr = make_bigrams(bptr, buf, bytelen + LPADDING + RPADDING,
262 charlen + LPADDING + RPADDING);
267 if ((len = bptr - GETARR(bgm)) == 0)
272 bool haveDups = false;
274 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
276 len = unique_array(GETARR(bgm), len);
279 SET_VARSIZE(bgm, CALCGTSIZE(len));
285 * Extract the next non-wildcard part of a search string, ie, a word bounded
286 * by '_' or '%' meta-characters, non-word characters or string end.
288 * str: source string, of length lenstr bytes (need not be null-terminated)
289 * buf: where to return the substring (must be long enough)
290 * *bytelen: receives byte length of the found substring
291 * *charlen: receives character length of the found substring
293 * Returns pointer to end+1 of the found substring in the source string.
294 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
296 * If the found word is bounded by non-word characters or string boundaries
297 * then this function will include corresponding padding spaces into buf.
300 get_wildcard_part(const char *str, int lenstr,
301 char *buf, int *bytelen, int *charlen)
303 const char *beginword = str;
306 bool in_leading_wildcard_meta = false;
307 bool in_trailing_wildcard_meta = false;
308 bool in_escape = false;
312 * Find the first word character, remembering whether preceding character
313 * was wildcard meta-character. Note that the in_escape state persists
314 * from this loop to the next one, since we may exit at a word character
317 while (beginword - str < lenstr)
321 if (iswordchr(beginword))
324 in_leading_wildcard_meta = false;
328 if (ISESCAPECHAR(beginword))
330 else if (ISWILDCARDCHAR(beginword))
331 in_leading_wildcard_meta = true;
332 else if (iswordchr(beginword))
335 in_leading_wildcard_meta = false;
337 beginword += pg_mblen(beginword);
343 if (beginword - str >= lenstr)
347 * Add left padding spaces if preceding character wasn't wildcard
351 if (!in_leading_wildcard_meta)
366 * Copy data into buf until wildcard meta-character, non-word character or
367 * string boundary. Strip escapes during copy.
370 while (endword - str < lenstr)
372 clen = pg_mblen(endword);
375 if (iswordchr(endword))
377 memcpy(s, endword, clen);
384 * Back up endword to the escape character when stopping at
385 * an escaped char, so that subsequent get_wildcard_part will
386 * restart from the escape character. We assume here that
387 * escape chars are single-byte.
396 if (ISESCAPECHAR(endword))
398 else if (ISWILDCARDCHAR(endword))
400 in_trailing_wildcard_meta = true;
403 else if (iswordchr(endword))
405 memcpy(s, endword, clen);
416 * Add right padding spaces if next character isn't wildcard
419 if (!in_trailing_wildcard_meta)
438 * Generates bigrams for wildcard search string.
440 * Returns array of bigrams that must occur in any string that matches the
441 * wildcard string. For example, given pattern "a%bcd%" the bigrams
442 * " a", "bcd" would be extracted.
444 * Set 'removeDups' to true if duplicate bigrams are removed.
447 generate_wildcard_bigm(const char *str, int slen, bool *removeDups)
459 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen / 2 + 1) *3);
460 SET_VARSIZE(bgm, VARHDRSZ);
462 if (slen + LPADDING + RPADDING < 2 || slen == 0)
467 buf = palloc(sizeof(char) * (slen + 4));
470 * Extract bigrams from each substring extracted by get_wildcard_part.
473 while ((eword = get_wildcard_part(eword, slen - (eword - str),
474 buf, &bytelen, &charlen)) != NULL)
479 bptr = make_bigrams(bptr, buf, bytelen, charlen);
484 if ((len = bptr - GETARR(bgm)) == 0)
488 * Make bigrams unique.
492 bool haveDups = false;
494 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
498 len = unique_array(GETARR(bgm), len);
502 SET_VARSIZE(bgm, CALCGTSIZE(len));
508 show_bigm(PG_FUNCTION_ARGS)
510 text *in = PG_GETARG_TEXT_P(0);
517 bgm = generate_bigm(VARDATA(in), VARSIZE(in) - VARHDRSZ);
518 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(bgm)));
520 for (i = 0, ptr = GETARR(bgm); i < ARRNELEM(bgm); i++, ptr++)
522 text *item = cstring_to_text_with_len(ptr->str, ptr->bytelen);
523 d[i] = PointerGetDatum(item);
535 for (i = 0; i < ARRNELEM(bgm); i++)
536 pfree(DatumGetPointer(d[i]));
540 PG_FREE_IF_COPY(in, 0);
542 PG_RETURN_POINTER(a);
546 cnt_sml_bigm(BIGM *bgm1, BIGM *bgm2)
557 len1 = ARRNELEM(bgm1);
558 len2 = ARRNELEM(bgm2);
560 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
561 if (len1 <= 0 || len2 <= 0)
564 while (ptr1 - GETARR(bgm1) < len1 && ptr2 - GETARR(bgm2) < len2)
566 int res = CMPBIGM(ptr1, ptr2);
581 return ((float4) count) / ((float4) (len1 + len2 - count));
583 return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
588 bigm_similarity(PG_FUNCTION_ARGS)
590 text *in1 = PG_GETARG_TEXT_P(0);
591 text *in2 = PG_GETARG_TEXT_P(1);
596 bgm1 = generate_bigm(VARDATA(in1), VARSIZE(in1) - VARHDRSZ);
597 bgm2 = generate_bigm(VARDATA(in2), VARSIZE(in2) - VARHDRSZ);
599 res = cnt_sml_bigm(bgm1, bgm2);
603 PG_FREE_IF_COPY(in1, 0);
604 PG_FREE_IF_COPY(in2, 1);
606 PG_RETURN_FLOAT4(res);
610 likequery(PG_FUNCTION_ARGS)
612 text *query = PG_GETARG_TEXT_PP(0);
620 str = VARDATA_ANY(query);
621 len = VARSIZE_ANY_EXHDR(query);
626 result = (text *) palloc(len * 2 + 2 + VARHDRSZ);
627 rp = VARDATA(result);
630 for (sp = str; (sp - str) < len;)
632 if (ISWILDCARDCHAR(sp) || ISESCAPECHAR(sp))
637 else if (IS_HIGHBIT_SET(*sp))
639 mblen = pg_mblen(sp);
640 memcpy(rp, sp, mblen);
649 SET_VARSIZE(result, rp - VARDATA(result) + VARHDRSZ);
651 PG_RETURN_TEXT_P(result);
655 bigmstrcmp(char *arg1, int len1, char *arg2, int len2)
658 int len = Min(len1, len2);
660 for (i = 0; i < len; i++, arg1++, arg2++)
670 return (len1 == len2) ? 0 : ((len1 < len2) ? -1 : 1);
674 bigmtextcmp(PG_FUNCTION_ARGS)
676 text *arg1 = PG_GETARG_TEXT_PP(0);
677 text *arg2 = PG_GETARG_TEXT_PP(1);
678 char *a1p = VARDATA_ANY(arg1);
679 char *a2p = VARDATA_ANY(arg2);
680 int len1 = VARSIZE_ANY_EXHDR(arg1);
681 int len2 = VARSIZE_ANY_EXHDR(arg2);
683 PG_RETURN_INT32(bigmstrcmp(a1p, len1, a2p, len2));