/* * dbms_report.cpp — частичная реализация пакета DBMS_REPORT. * Не реализованные экспортируемые функции завершаются ошибкой NOT_IMPLEMENTED. */ extern "C" { #include "postgres.h" #include "fmgr.h" #include "utils/builtins.h" #include "lib/stringinfo.h" #include #include #include #include "funcapi.h" #include "access/htup_details.h" } #include #include #include "dbms_report.hpp" #include #include #include /// Преобразует text* в std::string inline std::string text_to_std_string(text* t) { char* c = text_to_cstring(t); std::string s(c); pfree(c); return s; } /// Кодирует бинарные данные в Base64 (строка ASCII) static const char B64_TABLE[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; inline std::string base64_encode_bytes(const std::string& in) { std::string out; out.reserve(((in.size() + 2) / 3) * 4); size_t i = 0; while (i + 3 <= in.size()) { unsigned a = (unsigned char)in[i++]; unsigned b = (unsigned char)in[i++]; unsigned c = (unsigned char)in[i++]; out.push_back(B64_TABLE[a >> 2]); out.push_back(B64_TABLE[((a & 3) << 4) | (b >> 4)]); out.push_back(B64_TABLE[((b & 0xF) << 2) | (c >> 6)]); out.push_back(B64_TABLE[c & 0x3F]); } size_t rem = in.size() - i; if (rem == 1) { unsigned a = (unsigned char)in[i++]; out.push_back(B64_TABLE[a >> 2]); out.push_back(B64_TABLE[(a & 3) << 4]); out.push_back('='); out.push_back('='); } else if (rem == 2) { unsigned a = (unsigned char)in[i++]; unsigned b = (unsigned char)in[i++]; out.push_back(B64_TABLE[a >> 2]); out.push_back(B64_TABLE[((a & 3) << 4) | (b >> 4)]); out.push_back(B64_TABLE[(b & 0xF) << 2]); out.push_back('='); } return out; } /// Сжатие строки с помощью zlib (уровень сжатия по умолчанию) inline std::string zlib_compress(const std::string& input) { uLongf compressed_size = compressBound(input.size()); std::string compressed; compressed.resize(compressed_size); int ret = compress2((Bytef*)&compressed[0], &compressed_size, (const Bytef*)input.data(), input.size(), Z_DEFAULT_COMPRESSION); if (ret != Z_OK) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("ZLIB compression failed: %d", ret))); } compressed.resize(compressed_size); return compressed; } static int hex_nibble(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); return -1; } static std::string url_decode_component(const std::string& in) { std::string out; out.reserve(in.size()); for (size_t i = 0; i < in.size(); ++i) { char ch = in[i]; if (ch == '+') { out.push_back(' '); continue; } if (ch == '%' && i + 2 < in.size()) { int hi = hex_nibble(in[i + 1]); int lo = hex_nibble(in[i + 2]); if (hi >= 0 && lo >= 0) { out.push_back((char)((hi << 4) | lo)); i += 2; continue; } } out.push_back(ch); } return out; } static bool extract_param_from_ref_string(const std::string& ref_or_query, const std::string& target_name, std::string* out_value) { size_t qpos = ref_or_query.find('?'); const std::string query = (qpos == std::string::npos) ? ref_or_query : ref_or_query.substr(qpos + 1); size_t pos = 0; while (pos <= query.size()) { size_t amp = query.find('&', pos); std::string token = (amp == std::string::npos) ? query.substr(pos) : query.substr(pos, amp - pos); if (!token.empty()) { size_t eq = token.find('='); std::string raw_name = (eq == std::string::npos) ? token : token.substr(0, eq); std::string raw_value = (eq == std::string::npos) ? "" : token.substr(eq + 1); std::string name = url_decode_component(raw_name); if (name == target_name) { *out_value = url_decode_component(raw_value); return true; } } if (amp == std::string::npos) break; pos = amp + 1; } return false; } /* Вспомогательные функции */ static char *get_value_by_path(const char *report_json, const char *path); static void process_section(const char *section_json, const char *report_json, StringInfo result, int indent); static void parse_nest_array(const char *nest_start, const char *report_json, StringInfo result, int indent); static void process_section_html(const char *section_json, const char *report_json, StringInfo result, int indent); static void parse_nest_array_html(const char *nest_start, const char *report_json, StringInfo result, int indent); static const char *find_top_level_value_start(const char *json_obj, const char *key); static std::string html_to_text_basic(const std::string& html, int max_linesize); /* * Извлекает значение из отчёта по точечному пути "$.key1.key2". * report_json – полный JSON отчёта в виде строки. */ static char * get_value_by_path(const char *report_json, const char *path) { if (path[0] != '$' || path[1] != '.') return NULL; const char *p = path + 2; const char *current_json = report_json; char key[256]; while (*p) { const char *dot = strchr(p, '.'); int len; if (dot) len = dot - p; else len = strlen(p); if (len >= (int)sizeof(key)) return NULL; memcpy(key, p, len); key[len] = '\0'; char *val; { LOCAL_FCINFO(fcinfo2, 2); InitFunctionCallInfoData(*fcinfo2, NULL, 2, InvalidOid, NULL, NULL); fcinfo2->args[0].value = PointerGetDatum(cstring_to_text(current_json)); fcinfo2->args[0].isnull = false; fcinfo2->args[1].value = PointerGetDatum(cstring_to_text(key)); fcinfo2->args[1].isnull = false; Datum result = dbms_report_extract_string_value(fcinfo2); if (result == 0) { val == NULL; } else { val = text_to_cstring(DatumGetTextP(result)); } } if (!val) return NULL; if (dot == NULL) { /* Последний ключ – возвращаем значение */ return val; } else { /* Для промежуточного ключа ожидается JSON-объект (начинается с '{') */ /* Выполняется проверка типа значения и продолжение поиска во вложенном объекте */ p = dot + 1; /* Проверка, что значение является объектом */ const char *v = val; while (isspace((unsigned char)*v)) v++; if (*v != '{') { pfree(val); return NULL; } current_json = val; /* теперь ищем внутри этого объекта */ } } return NULL; } /* * Разбирает массив nest, начиная с позиции nest_start (которая указывает на '[') */ static void parse_nest_array(const char *nest_start, const char *report_json, StringInfo result, int indent) { const char *p = nest_start; if (*p != '[') return; p++; /* пропускаем '[' */ while (*p && *p != ']') { while (isspace((unsigned char)*p)) p++; if (*p == '{') { int brace = 1; const char *obj_start = p; while (*(++p)) { if (*p == '{') brace++; else if (*p == '}') brace--; if (brace == 0) break; } if (brace == 0) { int obj_len = p - obj_start + 1; char *section = (char *) palloc(obj_len + 1); memcpy(section, obj_start, obj_len); section[obj_len] = '\0'; process_section(section, report_json, result, indent); pfree(section); } } else { p++; /* пропускаем запятые и прочее */ } } } /* Вспомогательные функции HTML */ static void append_html_escaped(StringInfo out, const char *src, int len) { for (int i = 0; i < len; ++i) { char ch = src[i]; switch (ch) { case '&': appendStringInfoString(out, "&"); break; case '<': appendStringInfoString(out, "<"); break; case '>': appendStringInfoString(out, ">"); break; case '"': appendStringInfoString(out, """); break; default: appendStringInfoChar(out, ch); break; } } } static const char * find_top_level_value_start(const char *json_obj, const char *key) { if (!json_obj || !key) return NULL; char needle[256]; snprintf(needle, sizeof(needle), "\"%s\"", key); int needle_len = (int)strlen(needle); int obj_depth = 0; bool in_string = false; bool escaped = false; const char *p = json_obj; while (*p) { char c = *p; if (in_string) { if (escaped) escaped = false; else if (c == '\\') escaped = true; else if (c == '"') in_string = false; p++; continue; } if (c == '"') { if (obj_depth == 1 && strncmp(p, needle, needle_len) == 0) { const char *q = p + needle_len; while (*q && isspace((unsigned char)*q)) q++; if (*q != ':') { p++; continue; } q++; while (*q && isspace((unsigned char)*q)) q++; return q; } in_string = true; p++; continue; } if (c == '{') obj_depth++; else if (c == '}') obj_depth--; p++; } return NULL; } static void append_wrapped_word(StringInfo out, StringInfo line, const std::string& word, int max_linesize) { if (word.empty()) return; if (line->len == 0) { appendStringInfoString(line, word.c_str()); return; } if (line->len + 1 + (int)word.size() <= max_linesize) { appendStringInfoChar(line, ' '); appendStringInfoString(line, word.c_str()); return; } appendStringInfoString(out, line->data); appendStringInfoChar(out, '\n'); resetStringInfo(line); appendStringInfoString(line, word.c_str()); } static std::string html_to_text_basic(const std::string& html, int max_linesize) { StringInfoData raw; initStringInfo(&raw); bool in_tag = false; std::string tag_buf; for (size_t i = 0; i < html.size(); ++i) { char ch = html[i]; if (!in_tag) { if (ch == '<') { in_tag = true; tag_buf.clear(); continue; } if (ch == '\r') continue; appendStringInfoChar(&raw, ch); } else { if (ch == '>') { in_tag = false; std::string t; t.reserve(tag_buf.size()); for (char c : tag_buf) t.push_back((char)tolower((unsigned char)c)); if (t.compare(0, 2, "br") == 0 || t.compare(0, 3, "/p") == 0 || t.compare(0, 2, "p ") == 0 || t == "p" || t.compare(0, 3, "/h1") == 0 || t.compare(0, 3, "/h2") == 0 || t.compare(0, 3, "/h3") == 0 || t.compare(0, 3, "/h4") == 0 || t.compare(0, 3, "/h5") == 0 || t.compare(0, 3, "/h6") == 0 || t.compare(0, 3, "/li") == 0 || t.compare(0, 3, "/tr") == 0 || t.compare(0, 4, "/div") == 0) { appendStringInfoChar(&raw, '\n'); } continue; } tag_buf.push_back(ch); } } std::string s(raw.data, raw.len); pfree(raw.data); auto replace_all = [](std::string& x, const std::string& from, const std::string& to) { size_t pos = 0; while ((pos = x.find(from, pos)) != std::string::npos) { x.replace(pos, from.size(), to); pos += to.size(); } }; replace_all(s, "<", "<"); replace_all(s, ">", ">"); replace_all(s, "&", "&"); replace_all(s, """, "\""); replace_all(s, "'", "'"); replace_all(s, " ", " "); StringInfoData out; StringInfoData line; initStringInfo(&out); initStringInfo(&line); std::string word; for (size_t i = 0; i < s.size(); ++i) { char ch = s[i]; if (ch == '\n') { if (!word.empty()) { append_wrapped_word(&out, &line, word, max_linesize); word.clear(); } if (line.len > 0) { appendStringInfoString(&out, line.data); resetStringInfo(&line); } if (out.len == 0 || out.data[out.len - 1] != '\n') appendStringInfoChar(&out, '\n'); continue; } if (isspace((unsigned char)ch)) { if (!word.empty()) { append_wrapped_word(&out, &line, word, max_linesize); word.clear(); } } else { word.push_back(ch); } } if (!word.empty()) append_wrapped_word(&out, &line, word, max_linesize); if (line.len > 0) appendStringInfoString(&out, line.data); while (out.len > 0 && (out.data[out.len - 1] == '\n' || out.data[out.len - 1] == ' ')) { out.len--; out.data[out.len] = '\0'; } std::string result(out.data, out.len); pfree(out.data); pfree(line.data); return result; } static bool is_safe_html_tag(const char *tag) { if (!tag || !*tag) return false; for (const char *p = tag; *p; ++p) { if (!isalnum((unsigned char)*p)) return false; } return true; } static void append_args_html(StringInfo out, const char *section_json, const char *report_json) { const char *args_start = find_top_level_value_start(section_json, "args"); if (!args_start) return; if (*args_start == '"') { args_start++; const char *end = strchr(args_start, '"'); if (end) append_html_escaped(out, args_start, (int)(end - args_start)); return; } if (*args_start != '[') return; const char *p = args_start + 1; while (*p && *p != ']') { while (isspace((unsigned char)*p)) p++; if (*p == '"') { p++; const char *end = strchr(p, '"'); if (!end) break; int len = (int)(end - p); if (len > 2 && p[0] == '$' && p[1] == '.') { char *path = (char *) palloc(len + 1); memcpy(path, p, len); path[len] = '\0'; char *val = get_value_by_path(report_json, path); if (val) { append_html_escaped(out, val, (int)strlen(val)); pfree(val); } pfree(path); } else { append_html_escaped(out, p, len); } p = end + 1; } else { while (*p && *p != ',' && *p != ']') p++; } if (*p == ',') p++; } } static void append_attrs_html(StringInfo out, const char *section_json, const char *report_json) { const char *attrs = find_top_level_value_start(section_json, "attrs"); if (!attrs) return; if (*attrs != '[') return; attrs++; while (*attrs && *attrs != ']') { while (isspace((unsigned char)*attrs)) attrs++; if (*attrs == '"') { attrs++; const char *end = strchr(attrs, '"'); if (!end) break; const char *eq = (const char *)memchr(attrs, '=', (size_t)(end - attrs)); if (eq && eq > attrs) { appendStringInfoChar(out, ' '); appendBinaryStringInfo(out, attrs, (int)(eq - attrs)); appendStringInfoChar(out, '='); appendBinaryStringInfo(out, eq + 1, (int)(end - eq - 1)); } attrs = end + 1; } else { attrs++; } if (*attrs == ',') attrs++; } } static void process_section_html(const char *section_json, const char *report_json, StringInfo result, int indent) { char *type; { LOCAL_FCINFO(fcinfo2, 2); InitFunctionCallInfoData(*fcinfo2, NULL, 2, InvalidOid, NULL, NULL); fcinfo2->args[0].value = PointerGetDatum(cstring_to_text(section_json)); fcinfo2->args[0].isnull = false; fcinfo2->args[1].value = PointerGetDatum(cstring_to_text("type")); fcinfo2->args[1].isnull = false; Datum result = dbms_report_extract_string_value(fcinfo2); if (result == 0) { type == NULL; } else { type = text_to_cstring(DatumGetTextP(result)); } } if (!type) return; if (!is_safe_html_tag(type)) { pfree(type); return; } bool is_heading = (type[0] == 'h' && strlen(type) == 2 && isdigit((unsigned char)type[1])); bool is_control = (strcmp(type, "loop") == 0 || strcmp(type, "if") == 0); bool is_multiline = (strcmp(type, "p") == 0 || strcmp(type, "div") == 0 || strcmp(type, "strong") == 0 || strcmp(type, "ul") == 0 || strcmp(type, "ol") == 0 || strcmp(type, "li") == 0 || strcmp(type, "a") == 0 || is_heading || is_control); if (strcmp(type, "hr") == 0) { appendStringInfoString(result, "
\n"); appendStringInfoChar(result, '\n'); pfree(type); return; } if (strcmp(type, "br") == 0) { appendStringInfoString(result, "
"); appendStringInfoChar(result, '\n'); pfree(type); return; } appendStringInfo(result, "<%s", type); if (strcmp(type, "a") == 0) append_attrs_html(result, section_json, report_json); if (is_multiline) appendStringInfoString(result, ">\n"); else appendStringInfoChar(result, '>'); bool suppress_args = is_control || strcmp(type, "li") == 0 || strcmp(type, "a") == 0 || strcmp(type, "ul") == 0 || strcmp(type, "ol") == 0; if (!suppress_args) { StringInfoData args_buf; initStringInfo(&args_buf); append_args_html(&args_buf, section_json, report_json); if (args_buf.len > 0) { if (is_multiline && (strcmp(type, "strong") == 0 || strcmp(type, "p") == 0) && indent > 0) { appendStringInfoString(result, " "); } appendStringInfoString(result, args_buf.data); if (is_multiline) appendStringInfoChar(result, '\n'); } pfree(args_buf.data); } const char *nest_start = find_top_level_value_start(section_json, "nest"); if (nest_start) { if (*nest_start == '[') { parse_nest_array_html(nest_start, report_json, result, indent + 1); } } if (is_multiline) { appendStringInfo(result, "", type); } else appendStringInfo(result, "", type); appendStringInfoChar(result, '\n'); pfree(type); } static void parse_nest_array_html(const char *nest_start, const char *report_json, StringInfo result, int indent) { const char *p = nest_start; if (*p != '[') return; p++; while (*p && *p != ']') { while (isspace((unsigned char)*p)) p++; if (*p == '{') { int brace = 1; const char *obj_start = p; while (*(++p)) { if (*p == '{') brace++; else if (*p == '}') brace--; if (brace == 0) break; } if (brace == 0) { int obj_len = (int)(p - obj_start + 1); char *section = (char *) palloc(obj_len + 1); memcpy(section, obj_start, obj_len); section[obj_len] = '\0'; process_section_html(section, report_json, result, indent); pfree(section); } } else { p++; } } } /* * Обрабатывает одну секцию мета-спецификации. */ static void process_section(const char *section_json, const char *report_json, StringInfo result, int indent) { char *type; { LOCAL_FCINFO(fcinfo2, 2); InitFunctionCallInfoData(*fcinfo2, NULL, 2, InvalidOid, NULL, NULL); fcinfo2->args[0].value = PointerGetDatum(cstring_to_text(section_json)); fcinfo2->args[0].isnull = false; fcinfo2->args[1].value = PointerGetDatum(cstring_to_text("type")); fcinfo2->args[1].isnull = false; Datum result = dbms_report_extract_string_value(fcinfo2); if (result == 0) { type == NULL; } else { type = text_to_cstring(DatumGetTextP(result)); } } if (!type) return; /* Собираем текст из args */ StringInfoData section_text; initStringInfo(§ion_text); /* args может быть строкой или массивом */ const char *args_start = strstr(section_json, "\"args\""); if (args_start) { args_start += 5; while (*args_start && *args_start != ':') args_start++; if (*args_start == ':') { args_start++; while (isspace((unsigned char)*args_start)) args_start++; if (*args_start == '"') { /* args – строка */ args_start++; const char *end = strchr(args_start, '"'); if (end) { int len = end - args_start; appendBinaryStringInfo(§ion_text, args_start, len); } } else if (*args_start == '[') { /* args – массив строк */ const char *p = args_start + 1; while (*p && *p != ']') { while (isspace((unsigned char)*p)) p++; if (*p == '"') { p++; const char *end = strchr(p, '"'); if (end) { int len = end - p; /* Проверим, не является ли этот элемент путём (начинается с "$.") */ if (len > 2 && p[0] == '$' && p[1] == '.') { char *path = (char *) palloc(len + 1); memcpy(path, p, len); path[len] = '\0'; char *val = get_value_by_path(report_json, path); if (val) { appendStringInfoString(§ion_text, val); pfree(val); } pfree(path); } else { appendBinaryStringInfo(§ion_text, p, len); } p = end + 1; } } else { /* Пропуск нестроковых элементов */ while (*p && *p != ',' && *p != ']') p++; } if (*p == ',') p++; } } } } /* Отступ */ bool need_indent = (strcmp(type, "br") != 0) && (section_text.len > 0); if (need_indent) { for (int i = 0; i < indent; i++) appendStringInfoString(result, " "); } /* Обработка типа секции */ if (strcmp(type, "p") == 0 || strcmp(type, "li") == 0) { appendStringInfoString(result, section_text.data); } else if (strncmp(type, "h", 1) == 0 && strlen(type) == 2 && isdigit(type[1])) { /* Заголовок h1-h6 */ appendStringInfoString(result, section_text.data); appendStringInfoString(result, "\n"); if (need_indent) { for (int i = 0; i < indent; i++) appendStringInfoString(result, " "); } char *line; { LOCAL_FCINFO(fcinfo2, 2); InitFunctionCallInfoData(*fcinfo2, NULL, 2, InvalidOid, NULL, NULL); fcinfo2->args[0].value = PointerGetDatum(cstring_to_text(section_json)); fcinfo2->args[0].isnull = false; fcinfo2->args[1].value = PointerGetDatum(cstring_to_text("line")); fcinfo2->args[1].isnull = false; Datum result = dbms_report_extract_string_value(fcinfo2); if (result == 0) { line == NULL; } else { line = text_to_cstring(DatumGetTextP(result)); } } const char *line_char = line ? line : "-"; int len = section_text.len; for (int i = 0; i < len; i++) appendStringInfoString(result, line_char); if (line) pfree(line); } else if (strcmp(type, "br") == 0) { appendStringInfoString(result, "\n"); } else { /* Неподдерживаемый тип – игнорируем */ } if (need_indent && strcmp(type, "br") != 0) appendStringInfoString(result, "\n"); /* Обработка вложенных секций */ const char *nest_start = strstr(section_json, "\"nest\""); if (nest_start) { nest_start += 5; while (*nest_start && *nest_start != ':') nest_start++; if (*nest_start == ':') { nest_start++; while (isspace((unsigned char)*nest_start)) nest_start++; if (*nest_start == '[') { parse_nest_array(nest_start, report_json, result, indent + 1); } } } pfree(type); pfree(section_text.data); } static void dbms_report_raise_not_implemented(const char* routine_name, int nargs) { ereport(ERROR, (errmsg("NOT_IMPLEMENTED"), errdetail("DBMS_REPORT: %s, argc=%d", routine_name, nargs))); } PG_FUNCTION_INFO_V1(dbms_report_build_generic_tag); PG_FUNCTION_INFO_V1(dbms_report_build_report_reference_struct); PG_FUNCTION_INFO_V1(dbms_report_build_report_reference_varg); PG_FUNCTION_INFO_V1(dbms_report_clear_framework); PG_FUNCTION_INFO_V1(dbms_report_format_message); PG_FUNCTION_INFO_V1(dbms_report_format_report); PG_FUNCTION_INFO_V1(dbms_report_get_awr_context); PG_FUNCTION_INFO_V1(dbms_report_get_awr_diff_context); PG_FUNCTION_INFO_V1(dbms_report_get_imported_report_attrs); PG_FUNCTION_INFO_V1(dbms_report_get_param); PG_FUNCTION_INFO_V1(dbms_report_get_report); PG_FUNCTION_INFO_V1(dbms_report_get_report_json); PG_FUNCTION_INFO_V1(dbms_report_get_report_with_summary); PG_FUNCTION_INFO_V1(dbms_report_get_snap_id); PG_FUNCTION_INFO_V1(dbms_report_get_timing_info); PG_FUNCTION_INFO_V1(dbms_report_gzip_report_xml); PG_FUNCTION_INFO_V1(dbms_report_is_compress_event_set); PG_FUNCTION_INFO_V1(dbms_report_json_to_html); PG_FUNCTION_INFO_V1(dbms_report_json_to_text); PG_FUNCTION_INFO_V1(dbms_report_lookup_component_id); PG_FUNCTION_INFO_V1(dbms_report_lookup_report_id); PG_FUNCTION_INFO_V1(dbms_report_parse_report_reference); PG_FUNCTION_INFO_V1(dbms_report_register_component); PG_FUNCTION_INFO_V1(dbms_report_register_custom_format); PG_FUNCTION_INFO_V1(dbms_report_register_report); PG_FUNCTION_INFO_V1(dbms_report_register_swf); PG_FUNCTION_INFO_V1(dbms_report_register_text_format); PG_FUNCTION_INFO_V1(dbms_report_register_xslt_format); PG_FUNCTION_INFO_V1(dbms_report_restore_report_env); PG_FUNCTION_INFO_V1(dbms_report_setup_report_env); PG_FUNCTION_INFO_V1(dbms_report_transform_html_to_text); PG_FUNCTION_INFO_V1(dbms_report_transform_report_json); PG_FUNCTION_INFO_V1(dbms_report_transform_report_xml); PG_FUNCTION_INFO_V1(dbms_report_unescape_report_ref); PG_FUNCTION_INFO_V1(dbms_report_validate_ref_parameter); PG_FUNCTION_INFO_V1(dbms_report_validate_report); PG_FUNCTION_INFO_V1(dbms_report_zlib2base64_clob); PG_FUNCTION_INFO_V1(dbms_report_zlib2base64_report_xml); PG_FUNCTION_INFO_V1(dbms_report_get_version); PG_FUNCTION_INFO_V1(dbms_report_extract_string_value); /// @brief Версия RUDB пакета DBMS_REPORT (Oracle DBMS_REPORT пакет) #define RUDB_DBMS_REPORT_VERSION "1.0.0" extern "C" Datum dbms_report_build_generic_tag(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_build_generic_tag", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_build_report_reference_struct(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_build_report_reference_struct", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_build_report_reference_varg(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_build_report_reference_varg", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_clear_framework(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_clear_framework", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_format_message(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_format_message", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_format_report(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_format_report", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_get_awr_context(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_get_awr_context", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_get_awr_diff_context(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_get_awr_diff_context", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_get_imported_report_attrs(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_get_imported_report_attrs", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_get_param(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(1)) PG_RETURN_NULL(); std::string param_name = text_to_std_string(PG_GETARG_TEXT_PP(1)); bool mandatory = false; bool nullable = false; if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) mandatory = PG_GETARG_BOOL(2); if (PG_NARGS() > 4 && !PG_ARGISNULL(4)) nullable = PG_GETARG_BOOL(4); std::string value; bool found = false; if (!PG_ARGISNULL(0)) { std::string ref_or_query = text_to_std_string(PG_GETARG_TEXT_PP(0)); found = extract_param_from_ref_string(ref_or_query, param_name, &value); } if (found) { if (nullable && value.empty()) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text_with_len(value.data(), value.size())); } if (mandatory) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("mandatory parameter is missing: %s", param_name.c_str()))); } if (PG_NARGS() > 3 && !PG_ARGISNULL(3)) { text *def_val = PG_GETARG_TEXT_PP(3); std::string def_value = text_to_std_string(def_val); PG_RETURN_TEXT_P(cstring_to_text_with_len(def_value.data(), def_value.size())); } PG_RETURN_NULL(); } extern "C" Datum dbms_report_get_report(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_get_report", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_get_report_json(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_get_report_json", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_get_report_with_summary(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_get_report_with_summary", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_get_snap_id(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_get_snap_id", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_get_timing_info(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int32 phase = PG_GETARG_INT32(0); Datum elapsed_in = (Datum) 0; Datum cpu_in = (Datum) 0; if (!PG_ARGISNULL(1)) elapsed_in = PG_GETARG_DATUM(1); if (!PG_ARGISNULL(2)) cpu_in = PG_GETARG_DATUM(2); TupleDesc tupdesc; if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("function returning record called in context that cannot accept type record"))); } struct timeval tv; gettimeofday(&tv, NULL); /* time in hundredths of a second */ int64 current_elapsed = (int64)tv.tv_sec * 100 + tv.tv_usec / 10000; struct rusage ru; getrusage(RUSAGE_SELF, &ru); int64 current_cpu = ((int64)ru.ru_utime.tv_sec * 100 + ru.ru_utime.tv_usec / 10000) + ((int64)ru.ru_stime.tv_sec * 100 + ru.ru_stime.tv_usec / 10000); int64 out_elapsed = current_elapsed; int64 out_cpu = current_cpu; if (phase == 1) { int64 in_elapsed_val = 0; int64 in_cpu_val = 0; if (!PG_ARGISNULL(1)) { char *str_el = DatumGetCString(DirectFunctionCall1(numeric_out, elapsed_in)); in_elapsed_val = strtoll(str_el, NULL, 10); pfree(str_el); } if (!PG_ARGISNULL(2)) { char *str_cpu = DatumGetCString(DirectFunctionCall1(numeric_out, cpu_in)); in_cpu_val = strtoll(str_cpu, NULL, 10); pfree(str_cpu); } out_elapsed = current_elapsed - in_elapsed_val; if (out_elapsed < 0) out_elapsed = 0; out_cpu = current_cpu - in_cpu_val; if (out_cpu < 0) out_cpu = 0; } char buf_elapsed[64]; char buf_cpu[64]; snprintf(buf_elapsed, sizeof(buf_elapsed), "%lld", (long long)out_elapsed); snprintf(buf_cpu, sizeof(buf_cpu), "%lld", (long long)out_cpu); Datum cur_el_num = DirectFunctionCall3(numeric_in, CStringGetDatum(buf_elapsed), ObjectIdGetDatum(0), Int32GetDatum(-1)); Datum cur_cpu_num = DirectFunctionCall3(numeric_in, CStringGetDatum(buf_cpu), ObjectIdGetDatum(0), Int32GetDatum(-1)); Datum values[2]; bool nulls[2] = {false, false}; values[0] = cur_el_num; values[1] = cur_cpu_num; HeapTuple tuple = heap_form_tuple(tupdesc, values, nulls); PG_RETURN_DATUM(HeapTupleGetDatum(tuple)); } extern "C" Datum dbms_report_gzip_report_xml(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_gzip_report_xml", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_is_compress_event_set(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_is_compress_event_set", PG_NARGS()); PG_RETURN_BOOL(false); } extern "C" Datum dbms_report_json_to_html(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) PG_RETURN_NULL(); text *json_report_text = PG_GETARG_TEXT_PP(0); text *json_meta_text = PG_GETARG_TEXT_PP(1); char *report_json = text_to_cstring(json_report_text); char *meta_json = text_to_cstring(json_meta_text); StringInfoData body_result; initStringInfo(&body_result); const char *nest_start = strstr(meta_json, "\"nest\""); if (nest_start) { nest_start += 5; while (*nest_start && *nest_start != ':') nest_start++; if (*nest_start == ':') { nest_start++; while (isspace((unsigned char)*nest_start)) nest_start++; if (*nest_start == '[') parse_nest_array_html(nest_start, report_json, &body_result, 0); } } if (body_result.len == 0) appendStringInfoString(&body_result, ""); StringInfoData result; initStringInfo(&result); appendStringInfoString(&result, "\n" "HTML Report\n" " \n" "\n" "\n"); while (body_result.len > 0 && (body_result.data[body_result.len - 1] == '\n' || body_result.data[body_result.len - 1] == '\r')) { body_result.len--; body_result.data[body_result.len] = '\0'; } appendStringInfoString(&result, body_result.data); appendStringInfoChar(&result, '\n'); appendStringInfoString(&result, ""); pfree(report_json); pfree(meta_json); pfree(body_result.data); PG_RETURN_TEXT_P(cstring_to_text(result.data)); } extern "C" Datum dbms_report_json_to_text(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) PG_RETURN_NULL(); text *json_report_text = PG_GETARG_TEXT_PP(0); text *json_meta_text = PG_GETARG_TEXT_PP(1); /* Получаем C-строки напрямую */ char *report_json = text_to_cstring(json_report_text); char *meta_json = text_to_cstring(json_meta_text); StringInfoData result; initStringInfo(&result); /* Ищем корневой массив nest */ const char *nest_start = strstr(meta_json, "\"nest\""); if (nest_start) { nest_start += 5; while (*nest_start && *nest_start != ':') nest_start++; if (*nest_start == ':') { nest_start++; while (isspace((unsigned char)*nest_start)) nest_start++; if (*nest_start == '[') { parse_nest_array(nest_start, report_json, &result, 0); } } } /* Если ничего не вывели, возвращаем пустую строку */ if (result.len == 0) appendStringInfoString(&result, ""); pfree(report_json); pfree(meta_json); PG_RETURN_TEXT_P(cstring_to_text(result.data)); } extern "C" Datum dbms_report_lookup_component_id(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_lookup_component_id", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_lookup_report_id(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_lookup_report_id", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_parse_report_reference(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_parse_report_reference", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_register_component(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_register_component", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_register_custom_format(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_register_custom_format", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_register_report(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_register_report", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_register_swf(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_register_swf", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_register_text_format(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_register_text_format", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_register_xslt_format(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_register_xslt_format", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_restore_report_env(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_restore_report_env", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_setup_report_env(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_setup_report_env", PG_NARGS()); PG_RETURN_BOOL(false); } extern "C" Datum dbms_report_transform_html_to_text(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int max_linesize = 80; if (!PG_ARGISNULL(1)) max_linesize = PG_GETARG_INT32(1); if (max_linesize <= 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("max_linesize must be positive"))); } text *html_text = PG_GETARG_TEXT_PP(0); std::string html = text_to_std_string(html_text); std::string plain = html_to_text_basic(html, max_linesize); PG_RETURN_TEXT_P(cstring_to_text_with_len(plain.data(), plain.size())); } extern "C" Datum dbms_report_transform_report_json(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_transform_report_json", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_transform_report_xml(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_transform_report_xml", PG_NARGS()); PG_RETURN_NULL(); } extern "C" Datum dbms_report_unescape_report_ref(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); text *input_text = PG_GETARG_TEXT_PP(0); std::string input = text_to_std_string(input_text); std::string output; output.reserve(input.size()); for (size_t i = 0; i < input.size(); ++i) { char ch = input[i]; if (ch == '+') { output.push_back(' '); continue; } if (ch == '%') { if (i + 2 >= input.size()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid escaped report reference"))); } int hi = hex_nibble(input[i + 1]); int lo = hex_nibble(input[i + 2]); if (hi < 0 || lo < 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid escaped report reference"))); } output.push_back((char)((hi << 4) | lo)); i += 2; continue; } output.push_back(ch); } PG_RETURN_TEXT_P(cstring_to_text_with_len(output.data(), output.size())); } extern "C" Datum dbms_report_validate_ref_parameter(PG_FUNCTION_ARGS) { bool is_name = false; if (PG_NARGS() > 1 && !PG_ARGISNULL(1)) is_name = PG_GETARG_BOOL(1); /* * Поведение оставлено максимально совместимым с практическими * проверками в Oracle: строго не допускается только NULL-имя * параметра. Для значения параметра NULL допускается. */ if (is_name && PG_ARGISNULL(0)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid reference parameter name"))); } PG_RETURN_VOID(); } extern "C" Datum dbms_report_validate_report(PG_FUNCTION_ARGS) { dbms_report_raise_not_implemented("dbms_report_validate_report", PG_NARGS()); PG_RETURN_VOID(); } extern "C" Datum dbms_report_zlib2base64_clob(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); text* input_text = PG_GETARG_TEXT_PP(0); std::string input_str = text_to_std_string(input_text); std::string compressed = zlib_compress(input_str); /* * Второй байт заголовка устанавливается в 0x01 * для согласования результата с Oracle. */ if (compressed.size() >= 2) { compressed[1] = 0x01; } std::string base64 = base64_encode_bytes(compressed); PG_RETURN_TEXT_P(cstring_to_text_with_len(base64.data(), base64.size())); } extern "C" Datum dbms_report_zlib2base64_report_xml(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); /* * В текущей реализации аргумент принимается как text-представление XML. * Поведение сжатия и кодирования соответствует zlib2base64_clob. */ text* input_text = PG_GETARG_TEXT_PP(0); std::string input_str = text_to_std_string(input_text); std::string compressed = zlib_compress(input_str); /* * Второй байт заголовка устанавливается в 0x01 * для согласования результата с Oracle. */ if (compressed.size() >= 2) { compressed[1] = 0x01; } std::string base64 = base64_encode_bytes(compressed); PG_RETURN_TEXT_P(cstring_to_text_with_len(base64.data(), base64.size())); } /// @brief Возвращает версию RUDB пакета DBMS_REPORT (Oracle DBMS_REPORT пакет) extern "C" Datum dbms_report_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_REPORT_VERSION)); } /* * Извлекает строковое значение поля из JSON-объекта. * Возвращает text или NULL. * Учитывает, что поле может быть строкой в кавычках или простым значением. */ extern "C" Datum dbms_report_extract_string_value(PG_FUNCTION_ARGS) { char search[256]; text *json_text = PG_GETARG_TEXT_P(0); text *key_text = PG_GETARG_TEXT_P(1); char *json = text_to_cstring(json_text); char *key = text_to_cstring(key_text); snprintf(search, sizeof(search), "\"%s\"", key); const char *p = strstr(json, search); if (!p) { pfree(json); pfree(key); PG_RETURN_NULL(); } p += strlen(search); while (*p && isspace((unsigned char)*p)) p++; if (*p != ':') { pfree(json); pfree(key); PG_RETURN_NULL(); } p++; while (*p && isspace((unsigned char)*p)) p++; if (*p == '"') { p++; const char *end = strchr(p, '"'); if (!end) return NULL; int len = end - p; char *val = (char *) palloc(len + 1); memcpy(val, p, len); val[len] = '\0'; pfree(json); pfree(key); text *result = cstring_to_text(val); pfree(val); PG_RETURN_TEXT_P(result); } else { /* Число, true, false, null */ const char *end = p; while (*end && *end != ',' && *end != '}' && !isspace((unsigned char)*end)) end++; int len = end - p; char *val = (char *) palloc(len + 1); memcpy(val, p, len); val[len] = '\0'; pfree(json); pfree(key); text *result = cstring_to_text(val); pfree(val); PG_RETURN_TEXT_P(result); } }