Исходный код СУБД 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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
/*
 * dbms_report.cpp — частичная реализация пакета DBMS_REPORT.
 * Не реализованные экспортируемые функции завершаются ошибкой NOT_IMPLEMENTED.
 */
 
extern "C" {
#include "postgres.h"
#include "fmgr.h"
#include "utils/builtins.h"
#include "lib/stringinfo.h"
#include <ctype.h>
#include <string.h>
#include <zlib.h>
#include "funcapi.h"
#include "access/htup_details.h"
}
 
#include <string>
#include <vector>
#include "dbms_report.hpp"
#include <sys/time.h>
#include <sys/resource.h>
#include <stdlib.h>
 
/// Преобразует text* в std::string
inline std::string text_to_std_string(text* t)
{
    char* c = text_to_cstring(t);
    std::string s(c);
    pfree(c);
    return s;
}
 
/// Кодирует бинарные данные в Base64 (строка ASCII)
static const char B64_TABLE[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 
inline std::string base64_encode_bytes(const std::string& in)
{
    std::string out;
    out.reserve(((in.size() + 2) / 3) * 4);
    size_t i = 0;
    while (i + 3 <= in.size()) {
        unsigned a = (unsigned char)in[i++];
        unsigned b = (unsigned char)in[i++];
        unsigned c = (unsigned char)in[i++];
        out.push_back(B64_TABLE[a >> 2]);
        out.push_back(B64_TABLE[((a & 3) << 4) | (b >> 4)]);
        out.push_back(B64_TABLE[((b & 0xF) << 2) | (c >> 6)]);
        out.push_back(B64_TABLE[c & 0x3F]);
    }
    size_t rem = in.size() - i;
    if (rem == 1) {
        unsigned a = (unsigned char)in[i++];
        out.push_back(B64_TABLE[a >> 2]);
        out.push_back(B64_TABLE[(a & 3) << 4]);
        out.push_back('=');
        out.push_back('=');
    } else if (rem == 2) {
        unsigned a = (unsigned char)in[i++];
        unsigned b = (unsigned char)in[i++];
        out.push_back(B64_TABLE[a >> 2]);
        out.push_back(B64_TABLE[((a & 3) << 4) | (b >> 4)]);
        out.push_back(B64_TABLE[(b & 0xF) << 2]);
        out.push_back('=');
    }
    return out;
}
 
/// Сжатие строки с помощью zlib (уровень сжатия по умолчанию)
inline std::string zlib_compress(const std::string& input)
{
    uLongf compressed_size = compressBound(input.size());
    std::string compressed;
    compressed.resize(compressed_size);
    int ret = compress2((Bytef*)&compressed[0], &compressed_size,
                        (const Bytef*)input.data(), input.size(),
                        Z_DEFAULT_COMPRESSION);
    if (ret != Z_OK) {
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                    errmsg("ZLIB compression failed: %d", ret)));
    }
    compressed.resize(compressed_size);
    return compressed;
}
 
static int
hex_nibble(char c)
{
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'a' && c <= 'f') return 10 + (c - 'a');
    if (c >= 'A' && c <= 'F') return 10 + (c - 'A');
    return -1;
}
 
static std::string
url_decode_component(const std::string& in)
{
    std::string out;
    out.reserve(in.size());
    for (size_t i = 0; i < in.size(); ++i)
    {
        char ch = in[i];
        if (ch == '+')
        {
            out.push_back(' ');
            continue;
        }
        if (ch == '%' && i + 2 < in.size())
        {
            int hi = hex_nibble(in[i + 1]);
            int lo = hex_nibble(in[i + 2]);
            if (hi >= 0 && lo >= 0)
            {
                out.push_back((char)((hi << 4) | lo));
                i += 2;
                continue;
            }
        }
        out.push_back(ch);
    }
    return out;
}
 
static bool
extract_param_from_ref_string(const std::string& ref_or_query,
                              const std::string& target_name,
                              std::string* out_value)
{
    size_t qpos = ref_or_query.find('?');
    const std::string query = (qpos == std::string::npos)
                                  ? ref_or_query
                                  : ref_or_query.substr(qpos + 1);
 
    size_t pos = 0;
    while (pos <= query.size())
    {
        size_t amp = query.find('&', pos);
        std::string token = (amp == std::string::npos)
                                ? query.substr(pos)
                                : query.substr(pos, amp - pos);
 
        if (!token.empty())
        {
            size_t eq = token.find('=');
            std::string raw_name = (eq == std::string::npos) ? token : token.substr(0, eq);
            std::string raw_value = (eq == std::string::npos) ? "" : token.substr(eq + 1);
 
            std::string name = url_decode_component(raw_name);
            if (name == target_name)
            {
                *out_value = url_decode_component(raw_value);
                return true;
            }
        }
 
        if (amp == std::string::npos) break;
        pos = amp + 1;
    }
 
    return false;
}
 
    /* Вспомогательные функции */
    static char *get_value_by_path(const char *report_json, const char *path);
    static void process_section(const char *section_json, const char *report_json,
                                StringInfo result, int indent);
    static void parse_nest_array(const char *nest_start, const char *report_json,
                                 StringInfo result, int indent);
    static void process_section_html(const char *section_json, const char *report_json,
                                     StringInfo result, int indent);
    static void parse_nest_array_html(const char *nest_start, const char *report_json,
                                      StringInfo result, int indent);
    static const char *find_top_level_value_start(const char *json_obj, const char *key);
    static std::string html_to_text_basic(const std::string& html, int max_linesize);
 
    /*
     * Извлекает значение из отчёта по точечному пути "$.key1.key2".
     * report_json – полный JSON отчёта в виде строки.
     */
    static char *
    get_value_by_path(const char *report_json, const char *path)
    {
        if (path[0] != '$' || path[1] != '.')
            return NULL;
 
        const char *p = path + 2;
        const char *current_json = report_json;
        char key[256];
 
        while (*p)
        {
            const char *dot = strchr(p, '.');
            int len;
            if (dot)
                len = dot - p;
            else
                len = strlen(p);
 
            if (len >= (int)sizeof(key)) return NULL;
            memcpy(key, p, len);
            key[len] = '\0';
 
            char *val;
            {
                LOCAL_FCINFO(fcinfo2, 2);
                InitFunctionCallInfoData(*fcinfo2, NULL, 2, InvalidOid, NULL, NULL);
 
                fcinfo2->args[0].value = PointerGetDatum(cstring_to_text(current_json));
                fcinfo2->args[0].isnull = false;
 
                fcinfo2->args[1].value = PointerGetDatum(cstring_to_text(key));
                fcinfo2->args[1].isnull = false;
 
                Datum result = dbms_report_extract_string_value(fcinfo2);
                if (result == 0) {
                    val == NULL;
                } else {
                    val = text_to_cstring(DatumGetTextP(result));
                }
            }
 
            if (!val) return NULL;
 
            if (dot == NULL)
            {
                /* Последний ключ – возвращаем значение */
                return val;
            }
            else
            {
                /* Для промежуточного ключа ожидается JSON-объект (начинается с '{') */
                /* Выполняется проверка типа значения и продолжение поиска во вложенном объекте */
                p = dot + 1;
                /* Проверка, что значение является объектом */
                const char *v = val;
                while (isspace((unsigned char)*v)) v++;
                if (*v != '{')
                {
                    pfree(val);
                    return NULL;
                }
                current_json = val;  /* теперь ищем внутри этого объекта */
            }
        }
        return NULL;
    }
 
    /*
     * Разбирает массив nest, начиная с позиции nest_start (которая указывает на '[')
     */
    static void
    parse_nest_array(const char *nest_start, const char *report_json,
                     StringInfo result, int indent)
    {
        const char *p = nest_start;
        if (*p != '[') return;
        p++; /* пропускаем '[' */
 
        while (*p && *p != ']')
        {
            while (isspace((unsigned char)*p)) p++;
            if (*p == '{')
            {
                int brace = 1;
                const char *obj_start = p;
                while (*(++p))
                {
                    if (*p == '{') brace++;
                    else if (*p == '}') brace--;
                    if (brace == 0) break;
                }
                if (brace == 0)
                {
                    int obj_len = p - obj_start + 1;
                    char *section = (char *) palloc(obj_len + 1);
                    memcpy(section, obj_start, obj_len);
                    section[obj_len] = '\0';
                    process_section(section, report_json, result, indent);
                    pfree(section);
                }
            }
            else
            {
                p++; /* пропускаем запятые и прочее */
            }
        }
    }
 
    /* Вспомогательные функции HTML */
    static void
    append_html_escaped(StringInfo out, const char *src, int len)
    {
        for (int i = 0; i < len; ++i)
        {
            char ch = src[i];
            switch (ch)
            {
                case '&': appendStringInfoString(out, "&amp;"); break;
                case '<': appendStringInfoString(out, "&lt;"); break;
                case '>': appendStringInfoString(out, "&gt;"); break;
                case '"': appendStringInfoString(out, "&quot;"); break;
                default: appendStringInfoChar(out, ch); break;
            }
        }
    }
 
    static const char *
    find_top_level_value_start(const char *json_obj, const char *key)
    {
        if (!json_obj || !key) return NULL;
 
        char needle[256];
        snprintf(needle, sizeof(needle), "\"%s\"", key);
        int needle_len = (int)strlen(needle);
 
        int obj_depth = 0;
        bool in_string = false;
        bool escaped = false;
        const char *p = json_obj;
 
        while (*p)
        {
            char c = *p;
            if (in_string)
            {
                if (escaped) escaped = false;
                else if (c == '\\') escaped = true;
                else if (c == '"') in_string = false;
                p++;
                continue;
            }
 
            if (c == '"')
            {
                if (obj_depth == 1 && strncmp(p, needle, needle_len) == 0)
                {
                    const char *q = p + needle_len;
                    while (*q && isspace((unsigned char)*q)) q++;
                    if (*q != ':')
                    {
                        p++;
                        continue;
                    }
                    q++;
                    while (*q && isspace((unsigned char)*q)) q++;
                    return q;
                }
                in_string = true;
                p++;
                continue;
            }
 
            if (c == '{') obj_depth++;
            else if (c == '}') obj_depth--;
            p++;
        }
 
        return NULL;
    }
 
    static void
    append_wrapped_word(StringInfo out, StringInfo line, const std::string& word, int max_linesize)
    {
        if (word.empty()) return;
 
        if (line->len == 0)
        {
            appendStringInfoString(line, word.c_str());
            return;
        }
 
        if (line->len + 1 + (int)word.size() <= max_linesize)
        {
            appendStringInfoChar(line, ' ');
            appendStringInfoString(line, word.c_str());
            return;
        }
 
        appendStringInfoString(out, line->data);
        appendStringInfoChar(out, '\n');
        resetStringInfo(line);
        appendStringInfoString(line, word.c_str());
    }
 
    static std::string
    html_to_text_basic(const std::string& html, int max_linesize)
    {
        StringInfoData raw;
        initStringInfo(&raw);
 
        bool in_tag = false;
        std::string tag_buf;
        for (size_t i = 0; i < html.size(); ++i)
        {
            char ch = html[i];
            if (!in_tag)
            {
                if (ch == '<')
                {
                    in_tag = true;
                    tag_buf.clear();
                    continue;
                }
                if (ch == '\r') continue;
                appendStringInfoChar(&raw, ch);
            }
            else
            {
                if (ch == '>')
                {
                    in_tag = false;
 
                    std::string t;
                    t.reserve(tag_buf.size());
                    for (char c : tag_buf)
                        t.push_back((char)tolower((unsigned char)c));
 
                    if (t.compare(0, 2, "br") == 0 ||
                        t.compare(0, 3, "/p") == 0 ||
                        t.compare(0, 2, "p ") == 0 || t == "p" ||
                        t.compare(0, 3, "/h1") == 0 || t.compare(0, 3, "/h2") == 0 ||
                        t.compare(0, 3, "/h3") == 0 || t.compare(0, 3, "/h4") == 0 ||
                        t.compare(0, 3, "/h5") == 0 || t.compare(0, 3, "/h6") == 0 ||
                        t.compare(0, 3, "/li") == 0 || t.compare(0, 3, "/tr") == 0 ||
                        t.compare(0, 4, "/div") == 0)
                    {
                        appendStringInfoChar(&raw, '\n');
                    }
                    continue;
                }
                tag_buf.push_back(ch);
            }
        }
 
        std::string s(raw.data, raw.len);
        pfree(raw.data);
 
        auto replace_all = [](std::string& x, const std::string& from, const std::string& to) {
            size_t pos = 0;
            while ((pos = x.find(from, pos)) != std::string::npos)
            {
                x.replace(pos, from.size(), to);
                pos += to.size();
            }
        };
        replace_all(s, "&lt;", "<");
        replace_all(s, "&gt;", ">");
        replace_all(s, "&amp;", "&");
        replace_all(s, "&quot;", "\"");
        replace_all(s, "&#39;", "'");
        replace_all(s, "&nbsp;", " ");
 
        StringInfoData out;
        StringInfoData line;
        initStringInfo(&out);
        initStringInfo(&line);
 
        std::string word;
        for (size_t i = 0; i < s.size(); ++i)
        {
            char ch = s[i];
            if (ch == '\n')
            {
                if (!word.empty())
                {
                    append_wrapped_word(&out, &line, word, max_linesize);
                    word.clear();
                }
                if (line.len > 0)
                {
                    appendStringInfoString(&out, line.data);
                    resetStringInfo(&line);
                }
                if (out.len == 0 || out.data[out.len - 1] != '\n')
                    appendStringInfoChar(&out, '\n');
                continue;
            }
 
            if (isspace((unsigned char)ch))
            {
                if (!word.empty())
                {
                    append_wrapped_word(&out, &line, word, max_linesize);
                    word.clear();
                }
            }
            else
            {
                word.push_back(ch);
            }
        }
 
        if (!word.empty())
            append_wrapped_word(&out, &line, word, max_linesize);
        if (line.len > 0)
            appendStringInfoString(&out, line.data);
 
        while (out.len > 0 && (out.data[out.len - 1] == '\n' || out.data[out.len - 1] == ' '))
        {
            out.len--;
            out.data[out.len] = '\0';
        }
 
        std::string result(out.data, out.len);
        pfree(out.data);
        pfree(line.data);
        return result;
    }
 
    static bool
    is_safe_html_tag(const char *tag)
    {
        if (!tag || !*tag) return false;
        for (const char *p = tag; *p; ++p)
        {
            if (!isalnum((unsigned char)*p))
                return false;
        }
        return true;
    }
 
    static void
    append_args_html(StringInfo out, const char *section_json, const char *report_json)
    {
        const char *args_start = find_top_level_value_start(section_json, "args");
        if (!args_start) return;
 
        if (*args_start == '"')
        {
            args_start++;
            const char *end = strchr(args_start, '"');
            if (end)
                append_html_escaped(out, args_start, (int)(end - args_start));
            return;
        }
 
        if (*args_start != '[') return;
        const char *p = args_start + 1;
        while (*p && *p != ']')
        {
            while (isspace((unsigned char)*p)) p++;
            if (*p == '"')
            {
                p++;
                const char *end = strchr(p, '"');
                if (!end) break;
                int len = (int)(end - p);
                if (len > 2 && p[0] == '$' && p[1] == '.')
                {
                    char *path = (char *) palloc(len + 1);
                    memcpy(path, p, len);
                    path[len] = '\0';
                    char *val = get_value_by_path(report_json, path);
                    if (val)
                    {
                        append_html_escaped(out, val, (int)strlen(val));
                        pfree(val);
                    }
                    pfree(path);
                }
                else
                {
                    append_html_escaped(out, p, len);
                }
                p = end + 1;
            }
            else
            {
                while (*p && *p != ',' && *p != ']') p++;
            }
            if (*p == ',') p++;
        }
    }
 
    static void
    append_attrs_html(StringInfo out, const char *section_json, const char *report_json)
    {
        const char *attrs = find_top_level_value_start(section_json, "attrs");
        if (!attrs) return;
        if (*attrs != '[') return;
        attrs++;
 
        while (*attrs && *attrs != ']')
        {
            while (isspace((unsigned char)*attrs)) attrs++;
            if (*attrs == '"')
            {
                attrs++;
                const char *end = strchr(attrs, '"');
                if (!end) break;
 
                const char *eq = (const char *)memchr(attrs, '=', (size_t)(end - attrs));
                if (eq && eq > attrs)
                {
                    appendStringInfoChar(out, ' ');
                    appendBinaryStringInfo(out, attrs, (int)(eq - attrs));
                    appendStringInfoChar(out, '=');
                    appendBinaryStringInfo(out, eq + 1, (int)(end - eq - 1));
                }
                attrs = end + 1;
            }
            else
            {
                attrs++;
            }
            if (*attrs == ',') attrs++;
        }
    }
 
    static void
    process_section_html(const char *section_json, const char *report_json,
                         StringInfo result, int indent)
    {
        char *type;
        {
            LOCAL_FCINFO(fcinfo2, 2);
            InitFunctionCallInfoData(*fcinfo2, NULL, 2, InvalidOid, NULL, NULL);
 
            fcinfo2->args[0].value = PointerGetDatum(cstring_to_text(section_json));
            fcinfo2->args[0].isnull = false;
 
            fcinfo2->args[1].value = PointerGetDatum(cstring_to_text("type"));
            fcinfo2->args[1].isnull = false;
 
            Datum result = dbms_report_extract_string_value(fcinfo2);
            if (result == 0) {
                type == NULL;
            } else {
                type = text_to_cstring(DatumGetTextP(result));
            }
        }
        if (!type) return;
 
        if (!is_safe_html_tag(type))
        {
            pfree(type);
            return;
        }
 
        bool is_heading =
            (type[0] == 'h' && strlen(type) == 2 &&
             isdigit((unsigned char)type[1]));
        bool is_control = (strcmp(type, "loop") == 0 || strcmp(type, "if") == 0);
        bool is_multiline =
            (strcmp(type, "p") == 0 || strcmp(type, "div") == 0 ||
             strcmp(type, "strong") == 0 || strcmp(type, "ul") == 0 ||
             strcmp(type, "ol") == 0 || strcmp(type, "li") == 0 ||
             strcmp(type, "a") == 0 || is_heading || is_control);
 
        if (strcmp(type, "hr") == 0)
        {
            appendStringInfoString(result, "<hr>\n</hr>");
            appendStringInfoChar(result, '\n');
            pfree(type);
            return;
        }
 
        if (strcmp(type, "br") == 0)
        {
            appendStringInfoString(result, "<br/>");
            appendStringInfoChar(result, '\n');
            pfree(type);
            return;
        }
 
        appendStringInfo(result, "<%s", type);
        if (strcmp(type, "a") == 0)
            append_attrs_html(result, section_json, report_json);
        if (is_multiline)
            appendStringInfoString(result, ">\n");
        else
            appendStringInfoChar(result, '>');
 
        bool suppress_args =
            is_control || strcmp(type, "li") == 0 || strcmp(type, "a") == 0 ||
            strcmp(type, "ul") == 0 || strcmp(type, "ol") == 0;
        if (!suppress_args)
        {
            StringInfoData args_buf;
            initStringInfo(&args_buf);
            append_args_html(&args_buf, section_json, report_json);
            if (args_buf.len > 0)
            {
                if (is_multiline && (strcmp(type, "strong") == 0 || strcmp(type, "p") == 0) && indent > 0)
                {
                    appendStringInfoString(result, "  ");
                }
                appendStringInfoString(result, args_buf.data);
                if (is_multiline)
                    appendStringInfoChar(result, '\n');
            }
            pfree(args_buf.data);
        }
 
        const char *nest_start = find_top_level_value_start(section_json, "nest");
        if (nest_start)
        {
            if (*nest_start == '[')
            {
                parse_nest_array_html(nest_start, report_json, result, indent + 1);
            }
        }
 
        if (is_multiline)
        {
            appendStringInfo(result, "</%s>", type);
        }
        else
            appendStringInfo(result, "</%s>", type);
        appendStringInfoChar(result, '\n');
        pfree(type);
    }
 
    static void
    parse_nest_array_html(const char *nest_start, const char *report_json,
                          StringInfo result, int indent)
    {
        const char *p = nest_start;
        if (*p != '[') return;
        p++;
 
        while (*p && *p != ']')
        {
            while (isspace((unsigned char)*p)) p++;
            if (*p == '{')
            {
                int brace = 1;
                const char *obj_start = p;
                while (*(++p))
                {
                    if (*p == '{') brace++;
                    else if (*p == '}') brace--;
                    if (brace == 0) break;
                }
                if (brace == 0)
                {
                    int obj_len = (int)(p - obj_start + 1);
                    char *section = (char *) palloc(obj_len + 1);
                    memcpy(section, obj_start, obj_len);
                    section[obj_len] = '\0';
                    process_section_html(section, report_json, result, indent);
                    pfree(section);
                }
            }
            else
            {
                p++;
            }
        }
    }
 
    /*
     * Обрабатывает одну секцию мета-спецификации.
     */
    static void
    process_section(const char *section_json, const char *report_json,
                    StringInfo result, int indent)
    {
        char *type;
        {
            LOCAL_FCINFO(fcinfo2, 2);
            InitFunctionCallInfoData(*fcinfo2, NULL, 2, InvalidOid, NULL, NULL);
 
            fcinfo2->args[0].value = PointerGetDatum(cstring_to_text(section_json));
            fcinfo2->args[0].isnull = false;
 
            fcinfo2->args[1].value = PointerGetDatum(cstring_to_text("type"));
            fcinfo2->args[1].isnull = false;
 
            Datum result = dbms_report_extract_string_value(fcinfo2);
            if (result == 0) {
                type == NULL;
            } else {
                type = text_to_cstring(DatumGetTextP(result));
            }
        }
        if (!type) return;
 
        /* Собираем текст из args */
        StringInfoData section_text;
        initStringInfo(&section_text);
 
        /* args может быть строкой или массивом */
        const char *args_start = strstr(section_json, "\"args\"");
        if (args_start)
        {
            args_start += 5;
            while (*args_start && *args_start != ':') args_start++;
            if (*args_start == ':')
            {
                args_start++;
                while (isspace((unsigned char)*args_start)) args_start++;
 
                if (*args_start == '"')
                {
                    /* args – строка */
                    args_start++;
                    const char *end = strchr(args_start, '"');
                    if (end)
                    {
                        int len = end - args_start;
                        appendBinaryStringInfo(&section_text, args_start, len);
                    }
                }
                else if (*args_start == '[')
                {
                    /* args – массив строк */
                    const char *p = args_start + 1;
                    while (*p && *p != ']')
                    {
                        while (isspace((unsigned char)*p)) p++;
                        if (*p == '"')
                        {
                            p++;
                            const char *end = strchr(p, '"');
                            if (end)
                            {
                                int len = end - p;
                                /* Проверим, не является ли этот элемент путём (начинается с "$.") */
                                if (len > 2 && p[0] == '$' && p[1] == '.')
                                {
                                    char *path = (char *) palloc(len + 1);
                                    memcpy(path, p, len);
                                    path[len] = '\0';
                                    char *val = get_value_by_path(report_json, path);
                                    if (val)
                                    {
                                        appendStringInfoString(&section_text, val);
                                        pfree(val);
                                    }
                                    pfree(path);
                                }
                                else
                                {
                                    appendBinaryStringInfo(&section_text, p, len);
                                }
                                p = end + 1;
                            }
                        }
                        else
                        {
                            /* Пропуск нестроковых элементов */
                            while (*p && *p != ',' && *p != ']') p++;
                        }
                        if (*p == ',') p++;
                    }
                }
            }
        }
 
        /* Отступ */
        bool need_indent = (strcmp(type, "br") != 0) && (section_text.len > 0);
        if (need_indent)
        {
            for (int i = 0; i < indent; i++)
                appendStringInfoString(result, "  ");
        }
 
        /* Обработка типа секции */
        if (strcmp(type, "p") == 0 || strcmp(type, "li") == 0)
        {
            appendStringInfoString(result, section_text.data);
        }
        else if (strncmp(type, "h", 1) == 0 && strlen(type) == 2 && isdigit(type[1]))
        {
            /* Заголовок h1-h6 */
            appendStringInfoString(result, section_text.data);
            appendStringInfoString(result, "\n");
            if (need_indent)
            {
                for (int i = 0; i < indent; i++)
                    appendStringInfoString(result, "  ");
            }
            char *line;
            {
                LOCAL_FCINFO(fcinfo2, 2);
                InitFunctionCallInfoData(*fcinfo2, NULL, 2, InvalidOid, NULL, NULL);
 
                fcinfo2->args[0].value = PointerGetDatum(cstring_to_text(section_json));
                fcinfo2->args[0].isnull = false;
 
                fcinfo2->args[1].value = PointerGetDatum(cstring_to_text("line"));
                fcinfo2->args[1].isnull = false;
 
                Datum result = dbms_report_extract_string_value(fcinfo2);
                if (result == 0) {
                    line == NULL;
                } else {
                    line = text_to_cstring(DatumGetTextP(result));
                }
            }
            const char *line_char = line ? line : "-";
            int len = section_text.len;
            for (int i = 0; i < len; i++)
                appendStringInfoString(result, line_char);
            if (line) pfree(line);
        }
        else if (strcmp(type, "br") == 0)
        {
            appendStringInfoString(result, "\n");
        }
        else
        {
            /* Неподдерживаемый тип – игнорируем */
        }
 
        if (need_indent && strcmp(type, "br") != 0)
            appendStringInfoString(result, "\n");
 
        /* Обработка вложенных секций */
        const char *nest_start = strstr(section_json, "\"nest\"");
        if (nest_start)
        {
            nest_start += 5;
            while (*nest_start && *nest_start != ':') nest_start++;
            if (*nest_start == ':')
            {
                nest_start++;
                while (isspace((unsigned char)*nest_start)) nest_start++;
                if (*nest_start == '[')
                {
                    parse_nest_array(nest_start, report_json, result, indent + 1);
                }
            }
        }
 
        pfree(type);
        pfree(section_text.data);
    }
 
 
    static void
    dbms_report_raise_not_implemented(const char* routine_name, int nargs)
    {
        ereport(ERROR,
                (errmsg("NOT_IMPLEMENTED"),
                 errdetail("DBMS_REPORT: %s, argc=%d", routine_name, nargs)));
    }
 
    PG_FUNCTION_INFO_V1(dbms_report_build_generic_tag);
    PG_FUNCTION_INFO_V1(dbms_report_build_report_reference_struct);
    PG_FUNCTION_INFO_V1(dbms_report_build_report_reference_varg);
    PG_FUNCTION_INFO_V1(dbms_report_clear_framework);
    PG_FUNCTION_INFO_V1(dbms_report_format_message);
    PG_FUNCTION_INFO_V1(dbms_report_format_report);
    PG_FUNCTION_INFO_V1(dbms_report_get_awr_context);
    PG_FUNCTION_INFO_V1(dbms_report_get_awr_diff_context);
    PG_FUNCTION_INFO_V1(dbms_report_get_imported_report_attrs);
    PG_FUNCTION_INFO_V1(dbms_report_get_param);
    PG_FUNCTION_INFO_V1(dbms_report_get_report);
    PG_FUNCTION_INFO_V1(dbms_report_get_report_json);
    PG_FUNCTION_INFO_V1(dbms_report_get_report_with_summary);
    PG_FUNCTION_INFO_V1(dbms_report_get_snap_id);
    PG_FUNCTION_INFO_V1(dbms_report_get_timing_info);
    PG_FUNCTION_INFO_V1(dbms_report_gzip_report_xml);
    PG_FUNCTION_INFO_V1(dbms_report_is_compress_event_set);
    PG_FUNCTION_INFO_V1(dbms_report_json_to_html);
    PG_FUNCTION_INFO_V1(dbms_report_json_to_text);
    PG_FUNCTION_INFO_V1(dbms_report_lookup_component_id);
    PG_FUNCTION_INFO_V1(dbms_report_lookup_report_id);
    PG_FUNCTION_INFO_V1(dbms_report_parse_report_reference);
    PG_FUNCTION_INFO_V1(dbms_report_register_component);
    PG_FUNCTION_INFO_V1(dbms_report_register_custom_format);
    PG_FUNCTION_INFO_V1(dbms_report_register_report);
    PG_FUNCTION_INFO_V1(dbms_report_register_swf);
    PG_FUNCTION_INFO_V1(dbms_report_register_text_format);
    PG_FUNCTION_INFO_V1(dbms_report_register_xslt_format);
    PG_FUNCTION_INFO_V1(dbms_report_restore_report_env);
    PG_FUNCTION_INFO_V1(dbms_report_setup_report_env);
    PG_FUNCTION_INFO_V1(dbms_report_transform_html_to_text);
    PG_FUNCTION_INFO_V1(dbms_report_transform_report_json);
    PG_FUNCTION_INFO_V1(dbms_report_transform_report_xml);
    PG_FUNCTION_INFO_V1(dbms_report_unescape_report_ref);
    PG_FUNCTION_INFO_V1(dbms_report_validate_ref_parameter);
    PG_FUNCTION_INFO_V1(dbms_report_validate_report);
    PG_FUNCTION_INFO_V1(dbms_report_zlib2base64_clob);
    PG_FUNCTION_INFO_V1(dbms_report_zlib2base64_report_xml);
 
PG_FUNCTION_INFO_V1(dbms_report_get_version);
PG_FUNCTION_INFO_V1(dbms_report_extract_string_value);
 
/// @brief Версия RUDB пакета DBMS_REPORT (Oracle DBMS_REPORT пакет)
#define RUDB_DBMS_REPORT_VERSION "1.0.0"
 
    extern "C" Datum
    dbms_report_build_generic_tag(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_build_generic_tag", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_build_report_reference_struct(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_build_report_reference_struct", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_build_report_reference_varg(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_build_report_reference_varg", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_clear_framework(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_clear_framework", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_format_message(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_format_message", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_format_report(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_format_report", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_get_awr_context(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_get_awr_context", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_get_awr_diff_context(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_get_awr_diff_context", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_get_imported_report_attrs(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_get_imported_report_attrs", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_get_param(PG_FUNCTION_ARGS)
    {
        if (PG_ARGISNULL(1))
            PG_RETURN_NULL();
 
        std::string param_name = text_to_std_string(PG_GETARG_TEXT_PP(1));
        bool mandatory = false;
        bool nullable = false;
 
        if (PG_NARGS() > 2 && !PG_ARGISNULL(2))
            mandatory = PG_GETARG_BOOL(2);
        if (PG_NARGS() > 4 && !PG_ARGISNULL(4))
            nullable = PG_GETARG_BOOL(4);
 
        std::string value;
        bool found = false;
        if (!PG_ARGISNULL(0))
        {
            std::string ref_or_query = text_to_std_string(PG_GETARG_TEXT_PP(0));
            found = extract_param_from_ref_string(ref_or_query, param_name, &value);
        }
 
        if (found)
        {
            if (nullable && value.empty())
                PG_RETURN_NULL();
            PG_RETURN_TEXT_P(cstring_to_text_with_len(value.data(), value.size()));
        }
 
        if (mandatory)
        {
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("mandatory parameter is missing: %s", param_name.c_str())));
        }
 
        if (PG_NARGS() > 3 && !PG_ARGISNULL(3))
        {
            text *def_val = PG_GETARG_TEXT_PP(3);
            std::string def_value = text_to_std_string(def_val);
            PG_RETURN_TEXT_P(cstring_to_text_with_len(def_value.data(), def_value.size()));
        }
 
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_get_report(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_get_report", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_get_report_json(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_get_report_json", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_get_report_with_summary(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_get_report_with_summary", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_get_snap_id(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_get_snap_id", PG_NARGS());
        PG_RETURN_NULL();
    }
 
extern "C" Datum
dbms_report_get_timing_info(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        PG_RETURN_NULL();
 
    int32 phase = PG_GETARG_INT32(0);
    Datum elapsed_in = (Datum) 0;
    Datum cpu_in = (Datum) 0;
 
    if (!PG_ARGISNULL(1)) elapsed_in = PG_GETARG_DATUM(1);
    if (!PG_ARGISNULL(2)) cpu_in = PG_GETARG_DATUM(2);
 
    TupleDesc tupdesc;
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
    {
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("function returning record called in context that cannot accept type record")));
    }
 
    struct timeval tv;
    gettimeofday(&tv, NULL);
    /* time in hundredths of a second */
    int64 current_elapsed = (int64)tv.tv_sec * 100 + tv.tv_usec / 10000;
 
    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);
    int64 current_cpu = ((int64)ru.ru_utime.tv_sec * 100 + ru.ru_utime.tv_usec / 10000)
                      + ((int64)ru.ru_stime.tv_sec * 100 + ru.ru_stime.tv_usec / 10000);
 
    int64 out_elapsed = current_elapsed;
    int64 out_cpu = current_cpu;
 
    if (phase == 1)
    {
        int64 in_elapsed_val = 0;
        int64 in_cpu_val = 0;
 
        if (!PG_ARGISNULL(1))
        {
            char *str_el = DatumGetCString(DirectFunctionCall1(numeric_out, elapsed_in));
            in_elapsed_val = strtoll(str_el, NULL, 10);
            pfree(str_el);
        }
 
        if (!PG_ARGISNULL(2))
        {
            char *str_cpu = DatumGetCString(DirectFunctionCall1(numeric_out, cpu_in));
            in_cpu_val = strtoll(str_cpu, NULL, 10);
            pfree(str_cpu);
        }
 
        out_elapsed = current_elapsed - in_elapsed_val;
        if (out_elapsed < 0) out_elapsed = 0;
 
        out_cpu = current_cpu - in_cpu_val;
        if (out_cpu < 0) out_cpu = 0;
    }
 
    char buf_elapsed[64];
    char buf_cpu[64];
    snprintf(buf_elapsed, sizeof(buf_elapsed), "%lld", (long long)out_elapsed);
    snprintf(buf_cpu, sizeof(buf_cpu), "%lld", (long long)out_cpu);
 
    Datum cur_el_num = DirectFunctionCall3(numeric_in, CStringGetDatum(buf_elapsed), ObjectIdGetDatum(0), Int32GetDatum(-1));
    Datum cur_cpu_num = DirectFunctionCall3(numeric_in, CStringGetDatum(buf_cpu), ObjectIdGetDatum(0), Int32GetDatum(-1));
 
    Datum values[2];
    bool nulls[2] = {false, false};
 
    values[0] = cur_el_num;
    values[1] = cur_cpu_num;
 
    HeapTuple tuple = heap_form_tuple(tupdesc, values, nulls);
    PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
}
 
    extern "C" Datum
    dbms_report_gzip_report_xml(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_gzip_report_xml", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_is_compress_event_set(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_is_compress_event_set", PG_NARGS());
        PG_RETURN_BOOL(false);
    }
 
    extern "C" Datum
    dbms_report_json_to_html(PG_FUNCTION_ARGS)
    {
        if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
            PG_RETURN_NULL();
 
        text *json_report_text = PG_GETARG_TEXT_PP(0);
        text *json_meta_text = PG_GETARG_TEXT_PP(1);
 
        char *report_json = text_to_cstring(json_report_text);
        char *meta_json = text_to_cstring(json_meta_text);
 
        StringInfoData body_result;
        initStringInfo(&body_result);
 
        const char *nest_start = strstr(meta_json, "\"nest\"");
        if (nest_start)
        {
            nest_start += 5;
            while (*nest_start && *nest_start != ':') nest_start++;
            if (*nest_start == ':')
            {
                nest_start++;
                while (isspace((unsigned char)*nest_start)) nest_start++;
                if (*nest_start == '[')
                    parse_nest_array_html(nest_start, report_json, &body_result, 0);
            }
        }
 
        if (body_result.len == 0)
            appendStringInfoString(&body_result, "");
 
        StringInfoData result;
        initStringInfo(&result);
        appendStringInfoString(&result,
            "<html lang=\"en\"><head>\n"
            "<title>HTML Report</title>\n"
            " <style type=\"text/css\">        \n"
            "  body {font:bold 12pt Arial,Helvetica,Geneva,sans-serif;\n"
            "    color:black; \n"
            "    background:White;}\n"
            "  h1 {font:bold 20pt Arial,Helvetica,Geneva,sans-serif;\n"
            "    color:#336699;\n"
            "    background-color:White;\n"
            "    border-bottom:1px solid #cccc99;\n"
            "    margin-top:0pt; \n"
            "    margin-bottom:0pt;\n"
            "    padding:0px 0px 0px 0px;}\n"
            "  h2 {font:bold 18pt Arial,Helvetica,Geneva,sans-serif;\n"
            "    color:#336699;\n"
            "    background-color:White;\n"
            "    margin-top:4pt; \n"
            "    margin-bottom:4pt;}\n"
            "  h3 {font:bold 16pt Arial,Helvetica,Geneva,sans-serif;\n"
            "    color:#336699;\n"
            "    background-color:White;margin-top:4pt; \n"
            "    margin-bottom:4pt;}\n"
            "  h4 {font:bold 13pt Arial,Helvetica,Geneva,sans-serif;\n"
            "    color:#336699;\n"
            "    background-color:White;margin-top:3pt; \n"
            "    margin-bottom:3pt;}\n"
            "  li {font: 8pt Arial,Helvetica,Geneva,sans-serif; \n"
            "    color:black; \n"
            "    background:White;}\n"
            "  table {\n"
            "    border: thin solid line; }\n"
            "  tr {\n"
            "    border: thin solid line;\n"
            "    background: #FFFFCC; }\n"
            "  tr:nth-child(odd) {\n"
            "    background: White; }\n"
            "  th {font:bold 10pt Arial,Helvetica,Geneva,sans-serif; \n"
            "    color:White; \n"
            "    background:#0066CC;\n"
            "    padding-left:4px; \n"
            "    padding-right:4px;\n"
            "    padding-bottom:2px}\n"
            "  td {font:10pt Arial,Helvetica,Geneva,sans-serif;\n"
            "    color:black;\n"
            "    vertical-align:top;\n"
            "    border-right: thin solid black; }\n"
            "  .hidden {position:absolute;\n"
            "    left:-10000px;\n"
            "    top:auto;width:1px;height:1px;overflow:hidden;}\n"
            "  .pad   {margin-left:17px;}\n"
            "  .doublepad {margin-left:34px;}\n"
            "      </style>\n"
            "</head>\n"
            "<body>\n");
 
        while (body_result.len > 0 &&
               (body_result.data[body_result.len - 1] == '\n' ||
                body_result.data[body_result.len - 1] == '\r'))
        {
            body_result.len--;
            body_result.data[body_result.len] = '\0';
        }
 
        appendStringInfoString(&result, body_result.data);
        appendStringInfoChar(&result, '\n');
        appendStringInfoString(&result, "</body></html>");
 
        pfree(report_json);
        pfree(meta_json);
        pfree(body_result.data);
 
        PG_RETURN_TEXT_P(cstring_to_text(result.data));
    }
 
    extern "C" Datum
    dbms_report_json_to_text(PG_FUNCTION_ARGS)
    {
        if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
            PG_RETURN_NULL();
 
        text *json_report_text = PG_GETARG_TEXT_PP(0);
        text *json_meta_text = PG_GETARG_TEXT_PP(1);
 
        /* Получаем C-строки напрямую */
        char *report_json = text_to_cstring(json_report_text);
        char *meta_json = text_to_cstring(json_meta_text);
 
        StringInfoData result;
        initStringInfo(&result);
 
        /* Ищем корневой массив nest */
        const char *nest_start = strstr(meta_json, "\"nest\"");
        if (nest_start)
        {
            nest_start += 5;
            while (*nest_start && *nest_start != ':') nest_start++;
            if (*nest_start == ':')
            {
                nest_start++;
                while (isspace((unsigned char)*nest_start)) nest_start++;
                if (*nest_start == '[')
                {
                    parse_nest_array(nest_start, report_json, &result, 0);
                }
            }
        }
 
        /* Если ничего не вывели, возвращаем пустую строку */
        if (result.len == 0)
            appendStringInfoString(&result, "");
 
        pfree(report_json);
        pfree(meta_json);
 
        PG_RETURN_TEXT_P(cstring_to_text(result.data));
    }
 
    extern "C" Datum
    dbms_report_lookup_component_id(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_lookup_component_id", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_lookup_report_id(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_lookup_report_id", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_parse_report_reference(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_parse_report_reference", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_register_component(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_register_component", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_register_custom_format(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_register_custom_format", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_register_report(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_register_report", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_register_swf(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_register_swf", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_register_text_format(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_register_text_format", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_register_xslt_format(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_register_xslt_format", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_restore_report_env(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_restore_report_env", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_setup_report_env(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_setup_report_env", PG_NARGS());
        PG_RETURN_BOOL(false);
    }
 
    extern "C" Datum
    dbms_report_transform_html_to_text(PG_FUNCTION_ARGS)
    {
        if (PG_ARGISNULL(0))
            PG_RETURN_NULL();
 
        int max_linesize = 80;
        if (!PG_ARGISNULL(1))
            max_linesize = PG_GETARG_INT32(1);
        if (max_linesize <= 0)
        {
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("max_linesize must be positive")));
        }
 
        text *html_text = PG_GETARG_TEXT_PP(0);
        std::string html = text_to_std_string(html_text);
        std::string plain = html_to_text_basic(html, max_linesize);
 
        PG_RETURN_TEXT_P(cstring_to_text_with_len(plain.data(), plain.size()));
    }
 
    extern "C" Datum
    dbms_report_transform_report_json(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_transform_report_json", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_transform_report_xml(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_transform_report_xml", PG_NARGS());
        PG_RETURN_NULL();
    }
 
    extern "C" Datum
    dbms_report_unescape_report_ref(PG_FUNCTION_ARGS)
    {
        if (PG_ARGISNULL(0))
            PG_RETURN_NULL();
 
        text *input_text = PG_GETARG_TEXT_PP(0);
        std::string input = text_to_std_string(input_text);
        std::string output;
        output.reserve(input.size());
 
        for (size_t i = 0; i < input.size(); ++i)
        {
            char ch = input[i];
            if (ch == '+')
            {
                output.push_back(' ');
                continue;
            }
 
            if (ch == '%')
            {
                if (i + 2 >= input.size())
                {
                    ereport(ERROR,
                            (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                             errmsg("invalid escaped report reference")));
                }
 
                int hi = hex_nibble(input[i + 1]);
                int lo = hex_nibble(input[i + 2]);
                if (hi < 0 || lo < 0)
                {
                    ereport(ERROR,
                            (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                             errmsg("invalid escaped report reference")));
                }
 
                output.push_back((char)((hi << 4) | lo));
                i += 2;
                continue;
            }
 
            output.push_back(ch);
        }
 
        PG_RETURN_TEXT_P(cstring_to_text_with_len(output.data(), output.size()));
    }
 
    extern "C" Datum
    dbms_report_validate_ref_parameter(PG_FUNCTION_ARGS)
    {
        bool is_name = false;
        if (PG_NARGS() > 1 && !PG_ARGISNULL(1))
            is_name = PG_GETARG_BOOL(1);
 
        /*
         * Поведение оставлено максимально совместимым с практическими
         * проверками в Oracle: строго не допускается только NULL-имя
         * параметра. Для значения параметра NULL допускается.
         */
        if (is_name && PG_ARGISNULL(0))
        {
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("invalid reference parameter name")));
        }
 
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_validate_report(PG_FUNCTION_ARGS)
    {
        dbms_report_raise_not_implemented("dbms_report_validate_report", PG_NARGS());
        PG_RETURN_VOID();
    }
 
    extern "C" Datum
    dbms_report_zlib2base64_clob(PG_FUNCTION_ARGS)
    {
        if (PG_ARGISNULL(0))
            PG_RETURN_NULL();
 
        text* input_text = PG_GETARG_TEXT_PP(0);
        std::string input_str = text_to_std_string(input_text);
 
        std::string compressed = zlib_compress(input_str);
 
        /*
         * Второй байт заголовка устанавливается в 0x01
         * для согласования результата с Oracle.
         */
        if (compressed.size() >= 2) {
            compressed[1] = 0x01;
        }
 
        std::string base64 = base64_encode_bytes(compressed);
 
        PG_RETURN_TEXT_P(cstring_to_text_with_len(base64.data(), base64.size()));
    }
 
    extern "C" Datum
    dbms_report_zlib2base64_report_xml(PG_FUNCTION_ARGS)
    {
        if (PG_ARGISNULL(0))
            PG_RETURN_NULL();
 
        /*
         * В текущей реализации аргумент принимается как text-представление XML.
         * Поведение сжатия и кодирования соответствует zlib2base64_clob.
         */
        text* input_text = PG_GETARG_TEXT_PP(0);
        std::string input_str = text_to_std_string(input_text);
 
        std::string compressed = zlib_compress(input_str);
 
        /*
         * Второй байт заголовка устанавливается в 0x01
         * для согласования результата с Oracle.
         */
        if (compressed.size() >= 2) {
            compressed[1] = 0x01;
        }
 
        std::string base64 = base64_encode_bytes(compressed);
 
        PG_RETURN_TEXT_P(cstring_to_text_with_len(base64.data(), base64.size()));
    }
 
/// @brief Возвращает версию RUDB пакета DBMS_REPORT (Oracle DBMS_REPORT пакет)
extern "C" Datum dbms_report_get_version(PG_FUNCTION_ARGS) {
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_REPORT_VERSION));
}
 
/*
* Извлекает строковое значение поля из JSON-объекта.
* Возвращает text или NULL.
* Учитывает, что поле может быть строкой в кавычках или простым значением.
*/
extern "C" Datum dbms_report_extract_string_value(PG_FUNCTION_ARGS)
{
    char search[256];
    text *json_text = PG_GETARG_TEXT_P(0);
    text *key_text = PG_GETARG_TEXT_P(1);
    char *json = text_to_cstring(json_text);
    char *key = text_to_cstring(key_text);
 
    snprintf(search, sizeof(search), "\"%s\"", key);
    const char *p = strstr(json, search);
    if (!p) {
        pfree(json);
        pfree(key);
        PG_RETURN_NULL();
    }
    p += strlen(search);
    while (*p && isspace((unsigned char)*p)) p++;
    if (*p != ':') {
        pfree(json);
        pfree(key);
        PG_RETURN_NULL();
    }
    p++;
    while (*p && isspace((unsigned char)*p)) p++;
 
    if (*p == '"')
    {
        p++;
        const char *end = strchr(p, '"');
        if (!end) return NULL;
        int len = end - p;
        char *val = (char *) palloc(len + 1);
        memcpy(val, p, len);
        val[len] = '\0';
        pfree(json);
        pfree(key);
        text *result = cstring_to_text(val);
        pfree(val);
        PG_RETURN_TEXT_P(result);
    }
    else
    {
        /* Число, true, false, null */
        const char *end = p;
        while (*end && *end != ',' && *end != '}' && !isspace((unsigned char)*end))
            end++;
        int len = end - p;
        char *val = (char *) palloc(len + 1);
        memcpy(val, p, len);
        val[len] = '\0';
        pfree(json);
        pfree(key);
        text *result = cstring_to_text(val);
        pfree(val);
        PG_RETURN_TEXT_P(result);
    }
}