Исходный код СУБД 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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
#include "dbms_ash.hpp"
#include "ash.hpp"
#include "awr.hpp"
 
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <cstdio>
#include <limits>
#include <optional>
#include <string>
#include <vector>
 
extern "C"
{
#include "executor/executor.h"
#include "access/htup_details.h"
#include "catalog/pg_class.h"
#include "catalog/pg_proc.h"
#include "common/md5.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/guc.h"
#include "utils/fmgrprotos.h"
#include "utils/lsyscache.h"
#include "utils/numeric.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
} // extern "C"
 
extern "C"
{
PG_FUNCTION_INFO_V1(dbms_ash_fetch_obj_name);
PG_FUNCTION_INFO_V1(dbms_ash_fetch_procedure_name);
PG_FUNCTION_INFO_V1(dbms_ash_sql_id);
PG_FUNCTION_INFO_V1(dbms_ash_fetch_sqltext);
PG_FUNCTION_INFO_V1(dbms_ash_fetch_user_name);
PG_FUNCTION_INFO_V1(dbms_ash_getadditionalinfo);
PG_FUNCTION_INFO_V1(dbms_ash_getawrinfo);
PG_FUNCTION_INFO_V1(dbms_ash_getcpuinfo);
PG_FUNCTION_INFO_V1(dbms_ash_getdata);
PG_FUNCTION_INFO_V1(dbms_ash_getdatahistorical);
PG_FUNCTION_INFO_V1(dbms_ash_getdatarealtime);
PG_FUNCTION_INFO_V1(dbms_ash_gethistogramhistorical);
PG_FUNCTION_INFO_V1(dbms_ash_gethistogramrealtime);
PG_FUNCTION_INFO_V1(dbms_ash_getsqltext);
PG_FUNCTION_INFO_V1(dbms_ash_gettimeformat);
PG_FUNCTION_INFO_V1(dbms_ash_gettimepickerhistorical);
PG_FUNCTION_INFO_V1(dbms_ash_gettimepickerrealtime);
PG_FUNCTION_INFO_V1(dbms_ash_getversion);
PG_FUNCTION_INFO_V1(dbms_ash_get_blocking_session_data);
PG_FUNCTION_INFO_V1(dbms_ash_incrementdata);
PG_FUNCTION_INFO_V1(dbms_ash_incrementhistogram);
PG_FUNCTION_INFO_V1(dbms_ash_incrementtimepicker);
PG_FUNCTION_INFO_V1(dbms_ash_str_to_ascii);
PG_FUNCTION_INFO_V1(dbms_ash_get_version);
} // extern "C"
 
#define RUDB_DBMS_ASH_VERSION "1.0.0"
 
namespace
{
struct ResolutionInfo
{
    const char* name;
    int bucket_count;
};
 
template <typename Entry, typename Accessor>
void
prune_oldest_entries(std::vector<Entry>& entries, std::size_t max_entries, Accessor accessor)
{
    if (entries.size() <= max_entries)
        return;
 
    std::sort(entries.begin(), entries.end(),
              [&](const Entry& left, const Entry& right)
              {
                  return accessor(left) < accessor(right);
              });
 
    entries.erase(entries.begin(), entries.begin() +
                  static_cast<typename std::vector<Entry>::difference_type>(entries.size() - max_entries));
}
 
std::string
trim_ascii_copy(const std::string& value)
{
    std::size_t begin = 0;
    std::size_t end = value.size();
 
    while (begin < end && std::isspace(static_cast<unsigned char>(value[begin])) != 0)
        ++begin;
 
    while (end > begin && std::isspace(static_cast<unsigned char>(value[end - 1])) != 0)
        --end;
 
    return value.substr(begin, end - begin);
}
 
std::optional<std::string>
text_arg_to_string(FunctionCallInfo fcinfo, int argno)
{
    if (PG_ARGISNULL(argno))
        return std::nullopt;
 
    char* value = text_to_cstring(PG_GETARG_TEXT_PP(argno));
    std::string result(value);
 
    pfree(value);
    return result;
}
 
std::optional<int64>
number_arg_to_int64(FunctionCallInfo fcinfo, int argno)
{
    if (PG_ARGISNULL(argno))
        return std::nullopt;
 
    Numeric value = PG_GETARG_NUMERIC(argno);
    return DatumGetInt64(DirectFunctionCall1(numeric_int8, NumericGetDatum(value)));
}
 
std::optional<Oid>
number_arg_to_oid(FunctionCallInfo fcinfo, int argno)
{
    const std::optional<int64> value = number_arg_to_int64(fcinfo, argno);
 
    if (!value.has_value())
        return std::nullopt;
 
    if (*value <= 0 || static_cast<uint64_t>(*value) > std::numeric_limits<Oid>::max())
        return std::nullopt;
 
    return static_cast<Oid>(*value);
}
 
std::optional<bool>
parse_yes_no_flag_strict(const std::optional<std::string>& value)
{
    if (!value.has_value())
        return std::nullopt;
 
    const std::string trimmed = trim_ascii_copy(*value);
 
    if (trimmed.empty())
        return std::nullopt;
 
    if (pg_strcasecmp(trimmed.c_str(), "Y") == 0)
        return true;
 
    if (pg_strcasecmp(trimmed.c_str(), "N") == 0)
        return false;
 
    return std::nullopt;
}
 
bool
parse_yes_no_flag_default(const std::optional<std::string>& value, bool default_value)
{
    const std::optional<bool> parsed = parse_yes_no_flag_strict(value);
    return parsed.has_value() ? *parsed : default_value;
}
 
ResolutionInfo
normalize_resolution(const std::optional<std::string>& value)
{
    if (!value.has_value())
        return {"MEDIUM", 180};
 
    const std::string trimmed = trim_ascii_copy(*value);
 
    if (pg_strcasecmp(trimmed.c_str(), "LOW") == 0)
        return {"LOW", 120};
 
    if (pg_strcasecmp(trimmed.c_str(), "HIGH") == 0)
        return {"HIGH", 360};
 
    return {"MEDIUM", 180};
}
 
std::string
xml_escape_impl(const std::string& value)
{
    std::string result;
    result.reserve(value.size());
 
    for (const char ch : value)
    {
        switch (ch)
        {
            case '&':
                result += "&amp;";
                break;
            case '<':
                result += "&lt;";
                break;
            case '>':
                result += "&gt;";
                break;
            case '"':
                result += "&quot;";
                break;
            case '\'':
                result += "&apos;";
                break;
            default:
                result.push_back(ch);
                break;
        }
    }
 
    return result;
}
 
std::string
dbms_ash_xml_escape_internal(const std::string& value)
{
    return xml_escape_impl(value);
}
 
std::optional<std::string>
build_obj_name_xml(const std::string& qualified_name, const std::string& object_type)
{
    return "<a><n>" + dbms_ash_xml_escape_internal(qualified_name) + "</n><t>" +
           dbms_ash_xml_escape_internal(object_type) + "</t></a>";
}
 
std::optional<std::string>
lookup_local_relation_xml(Oid relation_oid)
{
    HeapTuple rel_tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relation_oid));
 
    if (!HeapTupleIsValid(rel_tuple))
        return std::nullopt;
 
    Form_pg_class rel_form = (Form_pg_class) GETSTRUCT(rel_tuple);
    std::optional<std::string> result = std::nullopt;
    const char* type_name = nullptr;
 
    switch (rel_form->relkind)
    {
        case RELKIND_RELATION:
            type_name = "TABLE";
            break;
        case RELKIND_INDEX:
            type_name = "INDEX";
            break;
        case RELKIND_SEQUENCE:
            type_name = "SEQUENCE";
            break;
        case RELKIND_VIEW:
            type_name = "VIEW";
            break;
        case RELKIND_MATVIEW:
            type_name = "MATERIALIZED VIEW";
            break;
        case RELKIND_FOREIGN_TABLE:
            type_name = "FOREIGN TABLE";
            break;
        default:
            break;
    }
 
    if (type_name != nullptr)
    {
        char* schema_name = get_namespace_name(rel_form->relnamespace);
 
        if (schema_name != nullptr)
        {
            result = build_obj_name_xml(std::string(schema_name) + "." +
                                            NameStr(rel_form->relname),
                                        type_name);
            pfree(schema_name);
        }
    }
 
    ReleaseSysCache(rel_tuple);
    return result;
}
 
std::optional<std::string>
lookup_standalone_routine_name(Oid procedure_oid, int64 subprogram_id)
{
    if (subprogram_id != 1)
        return std::nullopt;
 
    HeapTuple proc_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(procedure_oid));
 
    if (!HeapTupleIsValid(proc_tuple))
        return std::nullopt;
 
    Form_pg_proc proc_form = (Form_pg_proc) GETSTRUCT(proc_tuple);
    std::optional<std::string> result = std::nullopt;
 
    if (proc_form->prokind == PROKIND_FUNCTION || proc_form->prokind == PROKIND_PROCEDURE)
    {
        char* schema_name = get_namespace_name(proc_form->pronamespace);
 
        if (schema_name != nullptr)
        {
            result = std::string(schema_name) + "." + NameStr(proc_form->proname) + ".";
            pfree(schema_name);
        }
    }
 
    ReleaseSysCache(proc_tuple);
    return result;
}
 
std::optional<std::string>
lookup_user_name(Oid role_oid)
{
    if (!SearchSysCacheExists1(AUTHOID, ObjectIdGetDatum(role_oid)))
        return std::nullopt;
 
    char* role_name = GetUserNameFromId(role_oid, true);
 
    if (role_name == nullptr)
        return std::nullopt;
 
    std::string result(role_name);
    pfree(role_name);
 
    return result;
}
 
int64
normalize_time_since_sec(const std::optional<int64>& time_since_sec)
{
    if (!time_since_sec.has_value() || *time_since_sec <= 0)
        return 86400;
 
    return *time_since_sec;
}
 
[[noreturn]] void
raise_not_supported(const char* function_name)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("DBMS_ASH.%s is not supported", function_name)));
    pg_unreachable();
}
 
} // namespace
 
extern "C" void
dbms_ash_init(void)
{
    rudb_awr_init();
}
 
Datum
dbms_ash_fetch_obj_name(PG_FUNCTION_ARGS)
{
    const std::optional<Oid> object_oid = number_arg_to_oid(fcinfo, 0);
    const std::optional<bool> is_local = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 3));
    const std::optional<bool> is_old = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 5));
 
    if (!object_oid.has_value() || !is_local.has_value() || !is_old.has_value())
        PG_RETURN_NULL();
 
    if (*is_local)
    {
        const std::optional<std::string> result = lookup_local_relation_xml(*object_oid);
 
        if (!result.has_value())
            PG_RETURN_NULL();
 
        PG_RETURN_TEXT_P(cstring_to_text(result->c_str()));
    }
 
    PG_RETURN_NULL();
}
 
Datum
dbms_ash_fetch_procedure_name(PG_FUNCTION_ARGS)
{
    const std::optional<Oid> procedure_oid = number_arg_to_oid(fcinfo, 0);
    const std::optional<int64> subprogram_id = number_arg_to_int64(fcinfo, 1);
 
    if (!procedure_oid.has_value() || !subprogram_id.has_value())
        PG_RETURN_NULL();
 
    const std::optional<std::string> result =
        lookup_standalone_routine_name(*procedure_oid, *subprogram_id);
 
    if (!result.has_value())
        PG_RETURN_NULL();
 
    PG_RETURN_TEXT_P(cstring_to_text(result->c_str()));
}
 
Datum
dbms_ash_sql_id(PG_FUNCTION_ARGS)
{
    const std::optional<std::string> sql_text = text_arg_to_string(fcinfo, 0);
 
    if (!sql_text.has_value())
        PG_RETURN_NULL();
 
    const std::string normalized_sql = trim_ascii_copy(*sql_text);
 
    if (normalized_sql.empty())
        PG_RETURN_NULL();
 
    const std::string sql_id = rudb::ash::compute_sql_id(normalized_sql);
    PG_RETURN_TEXT_P(cstring_to_text(sql_id.c_str()));
}
 
Datum
dbms_ash_fetch_sqltext(PG_FUNCTION_ARGS)
{
    const std::optional<std::string> sql_id = text_arg_to_string(fcinfo, 0);
    const std::optional<bool> is_local = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 3));
    const std::optional<bool> is_pdb = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 4));
    const std::optional<bool> is_old = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 5));
 
    if (!sql_id.has_value() || sql_id->empty())
        PG_RETURN_NULL();
 
    if (!is_local.has_value() || !is_pdb.has_value() || !is_old.has_value())
        PG_RETURN_NULL();
 
    const std::optional<std::string> xml =
        rudb::ash::lookup_sql_text(*sql_id, *is_local, !*is_local && *is_old);
 
    if (!xml.has_value())
        PG_RETURN_NULL();
 
    PG_RETURN_TEXT_P(cstring_to_text(xml->c_str()));
}
 
Datum
dbms_ash_fetch_user_name(PG_FUNCTION_ARGS)
{
    const std::optional<Oid> role_oid = number_arg_to_oid(fcinfo, 0);
    const std::optional<int64> con_dbid = number_arg_to_int64(fcinfo, 1);
 
    if (!role_oid.has_value() || (con_dbid.has_value() && *con_dbid < 0))
        PG_RETURN_NULL();
 
    const std::optional<std::string> result = lookup_user_name(*role_oid);
 
    if (!result.has_value())
        PG_RETURN_NULL();
 
    PG_RETURN_TEXT_P(cstring_to_text(result->c_str()));
}
 
Datum
dbms_ash_getadditionalinfo(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETADDITIONALINFO");
}
 
Datum
dbms_ash_getawrinfo(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETAWRINFO");
}
 
Datum
dbms_ash_getcpuinfo(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETCPUINFO");
}
 
Datum
dbms_ash_getdata(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETDATA");
}
 
Datum
dbms_ash_getdatahistorical(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETDATAHISTORICAL");
}
 
Datum
dbms_ash_getdatarealtime(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETDATAREALTIME");
}
 
Datum
dbms_ash_gethistogramhistorical(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETHISTOGRAMHISTORICAL");
}
 
Datum
dbms_ash_gethistogramrealtime(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETHISTOGRAMREALTIME");
}
 
Datum
dbms_ash_getsqltext(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETSQLTEXT");
}
 
Datum
dbms_ash_gettimeformat(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETTIMEFORMAT");
}
 
Datum
dbms_ash_gettimepickerhistorical(PG_FUNCTION_ARGS)
{
    rudb::ash::TimepickerRequest request;
    request.begin_time_utc = text_arg_to_string(fcinfo, 1);
    request.end_time_utc = text_arg_to_string(fcinfo, 2);
    request.time_since_sec = normalize_time_since_sec(number_arg_to_int64(fcinfo, 3));
    request.show_sql = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 4), false);
    request.verbose_xml = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 5), false);
    request.instance_number = number_arg_to_int64(fcinfo, 6);
    request.awr_info = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 7), false);
    request.ignore_cpu_history = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 8), false);
    request.resolution = normalize_resolution(text_arg_to_string(fcinfo, 9)).name;
    request.include_bg = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 10), false);
    request.memory_only = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 11), false);
 
    std::string xml = rudb::ash::build_timepicker_core_xml(request);
 
    if (request.awr_info)
    {
        rudb::awr::TimepickerMetadataRequest awr_request;
        awr_request.include_metadata = true;
        awr_request.dbid = rudb::awr::local_dbid();
        awr_request.retention_seconds = rudb::ash::retention_seconds();
 
        const std::string awr_xml = rudb::awr::build_timepicker_metadata_xml(awr_request);
        const std::size_t insert_pos = xml.find("<cpuinfo");
 
        if (insert_pos != std::string::npos)
            xml.insert(insert_pos, awr_xml);
    }
 
    PG_RETURN_TEXT_P(cstring_to_text(xml.c_str()));
}
 
Datum
dbms_ash_gettimepickerrealtime(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETTIMEPICKERREALTIME");
}
 
Datum
dbms_ash_getversion(PG_FUNCTION_ARGS)
{
    raise_not_supported("GETVERSION");
}
 
Datum
dbms_ash_get_blocking_session_data(PG_FUNCTION_ARGS)
{
    raise_not_supported("GET_BLOCKING_SESSION_DATA");
}
 
Datum
dbms_ash_incrementdata(PG_FUNCTION_ARGS)
{
    raise_not_supported("INCREMENTDATA");
}
 
Datum
dbms_ash_incrementhistogram(PG_FUNCTION_ARGS)
{
    raise_not_supported("INCREMENTHISTOGRAM");
}
 
Datum
dbms_ash_incrementtimepicker(PG_FUNCTION_ARGS)
{
    raise_not_supported("INCREMENTTIMEPICKER");
}
 
Datum
dbms_ash_str_to_ascii(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        PG_RETURN_NULL();
 
    const text* input_text = PG_GETARG_TEXT_PP(0);
    char* input_cstr = text_to_cstring(input_text);
    const int input_len = std::strlen(input_cstr);
 
    if (input_len == 0)
    {
        pfree(input_cstr);
        PG_RETURN_NULL();
    }
 
    char* utf8_input = pg_server_to_any(input_cstr, input_len, PG_UTF8);
    std::string result;
 
    for (const unsigned char* ptr = reinterpret_cast<unsigned char*>(utf8_input);
         *ptr != '\0';)
    {
        const int char_len = pg_utf_mblen(ptr);
        const pg_wchar codepoint = utf8_to_unicode(ptr);
 
        if (codepoint >= 0x20 && codepoint <= 0x7E)
        {
            result.push_back(static_cast<char>(codepoint));
        }
        else
        {
            char buffer[16];
            std::snprintf(buffer, sizeof(buffer), "\\%04X",
                          static_cast<unsigned int>(codepoint));
            result += buffer;
        }
 
        ptr += char_len;
    }
 
    if (utf8_input != input_cstr)
        pfree(utf8_input);
 
    pfree(input_cstr);
    PG_RETURN_TEXT_P(cstring_to_text(result.c_str()));
}
 
Datum
dbms_ash_get_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_ASH_VERSION));
}