Исходный код СУБД 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
#include "dbms_tns.hpp"
 
extern "C"
{
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/guc.h"
#include "miscadmin.h"
#include "utils/varlena.h"
#include "varatt.h"
} // extern "C"
 
#include <cctype>
#include <algorithm>
#include <fstream>
#include <iterator>
#include <unordered_map>
#include <string>
#include <string_view>
#include <vector>
#include <unistd.h>
 
namespace
{
enum class SqlnetSource
{
    Tnsnames,
    Ezconnect
};
 
enum class SqlnetParseStatus
{
    MissingConfig,
    ParsedOk,
    Malformed
};
 
struct SqlnetParseResult
{
    SqlnetParseStatus status;
    std::vector<SqlnetSource> sources;
};
 
enum class TnsnamesParseStatus
{
    MissingConfig,
    ParsedOk,
    Malformed
};
 
struct TnsnamesParseResult
{
    TnsnamesParseStatus status;
    std::unordered_map<std::string, std::string> aliases;
};
 
constexpr std::string_view kSqlnetDirectoryPathParam = "NAMES.DIRECTORY_PATH";
constexpr std::string_view kSqlnetConfigFile = "sqlnet.ora";
constexpr std::string_view kTnsnamesConfigFile = "tnsnames.ora";
constexpr std::string_view kTnsnamesToken = "TNSNAMES";
constexpr std::string_view kEzconnectToken = "EZCONNECT";
constexpr std::string_view kCidProgram = "rudb";
 
static std::string lower_copy(std::string_view input);
static bool case_insensitive_equals(std::string_view lhs, std::string_view rhs);
static size_t skip_spaces(const std::string& input, size_t pos);
static bool match_param_name(const std::string& input, size_t pos, std::string_view needle);
static std::string tnsnames_config_path();
 
/*
 * Внутренняя схема разбора Oracle Net configuration для DBMS_TNS.
 *
 * Здесь держим private parser/resolver для `dbms_tns_resolve_tnsname(text)`.
 * Он читает только `sqlnet.ora` и `tnsnames.ora` из каталога
 * `dbms_tns.tns_admin`, не делает сетевых проверок и не эмулирует полный
 * Oracle Net stack.
 *
 * 1. `sqlnet.ora`
 *    Parser ищет только `NAMES.DIRECTORY_PATH`. Из списка sources
 *    используются только `TNSNAMES` и `EZCONNECT`, остальные значения
 *    игнорируются. Если синтаксис `NAMES.DIRECTORY_PATH` повреждён, resolver
 *    возвращает SQL NULL.
 *
 * 2. `tnsnames.ora`
 *    Parser читает top-level записи вида
 *
 *        ALIAS[, ALIAS2] = (DESCRIPTION=...)
 *
 *    Alias сравниваются без учёта регистра. Если один alias встречается
 *    несколько раз, используется последняя запись. Descriptor собирается как
 *    сбалансированный блок скобок и сохраняется как pass-through text:
 *    сетевые параметры и порядок `ADDRESS` / `DESCRIPTION` не
 *    интерпретируются.
 *
 * 3. Scanner descriptor-а
 *    Сканер считает баланс круглых скобок, учитывает quoted text и
 *    нормализует whitespace вне quoted values. Символ `#` внутри quoted value
 *    не считается началом комментария. Незакрытые quotes или
 *    несбалансированные скобки считаются malformed input и приводят к SQL
 *    NULL.
 *
 * 4. Easy Connect
 *    Поддерживаются только простые формы
 *
 *        //host/service
 *        //host:port/service
 *        host/service
 *        host:port/service
 *
 *    Parser не выполняет DNS lookup, не открывает TCP-соединение, не
 *    проверяет listener/service availability, не нормализует localhost и не
 *    добавляет CID / descriptor decoration вне текущего локального правила.
 */
 
static inline bool is_space(unsigned char ch)
{
    return std::isspace(static_cast<int>(ch)) != 0;
}
 
static inline bool is_token_boundary(char ch)
{
    return ch == '\0' ||
           (!std::isalnum(static_cast<unsigned char>(ch)) && ch != '_' && ch != '.');
}
 
static inline bool is_quote_char(char ch)
{
    return ch == '\'' || ch == '"';
}
 
// Удаляет # line comments, но сохраняет # внутри quoted values.
static std::string strip_line_comments(const std::string& input)
{
    std::string output;
    output.reserve(input.size());
    bool in_comment = false;
    bool in_quote = false;
    char quote_char = '\0';
 
    for (char ch : input)
    {
        if (in_comment)
        {
            if (ch == '\n' || ch == '\r')
            {
                in_comment = false;
                output.push_back(ch);
            }
            continue;
        }
 
        if (in_quote)
        {
            output.push_back(ch);
            if (ch == quote_char)
            {
                in_quote = false;
                quote_char = '\0';
            }
            continue;
        }
 
        if (is_quote_char(ch))
        {
            in_quote = true;
            quote_char = ch;
            output.push_back(ch);
            continue;
        }
 
        if (ch == '#')
        {
            in_comment = true;
            continue;
        }
 
        output.push_back(ch);
    }
 
    return output;
}
 
static std::string lower_copy(std::string_view input)
{
    std::string output;
    output.reserve(input.size());
 
    for (char ch : input)
        output.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(ch))));
 
    return output;
}
 
static bool cid_decoration_enabled()
{
    // CID включаем только по явному session marker в selfcheck, чтобы HOST/USER
    // не меняли обычный regression output.
    const char* appname = GetConfigOptionByName("application_name", NULL, false);
    return appname != nullptr && case_insensitive_equals(appname, "dbms_tns_cid");
}
 
static std::string cid_host_name()
{
    char buffer[256] = {0};
    if (gethostname(buffer, sizeof(buffer)) != 0 || buffer[0] == '\0')
        return "unknown";
 
    buffer[sizeof(buffer) - 1] = '\0';
    return buffer;
}
 
static std::string cid_user_name()
{
    const char* user = GetUserNameFromId(GetUserId(), false);
    if (user == nullptr || user[0] == '\0')
        return "unknown";
 
    return user;
}
 
static std::string build_cid_block()
{
    std::string cid;
    cid.reserve(64);
    cid.append("(CID=(PROGRAM=");
    cid.append(kCidProgram.data(), kCidProgram.size());
    cid.append(")(HOST=");
    cid.append(cid_host_name());
    cid.append(")(USER=");
    cid.append(cid_user_name());
    cid.append("))");
    return cid;
}
 
static bool find_matching_paren(const std::string& input, size_t open_pos, size_t& close_pos)
{
    if (open_pos >= input.size() || input[open_pos] != '(')
        return false;
 
    int depth = 0;
    bool in_quote = false;
    char quote_char = '\0';
 
    for (size_t pos = open_pos; pos < input.size(); ++pos)
    {
        const char ch = input[pos];
 
        if (in_quote)
        {
            if (ch == quote_char)
            {
                in_quote = false;
                quote_char = '\0';
            }
            continue;
        }
 
        if (is_quote_char(ch))
        {
            in_quote = true;
            quote_char = ch;
            continue;
        }
 
        if (ch == '(')
        {
            ++depth;
        }
        else if (ch == ')')
        {
            --depth;
            if (depth < 0)
                return false;
 
            if (depth == 0)
            {
                close_pos = pos;
                return true;
            }
        }
    }
 
    return false;
}
 
static bool descriptor_has_top_level_cid(const std::string& input, size_t open_pos, size_t close_pos)
{
    (void) close_pos;
    bool in_quote = false;
    char quote_char = '\0';
 
    for (size_t pos = open_pos + 1; pos < input.size(); ++pos)
    {
        const char ch = input[pos];
 
        if (in_quote)
        {
            if (ch == quote_char)
            {
                in_quote = false;
                quote_char = '\0';
            }
            continue;
        }
 
        if (is_quote_char(ch))
        {
            in_quote = true;
            quote_char = ch;
            continue;
        }
 
        if (ch == '(' && pos + 5 <= input.size() &&
            case_insensitive_equals(std::string_view(input).substr(pos + 1, 4), "CID="))
        {
            return true;
        }
    }
 
    return false;
}
 
static bool find_connect_data_group(const std::string& descriptor, size_t& open_pos, size_t& close_pos)
{
    bool in_quote = false;
    char quote_char = '\0';
 
    for (size_t pos = 0; pos < descriptor.size(); ++pos)
    {
        const char ch = descriptor[pos];
 
        if (in_quote)
        {
            if (ch == quote_char)
            {
                in_quote = false;
                quote_char = '\0';
            }
            continue;
        }
 
        if (is_quote_char(ch))
        {
            in_quote = true;
            quote_char = ch;
            continue;
        }
 
        if (!match_param_name(descriptor, pos, "CONNECT_DATA"))
            continue;
 
        size_t after = pos + std::string_view("CONNECT_DATA").size();
        after = skip_spaces(descriptor, after);
        if (after >= descriptor.size() || descriptor[after] != '=')
            continue;
 
        ++after;
        after = skip_spaces(descriptor, after);
        if (after >= descriptor.size() || descriptor[after] != '(')
            continue;
 
        open_pos = after;
        return find_matching_paren(descriptor, open_pos, close_pos);
    }
 
    return false;
}
 
static std::string decorate_descriptor_with_cid(const std::string& descriptor)
{
    if (!cid_decoration_enabled())
        return descriptor;
 
    size_t open_pos = 0;
    size_t close_pos = 0;
    if (!find_connect_data_group(descriptor, open_pos, close_pos))
        return descriptor;
 
    if (descriptor_has_top_level_cid(descriptor, open_pos, close_pos))
        return descriptor;
 
    const std::string cid = build_cid_block();
    std::string decorated;
    decorated.reserve(descriptor.size() + cid.size());
    decorated.append(descriptor, 0, close_pos);
    decorated.append(cid);
    decorated.append(descriptor, close_pos, std::string::npos);
    return decorated;
}
 
static bool case_insensitive_equals(std::string_view lhs, std::string_view rhs)
{
    if (lhs.size() != rhs.size())
        return false;
 
    for (size_t i = 0; i < lhs.size(); ++i)
    {
        const unsigned char left = static_cast<unsigned char>(lhs[i]);
        const unsigned char right = static_cast<unsigned char>(rhs[i]);
        if (std::tolower(left) != std::tolower(right))
            return false;
    }
 
    return true;
}
 
// Формирует descriptor для поддержанных простых Easy Connect строк.
static bool try_parse_easy_connect_descriptor(std::string_view input,
    std::string& descriptor)
{
    descriptor.clear();
 
    if (input.empty())
        return false;
 
    for (char ch : input)
    {
        if (is_space(static_cast<unsigned char>(ch)))
            return false;
    }
 
    if (input.size() >= 2 && input[0] == '/' && input[1] == '/')
        input.remove_prefix(2);
 
    if (input.empty())
        return false;
 
    const size_t slash_pos = input.find('/');
    if (slash_pos == std::string_view::npos)
        return false;
 
    const std::string_view host_port = input.substr(0, slash_pos);
    const std::string_view service = input.substr(slash_pos + 1);
    if (host_port.empty() || service.find('/') != std::string_view::npos)
        return false;
 
    std::string_view host = host_port;
    std::string_view port = "1521";
    const size_t colon_pos = host_port.find(':');
    if (colon_pos != std::string_view::npos)
    {
        if (host_port.find(':', colon_pos + 1) != std::string_view::npos)
            return false;
 
        host = host_port.substr(0, colon_pos);
        port = host_port.substr(colon_pos + 1);
        if (host.empty() || port.empty())
            return false;
    }
 
    if (host.empty())
        return false;
 
    descriptor.reserve(host.size() + port.size() + service.size() + 64);
    descriptor.append("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=");
    descriptor.append(host.data(), host.size());
    descriptor.append(")(PORT=");
    descriptor.append(port.data(), port.size());
    descriptor.append("))(CONNECT_DATA=(SERVICE_NAME=");
    descriptor.append(service.data(), service.size());
    descriptor.append(")))");
    return true;
}
 
static size_t skip_spaces(const std::string& input, size_t pos)
{
    while (pos < input.size() && is_space(static_cast<unsigned char>(input[pos])))
        ++pos;
 
    return pos;
}
 
static bool match_param_name(const std::string& input, size_t pos, std::string_view needle)
{
    if (pos > input.size() || input.size() - pos < needle.size())
        return false;
 
    if (pos > 0 && !is_token_boundary(input[pos - 1]))
        return false;
 
    if (pos + needle.size() < input.size() && !is_token_boundary(input[pos + needle.size()]))
        return false;
 
    return case_insensitive_equals(std::string_view(input).substr(pos, needle.size()), needle);
}
 
// Разбирает значение NAMES.DIRECTORY_PATH=(...).
static bool collect_directory_path(const std::string& input, size_t name_pos,
                                   SqlnetParseResult& result)
{
    size_t pos = name_pos + kSqlnetDirectoryPathParam.size();
    pos = skip_spaces(input, pos);
 
    if (pos >= input.size() || input[pos] != '=')
        return false;
 
    ++pos;
    pos = skip_spaces(input, pos);
    if (pos >= input.size() || input[pos] != '(')
        return false;
 
    ++pos;
    bool saw_closing_paren = false;
 
    while (pos < input.size())
    {
        pos = skip_spaces(input, pos);
        if (pos >= input.size())
            return false;
 
        if (input[pos] == ')')
        {
            saw_closing_paren = true;
            ++pos;
            break;
        }
 
        if (input[pos] == ',')
        {
            ++pos;
            continue;
        }
 
        const size_t token_start = pos;
        while (pos < input.size())
        {
            const char ch = input[pos];
            if (is_space(static_cast<unsigned char>(ch)) || ch == ',' || ch == ')')
                break;
            ++pos;
        }
 
        if (pos == token_start)
            return false;
 
        const std::string_view token(input.data() + token_start, pos - token_start);
        if (case_insensitive_equals(token, kTnsnamesToken))
            result.sources.push_back(SqlnetSource::Tnsnames);
        else if (case_insensitive_equals(token, kEzconnectToken))
            result.sources.push_back(SqlnetSource::Ezconnect);
 
        pos = skip_spaces(input, pos);
        if (pos < input.size() && input[pos] == ',')
        {
            ++pos;
            continue;
        }
 
        if (pos < input.size() && input[pos] == ')')
        {
            saw_closing_paren = true;
            ++pos;
            break;
        }
 
        if (pos < input.size())
        {
            const char next = input[pos];
            if (!std::isalpha(static_cast<unsigned char>(next)))
                return false;
        }
    }
 
    if (!saw_closing_paren)
        return false;
 
    result.status = SqlnetParseStatus::ParsedOk;
    return true;
}
 
// Разбирает левую часть tnsnames.ora entry: ALIAS[, ALIAS2].
static bool parse_tnsnames_aliases(std::string_view aliases_text,
                                   std::vector<std::string>& aliases)
{
    aliases.clear();
 
    size_t pos = 0;
    while (pos < aliases_text.size())
    {
        size_t begin = pos;
        while (begin < aliases_text.size() && is_space(static_cast<unsigned char>(aliases_text[begin])))
            ++begin;
 
        size_t end = begin;
        while (end < aliases_text.size() && aliases_text[end] != ',')
            ++end;
 
        while (end > begin && is_space(static_cast<unsigned char>(aliases_text[end - 1])))
            --end;
 
        if (end == begin)
            return false;
 
        aliases.push_back(lower_copy(aliases_text.substr(begin, end - begin)));
 
        if (end >= aliases_text.size())
            break;
 
        pos = end + 1;
    }
 
    return !aliases.empty();
}
 
// Собирает descriptor как balanced parentheses block.
static bool collect_tnsnames_descriptor(const std::string& input, size_t pos,
                                        std::string& descriptor, size_t& next_pos)
{
    descriptor.clear();
 
    if (pos >= input.size() || input[pos] != '(')
        return false;
 
    int depth = 0;
    bool in_quote = false;
    char quote_char = '\0';
    while (pos < input.size())
    {
        const char ch = input[pos];
        ++pos;
 
        if (!in_quote && is_space(static_cast<unsigned char>(ch)))
            continue;
 
        descriptor.push_back(ch);
        if (in_quote)
        {
            if (ch == quote_char)
            {
                in_quote = false;
                quote_char = '\0';
            }
            continue;
        }
 
        if (is_quote_char(ch))
        {
            in_quote = true;
            quote_char = ch;
            continue;
        }
 
        if (ch == '(')
        {
            ++depth;
        }
        else if (ch == ')')
        {
            --depth;
            if (depth < 0)
                return false;
 
            if (depth == 0)
            {
                if (in_quote)
                    return false;
 
                next_pos = pos;
                return true;
            }
        }
    }
 
    return !in_quote && depth == 0;
}
 
// Разбирает одну top-level запись tnsnames.ora.
static bool parse_tnsnames_entry(const std::string& input, size_t entry_start,
                                 TnsnamesParseResult& result, size_t& next_pos)
{
    const size_t eq_pos = input.find('=', entry_start);
    if (eq_pos == std::string::npos)
        return false;
 
    size_t aliases_end = eq_pos;
    while (aliases_end > entry_start &&
           is_space(static_cast<unsigned char>(input[aliases_end - 1])))
        --aliases_end;
 
    const std::string_view aliases_text(input.data() + entry_start, aliases_end - entry_start);
    std::vector<std::string> aliases;
    if (!parse_tnsnames_aliases(aliases_text, aliases))
        return false;
 
    size_t pos = skip_spaces(input, eq_pos + 1);
    std::string descriptor;
    if (!collect_tnsnames_descriptor(input, pos, descriptor, next_pos))
        return false;
 
    for (const std::string& alias : aliases)
        result.aliases[alias] = descriptor;
 
    result.status = TnsnamesParseStatus::ParsedOk;
    return true;
}
 
// Возвращает порядок поддержанных naming sources из sqlnet.ora.
static SqlnetParseResult parse_sqlnet_ora(const std::string& input)
{
    SqlnetParseResult result{SqlnetParseStatus::ParsedOk, {}};
    const std::string cleaned = strip_line_comments(input);
    const std::string_view needle = kSqlnetDirectoryPathParam;
 
    for (size_t pos = 0; pos < cleaned.size(); ++pos)
    {
        if (!match_param_name(cleaned, pos, needle))
            continue;
 
        if (!collect_directory_path(cleaned, pos, result))
        {
            result.status = SqlnetParseStatus::Malformed;
            result.sources.clear();
        }
 
        return result;
    }
 
    return result;
}
 
// Возвращает map нормализованных aliases к descriptor text.
static TnsnamesParseResult parse_tnsnames_ora(const std::string& input)
{
    TnsnamesParseResult result{TnsnamesParseStatus::ParsedOk, {}};
    const std::string cleaned = strip_line_comments(input);
 
    for (size_t pos = 0; pos < cleaned.size(); )
    {
        pos = skip_spaces(cleaned, pos);
        if (pos >= cleaned.size())
            break;
 
        size_t next_pos = pos;
        if (!parse_tnsnames_entry(cleaned, pos, result, next_pos))
        {
            result.status = TnsnamesParseStatus::Malformed;
            result.aliases.clear();
            return result;
        }
 
        pos = next_pos;
    }
 
    return result;
}
 
static SqlnetParseResult read_sqlnet_config()
{
    const char* tns_admin = GetConfigOptionByName("dbms_tns.tns_admin", NULL, false);
    if (tns_admin == NULL || tns_admin[0] == '\0')
        return {SqlnetParseStatus::MissingConfig, {}};
 
    std::string config_path(tns_admin);
    if (!config_path.empty() && config_path.back() != '/' && config_path.back() != '\\')
        config_path.push_back('/');
    config_path.append(kSqlnetConfigFile);
 
    std::ifstream file(config_path);
    if (!file.is_open())
        return {SqlnetParseStatus::MissingConfig, {}};
 
    std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    return parse_sqlnet_ora(contents);
}
 
static TnsnamesParseResult read_tnsnames_config()
{
    const std::string config_path = tnsnames_config_path();
    if (config_path.empty())
        return {TnsnamesParseStatus::MissingConfig, {}};
 
    std::ifstream file(config_path);
    if (!file.is_open())
        return {TnsnamesParseStatus::MissingConfig, {}};
 
    std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    return parse_tnsnames_ora(contents);
}
 
static std::string tnsnames_config_path()
{
    const char* tns_admin = GetConfigOptionByName("dbms_tns.tns_admin", NULL, false);
    if (tns_admin == NULL || tns_admin[0] == '\0')
        return {};
 
    std::string config_path(tns_admin);
    if (!config_path.empty() && config_path.back() != '/' && config_path.back() != '\\')
        config_path.push_back('/');
    config_path.append(kTnsnamesConfigFile);
    return config_path;
}
} // namespace
 
extern "C"
{
 
PG_FUNCTION_INFO_V1(dbms_tns_resolve_tnsname);
PG_FUNCTION_INFO_V1(dbms_tns_has_tnsnames_config);
PG_FUNCTION_INFO_V1(dbms_tns_get_version);
 
/// @brief Версия RUDB пакета DBMS_TNS (Oracle DBMS_TNS пакет)
#define RUDB_DBMS_TNS_VERSION "1.0.0"
 
/*
 * @qdb_func: dbms_tns_resolve_tnsname(text)
 */
Datum dbms_tns_resolve_tnsname(PG_FUNCTION_ARGS)
{
    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 errmsg("must be superuser to call %s()",
                        "dbms_tns_resolve_tnsname")));
 
    if (PG_ARGISNULL(0))
        PG_RETURN_NULL();
 
    const text *tns_name = PG_GETARG_TEXT_PP(0);
    if (VARSIZE_ANY_EXHDR(tns_name) == 0)
        PG_RETURN_NULL();
 
    const SqlnetParseResult sqlnet = read_sqlnet_config();
    if (sqlnet.status != SqlnetParseStatus::ParsedOk)
        PG_RETURN_NULL();
 
    const std::string_view input_text(VARDATA_ANY(tns_name), VARSIZE_ANY_EXHDR(tns_name));
    bool tnsnames_loaded = false;
    TnsnamesParseResult tnsnames;
 
    for (const SqlnetSource source : sqlnet.sources)
    {
        switch (source)
        {
            case SqlnetSource::Ezconnect:
            {
                std::string descriptor;
                if (try_parse_easy_connect_descriptor(input_text, descriptor))
                {
                    descriptor = decorate_descriptor_with_cid(descriptor);
                    PG_RETURN_TEXT_P(cstring_to_text(descriptor.c_str()));
                }
                break;
            }
 
            case SqlnetSource::Tnsnames:
            {
                if (!tnsnames_loaded)
                {
                    const bool has_tnsnames = DatumGetBool(
                        DirectFunctionCall0(dbms_tns_has_tnsnames_config));
                    if (!has_tnsnames)
                        break;
 
                    tnsnames = read_tnsnames_config();
                    if (tnsnames.status != TnsnamesParseStatus::ParsedOk)
                        break;
 
                    tnsnames_loaded = true;
                }
 
                const std::string alias = lower_copy(input_text);
                const auto found = tnsnames.aliases.find(alias);
                if (found != tnsnames.aliases.end())
                {
                    std::string descriptor = decorate_descriptor_with_cid(found->second);
                    PG_RETURN_TEXT_P(cstring_to_text(descriptor.c_str()));
                }
                break;
            }
        }
    }
 
    PG_RETURN_NULL();
}
 
/*
 * @qdb_func: dbms_tns_has_tnsnames_config()
 */
Datum dbms_tns_has_tnsnames_config(PG_FUNCTION_ARGS)
{
    const std::string config_path = tnsnames_config_path();
    if (config_path.empty())
        PG_RETURN_BOOL(false);
 
    std::ifstream file(config_path);
    PG_RETURN_BOOL(file.is_open());
}
 
Datum dbms_tns_get_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_TNS_VERSION));
}
 
} // extern "C"