#include "utils/dbms_warning.h" #include "dbms_warning.hpp" #include "dbms_warning_errors.hpp" extern "C" { PG_FUNCTION_INFO_V1(dbms_warning_add_warning_setting_cat); PG_FUNCTION_INFO_V1(dbms_warning_add_warning_setting_num); PG_FUNCTION_INFO_V1(dbms_warning_get_category); PG_FUNCTION_INFO_V1(dbms_warning_get_warning_setting_cat); PG_FUNCTION_INFO_V1(dbms_warning_get_warning_setting_num); PG_FUNCTION_INFO_V1(dbms_warning_get_warning_setting_string); PG_FUNCTION_INFO_V1(dbms_warning_normalize_setting); PG_FUNCTION_INFO_V1(dbms_warning_set_warning_setting_string); PG_FUNCTION_INFO_V1(dbms_warning_get_version); /// @brief Версия RUDB пакета DBMS_WARNING (Oracle DBMS_WARNING пакет) #define RUDB_DBMS_WARNING_VERSION "1.0.0" } // extern "C" #include #include #include #include #include #include extern "C" { #include "utils/builtins.h" } namespace { /* * Локальная модель состояния предупреждений для пакета DBMS_WARNING. * * Здесь храним только ordered clauses текущей строки PLSQL_WARNINGS. * Публичные точки входа остаются частью поверхности пакета, а хук * компилятора читает только сессионное строковое состояние. */ enum class WarningAction { Enable, Disable, Error }; enum class WarningSelectorKind { All, Category, Number, NumberList }; struct WarningClause { WarningAction action; WarningSelectorKind selector_kind; std::string selector_canonical; }; struct WarningState { std::vector clauses; }; // Проверяет, является ли символ пробелом. inline bool is_space(const unsigned char ch) { return std::isspace(static_cast(ch)) != 0; } // Убирает пробелы по краям строки без копирования. inline std::string_view trim_view(const std::string_view input) { size_t begin = 0; size_t end = input.size(); while (begin < end && is_space(static_cast(input[begin]))) ++begin; while (end > begin && is_space(static_cast(input[end - 1]))) --end; return input.substr(begin, end - begin); } // Возвращает копию строки в нижнем регистре. inline std::string lower_copy(const std::string_view input) { std::string output; output.reserve(input.size()); for (const char ch : input) output.push_back(static_cast(std::tolower(static_cast(ch)))); return output; } // Сравнивает строки без учета регистра и внешних пробелов. inline bool iequals(const std::string_view lhs, const std::string_view rhs) { return lower_copy(trim_view(lhs)) == lower_copy(trim_view(rhs)); } // Проверяет токен действия на одно из допустимых значений. inline bool is_action_token(const std::string_view token, const WarningAction action) { switch (action) { case WarningAction::Enable: return iequals(token, "ENABLE"); case WarningAction::Disable: return iequals(token, "DISABLE"); case WarningAction::Error: return iequals(token, "ERROR"); } return false; } // Возвращает имя действия. inline const char* action_name(const WarningAction action) { switch (action) { case WarningAction::Enable: return "ENABLE"; case WarningAction::Disable: return "DISABLE"; case WarningAction::Error: return "ERROR"; } return "DISABLE"; } // Проверяет, что токен содержит положительное десятичное число. inline bool parse_positive_integer(const std::string_view token, int& value) { const std::string_view trimmed = trim_view(token); if (trimmed.empty()) return false; long long parsed = 0; for (const char ch : trimmed) { if (!std::isdigit(static_cast(ch))) return false; parsed = parsed * 10 + (ch - '0'); if (parsed > std::numeric_limits::max()) return false; } if (parsed <= 0) return false; value = static_cast(parsed); return true; } // Формирует канонический десятичный текст числа без ведущих нулей. inline std::string format_positive_integer(const int value) { return std::to_string(value); } // Собирает канонический вид числового списка. inline std::string format_numeric_list(const std::vector& values) { std::string output = "("; for (size_t index = 0; index < values.size(); ++index) { if (index > 0) output.push_back(','); output += format_positive_integer(values[index]); } output.push_back(')'); return output; } // Парсит селектор предупреждения и заполняет его канонический вид. inline bool parse_warning_selector(const std::string_view selector_token, WarningClause& clause) { if (iequals(selector_token, "ALL")) { clause.selector_kind = WarningSelectorKind::All; clause.selector_canonical = "ALL"; return true; } if (iequals(selector_token, "SEVERE")) { clause.selector_kind = WarningSelectorKind::Category; clause.selector_canonical = "SEVERE"; return true; } if (iequals(selector_token, "INFORMATIONAL")) { clause.selector_kind = WarningSelectorKind::Category; clause.selector_canonical = "INFORMATIONAL"; return true; } if (iequals(selector_token, "PERFORMANCE")) { clause.selector_kind = WarningSelectorKind::Category; clause.selector_canonical = "PERFORMANCE"; return true; } if (!selector_token.empty() && selector_token.front() == '(' && selector_token.back() == ')') { const std::string_view body = trim_view(selector_token.substr(1, selector_token.size() - 2)); if (body.empty()) return false; std::vector numbers; size_t item_begin = 0; for (size_t pos = 0; pos <= body.size(); ++pos) { const bool at_end = (pos == body.size()); if (!at_end && body[pos] != ',') continue; const std::string_view item = trim_view(body.substr(item_begin, pos - item_begin)); int parsed_number = 0; if (!parse_positive_integer(item, parsed_number)) return false; numbers.push_back(parsed_number); item_begin = pos + 1; } if (numbers.empty()) return false; clause.selector_kind = WarningSelectorKind::NumberList; clause.selector_canonical = format_numeric_list(numbers); return true; } int parsed_number = 0; if (!parse_positive_integer(selector_token, parsed_number)) return false; clause.selector_kind = WarningSelectorKind::Number; clause.selector_canonical = format_positive_integer(parsed_number); return true; } // Формирует каноническую строку для одного клауза. inline std::string format_warning_clause(const WarningClause& clause) { return std::string(action_name(clause.action)) + ':' + clause.selector_canonical; } // Проверяет, есть ли в строке хотя бы один ALL-клауз. constexpr int kCompilerShadowWarningNumber = 6002; constexpr const char* kCompilerShadowWarningCategory = "INFORMATIONAL"; // Проверяет, что селектор затрагивает warning компилятора PL/pgSQL. inline bool warning_selector_matches_compiler_warning(const WarningClause& clause) { switch (clause.selector_kind) { case WarningSelectorKind::All: return true; case WarningSelectorKind::Category: return clause.selector_canonical == kCompilerShadowWarningCategory; case WarningSelectorKind::Number: return clause.selector_canonical == std::to_string(kCompilerShadowWarningNumber); case WarningSelectorKind::NumberList: { const std::string needle = std::to_string(kCompilerShadowWarningNumber); const std::string_view list = clause.selector_canonical; size_t pos = list.find(needle); while (pos != std::string::npos) { const bool left_boundary = (pos == 1) || list[pos - 1] == '(' || list[pos - 1] == ','; const size_t right_pos = pos + needle.size(); const bool right_boundary = (right_pos + 1 == list.size() && list[right_pos] == ')') || (right_pos < list.size() && list[right_pos] == ','); if (left_boundary && right_boundary) return true; pos = list.find(needle, pos + 1); } return false; } } return false; } // Возвращает режим компилятора для shadow-variable warning. inline WarningAction warning_state_compiler_action(const WarningState& state, bool& is_explicit) { WarningAction action = WarningAction::Disable; is_explicit = false; for (const WarningClause& clause : state.clauses) { if (!warning_selector_matches_compiler_warning(clause)) continue; is_explicit = true; action = clause.action; } return action; } // Парсит строковое значение настройки предупреждений в локальное состояние. inline bool parse_warning_setting_string(const std::string_view input, WarningState& state) { const std::string_view normalized = trim_view(input); if (normalized.empty()) return false; WarningState parsed_state; size_t clause_begin = 0; int parentheses_depth = 0; for (size_t pos = 0; pos < normalized.size(); ++pos) { const char ch = normalized[pos]; if (ch == '(') { ++parentheses_depth; continue; } if (ch == ')') { if (parentheses_depth == 0) return false; --parentheses_depth; continue; } if (ch != ',' || parentheses_depth != 0) continue; const std::string_view clause_token = trim_view(normalized.substr(clause_begin, pos - clause_begin)); if (clause_token.empty()) return false; const size_t colon_pos = clause_token.find(':'); if (colon_pos == std::string_view::npos) return false; if (clause_token.find(':', colon_pos + 1) != std::string_view::npos) return false; const std::string_view action_token = trim_view(clause_token.substr(0, colon_pos)); const std::string_view selector_token = trim_view(clause_token.substr(colon_pos + 1)); if (action_token.empty() || selector_token.empty()) return false; WarningClause clause; if (is_action_token(action_token, WarningAction::Enable)) clause.action = WarningAction::Enable; else if (is_action_token(action_token, WarningAction::Disable)) clause.action = WarningAction::Disable; else if (is_action_token(action_token, WarningAction::Error)) clause.action = WarningAction::Error; else return false; if (!parse_warning_selector(selector_token, clause)) return false; parsed_state.clauses.push_back(std::move(clause)); clause_begin = pos + 1; } if (parentheses_depth != 0) return false; const std::string_view clause_token = trim_view(normalized.substr(clause_begin)); if (clause_token.empty()) return false; const size_t colon_pos = clause_token.find(':'); if (colon_pos == std::string_view::npos) return false; if (clause_token.find(':', colon_pos + 1) != std::string_view::npos) return false; const std::string_view action_token = trim_view(clause_token.substr(0, colon_pos)); const std::string_view selector_token = trim_view(clause_token.substr(colon_pos + 1)); if (action_token.empty() || selector_token.empty()) return false; WarningClause clause; if (is_action_token(action_token, WarningAction::Enable)) clause.action = WarningAction::Enable; else if (is_action_token(action_token, WarningAction::Disable)) clause.action = WarningAction::Disable; else if (is_action_token(action_token, WarningAction::Error)) clause.action = WarningAction::Error; else return false; if (!parse_warning_selector(selector_token, clause)) return false; parsed_state.clauses.push_back(std::move(clause)); state = std::move(parsed_state); return true; } // Формирует каноническое строковое представление текущего состояния. inline std::string format_warning_setting_string(const WarningState& state) { if (state.clauses.empty()) return "DISABLE:ALL"; std::string output; for (size_t index = 0; index < state.clauses.size(); ++index) { if (index > 0) output.push_back(','); output += format_warning_clause(state.clauses[index]); } return output; } inline std::string normalize_warning_setting(const std::string_view input) { WarningState parsed_state; if (!parse_warning_setting_string(input, parsed_state)) dbms_warning_errors::raise_ora_39950(); return format_warning_setting_string(parsed_state); } // Сессионный источник истины для PLSQL_WARNINGS. static WarningState s_warning_setting_state = WarningState{}; } // namespace /* * Строковая реализация DBMS_WARNING. * * Здесь держим сессионный источник истины для PLSQL_WARNINGS и * предоставляем helper для хука компилятора. */ extern "C" { // Добавляет настройку предупреждений в сессионное состояние. Datum dbms_warning_add_warning_setting_cat(PG_FUNCTION_ARGS) { PG_RETURN_VOID(); } // Добавляет настройку предупреждений по числу. Datum dbms_warning_add_warning_setting_num(PG_FUNCTION_ARGS) { PG_RETURN_VOID(); } // Возвращает категорию предупреждения. Datum dbms_warning_get_category(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } // Возвращает настройку предупреждений по категории. Datum dbms_warning_get_warning_setting_cat(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } // Возвращает настройку предупреждений по числу. Datum dbms_warning_get_warning_setting_num(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } // Возвращает текущее сессионное строковое значение PLSQL_WARNINGS. Datum dbms_warning_get_warning_setting_string(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(format_warning_setting_string(s_warning_setting_state).c_str())); } Datum dbms_warning_normalize_setting(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); const std::string value = text_to_cstring(PG_GETARG_TEXT_PP(0)); PG_RETURN_TEXT_P(cstring_to_text(normalize_warning_setting(value).c_str())); } // Записывает текущее сессионное строковое значение PLSQL_WARNINGS. Datum dbms_warning_set_warning_setting_string(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) dbms_warning_errors::raise_ora_01405(); if (PG_ARGISNULL(1)) dbms_warning_errors::raise_ora_01405(); const std::string value = text_to_cstring(PG_GETARG_TEXT_PP(0)); const std::string scope = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (iequals(scope, "SYSTEM")) dbms_warning_errors::raise_ora_01031(); if (!iequals(scope, "SESSION")) dbms_warning_errors::raise_ora_39960(); WarningState parsed_state = s_warning_setting_state; const Datum normalized_datum = DirectFunctionCall1(dbms_warning_normalize_setting, PG_GETARG_DATUM(0)); const std::string normalized = text_to_cstring(DatumGetTextPP(normalized_datum)); parse_warning_setting_string(normalized, parsed_state); s_warning_setting_state = std::move(parsed_state); PG_RETURN_VOID(); } DBMSWarningCompilerMode dbms_warning_get_compiler_warning_mode(bool* is_explicit) { bool local_is_explicit = false; const WarningAction action = warning_state_compiler_action(s_warning_setting_state, local_is_explicit); if (is_explicit != nullptr) *is_explicit = local_is_explicit; switch (action) { case WarningAction::Enable: return DBMS_WARNING_COMPILER_MODE_ENABLE; case WarningAction::Disable: return DBMS_WARNING_COMPILER_MODE_DISABLE; case WarningAction::Error: return DBMS_WARNING_COMPILER_MODE_ERROR; } return DBMS_WARNING_COMPILER_MODE_DISABLE; } Datum dbms_warning_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_WARNING_VERSION)); } } // extern "C"