#include "dbms_stat_funcs.hpp" extern "C" { #include "utils/builtins.h" #include "access/htup_details.h" #include "catalog/pg_type_d.h" #include "funcapi.h" #include "utils/array.h" #include "utils/elog.h" #include "utils/lsyscache.h" #include "utils/numeric.h" #include "executor/spi.h" } // extern "C" #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * Реализация DBMS_STAT_FUNCS. * * Функции пакета читают числовую выборку из указанной таблицы и колонки, * применяют статистические критерии согласия или формируют сводную статистику. * Результаты SQL-visible функций возвращаются как именованные record-значения, * описанные в pg_proc.dat. Общие helpers ниже отвечают за разбор аргументов, * загрузку выборки, математические критерии и формирование tuple-результата. */ namespace { struct DistFitArgs { std::string ownername; std::string tablename; std::string columnname; std::string test_type; bool test_type_is_null = false; bool lambda_is_null = false; bool mu_is_null = false; double lambda = 0.0; double mu = 0.0; }; struct DistFitResult { bool has_sig = false; double sig = 0.0; bool lambda_is_null = false; double lambda = 0.0; bool mu_is_null = false; double mu = 0.0; }; struct WeibullFitArgs { std::string ownername; std::string tablename; std::string columnname; std::string test_type; bool test_type_is_null = false; bool alpha_is_null = false; bool mu_is_null = false; bool beta_is_null = false; double alpha = 0.0; double mu = 0.0; double beta = 0.0; }; struct WeibullFitResult { bool has_sig = false; double sig = 0.0; bool alpha_is_null = false; double alpha = 0.0; bool mu_is_null = false; double mu = 0.0; bool beta_is_null = false; double beta = 0.0; }; struct SummaryArgs { std::string ownername; std::string tablename; std::string columnname; bool sigma_is_null = false; double sigma = 3.0; }; enum class TestType { KolmogorovSmirnov, AndersonDarling, ChiSquared, Invalid }; enum class NormalTestType { ShapiroWilks, KolmogorovSmirnov, AndersonDarling, ChiSquared, Invalid }; enum class PoissonTestType { KolmogorovSmirnov, AndersonDarling, Invalid }; enum class UniformVarType { Continuous, Discrete, Invalid }; inline std::string trim_copy(const std::string_view input) { size_t begin = 0; size_t end = input.size(); while (begin < end && std::isspace(static_cast(input[begin])) != 0) ++begin; while (end > begin && std::isspace(static_cast(input[end - 1])) != 0) --end; return std::string(input.substr(begin, end - begin)); } inline std::string upper_copy(const std::string_view input) { std::string output; output.reserve(input.size()); for (const unsigned char ch : input) output.push_back(static_cast(std::toupper(ch))); return output; } inline bool parse_double_text(const std::string& text, double& value) { if (text.empty()) return false; char* end = nullptr; errno = 0; const double parsed = std::strtod(text.c_str(), &end); if (end == text.c_str() || *end != '\0' || errno == ERANGE || !std::isfinite(parsed)) return false; value = parsed; return true; } static double read_numeric_arg(FunctionCallInfo fcinfo, const int arg_index, const char* parameter_name) { (void)parameter_name; const double value = DatumGetFloat8(DirectFunctionCall1(numeric_float8, PG_GETARG_DATUM(arg_index))); if (std::isnan(value)) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("ORA-06502: PL/SQL: value or conversion error"))); if (!std::isfinite(value)) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("ORA-01426: numeric overflow"))); return value; } inline TestType parse_exponential_test_type(const DistFitArgs& args) { /* * EXPONENTIAL_DIST_FIT использует KOLMOGOROV_SMIRNOV по умолчанию. * В фиксированной SQL-сигнатуре NULL test_type трактуется как запрос * default-поведения. Пустая строка и значения в другом регистре * остаются невалидными. */ if (args.test_type_is_null) return TestType::KolmogorovSmirnov; if (args.test_type == "KOLMOGOROV_SMIRNOV") return TestType::KolmogorovSmirnov; if (args.test_type == "ANDERSON_DARLING") return TestType::AndersonDarling; if (args.test_type == "CHI_SQUARED") return TestType::ChiSquared; return TestType::Invalid; } inline NormalTestType parse_normal_test_type(const DistFitArgs& args) { if (args.test_type_is_null) return NormalTestType::Invalid; if (args.test_type == "SHAPIRO_WILKS") return NormalTestType::ShapiroWilks; if (args.test_type == "KOLMOGOROV_SMIRNOV") return NormalTestType::KolmogorovSmirnov; if (args.test_type == "ANDERSON_DARLING") return NormalTestType::AndersonDarling; if (args.test_type == "CHI_SQUARED") return NormalTestType::ChiSquared; return NormalTestType::Invalid; } inline PoissonTestType parse_poisson_test_type(const DistFitArgs& args) { /* * В фиксированной SQL-сигнатуре default-поведение проверяется явным * KOLMOGOROV_SMIRNOV. Явный NULL, пустая строка, другой регистр и * CHI_SQUARED дают NULL sig. */ if (args.test_type_is_null) return PoissonTestType::Invalid; if (args.test_type == "KOLMOGOROV_SMIRNOV") return PoissonTestType::KolmogorovSmirnov; if (args.test_type == "ANDERSON_DARLING") return PoissonTestType::AndersonDarling; return PoissonTestType::Invalid; } inline UniformVarType parse_uniform_var_type(const bool var_type_is_null, const std::string& var_type) { /* * В фиксированной SQL-сигнатуре default-поведение проверяется явным * CONTINUOUS. Явный NULL, пустая строка и значения в другом регистре * дают NULL sig без обращения к таблице. */ if (var_type_is_null) return UniformVarType::Invalid; if (var_type == "CONTINUOUS") return UniformVarType::Continuous; if (var_type == "DISCRETE") return UniformVarType::Discrete; return UniformVarType::Invalid; } inline TestType parse_uniform_test_type(const DistFitArgs& args) { /* * В фиксированной SQL-сигнатуре default-поведение проверяется явным * KOLMOGOROV_SMIRNOV. Явный NULL, пустая строка и значения в другом * регистре дают NULL sig без обращения к таблице. */ if (args.test_type_is_null) return TestType::Invalid; if (args.test_type == "KOLMOGOROV_SMIRNOV") return TestType::KolmogorovSmirnov; if (args.test_type == "ANDERSON_DARLING") return TestType::AndersonDarling; if (args.test_type == "CHI_SQUARED") return TestType::ChiSquared; return TestType::Invalid; } inline TestType parse_weibull_test_type(const WeibullFitArgs& args) { /* * В фиксированной SQL-сигнатуре default-поведение проверяется явным * KOLMOGOROV_SMIRNOV. Явный NULL, пустая строка и значения в другом * регистре дают NULL sig без обращения к таблице. */ if (args.test_type_is_null) return TestType::Invalid; if (args.test_type == "KOLMOGOROV_SMIRNOV") return TestType::KolmogorovSmirnov; if (args.test_type == "ANDERSON_DARLING") return TestType::AndersonDarling; if (args.test_type == "CHI_SQUARED") return TestType::ChiSquared; return TestType::Invalid; } inline bool is_exponential_test_type_supported(const TestType test_type) { return test_type == TestType::KolmogorovSmirnov; } inline bool is_normal_test_type_supported(const NormalTestType test_type) { return test_type == NormalTestType::KolmogorovSmirnov; } inline bool is_poisson_test_type_supported(const PoissonTestType test_type) { return test_type == PoissonTestType::KolmogorovSmirnov; } inline bool is_uniform_combination_supported(const UniformVarType var_type, const TestType test_type) { return var_type == UniformVarType::Continuous && test_type == TestType::KolmogorovSmirnov; } inline bool is_weibull_test_type_supported(const TestType test_type) { return test_type == TestType::KolmogorovSmirnov; } inline void set_default_mu(DistFitResult& result, const DistFitArgs& args) { result.mu_is_null = false; result.mu = args.mu_is_null ? 0.0 : args.mu; } inline DistFitResult make_exponential_null_sig_result(const DistFitArgs& args) { DistFitResult result; result.has_sig = false; result.lambda_is_null = args.lambda_is_null; result.lambda = args.lambda; set_default_mu(result, args); return result; } inline DistFitResult make_normal_null_sig_result(const DistFitArgs& args) { DistFitResult result; result.has_sig = false; result.lambda_is_null = args.lambda_is_null; result.lambda = args.lambda; result.mu_is_null = args.mu_is_null; result.mu = args.mu; return result; } inline DistFitResult make_dist_fit_result_with_sig(const DistFitArgs& args, const double sig_value) { DistFitResult result; result.has_sig = true; result.sig = sig_value; result.lambda_is_null = args.lambda_is_null; result.lambda = args.lambda; set_default_mu(result, args); return result; } struct NumericSample { std::vector values; int64 row_count = 0; int64 null_count = 0; }; struct SummaryLoadResult { NumericSample sample; }; struct SummaryPayload { bool count_is_null = true; double count = 0.0; bool has_scalar_values = false; double min = 0.0; double max = 0.0; double range = 0.0; double mean = 0.0; bool cmode_is_null = false; bool cmode_contains_single_null = false; std::vector cmode; double variance = 0.0; double stddev = 0.0; double quantile_5 = 0.0; double quantile_25 = 0.0; double median = 0.0; double quantile_75 = 0.0; double quantile_95 = 0.0; bool has_plus_x_sigma = false; bool has_minus_x_sigma = false; double plus_x_sigma = 0.0; double minus_x_sigma = 0.0; bool extreme_values_is_null = false; std::vector extreme_values; bool top_5_values_is_null = false; std::vector top_5_values; bool bottom_5_values_is_null = false; std::vector bottom_5_values; }; static std::string quote_name_or_throw(const std::string& name, const char* what) { if (name.empty()) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("%s cannot be empty", what))); return std::string(quote_identifier(name.c_str())); } template static std::string qualified_relation_name(const Args& args) { const std::string schema = quote_name_or_throw(args.ownername, "ownername"); const std::string table = quote_name_or_throw(args.tablename, "tablename"); return schema + "." + table; } template static NumericSample load_numeric_sample(const Args& args, const char* context_name, const bool ignore_invalid_text = false) { NumericSample sample; const std::string relation = qualified_relation_name(args); const std::string column = quote_name_or_throw(args.columnname, "columnname"); if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errmsg("SPI_connect failed"))); StringInfoData query; initStringInfo(&query); appendStringInfo(&query, "SELECT %s FROM %s", column.c_str(), relation.c_str()); const int rc = SPI_execute(query.data, true, 0); if (rc != SPI_OK_SELECT) { pfree(query.data); SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("failed to query %s", context_name))); } sample.row_count = SPI_processed; for (uint64 i = 0; i < SPI_processed; ++i) { HeapTuple tuple = SPI_tuptable->vals[i]; TupleDesc tupdesc = SPI_tuptable->tupdesc; char* raw = SPI_getvalue(tuple, tupdesc, 1); if (raw == nullptr || *raw == '\0') { sample.null_count += 1; if (raw != nullptr) pfree(raw); continue; } char* end = nullptr; errno = 0; const double parsed = std::strtod(raw, &end); if (end == raw || *end != '\0' || errno == ERANGE) { if (ignore_invalid_text) { pfree(raw); continue; } const char first_char = raw[0]; pfree(raw); pfree(query.data); SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("ORA-01722: unable to convert string value containing '%c' to a number: %s", first_char, args.columnname.c_str()))); } if (!std::isfinite(parsed)) { pfree(raw); pfree(query.data); SPI_finish(); ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("ORA-01426: numeric overflow"))); } pfree(raw); sample.values.push_back(parsed); } pfree(query.data); SPI_finish(); return sample; } static bool summary_type_is_numeric(const Oid type_oid) { switch (type_oid) { case NUMERICOID: case INT2OID: case INT4OID: case INT8OID: case FLOAT4OID: case FLOAT8OID: return true; default: return false; } } static SummaryLoadResult load_summary_sample(const SummaryArgs& args) { SummaryLoadResult result; const std::string relation = qualified_relation_name(args); const std::string column = quote_name_or_throw(args.columnname, "columnname"); if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errmsg("SPI_connect failed"))); StringInfoData query; initStringInfo(&query); appendStringInfo(&query, "SELECT %s FROM %s", column.c_str(), relation.c_str()); const int rc = SPI_execute(query.data, true, 0); if (rc != SPI_OK_SELECT) { pfree(query.data); SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("failed to query DBMS_STAT_FUNCS.SUMMARY"))); } const Oid value_type = SPI_gettypeid(SPI_tuptable->tupdesc, 1); if (!summary_type_is_numeric(value_type)) { pfree(query.data); SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ORA-30495: The argument should be of numeric or datetime type."))); } result.sample.row_count = SPI_processed; for (uint64 i = 0; i < SPI_processed; ++i) { HeapTuple tuple = SPI_tuptable->vals[i]; TupleDesc tupdesc = SPI_tuptable->tupdesc; char* raw = SPI_getvalue(tuple, tupdesc, 1); if (raw == nullptr || *raw == '\0') { result.sample.null_count += 1; if (raw != nullptr) pfree(raw); continue; } char* end = nullptr; errno = 0; const double parsed = std::strtod(raw, &end); if (end == raw || *end != '\0' || errno == ERANGE) { pfree(raw); pfree(query.data); SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ORA-30495: The argument should be of numeric or datetime type."))); } if (!std::isfinite(parsed)) { pfree(raw); pfree(query.data); SPI_finish(); ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("ORA-01426: numeric overflow"))); } pfree(raw); result.sample.values.push_back(parsed); } pfree(query.data); SPI_finish(); return result; } static double sample_mean(const std::vector& values) { if (values.empty()) return 0.0; return std::accumulate(values.begin(), values.end(), 0.0) / static_cast(values.size()); } static double sample_variance(const std::vector& values, const double mean) { if (values.size() < 2) return 0.0; double acc = 0.0; for (const double v : values) { const double d = v - mean; acc += d * d; } return acc / static_cast(values.size() - 1); } static double sample_quantile(std::vector values, const double q) { if (values.empty()) return 0.0; std::sort(values.begin(), values.end()); if (q <= 0.0) return values.front(); if (q >= 1.0) return values.back(); const double pos = q * (static_cast(values.size()) - 1.0); const size_t lo = static_cast(std::floor(pos)); const size_t hi = static_cast(std::ceil(pos)); if (lo == hi) return values[lo]; const double frac = pos - static_cast(lo); return values[lo] * (1.0 - frac) + values[hi] * frac; } static std::vector sorted_copy(const std::vector& values) { std::vector out = values; std::sort(out.begin(), out.end()); return out; } static std::vector top_k_desc(const std::vector& values, const size_t k) { std::vector out = values; std::sort(out.begin(), out.end(), std::greater()); if (out.size() > k) out.resize(k); return out; } static std::vector bottom_k_desc(const std::vector& values, const size_t k) { std::vector out = values; std::sort(out.begin(), out.end(), std::less()); if (out.size() > k) out.resize(k); std::sort(out.begin(), out.end(), std::greater()); return out; } static std::vector mode_values(const std::vector& values) { std::map counts; for (const double v : values) ++counts[v]; size_t best = 0; for (const auto& [value, count] : counts) best = std::max(best, count); std::vector out; for (const auto& [value, count] : counts) { if (count == best) out.push_back(value); } return out; } static std::vector extreme_values(const std::vector& values, const double lower, const double upper) { std::vector out; for (const double v : values) { if (v < lower || v > upper) out.push_back(v); } std::sort(out.begin(), out.end()); return out; } static double normal_cdf(const double x, const double mean, const double stdev) { if (stdev == 0.0) return std::numeric_limits::quiet_NaN(); return 0.5 * std::erfc(-(x - mean) / (stdev * std::sqrt(2.0))); } static double exponential_cdf(const double x, const double lambda, const double mu) { if (x < mu) return 0.0; if (lambda <= 0.0) return 0.0; return 1.0 - std::exp(-lambda * (x - mu)); } static double uniform_continuous_cdf_oracle(const double x, const double a, const double b) { /* * При нормальном порядке границ CDF зажимается в [0, 1]. Если paramA > * paramB, Oracle сохраняет исходный порядок и использует линейную формулу * без перестановки границ. */ if (a < b) { if (x < a) return 0.0; if (x >= b) return 1.0; return (x - a) / (b - a); } return (x - a) / (b - a); } static double weibull_cdf(const double x, const double alpha, const double mu, const double beta) { if (x < mu) return 0.0; if (alpha <= 0.0) return std::numeric_limits::quiet_NaN(); const double t = (x - mu) / alpha; if (t < 0.0) return 0.0; return 1.0 - std::exp(-std::pow(t, beta)); } static double regularized_gamma_q(double a, double x) { const int ITMAX = 100; const double EPS = 3.0e-7; const double FPMIN = 1.0e-30; if (x < 0.0 || a <= 0.0) return std::numeric_limits::quiet_NaN(); if (x == 0.0) return 1.0; if (x < a + 1.0) { double ap = a; double sum = 1.0 / a; double del = sum; for (int n = 1; n <= ITMAX; ++n) { ++ap; del *= x / ap; sum += del; if (std::fabs(del) < std::fabs(sum) * EPS) break; } return 1.0 - sum * std::exp(-x + a * std::log(x) - std::lgamma(a)); } double b = x + 1.0 - a; double c = 1.0 / FPMIN; double d = 1.0 / b; double h = d; for (int i = 1; i <= ITMAX; ++i) { const double an = -static_cast(i) * (static_cast(i) - a); b += 2.0; d = an * d + b; if (std::fabs(d) < FPMIN) d = FPMIN; c = b + an / c; if (std::fabs(c) < FPMIN) c = FPMIN; d = 1.0 / d; const double del = d * c; h *= del; if (std::fabs(del - 1.0) < EPS) break; } return std::exp(-x + a * std::log(x) - std::lgamma(a)) * h; } static double poisson_cdf_oracle(const double x, const double lambda) { /* * Для совместимого поведения CDF вычисляется через Q(x + 1, lambda) * без принудительного округления x. Это сохраняет наблюдаемую семантику * для дробных значений в проверяемой колонке. */ if (x < 0.0) return 0.0; if (lambda < 0.0) return 0.0; if (lambda == 0.0) return 1.0; return std::clamp(regularized_gamma_q(x + 1.0, lambda), 0.0, 1.0); } static double compute_ks_pvalue(const double d, const size_t n) { if (n == 0) return 0.0; const double en = std::sqrt(static_cast(n)); const double x = (en + 0.12 + 0.11 / en) * d; double sum = 0.0; for (int k = 1; k < 100; ++k) { const double term = 2.0 * std::pow(-1.0, k - 1) * std::exp(-2.0 * k * k * x * x); sum += term; if (std::fabs(term) < 1e-12) break; } return std::clamp(sum, 0.0, 1.0); } static std::optional ks_pvalue_checked(const double d, const int32 sample_count) { if (!std::isfinite(d) || d < 0.0 || sample_count <= 0) return std::nullopt; return compute_ks_pvalue(d, static_cast(sample_count)); } static double call_ks_pvalue_service(const double stat, const size_t sample_count) { if (sample_count > static_cast(PG_INT32_MAX)) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("sample count is too large"))); const Datum result = DirectFunctionCall2(dbms_stat_funcs_ks_pvalue, Float8GetDatum(stat), Int32GetDatum(static_cast(sample_count))); return DatumGetFloat8(result); } static double compute_ks_statistic(const std::vector& values, const std::function& cdf) { const std::vector sorted = sorted_copy(values); const size_t n = sorted.size(); double d = 0.0; for (size_t i = 0; i < n; ++i) { const double fi = cdf(sorted[i]); const double fn = static_cast(i + 1) / static_cast(n); const double fn1 = static_cast(i) / static_cast(n); d = std::max(d, std::fabs(fn - fi)); d = std::max(d, std::fabs(fi - fn1)); } return d; } static double compute_fit_ks_statistic(const std::vector& values, const std::function& cdf) { /* * Критерий Колмогорова-Смирнова для distribution-fit путей пакета * сравнивает теоретическую CDF с накопленной долей после текущего * значения отсортированной выборки: * * D = max |(i + 1) / n - F(x_i)| * * Общий two-sided вариант compute_ks_statistic оставлен для функций, * где уже используется прежняя формула. */ const std::vector sorted = sorted_copy(values); const size_t n = sorted.size(); double d = 0.0; for (size_t i = 0; i < n; ++i) { const double empirical = static_cast(i + 1) / static_cast(n); const double theoretical = cdf(sorted[i]); d = std::max(d, std::fabs(empirical - theoretical)); } return d; } static SummaryPayload compute_summary_payload(const NumericSample& sample, const double sigma_value, const bool sigma_is_null) { SummaryPayload payload; if (sample.row_count == 0) { payload.count_is_null = true; payload.has_scalar_values = false; return payload; } payload.count_is_null = false; payload.count = static_cast(sample.values.size()); if (sample.values.empty()) { payload.has_scalar_values = false; /* Oracle SUMMARY возвращает cmode-коллекцию с одним NULL для all-NULL колонок. */ payload.cmode_contains_single_null = true; return payload; } const std::vector sorted = sorted_copy(sample.values); payload.has_scalar_values = true; payload.min = sorted.front(); payload.max = sorted.back(); payload.range = payload.max - payload.min; payload.mean = sample_mean(sample.values); payload.variance = sample_variance(sample.values, payload.mean); payload.stddev = std::sqrt(payload.variance); payload.quantile_5 = sample_quantile(sample.values, 0.05); payload.quantile_25 = sample_quantile(sample.values, 0.25); payload.median = sample_quantile(sample.values, 0.5); payload.quantile_75 = sample_quantile(sample.values, 0.75); payload.quantile_95 = sample_quantile(sample.values, 0.95); payload.has_plus_x_sigma = !sigma_is_null; payload.has_minus_x_sigma = !sigma_is_null; if (!sigma_is_null) { payload.plus_x_sigma = payload.mean + sigma_value * payload.stddev; payload.minus_x_sigma = payload.mean - sigma_value * payload.stddev; payload.extreme_values = extreme_values(sample.values, payload.minus_x_sigma, payload.plus_x_sigma); } payload.cmode = mode_values(sample.values); payload.top_5_values = top_k_desc(sample.values, 5); payload.bottom_5_values = bottom_k_desc(sample.values, 5); return payload; } static Datum numeric_datum(const double value) { return DirectFunctionCall1(float8_numeric, Float8GetDatum(value)); } static Datum numeric_array_datum(const std::vector& values) { if (values.empty()) return PointerGetDatum(construct_empty_array(NUMERICOID)); std::vector elems(values.size()); bool* null_flags = static_cast(palloc0(sizeof(bool) * values.size())); for (size_t i = 0; i < values.size(); ++i) elems[i] = numeric_datum(values[i]); int dims[1] = {static_cast(values.size())}; int lbs[1] = {1}; ArrayType* array = construct_md_array(elems.data(), null_flags, 1, dims, lbs, NUMERICOID, -1, false, 'i'); pfree(null_flags); return PointerGetDatum(array); } static Datum single_null_numeric_array_datum() { Datum elem = static_cast(0); bool is_null = true; int dims[1] = {1}; int lbs[1] = {1}; ArrayType* array = construct_md_array(&elem, &is_null, 1, dims, lbs, NUMERICOID, -1, false, 'i'); return PointerGetDatum(array); } static TupleDesc result_tuple_desc(FunctionCallInfo fcinfo, const char* function_name, const int expected_field_count) { TupleDesc tupdesc; if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("function returning record called in context that cannot accept type record"))); tupdesc = BlessTupleDesc(tupdesc); if (tupdesc->natts != expected_field_count) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("%s result descriptor has %d fields, expected %d", function_name, tupdesc->natts, expected_field_count))); return tupdesc; } inline void set_numeric_tuple_field(Datum* values, bool* nulls, const int index, const bool is_null, const double value) { nulls[index] = is_null; if (!is_null) values[index] = numeric_datum(value); } inline void set_numeric_array_tuple_field(Datum* values, bool* nulls, const int index, const bool is_null, const std::vector& value) { nulls[index] = is_null; if (!is_null) values[index] = numeric_array_datum(value); } inline void set_single_null_numeric_array_tuple_field(Datum* values, bool* nulls, const int index) { nulls[index] = false; values[index] = single_null_numeric_array_datum(); } inline Datum heap_tuple_datum(TupleDesc tupdesc, Datum* values, bool* nulls) { HeapTuple tuple = heap_form_tuple(tupdesc, values, nulls); return HeapTupleGetDatum(tuple); } static Datum form_summary_tuple(FunctionCallInfo fcinfo, const SummaryPayload& payload) { constexpr int field_count = 18; TupleDesc tupdesc = result_tuple_desc(fcinfo, "DBMS_STAT_FUNCS.SUMMARY", field_count); Datum values[field_count] = {}; bool nulls[field_count] = {}; set_numeric_tuple_field(values, nulls, 0, payload.count_is_null, payload.count); const bool scalar_null = !payload.has_scalar_values; set_numeric_tuple_field(values, nulls, 1, scalar_null, payload.min); set_numeric_tuple_field(values, nulls, 2, scalar_null, payload.max); set_numeric_tuple_field(values, nulls, 3, scalar_null, payload.range); set_numeric_tuple_field(values, nulls, 4, scalar_null, payload.mean); if (payload.cmode_contains_single_null) set_single_null_numeric_array_tuple_field(values, nulls, 5); else set_numeric_array_tuple_field(values, nulls, 5, payload.cmode_is_null, payload.cmode); set_numeric_tuple_field(values, nulls, 6, scalar_null, payload.variance); set_numeric_tuple_field(values, nulls, 7, scalar_null, payload.stddev); set_numeric_tuple_field(values, nulls, 8, scalar_null, payload.quantile_5); set_numeric_tuple_field(values, nulls, 9, scalar_null, payload.quantile_25); set_numeric_tuple_field(values, nulls, 10, scalar_null, payload.median); set_numeric_tuple_field(values, nulls, 11, scalar_null, payload.quantile_75); set_numeric_tuple_field(values, nulls, 12, scalar_null, payload.quantile_95); set_numeric_tuple_field(values, nulls, 13, !payload.has_plus_x_sigma, payload.plus_x_sigma); set_numeric_tuple_field(values, nulls, 14, !payload.has_minus_x_sigma, payload.minus_x_sigma); set_numeric_array_tuple_field(values, nulls, 15, payload.extreme_values_is_null, payload.extreme_values); set_numeric_array_tuple_field(values, nulls, 16, payload.top_5_values_is_null, payload.top_5_values); set_numeric_array_tuple_field(values, nulls, 17, payload.bottom_5_values_is_null, payload.bottom_5_values); return heap_tuple_datum(tupdesc, values, nulls); } static Datum form_dist_fit_tuple(FunctionCallInfo fcinfo, const DistFitResult& result) { constexpr int field_count = 3; TupleDesc tupdesc = result_tuple_desc(fcinfo, "DBMS_STAT_FUNCS distribution fit", field_count); Datum values[field_count] = {}; bool nulls[field_count] = {}; set_numeric_tuple_field(values, nulls, 0, result.lambda_is_null, result.lambda); set_numeric_tuple_field(values, nulls, 1, result.mu_is_null, result.mu); set_numeric_tuple_field(values, nulls, 2, !result.has_sig, result.sig); return heap_tuple_datum(tupdesc, values, nulls); } static Datum form_poisson_tuple(FunctionCallInfo fcinfo, const DistFitResult& result) { constexpr int field_count = 2; TupleDesc tupdesc = result_tuple_desc(fcinfo, "DBMS_STAT_FUNCS.POISSON_DIST_FIT", field_count); Datum values[field_count] = {}; bool nulls[field_count] = {}; set_numeric_tuple_field(values, nulls, 0, result.lambda_is_null, result.lambda); set_numeric_tuple_field(values, nulls, 1, !result.has_sig, result.sig); return heap_tuple_datum(tupdesc, values, nulls); } static Datum form_weibull_tuple(FunctionCallInfo fcinfo, const WeibullFitResult& result) { constexpr int field_count = 4; TupleDesc tupdesc = result_tuple_desc(fcinfo, "DBMS_STAT_FUNCS.WEIBULL_DIST_FIT", field_count); Datum values[field_count] = {}; bool nulls[field_count] = {}; set_numeric_tuple_field(values, nulls, 0, result.alpha_is_null, result.alpha); set_numeric_tuple_field(values, nulls, 1, result.mu_is_null, result.mu); set_numeric_tuple_field(values, nulls, 2, result.beta_is_null, result.beta); set_numeric_tuple_field(values, nulls, 3, !result.has_sig, result.sig); return heap_tuple_datum(tupdesc, values, nulls); } inline void raise_compat_error(const char* message, const char* detail = nullptr); static DistFitResult compute_exponential_fit_result(const DistFitArgs& args, const NumericSample& sample) { /* * EXPONENTIAL_DIST_FIT использует KS-критерий для заданных lambda и mu. * NULL mu трактуется как 0. Другие критерии возвращают NULL sig до чтения таблицы. */ if (sample.values.empty()) raise_compat_error("ORA-01405: The fetched column returned a NULL value."); const double lambda = args.lambda; const double mu = args.mu_is_null ? 0.0 : args.mu; if (lambda < 0.0) { DistFitResult result = make_dist_fit_result_with_sig(args, 0.0); result.lambda_is_null = false; result.lambda = lambda; result.mu_is_null = false; result.mu = mu; return result; } const auto cdf = [lambda, mu](double x) { return exponential_cdf(x, lambda, mu); }; const double stat = compute_fit_ks_statistic(sample.values, cdf); const double sig = call_ks_pvalue_service(stat, sample.values.size()); DistFitResult result = make_dist_fit_result_with_sig(args, sig); result.lambda_is_null = false; result.lambda = lambda; result.mu_is_null = false; result.mu = mu; return result; } static DistFitResult compute_normal_fit_result(const DistFitArgs& args, const NumericSample& sample, const NormalTestType test_type) { /* * NORMAL_DIST_FIT использует KS-критерий. NULL mean или stdev * подставляет оценку по выборке. */ if (sample.values.empty()) raise_compat_error("ORA-01405: The fetched column returned a NULL value."); const double sample_mean_value = sample_mean(sample.values); const double sample_stdev_value = std::sqrt(std::max(0.0, sample_variance(sample.values, sample_mean_value))); Assert(test_type == NormalTestType::KolmogorovSmirnov); const double mean = args.lambda_is_null ? sample_mean_value : args.lambda; const double stdev = args.mu_is_null ? sample_stdev_value : args.mu; if (stdev == 0.0) raise_compat_error("ORA-01405: The fetched column returned a NULL value."); const auto cdf = [mean, stdev](double x) { return normal_cdf(x, mean, stdev); }; const double stat = compute_ks_statistic(sample.values, cdf); const double sig = call_ks_pvalue_service(stat, sample.values.size()); DistFitResult result = make_dist_fit_result_with_sig(args, sig); result.lambda_is_null = false; result.lambda = mean; result.mu_is_null = false; result.mu = stdev; return result; } static DistFitResult make_poisson_null_sig_result(const DistFitArgs& args) { DistFitResult result; result.has_sig = false; result.lambda_is_null = args.lambda_is_null; result.lambda = args.lambda; result.mu_is_null = true; result.mu = 0.0; return result; } static DistFitResult compute_poisson_fit_result(const DistFitArgs& args, const NumericSample& sample) { /* * POISSON_DIST_FIT проверяет целочисленные или близкие к ним счётчики * событий относительно заданной интенсивности lambda. Невалидный * test_type и NULL lambda обрабатываются до чтения таблицы. Пустая * non-NULL выборка и наличие NULL в колонке остаются ошибкой. */ if (args.lambda_is_null) return make_poisson_null_sig_result(args); if (sample.values.empty()) raise_compat_error("ORA-01405: The fetched column returned a NULL value."); if (sample.null_count > 0) raise_compat_error("ORA-01405: The fetched column returned a NULL value."); const double lambda = args.lambda; const auto cdf = [lambda](double x) { return poisson_cdf_oracle(x, lambda); }; const double stat = compute_fit_ks_statistic(sample.values, cdf); const double sig = call_ks_pvalue_service(stat, sample.values.size()); DistFitResult result = make_poisson_null_sig_result(args); result.has_sig = true; result.sig = sig; result.lambda_is_null = false; result.lambda = lambda; return result; } static DistFitResult make_uniform_null_sig_result(const DistFitArgs& args) { DistFitResult result; result.has_sig = false; result.lambda_is_null = args.lambda_is_null; result.lambda = args.lambda; result.mu_is_null = args.mu_is_null; result.mu = args.mu; return result; } static DistFitResult compute_uniform_fit_result(const DistFitArgs& args, const NumericSample& sample) { if (sample.values.empty()) raise_compat_error("ORA-01405: The fetched column returned a NULL value."); const double param_a = args.lambda; const double param_b = args.mu; DistFitResult result = make_uniform_null_sig_result(args); result.lambda_is_null = false; result.lambda = param_a; result.mu_is_null = false; result.mu = param_b; const auto cdf = [param_a, param_b](double x) { return uniform_continuous_cdf_oracle(x, param_a, param_b); }; const double stat = compute_fit_ks_statistic(sample.values, cdf); result.has_sig = true; result.sig = call_ks_pvalue_service(stat, sample.values.size()); return result; } static WeibullFitResult make_weibull_null_sig_result(const WeibullFitArgs& args) { WeibullFitResult result; result.has_sig = false; result.alpha_is_null = args.alpha_is_null; result.alpha = args.alpha; result.mu_is_null = false; result.mu = args.mu_is_null ? 0.0 : args.mu; result.beta_is_null = args.beta_is_null; result.beta = args.beta; return result; } static WeibullFitResult compute_weibull_fit_result(const WeibullFitArgs& args, const NumericSample& sample) { /* * WEIBULL_DIST_FIT использует KS-критерий для распределения Вейбулла * с параметрами alpha, mu и beta. NULL mu трактуется как 0. */ if (sample.values.empty()) raise_compat_error("ORA-01405: The fetched column returned a NULL value."); const double alpha = args.alpha; const double mu = args.mu_is_null ? 0.0 : args.mu; const double beta = args.beta; if (alpha == 0.0) ereport(ERROR, (errcode(ERRCODE_DIVISION_BY_ZERO), errmsg("ORA-01476: divisor is equal to zero"))); if (alpha < 0.0) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("ORA-06502: PL/SQL: value or conversion error"))); for (const double value : sample.values) { if (value < mu) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("ORA-06502: PL/SQL: value or conversion error"))); } const auto cdf = [alpha, mu, beta](double x) { return weibull_cdf(x, alpha, mu, beta); }; const double stat = compute_fit_ks_statistic(sample.values, cdf); const double sig = call_ks_pvalue_service(stat, sample.values.size()); WeibullFitResult result = make_weibull_null_sig_result(args); result.has_sig = true; result.sig = sig; result.alpha_is_null = false; result.alpha = alpha; result.mu_is_null = false; result.mu = mu; result.beta_is_null = false; result.beta = beta; return result; } inline void raise_compat_error(const char* message, const char* detail) { if (detail != nullptr) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("%s: %s", message, detail))); ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("%s", message))); } inline SummaryArgs read_summary_args(FunctionCallInfo fcinfo) { SummaryArgs args; if (!PG_ARGISNULL(0)) args.ownername = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) args.tablename = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) args.columnname = text_to_cstring(PG_GETARG_TEXT_PP(2)); args.sigma_is_null = PG_ARGISNULL(3); if (!args.sigma_is_null) args.sigma = read_numeric_arg(fcinfo, 3, "sigma_value"); return args; } inline DistFitArgs read_dist_fit_args(FunctionCallInfo fcinfo) { DistFitArgs args; if (!PG_ARGISNULL(0)) args.ownername = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) args.tablename = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) args.columnname = text_to_cstring(PG_GETARG_TEXT_PP(2)); args.test_type_is_null = PG_ARGISNULL(3); if (!args.test_type_is_null) args.test_type = trim_copy(text_to_cstring(PG_GETARG_TEXT_PP(3))); args.lambda_is_null = PG_ARGISNULL(4); if (!args.lambda_is_null) args.lambda = read_numeric_arg(fcinfo, 4, "lambda"); args.mu_is_null = PG_ARGISNULL(5); if (!args.mu_is_null) args.mu = read_numeric_arg(fcinfo, 5, "mu"); return args; } inline DistFitArgs read_poisson_dist_fit_args(FunctionCallInfo fcinfo) { DistFitArgs args; if (!PG_ARGISNULL(0)) args.ownername = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) args.tablename = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) args.columnname = text_to_cstring(PG_GETARG_TEXT_PP(2)); args.test_type_is_null = PG_ARGISNULL(3); if (!args.test_type_is_null) args.test_type = trim_copy(text_to_cstring(PG_GETARG_TEXT_PP(3))); args.lambda_is_null = PG_ARGISNULL(4); if (!args.lambda_is_null) args.lambda = read_numeric_arg(fcinfo, 4, "lambda"); args.mu_is_null = true; args.mu = 0.0; return args; } inline DistFitArgs read_uniform_dist_fit_args(FunctionCallInfo fcinfo, std::string& var_type, bool& var_type_is_null) { DistFitArgs args; if (!PG_ARGISNULL(0)) args.ownername = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) args.tablename = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) args.columnname = text_to_cstring(PG_GETARG_TEXT_PP(2)); var_type_is_null = PG_ARGISNULL(3); if (!var_type_is_null) var_type = trim_copy(text_to_cstring(PG_GETARG_TEXT_PP(3))); args.test_type_is_null = PG_ARGISNULL(4); if (!args.test_type_is_null) args.test_type = trim_copy(text_to_cstring(PG_GETARG_TEXT_PP(4))); args.lambda_is_null = PG_ARGISNULL(5); if (!args.lambda_is_null) args.lambda = read_numeric_arg(fcinfo, 5, "paramA"); args.mu_is_null = PG_ARGISNULL(6); if (!args.mu_is_null) args.mu = read_numeric_arg(fcinfo, 6, "paramB"); return args; } inline WeibullFitArgs read_weibull_dist_fit_args(FunctionCallInfo fcinfo) { WeibullFitArgs args; if (!PG_ARGISNULL(0)) args.ownername = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) args.tablename = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) args.columnname = text_to_cstring(PG_GETARG_TEXT_PP(2)); args.test_type_is_null = PG_ARGISNULL(3); if (!args.test_type_is_null) args.test_type = trim_copy(text_to_cstring(PG_GETARG_TEXT_PP(3))); args.alpha_is_null = PG_ARGISNULL(4); if (!args.alpha_is_null) args.alpha = read_numeric_arg(fcinfo, 4, "alpha"); args.mu_is_null = PG_ARGISNULL(5); if (!args.mu_is_null) args.mu = read_numeric_arg(fcinfo, 5, "mu"); args.beta_is_null = PG_ARGISNULL(6); if (!args.beta_is_null) args.beta = read_numeric_arg(fcinfo, 6, "beta"); return args; } } // namespace extern "C" { PG_FUNCTION_INFO_V1(dbms_stat_funcs_exponential_dist_fit); PG_FUNCTION_INFO_V1(dbms_stat_funcs_get_version); PG_FUNCTION_INFO_V1(dbms_stat_funcs_ks_pvalue); PG_FUNCTION_INFO_V1(dbms_stat_funcs_normal_dist_fit); PG_FUNCTION_INFO_V1(dbms_stat_funcs_poisson_dist_fit); PG_FUNCTION_INFO_V1(dbms_stat_funcs_summary); PG_FUNCTION_INFO_V1(dbms_stat_funcs_uniform_dist_fit); PG_FUNCTION_INFO_V1(dbms_stat_funcs_weibull_dist_fit); /// @brief Версия RUDB пакета DBMS_STAT_FUNCS (Oracle DBMS_STAT_FUNCS пакет) #define RUDB_DBMS_STAT_FUNCS_VERSION "1.0.0" } // extern "C" Datum dbms_stat_funcs_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_STAT_FUNCS_VERSION)); } Datum dbms_stat_funcs_ks_pvalue(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) PG_RETURN_NULL(); const double statistic = PG_GETARG_FLOAT8(0); const int32 sample_count = PG_GETARG_INT32(1); const std::optional result = ks_pvalue_checked(statistic, sample_count); if (!result.has_value()) PG_RETURN_NULL(); PG_RETURN_FLOAT8(*result); } Datum dbms_stat_funcs_exponential_dist_fit(PG_FUNCTION_ARGS) { const DistFitArgs args = read_dist_fit_args(fcinfo); const TestType test_type = parse_exponential_test_type(args); /* * Мягкие ошибки аргументов обрабатываются до чтения таблицы: * невалидный test_type и NULL lambda дают NULL sig. */ if (test_type == TestType::Invalid || !is_exponential_test_type_supported(test_type) || args.lambda_is_null) { const DistFitResult result = make_exponential_null_sig_result(args); PG_RETURN_DATUM(form_dist_fit_tuple(fcinfo, result)); } const NumericSample sample = load_numeric_sample(args, "DBMS_STAT_FUNCS.EXPONENTIAL_DIST_FIT"); const DistFitResult result = compute_exponential_fit_result(args, sample); PG_RETURN_DATUM(form_dist_fit_tuple(fcinfo, result)); } Datum dbms_stat_funcs_normal_dist_fit(PG_FUNCTION_ARGS) { const DistFitArgs args = read_dist_fit_args(fcinfo); const NormalTestType test_type = parse_normal_test_type(args); /* Невалидный test_type даёт NULL sig без обращения к таблице. */ if (test_type == NormalTestType::Invalid || !is_normal_test_type_supported(test_type)) { const DistFitResult result = make_normal_null_sig_result(args); PG_RETURN_DATUM(form_dist_fit_tuple(fcinfo, result)); } const NumericSample sample = load_numeric_sample(args, "DBMS_STAT_FUNCS.NORMAL_DIST_FIT", true); const DistFitResult result = compute_normal_fit_result(args, sample, test_type); PG_RETURN_DATUM(form_dist_fit_tuple(fcinfo, result)); } Datum dbms_stat_funcs_poisson_dist_fit(PG_FUNCTION_ARGS) { const DistFitArgs args = read_poisson_dist_fit_args(fcinfo); const PoissonTestType test_type = parse_poisson_test_type(args); /* Невалидный test_type и NULL lambda дают NULL sig без обращения к таблице. */ if (test_type == PoissonTestType::Invalid || !is_poisson_test_type_supported(test_type) || args.lambda_is_null) { const DistFitResult result = make_poisson_null_sig_result(args); PG_RETURN_DATUM(form_poisson_tuple(fcinfo, result)); } const NumericSample sample = load_numeric_sample(args, "DBMS_STAT_FUNCS.POISSON_DIST_FIT"); const DistFitResult result = compute_poisson_fit_result(args, sample); PG_RETURN_DATUM(form_poisson_tuple(fcinfo, result)); } Datum dbms_stat_funcs_summary(PG_FUNCTION_ARGS) { const SummaryArgs args = read_summary_args(fcinfo); const SummaryLoadResult loaded = load_summary_sample(args); const SummaryPayload payload = compute_summary_payload(loaded.sample, args.sigma, args.sigma_is_null); PG_RETURN_DATUM(form_summary_tuple(fcinfo, payload)); } Datum dbms_stat_funcs_uniform_dist_fit(PG_FUNCTION_ARGS) { std::string var_type_raw; bool var_type_is_null = false; const DistFitArgs args = read_uniform_dist_fit_args(fcinfo, var_type_raw, var_type_is_null); const UniformVarType var_type = parse_uniform_var_type(var_type_is_null, var_type_raw); const TestType test_type = parse_uniform_test_type(args); if (var_type == UniformVarType::Invalid || test_type == TestType::Invalid || !is_uniform_combination_supported(var_type, test_type)) { const DistFitResult result = make_uniform_null_sig_result(args); PG_RETURN_DATUM(form_dist_fit_tuple(fcinfo, result)); } if (args.lambda_is_null || args.mu_is_null) { const DistFitResult result = make_uniform_null_sig_result(args); PG_RETURN_DATUM(form_dist_fit_tuple(fcinfo, result)); } if (args.lambda == args.mu) ereport(ERROR, (errcode(ERRCODE_DIVISION_BY_ZERO), errmsg("ORA-01476: divisor is equal to zero"))); const NumericSample sample = load_numeric_sample(args, "DBMS_STAT_FUNCS.UNIFORM_DIST_FIT"); const DistFitResult result = compute_uniform_fit_result(args, sample); PG_RETURN_DATUM(form_dist_fit_tuple(fcinfo, result)); } Datum dbms_stat_funcs_weibull_dist_fit(PG_FUNCTION_ARGS) { const WeibullFitArgs args = read_weibull_dist_fit_args(fcinfo); const TestType test_type = parse_weibull_test_type(args); /* Невалидный test_type и NULL alpha/beta дают NULL sig без обращения к таблице. */ if (test_type == TestType::Invalid || !is_weibull_test_type_supported(test_type) || args.alpha_is_null || args.beta_is_null) { const WeibullFitResult result = make_weibull_null_sig_result(args); PG_RETURN_DATUM(form_weibull_tuple(fcinfo, result)); } if (args.alpha == 0.0) ereport(ERROR, (errcode(ERRCODE_DIVISION_BY_ZERO), errmsg("ORA-01476: divisor is equal to zero"))); if (args.alpha < 0.0) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("ORA-06502: PL/SQL: value or conversion error"))); const NumericSample sample = load_numeric_sample(args, "DBMS_STAT_FUNCS.WEIBULL_DIST_FIT"); const WeibullFitResult result = compute_weibull_fit_result(args, sample); PG_RETURN_DATUM(form_weibull_tuple(fcinfo, result)); }