Исходный код СУБД 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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
#include "dbms_trace.hpp"
 
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <limits>
#include <string>
#include <utility>
 
extern "C"
{
#include "access/htup_details.h"
#include "catalog/pg_type_d.h"
#include "funcapi.h"
#include "plpgsql.h"
#include "utils/builtins.h"
#include "utils/tuplestore.h"
}
 
namespace
{
constexpr int32 kTracePause = 4096;
constexpr int32 kTraceResume = 8192;
constexpr int32 kTraceStop = 16384;
 
constexpr int32 kControlMask = kTracePause | kTraceResume | kTraceStop;
 
PLpgSQL_plugin g_dbms_trace_plpgsql_plugin;
bool g_dbms_trace_plpgsql_plugin_installed = false;
 
const char* trace_event_type_label(const char* event_type);
 
bool is_trace_enabled(const DbmsTraceSessionState& state)
{
    return state.enabled;
}
 
/* Сравнивает имя SQL-атрибута без учёта регистра. */
bool
dbms_trace_attr_name_is(Form_pg_attribute attr, const char* expected)
{
    return pg_strcasecmp(NameStr(attr->attname), expected) == 0;
}
 
/* Выдаёт ошибку о неподдерживаемой выходной колонке DBMS_TRACE. */
void
dbms_trace_unsupported_column_error(const char* function_name, const char* colname)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("unsupported DBMS_TRACE %s output column \"%s\"",
                    function_name,
                    colname)));
}
 
/* Выдаёт ошибку о неподдерживаемом типе выходной колонки DBMS_TRACE. */
void
dbms_trace_unsupported_type_error(const char* function_name, const char* colname, Oid typid)
{
    ereport(ERROR,
            (errcode(ERRCODE_DATATYPE_MISMATCH),
             errmsg("unsupported type %s for DBMS_TRACE %s output column \"%s\"",
                    format_type_be(typid),
                    function_name,
                    colname)));
}
 
/* Проверяет, что int64 помещается в int32 для SQL-колонки. */
int32
dbms_trace_checked_int64_to_int32(int64 value, const char* function_name, const char* colname)
{
    if (value < std::numeric_limits<int32>::min() ||
        value > std::numeric_limits<int32>::max())
    {
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("value out of range for DBMS_TRACE %s output column \"%s\"",
                        function_name,
                        colname)));
    }
 
    return static_cast<int32>(value);
}
 
/* Формирует текстовый Datum для согласованной SQL-колонки. */
Datum
dbms_trace_text_datum_or_null(const char* value, Oid typid, bool* isnull, const char* function_name, const char* colname)
{
    if (value == nullptr || value[0] == '\0')
    {
        *isnull = true;
        return static_cast<Datum>(0);
    }
 
    if (typid != TEXTOID)
        dbms_trace_unsupported_type_error(function_name, colname, typid);
 
    *isnull = false;
    return CStringGetTextDatum(value);
}
 
/* Формирует текстовый Datum из std::string для согласованной SQL-колонки. */
Datum
dbms_trace_text_datum_or_null(const std::string& value,
                              Oid typid,
                              bool* isnull,
                              const char* function_name,
                              const char* colname)
{
    return dbms_trace_text_datum_or_null(value.empty() ? nullptr : value.c_str(),
                                         typid,
                                         isnull,
                                         function_name,
                                         colname);
}
 
/* Формирует целочисленный Datum для int32 SQL-колонки. */
Datum
dbms_trace_int32_datum(int32 value, Oid typid, const char* function_name, const char* colname)
{
    if (typid != INT4OID)
        dbms_trace_unsupported_type_error(function_name, colname, typid);
 
    return Int32GetDatum(value);
}
 
/* Формирует целочисленный Datum для int64/int32 SQL-колонки. */
Datum
dbms_trace_int64_datum(int64 value, Oid typid, const char* function_name, const char* colname)
{
    if (typid == INT8OID)
        return Int64GetDatum(value);
    if (typid == INT4OID)
        return Int32GetDatum(dbms_trace_checked_int64_to_int32(value, function_name, colname));
 
    dbms_trace_unsupported_type_error(function_name, colname, typid);
    return static_cast<Datum>(0);
}
 
/* Формирует timestamptz Datum для SQL-колонки времени. */
Datum
dbms_trace_timestamptz_datum(TimestampTz value, Oid typid, const char* function_name, const char* colname)
{
    if (typid != TIMESTAMPTZOID)
        dbms_trace_unsupported_type_error(function_name, colname, typid);
 
    return TimestampTzGetDatum(value);
}
 
/* Формирует bool Datum для булевой SQL-колонки. */
Datum
dbms_trace_bool_datum(bool value, Oid typid, const char* function_name, const char* colname)
{
    if (typid != BOOLOID)
        dbms_trace_unsupported_type_error(function_name, colname, typid);
 
    return BoolGetDatum(value);
}
 
/* Проверяет, завершён ли run. */
bool
dbms_trace_run_is_closed(const DbmsTraceRun& run)
{
    return !run.is_active && run.ended_at != 0;
}
 
/* Заполняет одну строку SQL-результата trace runs по фактическому descriptor. */
void
dbms_trace_fill_run_row(const DbmsTraceRun& run, TupleDesc tupdesc, Datum* values, bool* nulls)
{
    const char* function_name = "run";
 
    for (int attno = 0; attno < tupdesc->natts; ++attno)
    {
        Form_pg_attribute attr = TupleDescAttr(tupdesc, attno);
        const char* colname = NameStr(attr->attname);
        const Oid typid = attr->atttypid;
 
        nulls[attno] = true;
        values[attno] = static_cast<Datum>(0);
 
        if (attr->attisdropped)
            continue;
 
        if (dbms_trace_attr_name_is(attr, "run_id"))
        {
            values[attno] = dbms_trace_int64_datum(run.run_id, typid, function_name, colname);
            nulls[attno] = false;
        }
        else if (dbms_trace_attr_name_is(attr, "trace_mask") ||
                 dbms_trace_attr_name_is(attr, "trace_level"))
        {
            values[attno] = dbms_trace_int32_datum(run.trace_mask, typid, function_name, colname);
            nulls[attno] = false;
        }
        else if (dbms_trace_attr_name_is(attr, "started_at"))
        {
            values[attno] = dbms_trace_timestamptz_datum(run.started_at, typid, function_name, colname);
            nulls[attno] = false;
        }
        else if (dbms_trace_attr_name_is(attr, "ended_at"))
        {
            if (dbms_trace_run_is_closed(run))
            {
                values[attno] = dbms_trace_timestamptz_datum(run.ended_at, typid, function_name, colname);
                nulls[attno] = false;
            }
        }
        else if (dbms_trace_attr_name_is(attr, "event_count"))
        {
            values[attno] = dbms_trace_int32_datum(run.event_count, typid, function_name, colname);
            nulls[attno] = false;
        }
        else if (dbms_trace_attr_name_is(attr, "is_active"))
        {
            values[attno] = dbms_trace_bool_datum(run.is_active, typid, function_name, colname);
            nulls[attno] = false;
        }
        else
            dbms_trace_unsupported_column_error(function_name, colname);
    }
}
 
/* Заполняет одну строку SQL-результата trace events по фактическому descriptor. */
void
dbms_trace_fill_event_row(const DbmsTraceEvent& event, TupleDesc tupdesc, Datum* values, bool* nulls)
{
    const char* function_name = "event";
 
    for (int attno = 0; attno < tupdesc->natts; ++attno)
    {
        Form_pg_attribute attr = TupleDescAttr(tupdesc, attno);
        const char* colname = NameStr(attr->attname);
        const Oid typid = attr->atttypid;
 
        nulls[attno] = true;
        values[attno] = static_cast<Datum>(0);
 
        if (attr->attisdropped)
            continue;
 
        if (dbms_trace_attr_name_is(attr, "event_type"))
        {
            values[attno] = dbms_trace_text_datum_or_null(trace_event_type_label(event.event_type.c_str()),
                                                          typid,
                                                          &nulls[attno],
                                                          function_name,
                                                          colname);
        }
        else if (dbms_trace_attr_name_is(attr, "run_id"))
        {
            values[attno] = dbms_trace_int64_datum(event.run_id, typid, function_name, colname);
            nulls[attno] = false;
        }
        else if (dbms_trace_attr_name_is(attr, "event_seq"))
        {
            values[attno] = dbms_trace_int64_datum(event.event_seq, typid, function_name, colname);
            nulls[attno] = false;
        }
        else if (dbms_trace_attr_name_is(attr, "event_time") ||
                 dbms_trace_attr_name_is(attr, "event_timestamp") ||
                 dbms_trace_attr_name_is(attr, "timestamp"))
        {
            values[attno] = dbms_trace_timestamptz_datum(event.timestamp, typid, function_name, colname);
            nulls[attno] = false;
        }
        else if (dbms_trace_attr_name_is(attr, "unit_name"))
        {
            values[attno] = dbms_trace_text_datum_or_null(event.unit_name,
                                                          typid,
                                                          &nulls[attno],
                                                          function_name,
                                                          colname);
        }
        else if (dbms_trace_attr_name_is(attr, "subprogram_name"))
        {
            values[attno] = dbms_trace_text_datum_or_null(event.subprogram_name,
                                                          typid,
                                                          &nulls[attno],
                                                          function_name,
                                                          colname);
        }
        else if (dbms_trace_attr_name_is(attr, "nesting_depth"))
        {
            values[attno] = dbms_trace_int32_datum(event.nesting_depth, typid, function_name, colname);
            nulls[attno] = false;
        }
        else if (dbms_trace_attr_name_is(attr, "line_no"))
        {
            if (event.line_no != 0)
            {
                values[attno] = dbms_trace_int32_datum(event.line_no, typid, function_name, colname);
                nulls[attno] = false;
            }
        }
        else if (dbms_trace_attr_name_is(attr, "sql_text"))
        {
            values[attno] = dbms_trace_text_datum_or_null(event.sql_text,
                                                          typid,
                                                          &nulls[attno],
                                                          function_name,
                                                          colname);
        }
        else if (dbms_trace_attr_name_is(attr, "error_code"))
        {
            if (event.error_code != 0)
            {
                values[attno] = dbms_trace_int32_datum(event.error_code, typid, function_name, colname);
                nulls[attno] = false;
            }
        }
        else if (dbms_trace_attr_name_is(attr, "comment"))
        {
            values[attno] = dbms_trace_text_datum_or_null(event.comment,
                                                          typid,
                                                          &nulls[attno],
                                                          function_name,
                                                          colname);
        }
        else
            dbms_trace_unsupported_column_error(function_name, colname);
    }
}
 
/* Нормализует внутренние коды событий для SQL-вывода. */
const char*
trace_event_type_label(const char* event_type)
{
    if (event_type == nullptr)
        return "";
 
    if (std::strcmp(event_type, "SET") == 0)
        return "SET_TRACE";
    if (std::strcmp(event_type, "CLEAR") == 0)
        return "CLEAR_TRACE";
    return event_type;
}
 
/* Проверяет, что маска содержит только управляющие флаги. */
bool is_control_only(int32 trace_mask)
{
    return (trace_mask & kControlMask) != 0 && (trace_mask & ~kControlMask) == 0;
}
 
/* Собирает базовую структуру trace event с общими полями. */
DbmsTraceEvent
make_trace_event(DbmsTraceSessionState& state, const char* event_type, TimestampTz timestamp)
{
    DbmsTraceEvent event{};
    event.event_type = event_type != nullptr ? event_type : "";
    event.run_id = state.active_run_id;
    event.event_seq = state.next_event_seq++;
    event.timestamp = timestamp;
    return event;
}
 
/* Возвращает активный run для текущего состояния сессии. */
DbmsTraceRun*
current_trace_run(DbmsTraceSessionState& state)
{
    if (!state.enabled || state.active_run_id == 0 || state.trace_runs.empty())
        return nullptr;
 
    DbmsTraceRun& run = state.trace_runs.back();
    if (run.run_id != state.active_run_id)
        return nullptr;
 
    return &run;
}
 
/* Добавляет обычное trace-событие в историю сессии. */
void append_trace_event(DbmsTraceSessionState& state,
                        const char* event_type,
                        const std::string& comment,
                        TimestampTz timestamp)
{
    DbmsTraceEvent event = make_trace_event(state, event_type, timestamp);
    event.comment = comment;
    state.trace_rows.emplace_back(std::move(event));
    if (DbmsTraceRun* run = current_trace_run(state))
        run->event_count++;
}
 
/* Извлекает имя unit из signature функции. */
std::string
derive_unit_name(const char* fn_signature)
{
    if (fn_signature == nullptr || fn_signature[0] == '\0')
        return std::string();
 
    const std::string signature(fn_signature);
    const std::string::size_type open_paren = signature.find('(');
    if (open_paren == std::string::npos)
        return signature;
 
    return signature.substr(0, open_paren);
}
 
/* Извлекает имя subprogram из signature функции. */
std::string
derive_subprogram_name(const char* fn_signature)
{
    if (fn_signature == nullptr || fn_signature[0] == '\0')
        return std::string();
 
    const std::string signature(fn_signature);
    const std::string::size_type open_paren = signature.find('(');
    const std::string::size_type name_end = open_paren == std::string::npos ? signature.size() : open_paren;
    const std::string::size_type dot = signature.rfind('.', name_end);
    const std::string::size_type name_begin = dot == std::string::npos ? 0 : dot + 1;
 
    return signature.substr(name_begin, name_end - name_begin);
}
 
/* Создаёт запись о новом run. */
void
open_trace_run(DbmsTraceSessionState& state, int32 trace_level, TimestampTz timestamp)
{
    DbmsTraceRun run{};
    run.run_id = state.active_run_id;
    run.trace_mask = trace_level;
    run.started_at = timestamp;
    run.ended_at = 0;
    run.event_count = 0;
    run.is_active = true;
    state.trace_runs.emplace_back(run);
}
 
/* Закрывает текущий run по timestamp завершения. */
void
close_trace_run(DbmsTraceSessionState& state, TimestampTz timestamp)
{
    DbmsTraceRun* run = current_trace_run(state);
    if (run == nullptr)
        return;
 
    run->ended_at = timestamp;
    run->is_active = false;
}
 
/* Добавляет PL/pgSQL CALL или RETURN событие. */
void
append_plpgsql_trace_event(DbmsTraceSessionState& state,
                           const char* event_type,
                           PLpgSQL_function* func,
                           const char* comment_prefix)
{
    if (!state.enabled || state.active_run_id == 0 || func == nullptr)
        return;
 
    TimestampTz timestamp = GetCurrentTimestamp();
    DbmsTraceEvent event = make_trace_event(state, event_type, timestamp);
    event.unit_name = derive_unit_name(func->fn_signature);
    event.subprogram_name = derive_subprogram_name(func->fn_signature);
    event.comment = comment_prefix != nullptr ? comment_prefix : "";
    if (func->fn_signature != nullptr && func->fn_signature[0] != '\0')
    {
        if (!event.comment.empty())
            event.comment.push_back(' ');
        event.comment += func->fn_signature;
    }
    state.trace_rows.emplace_back(std::move(event));
    if (DbmsTraceRun* run = current_trace_run(state))
        run->event_count++;
}
 
/* Хук начала PL/pgSQL-функции. */
void
dbms_trace_plpgsql_func_beg(PLpgSQL_execstate* estate, PLpgSQL_function* func)
{
    (void) estate;
    auto& state = dbms_trace_session_state();
    append_plpgsql_trace_event(state,
                               "CALL",
                               func,
                               "PL/pgSQL function entered");
}
 
/* Хук завершения PL/pgSQL-функции. */
void
dbms_trace_plpgsql_func_end(PLpgSQL_execstate* estate, PLpgSQL_function* func)
{
    (void) estate;
    auto& state = dbms_trace_session_state();
    append_plpgsql_trace_event(state,
                               "RETURN",
                               func,
                               "PL/pgSQL function exited");
}
 
/* Устанавливает обработчики PL/pgSQL один раз на backend. */
void
dbms_trace_install_plpgsql_plugin()
{
    if (g_dbms_trace_plpgsql_plugin_installed)
        return;
 
    void** rendezvous = find_rendezvous_variable("PLpgSQL_plugin");
    if (rendezvous == nullptr)
        return;
 
    g_dbms_trace_plpgsql_plugin.func_setup = nullptr;
    g_dbms_trace_plpgsql_plugin.func_beg = dbms_trace_plpgsql_func_beg;
    g_dbms_trace_plpgsql_plugin.func_end = dbms_trace_plpgsql_func_end;
    g_dbms_trace_plpgsql_plugin.stmt_beg = nullptr;
    g_dbms_trace_plpgsql_plugin.stmt_end = nullptr;
 
    *reinterpret_cast<PLpgSQL_plugin**>(rendezvous) = &g_dbms_trace_plpgsql_plugin;
    g_dbms_trace_plpgsql_plugin_installed = true;
}
} // namespace
 
/*
 * Семантика выполнения DBMS_TRACE.
 *
 * Пакет хранит локальное состояние сессии и историю строк трассировки для
 * `SET_PLSQL_TRACE` / `CLEAR_PLSQL_TRACE`.
 *
 * Остальные public entrypoints остаются явными заглушками, чтобы SQL-клиенты
 * получали предсказуемую ошибку "not implemented" вместо отсутствующей
 * поверхности.
 */
 
static DbmsTraceSessionState g_dbms_trace_session_state{false, 0};
 
/* Возвращает backend-local состояние DBMS_TRACE. */
DbmsTraceSessionState&
dbms_trace_session_state()
{
    return g_dbms_trace_session_state;
}
 
PG_FUNCTION_INFO_V1(dbms_trace_set_plsql_trace);
PG_FUNCTION_INFO_V1(dbms_trace_clear_plsql_trace);
PG_FUNCTION_INFO_V1(dbms_trace_is_enabled);
PG_FUNCTION_INFO_V1(dbms_trace_get_plsql_trace_level);
PG_FUNCTION_INFO_V1(dbms_trace_plsql_trace_version);
PG_FUNCTION_INFO_V1(dbms_trace_get_version);
PG_FUNCTION_INFO_V1(dbms_trace_plsql_trace_runs);
PG_FUNCTION_INFO_V1(dbms_trace_plsql_trace_events);
 
/// @brief Версия RUDB пакета DBMS_TRACE (Oracle DBMS_TRACE пакет)
#define RUDB_DBMS_TRACE_VERSION "1.0.0"
 
Datum dbms_trace_set_plsql_trace(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
    {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("SET_PLSQL_TRACE requires a trace level")));
    }
 
    int32 trace_level = PG_GETARG_INT32(0);
    const bool enabled = DatumGetBool(
        DirectFunctionCall0(dbms_trace_is_enabled));
 
    if (is_control_only(trace_level))
    {
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("control trace flags cannot be combined with regular trace flags")));
    }
 
    auto& state = dbms_trace_session_state();
    if (!enabled)
    {
        dbms_trace_install_plpgsql_plugin();
        TimestampTz timestamp = GetCurrentTimestamp();
        state.enabled = true;
        state.active_run_id = state.next_run_id++;
        state.next_event_seq = 1;
        open_trace_run(state, trace_level, timestamp);
 
        append_trace_event(state,
                           "SET",
                           std::string("SET_PLSQL_TRACE trace_level=") + std::to_string(trace_level),
                           timestamp);
    }
    else if (!state.trace_runs.empty())
    {
        state.trace_runs.back().trace_mask = trace_level;
    }
 
    state.trace_mask = trace_level;
 
    PG_RETURN_VOID();
}
 
Datum dbms_trace_clear_plsql_trace(PG_FUNCTION_ARGS)
{
    auto& state = dbms_trace_session_state();
    const bool enabled = DatumGetBool(
        DirectFunctionCall0(dbms_trace_is_enabled));
    if (enabled)
    {
        TimestampTz timestamp = GetCurrentTimestamp();
        append_trace_event(state,
                           "CLEAR",
                           "CLEAR_PLSQL_TRACE",
                           timestamp);
        close_trace_run(state, timestamp);
    }
    state.enabled = false;
    state.trace_mask = 0;
    state.active_run_id = 0;
 
    PG_RETURN_VOID();
}
 
Datum dbms_trace_is_enabled(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL(is_trace_enabled(dbms_trace_session_state()));
}
 
/* Генерирует ошибку для не реализованных entrypoints. */
static void
dbms_trace_not_implemented(const char* function_name)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("%s is not implemented yet", function_name)));
}
 
Datum dbms_trace_get_plsql_trace_level(PG_FUNCTION_ARGS)
{
    dbms_trace_not_implemented("DBMS_TRACE.GET_PLSQL_TRACE_LEVEL");
    PG_RETURN_INT32(0);
}
 
Datum dbms_trace_plsql_trace_version(PG_FUNCTION_ARGS)
{
    dbms_trace_not_implemented("DBMS_TRACE.PLSQL_TRACE_VERSION");
    PG_RETURN_VOID();
}
 
Datum dbms_trace_get_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_TRACE_VERSION));
}
 
/*
 * SQL-доступ к строкам запуска трассировки поверх локальной истории сессии.
 */
Datum dbms_trace_plsql_trace_runs(PG_FUNCTION_ARGS)
{
    ReturnSetInfo* rsinfo = reinterpret_cast<ReturnSetInfo*>(fcinfo->resultinfo);
    if (rsinfo == nullptr || !IsA(rsinfo, ReturnSetInfo))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("set-valued function called in context that cannot accept a set")));
 
    InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC | MAT_SRF_BLESS);
    TupleDesc tupdesc = rsinfo->setDesc;
 
    for (const DbmsTraceRun& run : dbms_trace_session_state().trace_runs)
    {
        Datum* values = reinterpret_cast<Datum*>(palloc0(sizeof(Datum) * tupdesc->natts));
        bool* nulls = reinterpret_cast<bool*>(palloc(sizeof(bool) * tupdesc->natts));
 
        dbms_trace_fill_run_row(run, tupdesc, values, nulls);
        tuplestore_putvalues(rsinfo->setResult, tupdesc, values, nulls);
 
        pfree(values);
        pfree(nulls);
    }
 
    PG_RETURN_NULL();
}
 
/*
 * SQL-доступ к событиям трассировки поверх локальной истории сессии.
 */
Datum dbms_trace_plsql_trace_events(PG_FUNCTION_ARGS)
{
    ReturnSetInfo* rsinfo = reinterpret_cast<ReturnSetInfo*>(fcinfo->resultinfo);
    if (rsinfo == nullptr || !IsA(rsinfo, ReturnSetInfo))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("set-valued function called in context that cannot accept a set")));
 
    InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC | MAT_SRF_BLESS);
    TupleDesc tupdesc = rsinfo->setDesc;
 
    for (const DbmsTraceEvent& event : dbms_trace_session_state().trace_rows)
    {
        Datum* values = reinterpret_cast<Datum*>(palloc0(sizeof(Datum) * tupdesc->natts));
        bool* nulls = reinterpret_cast<bool*>(palloc(sizeof(bool) * tupdesc->natts));
 
        dbms_trace_fill_event_row(event, tupdesc, values, nulls);
        tuplestore_putvalues(rsinfo->setResult, tupdesc, values, nulls);
 
        pfree(values);
        pfree(nulls);
    }
 
    PG_RETURN_NULL();
}
 
/* Снимает debug snapshot для регрессионных проверок. */
extern "C" void
dbms_trace_get_debug_snapshot(DbmsTraceDebugSnapshot* out)
{
    if (out == nullptr)
    {
        return;
    }
 
    auto& state = dbms_trace_session_state();
    *out = DbmsTraceDebugSnapshot{};
    out->enabled = state.enabled;
    out->trace_mask = state.trace_mask;
    out->active_run_id = state.active_run_id;
    out->next_run_id = state.next_run_id;
    out->next_event_seq = state.next_event_seq;
    out->trace_rows_count = static_cast<int32>(state.trace_rows.size());
    if (!state.trace_rows.empty())
    {
        const std::string& last_event = state.trace_rows.back().event_type;
        std::snprintf(out->last_event_type,
                      sizeof(out->last_event_type),
                      "%s",
                      last_event.c_str());
    }
}