Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2026-06-19 0cfc87bd32822e5ba22d8c2b1a26fa60f63ad7fa
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
#include "dbms_sqlset.hpp"
 
extern "C"
{
#include "access/htup_details.h"
#include "access/tupdesc.h"
#include "catalog/pg_type_d.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/numeric.h"
#include "utils/typcache.h"
#include "miscadmin.h"
} // extern "C"
 
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cerrno>
#include <cstdlib>
#include <iterator>
#include <limits>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
 
namespace
{
constexpr int32 kDbmsSqlsetModeReplaceOldStats = 1;
constexpr int32 kDbmsSqlsetModeAccumulateStats = 2;
constexpr char kDbmsSqlsetHasRecursiveSql[] = "Y";
constexpr char kDbmsSqlsetNoRecursiveSql[] = "N";
constexpr int32 kDbmsSqlsetSingleExecution = 1;
constexpr int32 kDbmsSqlsetAllExecutions = 2;
constexpr int32 kDbmsSqlsetLimitedCommandType = 1;
constexpr int32 kDbmsSqlsetAllCommandType = 2;
constexpr int32 kDbmsSqlsetStsStgtab102Version = 1;
constexpr int32 kDbmsSqlsetStsStgtab111Version = 2;
constexpr int32 kDbmsSqlsetStsStgtab112Version = 3;
constexpr int32 kDbmsSqlsetStsStgtab121Version = 5;
constexpr int32 kDbmsSqlsetStsStgtab122Version = 6;
 
enum class SqlsetFieldKind
{
    Text,
    Numeric,
    Raw
};
 
struct SqlsetFieldDef
{
    const char* name;
    SqlsetFieldKind kind;
    bool updateable;
    bool accumulable;
    bool basic_visible;
    Oid type_oid;
};
 
struct SqlsetRow
{
    std::string sql_id;
    int64 plan_hash_value = -1;
    std::unordered_map<std::string, std::optional<std::string>> scalar_fields;
};
 
struct Sqlset
{
    std::string owner;
    std::optional<std::string> description;
    std::vector<SqlsetRow> rows;
    std::unordered_map<std::string, size_t> row_index;
};
 
enum class SqlsetLoadOption
{
    Insert,
    Update,
    Merge
};
 
enum class SqlsetUpdateOption
{
    Replace,
    Accumulate
};
 
enum class SqlsetAttributeList
{
    Basic,
    Typical,
    All
};
 
std::unordered_map<std::string, Sqlset>& sqlset_store();
std::string build_sqlset_key(const std::string& owner, const std::string& name);
 
constexpr SqlsetFieldDef kSqlsetFieldDefs[] = {
    {"sql_id", SqlsetFieldKind::Text, false, false, true, TEXTOID},
    {"force_matching_signature", SqlsetFieldKind::Numeric, true, false, true, NUMERICOID},
    {"sql_text", SqlsetFieldKind::Text, false, false, true, TEXTOID},
    {"parsing_schema_name", SqlsetFieldKind::Text, false, false, true, TEXTOID},
    {"module", SqlsetFieldKind::Text, false, false, true, TEXTOID},
    {"action", SqlsetFieldKind::Text, false, false, true, TEXTOID},
    {"elapsed_time", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"cpu_time", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"buffer_gets", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"disk_reads", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"direct_writes", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"rows_processed", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"fetches", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"executions", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"end_of_fetch_count", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"optimizer_cost", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID},
    {"optimizer_env", SqlsetFieldKind::Raw, true, false, false, BYTEAOID},
    {"priority", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID},
    {"command_type", SqlsetFieldKind::Numeric, true, false, true, NUMERICOID},
    {"first_load_time", SqlsetFieldKind::Text, true, false, false, TEXTOID},
    {"stat_period", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"active_stat_period", SqlsetFieldKind::Numeric, true, true, false, NUMERICOID},
    {"other", SqlsetFieldKind::Text, true, false, false, TEXTOID},
    {"plan_hash_value", SqlsetFieldKind::Numeric, false, false, true, NUMERICOID},
    {"con_dbid", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID},
    {"last_exec_start_time", SqlsetFieldKind::Text, true, false, false, TEXTOID},
    {"sharable_mem", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID},
    {"exact_matching_signature", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID},
    {"result_cache_executions", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID},
    {"sql_profile", SqlsetFieldKind::Text, true, false, false, TEXTOID},
    {"sql_plan_baseline", SqlsetFieldKind::Text, true, false, false, TEXTOID},
    {"sql_patch", SqlsetFieldKind::Text, true, false, false, TEXTOID},
    {"avg_hard_parse_time", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID},
    {"user_io_wait_time", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID},
    {"io_interconnect_bytes", SqlsetFieldKind::Numeric, true, false, false, NUMERICOID},
    {"parsing_user_name", SqlsetFieldKind::Text, false, false, false, TEXTOID},
};
 
constexpr size_t kSqlsetFieldCount = sizeof(kSqlsetFieldDefs) / sizeof(kSqlsetFieldDefs[0]);
} // namespace
 
extern "C"
{
PG_FUNCTION_INFO_V1(dbms_sqlset_mode_replace_old_stats);
PG_FUNCTION_INFO_V1(dbms_sqlset_mode_accumulate_stats);
PG_FUNCTION_INFO_V1(dbms_sqlset_has_recursive_sql);
PG_FUNCTION_INFO_V1(dbms_sqlset_no_recursive_sql);
PG_FUNCTION_INFO_V1(dbms_sqlset_single_execution);
PG_FUNCTION_INFO_V1(dbms_sqlset_all_executions);
PG_FUNCTION_INFO_V1(dbms_sqlset_limited_command_type);
PG_FUNCTION_INFO_V1(dbms_sqlset_all_command_type);
PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_10_2_version);
PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_11_1_version);
PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_11_2_version);
PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_12_1_version);
PG_FUNCTION_INFO_V1(dbms_sqlset_sts_stgtab_12_2_version);
PG_FUNCTION_INFO_V1(dbms_sqlset_get_version);
PG_FUNCTION_INFO_V1(dbms_sqlset_add_reference);
PG_FUNCTION_INFO_V1(dbms_sqlset_create_sqlset);
PG_FUNCTION_INFO_V1(dbms_sqlset_select_cursor_cache);
PG_FUNCTION_INFO_V1(dbms_sqlset_select_sqlpa_task);
PG_FUNCTION_INFO_V1(dbms_sqlset_select_sqlset);
PG_FUNCTION_INFO_V1(dbms_sqlset_normalize_attribute_list);
PG_FUNCTION_INFO_V1(dbms_sqlset_select_sql_trace);
PG_FUNCTION_INFO_V1(dbms_sqlset_select_workload_repository_0);
PG_FUNCTION_INFO_V1(dbms_sqlset_select_workload_repository_1);
PG_FUNCTION_INFO_V1(dbms_sqlset_capture_cursor_cache);
PG_FUNCTION_INFO_V1(dbms_sqlset_create_sqlset_proc);
PG_FUNCTION_INFO_V1(dbms_sqlset_create_stgtab);
PG_FUNCTION_INFO_V1(dbms_sqlset_delete_sqlset);
PG_FUNCTION_INFO_V1(dbms_sqlset_drop_sqlset);
PG_FUNCTION_INFO_V1(dbms_sqlset_drop_sqlset_by_prefix);
PG_FUNCTION_INFO_V1(dbms_sqlset_load_sqlset);
PG_FUNCTION_INFO_V1(dbms_sqlset_pack_stgtab);
PG_FUNCTION_INFO_V1(dbms_sqlset_remap_stgtab);
PG_FUNCTION_INFO_V1(dbms_sqlset_remove_reference);
PG_FUNCTION_INFO_V1(dbms_sqlset_unpack_stgtab);
PG_FUNCTION_INFO_V1(dbms_sqlset_update_sqlset_0);
PG_FUNCTION_INFO_V1(dbms_sqlset_update_sqlset_1);
PG_FUNCTION_INFO_V1(dbms_sqlset_update_sqlset_2);
 
/// @brief Версия RUDB пакета DBMS_SQLSET (Oracle DBMS_SQLSET пакет)
#define RUDB_DBMS_SQLSET_VERSION "1.0.0"
} // extern "C"
 
namespace
{
const SqlsetFieldDef*
find_field_def(const char* name)
{
    for (const SqlsetFieldDef& field : kSqlsetFieldDefs)
    {
        if (pg_strcasecmp(field.name, name) == 0)
            return &field;
    }
 
    return nullptr;
}
 
std::string
text_to_std_string(const text* value)
{
    char* cstring_value = text_to_cstring(value);
    std::string result(cstring_value);
    pfree(cstring_value);
    return result;
}
 
std::optional<std::string>
pg_arg_text_optional(FunctionCallInfo fcinfo, int argno)
{
    if (argno >= fcinfo->nargs || PG_ARGISNULL(argno))
        return std::nullopt;
 
    std::string value = text_to_std_string(PG_GETARG_TEXT_PP(argno));
    if (value.empty())
        return std::nullopt;
 
    return value;
}
 
std::optional<Numeric>
pg_arg_numeric_optional(FunctionCallInfo fcinfo, int argno)
{
    if (argno >= fcinfo->nargs || PG_ARGISNULL(argno))
        return std::nullopt;
 
    return PG_GETARG_NUMERIC(argno);
}
 
std::string
current_user_name()
{
    const char* user_name = GetUserNameFromId(GetUserId(), false);
    return user_name != nullptr ? user_name : "";
}
 
std::optional<std::string>
normalize_owner_argument(const std::optional<std::string>& owner_argument)
{
    if (!owner_argument.has_value() || owner_argument->empty())
        return current_user_name();
 
    if (pg_strcasecmp(owner_argument->c_str(), current_user_name().c_str()) != 0)
        return std::nullopt;
 
    return current_user_name();
}
 
std::string
require_sqlset_name(const std::optional<std::string>& name, bool allow_generate, bool& generated,
        const std::string& owner)
{
    generated = false;
 
    if (name.has_value() && !name->empty())
        return *name;
 
    if (!allow_generate)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_NAME),
                errmsg("ORA-13755: invalid \"SQL Tuning Set\" name")));
 
    generated = true;
 
    int64& next_generated_id = []() -> int64& {
        static int64 next_id = 1;
        return next_id;
    }();
 
    std::string generated_name;
    do
    {
        generated_name = "STS_" + std::to_string(next_generated_id++);
    } while (sqlset_store().find(build_sqlset_key(owner, generated_name)) != sqlset_store().end());
 
    return generated_name;
}
 
std::unordered_map<std::string, Sqlset>&
sqlset_store()
{
    static std::unordered_map<std::string, Sqlset> sqlsets;
    return sqlsets;
}
 
std::string
build_sqlset_key(const std::string& owner, const std::string& name)
{
    return owner + '\x1f' + name;
}
 
std::optional<std::string>
canonicalize_numeric_text(const std::optional<std::string>& value)
{
    if (!value.has_value())
        return std::nullopt;
 
    Datum numeric_value = DirectFunctionCall3(numeric_in,
            CStringGetDatum(value->c_str()),
            ObjectIdGetDatum(0),
            Int32GetDatum(-1));
    char* canonical = DatumGetCString(DirectFunctionCall1(numeric_out, numeric_value));
    std::string result(canonical);
    pfree(canonical);
    return result;
}
 
std::string
numeric_to_std_string(Numeric value)
{
    char* numeric_value = DatumGetCString(DirectFunctionCall1(numeric_out, NumericGetDatum(value)));
    std::string result(numeric_value);
    pfree(numeric_value);
    return result;
}
 
Numeric
int32_to_numeric(int32 value)
{
    return DatumGetNumeric(DirectFunctionCall1(int4_numeric, Int32GetDatum(value)));
}
 
Numeric
int64_to_numeric(int64 value)
{
    return DatumGetNumeric(DirectFunctionCall1(int8_numeric, Int64GetDatum(value)));
}
 
bool
numeric_eq_value(Numeric lhs, Numeric rhs)
{
    return DatumGetBool(DirectFunctionCall2(numeric_eq, NumericGetDatum(lhs), NumericGetDatum(rhs)));
}
 
bool
numeric_lt_value(Numeric lhs, Numeric rhs)
{
    return DatumGetBool(DirectFunctionCall2(numeric_lt, NumericGetDatum(lhs), NumericGetDatum(rhs)));
}
 
bool
numeric_gt_value(Numeric lhs, Numeric rhs)
{
    return DatumGetBool(DirectFunctionCall2(numeric_gt, NumericGetDatum(lhs), NumericGetDatum(rhs)));
}
 
bool
numeric_is_integer_value(Numeric value)
{
    Numeric truncated = DatumGetNumeric(DirectFunctionCall2(
        numeric_trunc, NumericGetDatum(value), Int32GetDatum(0)));
    return numeric_eq_value(value, truncated);
}
 
Datum
string_to_datum(const std::string& value, SqlsetFieldKind kind)
{
    switch (kind)
    {
        case SqlsetFieldKind::Text:
            return CStringGetTextDatum(value.c_str());
        case SqlsetFieldKind::Numeric:
            return DirectFunctionCall3(numeric_in,
                CStringGetDatum(value.c_str()),
                ObjectIdGetDatum(0),
                Int32GetDatum(-1));
        case SqlsetFieldKind::Raw:
            return DirectFunctionCall1(byteain, CStringGetDatum(value.c_str()));
    }
 
    return PointerGetDatum(nullptr);
}
 
std::optional<std::string>
datum_to_string(Datum value, Oid type_oid)
{
    Oid output_function = InvalidOid;
    bool type_is_varlena = false;
    getTypeOutputInfo(type_oid, &output_function, &type_is_varlena);
 
    char* text_value = OidOutputFunctionCall(output_function, value);
    std::string result(text_value);
    pfree(text_value);
    return result;
}
 
int64
parse_int64_text(const std::string& text_value, const char* field_name)
{
    errno = 0;
    char* end = nullptr;
    const long long parsed = std::strtoll(text_value.c_str(), &end, 10);
    if (errno != 0 || end == text_value.c_str() || *end != '\0')
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                errmsg("неверное числовое значение для %s: %s", field_name, text_value.c_str())));
 
    return static_cast<int64>(parsed);
}
 
SqlsetRow
parse_sqlset_row_tuple(HeapTuple tuple, TupleDesc tuple_desc);
 
SqlsetRow
parse_sqlset_row_composite(Datum value, Oid type_oid, int32 typmod)
{
    TupleDesc nested_desc = lookup_rowtype_tupdesc_copy(type_oid, typmod);
    HeapTupleHeader header = DatumGetHeapTupleHeader(value);
    HeapTupleData nested_tuple;
    MemSet(&nested_tuple, 0, sizeof(nested_tuple));
    nested_tuple.t_len = HeapTupleHeaderGetDatumLength(header);
    nested_tuple.t_data = header;
    nested_tuple.t_tableOid = InvalidOid;
 
    PG_TRY();
    {
        SqlsetRow row = parse_sqlset_row_tuple(&nested_tuple, nested_desc);
        FreeTupleDesc(nested_desc);
        return row;
    }
    PG_CATCH();
    {
        FreeTupleDesc(nested_desc);
        PG_RE_THROW();
    }
    PG_END_TRY();
}
 
SqlsetRow
parse_sqlset_row_tuple(HeapTuple tuple, TupleDesc tuple_desc)
{
    SqlsetRow row;
 
    if (tuple_desc->natts == 1)
    {
        Form_pg_attribute attr = TupleDescAttr(tuple_desc, 0);
        if (type_is_rowtype(attr->atttypid))
        {
            bool is_null = false;
            Datum composite_value = heap_getattr(tuple, 1, tuple_desc, &is_null);
            if (is_null)
                ereport(ERROR,
                        (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                        errmsg("DBMS_SQLSET.LOAD_SQLSET получил пустую строку SQLSET_ROW")));
 
            return parse_sqlset_row_composite(composite_value, attr->atttypid, attr->atttypmod);
        }
    }
 
    for (int attno = 0; attno < tuple_desc->natts; ++attno)
    {
        Form_pg_attribute attr = TupleDescAttr(tuple_desc, attno);
        if (attr->attisdropped)
            continue;
 
        bool is_null = false;
        Datum value = heap_getattr(tuple, attno + 1, tuple_desc, &is_null);
        const char* field_name = NameStr(attr->attname);
        const SqlsetFieldDef* field = find_field_def(field_name);
 
        if (pg_strcasecmp(field_name, "sql_id") == 0)
        {
            if (!is_null)
                row.sql_id = datum_to_string(value, attr->atttypid).value();
            continue;
        }
 
        if (pg_strcasecmp(field_name, "plan_hash_value") == 0)
        {
            if (is_null)
                ereport(ERROR,
                        (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                        errmsg("DBMS_SQLSET.LOAD_SQLSET требует plan_hash_value")));
 
            row.plan_hash_value =
                parse_int64_text(datum_to_string(value, attr->atttypid).value(), "plan_hash_value");
            continue;
        }
 
        if (pg_strcasecmp(field_name, "object_list") == 0 || pg_strcasecmp(field_name, "bind_data") == 0 ||
            pg_strcasecmp(field_name, "sql_plan") == 0 || pg_strcasecmp(field_name, "bind_list") == 0)
        {
            if (!is_null)
                ereport(ERROR,
                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                        errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает столбец \"%s\"", field_name)));
 
            continue;
        }
 
        if (field == nullptr)
        {
            if (!is_null)
                ereport(ERROR,
                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                        errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает столбец \"%s\"", field_name)));
            continue;
        }
 
        if (is_null)
        {
            row.scalar_fields[field->name] = std::nullopt;
            continue;
        }
 
        std::optional<std::string> field_value = datum_to_string(value, attr->atttypid);
        if (field->kind == SqlsetFieldKind::Numeric)
            field_value = canonicalize_numeric_text(field_value);
 
        row.scalar_fields[field->name] = field_value;
    }
 
    if (row.sql_id.empty())
        ereport(ERROR,
                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                errmsg("DBMS_SQLSET.LOAD_SQLSET требует sql_id")));
 
    if (row.plan_hash_value < 0)
        ereport(ERROR,
                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                errmsg("DBMS_SQLSET.LOAD_SQLSET требует plan_hash_value")));
 
    return row;
}
 
const std::optional<std::string>*
find_scalar_field(const SqlsetRow& row, const char* field_name)
{
    auto it = row.scalar_fields.find(field_name);
    if (it == row.scalar_fields.end())
        return nullptr;
 
    return &it->second;
}
 
std::optional<std::string>*
mutable_scalar_field(SqlsetRow& row, const char* field_name)
{
    auto it = row.scalar_fields.find(field_name);
    if (it == row.scalar_fields.end())
        return nullptr;
 
    return &it->second;
}
 
void
apply_scalar_update(SqlsetRow& existing, const SqlsetRow& incoming, const SqlsetFieldDef& field,
        SqlsetUpdateOption update_option, bool ignore_null)
{
    if (!field.updateable)
        return;
 
    const std::optional<std::string>* source = find_scalar_field(incoming, field.name);
    if (source == nullptr)
        return;
 
    std::optional<std::string>* target = mutable_scalar_field(existing, field.name);
    if (target == nullptr)
        target = &existing.scalar_fields[field.name];
 
    if (!source->has_value())
    {
        if (!ignore_null)
            target->reset();
        return;
    }
 
    if (update_option == SqlsetUpdateOption::Accumulate && field.accumulable)
    {
        if (target->has_value())
        {
            const std::string lhs = canonicalize_numeric_text(*target).value();
            const std::string rhs = canonicalize_numeric_text(*source).value();
            Datum lhs_numeric = DirectFunctionCall3(numeric_in,
                    CStringGetDatum(lhs.c_str()),
                    ObjectIdGetDatum(0),
                    Int32GetDatum(-1));
            Datum rhs_numeric = DirectFunctionCall3(numeric_in,
                    CStringGetDatum(rhs.c_str()),
                    ObjectIdGetDatum(0),
                    Int32GetDatum(-1));
            char* accumulated = DatumGetCString(DirectFunctionCall1(
                numeric_out, DirectFunctionCall2(numeric_add, lhs_numeric, rhs_numeric)));
            *target = std::string(accumulated);
            pfree(accumulated);
        }
        else
        {
            *target = canonicalize_numeric_text(*source);
        }
        return;
    }
 
    *target = *source;
}
 
void
apply_sqlset_row_update(SqlsetRow& existing, const SqlsetRow& incoming, SqlsetUpdateOption update_option,
        bool ignore_null)
{
    for (const SqlsetFieldDef& field : kSqlsetFieldDefs)
        apply_scalar_update(existing, incoming, field, update_option, ignore_null);
}
 
bool
attribute_list_includes_field(SqlsetAttributeList attribute_mode, const SqlsetFieldDef& field)
{
    if (attribute_mode == SqlsetAttributeList::Typical)
        return true;
 
    return field.basic_visible;
}
 
void
fill_sqlset_tuple_values(const SqlsetRow& row,
        SqlsetAttributeList attribute_mode,
        Datum* values,
        bool* nulls)
{
    for (size_t idx = 0; idx < kSqlsetFieldCount; ++idx)
    {
        const SqlsetFieldDef& field = kSqlsetFieldDefs[idx];
        nulls[idx] = false;
 
        if (!attribute_list_includes_field(attribute_mode, field))
        {
            nulls[idx] = true;
            continue;
        }
 
        if (pg_strcasecmp(field.name, "sql_id") == 0)
        {
            values[idx] = CStringGetTextDatum(row.sql_id.c_str());
            continue;
        }
 
        if (pg_strcasecmp(field.name, "plan_hash_value") == 0)
        {
            values[idx] = DirectFunctionCall3(numeric_in,
                    CStringGetDatum(std::to_string(row.plan_hash_value).c_str()),
                    ObjectIdGetDatum(0),
                    Int32GetDatum(-1));
            continue;
        }
 
        if (pg_strcasecmp(field.name, "object_list") == 0 || pg_strcasecmp(field.name, "bind_data") == 0 ||
            pg_strcasecmp(field.name, "sql_plan") == 0 || pg_strcasecmp(field.name, "bind_list") == 0)
        {
            nulls[idx] = true;
            continue;
        }
 
        const std::optional<std::string>* source = find_scalar_field(row, field.name);
        if (source == nullptr || !source->has_value())
        {
            nulls[idx] = true;
            continue;
        }
 
        values[idx] = string_to_datum(source->value(), field.kind);
    }
}
 
std::string
build_row_key(const SqlsetRow& row)
{
    return row.sql_id + '\x1f' + std::to_string(row.plan_hash_value);
}
 
Sqlset*
find_sqlset(const std::string& owner, const std::string& name)
{
    auto& store = sqlset_store();
    auto it = store.find(build_sqlset_key(owner, name));
    if (it == store.end())
        return nullptr;
 
    return &it->second;
}
 
Sqlset&
require_sqlset(const std::string& owner, const std::string& name)
{
    Sqlset* sqlset = find_sqlset(owner, name);
    if (sqlset == nullptr)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_OBJECT),
                errmsg("ORA-13754: \"SQL Tuning Set\" \"%s\" does not exist.",
                name.c_str())));
 
    return *sqlset;
}
 
std::string
normalize_load_option(const std::string& value)
{
    if (pg_strcasecmp(value.c_str(), "INSERT") == 0)
        return "INSERT";
    if (pg_strcasecmp(value.c_str(), "UPDATE") == 0)
        return "UPDATE";
    if (pg_strcasecmp(value.c_str(), "MERGE") == 0)
        return "MERGE";
 
    ereport(ERROR, (errmsg("ORA-13779: invalid load option")));
    return "";
}
 
std::string
normalize_update_option(const std::string& value)
{
    if (pg_strcasecmp(value.c_str(), "REPLACE") == 0)
        return "REPLACE";
    if (pg_strcasecmp(value.c_str(), "ACCUMULATE") == 0)
        return "ACCUMULATE";
 
    ereport(ERROR, (errmsg("ORA-19371: invalid update option")));
    return "";
}
 
SqlsetLoadOption
parse_load_option(const std::optional<std::string>& option)
{
    const std::string normalized = option.has_value() ? normalize_load_option(*option) : "INSERT";
    if (normalized == "INSERT")
        return SqlsetLoadOption::Insert;
    if (normalized == "UPDATE")
        return SqlsetLoadOption::Update;
    return SqlsetLoadOption::Merge;
}
 
SqlsetUpdateOption
parse_update_option(const std::optional<std::string>& option)
{
    const std::string normalized = option.has_value() ? normalize_update_option(*option) : "REPLACE";
    if (normalized == "REPLACE")
        return SqlsetUpdateOption::Replace;
    return SqlsetUpdateOption::Accumulate;
}
 
SqlsetAttributeList
parse_attribute_list(const std::optional<std::string>& option)
{
    if (!option.has_value() || option->empty() || pg_strcasecmp(option->c_str(), "TYPICAL") == 0)
        return SqlsetAttributeList::Typical;
 
    if (pg_strcasecmp(option->c_str(), "BASIC") == 0)
        return SqlsetAttributeList::Basic;
 
    if (pg_strcasecmp(option->c_str(), "ALL") == 0)
        return SqlsetAttributeList::All;
 
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
            errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает attribute_list=\"%s\"",
            option->c_str())));
    return SqlsetAttributeList::Typical;
}
 
const char*
attribute_list_name(const SqlsetAttributeList value)
{
    switch (value)
    {
        case SqlsetAttributeList::Basic:
            return "BASIC";
        case SqlsetAttributeList::Typical:
            return "TYPICAL";
        case SqlsetAttributeList::All:
            return "ALL";
    }
 
    return "TYPICAL";
}
 
void
parse_result_percentage(const std::optional<Numeric>& option)
{
    if (!option.has_value())
        return;
 
    const Numeric one = int32_to_numeric(1);
    if (!numeric_eq_value(*option, one))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает result_percentage")));
}
 
std::optional<int64>
parse_result_limit(const std::optional<Numeric>& option)
{
    if (!option.has_value())
        return std::nullopt;
 
    const Numeric zero = int32_to_numeric(0);
    const Numeric max_value = int64_to_numeric(std::numeric_limits<int64>::max());
    const std::string value_text = numeric_to_std_string(*option);
 
    if (numeric_is_nan(*option) || numeric_lt_value(*option, zero) || numeric_gt_value(*option, max_value) ||
        !numeric_is_integer_value(*option))
    {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                errmsg("ORA-13765: Value \"%s\" is illegal for a result limit.", value_text.c_str())));
    }
 
    return DatumGetInt64(DirectFunctionCall1(numeric_int8, NumericGetDatum(*option)));
}
 
void
validate_select_filters(const std::optional<std::string>& basic_filter,
        const std::optional<std::string>& ranking_measure1,
        const std::optional<std::string>& ranking_measure2,
        const std::optional<std::string>& ranking_measure3,
        const std::optional<std::string>& plan_filter)
{
    if (basic_filter.has_value())
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает basic_filter")));
    if (ranking_measure1.has_value() || ranking_measure2.has_value() || ranking_measure3.has_value())
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает ranking_measure")));
    if (plan_filter.has_value())
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает plan_filter")));
}
 
void
validate_select_sqlset_unsupported_options(const std::optional<std::string>& object_filter,
        const std::optional<std::string>& recursive_sql)
{
    if (object_filter.has_value())
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает object_filter")));
 
    if (!recursive_sql.has_value() || pg_strcasecmp(recursive_sql->c_str(), "HAS_RECURSIVE_SQL") == 0 ||
        pg_strcasecmp(recursive_sql->c_str(), kDbmsSqlsetHasRecursiveSql) == 0 ||
        pg_strcasecmp(recursive_sql->c_str(), "Y") == 0)
        return;
 
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
            errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает recursive_sql")));
}
 
void
validate_load_extras(const std::optional<std::string>& update_condition,
        const std::optional<std::string>& update_attributes,
        bool has_commit_rows)
{
    if (update_condition.has_value())
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает update_condition")));
    if (update_attributes.has_value())
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает update_attributes")));
    if (has_commit_rows)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает commit_rows")));
}
 
std::string
create_sqlset_impl(const std::optional<std::string>& sqlset_name,
        const std::optional<std::string>& description,
        const std::optional<std::string>& sqlset_owner,
        bool allow_generate)
{
    bool generated = false;
    const std::optional<std::string> resolved_owner = normalize_owner_argument(sqlset_owner);
    if (!resolved_owner.has_value())
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.CREATE_SQLSET не поддерживает sqlset_owner вне текущего пользователя")));
 
    const std::string resolved_name = require_sqlset_name(sqlset_name, allow_generate, generated, *resolved_owner);
    (void) generated;
 
    auto& store = sqlset_store();
    const std::string key = build_sqlset_key(*resolved_owner, resolved_name);
    if (store.find(key) != store.end())
        ereport(ERROR,
                (errcode(ERRCODE_DUPLICATE_OBJECT),
                errmsg("ORA-13753: \"SQL Tuning Set\" \"%s\" already exists.",
                resolved_name.c_str())));
 
    Sqlset set;
    set.owner = *resolved_owner;
    set.description = description;
    store.emplace(key, std::move(set));
 
    return resolved_name;
}
 
void
store_sqlset_row(Sqlset& sqlset, SqlsetRow row, SqlsetLoadOption load_option,
        SqlsetUpdateOption update_option, bool ignore_null)
{
    const std::string key = build_row_key(row);
    auto index_it = sqlset.row_index.find(key);
    if (index_it == sqlset.row_index.end())
    {
        if (load_option == SqlsetLoadOption::Update)
            return;
 
        sqlset.row_index.emplace(key, sqlset.rows.size());
        sqlset.rows.push_back(std::move(row));
        return;
    }
 
    if (load_option == SqlsetLoadOption::Insert)
        return;
 
    apply_sqlset_row_update(sqlset.rows[index_it->second], row, update_option, ignore_null);
}
 
void
load_sqlset_impl(const std::optional<std::string>& sqlset_name,
        const std::optional<std::string>& populate_cursor,
        const std::optional<std::string>& load_option,
        const std::optional<std::string>& update_option,
        const std::optional<std::string>& update_condition,
        const std::optional<std::string>& update_attributes,
        bool ignore_null,
        bool has_commit_rows,
        const std::optional<std::string>& sqlset_owner)
{
    if (!sqlset_name.has_value() || sqlset_name->empty())
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_NAME),
                errmsg("ORA-13755: invalid \"SQL Tuning Set\" name")));
 
    const std::optional<std::string> resolved_owner = normalize_owner_argument(sqlset_owner);
    if (!resolved_owner.has_value())
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                errmsg("DBMS_SQLSET.LOAD_SQLSET не поддерживает sqlset_owner вне текущего пользователя")));
 
    validate_load_extras(update_condition, update_attributes, has_commit_rows);
 
    const SqlsetLoadOption parsed_load_option = parse_load_option(load_option);
    const SqlsetUpdateOption parsed_update_option = parse_update_option(update_option);
 
    if (!populate_cursor.has_value() || populate_cursor->empty())
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_CURSOR_NAME),
                errmsg("DBMS_SQLSET.LOAD_SQLSET получил пустой cursor")));
 
    Sqlset& sqlset = require_sqlset(*resolved_owner, *sqlset_name);
 
    if (SPI_connect() != SPI_OK_CONNECT)
        ereport(ERROR, (errmsg("SPI_connect failed")));
 
    Portal portal = SPI_cursor_find(populate_cursor->c_str());
    if (portal == nullptr)
    {
        SPI_finish();
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_CURSOR),
                errmsg("cursor \"%s\" does not exist", populate_cursor->c_str())));
    }
 
    PG_TRY();
    {
        const long fetch_size = 1000;
        for (;;)
        {
            SPI_cursor_fetch(portal, true, fetch_size);
            if (SPI_processed == 0)
                break;
 
            if (SPI_tuptable == nullptr)
                ereport(ERROR, (errmsg("SPI_cursor_fetch returned no tuple table")));
 
            TupleDesc tuple_desc = SPI_tuptable->tupdesc;
            for (uint64 idx = 0; idx < SPI_processed; ++idx)
            {
                HeapTuple tuple = SPI_tuptable->vals[idx];
                SqlsetRow row = parse_sqlset_row_tuple(tuple, tuple_desc);
                store_sqlset_row(sqlset, std::move(row), parsed_load_option, parsed_update_option, ignore_null);
            }
        }
 
        SPI_finish();
    }
    PG_CATCH();
    {
        SPI_finish();
        PG_RE_THROW();
    }
    PG_END_TRY();
}
 
} // namespace
 
Datum dbms_sqlset_mode_replace_old_stats(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetModeReplaceOldStats);
}
 
Datum dbms_sqlset_mode_accumulate_stats(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetModeAccumulateStats);
}
 
Datum dbms_sqlset_has_recursive_sql(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(kDbmsSqlsetHasRecursiveSql));
}
 
Datum dbms_sqlset_no_recursive_sql(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(kDbmsSqlsetNoRecursiveSql));
}
 
Datum dbms_sqlset_single_execution(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetSingleExecution);
}
 
Datum dbms_sqlset_all_executions(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetAllExecutions);
}
 
Datum dbms_sqlset_limited_command_type(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetLimitedCommandType);
}
 
Datum dbms_sqlset_all_command_type(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetAllCommandType);
}
 
Datum dbms_sqlset_sts_stgtab_10_2_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetStsStgtab102Version);
}
 
Datum dbms_sqlset_sts_stgtab_11_1_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetStsStgtab111Version);
}
 
Datum dbms_sqlset_sts_stgtab_11_2_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetStsStgtab112Version);
}
 
Datum dbms_sqlset_sts_stgtab_12_1_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetStsStgtab121Version);
}
 
Datum dbms_sqlset_sts_stgtab_12_2_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsSqlsetStsStgtab122Version);
}
 
Datum dbms_sqlset_get_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_SQLSET_VERSION));
}
 
Datum dbms_sqlset_add_reference(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.ADD_REFERENCE")));
    PG_RETURN_NULL();
}
 
Datum dbms_sqlset_create_sqlset(PG_FUNCTION_ARGS)
{
    const std::optional<std::string> sqlset_name = pg_arg_text_optional(fcinfo, 0);
    const std::optional<std::string> description = pg_arg_text_optional(fcinfo, 1);
    const std::optional<std::string> sqlset_owner = pg_arg_text_optional(fcinfo, 2);
 
    const std::string resolved_name = create_sqlset_impl(sqlset_name, description, sqlset_owner, true);
    PG_RETURN_TEXT_P(cstring_to_text(resolved_name.c_str()));
}
 
Datum dbms_sqlset_select_cursor_cache(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_CURSOR_CACHE")));
    PG_RETURN_NULL();
}
 
Datum dbms_sqlset_select_sqlpa_task(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_SQLPA_TASK")));
    PG_RETURN_NULL();
}
 
Datum dbms_sqlset_select_sqlset(PG_FUNCTION_ARGS)
{
    const std::optional<std::string> sqlset_name = pg_arg_text_optional(fcinfo, 0);
    const std::optional<std::string> basic_filter = pg_arg_text_optional(fcinfo, 1);
    const std::optional<std::string> object_filter = pg_arg_text_optional(fcinfo, 2);
    const std::optional<std::string> ranking_measure1 = pg_arg_text_optional(fcinfo, 3);
    const std::optional<std::string> ranking_measure2 = pg_arg_text_optional(fcinfo, 4);
    const std::optional<std::string> ranking_measure3 = pg_arg_text_optional(fcinfo, 5);
    const std::optional<Numeric> result_percentage = pg_arg_numeric_optional(fcinfo, 6);
    const std::optional<Numeric> result_limit_arg = pg_arg_numeric_optional(fcinfo, 7);
    const std::optional<std::string> attribute_list = pg_arg_text_optional(fcinfo, 8);
    const std::optional<std::string> plan_filter = pg_arg_text_optional(fcinfo, 9);
    const std::optional<std::string> sqlset_owner = pg_arg_text_optional(fcinfo, 10);
    const std::optional<std::string> recursive_sql = pg_arg_text_optional(fcinfo, 11);
 
    if (!sqlset_name.has_value() || sqlset_name->empty())
        ereport(ERROR,
            (errcode(ERRCODE_INVALID_NAME),
             errmsg("ORA-13755: invalid \"SQL Tuning Set\" name")));
 
    const std::optional<std::string> resolved_owner = normalize_owner_argument(sqlset_owner);
    if (!resolved_owner.has_value())
        ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает sqlset_owner вне текущего пользователя")));
 
    validate_select_filters(basic_filter, ranking_measure1, ranking_measure2, ranking_measure3, plan_filter);
    validate_select_sqlset_unsupported_options(object_filter, recursive_sql);
 
    LOCAL_FCINFO(normalize_fcinfo, 1);
    InitFunctionCallInfoData(*normalize_fcinfo, NULL, 1, InvalidOid, NULL, NULL);
 
    if (attribute_list.has_value())
    {
        normalize_fcinfo->args[0].value = CStringGetTextDatum(attribute_list->c_str());
        normalize_fcinfo->args[0].isnull = false;
    }
    else
    {
        normalize_fcinfo->args[0].value = static_cast<Datum>(0);
        normalize_fcinfo->args[0].isnull = true;
    }
 
    Datum normalized_datum = dbms_sqlset_normalize_attribute_list(normalize_fcinfo);
    if (normalize_fcinfo->isnull)
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("DBMS_SQLSET attribute_list normalization returned NULL")));
 
    const std::string normalized_attribute_list =
        text_to_cstring(DatumGetTextPP(normalized_datum));
    const SqlsetAttributeList attribute_mode =
        parse_attribute_list(std::make_optional(normalized_attribute_list));
 
    parse_result_percentage(result_percentage);
    const std::optional<int64> result_limit = parse_result_limit(result_limit_arg);
 
    Sqlset& sqlset = require_sqlset(*resolved_owner, *sqlset_name);
 
    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);
 
    const size_t row_count = sqlset.rows.size();
    const size_t limit = result_limit.has_value()
        ? std::min(static_cast<size_t>(*result_limit), row_count)
        : row_count;
 
    for (size_t idx = 0; idx < limit; ++idx)
    {
        Datum values[kSqlsetFieldCount];
        bool nulls[kSqlsetFieldCount];
        fill_sqlset_tuple_values(sqlset.rows[idx], attribute_mode, values, nulls);
        tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
    }
 
    PG_RETURN_NULL();
}
 
Datum dbms_sqlset_normalize_attribute_list(PG_FUNCTION_ARGS)
{
    const std::optional<std::string> attribute_list = pg_arg_text_optional(fcinfo, 0);
    const SqlsetAttributeList value = parse_attribute_list(attribute_list);
 
    if (value == SqlsetAttributeList::All)
        ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("DBMS_SQLSET.SELECT_SQLSET не поддерживает attribute_list => ALL")));
 
    PG_RETURN_TEXT_P(cstring_to_text(attribute_list_name(value)));
}
 
Datum dbms_sqlset_select_sql_trace(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_SQL_TRACE")));
    PG_RETURN_NULL();
}
 
Datum dbms_sqlset_select_workload_repository_0(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_WORKLOAD_REPOSITORY")));
    PG_RETURN_NULL();
}
 
Datum dbms_sqlset_select_workload_repository_1(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.SELECT_WORKLOAD_REPOSITORY")));
    PG_RETURN_NULL();
}
 
Datum dbms_sqlset_capture_cursor_cache(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.CAPTURE_CURSOR_CACHE")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_create_sqlset_proc(PG_FUNCTION_ARGS)
{
    const std::optional<std::string> sqlset_name = pg_arg_text_optional(fcinfo, 0);
    const std::optional<std::string> description = pg_arg_text_optional(fcinfo, 1);
    const std::optional<std::string> sqlset_owner = pg_arg_text_optional(fcinfo, 2);
 
    (void) create_sqlset_impl(sqlset_name, description, sqlset_owner, false);
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_create_stgtab(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.CREATE_STGTAB")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_delete_sqlset(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.DELETE_SQLSET")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_drop_sqlset(PG_FUNCTION_ARGS)
{
    const std::optional<std::string> sqlset_name = pg_arg_text_optional(fcinfo, 0);
    const std::optional<std::string> sqlset_owner = pg_arg_text_optional(fcinfo, 1);
    const std::optional<std::string> resolved_owner = normalize_owner_argument(sqlset_owner);
 
    if (!sqlset_name.has_value() || sqlset_name->empty())
        ereport(ERROR,
            (errcode(ERRCODE_INVALID_NAME),
             errmsg("ORA-13755: invalid \"SQL Tuning Set\" name")));
 
    if (!resolved_owner.has_value())
        ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("DBMS_SQLSET.DROP_SQLSET не поддерживает sqlset_owner вне текущего пользователя")));
 
    auto& store = sqlset_store();
    auto it = store.find(build_sqlset_key(*resolved_owner, *sqlset_name));
    if (it == store.end())
        ereport(ERROR,
            (errcode(ERRCODE_UNDEFINED_OBJECT),
             errmsg("ORA-13754: \"SQL Tuning Set\" \"%s\" does not exist.",
                sqlset_name->c_str())));
 
    store.erase(it);
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_drop_sqlset_by_prefix(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.DROP_SQLSET_BY_PREFIX")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_load_sqlset(PG_FUNCTION_ARGS)
{
    const std::optional<std::string> sqlset_name = pg_arg_text_optional(fcinfo, 0);
    const std::optional<std::string> populate_cursor = pg_arg_text_optional(fcinfo, 1);
    const std::optional<std::string> load_option = pg_arg_text_optional(fcinfo, 2);
    const std::optional<std::string> update_option = pg_arg_text_optional(fcinfo, 3);
    const std::optional<std::string> update_condition = pg_arg_text_optional(fcinfo, 4);
    const std::optional<std::string> update_attributes = pg_arg_text_optional(fcinfo, 5);
    const bool ignore_null = PG_ARGISNULL(6) ? true : PG_GETARG_BOOL(6);
    const bool has_commit_rows = !PG_ARGISNULL(7);
    const std::optional<std::string> sqlset_owner = pg_arg_text_optional(fcinfo, 8);
 
    load_sqlset_impl(sqlset_name,
        populate_cursor,
        load_option,
        update_option,
        update_condition,
        update_attributes,
        ignore_null,
        has_commit_rows,
        sqlset_owner);
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_pack_stgtab(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.PACK_STGTAB")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_remap_stgtab(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.REMAP_STGTAB")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_remove_reference(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.REMOVE_REFERENCE")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_unpack_stgtab(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.UNPACK_STGTAB")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_update_sqlset_0(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.UPDATE_SQLSET")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_update_sqlset_1(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.UPDATE_SQLSET")));
    PG_RETURN_VOID();
}
 
Datum dbms_sqlset_update_sqlset_2(PG_FUNCTION_ARGS)
{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("Неподдерживаемая compatibility-функция DBMS_SQLSET.UPDATE_SQLSET")));
    PG_RETURN_VOID();
}