// QDB_DBMS_GEN_MANAGED_SKELETON
|
// Generated implementation scaffold. Business logic must be implemented manually.
|
|
#include "dbms_vector_chain.hpp"
|
#include "dbms_vector_chain_common.hpp"
|
|
#include <libxml/HTMLparser.h>
|
#include <libxml/parser.h>
|
#include <libxml/xpath.h>
|
#include <libxml/xpathInternals.h>
|
|
extern "C"
|
{
|
#include <unistd.h>
|
#include <string.h>
|
#include <sys/wait.h>
|
#include <errno.h>
|
#include <poll.h>
|
#include "miscadmin.h"
|
#include "storage/fd.h"
|
#include "utils/wait_event.h"
|
#include "utils/builtins.h"
|
#include "utils/jsonb.h"
|
#include "utils/numeric.h"
|
#include "catalog/pg_type.h"
|
#include "utils/palloc.h"
|
#include "utils/elog.h"
|
} // extern "C"
|
|
namespace
|
{
|
constexpr const char* kDbmsVectorChainPreferenceProfileValue = "PROFILE";
|
constexpr const char* kDbmsVectorChainPreferenceChunkerValue = "CHUNKER";
|
constexpr const char* kDbmsVectorChainPreferenceEmbedderValue = "EMBEDDER";
|
constexpr const char* kDbmsVectorChainPreferenceIndexValue = "INDEX";
|
constexpr int32 kDbmsVectorChainExcpCredNotExistValue = -20001;
|
constexpr int32 kDbmsVectorChainExcpProviderErrValue = -20002;
|
constexpr int32 kDbmsVectorChainExcpGuErrValue = -20003;
|
} // namespace
|
|
extern "C"
|
{
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_hybrid_search);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_similar);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_chunks_0);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_chunks_1);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_embedding);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_embeddings_0);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_embeddings_1);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_generate_text);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_summary);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_text_0);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_text_1);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_preference_profile);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_preference_chunker);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_preference_embedder);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_preference_index);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_excp_cred_not_exist);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_excp_provider_err);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_excp_gu_err);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_get_version);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_mock);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_add_credential);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_create_lang_data);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_create_preference);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_add_vocabulary);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_del_credential);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_drop_lang_data);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_drop_preference);
|
PG_FUNCTION_INFO_V1(dbms_vector_chain_drop_vocabulary);
|
} // extern "C"
|
|
#define RUDB_DBMS_VECTOR_CHAIN_VERSION "1.0.0"
|
|
static void
|
dbms_vector_chain_raise_stub_error(const char* message)
|
{
|
ereport(ERROR, (errmsg("%s", message)));
|
}
|
|
Datum dbms_vector_chain_hybrid_search(PG_FUNCTION_ARGS)
|
{
|
/*
|
* TODO: функция пока не реализована; чтение аргументов оставлено
|
* ниже как подсказка для разработчика. Раскомментируйте и
|
* адаптируйте эти строки при ручной реализации.
|
*/
|
// const int32 query_spec = PG_GETARG_INT32(0);
|
// (void) query_spec;
|
//
|
// RESULT return_value (json): вернуть как scalar result функции.
|
|
dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.HYBRID_SEARCH не реализована.");
|
PG_RETURN_NULL();
|
}
|
|
Datum dbms_vector_chain_similar(PG_FUNCTION_ARGS)
|
{
|
/*
|
* TODO: функция пока не реализована; чтение аргументов оставлено
|
* ниже как подсказка для разработчика. Раскомментируйте и
|
* адаптируйте эти строки при ручной реализации.
|
*/
|
// const text* index_name = PG_GETARG_TEXT_PP(0);
|
// (void) index_name;
|
//
|
// const text* vector_query = PG_GETARG_TEXT_PP(1);
|
// (void) vector_query;
|
//
|
// const int32 num_results = PG_GETARG_INT32(2);
|
// (void) num_results;
|
//
|
// const bool has_text_query = PG_NARGS() > 3 && !PG_ARGISNULL(3);
|
// const text* text_query_default = nullptr;
|
// if (!has_text_query) {
|
// /* default literal nullptr для text_query: NULL (source CSV) */
|
// (void) text_query_default;
|
// } else {
|
// (void) PG_GETARG_TEXT_PP(3);
|
// }
|
//
|
// const text* result_mode = PG_GETARG_TEXT_PP(4);
|
// (void) result_mode;
|
//
|
// const text* score_function = PG_GETARG_TEXT_PP(5);
|
// (void) score_function;
|
//
|
// RESULT return_value (json): вернуть как scalar result функции.
|
|
dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.SIMILAR не реализована.");
|
PG_RETURN_NULL();
|
}
|
|
Datum dbms_vector_chain_utl_to_chunks_0(PG_FUNCTION_ARGS)
|
{
|
if(PG_ARGISNULL(0))
|
PG_RETURN_NULL();
|
|
text *data = PG_GETARG_TEXT_PP(0);
|
text *parameters = PG_ARGISNULL(1) ? NULL : PG_GETARG_TEXT_PP(1);
|
dbms_vector_chain::ChunkParams *param = dbms_vector_chain::initChunkParams(parameters);
|
//dbms_vector_chain::printChunkParams(param);
|
if(param->by == dbms_vector_chain::CHUNK_BY_CHARACTERS){
|
ArrayType *result = dbms_vector_chain::chunk_for_chars(data, param);
|
PG_RETURN_ARRAYTYPE_P(result);
|
}
|
if(param->by == dbms_vector_chain::CHUNK_BY_WORDS){
|
ArrayType *result = dbms_vector_chain::chunk_for_words(data, param);
|
PG_RETURN_ARRAYTYPE_P(result);
|
}
|
if(param->by == dbms_vector_chain::CHUNK_BY_VOCABULARY){
|
ArrayType *result = dbms_vector_chain::chunk_for_vocabulary(data, param);
|
PG_RETURN_ARRAYTYPE_P(result);
|
}
|
|
|
ereport(ERROR, (errmsg("Некорректный параметр by")));
|
PG_RETURN_NULL();
|
}
|
|
Datum dbms_vector_chain_utl_to_chunks_1(PG_FUNCTION_ARGS)
|
{
|
/*
|
* ERROR: неподдерживаемый элемент сохранён как заглушка.
|
* ERROR: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация.
|
*/
|
/*
|
* TODO: функция пока не реализована; чтение аргументов оставлено
|
* ниже как подсказка для разработчика. Раскомментируйте и
|
* адаптируйте эти строки при ручной реализации.
|
*/
|
// const text* data = PG_GETARG_TEXT_PP(0);
|
// (void) data;
|
//
|
// const bool has_params = PG_NARGS() > 1 && !PG_ARGISNULL(1);
|
// const int32 params_default = 0;
|
// if (!has_params) {
|
// /* default literal 0 для params: NULL (source CSV) */
|
// (void) params_default;
|
// } else {
|
// (void) PG_GETARG_INT32(1);
|
// }
|
//
|
// RESULT return_value (text): вернуть как scalar result функции.
|
|
dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_CHUNKS не поддерживается: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация. Проверьте соответствующую запись в pg_proc.dat.");
|
PG_RETURN_NULL();
|
}
|
|
Datum dbms_vector_chain_utl_to_embedding(PG_FUNCTION_ARGS)
|
{
|
/*
|
* TODO: функция пока не реализована; чтение аргументов оставлено
|
* ниже как подсказка для разработчика. Раскомментируйте и
|
* адаптируйте эти строки при ручной реализации.
|
*/
|
// const text* data = PG_GETARG_TEXT_PP(0);
|
// (void) data;
|
//
|
// const bool has_params = PG_NARGS() > 1 && !PG_ARGISNULL(1);
|
// const int32 params_default = 0;
|
// if (!has_params) {
|
// /* default literal 0 для params: NULL (source CSV) */
|
// (void) params_default;
|
// } else {
|
// (void) PG_GETARG_INT32(1);
|
// }
|
//
|
// RESULT return_value (vector): вернуть как scalar result функции.
|
|
dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_EMBEDDING не реализована.");
|
PG_RETURN_NULL();
|
}
|
|
Datum dbms_vector_chain_utl_to_embeddings_0(PG_FUNCTION_ARGS)
|
{
|
/*
|
* ERROR: неподдерживаемый элемент сохранён как заглушка.
|
* ERROR: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация.
|
*/
|
/*
|
* TODO: функция пока не реализована; чтение аргументов оставлено
|
* ниже как подсказка для разработчика. Раскомментируйте и
|
* адаптируйте эти строки при ручной реализации.
|
*/
|
// const text* data = PG_GETARG_TEXT_PP(0);
|
// (void) data;
|
//
|
// const bool has_params = PG_NARGS() > 1 && !PG_ARGISNULL(1);
|
// const int32 params_default = 0;
|
// if (!has_params) {
|
// /* default literal 0 для params: NULL (source CSV) */
|
// (void) params_default;
|
// } else {
|
// (void) PG_GETARG_INT32(1);
|
// }
|
//
|
// RESULT return_value (text): вернуть как scalar result функции.
|
|
dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_EMBEDDINGS не поддерживается: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация. Проверьте соответствующую запись в pg_proc.dat.");
|
PG_RETURN_NULL();
|
}
|
|
Datum dbms_vector_chain_utl_to_embeddings_1(PG_FUNCTION_ARGS)
|
{
|
/*
|
* ERROR: неподдерживаемый элемент сохранён как заглушка.
|
* ERROR: тип TABLE не поддерживается текущим каталогом rudb.
|
* ERROR: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация.
|
*/
|
/*
|
* TODO: функция пока не реализована; чтение аргументов оставлено
|
* ниже как подсказка для разработчика. Раскомментируйте и
|
* адаптируйте эти строки при ручной реализации.
|
*/
|
// const text* data = PG_GETARG_TEXT_PP(0);
|
// (void) data;
|
//
|
// const int32 params = PG_GETARG_INT32(1);
|
// (void) params;
|
//
|
// RESULT return_value (text): вернуть как scalar result функции.
|
|
dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_EMBEDDINGS не поддерживается: тип TABLE не поддерживается текущим каталогом rudb.; Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация. Проверьте соответствующую запись в pg_proc.dat.");
|
PG_RETURN_NULL();
|
}
|
|
Datum dbms_vector_chain_utl_to_generate_text(PG_FUNCTION_ARGS)
|
{
|
/*
|
* DBMS_VECTOR_CHAIN.UTL_TO_GENERATE_TEXT(data clob, params json).
|
*
|
* Логика живёт в dbms_vector_chain::utl_to_generate_text()
|
* (dbms_vector_chain_common.cpp): credential читается из собственной
|
* таблицы пакета pg_catalog.dbms_vector_chain_credential_table, а не из
|
* "SYS".vector_credentials пакета DBMS_VECTOR.
|
*/
|
if (PG_ARGISNULL(0))
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("data must be specified"),
|
errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
|
|
text *data = PG_GETARG_TEXT_PP(0);
|
|
Jsonb *params = NULL;
|
|
if (PG_NARGS() > 1 && !PG_ARGISNULL(1))
|
{
|
/* SQL-тип params — json; приводим к jsonb через jsonb_in. */
|
text *params_text = PG_GETARG_TEXT_PP(1);
|
|
params = DatumGetJsonbP(DirectFunctionCall1(
|
jsonb_in, CStringGetDatum(text_to_cstring(params_text))));
|
}
|
|
char *result = dbms_vector_chain::utl_to_generate_text(
|
VARDATA_ANY(data), VARSIZE_ANY_EXHDR(data), params);
|
|
PG_RETURN_TEXT_P(cstring_to_text(result));
|
}
|
|
Datum dbms_vector_chain_utl_to_summary(PG_FUNCTION_ARGS)
|
{
|
/*
|
* TODO: функция пока не реализована; чтение аргументов оставлено
|
* ниже как подсказка для разработчика. Раскомментируйте и
|
* адаптируйте эти строки при ручной реализации.
|
*/
|
// const text* data = PG_GETARG_TEXT_PP(0);
|
// (void) data;
|
//
|
// const bool has_params = PG_NARGS() > 1 && !PG_ARGISNULL(1);
|
// const int32 params_default = 0;
|
// if (!has_params) {
|
// /* default literal 0 для params: NULL (source CSV) */
|
// (void) params_default;
|
// } else {
|
// (void) PG_GETARG_INT32(1);
|
// }
|
//
|
// RESULT return_value (clob): вернуть как scalar result функции.
|
|
dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_SUMMARY не реализована.");
|
PG_RETURN_NULL();
|
}
|
|
|
char *extract_text_from_html(const char *html, int size_html)
|
{
|
if (html == NULL || size_html <= 0)
|
return NULL;
|
|
/* 1. Парсим HTML из памяти */
|
htmlDocPtr doc = htmlReadMemory(html,
|
size_html,
|
nullptr, /* URL */
|
nullptr, /* encoding: пусть определит сам */
|
HTML_PARSE_NOERROR |
|
HTML_PARSE_NOWARNING |
|
HTML_PARSE_RECOVER);
|
if (doc == NULL)
|
return NULL;
|
|
/* 2. XPath-контекст */
|
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
|
if (xpathCtx == NULL)
|
{
|
xmlFreeDoc(doc);
|
return NULL;
|
}
|
|
/* 3. Выбираем все текстовые узлы внутри body.
|
* Если body нет (фрагмент), попробуем взять весь документ. */
|
xmlXPathObjectPtr result = xmlXPathEvalExpression(
|
BAD_CAST "//body//text()", xpathCtx);
|
|
if (result == NULL || result->nodesetval == NULL ||
|
result->nodesetval->nodeNr == 0)
|
{
|
if (result) xmlXPathFreeObject(result);
|
result = xmlXPathEvalExpression(
|
BAD_CAST "//text()", xpathCtx);
|
}
|
|
/* 4. Собираем текст в StringInfo */
|
StringInfoData buffer;
|
initStringInfo(&buffer);
|
|
if (result != NULL && result->nodesetval != NULL)
|
{
|
for (int i = 0; i < result->nodesetval->nodeNr; ++i)
|
{
|
xmlNodePtr node = result->nodesetval->nodeTab[i];
|
if (node == NULL)
|
continue;
|
|
/* Пропускаем содержимое <script> и <style> */
|
if (node->parent != NULL &&
|
node->parent->type == XML_ELEMENT_NODE)
|
{
|
const xmlChar *parentName = node->parent->name;
|
if (parentName != NULL &&
|
(xmlStrcasecmp(parentName, BAD_CAST "script") == 0 ||
|
xmlStrcasecmp(parentName, BAD_CAST "style") == 0))
|
{
|
continue;
|
}
|
}
|
|
xmlChar *content = xmlNodeGetContent(node);
|
if (content != NULL)
|
{
|
appendStringInfoString(&buffer,
|
reinterpret_cast<const char *>(content));
|
xmlFree(content);
|
}
|
}
|
}
|
|
/* 5. Освобождаем ресурсы libxml2 */
|
if (result) xmlXPathFreeObject(result);
|
xmlXPathFreeContext(xpathCtx);
|
xmlFreeDoc(doc);
|
|
return buffer.data;
|
}
|
|
char *extract_text_from_xml(const char *xml, int size_xml)
|
{
|
if (xml == NULL || size_xml <= 0)
|
return NULL;
|
|
/* 1. Парсим XML из памяти */
|
xmlDocPtr doc = xmlReadMemory(xml,
|
size_xml,
|
nullptr, /* URL */
|
nullptr, /* encoding: пусть определит сам */
|
XML_PARSE_NOERROR |
|
XML_PARSE_NOWARNING |
|
XML_PARSE_RECOVER);
|
if (doc == NULL)
|
return NULL;
|
|
/* 2. XPath-контекст */
|
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
|
if (xpathCtx == NULL)
|
{
|
xmlFreeDoc(doc);
|
return NULL;
|
}
|
|
/* 3. Выбираем все текстовые узлы документа.
|
* Извлекаются только текстовые поля (значения элементов и атрибутов
|
* не включаются). */
|
xmlXPathObjectPtr result = xmlXPathEvalExpression(
|
BAD_CAST "//text()", xpathCtx);
|
|
/* 4. Собираем текст в StringInfo */
|
StringInfoData buffer;
|
initStringInfo(&buffer);
|
|
if (result != NULL && result->nodesetval != NULL)
|
{
|
for (int i = 0; i < result->nodesetval->nodeNr; ++i)
|
{
|
xmlNodePtr node = result->nodesetval->nodeTab[i];
|
if (node == NULL)
|
continue;
|
|
/* Пропускаем содержимое комментариев, CDATA и PI */
|
if (node->type != XML_TEXT_NODE)
|
continue;
|
|
xmlChar *content = xmlNodeGetContent(node);
|
if (content != NULL)
|
{
|
appendStringInfoString(&buffer,
|
reinterpret_cast<const char *>(content));
|
xmlFree(content);
|
}
|
}
|
}
|
|
/* 5. Освобождаем ресурсы libxml2 */
|
if (result) xmlXPathFreeObject(result);
|
xmlXPathFreeContext(xpathCtx);
|
xmlFreeDoc(doc);
|
|
return buffer.data;
|
}
|
|
// text
|
char *extract_text_from_pdf(const char *buffer, Size buffer_len)
|
{
|
int in_fd[2] = {-1, -1};
|
int out_fd[2] = {-1, -1};
|
int err_fd[2] = {-1, -1};
|
pid_t pid = -1;
|
StringInfoData result;
|
|
initStringInfo(&result);
|
|
PG_TRY();
|
{
|
if (pipe(in_fd) < 0 || pipe(out_fd) < 0 || pipe(err_fd) < 0)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("could not create pipes for pdftotext: %m")));
|
|
pid = fork();
|
if (pid < 0)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("could not fork for pdftotext: %m")));
|
|
if (pid == 0)
|
{
|
struct sigaction sa;
|
memset(&sa, 0, sizeof(sa));
|
sa.sa_handler = SIG_DFL;
|
sigemptyset(&sa.sa_mask);
|
sigaction(SIGPIPE, &sa, NULL);
|
sigaction(SIGINT, &sa, NULL);
|
sigaction(SIGQUIT, &sa, NULL);
|
sigaction(SIGTERM, &sa, NULL);
|
sigaction(SIGHUP, &sa, NULL);
|
|
if (dup2(in_fd[0], STDIN_FILENO) < 0 ||
|
dup2(out_fd[1], STDOUT_FILENO) < 0 ||
|
dup2(err_fd[1], STDERR_FILENO) < 0)
|
_exit(127);
|
|
close(in_fd[0]); close(in_fd[1]);
|
close(out_fd[0]); close(out_fd[1]);
|
close(err_fd[0]); close(err_fd[1]);
|
|
execlp("pdftotext", "pdftotext", "-nopgbrk", "-enc", "UTF-8", "-", "-", (char *) NULL);
|
|
{
|
static const char msg[] = "failed to exec pdftotext\n";
|
(void) write(STDERR_FILENO, msg, sizeof(msg) - 1);
|
}
|
_exit(127);
|
}
|
|
close(in_fd[0]); in_fd[0] = -1;
|
close(out_fd[1]); out_fd[1] = -1;
|
close(err_fd[1]); err_fd[1] = -1;
|
|
StringInfoData errbuf;
|
initStringInfo(&errbuf);
|
|
Size written = 0;
|
bool in_open = true;
|
bool out_open = true;
|
bool err_open = true;
|
|
if (buffer_len == 0)
|
{
|
close(in_fd[1]); in_fd[1] = -1; in_open = false;
|
}
|
|
while (in_open || out_open || err_open)
|
{
|
struct pollfd pfds[3];
|
int idx_in = -1, idx_out = -1, idx_err = -1, nfds = 0;
|
|
if (in_open) { pfds[nfds].fd = in_fd[1];
|
pfds[nfds].events = POLLOUT;
|
pfds[nfds].revents = 0;
|
idx_in = nfds++; }
|
if (out_open) { pfds[nfds].fd = out_fd[0];
|
pfds[nfds].events = POLLIN;
|
pfds[nfds].revents = 0;
|
idx_out = nfds++; }
|
if (err_open) { pfds[nfds].fd = err_fd[0];
|
pfds[nfds].events = POLLIN;
|
pfds[nfds].revents = 0;
|
idx_err = nfds++; }
|
|
int prc = poll(pfds, nfds, -1);
|
if (prc < 0)
|
{
|
if (errno == EINTR)
|
{
|
CHECK_FOR_INTERRUPTS();
|
continue;
|
}
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("poll() failed while running pdftotext: %m")));
|
}
|
|
if (idx_in >= 0 && pfds[idx_in].revents)
|
{
|
if (pfds[idx_in].revents & (POLLERR | POLLHUP))
|
{
|
close(in_fd[1]); in_fd[1] = -1; in_open = false;
|
}
|
else if (pfds[idx_in].revents & POLLOUT)
|
{
|
ssize_t n = write(in_fd[1], buffer + written,
|
buffer_len - written);
|
if (n < 0)
|
{
|
if (errno == EINTR)
|
CHECK_FOR_INTERRUPTS();
|
else if (errno == EPIPE)
|
{
|
close(in_fd[1]); in_fd[1] = -1; in_open = false;
|
}
|
else
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("write to pdftotext failed: %m")));
|
}
|
else
|
{
|
written += (Size) n;
|
if (written >= buffer_len)
|
{
|
close(in_fd[1]); in_fd[1] = -1; in_open = false;
|
}
|
}
|
}
|
}
|
|
if (idx_out >= 0 &&
|
(pfds[idx_out].revents & (POLLIN | POLLHUP | POLLERR)))
|
{
|
char buf[8192];
|
ssize_t n = read(out_fd[0], buf, sizeof(buf));
|
if (n < 0)
|
{
|
if (errno == EINTR)
|
CHECK_FOR_INTERRUPTS();
|
else
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("read from pdftotext failed: %m")));
|
}
|
else if (n == 0)
|
{
|
close(out_fd[0]); out_fd[0] = -1; out_open = false;
|
}
|
else
|
appendBinaryStringInfo(&result, buf, n);
|
}
|
|
if (idx_err >= 0 &&
|
(pfds[idx_err].revents & (POLLIN | POLLHUP | POLLERR)))
|
{
|
char buf[1024];
|
ssize_t n = read(err_fd[0], buf, sizeof(buf));
|
if (n < 0)
|
{
|
if (errno == EINTR)
|
CHECK_FOR_INTERRUPTS();
|
else
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("read from pdftotext stderr failed: %m")));
|
}
|
else if (n == 0)
|
{
|
close(err_fd[0]); err_fd[0] = -1; err_open = false;
|
}
|
else if (errbuf.len < 16 * 1024)
|
appendBinaryStringInfo(&errbuf, buf, n);
|
}
|
}
|
|
int status = 0;
|
while (waitpid(pid, &status, 0) < 0)
|
{
|
if (errno == EINTR) { CHECK_FOR_INTERRUPTS(); continue; }
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("waitpid() for pdftotext failed: %m")));
|
}
|
pid = -1;
|
|
if (WIFSIGNALED(status))
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("pdftotext was terminated by signal %d",
|
WTERMSIG(status))));
|
|
if (!WIFEXITED(status))
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("pdftotext did not exit normally")));
|
|
int exitcode = WEXITSTATUS(status);
|
if (exitcode != 0)
|
{
|
if (exitcode == 127)
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_FILE),
|
errmsg("could not execute pdftotext: command not found or "
|
"not executable in PATH")));
|
else
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("pdftotext exited with code %d: %s",
|
exitcode,
|
errbuf.len > 0 ? errbuf.data : "no stderr output")));
|
}
|
|
return result.data;
|
}
|
PG_CATCH();
|
{
|
if (pid > 0)
|
{
|
(void) kill(pid, SIGKILL);
|
{
|
int st;
|
while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {}
|
}
|
}
|
if (in_fd[0] >= 0) close(in_fd[0]);
|
if (in_fd[1] >= 0) close(in_fd[1]);
|
if (out_fd[0] >= 0) close(out_fd[0]);
|
if (out_fd[1] >= 0) close(out_fd[1]);
|
if (err_fd[0] >= 0) close(err_fd[0]);
|
if (err_fd[1] >= 0) close(err_fd[1]);
|
PG_RE_THROW();
|
}
|
PG_END_TRY();
|
|
return NULL;
|
}
|
|
char *extract_html_from_pdf(const char *buffer, Size buffer_len)
|
{
|
File temp_file;
|
char *temp_filename;
|
FILE *pipe;
|
StringInfoData result;
|
char read_buf[4096];
|
size_t nread;
|
char command[MAXPGPATH];
|
int n;
|
|
/* 1. Создаём временный файл, который будет автоматически удалён
|
* при закрытии или при завершении транзакции. */
|
temp_file = OpenTemporaryFile(false);
|
if (temp_file < 0)
|
ereport(ERROR,
|
(errcode(ERRCODE_IO_ERROR),
|
errmsg("could not create temporary file: %m")));
|
|
/* 2. Получаем имя временного файла, чтобы передать его pdftohtml. */
|
temp_filename = FilePathName(temp_file);
|
if (temp_filename == NULL)
|
ereport(ERROR,
|
(errcode(ERRCODE_IO_ERROR),
|
errmsg("could not get temporary file name")));
|
|
ereport(NOTICE,
|
(errmsg("extract_html_from_pdf: buffer_len = %zu", buffer_len)));
|
/* 3. Записываем PDF-буфер во временный файл. */
|
if (FileWrite(temp_file, buffer, (int) buffer_len, (pgoff_t) 0,
|
WAIT_EVENT_BUFFILE_WRITE) != (int) buffer_len)
|
ereport(ERROR,
|
(errcode(ERRCODE_IO_ERROR),
|
errmsg("could not write to temporary file: %m")));
|
|
/* 4. Формируем команду для pdftohtml. */
|
n = snprintf(command, sizeof(command),
|
"pdftohtml -enc UTF-8 -stdout -s -i -noframes -q \"%s\"",
|
temp_filename);
|
if (n < 0 || n >= (int) sizeof(command))
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("pdftohtml command too long")));
|
|
/* 5. Запускаем pdftohtml и открываем pipe для чтения его stdout. */
|
pipe = OpenPipeStream(command, "r");
|
if (pipe == NULL)
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("could not execute pdftohtml: %m")));
|
|
/* 6. Читаем вывод pdftohtml в StringInfo. */
|
initStringInfo(&result);
|
while ((nread = fread(read_buf, 1, sizeof(read_buf), pipe)) > 0)
|
appendBinaryStringInfo(&result, read_buf, nread);
|
|
if (ferror(pipe))
|
{
|
ClosePipeStream(pipe);
|
ereport(ERROR,
|
(errcode(ERRCODE_IO_ERROR),
|
errmsg("error reading from pdftohtml: %m")));
|
}
|
|
/* 7. Закрываем pipe. ClosePipeStream возвращает -1 при ошибке. */
|
if (ClosePipeStream(pipe) != 0)
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("could not close pipe to pdftohtml: %m")));
|
|
/* 8. Закрываем временный файл – он будет автоматически удалён. */
|
FileClose(temp_file);
|
|
/* 9. Возвращаем извлечённый текст (HTML-вывод pdftohtml). */
|
return result.data;
|
}
|
|
bool hasHtml(const char *str)
|
{
|
const char *p;
|
const char *tag = "<html>";
|
|
if (str == NULL)
|
return false;
|
|
/* Пропускаем ведущие пробельные символы */
|
p = str;
|
while (*p != '\0' && isspace((unsigned char) *p))
|
p++;
|
|
/* Сравниваем с "<html>" без учёта регистра */
|
if(pg_strncasecmp(p, tag, 6)==0)
|
return true;
|
|
return false;
|
}
|
|
bool hasXml(const char *str)
|
{
|
if (str == NULL)
|
return false;
|
|
/* Пытаемся распарсить строку как XML.
|
* Если парсинг удался — считаем, что это XML. */
|
xmlDocPtr doc = xmlReadMemory(str,
|
strlen(str),
|
nullptr, /* URL */
|
nullptr, /* encoding: пусть определит сам */
|
XML_PARSE_NOERROR |
|
XML_PARSE_NOWARNING);
|
if (doc == NULL)
|
return false;
|
|
xmlFreeDoc(doc);
|
return true;
|
}
|
|
/*
|
* hasPdf
|
* Проверяет, является ли буфер PDF-документом по сигнатуре.
|
*
|
* Согласно спецификации PDF (ISO 32000-1, раздел 7.5.2), заголовок
|
* "%PDF-" должен находиться в первых 1024 байтах файла — перед ним
|
* допускается "мусор" (например, BOM или артефакты генератора).
|
*
|
* Параметры:
|
* buffer - указатель на данные (может быть NULL)
|
* len - длина буфера в байтах
|
*
|
* Возвращает true, если сигнатура "%PDF-" найдена в первых 1024 байтах.
|
*/
|
bool hasPdf(const char *buffer, Size len)
|
{
|
static const char magic[] = "%PDF-";
|
const Size magic_len = sizeof(magic) - 1; /* 5, без '\0' */
|
Size limit;
|
const char *p;
|
const char *end;
|
|
if (buffer == NULL || len < magic_len)
|
return false;
|
|
/* По спеке заголовок должен быть в первых 1024 байтах */
|
limit = Min(len, (Size) 1024);
|
end = buffer + limit;
|
|
for (p = buffer; p + magic_len <= end; p++)
|
{
|
if (memcmp(p, magic, magic_len) == 0)
|
return true;
|
}
|
|
return false;
|
}
|
|
Datum dbms_vector_chain_utl_to_text_0(PG_FUNCTION_ARGS)
|
{
|
if(PG_ARGISNULL(0))
|
PG_RETURN_NULL();
|
|
text *data = PG_GETARG_TEXT_PP(0);
|
text *parameters = PG_ARGISNULL(1) ? NULL : PG_GETARG_TEXT_PP(1);
|
bool plaintext = true; // значение по умолчанию
|
char *charset = NULL;
|
Size buffer_len = VARSIZE_ANY_EXHDR(data);
|
char *buffer = VARDATA_ANY(data);
|
|
if (parameters != NULL)
|
{
|
Datum options;
|
Jsonb *jb;
|
|
/* json хранится как text — превращаем в jsonb для удобного доступа */
|
options = DirectFunctionCall1(jsonb_in,
|
CStringGetDatum(text_to_cstring(parameters)));
|
jb = DatumGetJsonbP(options);
|
|
plaintext = dbms_vector_chain::jsonGetBoolParam("plaintext", jb, true);
|
charset = dbms_vector_chain::jsonGetStringParam("charset", jb);
|
}
|
|
//elog(NOTICE, "plaintext: %s", plaintext ? "true" : "false");
|
//elog(NOTICE, "charset: %s", charset ? charset : "NULL");
|
|
// если charset задан, пропускается только UTF8
|
if(charset){
|
if(pg_strcasecmp(charset, "UTF8")!=0){
|
ereport(ERROR, (errmsg("недопустимое значение %s для charset", charset)));
|
PG_RETURN_NULL();
|
}
|
}
|
char *data_str = text_to_cstring(data);
|
if(hasHtml(data_str) && plaintext){
|
char *html_text = extract_text_from_html(data_str, strlen(data_str));
|
text *txt_result;
|
if(html_text){
|
txt_result = cstring_to_text(html_text);
|
pfree(html_text);
|
}
|
else{
|
// пустая строка
|
const char *empty_str = "";
|
txt_result = cstring_to_text(empty_str);
|
}
|
PG_RETURN_TEXT_P(txt_result);
|
}
|
else if(hasXml(data_str) && plaintext){
|
char *xml_text = extract_text_from_xml(data_str, strlen(data_str));
|
text *txt_result;
|
if(xml_text){
|
txt_result = cstring_to_text(xml_text);
|
pfree(xml_text);
|
}
|
else{
|
// пустая строка
|
const char *empty_str = "";
|
txt_result = cstring_to_text(empty_str);
|
}
|
PG_RETURN_TEXT_P(txt_result);
|
}
|
else if(hasPdf(buffer, buffer_len)){
|
text *txt_result;
|
char *pdf_text = plaintext ? extract_text_from_pdf(buffer, buffer_len) :
|
extract_html_from_pdf(buffer, buffer_len);
|
|
|
if(pdf_text){
|
/* pdftotext всегда отдаёт UTF-8 (мы указали -enc UTF-8).
|
* Приводим к кодировке базы, если это необходимо. */
|
char *converted = pg_any_to_server(pdf_text,
|
strlen(pdf_text),
|
PG_UTF8);
|
|
txt_result = cstring_to_text(converted);
|
|
/* pg_any_to_server может вернуть либо исходный указатель,
|
* либо новый (palloc'ed). Освобождаем оба корректно. */
|
if (converted != pdf_text)
|
pfree(converted);
|
pfree(pdf_text);
|
}
|
else{
|
// пустая строка
|
const char *empty_str = "";
|
txt_result = cstring_to_text(empty_str);
|
}
|
PG_RETURN_TEXT_P(txt_result);
|
}
|
|
PG_RETURN_TEXT_P(data);
|
}
|
|
Datum dbms_vector_chain_utl_to_text_1(PG_FUNCTION_ARGS)
|
{
|
Datum result;
|
Size sz;
|
FunctionCallInfo fcinfo_data;
|
|
/* Под args[] — flexible array member, поэтому выделяем память
|
* под структуру + место под 2 аргумента. */
|
sz = SizeForFunctionCallInfo(2);
|
fcinfo_data = (FunctionCallInfo) palloc0(sz);
|
|
InitFunctionCallInfoData(*fcinfo_data, NULL, 2,
|
InvalidOid, NULL, NULL);
|
|
fcinfo_data->args[0].value = (Datum) 0;
|
fcinfo_data->args[0].isnull = true;
|
fcinfo_data->args[1].value = (Datum) 0;
|
fcinfo_data->args[1].isnull = true;
|
|
/* Первый аргумент: blob (bytea) -> clob (text).
|
* Так как clob — это домен над text, а bytea и text структурно
|
* идентичны (оба varlena), достаточно переинтерпретировать указатель. */
|
if (!PG_ARGISNULL(0))
|
{
|
fcinfo_data->args[0].value =
|
PointerGetDatum((text *) PG_GETARG_BYTEA_PP(0));
|
fcinfo_data->args[0].isnull = false;
|
}
|
|
/* Второй аргумент: json (хранится как text). */
|
if (!PG_ARGISNULL(1))
|
{
|
fcinfo_data->args[1].value = PG_GETARG_DATUM(1);
|
fcinfo_data->args[1].isnull = false;
|
}
|
|
|
/* Вызываем целевую функцию. Она получит корректные argnull-флаги
|
* и сможет через PG_ARGISNULL отличить NULL от валидного значения. */
|
result = dbms_vector_chain_utl_to_text_0(fcinfo_data);
|
|
if (fcinfo_data->isnull)
|
{
|
pfree(fcinfo_data);
|
PG_RETURN_NULL();
|
}
|
|
pfree(fcinfo_data);
|
PG_RETURN_DATUM(result);
|
}
|
|
Datum dbms_vector_chain_preference_profile(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_TEXT_P(cstring_to_text(kDbmsVectorChainPreferenceProfileValue));
|
}
|
|
Datum dbms_vector_chain_preference_chunker(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_TEXT_P(cstring_to_text(kDbmsVectorChainPreferenceChunkerValue));
|
}
|
|
Datum dbms_vector_chain_preference_embedder(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_TEXT_P(cstring_to_text(kDbmsVectorChainPreferenceEmbedderValue));
|
}
|
|
Datum dbms_vector_chain_preference_index(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_TEXT_P(cstring_to_text(kDbmsVectorChainPreferenceIndexValue));
|
}
|
|
Datum dbms_vector_chain_excp_cred_not_exist(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_INT32(kDbmsVectorChainExcpCredNotExistValue);
|
}
|
|
Datum dbms_vector_chain_excp_provider_err(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_INT32(kDbmsVectorChainExcpProviderErrValue);
|
}
|
|
Datum dbms_vector_chain_excp_gu_err(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_INT32(kDbmsVectorChainExcpGuErrValue);
|
}
|
|
Datum dbms_vector_chain_get_version(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_VECTOR_CHAIN_VERSION));
|
}
|
|
Datum dbms_vector_chain_mock(PG_FUNCTION_ARGS)
|
{
|
/*
|
* ERROR: generated package mock stub.
|
* ERROR: Эта функция является checkpoint-заглушкой и требует ручной реализации.
|
* ERROR: Generated package mock stub: функция DBMS_VECTOR_CHAIN.MOCK является заглушкой и требует ручной реализации.
|
*/
|
/*
|
* TODO: функция пока не реализована; чтение аргументов оставлено
|
* ниже как подсказка для разработчика. Раскомментируйте и
|
* адаптируйте эти строки при ручной реализации.
|
*/
|
// RESULT return_value (text): вернуть как scalar result функции.
|
|
dbms_vector_chain_raise_stub_error("Сгенерированная функция DBMS_VECTOR_CHAIN.MOCK является mock stub; требуется ручная реализация.");
|
PG_RETURN_NULL();
|
}
|
|
Datum dbms_vector_chain_add_credential(PG_FUNCTION_ARGS)
|
{
|
if(PG_ARGISNULL(0))
|
ereport(ERROR, (errmsg("credential_name not defined")));
|
if(PG_ARGISNULL(0))
|
ereport(ERROR, (errmsg("credential_name not defined")));
|
text *credential_name = PG_GETARG_TEXT_PP(0);
|
text *params = PG_GETARG_TEXT_PP(1);
|
dbms_vector_chain::create_credential(credential_name, params);
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_vector_chain_create_lang_data(PG_FUNCTION_ARGS)
|
{
|
text *params = PG_ARGISNULL(0) ? NULL : PG_GETARG_TEXT_PP(0);
|
|
dbms_vector_chain::create_lang_data(params);
|
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_vector_chain_create_preference(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0))
|
ereport(ERROR, (errmsg("pref_name not defined")));
|
if (PG_ARGISNULL(1))
|
ereport(ERROR, (errmsg("pref_type not defined")));
|
|
char *pref_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
char *pref_type = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
text *params = PG_ARGISNULL(2) ? NULL : PG_GETARG_TEXT_PP(2);
|
|
dbms_vector_chain::create_preference(pref_name, pref_type, params);
|
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_vector_chain_add_vocabulary(PG_FUNCTION_ARGS)
|
{
|
if(PG_ARGISNULL(0))
|
dbms_vector_chain_raise_stub_error("недопустимый идентификатор");
|
|
text *parameters = PG_ARGISNULL(0) ? NULL : PG_GETARG_TEXT_PP(0);
|
dbms_vector_chain::VocabularyParams *param = dbms_vector_chain::initVocabularyParams(parameters);
|
dbms_vector_chain::create_vocabulary(param);
|
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_vector_chain_del_credential(PG_FUNCTION_ARGS)
|
{
|
if(PG_ARGISNULL(0))
|
dbms_vector_chain_raise_stub_error("недопустимый идентификатор");
|
text *credential_name = PG_GETARG_TEXT_PP(0);
|
dbms_vector_chain::drop_credential(credential_name);
|
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_vector_chain_drop_lang_data(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0))
|
ereport(ERROR,
|
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
|
errmsg("language name must not be null")));
|
|
char *pref_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
|
dbms_vector_chain::drop_lang_data(pref_name);
|
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_vector_chain_drop_preference(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0))
|
ereport(ERROR, (errmsg("pref_name not defined")));
|
|
char *pref_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
|
dbms_vector_chain::drop_preference(pref_name);
|
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_vector_chain_del_vocabulary(PG_FUNCTION_ARGS)
|
{
|
if(PG_ARGISNULL(0))
|
dbms_vector_chain_raise_stub_error("недопустимый идентификатор");
|
text *vocabulary_name = PG_ARGISNULL(0) ? NULL : PG_GETARG_TEXT_PP(0);
|
dbms_vector_chain::drop_vocabulary(vocabulary_name);
|
PG_RETURN_VOID();
|
}
|