#include "dbms_sqlset.hpp" extern "C" { #include "access/htup_details.h" #include "access/tupdesc.h" #include "catalog/pg_type_d.h" #include "executor/spi.h" #include "funcapi.h" #include "utils/builtins.h" #include "utils/elog.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/numeric.h" #include "utils/typcache.h" #include "utils/tuplestore.h" #include "miscadmin.h" } // extern "C" #include #include #include #include #include #include #include #include #include #include #include namespace { constexpr int32 kDbmsSqlsetModeReplaceOldStats = 1; constexpr int32 kDbmsSqlsetModeAccumulateStats = 2; constexpr char kDbmsSqlsetHasRecursiveSql[] = "Y"; constexpr char kDbmsSqlsetNoRecursiveSql[] = "N"; constexpr int32 kDbmsSqlsetSingleExecution = 1; constexpr int32 kDbmsSqlsetAllExecutions = 2; constexpr int32 kDbmsSqlsetLimitedCommandType = 1; constexpr int32 kDbmsSqlsetAllCommandType = 2; constexpr int32 kDbmsSqlsetStsStgtab102Version = 1; constexpr int32 kDbmsSqlsetStsStgtab111Version = 2; constexpr int32 kDbmsSqlsetStsStgtab112Version = 3; constexpr int32 kDbmsSqlsetStsStgtab121Version = 5; constexpr int32 kDbmsSqlsetStsStgtab122Version = 6; enum class SqlsetFieldKind { Text, Numeric, Raw }; struct SqlsetFieldDef { const char* name; SqlsetFieldKind kind; bool updateable; bool accumulable; bool basic_visible; Oid type_oid; }; struct SqlsetRow { std::string sql_id; int64 plan_hash_value = -1; std::unordered_map> scalar_fields; }; struct Sqlset { std::string owner; std::optional description; std::vector rows; std::unordered_map row_index; }; enum class SqlsetLoadOption { Insert, Update, Merge }; enum class SqlsetUpdateOption { Replace, Accumulate }; enum class SqlsetAttributeList { Basic, Typical, All }; std::unordered_map& sqlset_store(); std::string build_sqlset_key(const std::string& owner, const std::string& name); constexpr SqlsetFieldDef kSqlsetFieldDefs[] = { {"sql_id", SqlsetFieldKind::Text, false, false, true, TEXTOID}, {"force_matching_signature", SqlsetFieldKind::Numeric, true, false, true, NUMERICOID}, {"sql_text", SqlsetFieldKind::Text, false, false, true, TEXTOID}, {"parsing_schema_name", SqlsetFieldKind::Text, false, false, true, TEXTOID}, {"module", SqlsetFieldKind::Text, false, false, true, TEXTOID}, {"action", SqlsetFieldKind::Text, false, false, true, TEXTOID}, {"elapsed_time", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"cpu_time", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"buffer_gets", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"disk_reads", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"direct_writes", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"rows_processed", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"fetches", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"executions", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"end_of_fetch_count", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"optimizer_cost", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID}, {"optimizer_env", SqlsetFieldKind::Raw, true, false, false, BYTEAOID}, {"priority", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID}, {"command_type", SqlsetFieldKind::Numeric, true, false, true, NUMERICOID}, {"first_load_time", SqlsetFieldKind::Text, true, false, false, TEXTOID}, {"stat_period", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"active_stat_period", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID}, {"other", SqlsetFieldKind::Text, true, false, false, TEXTOID}, {"plan_hash_value", SqlsetFieldKind::Numeric, false, false, true, NUMERICOID}, {"con_dbid", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID}, {"last_exec_start_time", SqlsetFieldKind::Text, true, false, false, TEXTOID}, {"sharable_mem", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID}, {"exact_matching_signature", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID}, {"result_cache_executions", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID}, {"sql_profile", SqlsetFieldKind::Text, true, false, false, TEXTOID}, {"sql_plan_baseline", SqlsetFieldKind::Text, true, false, false, TEXTOID}, {"sql_patch", SqlsetFieldKind::Text, true, false, false, TEXTOID}, {"avg_hard_parse_time", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID}, {"user_io_wait_time", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID}, {"io_interconnect_bytes", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID}, {"parsing_user_name", SqlsetFieldKind::Text, false, false, false, TEXTOID}, }; constexpr size_t kSqlsetFieldCount = sizeof(kSqlsetFieldDefs) / sizeof(kSqlsetFieldDefs[0]); } // namespace extern "C" { PG_FUNCTION_INFO_V1(dbms_sqlset_mode_replace_old_stats); PG_FUNCTION_INFO_V1(dbms_sqlset_mode_accumulate_stats); PG_FUNCTION_INFO_V1(dbms_sqlset_has_recursive_sql); PG_FUNCTION_INFO_V1(dbms_sqlset_no_recursive_sql); PG_FUNCTION_INFO_V1(dbms_sqlset_single_execution); PG_FUNCTION_INFO_V1(dbms_sqlset_all_executions); PG_FUNCTION_INFO_V1(dbms_sqlset_limited_command_type); PG_FUNCTION_INFO_V1(dbms_sqlset_all_command_type); PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_10_2_version); PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_11_1_version); PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_11_2_version); PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_12_1_version); PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_12_2_version); PG_FUNCTION_INFO_V1(dbms_sqlset_get_version); PG_FUNCTION_INFO_V1(dbms_sqlset_add_reference); PG_FUNCTION_INFO_V1(dbms_sqlset_create_sqlset); PG_FUNCTION_INFO_V1(dbms_sqlset_select_cursor_cache); PG_FUNCTION_INFO_V1(dbms_sqlset_select_sqlpa_task); PG_FUNCTION_INFO_V1(dbms_sqlset_select_sqlset); PG_FUNCTION_INFO_V1(dbms_sqlset_normalize_attribute_list); PG_FUNCTION_INFO_V1(dbms_sqlset_select_sql_trace); PG_FUNCTION_INFO_V1(dbms_sqlset_select_workload_repository_0); PG_FUNCTION_INFO_V1(dbms_sqlset_select_workload_repository_1); PG_FUNCTION_INFO_V1(dbms_sqlset_capture_cursor_cache); PG_FUNCTION_INFO_V1(dbms_sqlset_create_sqlset_proc); PG_FUNCTION_INFO_V1(dbms_sqlset_create_stgtab); PG_FUNCTION_INFO_V1(dbms_sqlset_delete_sqlset); PG_FUNCTION_INFO_V1(dbms_sqlset_drop_sqlset); PG_FUNCTION_INFO_V1(dbms_sqlset_drop_sqlset_by_prefix); PG_FUNCTION_INFO_V1(dbms_sqlset_load_sqlset); PG_FUNCTION_INFO_V1(dbms_sqlset_pack_stgtab); PG_FUNCTION_INFO_V1(dbms_sqlset_remap_stgtab); PG_FUNCTION_INFO_V1(dbms_sqlset_remove_reference); PG_FUNCTION_INFO_V1(dbms_sqlset_unpack_stgtab); PG_FUNCTION_INFO_V1(dbms_sqlset_update_sqlset_0); PG_FUNCTION_INFO_V1(dbms_sqlset_update_sqlset_1); PG_FUNCTION_INFO_V1(dbms_sqlset_update_sqlset_2); /// @brief Версия RUDB пакета DBMS_SQLSET (Oracle DBMS_SQLSET пакет) #define RUDB_DBMS_SQLSET_VERSION "1.0.0" } // extern "C" namespace { const SqlsetFieldDef* find_field_def(const char* name) { for (const SqlsetFieldDef& field : kSqlsetFieldDefs) { if (pg_strcasecmp(field.name, name) == 0) return &field; } return nullptr; } std::string text_to_std_string(const text* value) { char* cstring_value = text_to_cstring(value); std::string result(cstring_value); pfree(cstring_value); return result; } std::optional pg_arg_text_optional(FunctionCallInfo fcinfo, int argno) { if (argno >= fcinfo->nargs || PG_ARGISNULL(argno)) return std::nullopt; std::string value = text_to_std_string(PG_GETARG_TEXT_PP(argno)); if (value.empty()) return std::nullopt; return value; } std::optional pg_arg_numeric_optional(FunctionCallInfo fcinfo, int argno) { if (argno >= fcinfo->nargs || PG_ARGISNULL(argno)) return std::nullopt; return PG_GETARG_NUMERIC(argno); } std::string current_user_name() { const char* user_name = GetUserNameFromId(GetUserId(), false); return user_name != nullptr ? user_name : ""; } std::optional normalize_owner_argument(const std::optional& owner_argument) { if (!owner_argument.has_value() || owner_argument->empty()) return current_user_name(); if (pg_strcasecmp(owner_argument->c_str(), current_user_name().c_str()) != 0) return std::nullopt; return current_user_name(); } std::string require_sqlset_name(const std::optional& name, bool allow_generate, bool& generated, const std::string& owner) { generated = false; if (name.has_value() && !name->empty()) return *name; if (!allow_generate) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("ORA-13755: invalid \"SQL Tuning Set\" name"))); generated = true; int64& next_generated_id = []() -> int64& { static int64 next_id = 1; return next_id; }(); std::string generated_name; do { generated_name = "STS_" + std::to_string(next_generated_id++); } while (sqlset_store().find(build_sqlset_key(owner, generated_name)) != sqlset_store().end()); return generated_name; } std::unordered_map& sqlset_store() { static std::unordered_map sqlsets; return sqlsets; } std::string build_sqlset_key(const std::string& owner, const std::string& name) { return owner + '\x1f' + name; } std::optional canonicalize_numeric_text(const std::optional& value) { if (!value.has_value()) return std::nullopt; Datum numeric_value = DirectFunctionCall3(numeric_in, CStringGetDatum(value->c_str()), ObjectIdGetDatum(0), Int32GetDatum(-1)); char* canonical = DatumGetCString(DirectFunctionCall1(numeric_out, numeric_value)); std::string result(canonical); pfree(canonical); return result; } std::string numeric_to_std_string(Numeric value) { char* numeric_value = DatumGetCString(DirectFunctionCall1(numeric_out, NumericGetDatum(value))); std::string result(numeric_value); pfree(numeric_value); return result; } Numeric int32_to_numeric(int32 value) { return DatumGetNumeric(DirectFunctionCall1(int4_numeric, Int32GetDatum(value))); } Numeric int64_to_numeric(int64 value) { return DatumGetNumeric(DirectFunctionCall1(int8_numeric, Int64GetDatum(value))); } bool numeric_eq_value(Numeric lhs, Numeric rhs) { return DatumGetBool(DirectFunctionCall2(numeric_eq, NumericGetDatum(lhs), NumericGetDatum(rhs))); } bool numeric_lt_value(Numeric lhs, Numeric rhs) { return DatumGetBool(DirectFunctionCall2(numeric_lt, NumericGetDatum(lhs), NumericGetDatum(rhs))); } bool numeric_gt_value(Numeric lhs, Numeric rhs) { return DatumGetBool(DirectFunctionCall2(numeric_gt, NumericGetDatum(lhs), NumericGetDatum(rhs))); } bool numeric_is_integer_value(Numeric value) { Numeric truncated = DatumGetNumeric(DirectFunctionCall2( numeric_trunc, NumericGetDatum(value), Int32GetDatum(0))); return numeric_eq_value(value, truncated); } Datum string_to_datum(const std::string& value, SqlsetFieldKind kind) { switch (kind) { case SqlsetFieldKind::Text: return CStringGetTextDatum(value.c_str()); case SqlsetFieldKind::Numeric: return DirectFunctionCall3(numeric_in, CStringGetDatum(value.c_str()), ObjectIdGetDatum(0), Int32GetDatum(-1)); case SqlsetFieldKind::Raw: return DirectFunctionCall1(byteain, CStringGetDatum(value.c_str())); } return (Datum) 0; } std::optional datum_to_string(Datum value, Oid type_oid) { Oid output_function = InvalidOid; bool type_is_varlena = false; getTypeOutputInfo(type_oid, &output_function, &type_is_varlena); char* text_value = OidOutputFunctionCall(output_function, value); std::string result(text_value); pfree(text_value); return result; } int64 parse_int64_text(const std::string& text_value, const char* field_name) { errno = 0; char* end = nullptr; const long long parsed = std::strtoll(text_value.c_str(), &end, 10); if (errno != 0 || end == text_value.c_str() || *end != '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("неверное числовое значение для %s: %s", field_name, text_value.c_str()))); return static_cast(parsed); } SqlsetRow parse_sqlset_row_tuple(HeapTuple tuple, TupleDesc tuple_desc); SqlsetRow parse_sqlset_row_composite(Datum value, Oid type_oid, int32 typmod) { TupleDesc nested_desc = lookup_rowtype_tupdesc_copy(type_oid, typmod); HeapTupleHeader header = DatumGetHeapTupleHeader(value); HeapTupleData nested_tuple; MemSet(&nested_tuple, 0, sizeof(nested_tuple)); nested_tuple.t_len = HeapTupleHeaderGetDatumLength(header); nested_tuple.t_data = header; nested_tuple.t_tableOid = InvalidOid; PG_TRY(); { SqlsetRow row = parse_sqlset_row_tuple(&nested_tuple, nested_desc); FreeTupleDesc(nested_desc); return row; } PG_CATCH(); { FreeTupleDesc(nested_desc); PG_RE_THROW(); } PG_END_TRY(); } SqlsetRow parse_sqlset_row_tuple(HeapTuple tuple, TupleDesc tuple_desc) { SqlsetRow row; if (tuple_desc->natts == 1) { Form_pg_attribute attr = TupleDescAttr(tuple_desc, 0); if (type_is_rowtype(attr->atttypid)) { bool is_null = false; Datum composite_value = heap_getattr(tuple, 1, tuple_desc, &is_null); if (is_null) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("DBMS_SQLSET.LOAD_SQLSET получил пустую строку SQLSET_ROW"))); return parse_sqlset_row_composite(composite_value, attr->atttypid, attr->atttypmod); } } for (int attno = 0; attno < tuple_desc->natts; ++attno) { Form_pg_attribute attr = TupleDescAttr(tuple_desc, attno); if (attr->attisdropped) continue; bool is_null = false; Datum value = heap_getattr(tuple, attno + 1, tuple_desc, &is_null); const char* field_name = NameStr(attr->attname); const SqlsetFieldDef* field = find_field_def(field_name); if (pg_strcasecmp(field_name, "sql_id") == 0) { if (!is_null) row.sql_id = datum_to_string(value, attr->atttypid).value(); continue; } if (pg_strcasecmp(field_name, "plan_hash_value") == 0) { if (is_null) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("DBMS_SQLSET.LOAD_SQLSET требует plan_hash_value"))); row.plan_hash_value = parse_int64_text(datum_to_string(value, attr->atttypid).value(), "plan_hash_value"); continue; } if (pg_strcasecmp(field_name, "object_list") == 0 || pg_strcasecmp(field_name, "bind_data") == 0 || pg_strcasecmp(field_name, "sql_plan") == 0 || pg_strcasecmp(field_name, "bind_list") == 0) { if (!is_null) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает столбец \"%s\"", field_name))); continue; } if (field == nullptr) { if (!is_null) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает столбец \"%s\"", field_name))); continue; } if (is_null) { row.scalar_fields[field->name] = std::nullopt; continue; } std::optional field_value = datum_to_string(value, attr->atttypid); if (field->kind == SqlsetFieldKind::Numeric) field_value = canonicalize_numeric_text(field_value); row.scalar_fields[field->name] = field_value; } if (row.sql_id.empty()) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("DBMS_SQLSET.LOAD_SQLSET требует sql_id"))); if (row.plan_hash_value < 0) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("DBMS_SQLSET.LOAD_SQLSET требует plan_hash_value"))); return row; } const std::optional* find_scalar_field(const SqlsetRow& row, const char* field_name) { auto it = row.scalar_fields.find(field_name); if (it == row.scalar_fields.end()) return nullptr; return &it->second; } std::optional* mutable_scalar_field(SqlsetRow& row, const char* field_name) { auto it = row.scalar_fields.find(field_name); if (it == row.scalar_fields.end()) return nullptr; return &it->second; } void apply_scalar_update(SqlsetRow& existing, const SqlsetRow& incoming, const SqlsetFieldDef& field, SqlsetUpdateOption update_option, bool ignore_null) { if (!field.updateable) return; const std::optional* source = find_scalar_field(incoming, field.name); if (source == nullptr) return; std::optional* target = mutable_scalar_field(existing, field.name); if (target == nullptr) target = &existing.scalar_fields[field.name]; if (!source->has_value()) { if (!ignore_null) target->reset(); return; } if (update_option == SqlsetUpdateOption::Accumulate && field.accumulable) { if (target->has_value()) { const std::string lhs = canonicalize_numeric_text(*target).value(); const std::string rhs = canonicalize_numeric_text(*source).value(); Datum lhs_numeric = DirectFunctionCall3(numeric_in, CStringGetDatum(lhs.c_str()), ObjectIdGetDatum(0), Int32GetDatum(-1)); Datum rhs_numeric = DirectFunctionCall3(numeric_in, CStringGetDatum(rhs.c_str()), ObjectIdGetDatum(0), Int32GetDatum(-1)); char* accumulated = DatumGetCString(DirectFunctionCall1( numeric_out, DirectFunctionCall2(numeric_add, lhs_numeric, rhs_numeric))); *target = std::string(accumulated); pfree(accumulated); } else { *target = canonicalize_numeric_text(*source); } return; } *target = *source; } void apply_sqlset_row_update(SqlsetRow& existing, const SqlsetRow& incoming, SqlsetUpdateOption update_option, bool ignore_null) { for (const SqlsetFieldDef& field : kSqlsetFieldDefs) apply_scalar_update(existing, incoming, field, update_option, ignore_null); } bool attribute_list_includes_field(SqlsetAttributeList attribute_mode, const SqlsetFieldDef& field) { if (attribute_mode == SqlsetAttributeList::Typical) return true; return field.basic_visible; } void fill_sqlset_tuple_values(const SqlsetRow& row, SqlsetAttributeList attribute_mode, Datum* values, bool* nulls) { for (size_t idx = 0; idx < kSqlsetFieldCount; ++idx) { const SqlsetFieldDef& field = kSqlsetFieldDefs[idx]; nulls[idx] = false; if (!attribute_list_includes_field(attribute_mode, field)) { nulls[idx] = true; continue; } if (pg_strcasecmp(field.name, "sql_id") == 0) { values[idx] = CStringGetTextDatum(row.sql_id.c_str()); continue; } if (pg_strcasecmp(field.name, "plan_hash_value") == 0) { values[idx] = DirectFunctionCall3(numeric_in, CStringGetDatum(std::to_string(row.plan_hash_value).c_str()), ObjectIdGetDatum(0), Int32GetDatum(-1)); continue; } if (pg_strcasecmp(field.name, "object_list") == 0 || pg_strcasecmp(field.name, "bind_data") == 0 || pg_strcasecmp(field.name, "sql_plan") == 0 || pg_strcasecmp(field.name, "bind_list") == 0) { nulls[idx] = true; continue; } const std::optional* source = find_scalar_field(row, field.name); if (source == nullptr || !source->has_value()) { nulls[idx] = true; continue; } values[idx] = string_to_datum(source->value(), field.kind); } } std::string build_row_key(const SqlsetRow& row) { return row.sql_id + '\x1f' + std::to_string(row.plan_hash_value); } Sqlset* find_sqlset(const std::string& owner, const std::string& name) { auto& store = sqlset_store(); auto it = store.find(build_sqlset_key(owner, name)); if (it == store.end()) return nullptr; return &it->second; } Sqlset& require_sqlset(const std::string& owner, const std::string& name) { Sqlset* sqlset = find_sqlset(owner, name); if (sqlset == nullptr) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("ORA-13754: \"SQL Tuning Set\" \"%s\" does not exist.", name.c_str()))); return *sqlset; } std::string normalize_load_option(const std::string& value) { if (pg_strcasecmp(value.c_str(), "INSERT") == 0) return "INSERT"; if (pg_strcasecmp(value.c_str(), "UPDATE") == 0) return "UPDATE"; if (pg_strcasecmp(value.c_str(), "MERGE") == 0) return "MERGE"; ereport(ERROR, (errmsg("ORA-13779: invalid load option"))); return ""; } std::string normalize_update_option(const std::string& value) { if (pg_strcasecmp(value.c_str(), "REPLACE") == 0) return "REPLACE"; if (pg_strcasecmp(value.c_str(), "ACCUMULATE") == 0) return "ACCUMULATE"; ereport(ERROR, (errmsg("ORA-19371: invalid update option"))); return ""; } SqlsetLoadOption parse_load_option(const std::optional& option) { const std::string normalized = option.has_value() ? normalize_load_option(*option) : "INSERT"; if (normalized == "INSERT") return SqlsetLoadOption::Insert; if (normalized == "UPDATE") return SqlsetLoadOption::Update; return SqlsetLoadOption::Merge; } SqlsetUpdateOption parse_update_option(const std::optional& option) { const std::string normalized = option.has_value() ? normalize_update_option(*option) : "REPLACE"; if (normalized == "REPLACE") return SqlsetUpdateOption::Replace; return SqlsetUpdateOption::Accumulate; } SqlsetAttributeList parse_attribute_list(const std::optional& option) { if (!option.has_value() || option->empty() || pg_strcasecmp(option->c_str(), "TYPICAL") == 0) return SqlsetAttributeList::Typical; if (pg_strcasecmp(option->c_str(), "BASIC") == 0) return SqlsetAttributeList::Basic; if (pg_strcasecmp(option->c_str(), "ALL") == 0) return SqlsetAttributeList::All; ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает attribute_list=\"%s\"", option->c_str()))); return SqlsetAttributeList::Typical; } const char* attribute_list_name(const SqlsetAttributeList value) { switch (value) { case SqlsetAttributeList::Basic: return "BASIC"; case SqlsetAttributeList::Typical: return "TYPICAL"; case SqlsetAttributeList::All: return "ALL"; } return "TYPICAL"; } void parse_result_percentage(const std::optional& option) { if (!option.has_value()) return; const Numeric one = int32_to_numeric(1); if (!numeric_eq_value(*option, one)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает result_percentage"))); } std::optional parse_result_limit(const std::optional& option) { if (!option.has_value()) return std::nullopt; const Numeric zero = int32_to_numeric(0); const Numeric max_value = int64_to_numeric(std::numeric_limits::max()); const std::string value_text = numeric_to_std_string(*option); if (numeric_is_nan(*option) || numeric_lt_value(*option, zero) || numeric_gt_value(*option, max_value) || !numeric_is_integer_value(*option)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ORA-13765: Value \"%s\" is illegal for a result limit.", value_text.c_str()))); } return DatumGetInt64(DirectFunctionCall1(numeric_int8, NumericGetDatum(*option))); } void validate_select_filters(const std::optional& basic_filter, const std::optional& ranking_measure1, const std::optional& ranking_measure2, const std::optional& ranking_measure3, const std::optional& plan_filter) { if (basic_filter.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает basic_filter"))); if (ranking_measure1.has_value() || ranking_measure2.has_value() || ranking_measure3.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает ranking_measure"))); if (plan_filter.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает plan_filter"))); } void validate_select_sqlset_unsupported_options(const std::optional& object_filter, const std::optional& recursive_sql) { if (object_filter.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает object_filter"))); if (!recursive_sql.has_value() || pg_strcasecmp(recursive_sql->c_str(), "HAS_RECURSIVE_SQL") == 0 || pg_strcasecmp(recursive_sql->c_str(), kDbmsSqlsetHasRecursiveSql) == 0 || pg_strcasecmp(recursive_sql->c_str(), "Y") == 0) return; ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает recursive_sql"))); } void validate_load_extras(const std::optional& update_condition, const std::optional& update_attributes, bool has_commit_rows) { if (update_condition.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает update_condition"))); if (update_attributes.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает update_attributes"))); if (has_commit_rows) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает commit_rows"))); } std::string create_sqlset_impl(const std::optional& sqlset_name, const std::optional& description, const std::optional& sqlset_owner, bool allow_generate) { bool generated = false; const std::optional resolved_owner = normalize_owner_argument(sqlset_owner); if (!resolved_owner.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.CREATE_SQLSET не поддерживает sqlset_owner вне текущего пользователя"))); const std::string resolved_name = require_sqlset_name(sqlset_name, allow_generate, generated, *resolved_owner); (void) generated; auto& store = sqlset_store(); const std::string key = build_sqlset_key(*resolved_owner, resolved_name); if (store.find(key) != store.end()) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("ORA-13753: \"SQL Tuning Set\" \"%s\" already exists.", resolved_name.c_str()))); Sqlset set; set.owner = *resolved_owner; set.description = description; store.emplace(key, std::move(set)); return resolved_name; } void store_sqlset_row(Sqlset& sqlset, SqlsetRow row, SqlsetLoadOption load_option, SqlsetUpdateOption update_option, bool ignore_null) { const std::string key = build_row_key(row); auto index_it = sqlset.row_index.find(key); if (index_it == sqlset.row_index.end()) { if (load_option == SqlsetLoadOption::Update) return; sqlset.row_index.emplace(key, sqlset.rows.size()); sqlset.rows.push_back(std::move(row)); return; } if (load_option == SqlsetLoadOption::Insert) return; apply_sqlset_row_update(sqlset.rows[index_it->second], row, update_option, ignore_null); } void load_sqlset_impl(const std::optional& sqlset_name, const std::optional& populate_cursor, const std::optional& load_option, const std::optional& update_option, const std::optional& update_condition, const std::optional& update_attributes, bool ignore_null, bool has_commit_rows, const std::optional& sqlset_owner) { if (!sqlset_name.has_value() || sqlset_name->empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("ORA-13755: invalid \"SQL Tuning Set\" name"))); const std::optional resolved_owner = normalize_owner_argument(sqlset_owner); if (!resolved_owner.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает sqlset_owner вне текущего пользователя"))); validate_load_extras(update_condition, update_attributes, has_commit_rows); const SqlsetLoadOption parsed_load_option = parse_load_option(load_option); const SqlsetUpdateOption parsed_update_option = parse_update_option(update_option); if (!populate_cursor.has_value() || populate_cursor->empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_CURSOR_NAME), errmsg("DBMS_SQLSET.LOAD_SQLSET получил пустой cursor"))); Sqlset& sqlset = require_sqlset(*resolved_owner, *sqlset_name); if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errmsg("SPI_connect failed"))); Portal portal = SPI_cursor_find(populate_cursor->c_str()); if (portal == nullptr) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_CURSOR), errmsg("cursor \"%s\" does not exist", populate_cursor->c_str()))); } PG_TRY(); { const long fetch_size = 1000; for (;;) { SPI_cursor_fetch(portal, true, fetch_size); if (SPI_processed == 0) break; if (SPI_tuptable == nullptr) ereport(ERROR, (errmsg("SPI_cursor_fetch returned no tuple table"))); TupleDesc tuple_desc = SPI_tuptable->tupdesc; for (uint64 idx = 0; idx < SPI_processed; ++idx) { HeapTuple tuple = SPI_tuptable->vals[idx]; SqlsetRow row = parse_sqlset_row_tuple(tuple, tuple_desc); store_sqlset_row(sqlset, std::move(row), parsed_load_option, parsed_update_option, ignore_null); } } SPI_finish(); } PG_CATCH(); { SPI_finish(); PG_RE_THROW(); } PG_END_TRY(); } } // namespace Datum dbms_sqlset_mode_replace_old_stats(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetModeReplaceOldStats); } Datum dbms_sqlset_mode_accumulate_stats(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetModeAccumulateStats); } Datum dbms_sqlset_has_recursive_sql(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(kDbmsSqlsetHasRecursiveSql)); } Datum dbms_sqlset_no_recursive_sql(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(kDbmsSqlsetNoRecursiveSql)); } Datum dbms_sqlset_single_execution(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetSingleExecution); } Datum dbms_sqlset_all_executions(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetAllExecutions); } Datum dbms_sqlset_limited_command_type(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetLimitedCommandType); } Datum dbms_sqlset_all_command_type(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetAllCommandType); } Datum dbms_sqlset_sts_stgtab_10_2_version(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetStsStgtab102Version); } Datum dbms_sqlset_sts_stgtab_11_1_version(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetStsStgtab111Version); } Datum dbms_sqlset_sts_stgtab_11_2_version(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetStsStgtab112Version); } Datum dbms_sqlset_sts_stgtab_12_1_version(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetStsStgtab121Version); } Datum dbms_sqlset_sts_stgtab_12_2_version(PG_FUNCTION_ARGS) { PG_RETURN_INT32(kDbmsSqlsetStsStgtab122Version); } Datum dbms_sqlset_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_SQLSET_VERSION)); } Datum dbms_sqlset_add_reference(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.ADD_REFERENCE"))); PG_RETURN_NULL(); } Datum dbms_sqlset_create_sqlset(PG_FUNCTION_ARGS) { const std::optional sqlset_name = pg_arg_text_optional(fcinfo, 0); const std::optional description = pg_arg_text_optional(fcinfo, 1); const std::optional sqlset_owner = pg_arg_text_optional(fcinfo, 2); const std::string resolved_name = create_sqlset_impl(sqlset_name, description, sqlset_owner, true); PG_RETURN_TEXT_P(cstring_to_text(resolved_name.c_str())); } Datum dbms_sqlset_select_cursor_cache(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_CURSOR_CACHE"))); PG_RETURN_NULL(); } Datum dbms_sqlset_select_sqlpa_task(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_SQLPA_TASK"))); PG_RETURN_NULL(); } Datum dbms_sqlset_select_sqlset(PG_FUNCTION_ARGS) { const std::optional sqlset_name = pg_arg_text_optional(fcinfo, 0); const std::optional basic_filter = pg_arg_text_optional(fcinfo, 1); const std::optional object_filter = pg_arg_text_optional(fcinfo, 2); const std::optional ranking_measure1 = pg_arg_text_optional(fcinfo, 3); const std::optional ranking_measure2 = pg_arg_text_optional(fcinfo, 4); const std::optional ranking_measure3 = pg_arg_text_optional(fcinfo, 5); const std::optional result_percentage = pg_arg_numeric_optional(fcinfo, 6); const std::optional result_limit_arg = pg_arg_numeric_optional(fcinfo, 7); const std::optional attribute_list = pg_arg_text_optional(fcinfo, 8); const std::optional plan_filter = pg_arg_text_optional(fcinfo, 9); const std::optional sqlset_owner = pg_arg_text_optional(fcinfo, 10); const std::optional recursive_sql = pg_arg_text_optional(fcinfo, 11); if (!sqlset_name.has_value() || sqlset_name->empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("ORA-13755: invalid \"SQL Tuning Set\" name"))); const std::optional resolved_owner = normalize_owner_argument(sqlset_owner); if (!resolved_owner.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает sqlset_owner вне текущего пользователя"))); validate_select_filters(basic_filter, ranking_measure1, ranking_measure2, ranking_measure3, plan_filter); validate_select_sqlset_unsupported_options(object_filter, recursive_sql); LOCAL_FCINFO(normalize_fcinfo, 1); InitFunctionCallInfoData(*normalize_fcinfo, NULL, 1, InvalidOid, NULL, NULL); if (attribute_list.has_value()) { normalize_fcinfo->args[0].value = CStringGetTextDatum(attribute_list->c_str()); normalize_fcinfo->args[0].isnull = false; } else { normalize_fcinfo->args[0].value = static_cast(0); normalize_fcinfo->args[0].isnull = true; } Datum normalized_datum = dbms_sqlset_normalize_attribute_list(normalize_fcinfo); if (normalize_fcinfo->isnull) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SQLSET attribute_list normalization returned NULL"))); const std::string normalized_attribute_list = text_to_cstring(DatumGetTextPP(normalized_datum)); const SqlsetAttributeList attribute_mode = parse_attribute_list(std::make_optional(normalized_attribute_list)); parse_result_percentage(result_percentage); const std::optional result_limit = parse_result_limit(result_limit_arg); Sqlset& sqlset = require_sqlset(*resolved_owner, *sqlset_name); 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); const size_t row_count = sqlset.rows.size(); const size_t limit = result_limit.has_value() ? std::min(static_cast(*result_limit), row_count) : row_count; for (size_t idx = 0; idx < limit; ++idx) { Datum values[kSqlsetFieldCount]; bool nulls[kSqlsetFieldCount]; fill_sqlset_tuple_values(sqlset.rows[idx], attribute_mode, values, nulls); tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls); } PG_RETURN_NULL(); } Datum dbms_sqlset_normalize_attribute_list(PG_FUNCTION_ARGS) { const std::optional attribute_list = pg_arg_text_optional(fcinfo, 0); const SqlsetAttributeList value = parse_attribute_list(attribute_list); if (value == SqlsetAttributeList::All) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает attribute_list => ALL"))); PG_RETURN_TEXT_P(cstring_to_text(attribute_list_name(value))); } Datum dbms_sqlset_select_sql_trace(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_SQL_TRACE"))); PG_RETURN_NULL(); } Datum dbms_sqlset_select_workload_repository_0(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_WORKLOAD_REPOSITORY"))); PG_RETURN_NULL(); } Datum dbms_sqlset_select_workload_repository_1(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_WORKLOAD_REPOSITORY"))); PG_RETURN_NULL(); } Datum dbms_sqlset_capture_cursor_cache(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.CAPTURE_CURSOR_CACHE"))); PG_RETURN_VOID(); } Datum dbms_sqlset_create_sqlset_proc(PG_FUNCTION_ARGS) { const std::optional sqlset_name = pg_arg_text_optional(fcinfo, 0); const std::optional description = pg_arg_text_optional(fcinfo, 1); const std::optional sqlset_owner = pg_arg_text_optional(fcinfo, 2); (void) create_sqlset_impl(sqlset_name, description, sqlset_owner, false); PG_RETURN_VOID(); } Datum dbms_sqlset_create_stgtab(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.CREATE_STGTAB"))); PG_RETURN_VOID(); } Datum dbms_sqlset_delete_sqlset(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.DELETE_SQLSET"))); PG_RETURN_VOID(); } Datum dbms_sqlset_drop_sqlset(PG_FUNCTION_ARGS) { const std::optional sqlset_name = pg_arg_text_optional(fcinfo, 0); const std::optional sqlset_owner = pg_arg_text_optional(fcinfo, 1); const std::optional resolved_owner = normalize_owner_argument(sqlset_owner); if (!sqlset_name.has_value() || sqlset_name->empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("ORA-13755: invalid \"SQL Tuning Set\" name"))); if (!resolved_owner.has_value()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_SQLSET.DROP_SQLSET не поддерживает sqlset_owner вне текущего пользователя"))); auto& store = sqlset_store(); auto it = store.find(build_sqlset_key(*resolved_owner, *sqlset_name)); if (it == store.end()) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("ORA-13754: \"SQL Tuning Set\" \"%s\" does not exist.", sqlset_name->c_str()))); store.erase(it); PG_RETURN_VOID(); } Datum dbms_sqlset_drop_sqlset_by_prefix(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.DROP_SQLSET_BY_PREFIX"))); PG_RETURN_VOID(); } Datum dbms_sqlset_load_sqlset(PG_FUNCTION_ARGS) { const std::optional sqlset_name = pg_arg_text_optional(fcinfo, 0); const std::optional populate_cursor = pg_arg_text_optional(fcinfo, 1); const std::optional load_option = pg_arg_text_optional(fcinfo, 2); const std::optional update_option = pg_arg_text_optional(fcinfo, 3); const std::optional update_condition = pg_arg_text_optional(fcinfo, 4); const std::optional update_attributes = pg_arg_text_optional(fcinfo, 5); const bool ignore_null = PG_ARGISNULL(6) ? true : PG_GETARG_BOOL(6); const bool has_commit_rows = !PG_ARGISNULL(7); const std::optional sqlset_owner = pg_arg_text_optional(fcinfo, 8); load_sqlset_impl(sqlset_name, populate_cursor, load_option, update_option, update_condition, update_attributes, ignore_null, has_commit_rows, sqlset_owner); PG_RETURN_VOID(); } Datum dbms_sqlset_pack_stgtab(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.PACK_STGTAB"))); PG_RETURN_VOID(); } Datum dbms_sqlset_remap_stgtab(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.REMAP_STGTAB"))); PG_RETURN_VOID(); } Datum dbms_sqlset_remove_reference(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.REMOVE_REFERENCE"))); PG_RETURN_VOID(); } Datum dbms_sqlset_unpack_stgtab(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.UNPACK_STGTAB"))); PG_RETURN_VOID(); } Datum dbms_sqlset_update_sqlset_0(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.UPDATE_SQLSET"))); PG_RETURN_VOID(); } Datum dbms_sqlset_update_sqlset_1(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.UPDATE_SQLSET"))); PG_RETURN_VOID(); } Datum dbms_sqlset_update_sqlset_2(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.UPDATE_SQLSET"))); PG_RETURN_VOID(); }