#include "dbms_ash_internal.hpp" #include "ash.hpp" extern "C" { #include "access/htup_details.h" #include "catalog/pg_proc.h" #include "catalog/pg_type_d.h" #include "executor/spi.h" #include "funcapi.h" #include "miscadmin.h" #include "nodes/miscnodes.h" #include "mb/pg_wchar.h" #include "utils/guc.h" #include "utils/array.h" #include "utils/builtins.h" #include "utils/datum.h" #include "utils/date.h" #include "utils/elog.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/numeric.h" #include "utils/syscache.h" #include "utils/timestamp.h" #include "utils/tuplestore.h" } // extern "C" #include #include #include #include #include #include #include extern "C" { Datum timestamp_to_char(PG_FUNCTION_ARGS); } extern "C" { PG_FUNCTION_INFO_V1(dbms_ash_internal_ash_phase_execution); PG_FUNCTION_INFO_V1(dbms_ash_internal_ash_rollup_sql_1d); PG_FUNCTION_INFO_V1(dbms_ash_internal_ash_rollup_sql_2d); PG_FUNCTION_INFO_V1(dbms_ash_internal_ash_rollup_sql_3d); PG_FUNCTION_INFO_V1(dbms_ash_internal_ash_rollup_xml_1d); PG_FUNCTION_INFO_V1(dbms_ash_internal_ash_rollup_xml_2d); PG_FUNCTION_INFO_V1(dbms_ash_internal_ash_sql_for_awr); PG_FUNCTION_INFO_V1(dbms_ash_internal_ash_view_sql); PG_FUNCTION_INFO_V1(dbms_ash_internal_build_action_tag); PG_FUNCTION_INFO_V1(dbms_ash_internal_build_database_header_tag); PG_FUNCTION_INFO_V1(dbms_ash_internal_build_event_tag); PG_FUNCTION_INFO_V1(dbms_ash_internal_build_service_module_tag); PG_FUNCTION_INFO_V1(dbms_ash_internal_build_session_tag); PG_FUNCTION_INFO_V1(dbms_ash_internal_build_sql_tag); PG_FUNCTION_INFO_V1(dbms_ash_internal_format_plsql); PG_FUNCTION_INFO_V1(dbms_ash_internal_getpackageversion); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_ash_heading); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_blksid_active); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_blksid_program); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_blksid_user); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_blksid_xids); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_blk_str); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_cpuinfo_xml); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_latch_name); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_obj_name); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_plsql_name); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_sid_active); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_sid_str); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_slot_width); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_sqltext); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_sql_plan_info); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_sql_plan_perc); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_user_name); PG_FUNCTION_INFO_V1(dbms_ash_internal_in_memory_ash_view_sql); PG_FUNCTION_INFO_V1(dbms_ash_internal_on_disk_ash_view_sql); PG_FUNCTION_INFO_V1(dbms_ash_internal_report_ashviewer_xml); PG_FUNCTION_INFO_V1(dbms_ash_internal_sample_time_to_id); PG_FUNCTION_INFO_V1(dbms_ash_internal_shrink_string); PG_FUNCTION_INFO_V1(dbms_ash_internal_slot_id_to_time); PG_FUNCTION_INFO_V1(dbms_ash_internal_unified_dba_files); PG_FUNCTION_INFO_V1(dbms_ash_internal_unified_dba_objects); PG_FUNCTION_INFO_V1(dbms_ash_internal_unified_plsql_subprograms); PG_FUNCTION_INFO_V1(dbms_ash_internal_unified_service_names); PG_FUNCTION_INFO_V1(dbms_ash_internal_unified_sqlstat); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_version); PG_FUNCTION_INFO_V1(dbms_ash_internal_compute_slot_width); PG_FUNCTION_INFO_V1(dbms_ash_internal_get_blksid_details); PG_FUNCTION_INFO_V1(dbms_ash_internal_initialize); PG_FUNCTION_INFO_V1(dbms_ash_internal_runreport); PG_FUNCTION_INFO_V1(rudb_ash_memory_rows); } // extern "C" #define RUDB_DBMS_ASH_INTERNAL_VERSION "1.0.0" namespace { struct ReportContext { // Контекст отчёта текущего серверного процесса не разделяется между сеансами. bool initialized = false; bool dbid_is_null = true; Numeric dbid = nullptr; bool instnum_is_null = true; ArrayType* instnum = nullptr; Numeric bsnap = nullptr; Numeric esnap = nullptr; bool btime_is_null = true; DateADT btime = 0; bool etime_is_null = true; DateADT etime = 0; Numeric nsmpls = nullptr; Numeric dfltr = nullptr; Numeric swidth = nullptr; Numeric m_en = nullptr; bool m_btime_is_null = true; DateADT m_btime = 0; bool m_etime_is_null = true; DateADT m_etime = 0; Numeric d_en = nullptr; bool d_btime_is_null = true; DateADT d_btime = 0; bool d_etime_is_null = true; DateADT d_etime = 0; Numeric data_src = nullptr; }; struct SessionReportContext { MemoryContext memory_context = nullptr; ReportContext context; }; bool g_context_guc_defined = false; char* g_context_guc_value = nullptr; SessionReportContext& report_context_store() { // Отдельный контекст памяти переживает COMMIT/ROLLBACK и освобождается // вместе с серверным процессом. static SessionReportContext store; if (store.memory_context == nullptr) { store.memory_context = AllocSetContextCreate(TopMemoryContext, "DBMS_ASH_INTERNAL report context", ALLOCSET_DEFAULT_SIZES); } return store; } struct SpiScope { const char* purpose = nullptr; bool connected = false; explicit SpiScope(const char* scope_purpose) : purpose(scope_purpose) { if (SPI_connect() != SPI_OK_CONNECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("не удалось открыть SPI для %s", purpose))); } connected = true; } ~SpiScope() { if (connected) (void) SPI_finish(); } void finish() { if (!connected) return; if (SPI_finish() != SPI_OK_FINISH) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("не удалось завершить SPI для %s", purpose))); } connected = false; } }; std::string json_escape(const std::string& value) { std::string result; result.reserve(value.size()); for (char ch : value) { switch (ch) { case '\\': result += "\\\\"; break; case '"': result += "\\\""; break; default: result.push_back(ch); break; } } return result; } std::string date_to_json_text(DateADT value) { char* rendered = DatumGetCString(DirectFunctionCall1(date_out, DateADTGetDatum(value))); std::string result(rendered); pfree(rendered); return result; } std::string numeric_to_string(Numeric value); std::string numeric_to_json_value(Numeric value) { return value == nullptr ? "null" : "\"" + json_escape(numeric_to_string(value)) + "\""; } std::string date_to_json_value(bool is_null, DateADT value) { return is_null ? "null" : "\"" + json_escape(date_to_json_text(value)) + "\""; } std::string report_context_json(void) { // Построенный SQL читает только сериализованную копию контекста отчёта // текущего серверного процесса. const ReportContext& context = report_context_store().context; Datum* elements = nullptr; bool* nulls = nullptr; int element_count = 0; std::ostringstream out; out << "{"; out << "\"initialized\":" << (context.initialized ? "true" : "false"); out << ",\"dbid\":" << numeric_to_json_value(context.dbid); out << ",\"bsnap\":" << numeric_to_json_value(context.bsnap); out << ",\"esnap\":" << numeric_to_json_value(context.esnap); out << ",\"btime\":" << date_to_json_value(context.btime_is_null, context.btime); out << ",\"etime\":" << date_to_json_value(context.etime_is_null, context.etime); out << ",\"nsmpls\":" << numeric_to_json_value(context.nsmpls); out << ",\"dfltr\":" << numeric_to_json_value(context.dfltr); out << ",\"swidth\":" << numeric_to_json_value(context.swidth); out << ",\"m_en\":" << numeric_to_json_value(context.m_en); out << ",\"m_btime\":" << date_to_json_value(context.m_btime_is_null, context.m_btime); out << ",\"m_etime\":" << date_to_json_value(context.m_etime_is_null, context.m_etime); out << ",\"d_en\":" << numeric_to_json_value(context.d_en); out << ",\"d_btime\":" << date_to_json_value(context.d_btime_is_null, context.d_btime); out << ",\"d_etime\":" << date_to_json_value(context.d_etime_is_null, context.d_etime); out << ",\"data_src\":" << numeric_to_json_value(context.data_src); out << ",\"instnum_is_null\":" << (context.instnum_is_null ? "true" : "false"); out << ",\"instnum_values\":["; if (!context.instnum_is_null && context.instnum != nullptr) { const Oid element_type = ARR_ELEMTYPE(context.instnum); int16 element_length = 0; bool element_by_value = false; char element_alignment = TYPALIGN_INT; get_typlenbyvalalign(element_type, &element_length, &element_by_value, &element_alignment); deconstruct_array(context.instnum, element_type, element_length, element_by_value, element_alignment, &elements, &nulls, &element_count); for (int idx = 0; idx < element_count; ++idx) { if (idx != 0) out << ","; if (nulls[idx]) out << "null"; else out << "\"" << json_escape(numeric_to_string(DatumGetNumeric(elements[idx]))) << "\""; } } out << "]}"; if (elements != nullptr) pfree(elements); if (nulls != nullptr) pfree(nulls); return out.str(); } const char* show_context_guc(void) { static std::string rendered; rendered = report_context_json(); return rendered.c_str(); } template Datum execute_ash_internal_entrypoint(Callback&& callback, const char* context_name) { try { return callback(); } catch (const std::bad_alloc&) { ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("недостаточно памяти в %s", context_name))); } catch (const std::exception& error) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("ошибка %s: %s", context_name, error.what()))); } pg_unreachable(); } void ensure_context_guc_defined(void) { if (g_context_guc_defined) return; DefineCustomStringVariable("dbms_ash_internal.context", "Текущий backend-local контекст DBMS_ASH_INTERNAL.", "Используется SQL generator templates во время выполнения.", &g_context_guc_value, nullptr, PGC_INTERNAL, GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE, nullptr, nullptr, show_context_guc); g_context_guc_defined = true; } void reset_context(SessionReportContext& store) { MemoryContextReset(store.memory_context); store.context = ReportContext{}; } Numeric copy_numeric_to_session_context(const SessionReportContext& store, Numeric value) { if (value == nullptr) return nullptr; MemoryContext old_context = MemoryContextSwitchTo(store.memory_context); Numeric copy = DatumGetNumeric(datumCopy(NumericGetDatum(value), false, -1)); MemoryContextSwitchTo(old_context); return copy; } ArrayType* copy_array_to_session_context(const SessionReportContext& store, ArrayType* value) { if (value == nullptr) return nullptr; MemoryContext old_context = MemoryContextSwitchTo(store.memory_context); ArrayType* copy = DatumGetArrayTypeP(datumCopy(PointerGetDatum(value), false, -1)); MemoryContextSwitchTo(old_context); return copy; } std::optional numeric_arg_optional(FunctionCallInfo fcinfo, int argno) { if (argno >= fcinfo->nargs) return std::nullopt; if (PG_ARGISNULL(argno)) return std::nullopt; return PG_GETARG_NUMERIC(argno); } std::optional date_arg_optional(FunctionCallInfo fcinfo, int argno) { if (argno >= fcinfo->nargs) return std::nullopt; if (PG_ARGISNULL(argno)) return std::nullopt; return PG_GETARG_DATEADT(argno); } std::optional text_arg_optional(FunctionCallInfo fcinfo, int argno) { if (argno >= fcinfo->nargs) return std::nullopt; if (PG_ARGISNULL(argno)) return std::nullopt; char* text_value = text_to_cstring(PG_GETARG_TEXT_PP(argno)); std::string result(text_value); pfree(text_value); return result; } std::string format_object_name(const std::optional& owner, const std::optional& object_name, const std::optional& subobject_name, const std::optional& object_type) { static constexpr const char* kMissingObject = "** MISSING **"; // Oracle считает пустой VARCHAR2 значением NULL. Для formatter это // означает, что без имени объекта результат всегда является sentinel. if (!object_name.has_value() || object_name->empty()) return kMissingObject; std::string result; if (owner.has_value()) result += *owner; // Oracle сохраняет точку даже при отсутствующем owner. result += "."; result += *object_name; // Пустой subobject эквивалентен NULL и не добавляет отдельный сегмент. if (subobject_name.has_value() && !subobject_name->empty()) { result += "."; result += *subobject_name; } // Скобки присутствуют всегда, даже если тип NULL или пустой. result += " ("; if (object_type.has_value()) result += *object_type; result += ")"; return result; } std::string numeric_to_string(Numeric value) { char* rendered = DatumGetCString(DirectFunctionCall1(numeric_out, NumericGetDatum(value))); std::string result(rendered); pfree(rendered); return result; } bool numeric_exact_flag(Numeric value, int32 expected); std::optional numeric_to_oid_exact(Numeric value) { const std::string rendered = numeric_to_string(value); if (rendered.empty()) return std::nullopt; std::size_t position = 0; if (rendered[position] == '+') ++position; // Отрицательный NUMBER не может быть OID роли. if (position >= rendered.size() || rendered[position] == '-') return std::nullopt; std::uint64_t parsed = 0; bool has_integer_digit = false; const std::uint64_t oid_max = static_cast(std::numeric_limits::max()); while (position < rendered.size() && rendered[position] >= '0' && rendered[position] <= '9') { has_integer_digit = true; const std::uint64_t digit = static_cast(rendered[position] - '0'); if (parsed > (oid_max - digit) / 10) return std::nullopt; parsed = parsed * 10 + digit; ++position; } if (!has_integer_digit) return std::nullopt; // NUMBER вида 123.0 является точным целым и должен разрешаться как OID. if (position < rendered.size() && rendered[position] == '.') { ++position; while (position < rendered.size()) { if (rendered[position] != '0') return std::nullopt; ++position; } } if (position != rendered.size()) return std::nullopt; return static_cast(parsed); } std::string format_user_name(const std::optional& user_id) { static constexpr const char* kUnknownUserPrefix = "UserID: "; if (!user_id.has_value()) return kUnknownUserPrefix; const std::string rendered_id = numeric_to_string(*user_id); const std::optional role_oid = numeric_to_oid_exact(*user_id); // В Oracle SYS имеет USER_ID=0. В PostgreSQL OID 0 является InvalidOid, // поэтому это отдельная compatibility mapping, а не catalog lookup. if (role_oid.has_value() && *role_oid == InvalidOid) return "SYS"; if (role_oid.has_value()) { char* role_name = GetUserNameFromId(*role_oid, true); if (role_name != nullptr) { std::string result(role_name); pfree(role_name); return result; } } return std::string(kUnknownUserPrefix) + rendered_id; } std::string oracle_varchar_fragment(const std::optional& value) { if (!value.has_value() || value->empty()) return ""; return *value; } std::optional oracle_empty_string_as_null(const std::optional& value) { if (!value.has_value() || value->empty()) return std::nullopt; return value; } std::optional format_plsql_name(const std::optional& owner, const std::optional& object_name, const std::optional& subprogram_name, const std::optional& overload) { const std::optional normalized_owner = oracle_empty_string_as_null(owner); const std::optional normalized_object_name = oracle_empty_string_as_null(object_name); const std::optional normalized_subprogram_name = oracle_empty_string_as_null(subprogram_name); const std::optional normalized_overload = oracle_empty_string_as_null(overload); if (!normalized_owner.has_value() || !normalized_object_name.has_value()) return std::nullopt; std::string result = *normalized_owner + "." + *normalized_object_name; if (normalized_subprogram_name.has_value()) { result += "."; result += *normalized_subprogram_name; if (normalized_overload.has_value()) { result += "#"; result += *normalized_overload; } } else if (normalized_overload.has_value()) { result += ".#package_initialization"; } return result; } std::string format_unknown_plsql_id(const std::optional& object_id, const std::optional& subprogram_id) { std::string result = "UNKNOWN_PLSQL_ID <"; if (object_id.has_value()) result += numeric_to_string(*object_id); result += ","; if (subprogram_id.has_value()) result += numeric_to_string(*subprogram_id); result += ">"; return result; } bool is_unified_plsql_namespace(const char* namespace_name) { if (namespace_name == nullptr) return false; const std::string schema_name(namespace_name); return schema_name != "pg_toast" && schema_name.rfind("pg_temp_", 0) != 0 && schema_name.rfind("pg_toast_temp_", 0) != 0; } std::optional lookup_unified_plsql_name(const std::optional& object_id, const std::optional& subprogram_id) { if (!object_id.has_value() || !subprogram_id.has_value()) return std::nullopt; const std::optional procedure_oid = numeric_to_oid_exact(*object_id); if (!procedure_oid.has_value() || !numeric_exact_flag(*subprogram_id, 1)) return std::nullopt; HeapTuple proc_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(*procedure_oid)); if (!HeapTupleIsValid(proc_tuple)) return std::nullopt; Form_pg_proc proc_form = (Form_pg_proc) GETSTRUCT(proc_tuple); std::optional result = std::nullopt; if (proc_form->prokind == PROKIND_FUNCTION || proc_form->prokind == PROKIND_PROCEDURE) { char* schema_name = get_namespace_name(proc_form->pronamespace); if (is_unified_plsql_namespace(schema_name)) { result = format_plsql_name(std::string(schema_name), std::string(NameStr(proc_form->proname)), std::nullopt, std::nullopt); } if (schema_name != nullptr) pfree(schema_name); } ReleaseSysCache(proc_tuple); return result; } std::string format_rollup_numeric_literal(Numeric value) { std::string result = numeric_to_string(value); if (result.rfind("0.", 0) == 0) result.erase(result.begin()); else if (result.rfind("-0.", 0) == 0) result.erase(result.begin() + 1); return result; } void check_rollup_result_length(const std::string& sql) { if (pg_mbstrlen(sql.c_str()) <= 32767) return; ereport(ERROR, (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION), errmsg("результат DBMS_ASH_INTERNAL.ASH_ROLLUP_SQL_1D превышает 32767 символов"))); } std::vector numeric_array_to_strings(ArrayType* value) { std::vector result; if (value == nullptr) return result; Datum* elements = nullptr; bool* nulls = nullptr; int element_count = 0; const Oid element_type = ARR_ELEMTYPE(value); int16 element_length = 0; bool element_by_value = false; char element_alignment = TYPALIGN_INT; get_typlenbyvalalign(element_type, &element_length, &element_by_value, &element_alignment); deconstruct_array(value, element_type, element_length, element_by_value, element_alignment, &elements, &nulls, &element_count); result.reserve(static_cast(element_count)); for (int idx = 0; idx < element_count; ++idx) { if (nulls[idx]) continue; result.push_back(numeric_to_string(DatumGetNumeric(elements[idx]))); } pfree(elements); pfree(nulls); return result; } Numeric int32_to_numeric(int32 value) { return DatumGetNumeric(DirectFunctionCall1(int4_numeric, Int32GetDatum(value))); } bool numeric_eq_value(Numeric lhs, Numeric rhs) { return DatumGetBool(DirectFunctionCall2(numeric_eq, NumericGetDatum(lhs), NumericGetDatum(rhs))); } bool numeric_gt_value(Numeric lhs, Numeric rhs) { return DatumGetBool(DirectFunctionCall2(numeric_gt, NumericGetDatum(lhs), NumericGetDatum(rhs))); } bool numeric_lt_value(Numeric lhs, Numeric rhs) { return DatumGetBool(DirectFunctionCall2(numeric_lt, NumericGetDatum(lhs), NumericGetDatum(rhs))); } Numeric numeric_add_value(Numeric lhs, Numeric rhs) { return DatumGetNumeric(DirectFunctionCall2(numeric_add, NumericGetDatum(lhs), NumericGetDatum(rhs))); } Numeric numeric_mul_value(Numeric lhs, Numeric rhs) { return DatumGetNumeric(DirectFunctionCall2(numeric_mul, NumericGetDatum(lhs), NumericGetDatum(rhs))); } Numeric numeric_sub_value(Numeric lhs, Numeric rhs) { return DatumGetNumeric(DirectFunctionCall2(numeric_sub, NumericGetDatum(lhs), NumericGetDatum(rhs))); } Numeric numeric_div_value(Numeric lhs, Numeric rhs) { return DatumGetNumeric(DirectFunctionCall2(numeric_div, NumericGetDatum(lhs), NumericGetDatum(rhs))); } Numeric numeric_round_value(Numeric value, int32 scale) { return DatumGetNumeric(DirectFunctionCall2(numeric_round, NumericGetDatum(value), Int32GetDatum(scale))); } Numeric numeric_trunc_value(Numeric value, int32 scale) { return DatumGetNumeric(DirectFunctionCall2(numeric_trunc, NumericGetDatum(value), Int32GetDatum(scale))); } int numeric_cmp_value(Numeric lhs, Numeric rhs) { return DatumGetInt32(DirectFunctionCall2(numeric_cmp, NumericGetDatum(lhs), NumericGetDatum(rhs))); } bool usedisk_is_exact_one(const std::optional& usedisk) { return usedisk.has_value() && numeric_eq_value(*usedisk, int32_to_numeric(1)); } std::optional context_duration_seconds(const ReportContext& context) { if (context.btime_is_null || context.etime_is_null) return std::nullopt; return int64_to_numeric( (static_cast(context.etime) - static_cast(context.btime)) * SECS_PER_DAY); } std::optional call_compute_slot_width(const std::optional& duration_seconds, const std::optional& requested_width, const std::optional& usedisk) { LOCAL_FCINFO(local_fcinfo, 3); InitFunctionCallInfoData(*local_fcinfo, nullptr, 3, InvalidOid, nullptr, nullptr); local_fcinfo->args[0].isnull = !duration_seconds.has_value(); if (duration_seconds.has_value()) local_fcinfo->args[0].value = NumericGetDatum(*duration_seconds); local_fcinfo->args[1].isnull = !requested_width.has_value(); if (requested_width.has_value()) local_fcinfo->args[1].value = NumericGetDatum(*requested_width); local_fcinfo->args[2].isnull = !usedisk.has_value(); if (usedisk.has_value()) local_fcinfo->args[2].value = NumericGetDatum(*usedisk); Datum result = dbms_ash_internal_compute_slot_width(local_fcinfo); if (local_fcinfo->isnull) return std::nullopt; return DatumGetNumeric(result); } int64 date_to_unix_seconds(DateADT value) { return (static_cast(value) + POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY; } Numeric date_to_unix_seconds_numeric(DateADT value) { return int64_to_numeric(date_to_unix_seconds(value)); } int64 numeric_to_int64_checked(Numeric value, const char* context) { ErrorSaveContext escontext = {T_ErrorSaveContext}; const int64 result = numeric_int8_safe(value, reinterpret_cast(&escontext)); if (escontext.error_occurred) { ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("%s выходит за диапазон int8", context))); } return result; } std::string group_decimal_integer(std::string digits) { bool negative = false; if (!digits.empty() && digits.front() == '-') { negative = true; digits.erase(digits.begin()); } std::string grouped; grouped.reserve(digits.size() + digits.size() / 3); const std::size_t first_group = digits.empty() ? 0 : digits.size() % 3; std::size_t offset = 0; if (first_group != 0) { grouped.append(digits, 0, first_group); offset = first_group; } while (offset < digits.size()) { if (!grouped.empty()) grouped.push_back(','); grouped.append(digits, offset, 3); offset += 3; } if (grouped.empty()) grouped = "0"; if (negative) grouped.insert(grouped.begin(), '-'); return grouped; } std::string format_duration_suffix(Numeric duration_seconds) { const Numeric sixty = int32_to_numeric(60); if (numeric_lt_value(duration_seconds, sixty)) { const Numeric rounded = numeric_round_value(duration_seconds, 0); std::string token = numeric_to_string(rounded); const std::size_t decimal_point = token.find('.'); if (decimal_point != std::string::npos) token.erase(decimal_point); if (token.size() > 7) token = "#######"; return " (" + token + " secs)"; } const Numeric rounded_minutes = numeric_round_value(numeric_div_value(duration_seconds, sixty), 1); std::string token = numeric_to_string(rounded_minutes); const std::size_t decimal_point = token.find('.'); std::string whole = decimal_point == std::string::npos ? token : token.substr(0, decimal_point); std::string fraction = decimal_point == std::string::npos ? "0" : token.substr(decimal_point + 1); if (fraction.empty()) fraction = "0"; else if (fraction.size() > 1) fraction.resize(1); return " (" + group_decimal_integer(whole) + "." + fraction + " min)"; } text* render_slot_time_text(const Numeric slot_seconds, const std::string& format_mask) { const Numeric slot_usecs = numeric_round_value(numeric_mul_value(slot_seconds, int64_to_numeric(USECS_PER_SEC)), 0); const int64 unix_usecs = numeric_to_int64_checked(slot_usecs, "Время слота"); const Timestamp slot_timestamp = static_cast(unix_usecs) - static_cast(POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * USECS_PER_DAY; text* format_text = cstring_to_text(format_mask.c_str()); return DatumGetTextPP( DirectFunctionCall2(timestamp_to_char, TimestampGetDatum(slot_timestamp), PointerGetDatum(format_text))); } std::string build_in_memory_ash_projection_sql(const std::string& source_tail) { return "SELECT " "a.dbid::number AS dbid, " "a.instance_number::number AS instance_number, " "0::number AS snap_id, " "0::number AS con_id, " "a.dbid::number AS con_dbid, " "current_database()::varchar2 AS pdb_name, " "a.sample_sequence::number AS sample_id, " "a.sample_time AS sample_time, " "a.session_id::number AS session_id, " "a.session_serial::number AS \"session_serial#\", " "NULL::varchar2 AS session_type, " "NULLIF(a.state, '')::varchar2 AS session_state, " "0::number AS flags, " "a.user_id::int8::number AS user_id, " "NULLIF(a.sql_id, '')::varchar2 AS sql_id, " "NULL::number AS sql_opcode, " "NULL::varchar2 AS sql_opname, " "NULL::varchar2 AS top_level_sql_id, " "0::number AS sql_child_number, " "NULL::number AS sql_plan_hash_value, " "NULL::number AS sql_full_plan_hash_value, " "NULL::number AS sql_plan_line_id, " "NULL::varchar2 AS sql_plan_operation, " "NULL::varchar2 AS sql_plan_options, " "NULL::number AS sql_exec_id, " "NULL::number AS force_matching_signature, " "NULL::number AS plsql_entry_object_id, " "NULL::number AS plsql_entry_subprogram_id, " "NULL::number AS plsql_object_id, " "NULL::number AS plsql_subprogram_id, " "NULL::number AS service_hash, " "NULL::number AS qc_session_id, " "NULL::number AS qc_instance_id, " "NULL::number AS \"qc_session_serial#\", " "COALESCE(NULLIF(a.event_name, ''), " " 'CPU + Wait for CPU')::varchar2 AS event, " "1::number AS event_id, " "COALESCE(NULLIF(a.wait_class, ''), " " 'CPU')::varchar2 AS wait_class, " "9999::number AS wait_class_id, " "a.sample_sequence::number AS \"seq#\", " "NULL::number AS p1, " "NULL::varchar2 AS p1text, " "NULL::number AS p2, " "NULL::varchar2 AS p2text, " "NULL::number AS p3, " "NULL::varchar2 AS p3text, " "NULL::number AS wait_time, " "NULL::number AS time_waited, " "NULL::varchar2 AS xid, " "NULL::number AS blocking_session, " "NULL::number AS \"blocking_session_serial#\", " "NULL::varchar2 AS blocking_session_status, " "NULL::number AS blocking_inst_id, " "NULL::number AS \"current_obj#\", " "NULL::number AS \"current_file#\", " "NULL::number AS \"current_block#\", " "NULL::number AS \"top_level_call#\", " "NULL::varchar2 AS top_level_call_name, " "NULL::varchar2 AS spid, " "NULL::varchar2 AS stid, " "NULLIF(a.application_name, '')::varchar2 AS program, " "NULLIF(a.module_name, '')::varchar2 AS module, " "NULL::varchar2 AS action, " "NULL::varchar2 AS client_id, " "NULL::varchar2 AS client_info, " "NULL::number AS \"remote_instance#\", " "NULL::varchar2 AS in_connection_mgmt, " "NULL::varchar2 AS in_parse, " "NULL::varchar2 AS in_hard_parse, " "NULL::varchar2 AS in_sql_execution, " "NULL::varchar2 AS in_plsql_execution, " "NULL::varchar2 AS in_plsql_rpc, " "NULL::varchar2 AS in_plsql_compilation, " "NULL::varchar2 AS in_java_execution, " "NULL::varchar2 AS in_bind, " "NULL::varchar2 AS in_cursor_close, " "NULL::varchar2 AS in_sequence_load " "FROM pg_catalog.rudb_ash_memory_rows(false) AS a" + source_tail; } std::string build_in_memory_ash_view_sql(void) { // Возвращает Oracle-совместимую проекцию memory ASH поверх общего row source. return build_in_memory_ash_projection_sql(""); } std::string build_on_disk_ash_view_sql(void) { // Возвращает стабильную Oracle-совместимую проекцию persistent ASH. return "SELECT " "s.dbid::number AS dbid, " "s.instance_number::number AS instance_number, " "s.snap_id::number AS snap_id, " "(-1)::number AS con_id, " "s.dbid::number AS con_dbid, " "CASE " " WHEN s.dbid = " " pg_catalog.dbms_workload_repository_local_awr_dbid() " " THEN current_database()::varchar2 " " ELSE ('UNKNOWN DBID ' || s.dbid::text)::varchar2 " "END AS pdb_name, " "s.sample_sequence::number AS sample_id, " "s.sample_time AS sample_time, " "s.session_id::number AS session_id, " "s.session_serial::number AS \"session_serial#\", " "CASE " " WHEN NULLIF(s.backend_type, '') IS NULL " " THEN NULL::varchar2 " " WHEN lower(s.backend_type) = 'client backend' " " THEN 'FOREGROUND'::varchar2 " " ELSE 'BACKGROUND'::varchar2 " "END AS session_type, " "NULLIF(s.state, '')::varchar2 AS session_state, " "0::number AS flags, " "s.user_id::int8::number AS user_id, " "NULLIF(s.sql_id, '')::varchar2 AS sql_id, " "NULL::number AS sql_opcode, " "NULLIF(s.command_type, '')::varchar2 AS sql_opname, " "NULL::varchar2 AS top_level_sql_id, " "0::number AS sql_child_number, " "NULL::number AS sql_plan_hash_value, " "NULL::number AS full_plan_hash_value, " "NULL::number AS sql_plan_line_id, " "NULL::varchar2 AS sql_plan_operation, " "NULL::varchar2 AS sql_plan_options, " "NULL::number AS sql_exec_id, " "NULL::number AS force_matching_signature, " "NULL::number AS plsql_entry_object_id, " "NULL::number AS plsql_entry_subprogram_id, " "NULL::number AS plsql_object_id, " "NULL::number AS plsql_subprogram_id, " "NULL::number AS service_hash, " "NULL::number AS qc_session_id, " "NULL::number AS qc_instance_id, " "NULL::number AS \"qc_session_serial#\", " "COALESCE(NULLIF(s.event_name, ''), " " 'CPU + Wait for CPU')::varchar2 AS event, " "1::number AS event_id, " "COALESCE(NULLIF(s.wait_class, ''), " " 'CPU')::varchar2 AS wait_class, " "9999::number AS wait_class_id, " "s.sample_sequence::number AS \"seq#\", " "NULL::number AS p1, " "NULL::varchar2 AS p1text, " "NULL::number AS p2, " "NULL::varchar2 AS p2text, " "NULL::number AS p3, " "NULL::varchar2 AS p3text, " "NULL::number AS wait_time, " "NULL::number AS time_waited, " "NULL::varchar2 AS xid, " "NULL::number AS blocking_session, " "NULL::number AS \"blocking_session_serial#\", " "NULL::varchar2 AS blocking_session_status, " "NULL::number AS blocking_inst_id, " "NULL::number AS \"current_obj#\", " "NULL::number AS \"current_file#\", " "NULL::number AS \"current_block#\", " "NULL::number AS \"top_level_call#\", " "NULL::varchar2 AS top_level_call_name, " "CAST(CAST(s.session_id AS text) AS varchar2) AS spid, " "NULL::varchar2 AS stid, " "NULLIF(s.application_name, '')::varchar2 AS program, " "NULLIF(s.module_name, '')::varchar2 AS module, " "NULL::varchar2 AS action, " "NULL::varchar2 AS client_id, " "NULL::varchar2 AS client_info, " "NULL::number AS \"remote_instance#\", " "NULL::varchar2 AS in_connection_mgmt, " "NULL::varchar2 AS in_parse, " "NULL::varchar2 AS in_hard_parse, " "NULL::varchar2 AS in_sql_execution, " "NULL::varchar2 AS in_plsql_execution, " "NULL::varchar2 AS in_plsql_rpc, " "NULL::varchar2 AS in_plsql_compilation, " "NULL::varchar2 AS in_java_execution, " "NULL::varchar2 AS in_bind, " "NULL::varchar2 AS in_cursor_close, " "NULL::varchar2 AS in_sequence_load " "FROM pg_catalog.rudb_ash_history_samples AS s " "WHERE s.is_awr_sample"; } std::string build_ash_sql_for_awr(bool global_scope) { // Формирует AWR source с фильтрами DBID, (bsnap, esnap] и instance. const std::string instance_predicate = global_scope ? "\n" "AND (\n" " COALESCE((c.value->>'instnum_is_null')::bool, true) = true\n" " OR (\n" " jsonb_typeof(c.value->'instnum_values') = 'array'\n" " AND jsonb_array_length(c.value->'instnum_values') > 0\n" " AND ash.instance_number IN (\n" " SELECT value::numeric\n" " FROM jsonb_array_elements_text(\n" " c.value->'instnum_values'\n" " ) AS value\n" " WHERE value IS NOT NULL\n" " AND value <> 'null'\n" " )\n" " )\n" ")\n" : "\n" "AND ash.instance_number = 1\n" "AND (\n" " COALESCE((c.value->>'instnum_is_null')::bool, true) = true\n" " OR (\n" " jsonb_typeof(c.value->'instnum_values') = 'array'\n" " AND jsonb_array_length(c.value->'instnum_values') > 0\n" " AND 1::number IN (\n" " SELECT value::numeric\n" " FROM jsonb_array_elements_text(\n" " c.value->'instnum_values'\n" " ) AS value\n" " WHERE value IS NOT NULL\n" " AND value <> 'null'\n" " )\n" " )\n" ")\n"; return "WITH ash_ctx AS MATERIALIZED (" " SELECT current_setting(" " 'dbms_ash_internal.context', true" " )::jsonb AS value" "), " "ash_disk AS MATERIALIZED (" + build_on_disk_ash_view_sql() + ") " "SELECT ash.* " "FROM ash_disk AS ash " "CROSS JOIN ash_ctx AS c " "WHERE COALESCE(" " (c.value->>'initialized')::bool," " false" " ) = true " "AND (c.value->>'dbid') IS NOT NULL " "AND (c.value->>'bsnap') IS NOT NULL " "AND (c.value->>'esnap') IS NOT NULL " "AND ash.dbid = " " (c.value->>'dbid')::numeric " "AND ash.snap_id > " " (c.value->>'bsnap')::numeric " "AND ash.snap_id <= " " (c.value->>'esnap')::numeric " + instance_predicate; } std::string build_ash_view_sql(void) { // Объединяет memory и persistent ASH по текущему report context. // При overlap приоритет имеет memory row с тем же sample identity. const std::string memory_tail = " CROSS JOIN ash_ctx AS c " " CROSS JOIN ash_flags AS f " "WHERE f.memory_enabled " "AND COALESCE(c.value->>'m_btime', c.value->>'btime') IS NOT NULL " "AND COALESCE(c.value->>'m_etime', c.value->>'etime') IS NOT NULL " "AND (NOT f.disk_enabled OR a.is_awr_sample)"; const std::string memory_sql = build_in_memory_ash_projection_sql(memory_tail); const std::string disk_sql = build_on_disk_ash_view_sql(); return "WITH ash_ctx AS MATERIALIZED (" " SELECT current_setting(" " 'dbms_ash_internal.context', true" " )::jsonb AS value" "), " "ash_flags AS MATERIALIZED (" " SELECT " " COALESCE((c.value->>'initialized')::bool, false) " " AND (c.value->>'dbid') IS NOT NULL " " AND COALESCE((c.value->>'m_en')::numeric, 1) <> 0 " " AND COALESCE((c.value->>'data_src')::numeric, 0) <> 2 " " AS memory_enabled, " " COALESCE((c.value->>'initialized')::bool, false) " " AND (c.value->>'dbid') IS NOT NULL " " AND COALESCE((c.value->>'d_en')::numeric, 1) <> 0 " " AND COALESCE((c.value->>'data_src')::numeric, 0) <> 1 " " AS disk_enabled " " FROM ash_ctx AS c" "), " "ash_memory AS MATERIALIZED (" + memory_sql + "), " "ash_disk AS MATERIALIZED (" " SELECT d.* " " FROM (" + disk_sql + ") AS d " " CROSS JOIN ash_ctx AS c " " CROSS JOIN ash_flags AS f " " WHERE f.disk_enabled " " AND COALESCE(" " c.value->>'d_btime'," " c.value->>'btime'" " ) IS NOT NULL " " AND COALESCE(" " c.value->>'d_etime'," " c.value->>'etime'" " ) IS NOT NULL " " AND d.sample_time >= " " COALESCE(" " c.value->>'d_btime'," " c.value->>'btime'" " )::date::timestamptz " " AND d.sample_time < (" " COALESCE(" " c.value->>'d_etime'," " c.value->>'etime'" " )::date::timestamptz " " + interval '1 day'" " )" "), " "unified_ash AS MATERIALIZED (" " SELECT m.* " " FROM ash_memory AS m " " UNION ALL " " SELECT d.* " " FROM ash_disk AS d " " WHERE NOT EXISTS (" " SELECT 1 " " FROM ash_memory AS m " " WHERE m.dbid = d.dbid " " AND m.instance_number = d.instance_number " " AND m.sample_id = d.sample_id" " )" ") " "SELECT u.* " "FROM unified_ash AS u " "CROSS JOIN ash_ctx AS c " "WHERE COALESCE(" " (c.value->>'initialized')::bool," " false" " ) = true " "AND (c.value->>'dbid') IS NOT NULL " "AND (c.value->>'btime') IS NOT NULL " "AND (c.value->>'etime') IS NOT NULL " "AND u.dbid = " " (c.value->>'dbid')::numeric " "AND (" " COALESCE(" " (c.value->>'instnum_is_null')::bool," " true" " ) = true " " OR (" " jsonb_typeof(c.value->'instnum_values') = 'array' " " AND jsonb_array_length(" " c.value->'instnum_values'" " ) > 0 " " AND u.instance_number IN (" " SELECT value::numeric " " FROM jsonb_array_elements_text(" " c.value->'instnum_values'" " ) AS value " " WHERE value IS NOT NULL " " AND value <> 'null'" " )" " )" ") " "AND (" " u.snap_id = 0 " " OR (" " (c.value->>'bsnap') IS NOT NULL " " AND (c.value->>'esnap') IS NOT NULL " " AND u.snap_id >= " " (c.value->>'bsnap')::numeric " " AND u.snap_id <= " " (c.value->>'esnap')::numeric" " )" ") " "AND u.sample_time >= " " (c.value->>'btime')::date::timestamptz " "AND u.sample_time < (" " (c.value->>'etime')::date::timestamptz " " + interval '1 day'" ")"; } std::string build_unified_dba_files_sql(void) { return "WITH ash_ctx AS MATERIALIZED (" " SELECT current_setting(" " 'dbms_ash_internal.context', true" " )::jsonb AS value" "), " "requested_dbid AS MATERIALIZED (" " SELECT CASE " " WHEN COALESCE((c.value->>'initialized')::bool, false) = true " " AND (c.value->>'dbid') IS NOT NULL " " THEN (c.value->>'dbid')::numeric " " ELSE NULL::number " " END AS dbid " " FROM ash_ctx AS c" "), " "local_database AS MATERIALIZED (" " SELECT " " pg_catalog.dbms_workload_repository_local_awr_dbid()::number AS local_dbid, " " d.oid AS database_oid, " " d.dattablespace AS dattablespace " " FROM pg_catalog.pg_database AS d " " WHERE d.datname = current_database()" "), " "used_tablespace_ids AS MATERIALIZED (" " SELECT ld.dattablespace AS tablespace_oid " " FROM local_database AS ld " " UNION " " SELECT DISTINCT c.reltablespace AS tablespace_oid " " FROM pg_catalog.pg_class AS c " " JOIN pg_catalog.pg_namespace AS n " " ON n.oid = c.relnamespace " " WHERE c.relkind IN ('r', 'i', 'S', 'm') " " AND c.reltablespace <> 0 " " AND n.nspname <> 'pg_toast' " " AND n.nspname NOT LIKE 'pg_temp_%' " " AND n.nspname NOT LIKE 'pg_toast_temp_%'" "), " "unified_files AS MATERIALIZED (" " SELECT " " t.oid::int8::number AS file_id, " " CASE " " WHEN t.spcname = 'pg_default' THEN " " ('base/' || ld.database_oid::text)::varchar2 " " WHEN t.spcname = 'pg_global' THEN " " 'global'::varchar2 " " ELSE COALESCE(" " NULLIF(pg_catalog.pg_tablespace_location(t.oid), ''), " " 'pg_tblspc/' || t.oid::text" " )::varchar2 " " END AS file_name, " " t.spcname::varchar2 AS tablespace_name " " FROM used_tablespace_ids AS u " " JOIN pg_catalog.pg_tablespace AS t " " ON t.oid = u.tablespace_oid " " CROSS JOIN local_database AS ld" ") " "SELECT f.file_id, " " f.file_name, " " f.tablespace_name " "FROM unified_files AS f " "CROSS JOIN requested_dbid AS r " "CROSS JOIN local_database AS ld " "WHERE r.dbid IS NOT NULL " " AND r.dbid = ld.local_dbid"; } std::string build_unified_dba_objects_sql(void) { return "WITH ash_ctx AS MATERIALIZED (" " SELECT current_setting(" " 'dbms_ash_internal.context', true" " )::jsonb AS value" "), " "requested_dbid AS MATERIALIZED (" " SELECT CASE " " WHEN COALESCE((c.value->>'initialized')::bool, false) = true " " AND (c.value->>'dbid') IS NOT NULL " " THEN (c.value->>'dbid')::numeric " " ELSE NULL::number " " END AS dbid " " FROM ash_ctx AS c" "), " "local_database AS MATERIALIZED (" " SELECT " " pg_catalog.dbms_workload_repository_local_awr_dbid()::number AS local_dbid, " " d.dattablespace AS dattablespace " " FROM pg_catalog.pg_database AS d " " WHERE d.datname = current_database()" "), " "unified_objects AS MATERIALIZED (" " SELECT " " 0::number AS con_id, " " n.nspname::varchar2 AS owner, " " c.oid::int8::number AS object_id, " " c.relname::varchar2 AS object_name, " " NULL::varchar2 AS subobject_name, " " CASE c.relkind " " WHEN 'r' THEN 'TABLE'::varchar2 " " WHEN 'p' THEN 'PARTITIONED TABLE'::varchar2 " " WHEN 'i' THEN 'INDEX'::varchar2 " " WHEN 'I' THEN 'PARTITIONED INDEX'::varchar2 " " WHEN 'S' THEN 'SEQUENCE'::varchar2 " " WHEN 'v' THEN 'VIEW'::varchar2 " " WHEN 'm' THEN 'MATERIALIZED VIEW'::varchar2 " " WHEN 'f' THEN 'FOREIGN TABLE'::varchar2 " " ELSE 'UNKNOWN'::varchar2 " " END AS object_type, " " CASE " " WHEN c.relkind IN ('r', 'i', 'S', 'm') THEN " " COALESCE(rel_ts.spcname, db_ts.spcname, 'pg_default')::varchar2 " " ELSE NULL::varchar2 " " END AS tablespace_name " " FROM pg_catalog.pg_class AS c " " JOIN pg_catalog.pg_namespace AS n " " ON n.oid = c.relnamespace " " CROSS JOIN local_database AS ld " " LEFT JOIN pg_catalog.pg_tablespace AS rel_ts " " ON rel_ts.oid = c.reltablespace " " LEFT JOIN pg_catalog.pg_tablespace AS db_ts " " ON db_ts.oid = ld.dattablespace " " WHERE c.relkind IN ('r', 'p', 'i', 'I', 'S', 'v', 'm', 'f') " " AND n.nspname <> 'pg_toast' " " AND n.nspname NOT LIKE 'pg_temp_%' " " AND n.nspname NOT LIKE 'pg_toast_temp_%'" ") " "SELECT u.con_id, " " u.owner, " " u.object_id, " " u.object_name, " " u.subobject_name, " " u.object_type, " " u.tablespace_name " "FROM unified_objects AS u " "CROSS JOIN requested_dbid AS r " "CROSS JOIN local_database AS ld " "WHERE r.dbid IS NOT NULL " " AND r.dbid = ld.local_dbid"; } std::string build_unified_plsql_subprograms_sql(void) { return "SELECT " " 0::number AS con_id, " " p.oid::int8::number AS object_id, " " 1::number AS subprogram_id, " " CASE p.prokind " " WHEN 'p' THEN 'PROCEDURE'::varchar2 " " ELSE 'FUNCTION'::varchar2 " " END AS object_type, " " n.nspname::varchar2 AS owner, " " p.proname::varchar2 AS object_name, " " NULL::varchar2 AS procedure_name, " " NULL::varchar2 AS overload " "FROM pg_catalog.pg_proc AS p " "JOIN pg_catalog.pg_namespace AS n " " ON n.oid = p.pronamespace " "WHERE p.prokind IN ('f', 'p') " " AND n.nspname <> 'pg_toast' " " AND n.nspname NOT LIKE 'pg_temp_%' " " AND n.nspname NOT LIKE 'pg_toast_temp_%'"; } std::string build_unified_service_names_sql(void) { return "WITH live_services AS MATERIALIZED (" " SELECT " " d.oid::int8::number AS service_hash, " " d.datname::varchar2 AS service " " FROM pg_catalog.pg_database AS d " " WHERE d.datname = current_database()" "), " "historical_services AS MATERIALIZED (" " SELECT " " NULL::number AS service_hash, " " NULL::varchar2 AS service " " WHERE false" ") " "SELECT l.service_hash, " " l.service " "FROM live_services AS l " "UNION ALL " "SELECT h.service_hash, " " h.service " "FROM historical_services AS h " "WHERE NOT EXISTS (" " SELECT 1 " " FROM live_services AS l " " WHERE l.service_hash = h.service_hash" " )"; } std::optional spi_lookup_current_sql_text(const std::string& sql_id) { return rudb::ash::find_sql_text(sql_id, false, rudb::ash::local_dbid()); } std::optional spi_lookup_historical_sql_text(const std::string& sql_id, Numeric dbid) { SpiScope spi("historical GET_SQLTEXT"); const char* query = "SELECT sql_text " "FROM pg_catalog.rudb_ash_history_sqltext " "WHERE sql_id = $1 AND dbid = $2 " "ORDER BY last_seen DESC LIMIT 1"; Oid argtypes[2] = {TEXTOID, NUMERICOID}; Datum values[2] = { CStringGetTextDatum(sql_id.c_str()), NumericGetDatum(dbid)}; const char nulls[2] = {' ', ' '}; const int spi_rc = SPI_execute_with_args(query, 2, argtypes, values, nulls, true, 1); if (spi_rc == SPI_OK_SELECT && SPI_processed == 1) { bool is_null = false; const Datum datum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &is_null); if (!is_null) { char* text_value = TextDatumGetCString(datum); std::string result(text_value); pfree(text_value); spi.finish(); return result; } } spi.finish(); return std::nullopt; } std::string call_text_entrypoint_zero(Datum (*entrypoint)(PG_FUNCTION_ARGS)) { LOCAL_FCINFO(local_fcinfo, 0); InitFunctionCallInfoData(*local_fcinfo, nullptr, 0, InvalidOid, nullptr, nullptr); const Datum datum = entrypoint(local_fcinfo); if (local_fcinfo->isnull) return ""; char* value = TextDatumGetCString(datum); std::string result(value); pfree(value); return result; } std::string call_text_entrypoint_bool(Datum (*entrypoint)(PG_FUNCTION_ARGS), const std::optional& value) { LOCAL_FCINFO(local_fcinfo, 1); InitFunctionCallInfoData(*local_fcinfo, nullptr, 1, InvalidOid, nullptr, nullptr); local_fcinfo->args[0].isnull = !value.has_value(); if (value.has_value()) local_fcinfo->args[0].value = BoolGetDatum(*value); const Datum datum = entrypoint(local_fcinfo); if (local_fcinfo->isnull) return ""; char* rendered = TextDatumGetCString(datum); std::string result(rendered); pfree(rendered); return result; } bool context_is_initialized(void) { return report_context_store().context.initialized; } bool numeric_exact_flag(Numeric value, int32 expected) { return value != nullptr && numeric_eq_value(value, int32_to_numeric(expected)); } std::optional numeric_to_int64_optional(Numeric value) { if (value == nullptr) return std::nullopt; return DatumGetInt64(DirectFunctionCall1(numeric_int8, NumericGetDatum(value))); } std::optional date_to_timestamptz_optional(bool is_null, DateADT value) { if (is_null) return std::nullopt; return DatumGetTimestampTz( DirectFunctionCall1(date_timestamptz, DateADTGetDatum(value))); } std::optional date_to_range_end_timestamptz_optional(bool is_null, DateADT value) { const std::optional start = date_to_timestamptz_optional(is_null, value); if (!start.has_value()) return std::nullopt; return *start + USECS_PER_DAY; } rudb::ash::HistoryFilter build_history_filter(bool history_path, bool global_scope) { // NULL списка экземпляров не ограничивает выборку, пустой список не даёт // совпадений; локальный путь в режиме одного экземпляра использует экземпляр 1. rudb::ash::HistoryFilter filter; if (!context_is_initialized()) return filter; const ReportContext& context = report_context_store().context; filter.dbid = numeric_to_int64_optional(context.dbid); filter.global_scope = global_scope; filter.instance_list_is_null = context.instnum_is_null || context.instnum == nullptr; filter.instance_list_is_empty = false; filter.instance_filter_enabled = !filter.instance_list_is_null; filter.instance_number = global_scope ? std::nullopt : std::optional(1); if (!context.instnum_is_null && context.instnum != nullptr) { for (const std::string& value : numeric_array_to_strings(context.instnum)) { Numeric numeric_value = DatumGetNumeric(DirectFunctionCall3(numeric_in, CStringGetDatum(value.c_str()), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1))); const int64 instance_number = DatumGetInt64(DirectFunctionCall1(numeric_int8, NumericGetDatum(numeric_value))); filter.instance_numbers.push_back(instance_number); } filter.instance_list_is_empty = filter.instance_numbers.empty(); if (!global_scope) { if (std::find(filter.instance_numbers.begin(), filter.instance_numbers.end(), 1) != filter.instance_numbers.end()) filter.instance_number = 1; else if (filter.instance_numbers.empty()) filter.instance_number = std::nullopt; else filter.instance_number = std::nullopt; } } if (history_path) { const bool begin_is_null = context.d_btime_is_null ? context.btime_is_null : false; const DateADT begin = context.d_btime_is_null ? context.btime : context.d_btime; const bool end_is_null = context.d_etime_is_null ? context.etime_is_null : false; const DateADT end = context.d_etime_is_null ? context.etime : context.d_etime; filter.begin_time = date_to_timestamptz_optional(begin_is_null, begin); filter.end_time = date_to_range_end_timestamptz_optional(end_is_null, end); filter.end_time_exclusive = filter.end_time.has_value(); filter.begin_snap_id = numeric_to_int64_optional(context.bsnap); filter.end_snap_id = numeric_to_int64_optional(context.esnap); } else { const bool begin_is_null = context.m_btime_is_null ? context.btime_is_null : false; const DateADT begin = context.m_btime_is_null ? context.btime : context.m_btime; const bool end_is_null = context.m_etime_is_null ? context.etime_is_null : false; const DateADT end = context.m_etime_is_null ? context.etime : context.m_etime; filter.begin_time = date_to_timestamptz_optional(begin_is_null, begin); filter.end_time = date_to_range_end_timestamptz_optional(end_is_null, end); filter.end_time_exclusive = filter.end_time.has_value(); } return filter; } bool memory_path_enabled(void) { if (!context_is_initialized()) return false; const ReportContext& context = report_context_store().context; if (context.dbid_is_null || context.dbid == nullptr) return false; if (context.m_en != nullptr && numeric_exact_flag(context.m_en, 0)) return false; if (context.data_src != nullptr && numeric_exact_flag(context.data_src, 2)) return false; return true; } void put_sample_row(ReturnSetInfo* rsinfo, const rudb::ash::SampleRow& row) { Datum values[17]; bool nulls[17] = {false}; values[0] = Int64GetDatum(static_cast(row.sample_sequence)); values[1] = TimestampTzGetDatum(row.sample_time); values[2] = Int64GetDatum(row.dbid); values[3] = Int64GetDatum(row.instance_number); values[4] = Int64GetDatum(row.session_id); values[5] = Int64GetDatum(row.session_serial); values[6] = Int64GetDatum(row.session_generation); values[7] = ObjectIdGetDatum(row.user_id); values[8] = CStringGetTextDatum(row.sql_id.c_str()); values[9] = CStringGetTextDatum(row.wait_class.c_str()); values[10] = CStringGetTextDatum(row.event_name.c_str()); values[11] = CStringGetTextDatum(row.module_name.c_str()); values[12] = CStringGetTextDatum(row.application_name.c_str()); values[13] = CStringGetTextDatum(row.state.c_str()); values[14] = CStringGetTextDatum(row.sql_text.c_str()); values[15] = BoolGetDatum(row.is_awr_sample); values[16] = Int64GetDatum(row.snap_id); if (row.user_id == InvalidOid) nulls[7] = true; if (row.sql_id.empty()) nulls[8] = true; if (row.wait_class.empty()) nulls[9] = true; if (row.event_name.empty()) nulls[10] = true; if (row.module_name.empty()) nulls[11] = true; if (row.application_name.empty()) nulls[12] = true; if (row.state.empty()) nulls[13] = true; if (row.sql_text.empty()) nulls[14] = true; tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls); } void emit_sample_rows(FunctionCallInfo fcinfo, const std::vector& rows) { ReturnSetInfo* rsinfo = reinterpret_cast(fcinfo->resultinfo); if (rsinfo == nullptr || !IsA(rsinfo, ReturnSetInfo)) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("set-valued function called in context that cannot accept a set"))); } InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC | MAT_SRF_BLESS); for (const rudb::ash::SampleRow& row : rows) put_sample_row(rsinfo, row); } } // namespace static void raise_feature_not_supported(const char* message) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("%s", message))); } void raise_unsupported_function(const char* function_name, const char* detail = nullptr) { if (detail == nullptr) raise_feature_not_supported(psprintf("функция DBMS_ASH_INTERNAL.%s не поддерживается", function_name)); else raise_feature_not_supported(psprintf("функция DBMS_ASH_INTERNAL.%s не поддерживается: %s", function_name, detail)); } Datum dbms_ash_internal_ash_phase_execution(PG_FUNCTION_ARGS) { raise_unsupported_function("ASH_PHASE_EXECUTION"); PG_RETURN_NULL(); } Datum dbms_ash_internal_ash_rollup_sql_1d(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { ensure_context_guc_defined(); if (fcinfo->nargs < 3) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_ASH_INTERNAL.ASH_ROLLUP_SQL_1D требует первые три аргумента"))); } const std::string select_list = oracle_varchar_fragment(text_arg_optional(fcinfo, 0)); const std::string dimension = oracle_varchar_fragment(text_arg_optional(fcinfo, 1)); const std::string xtra_select_list = oracle_varchar_fragment(text_arg_optional(fcinfo, 2)); const std::string predicate = oracle_varchar_fragment(text_arg_optional(fcinfo, 3)); const std::string join_with = oracle_varchar_fragment(text_arg_optional(fcinfo, 4)); const std::string join_predicate = oracle_varchar_fragment(text_arg_optional(fcinfo, 5)); const bool min_perc_omitted = fcinfo->nargs <= 6; const bool max_rank_omitted = fcinfo->nargs <= 7; const std::optional min_perc = numeric_arg_optional(fcinfo, 6); const std::optional max_rank = numeric_arg_optional(fcinfo, 7); const bool is_awr_section = fcinfo->nargs > 8 && !PG_ARGISNULL(8) && PG_GETARG_BOOL(8); const std::optional is_global_awr = fcinfo->nargs <= 9 || PG_ARGISNULL(9) ? std::nullopt : std::optional(PG_GETARG_BOOL(9)); const std::string source_sql = is_awr_section ? call_text_entrypoint_bool( dbms_ash_internal_ash_sql_for_awr, is_global_awr) : call_text_entrypoint_zero( dbms_ash_internal_ash_view_sql); const std::string min_perc_sql = min_perc_omitted ? "1" : (min_perc.has_value() ? format_rollup_numeric_literal(*min_perc) : ""); const std::string max_rank_sql = max_rank_omitted ? "5" : (max_rank.has_value() ? format_rollup_numeric_literal(*max_rank) : ""); const std::string xtra_select_sql = xtra_select_list.empty() ? "" : xtra_select_list + " , "; const std::string join_with_sql = join_with.empty() ? "" : ", " + join_with + " "; const std::string predicate_sql = predicate.empty() ? "" : " " + predicate + " "; const std::string join_predicate_sql = join_predicate.empty() ? "" : " " + join_predicate + " "; const std::string nsmpls_sql = "NULLIF((" "current_setting(" "'dbms_ash_internal.context', true" ")::jsonb->>'nsmpls'" ")::numeric, 0)"; std::string sql = "SELECT /*+ ALL_ROWS */ " + select_list + " FROM (" "SELECT " + dimension + " , " + xtra_select_sql + "COUNT(*)::number AS dim_count, " "(" "COUNT(*)::numeric * 100 " "/ NULLIF(" "SUM(COUNT(*)) OVER (), " "0" ")" ")::number AS dim_percentage, " "(" "COUNT(*)::numeric / " + nsmpls_sql + ")::number AS dim_act_sessions, " "RANK() OVER (" "ORDER BY COUNT(*) DESC, " + dimension + ")::number AS dim_rank " "FROM (" + source_sql + ") a " "WHERE 1 = 1" + predicate_sql + " " + "GROUP BY " + dimension + ") ash " + join_with_sql + "WHERE ash.dim_percentage >= " + min_perc_sql + " " "AND ash.dim_rank <= " + max_rank_sql + join_predicate_sql + " " + "ORDER BY ash.dim_rank"; check_rollup_result_length(sql); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.ASH_ROLLUP_SQL_1D"); } Datum dbms_ash_internal_ash_rollup_sql_2d(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { ensure_context_guc_defined(); if (fcinfo->nargs < 3) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_ASH_INTERNAL.ASH_ROLLUP_SQL_2D требует первые три аргумента"))); } const std::string select_list = oracle_varchar_fragment(text_arg_optional(fcinfo, 0)); const std::string dimension1 = oracle_varchar_fragment(text_arg_optional(fcinfo, 1)); const std::string dimension2 = oracle_varchar_fragment(text_arg_optional(fcinfo, 2)); const std::string xtra_select_list = oracle_varchar_fragment(text_arg_optional(fcinfo, 3)); const std::string predicate = oracle_varchar_fragment(text_arg_optional(fcinfo, 4)); const std::string join_with = oracle_varchar_fragment(text_arg_optional(fcinfo, 5)); const std::string join_predicate = oracle_varchar_fragment(text_arg_optional(fcinfo, 6)); const bool min_d1_perc_omitted = fcinfo->nargs <= 7; const bool max_d1_rank_omitted = fcinfo->nargs <= 8; const bool min_d12_perc_omitted = fcinfo->nargs <= 9; const bool max_d12_rank_omitted = fcinfo->nargs <= 10; const bool d12_min_cnt_omitted = fcinfo->nargs <= 11; const std::optional min_d1_perc = numeric_arg_optional(fcinfo, 7); const std::optional max_d1_rank = numeric_arg_optional(fcinfo, 8); const std::optional min_d12_perc = numeric_arg_optional(fcinfo, 9); const std::optional max_d12_rank = numeric_arg_optional(fcinfo, 10); const std::optional d12_min_cnt = numeric_arg_optional(fcinfo, 11); const bool is_awr_section = fcinfo->nargs > 12 && !PG_ARGISNULL(12) && PG_GETARG_BOOL(12); const std::optional is_global_awr = fcinfo->nargs <= 13 || PG_ARGISNULL(13) ? std::nullopt : std::optional(PG_GETARG_BOOL(13)); const std::string source_sql = is_awr_section ? call_text_entrypoint_bool( dbms_ash_internal_ash_sql_for_awr, is_global_awr) : call_text_entrypoint_zero( dbms_ash_internal_ash_view_sql); const std::string min_d1_perc_sql = min_d1_perc_omitted ? "1" : (min_d1_perc.has_value() ? format_rollup_numeric_literal(*min_d1_perc) : ""); const std::string max_d1_rank_sql = max_d1_rank_omitted ? "5" : (max_d1_rank.has_value() ? format_rollup_numeric_literal(*max_d1_rank) : ""); const std::string min_d12_perc_sql = min_d12_perc_omitted ? "1" : (min_d12_perc.has_value() ? format_rollup_numeric_literal(*min_d12_perc) : ""); const std::string max_d12_rank_sql = max_d12_rank_omitted ? "3" : (max_d12_rank.has_value() ? format_rollup_numeric_literal(*max_d12_rank) : ""); const std::string d12_min_cnt_sql = d12_min_cnt_omitted ? "1" : (d12_min_cnt.has_value() ? format_rollup_numeric_literal(*d12_min_cnt) : ""); const std::string xtra_select_sql = xtra_select_list.empty() ? "" : xtra_select_list + " , "; const std::string predicate_sql = predicate.empty() ? "" : " " + predicate + " "; const std::string join_with_sql = join_with.empty() ? "" : ", " + join_with + " "; const std::string join_predicate_sql = join_predicate.empty() ? "" : " " + join_predicate + " "; std::string sql = "SELECT /*+ ALL_ROWS */ " + select_list + " FROM (" "SELECT d12aa_ash.* " "FROM (" "SELECT d12gb_ash.*, " "(" "dim1_count::numeric * 100 " "/ NULLIF(" "SUM(dim12_count) OVER (), " "0" ")" ")::number AS dim1_percentage, " "DENSE_RANK() OVER (" "ORDER BY dim1_count DESC, " + dimension1 + ")::number AS dim1_rank " "FROM (" "SELECT " + dimension1 + " , " + dimension2 + " , " + xtra_select_sql + "COUNT(*)::number AS dim12_count, " "(" "COUNT(*)::numeric * 100 " "/ NULLIF(" "SUM(COUNT(*)) OVER (), " "0" ")" ")::number AS dim12_percentage, " "RANK() OVER (" "PARTITION BY " + dimension1 + " " "ORDER BY COUNT(*) DESC, " + dimension2 + ")::number AS dim12_rank, " "SUM(COUNT(*)) OVER (" "PARTITION BY " + dimension1 + ")::number AS dim1_count " "FROM (" + source_sql + ") a " "WHERE 1 = 1" + predicate_sql + " " "GROUP BY " + dimension1 + ", " + dimension2 + ") d12gb_ash" ") d12aa_ash " "WHERE d12aa_ash.dim1_rank <= " + max_d1_rank_sql + " " "AND d12aa_ash.dim1_percentage >= " + min_d1_perc_sql + " " "AND d12aa_ash.dim12_rank <= " + max_d12_rank_sql + " " "AND (" "d12aa_ash.dim12_rank <= " + d12_min_cnt_sql + " " "OR (" "d12aa_ash.dim12_rank > " + d12_min_cnt_sql + " " "AND d12aa_ash.dim12_percentage >= " + min_d12_perc_sql + ")" ") " "ORDER BY d12aa_ash.dim1_rank, " "d12aa_ash.dim12_rank" ") ash " + join_with_sql + "WHERE 1 = 1" + join_predicate_sql + " " "ORDER BY ash.dim1_rank, ash.dim12_rank"; check_rollup_result_length(sql); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.ASH_ROLLUP_SQL_2D"); } Datum dbms_ash_internal_ash_rollup_sql_3d(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { ensure_context_guc_defined(); if (fcinfo->nargs < 4) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_ASH_INTERNAL.ASH_ROLLUP_SQL_3D требует первые четыре аргумента"))); } const std::string select_list = oracle_varchar_fragment(text_arg_optional(fcinfo, 0)); const std::string dimension1 = oracle_varchar_fragment(text_arg_optional(fcinfo, 1)); const std::string dimension2 = oracle_varchar_fragment(text_arg_optional(fcinfo, 2)); const std::string dimension3 = oracle_varchar_fragment(text_arg_optional(fcinfo, 3)); const std::string xtra_select_list = oracle_varchar_fragment(text_arg_optional(fcinfo, 4)); const std::string predicate = oracle_varchar_fragment(text_arg_optional(fcinfo, 5)); const std::string join_with = oracle_varchar_fragment(text_arg_optional(fcinfo, 6)); const std::string join_predicate = oracle_varchar_fragment(text_arg_optional(fcinfo, 7)); const bool min_d1_perc_omitted = fcinfo->nargs <= 8; const bool max_d1_rank_omitted = fcinfo->nargs <= 9; const bool min_d12_perc_omitted = fcinfo->nargs <= 10; const bool max_d12_rank_omitted = fcinfo->nargs <= 11; const bool min_d123_perc_omitted = fcinfo->nargs <= 12; const bool max_d123_rank_omitted = fcinfo->nargs <= 13; const bool d12_min_cnt_omitted = fcinfo->nargs <= 14; const bool d123_min_cnt_omitted = fcinfo->nargs <= 15; const std::optional min_d1_perc = numeric_arg_optional(fcinfo, 8); const std::optional max_d1_rank = numeric_arg_optional(fcinfo, 9); const std::optional min_d12_perc = numeric_arg_optional(fcinfo, 10); const std::optional max_d12_rank = numeric_arg_optional(fcinfo, 11); const std::optional min_d123_perc = numeric_arg_optional(fcinfo, 12); const std::optional max_d123_rank = numeric_arg_optional(fcinfo, 13); const std::optional d12_min_cnt = numeric_arg_optional(fcinfo, 14); const std::optional d123_min_cnt = numeric_arg_optional(fcinfo, 15); const bool is_awr_section = fcinfo->nargs > 16 && !PG_ARGISNULL(16) && PG_GETARG_BOOL(16); const std::optional is_global_awr = fcinfo->nargs <= 17 || PG_ARGISNULL(17) ? std::nullopt : std::optional(PG_GETARG_BOOL(17)); const std::string source_sql = is_awr_section ? call_text_entrypoint_bool( dbms_ash_internal_ash_sql_for_awr, is_global_awr) : call_text_entrypoint_zero( dbms_ash_internal_ash_view_sql); const std::string min_d1_perc_sql = min_d1_perc_omitted ? "1" : (min_d1_perc.has_value() ? format_rollup_numeric_literal(*min_d1_perc) : ""); const std::string max_d1_rank_sql = max_d1_rank_omitted ? "5" : (max_d1_rank.has_value() ? format_rollup_numeric_literal(*max_d1_rank) : ""); const std::string min_d12_perc_sql = min_d12_perc_omitted ? "1" : (min_d12_perc.has_value() ? format_rollup_numeric_literal(*min_d12_perc) : ""); const std::string max_d12_rank_sql = max_d12_rank_omitted ? "3" : (max_d12_rank.has_value() ? format_rollup_numeric_literal(*max_d12_rank) : ""); const std::string min_d123_perc_sql = min_d123_perc_omitted ? "1" : (min_d123_perc.has_value() ? format_rollup_numeric_literal(*min_d123_perc) : ""); const std::string max_d123_rank_sql = max_d123_rank_omitted ? "1" : (max_d123_rank.has_value() ? format_rollup_numeric_literal(*max_d123_rank) : ""); const std::string d12_min_cnt_sql = d12_min_cnt_omitted ? "1" : (d12_min_cnt.has_value() ? format_rollup_numeric_literal(*d12_min_cnt) : ""); const std::string d123_min_cnt_sql = d123_min_cnt_omitted ? "1" : (d123_min_cnt.has_value() ? format_rollup_numeric_literal(*d123_min_cnt) : ""); const std::string xtra_select_sql = xtra_select_list.empty() ? "" : xtra_select_list + " , "; const std::string predicate_sql = predicate.empty() ? "" : " " + predicate + " "; const std::string join_with_sql = join_with.empty() ? "" : ", " + join_with + " "; const std::string join_predicate_sql = join_predicate.empty() ? "" : " " + join_predicate + " "; std::string sql = "SELECT /*+ ALL_ROWS */ " + select_list + " FROM (" "SELECT d123aa_ash.* " "FROM (" "SELECT d123gb_ash.*, " "(" "dim12_count::numeric * 100 " "/ NULLIF(" "SUM(dim123_count) OVER (), " "0" ")" ")::number AS dim12_percentage, " "DENSE_RANK() OVER (" "PARTITION BY " + dimension1 + " " "ORDER BY dim12_count DESC, " + dimension2 + ")::number AS dim12_rank, " "(" "dim1_count::numeric * 100 " "/ NULLIF(" "SUM(dim123_count) OVER (), " "0" ")" ")::number AS dim1_percentage, " "DENSE_RANK() OVER (" "ORDER BY dim1_count DESC, " + dimension1 + ")::number AS dim1_rank " "FROM (" "SELECT " + dimension1 + " , " + dimension2 + " , " + dimension3 + " , " + xtra_select_sql + "COUNT(*)::number AS dim123_count, " "(" "COUNT(*)::numeric * 100 " "/ NULLIF(" "SUM(COUNT(*)) OVER (), " "0" ")" ")::number AS dim123_percentage, " "RANK() OVER (" "PARTITION BY " + dimension1 + ", " + dimension2 + " " "ORDER BY COUNT(*) DESC, " + dimension3 + ")::number AS dim123_rank, " "SUM(COUNT(*)) OVER (" "PARTITION BY " + dimension1 + ", " + dimension2 + ")::number AS dim12_count, " "SUM(COUNT(*)) OVER (" "PARTITION BY " + dimension1 + ")::number AS dim1_count " "FROM (" + source_sql + ") a " "WHERE 1 = 1" + predicate_sql + " " "GROUP BY " + dimension1 + ", " + dimension2 + ", " + dimension3 + ") d123gb_ash" ") d123aa_ash " "WHERE d123aa_ash.dim1_rank <= " + max_d1_rank_sql + " " "AND d123aa_ash.dim1_percentage >= " + min_d1_perc_sql + " " "AND d123aa_ash.dim12_rank <= " + max_d12_rank_sql + " " "AND d123aa_ash.dim123_rank <= " + max_d123_rank_sql + " " "AND (" "d123aa_ash.dim12_rank <= " + d12_min_cnt_sql + " " "OR (" "d123aa_ash.dim12_rank > " + d12_min_cnt_sql + " " "AND d123aa_ash.dim12_percentage >= " + min_d12_perc_sql + ")" ") " "AND (" "d123aa_ash.dim123_rank <= " + d123_min_cnt_sql + " " "OR (" "d123aa_ash.dim123_rank > " + d123_min_cnt_sql + " " "AND d123aa_ash.dim123_percentage >= " + min_d123_perc_sql + ")" ") " "ORDER BY d123aa_ash.dim1_rank, " "d123aa_ash.dim12_rank, " "d123aa_ash.dim123_rank" ") ash " + join_with_sql + "WHERE 1 = 1" + join_predicate_sql + " " "ORDER BY ash.dim1_rank, " "ash.dim12_rank, " "ash.dim123_rank"; check_rollup_result_length(sql); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.ASH_ROLLUP_SQL_3D"); } Datum dbms_ash_internal_ash_rollup_xml_1d(PG_FUNCTION_ARGS) { raise_unsupported_function("ASH_ROLLUP_XML_1D", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_ash_rollup_xml_2d(PG_FUNCTION_ARGS) { raise_unsupported_function("ASH_ROLLUP_XML_2D", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_ash_sql_for_awr(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { ensure_context_guc_defined(); const bool global_scope = fcinfo->nargs > 0 && !PG_ARGISNULL(0) && PG_GETARG_BOOL(0); const std::string sql = build_ash_sql_for_awr(global_scope); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.ASH_SQL_FOR_AWR"); } Datum dbms_ash_internal_ash_view_sql(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { ensure_context_guc_defined(); const std::string sql = build_ash_view_sql(); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.ASH_VIEW_SQL"); } Datum dbms_ash_internal_build_action_tag(PG_FUNCTION_ARGS) { raise_unsupported_function("BUILD_ACTION_TAG", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_build_database_header_tag(PG_FUNCTION_ARGS) { raise_unsupported_function("BUILD_DATABASE_HEADER_TAG", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_build_event_tag(PG_FUNCTION_ARGS) { raise_unsupported_function("BUILD_EVENT_TAG", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_build_service_module_tag(PG_FUNCTION_ARGS) { raise_unsupported_function("BUILD_SERVICE_MODULE_TAG", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_build_session_tag(PG_FUNCTION_ARGS) { raise_unsupported_function("BUILD_SESSION_TAG", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_build_sql_tag(PG_FUNCTION_ARGS) { raise_unsupported_function("BUILD_SQL_TAG", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_format_plsql(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { const std::optional owner = text_arg_optional(fcinfo, 0); const std::optional object_name = text_arg_optional(fcinfo, 1); const std::optional subprogram_name = text_arg_optional(fcinfo, 3); const std::optional overload = text_arg_optional(fcinfo, 4); const std::optional result = format_plsql_name(owner, object_name, subprogram_name, overload); if (!result.has_value()) PG_RETURN_NULL(); return PointerGetDatum(cstring_to_text(result->c_str())); }, "DBMS_ASH_INTERNAL.FORMAT_PLSQL"); } Datum dbms_ash_internal_getpackageversion(PG_FUNCTION_ARGS) { raise_unsupported_function("GETPACKAGEVERSION"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_ash_heading(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_ASH_HEADING"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_blksid_active(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_BLKSID_ACTIVE"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_blksid_program(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_BLKSID_PROGRAM"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_blksid_user(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_BLKSID_USER"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_blksid_xids(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_BLKSID_XIDS"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_blk_str(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_BLK_STR"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_cpuinfo_xml(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_CPUINFO_XML", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_latch_name(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_LATCH_NAME"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_obj_name(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { const std::optional owner = text_arg_optional(fcinfo, 0); const std::optional object_name = text_arg_optional(fcinfo, 1); const std::optional subobject_name = text_arg_optional(fcinfo, 2); const std::optional object_type = text_arg_optional(fcinfo, 3); const std::string result = format_object_name(owner, object_name, subobject_name, object_type); return PointerGetDatum(cstring_to_text(result.c_str())); }, "DBMS_ASH_INTERNAL.GET_OBJ_NAME"); } Datum dbms_ash_internal_get_plsql_name(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { const std::optional object_id = numeric_arg_optional(fcinfo, 2); const std::optional subprogram_id = numeric_arg_optional(fcinfo, 3); // Oracle sentinel object_id = -1 всегда обозначает SQL вне зависимости // от subprogram_id и любых значений compatibility context. if (object_id.has_value() && numeric_exact_flag(*object_id, -1)) return PointerGetDatum(cstring_to_text("SQL")); const std::optional resolved_name = lookup_unified_plsql_name(object_id, subprogram_id); if (resolved_name.has_value()) return PointerGetDatum(cstring_to_text(resolved_name->c_str())); const std::string fallback_name = format_unknown_plsql_id(object_id, subprogram_id); return PointerGetDatum(cstring_to_text(fallback_name.c_str())); }, "DBMS_ASH_INTERNAL.GET_PLSQL_NAME"); } Datum dbms_ash_internal_get_sid_active(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_SID_ACTIVE"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_sid_str(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_SID_STR"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_slot_width(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { // Ширина вычисляется из контекста отчёта с учётом ограничения текущего // типа DATE, который хранит только календарный день. const std::optional usedisk = numeric_arg_optional(fcinfo, 0); const ReportContext& context = report_context_store().context; const std::optional duration_seconds = context_duration_seconds(context); const std::optional requested_width = context.swidth == nullptr ? std::nullopt : std::optional(context.swidth); const std::optional result = call_compute_slot_width(duration_seconds, requested_width, usedisk); if (!result.has_value()) PG_RETURN_NULL(); return NumericGetDatum(result.value()); }, "DBMS_ASH_INTERNAL.GET_SLOT_WIDTH"); } Datum dbms_ash_internal_get_sqltext(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { static constexpr const char* kSqlTextNotAvailable = "** SQL Text Not Available **"; const std::optional sqlid = text_arg_optional(fcinfo, 0); const std::optional chnum = numeric_arg_optional(fcinfo, 1); // Пустой SQL_ID в Oracle эквивалентен NULL и проверяется до контекста. if (!sqlid.has_value() || sqlid->empty()) PG_RETURN_NULL(); const ReportContext& context = report_context_store().context; if (!context.initialized) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("контекст DBMS_ASH_INTERNAL не инициализирован"), errdetail("Сначала вызовите DBMS_ASH_INTERNAL.INITIALIZE()."))); } // После неуспешного INITIALIZE(NULL, ...) Oracle-совместимо возвращаем sentinel. if (context.dbid_is_null || context.dbid == nullptr) return PointerGetDatum(cstring_to_text(kSqlTextNotAvailable)); const Numeric local_dbid = int64_to_numeric(rudb::ash::local_dbid()); const bool context_is_local = numeric_eq_value(context.dbid, local_dbid); const bool current_child_supported = !chnum.has_value() || numeric_eq_value(*chnum, int32_to_numeric(0)); if (context_is_local && current_child_supported) { if (const std::optional sql_text = spi_lookup_current_sql_text(*sqlid); sql_text.has_value()) { return PointerGetDatum(cstring_to_text(sql_text->c_str())); } } // Historical lookup использует только DBID из контекста и игнорирует child. if (const std::optional historical_sql = spi_lookup_historical_sql_text(*sqlid, context.dbid); historical_sql.has_value()) { return PointerGetDatum(cstring_to_text(historical_sql->c_str())); } return PointerGetDatum(cstring_to_text(kSqlTextNotAvailable)); }, "DBMS_ASH_INTERNAL.GET_SQLTEXT"); } Datum dbms_ash_internal_get_sql_plan_info(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_SQL_PLAN_INFO"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_sql_plan_perc(PG_FUNCTION_ARGS) { raise_unsupported_function("GET_SQL_PLAN_PERC"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_user_name(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { const std::optional user_id = numeric_arg_optional(fcinfo, 0); const std::string result = format_user_name(user_id); return PointerGetDatum(cstring_to_text(result.c_str())); }, "DBMS_ASH_INTERNAL.GET_USER_NAME"); } Datum dbms_ash_internal_in_memory_ash_view_sql(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { const std::string sql = build_in_memory_ash_view_sql(); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.IN_MEMORY_ASH_VIEW_SQL"); } Datum dbms_ash_internal_on_disk_ash_view_sql(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { const std::string sql = build_on_disk_ash_view_sql(); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.ON_DISK_ASH_VIEW_SQL"); } Datum dbms_ash_internal_report_ashviewer_xml(PG_FUNCTION_ARGS) { raise_unsupported_function("REPORT_ASHVIEWER_XML", "XMLTYPE недоступен"); PG_RETURN_NULL(); } Datum dbms_ash_internal_sample_time_to_id(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { // Текущий тип DATE хранит только календарный день. const std::optional stime = date_arg_optional(fcinfo, 0); const std::optional usedisk = numeric_arg_optional(fcinfo, 1); const ReportContext& context = report_context_store().context; const std::optional duration_seconds = context_duration_seconds(context); const std::optional requested_width = context.swidth == nullptr ? std::nullopt : std::optional(context.swidth); if (!stime.has_value()) PG_RETURN_NULL(); const std::optional width = call_compute_slot_width(duration_seconds, requested_width, usedisk); if (!width.has_value()) PG_RETURN_NULL(); const Numeric epoch_seconds = int64_to_numeric(date_to_unix_seconds(*stime)); return NumericGetDatum( numeric_trunc_value(numeric_div_value(epoch_seconds, width.value()), 0)); }, "DBMS_ASH_INTERNAL.SAMPLE_TIME_TO_ID"); } Datum dbms_ash_internal_shrink_string(PG_FUNCTION_ARGS) { raise_unsupported_function("SHRINK_STRING"); PG_RETURN_NULL(); } Datum dbms_ash_internal_slot_id_to_time(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { // Возвращаемый DATE не сохраняет время суток в текущем слое типов RUDB. const std::optional slotid = numeric_arg_optional(fcinfo, 0); const std::optional usedisk = numeric_arg_optional(fcinfo, 1); const std::optional frmt = text_arg_optional(fcinfo, 2); const std::optional collen = numeric_arg_optional(fcinfo, 3); const ReportContext& context = report_context_store().context; const std::optional duration_seconds = context_duration_seconds(context); const std::optional requested_width = context.swidth == nullptr ? std::nullopt : std::optional(context.swidth); const std::optional width = call_compute_slot_width(duration_seconds, requested_width, usedisk); if (!width.has_value()) return PointerGetDatum(cstring_to_text(" ( min)")); if (!slotid.has_value()) { const std::string suffix = format_duration_suffix(width.value()); return PointerGetDatum(cstring_to_text(suffix.c_str())); } const Numeric slot_start_numeric = numeric_mul_value(slotid.value(), width.value()); const Numeric slot_end_numeric = numeric_add_value(slot_start_numeric, width.value()); Numeric display_start_numeric = slot_start_numeric; Numeric display_end_numeric = slot_end_numeric; if (!context.btime_is_null) { const Numeric begin_numeric = date_to_unix_seconds_numeric(context.btime); if (numeric_cmp_value(display_start_numeric, begin_numeric) < 0) display_start_numeric = begin_numeric; } if (!context.etime_is_null) { const Numeric end_numeric = date_to_unix_seconds_numeric(context.etime); if (numeric_cmp_value(display_end_numeric, end_numeric) > 0) display_end_numeric = end_numeric; } const Numeric duration = numeric_sub_value(display_end_numeric, display_start_numeric); const std::string suffix = format_duration_suffix(duration); if (!frmt.has_value() || frmt->empty()) { return PointerGetDatum(cstring_to_text(suffix.c_str())); } char* timestamp_cstring = text_to_cstring(render_slot_time_text(display_start_numeric, *frmt)); std::string timestamp_text(timestamp_cstring); pfree(timestamp_cstring); int32 target_width = 0; if (collen.has_value()) { target_width = DatumGetInt32( DirectFunctionCall1(numeric_int4, NumericGetDatum(collen.value()))); } const int32 timestamp_characters = pg_mbstrlen(timestamp_text.c_str()); const int32 suffix_characters = pg_mbstrlen(suffix.c_str()); const int32 base_characters = timestamp_characters + suffix_characters; std::string result = timestamp_text; if (target_width > base_characters) { result.append(static_cast(target_width - base_characters), ' '); } result += suffix; return PointerGetDatum(cstring_to_text(result.c_str())); }, "DBMS_ASH_INTERNAL.SLOT_ID_TO_TIME"); } Datum dbms_ash_internal_unified_dba_files(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { ensure_context_guc_defined(); const std::string sql = build_unified_dba_files_sql(); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.UNIFIED_DBA_FILES"); } Datum dbms_ash_internal_unified_dba_objects(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { ensure_context_guc_defined(); const std::string sql = build_unified_dba_objects_sql(); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.UNIFIED_DBA_OBJECTS"); } Datum dbms_ash_internal_unified_plsql_subprograms(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { ensure_context_guc_defined(); const std::string sql = build_unified_plsql_subprograms_sql(); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.UNIFIED_PLSQL_SUBPROGRAMS"); } Datum dbms_ash_internal_unified_service_names(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { ensure_context_guc_defined(); const std::string sql = build_unified_service_names_sql(); return PointerGetDatum(cstring_to_text(sql.c_str())); }, "DBMS_ASH_INTERNAL.UNIFIED_SERVICE_NAMES"); } Datum dbms_ash_internal_unified_sqlstat(PG_FUNCTION_ARGS) { raise_unsupported_function("UNIFIED_SQLSTAT"); PG_RETURN_NULL(); } Datum dbms_ash_internal_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_ASH_INTERNAL_VERSION)); } Datum dbms_ash_internal_compute_slot_width(PG_FUNCTION_ARGS) { const std::optional duration_seconds = numeric_arg_optional(fcinfo, 0); const std::optional requested_width = numeric_arg_optional(fcinfo, 1); const std::optional usedisk = numeric_arg_optional(fcinfo, 2); const Numeric zero = int32_to_numeric(0); if (requested_width.has_value() && numeric_gt_value(requested_width.value(), zero)) PG_RETURN_NUMERIC(requested_width.value()); if (!duration_seconds.has_value()) PG_RETURN_NULL(); const bool disk_branch = usedisk_is_exact_one(usedisk); const Numeric minimum_width = disk_branch ? int32_to_numeric(300) : int32_to_numeric(60); const Numeric rounding_divisor = disk_branch ? int32_to_numeric(3000) : int32_to_numeric(600); const Numeric rounding_bias = disk_branch ? int32_to_numeric(150) : int32_to_numeric(30); const Numeric rounded_width = numeric_round_value( numeric_div_value(numeric_add_value(duration_seconds.value(), rounding_bias), rounding_divisor), 0); const Numeric computed_width = numeric_mul_value(rounded_width, minimum_width); if (numeric_lt_value(computed_width, minimum_width)) PG_RETURN_NUMERIC(minimum_width); PG_RETURN_NUMERIC(computed_width); } Datum dbms_ash_internal_get_blksid_details(PG_FUNCTION_ARGS) { raise_feature_not_supported("функция DBMS_ASH_INTERNAL.GET_BLKSID_DETAILS не поддерживается"); PG_RETURN_VOID(); } Datum dbms_ash_internal_initialize(PG_FUNCTION_ARGS) { return execute_ash_internal_entrypoint([&]() -> Datum { // NULL DBID сохраняет частично изменённое состояние, затем выдаёт ошибку; // успешный вызов INITIALIZE публикует контекст атомарно. SessionReportContext& store = report_context_store(); ReportContext& context = store.context; ensure_context_guc_defined(); reset_context(store); context.initialized = true; context.dbid_is_null = PG_ARGISNULL(0); if (!PG_ARGISNULL(1)) { context.instnum = copy_array_to_session_context(store, PG_GETARG_ARRAYTYPE_P(1)); context.instnum_is_null = false; } if (!PG_ARGISNULL(2)) context.bsnap = copy_numeric_to_session_context(store, PG_GETARG_NUMERIC(2)); if (!PG_ARGISNULL(3)) context.esnap = copy_numeric_to_session_context(store, PG_GETARG_NUMERIC(3)); if (!PG_ARGISNULL(4)) { context.btime = PG_GETARG_DATEADT(4); context.btime_is_null = false; } if (!PG_ARGISNULL(5)) { context.etime = PG_GETARG_DATEADT(5); context.etime_is_null = false; } if (!PG_ARGISNULL(6)) context.nsmpls = copy_numeric_to_session_context(store, PG_GETARG_NUMERIC(6)); if (!PG_ARGISNULL(7)) context.dfltr = copy_numeric_to_session_context(store, PG_GETARG_NUMERIC(7)); if (!PG_ARGISNULL(8)) context.swidth = copy_numeric_to_session_context(store, PG_GETARG_NUMERIC(8)); if (!PG_ARGISNULL(9)) context.m_en = copy_numeric_to_session_context(store, PG_GETARG_NUMERIC(9)); if (!PG_ARGISNULL(10)) { context.m_btime = PG_GETARG_DATEADT(10); context.m_btime_is_null = false; } if (!PG_ARGISNULL(11)) { context.m_etime = PG_GETARG_DATEADT(11); context.m_etime_is_null = false; } if (!PG_ARGISNULL(12)) context.d_en = copy_numeric_to_session_context(store, PG_GETARG_NUMERIC(12)); if (!PG_ARGISNULL(13)) { context.d_btime = PG_GETARG_DATEADT(13); context.d_btime_is_null = false; } if (!PG_ARGISNULL(14)) { context.d_etime = PG_GETARG_DATEADT(14); context.d_etime_is_null = false; } if (!PG_ARGISNULL(15)) context.data_src = copy_numeric_to_session_context(store, PG_GETARG_NUMERIC(15)); if (!PG_ARGISNULL(0)) context.dbid = copy_numeric_to_session_context(store, PG_GETARG_NUMERIC(0)); if (PG_ARGISNULL(0)) { ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("Value NULL for parameter l_dbid is invalid (1)"))); } PG_RETURN_VOID(); }, "DBMS_ASH_INTERNAL.INITIALIZE"); } Datum dbms_ash_internal_runreport(PG_FUNCTION_ARGS) { raise_unsupported_function("RUNREPORT"); PG_RETURN_NULL(); } Datum rudb_ash_memory_rows(PG_FUNCTION_ARGS) { ensure_context_guc_defined(); if (!superuser()) { ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("доступ к RUDB ASH memory row source запрещён"))); } const bool is_global = fcinfo->nargs > 0 && !PG_ARGISNULL(0) && PG_GETARG_BOOL(0); if (!memory_path_enabled()) { emit_sample_rows(fcinfo, {}); PG_RETURN_NULL(); } rudb::ash::HistoryFilter filter = build_history_filter(false, is_global); emit_sample_rows(fcinfo, rudb::ash::collect_memory_samples(filter)); PG_RETURN_NULL(); }