1 /*-------------------------------------------------------------------------
3 * Copyright (c) 2016-2019, ludia_funcs Development Group
4 * Copyright (c) 2006-2015, NTT DATA Corporation
9 * Update Ludia functions so that they are available with PostgreSQL9.1.
10 * Author: NTT DATA Corporation
12 *-------------------------------------------------------------------------
17 #include <sys/types.h>
21 #include "catalog/pg_type.h"
24 #include "ludia_funcs.h"
25 #include "mb/pg_wchar.h"
27 #include "storage/fd.h"
28 #include "utils/builtins.h"
29 #include "utils/guc.h"
30 #include "miscadmin.h"
32 #if PG_VERSION_NUM >= 90300
33 #include "access/htup_details.h"
38 /* Last update date of ludia_funcs */
39 #define PGS2_LAST_UPDATE "2019.10.04"
43 static bool pgs2_enable_debug = false;
45 static char *pgs2_last_update = NULL;
46 static int norm_cache_limit = -1;
47 static bool escape_snippet_keyword = false;
49 #define SEN_NORMALIZE_FLAGS 0
50 #define SEN_MAX_N_EXPRS 32
52 /* upper limit for GUC variables measured in kilobytes of memory */
53 /* note that various places assume the byte size fits in a "long" variable */
54 #if SIZEOF_SIZE_T > 4 && SIZEOF_LONG > 4
55 #define MAX_KILOBYTES INT_MAX
57 #define MAX_KILOBYTES (INT_MAX / 1024)
60 #define ISBACKSLASHCHAR(x) (*(x) == '\\')
61 #define ISDOUBLEQUOTECHAR(x) (*(x) == '"')
62 #define ISSENNAOPSCHAR(x) (*(x) == '+' || *(x) == '-' || *(x) == ' ')
64 PG_FUNCTION_INFO_V1(pgs2snippet1);
65 PG_FUNCTION_INFO_V1(pgs2norm);
66 PG_FUNCTION_INFO_V1(pgs2textporter1);
67 PG_FUNCTION_INFO_V1(pgs2seninfo);
70 * The function prototypes are created as a part of PG_FUNCTION_INFO_V1
71 * macro since 9.4, and hence the declaration of the function prototypes
72 * here is necessary only for 9.3 or before.
74 #if PG_VERSION_NUM < 90400
75 Datum pgs2snippet1(PG_FUNCTION_ARGS);
76 Datum pgs2norm(PG_FUNCTION_ARGS);
77 Datum pgs2textporter1(PG_FUNCTION_ARGS);
78 Datum pgs2seninfo(PG_FUNCTION_ARGS);
81 static sen_encoding GetSennaEncoding(void);
82 static sen_query *GetSennaQuery(char *str, size_t len);
83 static bool EscapeSnippetKeyword(char **s, size_t *slen);
86 #define TEXTPORTER_TMPDIR "/tmp"
87 #define TEXTPORTER_MKSTEMP_UMASK 0177
88 #define TEXTPORTER_GROUPNAME "UTF-8"
89 #define TEXTPORTER_DEFLANGNAME "Japanese"
90 #define TEXTPORTER_BBIGENDIAN 1
91 #define TEXTPORTER_OPTION 0x00000020 /* DMC_GETTEXT_OPT_LF */
92 #define TEXTPORTER_OPTION_STRING "32"
93 #define TEXTPORTER_OPTION1 0x00010000 /* DMC_GETTEXT_OPT1_TXCONV */
94 #define TEXTPORTER_SIZE 0
95 #define TEXTPORTER_CSV_C 0
98 /* GUC variables for pgs2textpoter1 */
99 static int textporter_error = ERROR;
100 static unsigned int textporter_option = TEXTPORTER_OPTION;
103 * This variable is a dummy that doesn't do anything, except in some
104 * cases provides the value for SHOW to display. The real state is
105 * elsewhere and is kept in sync by assign_hooks.
107 static char *textporter_option_string;
109 static const struct config_enum_entry textporter_error_options[] = {
110 {"debug1", DEBUG1, false},
112 {"info", INFO, false},
113 {"notice", NOTICE, false},
114 {"warning", WARNING, false},
115 {"error", ERROR, false},
119 static void CleanupTextPorterTmpFiles(void);
121 static bool check_textporter_option(char **newval, void **extra, GucSource source);
122 static void assign_textporter_option(const char *newval, void *extra);
123 #endif /* TEXTPORTER */
134 /* Define custom GUC variable for debugging */
135 DefineCustomBoolVariable("ludia_funcs.enable_debug",
136 "Emit ludia_funcs debugging output.",
147 /* Can't be set in postgresql.conf */
148 DefineCustomStringVariable("ludia_funcs.last_update",
149 "Shows the last update date of ludia_funcs.",
154 GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
160 /* Define custom GUC variables */
161 DefineCustomEnumVariable("ludia_funcs.textporter_error",
162 "Sets the message levels that are emitted "
163 "when textporter fails.",
167 textporter_error_options,
174 DefineCustomStringVariable("ludia_funcs.textporter_option",
175 "Sets the option used to get text data "
178 &textporter_option_string,
179 TEXTPORTER_OPTION_STRING,
182 check_textporter_option,
183 assign_textporter_option,
186 /* Clean up remaining textporter temporary files */
187 CleanupTextPorterTmpFiles();
188 #endif /* TEXTPORTER */
191 * A value of 0 means no limit on the cache size. A value of -1 means
192 * that work_mem is used as the upper size limit of the cache.
194 DefineCustomIntVariable("ludia_funcs.norm_cache_limit",
195 "Sets the maximum memory to be used for caching "
196 "the result of pgs2norm()",
208 DefineCustomBoolVariable("ludia_funcs.escape_snippet_keyword",
209 "Escapes snippet keyword string.",
211 &escape_snippet_keyword,
219 EmitWarningsOnPlaceholders("ludia_funcs");
221 /* Initialize Senna */
223 if (rc != sen_success)
225 (errmsg("sen_init() failed: %d", rc)));
234 #define REMOVE_TMPFILE(path) \
236 if (unlink(path) != 0) \
238 (errcode_for_file_access(), \
239 errmsg("could not remove temporary file \"%s\": %m", path))); \
243 pgs2textporter1(PG_FUNCTION_ARGS)
245 char *appfile = text_to_cstring(PG_GETARG_TEXT_P(0));
246 char txtfile[] = TEXTPORTER_TMPDIR "/ludia_funcs_XXXXXX";
252 bool return_null = false;
255 /* Confirm that database encoding is UTF-8 */
261 * Generate a unique temporary filename where text data gotten
262 * from application file by TextPorter is stored temporarily.
263 * Set the permission of a temporary file to 0600 to ensure that
264 * only the owner of PostgreSQL server can read and write the file.
266 oumask = umask(TEXTPORTER_MKSTEMP_UMASK);
267 tmpfd = mkstemp(txtfile);
272 (errcode_for_file_access(),
273 errmsg("could not generate a unique temporary filename: %m")));
274 if (close(tmpfd) != 0)
276 (errcode_for_file_access(),
277 errmsg("could not close temporary file \"%s\": %m", txtfile)));
280 * Run TextPorter to read text data from application file (appfile)
281 * to temporary file (txtfile).
283 ret = ExecTextPorter((unsigned char *)appfile,
284 (unsigned char *)txtfile,
285 (unsigned char *)TEXTPORTER_GROUPNAME,
286 (unsigned char *)TEXTPORTER_DEFLANGNAME,
287 TEXTPORTER_BBIGENDIAN, textporter_option,
288 TEXTPORTER_OPTION1, TEXTPORTER_SIZE,
292 ereport(textporter_error,
293 (errmsg("could not get text from application file \"%s\"",
295 errdetail("DMC_GetText_V5() failed with errcode %d",
298 /* Return NULL if textporter_error is set to other than ERROR */
303 /* Read text data from temporary file to memory */
304 if (stat(txtfile, &statbuf))
306 (errcode_for_file_access(),
307 errmsg("could not stat file \"%s\": %m", txtfile)));
308 result = (text *) palloc(statbuf.st_size + VARHDRSZ);
310 fp = AllocateFile(txtfile, "r");
313 (errcode_for_file_access(),
314 errmsg("could not open file \"%s\": %m", txtfile)));
316 if (fread(VARDATA(result), 1, statbuf.st_size, fp) != statbuf.st_size ||
319 (errcode_for_file_access(),
320 errmsg("could not read file \"%s\": %m", txtfile)));
325 REMOVE_TMPFILE(txtfile);
330 REMOVE_TMPFILE(txtfile);
338 SET_VARSIZE(result, statbuf.st_size + VARHDRSZ);
340 PG_RETURN_TEXT_P(result);
344 * Clean up remaining textporter temporary files
347 CleanupTextPorterTmpFiles(void)
351 char path[MAXPGPATH];
353 tpdir = AllocateDir(TEXTPORTER_TMPDIR);
356 (errcode_for_file_access(),
357 errmsg("could not open textporter temporary file directory \"%s\": %m",
358 TEXTPORTER_TMPDIR)));
360 while ((tpde = ReadDir(tpdir, TEXTPORTER_TMPDIR)) != NULL)
362 if (strlen(tpde->d_name) == 18 &&
363 strncmp(tpde->d_name, "ludia_funcs_", 12) == 0)
365 snprintf(path, MAXPGPATH, TEXTPORTER_TMPDIR "/%s", tpde->d_name);
366 REMOVE_TMPFILE(path);
374 check_textporter_option(char **newval, void **extra, GucSource source)
378 unsigned int *myextra;
381 val = strtoul(*newval, &endptr, 0);
386 if (errno == ERANGE || val != (unsigned long) ((unsigned int) val))
388 GUC_check_errhint("Value exceeds unsigned integer range.");
392 /* Set up the "extra" struct actually used by assign_textporter_option */
393 myextra = (unsigned int *) malloc(sizeof(unsigned int));
396 GUC_check_errcode(ERRCODE_OUT_OF_MEMORY);
397 GUC_check_errmsg("out of memory");
400 *myextra = (unsigned int) val;
401 *extra = (void *) myextra;
407 assign_textporter_option(const char *newval, void *extra)
409 textporter_option = *((unsigned int *) extra);
412 #else /* TEXTPORTER */
415 pgs2textporter1(PG_FUNCTION_ARGS)
420 #endif /* TEXTPORTER */
423 GetSennaEncoding(void)
425 static sen_encoding encoding = sen_enc_default;
427 if (encoding == sen_enc_default)
429 if (GetDatabaseEncoding() == PG_UTF8)
430 encoding = sen_enc_utf8;
433 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
434 errmsg("does not support database encoding \"%s\"",
435 GetDatabaseEncodingName())));
441 * Escape the backslash and double quote characters in the given string.
443 * Return false if the given string has no character which needs to be
444 * escaped. Otherwise, return true. In this case, **s points the palloc'd
445 * space storing the escaped keyword string and *slen is set to the size
446 * of that string. The caller needs to free the palloc'd space.
449 EscapeSnippetKeyword(char **s, size_t *slen)
456 bool in_doublequote = false;
457 bool in_sennaops = false;
458 bool need_escape = false;
461 * Skip the heading double quote character because it always doesn't
462 * need to be interpreted as a character itself and be escaped.
463 * Note that we must not skip the heading character if it's not a
467 if (ISDOUBLEQUOTECHAR(sp))
471 * Check whether the snippet keyword string has a character which
472 * needs to be escaped.
474 while ((sp - *s) < *slen)
476 mblen = pg_mblen(sp);
479 * Backslash in the keyword always needs to be escaped.
481 if (ISBACKSLASHCHAR(sp))
489 if (ISSENNAOPSCHAR(sp))
492 in_doublequote = false;
497 * Double quote in the keyword needs to be escaped if
498 * any Senna search operators are to neither its right
507 if (ISDOUBLEQUOTECHAR(sp) && !in_sennaops)
508 in_doublequote = true;
509 if (!ISSENNAOPSCHAR(sp))
517 * Quick exit if the keyword has no character which needs to be
524 * Allocate the buffer space to store the escaped snippet keyword string.
525 * The maximum size of escaped string is double the input keyword size.
526 * The size reaches the maximum when every character in the input keyword
527 * needs to be escaped.
529 ep = escaped = (char *) palloc(*slen * 2);
532 * Copy the characters which have been passed through in the above loop
533 * and don't need to be escaped, into the buffer. If in_doublequote is
534 * true, we don't copy the double quote in the previous position into the
535 * buffer because it might still need to be escaped.
537 copylen = sp - *s - ((in_doublequote) ? 1 : 0);
538 memcpy(ep, *s, copylen);
542 * Construct the escaped snippet keyword string.
544 while ((sp - *s) < *slen)
546 mblen = pg_mblen(sp);
551 * dqchar indicates the previous character, that is a double
552 * quote. We assume here that a double quote is single-byte
555 char dqchar = *(sp - 1);
557 if (ISSENNAOPSCHAR(sp))
560 * Don't escape the double quote which is just before Senna
566 in_doublequote = false;
571 * Escape the double quote if no Senna operator is next to it.
576 if (ISDOUBLEQUOTECHAR(sp))
577 in_doublequote = true;
580 if (ISBACKSLASHCHAR(sp))
582 memcpy(ep, sp, mblen);
584 in_doublequote = false;
590 if (ISDOUBLEQUOTECHAR(sp))
593 * Don't escape the double quote which is just after Senna
599 in_doublequote = true;
603 if (ISBACKSLASHCHAR(sp))
606 * We don't check ISSENNAOPSCHAR() here. We handle Senna
607 * operator character as a character itself instead of
608 * an operator if it doesn't follow a double quote.
610 memcpy(ep, sp, mblen);
614 if (!ISSENNAOPSCHAR(sp))
621 /* Add the tailing double quote into the buffer */
629 if (pgs2_enable_debug)
631 char *tmp = pnstrdup(*s, *slen);
633 elog(LOG, "escaped snippet keyword: %s", tmp);
642 GetSennaQuery(char *str, size_t len)
644 static sen_query *query_cache = NULL;
645 static char *key_cache = NULL;
646 static size_t len_cache = 0;
647 static bool guc_cache = false;
649 sen_encoding encoding;
653 bool needfree = false;
656 * Return the cached Senna query if the same keyword has
657 * been used the last time.
659 if (key_cache != NULL &&
661 strncmp(key_cache, str, len) == 0 &&
662 escape_snippet_keyword == guc_cache)
665 if (pgs2_enable_debug)
667 char *tmp = pnstrdup(str, len);
669 elog(LOG, "GetSennaQuery(): quick exit: %s", tmp);
676 encoding = GetSennaEncoding();
681 (errcode(ERRCODE_OUT_OF_MEMORY),
682 errmsg("out of memory")));
685 * We always cache the unescaped keyword. Which enables us
686 * to check whether we can use the cached Senna query before
687 * escaping the keyword.
689 memcpy(key, str, len);
693 * If the keyword has been escaped, 'str' points to the
694 * newly-palloc'd space storing the escaped keyword. This
695 * space needs to be freed later.
697 if (escape_snippet_keyword)
698 needfree = EscapeSnippetKeyword(&str, &len);
700 query = sen_query_open(str, len, sen_sel_or, SEN_MAX_N_EXPRS,
706 (errmsg("sen_query_open() failed")));
709 if ((rest = sen_query_rest(query, NULL)) != 0)
711 (errmsg("too many expressions (%d)", rest)));
713 if (query_cache != NULL)
715 sen_query_close(query_cache);
722 guc_cache = escape_snippet_keyword;
731 pgs2snippet1(PG_FUNCTION_ARGS)
733 int flags = PG_GETARG_INT32(0);
734 uint32 width = PG_GETARG_UINT32(1);
735 uint32 max_results = PG_GETARG_UINT32(2);
736 text *opentags = PG_GETARG_TEXT_P(3);
737 text *closetags = PG_GETARG_TEXT_P(4);
738 int mapping = PG_GETARG_INT32(5);
739 text *keywords = PG_GETARG_TEXT_P(6);
740 text *document = PG_GETARG_TEXT_P(7);
742 sen_snip *snip = NULL;
743 const char *opentags_str = VARDATA_ANY(opentags);
744 const char *closetags_str = VARDATA_ANY(closetags);
745 char *keywords_str = VARDATA_ANY(keywords);
746 char *document_str = VARDATA_ANY(document);
747 uint32 opentags_len = VARSIZE_ANY_EXHDR(opentags);
748 uint32 closetags_len = VARSIZE_ANY_EXHDR(closetags);
749 uint32 keywords_len = VARSIZE_ANY_EXHDR(keywords);
750 uint32 document_len = VARSIZE_ANY_EXHDR(document);
752 uint32 max_tagged_len = 0;
755 uint32 result_len = 0;
756 bool return_null = false;
758 query = GetSennaQuery(keywords_str, keywords_len);
760 snip = sen_query_snip(query, flags, width, max_results, 1,
761 &opentags_str, &opentags_len,
762 &closetags_str, &closetags_len,
763 mapping == 0 ? NULL : (sen_snip_mapping *)-1);
766 (errmsg("sen_query_snip() failed")));
770 rc = sen_snip_exec(snip, document_str, document_len,
771 &nresults, &max_tagged_len);
772 if (rc != sen_success)
774 (errmsg("sen_snip_exec() failed: %d", rc)));
776 result = (text *) palloc(max_tagged_len + VARHDRSZ);
778 rc = sen_snip_get_result(snip, 0, VARDATA(result), &result_len);
779 if (rc == sen_invalid_argument)
781 else if (rc != sen_success)
783 (errmsg("sen_snip_get_result() failed: %d", rc)));
787 sen_snip_close(snip);
792 sen_snip_close(snip);
797 SET_VARSIZE(result, max_tagged_len + VARHDRSZ);
799 PG_RETURN_TEXT_P(result);
803 * Make sure there is enough space for 'needed' more bytes.
805 * Sets **buf to the allocated space which can store the needed bytes if OK,
806 * NULL if failed to enlarge the space because 'needed' is larger than 'maxlen'.
809 pgs2malloc(void **buf, long *buflen, long needed, long maxlen)
812 if (pgs2_enable_debug)
813 elog(LOG, "pgs2malloc(): buflen %ld, needed %ld, maxlen %ld",
814 *buflen, needed, maxlen);
817 if (*buf != NULL && *buflen >= needed && (*buflen <= maxlen || maxlen == 0))
818 return; /* got enough space already */
821 * Release the already-allocated space since it's too small to
822 * store the needed bytes or larger than the upper limit.
832 * Don't allocate any space if the needed space is larger than
835 if (needed > maxlen && maxlen != 0)
839 * Allocate the space for the needed bytes.
841 * We don't want to allocate just a little more space with each enlarge;
842 * for efficiency, double the buffer size each time it overflows.
843 * Actually, we might need to more than double it if 'needed' is big...
845 * We check whether '*buflen' overflows each cycle to avoid infinite loop.
848 while (*buflen < needed && *buflen != 0)
852 * Clamp to maxlen in case we went past it. Note we are assuming
853 * here that maxlen <= LONG_MAX/2, else the above loop could
854 * overflow. We will still have *buflen >= needed.
856 if (*buflen > maxlen && maxlen != 0)
859 /* Guard against out-of-range '*buflen' value */
862 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
863 errmsg("out of memory"),
864 errdetail("Cannot enlarge buffer by %ld more bytes.",
867 *buf = (void *) malloc(*buflen);
870 (errcode(ERRCODE_OUT_OF_MEMORY),
871 errmsg("out of memory")));
875 pgs2norm(PG_FUNCTION_ARGS)
877 text *str = PG_GETARG_TEXT_PP(0);
878 char *s = VARDATA_ANY(str);
879 long slen = VARSIZE_ANY_EXHDR(str);
887 * norm_cache is the cache memory storing both input and normalized strings
888 * as the result of pgs2norm(). norm_cache_size is the size of norm_cache
889 * and its upper limit is specified by norm_cache_limit parameter. norm_result
890 * is the pointer to the normalized string with the verlena header (i.e.,
891 * text type) stored in the latter half of the cache. norm_reslen is the size
892 * of norm_result. norm_slen is the size of the input string which is stored
893 * in the first half of the cache.
895 static char *norm_cache = NULL;
896 static long norm_cache_size = 0;
897 static long norm_slen = 0;
898 static char *norm_result = NULL;
899 static long norm_reslen = 0;
902 * Return the cached normalization result if the same string of
903 * the given one has been normalized the last time.
905 if (norm_cache != NULL &&
907 strncmp(norm_cache, s, slen) == 0)
910 if (pgs2_enable_debug)
912 char *tmp = text_to_cstring(str);
914 elog(LOG, "pgs2norm(): quick exit: %s", tmp);
919 result = (text *) palloc(norm_reslen);
920 memcpy(result, norm_result, norm_reslen);
921 PG_RETURN_TEXT_P(result);
924 /* Confirm that database encoding is UTF-8 */
928 * Allocate the result buffer to store the normalized string. Since the size of
929 * normalized string can be larger than that of input one, the result buffer needs
930 * extra space. Problem is that, before calling sen_str_normalize, we need to
931 * allocate the result buffer but cannot know how large extra space is required.
932 * So we use RESULT_EXTRA_SIZE as the estimated size of extra space here.
934 #define RESULT_EXTRA_SIZE 64
935 buflen = slen + RESULT_EXTRA_SIZE;
938 result = (text *) palloc(buflen + VARHDRSZ);
940 #if defined(FAST_SENNA)
941 reslen = fast_sen_str_normalize(s, slen, VARDATA(result), buflen);
943 reslen = sen_str_normalize(s, slen, sen_enc_utf8,
945 VARDATA(result), buflen);
950 (errmsg("could not normalize the string")));
953 * If the result buffer size is too short to store the normalized string,
954 * we enlarge the buffer and retry the string normalization.
956 if (buflen <= reslen)
963 SET_VARSIZE(result, reslen + VARHDRSZ);
966 * Cache both input and normalized strings to accelerate the subsequent
967 * calls of pgs2norm() with the same input string. But we don't do that
968 * if the maximum allowed size of the cache is too small to store them.
970 needed = slen + reslen + VARHDRSZ;
971 maxlen = ((norm_cache_limit >= 0) ? norm_cache_limit : work_mem) * 1024L;
973 pgs2malloc((void **) &norm_cache, &norm_cache_size, needed, maxlen);
974 if (norm_cache != NULL)
976 /* Store the input string into the first half of the cache */
978 memcpy(norm_cache, s, slen);
981 * Store the normalized string with the varlena header (i.e., text type)
982 * into the latter half of the cache.
984 norm_result = norm_cache + slen;
985 norm_reslen = reslen + VARHDRSZ;
986 memcpy(norm_result, result, norm_reslen);
990 if (pgs2_enable_debug)
992 char *tmp = text_to_cstring(str);
994 elog(LOG, "pgs2norm(): complete (%s result cache): %s",
995 (norm_cache == NULL) ? "unset" : "set", tmp);
1000 PG_RETURN_TEXT_P(result);
1004 * Report the version and configure options of Senna which
1005 * ludia_funcs depends on.
1008 pgs2seninfo(PG_FUNCTION_ARGS)
1010 char *version[MAXPGPATH];
1011 char *coptions[MAXPGPATH];
1018 * Get the version and configure options of Senna. Ignore the
1019 * return value of sen_info() because it always returns a success.
1021 sen_info((char **)&version, (char **)&coptions, NULL, NULL, NULL, NULL);
1024 * Construct a tuple descriptor for the result row. This must
1025 * match this function's ludia_funcs--x.x.sql entry.
1027 #if PG_VERSION_NUM >= 120000
1028 tupdesc = CreateTemplateTupleDesc(2);
1030 tupdesc = CreateTemplateTupleDesc(2, false);
1032 TupleDescInitEntry(tupdesc, (AttrNumber) 1,
1033 "version", TEXTOID, -1, 0);
1034 TupleDescInitEntry(tupdesc, (AttrNumber) 2,
1035 "configure_options", TEXTOID, -1, 0);
1036 tupdesc = BlessTupleDesc(tupdesc);
1039 values[0] = CStringGetTextDatum(*version);
1042 /* configure option */
1043 values[1] = CStringGetTextDatum(*coptions);
1046 tuple = heap_form_tuple(tupdesc, values, isnull);
1047 PG_RETURN_DATUM(HeapTupleGetDatum(tuple));