Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#include "utils/dbms_warning.h"
#include "dbms_warning.hpp"
#include "dbms_warning_errors.hpp"
 
extern "C"
{
PG_FUNCTION_INFO_V1(dbms_warning_add_warning_setting_cat);
PG_FUNCTION_INFO_V1(dbms_warning_add_warning_setting_num);
PG_FUNCTION_INFO_V1(dbms_warning_get_category);
PG_FUNCTION_INFO_V1(dbms_warning_get_warning_setting_cat);
PG_FUNCTION_INFO_V1(dbms_warning_get_warning_setting_num);
PG_FUNCTION_INFO_V1(dbms_warning_get_warning_setting_string);
PG_FUNCTION_INFO_V1(dbms_warning_normalize_setting);
PG_FUNCTION_INFO_V1(dbms_warning_set_warning_setting_string);
PG_FUNCTION_INFO_V1(dbms_warning_get_version);
 
/// @brief Версия RUDB пакета DBMS_WARNING (Oracle DBMS_WARNING пакет)
#define RUDB_DBMS_WARNING_VERSION "1.0.0"
} // extern "C"
 
#include <cctype>
#include <limits>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
 
extern "C"
{
#include "utils/builtins.h"
}
 
namespace
{
/*
 * Локальная модель состояния предупреждений для пакета DBMS_WARNING.
 *
 * Здесь храним только ordered clauses текущей строки PLSQL_WARNINGS.
 * Публичные точки входа остаются частью поверхности пакета, а хук
 * компилятора читает только сессионное строковое состояние.
 */
enum class WarningAction
{
    Enable,
    Disable,
    Error
};
 
enum class WarningSelectorKind
{
    All,
    Category,
    Number,
    NumberList
};
 
struct WarningClause
{
    WarningAction action;
    WarningSelectorKind selector_kind;
    std::string selector_canonical;
};
 
struct WarningState
{
    std::vector<WarningClause> clauses;
};
 
// Проверяет, является ли символ пробелом.
inline bool is_space(const unsigned char ch)
{
    return std::isspace(static_cast<int>(ch)) != 0;
}
 
// Убирает пробелы по краям строки без копирования.
inline std::string_view trim_view(const std::string_view input)
{
    size_t begin = 0;
    size_t end = input.size();
 
    while (begin < end && is_space(static_cast<unsigned char>(input[begin])))
        ++begin;
 
    while (end > begin && is_space(static_cast<unsigned char>(input[end - 1])))
        --end;
 
    return input.substr(begin, end - begin);
}
 
// Возвращает копию строки в нижнем регистре.
inline std::string lower_copy(const std::string_view input)
{
    std::string output;
    output.reserve(input.size());
 
    for (const char ch : input)
        output.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(ch))));
 
    return output;
}
 
// Сравнивает строки без учета регистра и внешних пробелов.
inline bool iequals(const std::string_view lhs, const std::string_view rhs)
{
    return lower_copy(trim_view(lhs)) == lower_copy(trim_view(rhs));
}
 
// Проверяет токен действия на одно из допустимых значений.
inline bool is_action_token(const std::string_view token, const WarningAction action)
{
    switch (action)
    {
        case WarningAction::Enable:
            return iequals(token, "ENABLE");
        case WarningAction::Disable:
            return iequals(token, "DISABLE");
        case WarningAction::Error:
            return iequals(token, "ERROR");
    }
 
    return false;
}
 
// Возвращает имя действия.
inline const char* action_name(const WarningAction action)
{
    switch (action)
    {
        case WarningAction::Enable:
            return "ENABLE";
        case WarningAction::Disable:
            return "DISABLE";
        case WarningAction::Error:
            return "ERROR";
    }
 
    return "DISABLE";
}
 
// Проверяет, что токен содержит положительное десятичное число.
inline bool parse_positive_integer(const std::string_view token, int& value)
{
    const std::string_view trimmed = trim_view(token);
 
    if (trimmed.empty())
        return false;
 
    long long parsed = 0;
 
    for (const char ch : trimmed)
    {
        if (!std::isdigit(static_cast<unsigned char>(ch)))
            return false;
 
        parsed = parsed * 10 + (ch - '0');
        if (parsed > std::numeric_limits<int>::max())
            return false;
    }
 
    if (parsed <= 0)
        return false;
 
    value = static_cast<int>(parsed);
    return true;
}
 
// Формирует канонический десятичный текст числа без ведущих нулей.
inline std::string format_positive_integer(const int value)
{
    return std::to_string(value);
}
 
// Собирает канонический вид числового списка.
inline std::string format_numeric_list(const std::vector<int>& values)
{
    std::string output = "(";
 
    for (size_t index = 0; index < values.size(); ++index)
    {
        if (index > 0)
            output.push_back(',');
 
        output += format_positive_integer(values[index]);
    }
 
    output.push_back(')');
    return output;
}
 
// Парсит селектор предупреждения и заполняет его канонический вид.
inline bool parse_warning_selector(const std::string_view selector_token,
                                  WarningClause& clause)
{
    if (iequals(selector_token, "ALL"))
    {
        clause.selector_kind = WarningSelectorKind::All;
        clause.selector_canonical = "ALL";
        return true;
    }
 
    if (iequals(selector_token, "SEVERE"))
    {
        clause.selector_kind = WarningSelectorKind::Category;
        clause.selector_canonical = "SEVERE";
        return true;
    }
 
    if (iequals(selector_token, "INFORMATIONAL"))
    {
        clause.selector_kind = WarningSelectorKind::Category;
        clause.selector_canonical = "INFORMATIONAL";
        return true;
    }
 
    if (iequals(selector_token, "PERFORMANCE"))
    {
        clause.selector_kind = WarningSelectorKind::Category;
        clause.selector_canonical = "PERFORMANCE";
        return true;
    }
 
    if (!selector_token.empty() && selector_token.front() == '(' && selector_token.back() == ')')
    {
        const std::string_view body = trim_view(selector_token.substr(1, selector_token.size() - 2));
 
        if (body.empty())
            return false;
 
        std::vector<int> numbers;
        size_t item_begin = 0;
 
        for (size_t pos = 0; pos <= body.size(); ++pos)
        {
            const bool at_end = (pos == body.size());
 
            if (!at_end && body[pos] != ',')
                continue;
 
            const std::string_view item = trim_view(body.substr(item_begin, pos - item_begin));
            int parsed_number = 0;
 
            if (!parse_positive_integer(item, parsed_number))
                return false;
 
            numbers.push_back(parsed_number);
            item_begin = pos + 1;
        }
 
        if (numbers.empty())
            return false;
 
        clause.selector_kind = WarningSelectorKind::NumberList;
        clause.selector_canonical = format_numeric_list(numbers);
        return true;
    }
 
    int parsed_number = 0;
    if (!parse_positive_integer(selector_token, parsed_number))
        return false;
 
    clause.selector_kind = WarningSelectorKind::Number;
    clause.selector_canonical = format_positive_integer(parsed_number);
    return true;
}
 
// Формирует каноническую строку для одного клауза.
inline std::string format_warning_clause(const WarningClause& clause)
{
    return std::string(action_name(clause.action)) + ':' + clause.selector_canonical;
}
 
// Проверяет, есть ли в строке хотя бы один ALL-клауз.
constexpr int kCompilerShadowWarningNumber = 6002;
constexpr const char* kCompilerShadowWarningCategory = "INFORMATIONAL";
 
// Проверяет, что селектор затрагивает warning компилятора PL/pgSQL.
inline bool warning_selector_matches_compiler_warning(const WarningClause& clause)
{
    switch (clause.selector_kind)
    {
        case WarningSelectorKind::All:
            return true;
        case WarningSelectorKind::Category:
            return clause.selector_canonical == kCompilerShadowWarningCategory;
        case WarningSelectorKind::Number:
            return clause.selector_canonical == std::to_string(kCompilerShadowWarningNumber);
        case WarningSelectorKind::NumberList:
        {
            const std::string needle = std::to_string(kCompilerShadowWarningNumber);
            const std::string_view list = clause.selector_canonical;
            size_t pos = list.find(needle);
 
            while (pos != std::string::npos)
            {
                const bool left_boundary = (pos == 1) || list[pos - 1] == '(' || list[pos - 1] == ',';
                const size_t right_pos = pos + needle.size();
                const bool right_boundary =
                    (right_pos + 1 == list.size() && list[right_pos] == ')') ||
                    (right_pos < list.size() && list[right_pos] == ',');
 
                if (left_boundary && right_boundary)
                    return true;
 
                pos = list.find(needle, pos + 1);
            }
 
            return false;
        }
    }
 
    return false;
}
 
// Возвращает режим компилятора для shadow-variable warning.
inline WarningAction warning_state_compiler_action(const WarningState& state, bool& is_explicit)
{
    WarningAction action = WarningAction::Disable;
    is_explicit = false;
 
    for (const WarningClause& clause : state.clauses)
    {
        if (!warning_selector_matches_compiler_warning(clause))
            continue;
 
        is_explicit = true;
        action = clause.action;
    }
 
    return action;
}
 
// Парсит строковое значение настройки предупреждений в локальное состояние.
inline bool parse_warning_setting_string(const std::string_view input,
                                        WarningState& state)
{
    const std::string_view normalized = trim_view(input);
 
    if (normalized.empty())
        return false;
 
    WarningState parsed_state;
    size_t clause_begin = 0;
    int parentheses_depth = 0;
 
    for (size_t pos = 0; pos < normalized.size(); ++pos)
    {
        const char ch = normalized[pos];
 
        if (ch == '(')
        {
            ++parentheses_depth;
            continue;
        }
 
        if (ch == ')')
        {
            if (parentheses_depth == 0)
                return false;
 
            --parentheses_depth;
            continue;
        }
 
        if (ch != ',' || parentheses_depth != 0)
            continue;
 
        const std::string_view clause_token = trim_view(normalized.substr(clause_begin, pos - clause_begin));
 
        if (clause_token.empty())
            return false;
 
        const size_t colon_pos = clause_token.find(':');
        if (colon_pos == std::string_view::npos)
            return false;
 
        if (clause_token.find(':', colon_pos + 1) != std::string_view::npos)
            return false;
 
        const std::string_view action_token = trim_view(clause_token.substr(0, colon_pos));
        const std::string_view selector_token = trim_view(clause_token.substr(colon_pos + 1));
 
        if (action_token.empty() || selector_token.empty())
            return false;
 
        WarningClause clause;
        if (is_action_token(action_token, WarningAction::Enable))
            clause.action = WarningAction::Enable;
        else if (is_action_token(action_token, WarningAction::Disable))
            clause.action = WarningAction::Disable;
        else if (is_action_token(action_token, WarningAction::Error))
            clause.action = WarningAction::Error;
        else
            return false;
 
        if (!parse_warning_selector(selector_token, clause))
            return false;
 
        parsed_state.clauses.push_back(std::move(clause));
        clause_begin = pos + 1;
    }
 
    if (parentheses_depth != 0)
        return false;
 
    const std::string_view clause_token = trim_view(normalized.substr(clause_begin));
 
    if (clause_token.empty())
        return false;
 
    const size_t colon_pos = clause_token.find(':');
    if (colon_pos == std::string_view::npos)
        return false;
 
    if (clause_token.find(':', colon_pos + 1) != std::string_view::npos)
        return false;
 
    const std::string_view action_token = trim_view(clause_token.substr(0, colon_pos));
    const std::string_view selector_token = trim_view(clause_token.substr(colon_pos + 1));
 
    if (action_token.empty() || selector_token.empty())
        return false;
 
    WarningClause clause;
    if (is_action_token(action_token, WarningAction::Enable))
        clause.action = WarningAction::Enable;
    else if (is_action_token(action_token, WarningAction::Disable))
        clause.action = WarningAction::Disable;
    else if (is_action_token(action_token, WarningAction::Error))
        clause.action = WarningAction::Error;
    else
        return false;
 
    if (!parse_warning_selector(selector_token, clause))
        return false;
 
    parsed_state.clauses.push_back(std::move(clause));
    state = std::move(parsed_state);
    return true;
}
 
// Формирует каноническое строковое представление текущего состояния.
inline std::string format_warning_setting_string(const WarningState& state)
{
    if (state.clauses.empty())
        return "DISABLE:ALL";
 
    std::string output;
 
    for (size_t index = 0; index < state.clauses.size(); ++index)
    {
        if (index > 0)
            output.push_back(',');
 
        output += format_warning_clause(state.clauses[index]);
    }
 
    return output;
}
 
inline std::string normalize_warning_setting(const std::string_view input)
{
    WarningState parsed_state;
    if (!parse_warning_setting_string(input, parsed_state))
        dbms_warning_errors::raise_ora_39950();
 
    return format_warning_setting_string(parsed_state);
}
 
// Сессионный источник истины для PLSQL_WARNINGS.
static WarningState s_warning_setting_state = WarningState{};
} // namespace
 
/*
 * Строковая реализация DBMS_WARNING.
 *
 * Здесь держим сессионный источник истины для PLSQL_WARNINGS и
 * предоставляем helper для хука компилятора.
 */
 
extern "C"
{
// Добавляет настройку предупреждений в сессионное состояние.
Datum dbms_warning_add_warning_setting_cat(PG_FUNCTION_ARGS)
{
    PG_RETURN_VOID();
}
 
// Добавляет настройку предупреждений по числу.
Datum dbms_warning_add_warning_setting_num(PG_FUNCTION_ARGS)
{
    PG_RETURN_VOID();
}
 
// Возвращает категорию предупреждения.
Datum dbms_warning_get_category(PG_FUNCTION_ARGS)
{
    PG_RETURN_NULL();
}
 
// Возвращает настройку предупреждений по категории.
Datum dbms_warning_get_warning_setting_cat(PG_FUNCTION_ARGS)
{
    PG_RETURN_NULL();
}
 
// Возвращает настройку предупреждений по числу.
Datum dbms_warning_get_warning_setting_num(PG_FUNCTION_ARGS)
{
    PG_RETURN_NULL();
}
 
// Возвращает текущее сессионное строковое значение PLSQL_WARNINGS.
Datum dbms_warning_get_warning_setting_string(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(format_warning_setting_string(s_warning_setting_state).c_str()));
}
 
Datum dbms_warning_normalize_setting(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        PG_RETURN_NULL();
 
    const std::string value = text_to_cstring(PG_GETARG_TEXT_PP(0));
    PG_RETURN_TEXT_P(cstring_to_text(normalize_warning_setting(value).c_str()));
}
 
// Записывает текущее сессионное строковое значение PLSQL_WARNINGS.
Datum dbms_warning_set_warning_setting_string(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        dbms_warning_errors::raise_ora_01405();
 
    if (PG_ARGISNULL(1))
        dbms_warning_errors::raise_ora_01405();
 
    const std::string value = text_to_cstring(PG_GETARG_TEXT_PP(0));
    const std::string scope = text_to_cstring(PG_GETARG_TEXT_PP(1));
 
    if (iequals(scope, "SYSTEM"))
        dbms_warning_errors::raise_ora_01031();
 
    if (!iequals(scope, "SESSION"))
        dbms_warning_errors::raise_ora_39960();
 
    WarningState parsed_state = s_warning_setting_state;
    const Datum normalized_datum =
        DirectFunctionCall1(dbms_warning_normalize_setting,
                            PG_GETARG_DATUM(0));
    const std::string normalized =
        text_to_cstring(DatumGetTextPP(normalized_datum));
    parse_warning_setting_string(normalized, parsed_state);
    s_warning_setting_state = std::move(parsed_state);
    PG_RETURN_VOID();
}
 
DBMSWarningCompilerMode dbms_warning_get_compiler_warning_mode(bool* is_explicit)
{
    bool local_is_explicit = false;
    const WarningAction action = warning_state_compiler_action(s_warning_setting_state, local_is_explicit);
 
    if (is_explicit != nullptr)
        *is_explicit = local_is_explicit;
 
    switch (action)
    {
        case WarningAction::Enable:
            return DBMS_WARNING_COMPILER_MODE_ENABLE;
        case WarningAction::Disable:
            return DBMS_WARNING_COMPILER_MODE_DISABLE;
        case WarningAction::Error:
            return DBMS_WARNING_COMPILER_MODE_ERROR;
    }
 
    return DBMS_WARNING_COMPILER_MODE_DISABLE;
}
 
Datum dbms_warning_get_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_WARNING_VERSION));
}
} // extern "C"