Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#include "utl_match.hpp"
 
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring>
 
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 <cmath>
#include <cstring>
#include <cstdlib>
 
// Точная десятичная отсечка до 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<std::pair<size_t,size_t>>
collect_matched_codepoints(const std::string& s, const std::vector<bool>& matchFlags)
{
    std::vector<std::pair<size_t,size_t>> spans;
    const unsigned char* p = reinterpret_cast<const unsigned char*>(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<bool> 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<int>({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<int>({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<int> 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));
}