1 /*-------------------------------------------------------------------------
3 * Copyright (c) 2006-2013, NTT DATA Corporation
8 * Update Ludia functions so that they are available with PostgreSQL9.1.
9 * Author: NTT DATA Corporation
11 *-------------------------------------------------------------------------
16 #include <sys/types.h>
20 #include "catalog/pg_type.h"
23 #include "ludia_funcs.h"
24 #include "mb/pg_wchar.h"
26 #include "storage/fd.h"
27 #include "utils/builtins.h"
28 #include "utils/guc.h"
29 #include "miscadmin.h"
33 /* Last update date of ludia_funcs */
34 #define PGS2_LAST_UPDATE "2013.04.05"
38 static bool pgs2_enable_debug = false;
40 static char *pgs2_last_update = NULL;
41 static int norm_cache_limit = -1;
42 static bool escape_snippet_keyword = false;
44 #define SEN_NORMALIZE_FLAGS 0
45 #define SEN_MAX_N_EXPRS 32
47 /* upper limit for GUC variables measured in kilobytes of memory */
48 /* note that various places assume the byte size fits in a "long" variable */
49 #if SIZEOF_SIZE_T > 4 && SIZEOF_LONG > 4
50 #define MAX_KILOBYTES INT_MAX
52 #define MAX_KILOBYTES (INT_MAX / 1024)
55 #define ISBACKSLASHCHAR(x) (*(x) == '\\')
56 #define ISDOUBLEQUOTECHAR(x) (*(x) == '"')
57 #define ISSENNAOPSCHAR(x) (*(x) == '+' || *(x) == '-' || *(x) == ' ')
59 PG_FUNCTION_INFO_V1(pgs2snippet1);
60 Datum pgs2snippet1(PG_FUNCTION_ARGS);
61 PG_FUNCTION_INFO_V1(pgs2norm);
62 Datum pgs2norm(PG_FUNCTION_ARGS);
63 PG_FUNCTION_INFO_V1(pgs2textporter1);
64 Datum pgs2textporter1(PG_FUNCTION_ARGS);
65 PG_FUNCTION_INFO_V1(pgs2seninfo);
66 Datum pgs2seninfo(PG_FUNCTION_ARGS);
68 static sen_encoding GetSennaEncoding(void);
69 static sen_query *GetSennaQuery(char *str, size_t len);
70 static bool EscapeSnippetKeyword(char **s, size_t *slen);
73 #define TEXTPORTER_TMPDIR "/tmp"
74 #define TEXTPORTER_GROUPNAME "UTF-8"
75 #define TEXTPORTER_DEFLANGNAME "Japanese"
76 #define TEXTPORTER_BBIGENDIAN 1
77 #define TEXTPORTER_OPTION 0x00000020 /* DMC_GETTEXT_OPT_LF */
78 #define TEXTPORTER_OPTION_STRING "32"
79 #define TEXTPORTER_OPTION1 0x00010000 /* DMC_GETTEXT_OPT1_TXCONV */
80 #define TEXTPORTER_SIZE 0
81 #define TEXTPORTER_CSV_C 0
83 /* GUC variables for pgs2textpoter1 */
84 static int textporter_error = ERROR;
85 static unsigned int textporter_option = TEXTPORTER_OPTION;
88 * This variable is a dummy that doesn't do anything, except in some
89 * cases provides the value for SHOW to display. The real state is
90 * elsewhere and is kept in sync by assign_hooks.
92 static char *textporter_option_string;
94 static const struct config_enum_entry textporter_error_options[] = {
95 {"debug1", DEBUG1, false},
97 {"info", INFO, false},
98 {"notice", NOTICE, false},
99 {"warning", WARNING, false},
100 {"error", ERROR, false},
104 static void CleanupTextPorterTmpFiles(void);
106 static bool check_textporter_option(char **newval, void **extra, GucSource source);
107 static void assign_textporter_option(const char *newval, void *extra);
108 #endif /* TEXTPORTER */
119 /* Define custom GUC variable for debugging */
120 DefineCustomBoolVariable("ludia_funcs.enable_debug",
121 "Emit ludia_funcs debugging output.",
132 /* Can't be set in postgresql.conf */
133 DefineCustomStringVariable("ludia_funcs.last_update",
134 "Shows the last update date of ludia_funcs.",
139 GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
145 /* Define custom GUC variables */
146 DefineCustomEnumVariable("ludia_funcs.textporter_error",
147 "Sets the message levels that are emitted "
148 "when textporter fails.",
152 textporter_error_options,
159 DefineCustomStringVariable("ludia_funcs.textporter_option",
160 "Sets the option used to get text data "
163 &textporter_option_string,
164 TEXTPORTER_OPTION_STRING,
167 check_textporter_option,
168 assign_textporter_option,
171 /* Clean up remaining textporter temporary files */
172 CleanupTextPorterTmpFiles();
173 #endif /* TEXTPORTER */
176 * A value of 0 means no limit on the cache size. A value of -1 means
177 * that work_mem is used as the upper size limit of the cache.
179 DefineCustomIntVariable("ludia_funcs.norm_cache_limit",
180 "Sets the maximum memory to be used for caching "
181 "the result of pgs2norm()",
193 DefineCustomBoolVariable("ludia_funcs.escape_snippet_keyword",
194 "Escapes snippet keyword string.",
196 &escape_snippet_keyword,
204 EmitWarningsOnPlaceholders("ludia_funcs");
206 /* Initialize Senna */
208 if (rc != sen_success)
210 (errmsg("sen_init() failed: %d", rc)));
219 #define REMOVE_TMPFILE(path) \
221 if (unlink(path) != 0) \
223 (errcode_for_file_access(), \
224 errmsg("could not remove temporary file \"%s\": %m", path))); \
228 pgs2textporter1(PG_FUNCTION_ARGS)
230 char *appfile = text_to_cstring(PG_GETARG_TEXT_P(0));
231 char txtfile[] = TEXTPORTER_TMPDIR "/ludia_funcs_XXXXXX";
237 bool return_null = false;
239 /* Confirm that database encoding is UTF-8 */
245 * Generate a unique temporary filename where text data gotten
246 * from application file by TextPorter is stored temporarily.
248 tmpfd = mkstemp(txtfile);
251 (errcode_for_file_access(),
252 errmsg("could not generate a unique temporary filename: %m")));
253 if (close(tmpfd) != 0)
255 (errcode_for_file_access(),
256 errmsg("could not close temporary file \"%s\": %m", txtfile)));
259 * Run TextPorter to read text data from application file (appfile)
260 * to temporary file (txtfile).
262 ret = ExecTextPorter((unsigned char *)appfile,
263 (unsigned char *)txtfile,
264 (unsigned char *)TEXTPORTER_GROUPNAME,
265 (unsigned char *)TEXTPORTER_DEFLANGNAME,
266 TEXTPORTER_BBIGENDIAN, textporter_option,
267 TEXTPORTER_OPTION1, TEXTPORTER_SIZE,
271 ereport(textporter_error,
272 (errmsg("could not get text from application file \"%s\"",
274 errdetail("DMC_GetText_V5() failed with errcode %d",
277 /* Return NULL if textporter_error is set to other than ERROR */
282 /* Read text data from temporary file to memory */
283 if (stat(txtfile, &statbuf))
285 (errcode_for_file_access(),
286 errmsg("could not stat file \"%s\": %m", txtfile)));
287 result = (text *) palloc(statbuf.st_size + VARHDRSZ);
289 fp = AllocateFile(txtfile, "r");
292 (errcode_for_file_access(),
293 errmsg("could not open file \"%s\": %m", txtfile)));
295 if (fread(VARDATA(result), 1, statbuf.st_size, fp) != statbuf.st_size ||
298 (errcode_for_file_access(),
299 errmsg("could not read file \"%s\": %m", txtfile)));
304 REMOVE_TMPFILE(txtfile);
309 REMOVE_TMPFILE(txtfile);
317 SET_VARSIZE(result, statbuf.st_size + VARHDRSZ);
319 PG_RETURN_TEXT_P(result);
323 * Clean up remaining textporter temporary files
326 CleanupTextPorterTmpFiles(void)
330 char path[MAXPGPATH];
332 tpdir = AllocateDir(TEXTPORTER_TMPDIR);
335 (errcode_for_file_access(),
336 errmsg("could not open textporter temporary file directory \"%s\": %m",
337 TEXTPORTER_TMPDIR)));
339 while ((tpde = ReadDir(tpdir, TEXTPORTER_TMPDIR)) != NULL)
341 if (strlen(tpde->d_name) == 18 &&
342 strncmp(tpde->d_name, "ludia_funcs_", 12) == 0)
344 snprintf(path, MAXPGPATH, TEXTPORTER_TMPDIR "/%s", tpde->d_name);
345 REMOVE_TMPFILE(path);
353 check_textporter_option(char **newval, void **extra, GucSource source)
357 unsigned int *myextra;
360 val = strtoul(*newval, &endptr, 0);
365 if (errno == ERANGE || val != (unsigned long) ((unsigned int) val))
367 GUC_check_errhint("Value exceeds unsigned integer range.");
371 /* Set up the "extra" struct actually used by assign_textporter_option */
372 myextra = (unsigned int *) malloc(sizeof(unsigned int));
375 GUC_check_errcode(ERRCODE_OUT_OF_MEMORY);
376 GUC_check_errmsg("out of memory");
379 *myextra = (unsigned int) val;
380 *extra = (void *) myextra;
386 assign_textporter_option(const char *newval, void *extra)
388 textporter_option = *((unsigned int *) extra);
391 #else /* TEXTPORTER */
394 pgs2textporter1(PG_FUNCTION_ARGS)
399 #endif /* TEXTPORTER */
402 GetSennaEncoding(void)
404 static sen_encoding encoding = sen_enc_default;
406 if (encoding == sen_enc_default)
408 if (GetDatabaseEncoding() == PG_UTF8)
409 encoding = sen_enc_utf8;
412 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
413 errmsg("does not support database encoding \"%s\"",
414 GetDatabaseEncodingName())));
420 * Escape the backslash and double quote characters in the given string.
422 * Return false if the given string has no character which needs to be
423 * escaped. Otherwise, return true. In this case, **s points the palloc'd
424 * space storing the escaped keyword string and *slen is set to the size
425 * of that string. The caller needs to free the palloc'd space.
428 EscapeSnippetKeyword(char **s, size_t *slen)
435 bool in_doublequote = false;
436 bool in_sennaops = false;
437 bool need_escape = false;
440 * Skip the heading double quote character because it always doesn't
441 * need to be interpreted as a character itself and be escaped.
442 * Note that we must not skip the heading character if it's not a
446 if (ISDOUBLEQUOTECHAR(sp))
450 * Check whether the snippet keyword string has a character which
451 * needs to be escaped.
453 while ((sp - *s) < *slen)
455 mblen = pg_mblen(sp);
458 * Backslash in the keyword always needs to be escaped.
460 if (ISBACKSLASHCHAR(sp))
468 if (ISSENNAOPSCHAR(sp))
471 in_doublequote = false;
476 * Double quote in the keyword needs to be escaped if
477 * any Senna search operators are to neither its right
486 if (ISDOUBLEQUOTECHAR(sp) && !in_sennaops)
487 in_doublequote = true;
488 if (!ISSENNAOPSCHAR(sp))
496 * Quick exit if the keyword has no character which needs to be
503 * Allocate the buffer space to store the escaped snippet keyword string.
504 * The maximum size of escaped string is double the input keyword size.
505 * The size reaches the maximum when every character in the input keyword
506 * needs to be escaped.
508 ep = escaped = (char *) palloc(*slen * 2);
511 * Copy the characters which have been passed through in the above loop
512 * and don't need to be escaped, into the buffer. If in_doublequote is
513 * true, we don't copy the double quote in the previous position into the
514 * buffer because it might still need to be escaped.
516 copylen = sp - *s - ((in_doublequote) ? 1 : 0);
517 memcpy(ep, *s, copylen);
521 * Construct the escaped snippet keyword string.
523 while ((sp - *s) < *slen)
525 mblen = pg_mblen(sp);
530 * dqchar indicates the previous character, that is a double
531 * quote. We assume here that a double quote is single-byte
534 char dqchar = *(sp - 1);
536 if (ISSENNAOPSCHAR(sp))
539 * Don't escape the double quote which is just before Senna
545 in_doublequote = false;
550 * Escape the double quote if no Senna operator is next to it.
555 if (ISDOUBLEQUOTECHAR(sp))
556 in_doublequote = true;
559 if (ISBACKSLASHCHAR(sp))
561 memcpy(ep, sp, mblen);
563 in_doublequote = false;
569 if (ISDOUBLEQUOTECHAR(sp))
572 * Don't escape the double quote which is just after Senna
578 in_doublequote = true;
582 if (ISBACKSLASHCHAR(sp))
585 * We don't check ISSENNAOPSCHAR() here. We handle Senna
586 * operator character as a character itself instead of
587 * an operator if it doesn't follow a double quote.
589 memcpy(ep, sp, mblen);
593 if (!ISSENNAOPSCHAR(sp))
600 /* Add the tailing double quote into the buffer */
608 if (pgs2_enable_debug)
610 char *tmp = pnstrdup(*s, *slen);
612 elog(LOG, "escaped snippet keyword: %s", tmp);
621 GetSennaQuery(char *str, size_t len)
623 static sen_query *query_cache = NULL;
624 static char *key_cache = NULL;
625 static size_t len_cache = 0;
626 static bool guc_cache = false;
628 sen_encoding encoding;
632 bool needfree = false;
635 * Return the cached Senna query if the same keyword has
636 * been used the last time.
638 if (key_cache != NULL &&
640 strncmp(key_cache, str, len) == 0 &&
641 escape_snippet_keyword == guc_cache)
644 if (pgs2_enable_debug)
646 char *tmp = pnstrdup(str, len);
648 elog(LOG, "GetSennaQuery(): quick exit: %s", tmp);
655 encoding = GetSennaEncoding();
660 (errcode(ERRCODE_OUT_OF_MEMORY),
661 errmsg("out of memory")));
664 * We always cache the unescaped keyword. Which enables us
665 * to check whether we can use the cached Senna query before
666 * escaping the keyword.
668 memcpy(key, str, len);
672 * If the keyword has been escaped, 'str' points to the
673 * newly-palloc'd space storing the escaped keyword. This
674 * space needs to be freed later.
676 if (escape_snippet_keyword)
677 needfree = EscapeSnippetKeyword(&str, &len);
679 query = sen_query_open(str, len, sen_sel_or, SEN_MAX_N_EXPRS,
685 (errmsg("sen_query_open() failed")));
688 if ((rest = sen_query_rest(query, NULL)) != 0)
690 (errmsg("too many expressions (%d)", rest)));
692 if (query_cache != NULL)
694 sen_query_close(query_cache);
701 guc_cache = escape_snippet_keyword;
710 pgs2snippet1(PG_FUNCTION_ARGS)
712 int flags = PG_GETARG_INT32(0);
713 uint32 width = PG_GETARG_UINT32(1);
714 uint32 max_results = PG_GETARG_UINT32(2);
715 text *opentags = PG_GETARG_TEXT_P(3);
716 text *closetags = PG_GETARG_TEXT_P(4);
717 int mapping = PG_GETARG_INT32(5);
718 text *keywords = PG_GETARG_TEXT_P(6);
719 text *document = PG_GETARG_TEXT_P(7);
721 sen_snip *snip = NULL;
722 const char *opentags_str = VARDATA_ANY(opentags);
723 const char *closetags_str = VARDATA_ANY(closetags);
724 char *keywords_str = VARDATA_ANY(keywords);
725 char *document_str = VARDATA_ANY(document);
726 uint32 opentags_len = VARSIZE_ANY_EXHDR(opentags);
727 uint32 closetags_len = VARSIZE_ANY_EXHDR(closetags);
728 uint32 keywords_len = VARSIZE_ANY_EXHDR(keywords);
729 uint32 document_len = VARSIZE_ANY_EXHDR(document);
731 uint32 max_tagged_len = 0;
734 uint32 result_len = 0;
735 bool return_null = false;
737 query = GetSennaQuery(keywords_str, keywords_len);
739 snip = sen_query_snip(query, flags, width, max_results, 1,
740 &opentags_str, &opentags_len,
741 &closetags_str, &closetags_len,
742 mapping == 0 ? NULL : (sen_snip_mapping *)-1);
745 (errmsg("sen_query_snip() failed")));
749 rc = sen_snip_exec(snip, document_str, document_len,
750 &nresults, &max_tagged_len);
751 if (rc != sen_success)
753 (errmsg("sen_snip_exec() failed: %d", rc)));
755 result = (text *) palloc(max_tagged_len + VARHDRSZ);
757 rc = sen_snip_get_result(snip, 0, VARDATA(result), &result_len);
758 if (rc == sen_invalid_argument)
760 else if (rc != sen_success)
762 (errmsg("sen_snip_get_result() failed: %d", rc)));
766 sen_snip_close(snip);
771 sen_snip_close(snip);
776 SET_VARSIZE(result, max_tagged_len + VARHDRSZ);
778 PG_RETURN_TEXT_P(result);
782 * Make sure there is enough space for 'needed' more bytes.
784 * Sets **buf to the allocated space which can store the needed bytes if OK,
785 * NULL if failed to enlarge the space because 'needed' is larger than 'maxlen'.
788 pgs2malloc(void **buf, long *buflen, long needed, long maxlen)
791 if (pgs2_enable_debug)
792 elog(LOG, "pgs2malloc(): buflen %ld, needed %ld, maxlen %ld",
793 *buflen, needed, maxlen);
796 if (*buf != NULL && *buflen >= needed && (*buflen <= maxlen || maxlen == 0))
797 return; /* got enough space already */
800 * Release the already-allocated space since it's too small to
801 * store the needed bytes or larger than the upper limit.
811 * Don't allocate any space if the needed space is larger than
814 if (needed > maxlen && maxlen != 0)
818 * Allocate the space for the needed bytes.
820 * We don't want to allocate just a little more space with each enlarge;
821 * for efficiency, double the buffer size each time it overflows.
822 * Actually, we might need to more than double it if 'needed' is big...
824 * We check whether '*buflen' overflows each cycle to avoid infinite loop.
827 while (*buflen < needed && *buflen != 0)
831 * Clamp to maxlen in case we went past it. Note we are assuming
832 * here that maxlen <= LONG_MAX/2, else the above loop could
833 * overflow. We will still have *buflen >= needed.
835 if (*buflen > maxlen && maxlen != 0)
838 /* Guard against out-of-range '*buflen' value */
841 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
842 errmsg("out of memory"),
843 errdetail("Cannot enlarge buffer by %ld more bytes.",
846 *buf = (void *) malloc(*buflen);
849 (errcode(ERRCODE_OUT_OF_MEMORY),
850 errmsg("out of memory")));
854 pgs2norm(PG_FUNCTION_ARGS)
856 text *str = PG_GETARG_TEXT_PP(0);
857 char *s = VARDATA_ANY(str);
858 long slen = VARSIZE_ANY_EXHDR(str);
866 * norm_cache is the cache memory storing both input and normalized strings
867 * as the result of pgs2norm(). norm_cache_size is the size of norm_cache
868 * and its upper limit is specified by norm_cache_limit parameter. norm_result
869 * is the pointer to the normalized string with the verlena header (i.e.,
870 * text type) stored in the latter half of the cache. norm_reslen is the size
871 * of norm_result. norm_slen is the size of the input string which is stored
872 * in the first half of the cache.
874 static char *norm_cache = NULL;
875 static long norm_cache_size = 0;
876 static long norm_slen = 0;
877 static char *norm_result = NULL;
878 static long norm_reslen = 0;
881 * Return the cached normalization result if the same string of
882 * the given one has been normalized the last time.
884 if (norm_cache != NULL &&
886 strncmp(norm_cache, s, slen) == 0)
889 if (pgs2_enable_debug)
891 char *tmp = text_to_cstring(str);
893 elog(LOG, "pgs2norm(): quick exit: %s", tmp);
898 PG_RETURN_TEXT_P(pnstrdup(norm_result, norm_reslen));
901 /* Confirm that database encoding is UTF-8 */
905 * Allocate the result buffer to store the normalized string. Since the size of
906 * normalized string can be larger than that of input one, the result buffer needs
907 * extra space. Problem is that, before calling sen_str_normalize, we need to
908 * allocate the result buffer but cannot know how large extra space is required.
909 * So we use RESULT_EXTRA_SIZE as the estimated size of extra space here.
911 #define RESULT_EXTRA_SIZE 64
912 buflen = slen + RESULT_EXTRA_SIZE;
915 result = (text *) palloc(buflen + VARHDRSZ);
917 #if defined(FAST_SENNA)
918 reslen = fast_sen_str_normalize(s, slen, VARDATA(result), buflen);
920 reslen = sen_str_normalize(s, slen, sen_enc_utf8,
922 VARDATA(result), buflen);
927 (errmsg("could not normalize the string")));
930 * If the result buffer size is too short to store the normalized string,
931 * we enlarge the buffer and retry the string normalization.
933 if (buflen <= reslen)
940 SET_VARSIZE(result, reslen + VARHDRSZ);
943 * Cache both input and normalized strings to accelerate the subsequent
944 * calls of pgs2norm() with the same input string. But we don't do that
945 * if the maximum allowed size of the cache is too small to store them.
947 needed = slen + reslen + VARHDRSZ;
948 maxlen = ((norm_cache_limit >= 0) ? norm_cache_limit : work_mem) * 1024L;
950 pgs2malloc((void **) &norm_cache, &norm_cache_size, needed, maxlen);
951 if (norm_cache != NULL)
953 /* Store the input string into the first half of the cache */
955 memcpy(norm_cache, s, slen);
958 * Store the normalized string with the varlena header (i.e., text type)
959 * into the latter half of the cache.
961 norm_result = norm_cache + slen;
962 norm_reslen = reslen + VARHDRSZ;
963 memcpy(norm_result, result, norm_reslen);
967 if (pgs2_enable_debug)
969 char *tmp = text_to_cstring(str);
971 elog(LOG, "pgs2norm(): complete (%s result cache): %s",
972 (norm_cache == NULL) ? "unset" : "set", tmp);
977 PG_RETURN_TEXT_P(result);
981 * Report the version and configure options of Senna which
982 * ludia_funcs depends on.
985 pgs2seninfo(PG_FUNCTION_ARGS)
987 char *version[MAXPGPATH];
988 char *coptions[MAXPGPATH];
995 * Get the version and configure options of Senna. Ignore the
996 * return value of sen_info() because it always returns a success.
998 sen_info((char **)&version, (char **)&coptions, NULL, NULL, NULL, NULL);
1001 * Construct a tuple descriptor for the result row. This must
1002 * match this function's ludia_funcs--x.x.sql entry.
1004 tupdesc = CreateTemplateTupleDesc(2, false);
1005 TupleDescInitEntry(tupdesc, (AttrNumber) 1,
1006 "version", TEXTOID, -1, 0);
1007 TupleDescInitEntry(tupdesc, (AttrNumber) 2,
1008 "configure_options", TEXTOID, -1, 0);
1009 tupdesc = BlessTupleDesc(tupdesc);
1012 values[0] = CStringGetTextDatum(*version);
1015 /* configure option */
1016 values[1] = CStringGetTextDatum(*coptions);
1019 tuple = heap_form_tuple(tupdesc, values, isnull);
1020 PG_RETURN_DATUM(HeapTupleGetDatum(tuple));