#include "utl_match.hpp" #include #include #include #include #include extern "C" { PG_FUNCTION_INFO_V1(utl_match_edit_distance); PG_FUNCTION_INFO_V1(utl_match_edit_distance_similarity); PG_FUNCTION_INFO_V1(utl_match_jaro_winkler); PG_FUNCTION_INFO_V1(utl_match_jaro_winkler_similarity); PG_FUNCTION_INFO_V1(utl_match_levenshtein); PG_FUNCTION_INFO_V1(utl_match_get_version); /// @brief Версия RUDB пакета UTL_MATCH (Oracle UTL_MATCH пакет) #define RUDB_UTL_MATCH_VERSION "1.0.0" } /// @brief Преобразует PostgreSQL text* в std::string. static inline std::string to_std_string(text* t) { char* c = text_to_cstring(t); std::string s(c); pfree(c); return s; } #include #include #include // Точная десятичная отсечка до 16 знаков после точки (без округления). static inline double truncate_decimal_16(double x) { if (!std::isfinite(x)) return x; // держим в [0,1] для JW if (x < 0.0) x = 0.0; if (x > 1.0) x = 1.0; // Печатаем c фиксированной точкой и большим запасом дробных знаков, // затем ОТРЕЗАЕМ до 16 после точки. Локаль нужна "C" (в PG по умолчанию так). char buf[64]; // 20 знаков после точки достаточно, чтобы потом отрезать 16. int n = std::snprintf(buf, sizeof(buf), "%.20f", x); char* dot = std::strchr(buf, '.'); if (!dot) { // на всякий случай (для x == 0, 1 и т.п.) — вернём как есть return x; } const int keep = (int)((dot - buf) + 1 + 16); // позиция после 16-го знака char out[64]; const int m = std::min(keep, n); std::memcpy(out, buf, m); out[m] = '\0'; // Парсим обратно — получим ближайшее double к этой ДЕСЯТИЧНОЙ записи. return std::strtod(out, nullptr); } // --- helper: шаг по UTF-8 символу --- static inline size_t utf8_char_len(unsigned char b) { if (b < 0x80) return 1; if ((b & 0xE0) == 0xC0) return 2; if ((b & 0xF0) == 0xE0) return 3; return 4; // 11110xxx } // Собираем «совпавшие» символы UTF-8 как срезы байтов static std::vector> collect_matched_codepoints(const std::string& s, const std::vector& matchFlags) { std::vector> spans; const unsigned char* p = reinterpret_cast(s.data()); size_t n = s.size(); for (size_t i = 0; i < n; ) { size_t len = utf8_char_len(p[i]); size_t j = std::min(n, i + len); bool any = false; for (size_t k = i; k < j; ++k) { if (matchFlags[k]) { any = true; break; } } if (any) spans.emplace_back(i, j); i = j; } return spans; } /** * @brief Базовая метрика Jaro (0..1). * @details Считает совпадающие символы в окне ширины floor(max(|s|,|t|)/2)-1 * и половину транспозиций; формула Джаро: (m/|s| + m/|t| + (m-t)/m)/3. * @param s Первая строка. * @param t Вторая строка. * @return Значение сходства 0..1 (1 — полное совпадение). */ static double jaro_similarity(const std::string& s, const std::string& t) { const int s_len = (int)s.size(); const int t_len = (int)t.size(); if (s_len == 0 && t_len == 0) return 1.0; if (s_len == 0 || t_len == 0) return 0.0; const int match_distance = std::max(0, std::max(s_len, t_len) / 2 - 1); std::vector s_match(s_len, false), t_match(t_len, false); int matches = 0; // 1) совпадения — как и было (по байтам) for (int i = 0; i < s_len; ++i) { const int start = std::max(0, i - match_distance); const int end = std::min(i + match_distance + 1, t_len); for (int j = start; j < end; ++j) { if (t_match[j]) continue; if ((unsigned char)s[i] != (unsigned char)t[j]) continue; s_match[i] = t_match[j] = true; ++matches; break; } } if (matches == 0) return 0.0; // 2) транспозиции: сравниваем последовательности совпавших СИМВОЛОВ auto s_cp = collect_matched_codepoints(s, s_match); auto t_cp = collect_matched_codepoints(t, t_match); const size_t L = std::min(s_cp.size(), t_cp.size()); int mismatch_count = 0; for (size_t idx = 0; idx < L; ++idx) { const auto [si0, si1] = s_cp[idx]; const auto [ti0, ti1] = t_cp[idx]; const size_t sl = si1 - si0, tl = ti1 - ti0; if (sl != tl || std::memcmp(s.data() + si0, t.data() + ti0, std::min(sl, tl)) != 0) ++mismatch_count; } // ключевой момент: ИМЕННО ceil const double transpositions = std::ceil(mismatch_count / 2.0); const double m = (double)matches; return (m / s_len + m / t_len + (m - transpositions) / m) / 3.0; } /** * @brief Метрика Jaro–Winkler (0..1) с бустом префикса. * @details Буст: p=0.1, длина общего префикса l ∈ [0..4], формула: * JW = Jaro + l * p * (1 - Jaro). * @param s Первая строка. * @param t Вторая строка. * @return Значение 0..1. */ static double jaro_winkler_similarity(const std::string& s, const std::string& t) { const double j = jaro_similarity(s, t); // длина общего префикса до 4 int l = 0; const int limit = std::min({4, (int)s.size(), (int)t.size()}); while (l < limit && s[l] == t[l]) ++l; const double p = 0.1; // стандартный scaling return j + l * p * (1.0 - j); } // длина общего префикса (до 4 символов) static inline int common_prefix_len_le4(const std::string& s, const std::string& t) { int lim = std::min({4, (int)s.size(), (int)t.size()}); int l = 0; while (l < lim && s[l] == t[l]) ++l; return l; } // округление вверх (для EDIT_DISTANCE_SIMILARITY) static inline int clamp_ceil_0_100(double x) { int v = (int)std::ceil(x - 1e-12); if (v < 0) v = 0; if (v > 100) v = 100; return v; } // математическое округление .5 вверх (для JARO_WINKLER_SIMILARITY) static inline int clamp_round_half_up_0_100(double x) { int v = (int)std::floor(x + 0.5); if (v < 0) v = 0; if (v > 100) v = 100; return v; } // вариант для "floor" static inline int clamp_floor_0_100(double x) { int v = (int)std::floor(x); if (v < 0) v = 0; if (v > 100) v = 100; return v; } /** * @brief UTL_MATCH.EDIT_DISTANCE — расстояние Левенштейна. * Правила: * - если любой аргумент NULL или '' → вернуть -1; * - иначе классический Левенштейн. */ extern "C" Datum utl_match_edit_distance(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) { PG_RETURN_INT32(-1); } std::string s1 = to_std_string(PG_GETARG_TEXT_PP(0)); std::string s2 = to_std_string(PG_GETARG_TEXT_PP(1)); if (s1.empty() || s2.empty()) { PG_RETURN_INT32(-1); } const int d = DirectFunctionCall2Coll( utl_match_levenshtein, PG_GET_COLLATION(), CStringGetTextDatum(s1.c_str()), CStringGetTextDatum(s2.c_str())); PG_RETURN_INT32(d); } /** * @brief UTL_MATCH.EDIT_DISTANCE_SIMILARITY — нормированное сходство 0..100. * Нормализация по max(len). Спец-случаи: * - оба NULL → 100 * - один NULL (и другой не NULL) → 0 * - оба '' → 100 * - один '' и другой непустой → 0 */ extern "C" Datum utl_match_edit_distance_similarity(PG_FUNCTION_ARGS) { const bool null0 = PG_ARGISNULL(0); const bool null1 = PG_ARGISNULL(1); if (null0 && null1) { PG_RETURN_INT32(100); } if (null0 != null1) { PG_RETURN_INT32(0); } // Оба не NULL: переводим в строки и проверяем пустоту std::string s1 = to_std_string(PG_GETARG_TEXT_PP(0)); std::string s2 = to_std_string(PG_GETARG_TEXT_PP(1)); const bool empty0 = s1.empty(); const bool empty1 = s2.empty(); if (empty0 && empty1) { PG_RETURN_INT32(100); } if (empty0 != empty1) { PG_RETURN_INT32(0); } const int d = DirectFunctionCall2Coll( utl_match_levenshtein, PG_GET_COLLATION(), CStringGetTextDatum(s1.c_str()), CStringGetTextDatum(s2.c_str())); const int maxlen = (int)std::max(s1.size(), s2.size()); const double sim = 100.0 * std::max(0.0, 1.0 - ((double)d / (double)maxlen)); PG_RETURN_INT32(clamp_ceil_0_100(sim)); } /** * @brief UTL_MATCH.JARO_WINKLER — сходство Jaro–Winkler (0..1). * Спец-случаи: * - любые NULL → 0 * - любой из аргументов пустой (включая оба) → 0 * Плюс округление к стабильному виду. */ extern "C" Datum utl_match_jaro_winkler(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) { PG_RETURN_FLOAT8(0.0); } std::string s1 = to_std_string(PG_GETARG_TEXT_PP(0)); std::string s2 = to_std_string(PG_GETARG_TEXT_PP(1)); if (s1.empty() || s2.empty()) { PG_RETURN_FLOAT8(0.0); } double jw = jaro_winkler_similarity(s1, s2); if (jw < 0.0) jw = 0.0; if (jw > 1.0) jw = 1.0; jw = truncate_decimal_16(jw); PG_RETURN_FLOAT8(jw); } /** * @brief UTL_MATCH.JARO_WINKLER_SIMILARITY — 0..100 (int). * Спец-случаи: * - любые NULL → 0 * - любой пустой (включая оба) → 0 */ extern "C" Datum utl_match_jaro_winkler_similarity(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) PG_RETURN_INT32(0); std::string s1 = to_std_string(PG_GETARG_TEXT_PP(0)); std::string s2 = to_std_string(PG_GETARG_TEXT_PP(1)); if (s1.empty() || s2.empty()) PG_RETURN_INT32(0); double jw = jaro_winkler_similarity(s1, s2); if (jw < 0.0) jw = 0.0; if (jw > 1.0) jw = 1.0; // Oracle-совместимо: TRUNC(100*JW), с микро-эпсилоном от двоичных хвостов const int sim = (int)std::floor(jw * 100.0 + 1e-12); PG_RETURN_INT32(sim); } extern "C" Datum utl_match_levenshtein(PG_FUNCTION_ARGS) { const std::string a = to_std_string(PG_GETARG_TEXT_PP(0)); const std::string b = to_std_string(PG_GETARG_TEXT_PP(1)); const size_t n = a.size(), m = b.size(); if (n == 0) PG_RETURN_INT32((int)m); if (m == 0) PG_RETURN_INT32((int)n); std::vector prev(m + 1), curr(m + 1); for (size_t j = 0; j <= m; ++j) prev[j] = (int)j; for (size_t i = 1; i <= n; ++i) { curr[0] = (int)i; const unsigned char ai = (unsigned char)a[i - 1]; for (size_t j = 1; j <= m; ++j) { const unsigned char bj = (unsigned char)b[j - 1]; const int cost = (ai == bj) ? 0 : 1; curr[j] = std::min({ prev[j] + 1, // удаление curr[j - 1] + 1, // вставка prev[j - 1] + cost // замена }); } std::swap(prev, curr); } PG_RETURN_INT32(prev[m]); } /// @brief Возвращает версию RUDB пакета UTL_MATCH (Oracle UTL_MATCH пакет) extern "C" Datum utl_match_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_UTL_MATCH_VERSION)); }