Исходный код СУБД 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
#include "dbms_output.hpp"
 
extern "C"
{
#include "utils/builtins.h"
#include "utils/elog.h"
 
#include "funcapi.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "lib/stringinfo.h"
 
#include "utils/memutils.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/datetime.h"
#include "utils/date.h"
#include "utils/timestamp.h"
#include "utils/guc.h"
}
 
extern "C"
{
PG_FUNCTION_INFO_V1(dbms_output_clear_line_buffer);
PG_FUNCTION_INFO_V1(dbms_output_enable);
PG_FUNCTION_INFO_V1(dbms_output_disable);
PG_FUNCTION_INFO_V1(dbms_output_put);
PG_FUNCTION_INFO_V1(dbms_output_new_line);
PG_FUNCTION_INFO_V1(dbms_output_put_line);
PG_FUNCTION_INFO_V1(dbms_output_get_line);
PG_FUNCTION_INFO_V1(dbms_output_get_lines);
 
PG_FUNCTION_INFO_V1(dbms_output_get_version);
 
PG_FUNCTION_INFO_V1(dbms_output_flush_line_buffer);
 
/// @brief Версия RUDB пакета DBMS_OUTPUT (Oracle DBMS_OUTPUT пакет)
#define RUDB_DBMS_OUTPUT_VERSION "1.0.0"
 
#define BUFSIZE_DEFAULT     20000
#define BUFSIZE_MIN         2000
#define BUFSIZE_MAX         1000000
#define BUFSIZE_UNLIMITED   BUFSIZE_MAX
 
static char *main_buffer = NULL;
static int   main_buffer_size = 0;  /* allocated bytes in buffer */
static int   main_buffer_len = 0;   /* used bytes in buffer */
static int   main_buffer_get = 0;   /* retrieved bytes in buffer */
 
static char *line_buffer = NULL;   /* временный буфер для текущей строки (PUT) */
static int   line_buffer_size = 0; /* размер временного буфера */
static int   line_buffer_len = 0;  /* использовано во временном буфере */
 
static void add_str(const char *str, int len);
static void add_text_to_main_buffer(text *str);
static void clear_line_buffer_internal(void);
static void clear_main_buffer_internal(void);
 
static text *raw_datum_to_hex_text(Datum value)
{
    bytea *b = DatumGetByteaPP(value);
    const unsigned char *p = (const unsigned char *) VARDATA_ANY(b);
    const Size n = VARSIZE_ANY_EXHDR(b);
 
    static const char hexdigits[] = "0123456789ABCDEF";
    char *buf = (char *) palloc(n * 2 + 1);
    for (Size i = 0; i < n; ++i)
    {
        buf[i * 2]     = hexdigits[(p[i] >> 4) & 0x0F];
        buf[i * 2 + 1] = hexdigits[p[i] & 0x0F];
    }
    buf[n * 2] = '\0';
 
    text *out = cstring_to_text(buf);
    pfree(buf);
    return out;
}
 
/*
 * Helper: detect whether this C function is invoked via SQL helper wrapper
 * (client-side SQL*Plus-like API) with name "..._p".
 *
 * We intentionally keep DBMS_OUTPUT semantics for non-_p callers (e.g. PL/SQL),
 * and apply client-oriented buffer finalization only for *_p calls.
 */
static bool
called_as_sql_helper(FunctionCallInfo fcinfo, const char *expected_proname)
{
    char *fname;
    bool match = false;
 
    if (!fcinfo || !fcinfo->flinfo)
        return false;
 
    fname = get_func_name(fcinfo->flinfo->fn_oid);
    if (fname && expected_proname && strcmp(fname, expected_proname) == 0)
        match = true;
    if (fname)
        pfree(fname);
    return match;
}
 
/* Внутренняя очистка временного буфера без зависимости от вызова SQL-функции */
static void clear_line_buffer_internal(void)
{
    if (line_buffer != NULL)
    {
        free(line_buffer);
        line_buffer = NULL;
    }
    line_buffer_size = 0;
    line_buffer_len = 0;
}
 
/* Внутренняя очистка основного буфера */
static void clear_main_buffer_internal(void)
{
    if (main_buffer != NULL)
    {
        main_buffer_len = 0;
        main_buffer_get = 0;
        main_buffer[0] = '\0';
    }
}
 
Datum dbms_output_clear_line_buffer(PG_FUNCTION_ARGS)
{
    clear_line_buffer_internal();
    PG_RETURN_VOID();
}
 
/*
 * Aux. buffer functionality
 */
static void add_str(const char *str, int len)
{
    if (main_buffer == NULL)
        return;
 
    /* Discard all buffers if get_line was called. */
    if (main_buffer_get > 0)
    {
        main_buffer_get = 0;
        main_buffer_len = 0;
    }
 
    if (main_buffer_len + len > main_buffer_size)
    {
        ereport(WARNING,
            (errmsg("переполнение буфера"),
             errdetail("Переполнение буфера, предел составляет %d байт", main_buffer_size),
             errhint("Увеличьте размер буфера")));
        return;
    }
 
    memcpy(main_buffer + main_buffer_len, str, len);
    main_buffer_len += len;
    main_buffer[main_buffer_len] = '\0';
}
 
/* Добавление строки в главный буфер */
static void add_text_to_main_buffer(text *str)
{
    char *str_data = text_to_cstring(str);
 
    if (main_buffer != NULL)
    {
        add_str(str_data, strlen(str_data));
        add_str("", 1);
    }
 
    pfree(str_data);
}
 
/* Добавление строки во временный буфер */
static void add_to_line_buffer(const char *str, int len)
{
    if ((main_buffer_len + line_buffer_len + len) > BUFSIZE_MAX)
    {
        ereport(WARNING,
            (errmsg("переполнение буфера"),
             errdetail("Переполнение буфера, предел составляет %d байт", main_buffer_size),
             errhint("Увеличьте размер буфера")));
        return;
    }
 
    if (line_buffer == NULL)
    {
        /* Инициализируем буфер */
        line_buffer_size = len + 1;
        line_buffer = (char*) malloc(line_buffer_size);
        line_buffer_len = 0;
        line_buffer[0] = '\0';
    }
 
    if (line_buffer_len + len >= line_buffer_size)
    {
        /* Увеличиваем буфер */
        int new_size = line_buffer_len + len + 1;
 
        char *new_buffer = (char*) realloc(line_buffer, new_size);
        line_buffer = new_buffer;
        line_buffer_size = new_size;
    }
 
    memcpy(line_buffer + line_buffer_len, str, len);
    line_buffer_len += len;
    line_buffer[line_buffer_len] = '\0';
}
 
static void add_text_to_line_buffer(text *str)
{
    add_to_line_buffer(VARDATA_ANY(str), VARSIZE_ANY_EXHDR(str));
}
 
/* Функция для преобразования любого поддерживаемого типа Datum в текст */
static text *datum_to_text(Datum value, Oid type_id, bool is_null, bool *needs_free)
{
    *needs_free = false;
 
    if (is_null)
    {
        *needs_free = true;
        return cstring_to_text("");
    }
 
    switch (type_id)
    {
        case 9167: /* Oracle RAW */
        {
            *needs_free = true;
            return raw_datum_to_hex_text(value);
        }
        case TEXTOID:
        case VARCHAROID:
        case BPCHAROID:
        {
            *needs_free = false;
            return DatumGetTextPP(value);
        }
        case INT4OID:
        {
            char *str = DatumGetCString(DirectFunctionCall1(int4out, value));
            text *result = cstring_to_text(str);
            pfree(str);
            *needs_free = true;
            return result;
        }
        case INT8OID:
        {
            char *str = DatumGetCString(DirectFunctionCall1(int8out, value));
            text *result = cstring_to_text(str);
            pfree(str);
            *needs_free = true;
            return result;
        }
        case NUMERICOID:
        {
            char *str = DatumGetCString(DirectFunctionCall1(numeric_out, value));
            text *result = cstring_to_text(str);
            pfree(str);
            *needs_free = true;
            return result;
        }
        case FLOAT4OID:
        {
            char *str = DatumGetCString(DirectFunctionCall1(float4out, value));
            text *result = cstring_to_text(str);
            pfree(str);
            *needs_free = true;
            return result;
        }
        case FLOAT8OID:
        {
            char *str = DatumGetCString(DirectFunctionCall1(float8out, value));
            text *result = cstring_to_text(str);
            pfree(str);
            *needs_free = true;
            return result;
        }
        case BOOLOID:
        {
            char *str = DatumGetCString(DirectFunctionCall1(boolout, value));
            text *result = cstring_to_text(str);
            pfree(str);
            *needs_free = true;
            return result;
        }
        case DATEOID:
        {
            DateADT date = DatumGetDateADT(value);
            char result[16];
 
            int jday = date + POSTGRES_EPOCH_JDATE;
            int year, month, day;
            j2date(jday, &year, &month, &day);
 
            const char *months[] = {
                "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
                "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
            };
 
            if (month >= 1 && month <= 12)
                snprintf(result, sizeof(result), "%02d-%s-%02d",
                        day, months[month - 1], year % 100);
            else
                snprintf(result, sizeof(result), "%02d-XXX-%02d", day, year % 100);
 
            text *final_result = cstring_to_text(result);
            *needs_free = true;
            return final_result;
        }
        case TIMESTAMPOID:
        case TIMESTAMPTZOID:
        {
            Timestamp timestamp = DatumGetTimestamp(value);
 
            /* Распаковываем timestamp */
            struct pg_tm tm;
            fsec_t fsec;
            int tz;
            const char *tzn = NULL;
 
            if (type_id == TIMESTAMPTZOID)
            {
                if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) != 0)
                {
                    text *result = cstring_to_text("INVALID TIMESTAMP");
                    *needs_free = true;
                    return result;
                }
            }
            else
            {
                if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) != 0)
                {
                    text *result = cstring_to_text("INVALID TIMESTAMP");
                    *needs_free = true;
                    return result;
                }
            }
 
            /* Форматируем в Oracle-стиле */
            char result[64];
            const char *months[] =
            {
                "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
                "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
            };
 
            const char *ampm = (tm.tm_hour < 12) ? "AM" : "PM";
            int hour12 = (tm.tm_hour % 12 == 0) ? 12 : tm.tm_hour % 12;
 
            int month_index = tm.tm_mon;
            if (month_index >= 1 && month_index <= 12)
            {
                /* Если месяц 1-12, преобразуем в 0-11 */
                month_index = month_index - 1;
            } else if (month_index < 0 || month_index > 11)
                month_index = 0;  /* fallback */
 
            int nanoseconds = fsec * 1000;
 
            snprintf(result, sizeof(result), "%02d-%s-%02d %02d.%02d.%02d.%09d %s",
                    tm.tm_mday, months[month_index],
                    (tm.tm_year + 1900) % 100,
                    hour12, tm.tm_min, tm.tm_sec,
                    nanoseconds, ampm);
 
            text *final_result = cstring_to_text(result);
            *needs_free = true;
            return final_result;
        }
        case TIMEOID:
        case TIMETZOID:
        {
            struct pg_tm tm;
            fsec_t fsec;
            int tz = 0;
            char result[64];
 
            if (type_id == TIMETZOID)
            {
                /* Для TIMETZ разбираем структуру */
                TimeTzADT *timetz = (TimeTzADT *) DatumGetPointer(value);
                TimeADT time = timetz->time;
                tz = timetz->zone;  /* смещение в секундах (положительное к UTC) */
 
                if (time2tm(time, &tm, &fsec) != 0)
                {
                    text *error_result = cstring_to_text("INVALID TIMETZ");
                    *needs_free = true;
                    return error_result;
                }
 
                /* Форматируем с часовым поясом */
                const char *ampm = (tm.tm_hour < 12) ? "AM" : "PM";
                int hour12 = (tm.tm_hour % 12 == 0) ? 12 : tm.tm_hour % 12;
                int nanoseconds = fsec * 1000;
 
                int tz_total_minutes = tz / 60;  /* общее смещение в минутах */
                int tz_hour = tz_total_minutes / 60;
                int tz_minute = abs(tz_total_minutes) % 60;
 
                char tz_sign = (tz >= 0) ? '-' : '+';
 
                snprintf(result, sizeof(result), "%02d.%02d.%02d.%09d %s %c%02d:%02d",
                        hour12, tm.tm_min, tm.tm_sec, nanoseconds, ampm,
                        tz_sign, abs(tz_hour), tz_minute);
            }
            else
            {
                /* Для TIME */
                TimeADT time = DatumGetTimeADT(value);
 
                if (time2tm(time, &tm, &fsec) != 0)
                {
                    text *error_result = cstring_to_text("INVALID TIME");
                    *needs_free = true;
                    return error_result;
                }
 
                const char *ampm = (tm.tm_hour < 12) ? "AM" : "PM";
                int hour12 = (tm.tm_hour % 12 == 0) ? 12 : tm.tm_hour % 12;
                int nanoseconds = fsec * 1000;
 
                snprintf(result, sizeof(result), "%02d.%02d.%02d.%09d %s",
                        hour12, tm.tm_min, tm.tm_sec, nanoseconds, ampm);
            }
 
            text *final_result = cstring_to_text(result);
            *needs_free = true;
            return final_result;
        }
        case INTERVALOID:
        {
            /* Используем встроенную функцию для форматирования interval */
            char *interval_str = DatumGetCString(DirectFunctionCall1(interval_out, value));
 
            /* Преобразуем PostgreSQL формат в Oracle-подобный */
            char result[64];
            int days = 0, hours = 0, minutes = 0, seconds = 0, microsec = 0;
 
            if (sscanf(interval_str, "%d day %d:%d:%d.%d",
                    &days, &hours, &minutes, &seconds, &microsec) == 5)
            {
                snprintf(result, sizeof(result), "%+03d %02d:%02d:%02d.%06d",
                        days, hours, minutes, seconds, microsec);
            }
            else if (sscanf(interval_str, "%d:%d:%d.%d",
                            &hours, &minutes, &seconds, &microsec) == 4)
            {
                snprintf(result, sizeof(result), "+00 %02d:%02d:%02d.%06d",
                        hours, minutes, seconds, microsec);
            }
            else
            {
                /* Если не удалось распарсить, используем как есть */
                strncpy(result, interval_str, sizeof(result) - 1);
                result[sizeof(result) - 1] = '\0';
            }
 
            text *final_result = cstring_to_text(result);
            pfree(interval_str);
            *needs_free = true;
            return final_result;
        }
        default:
        {
            Oid output_function_id;
            bool is_varlena;
 
            /* Получаем информацию о функции вывода для типа */
            getTypeOutputInfo(type_id, &output_function_id, &is_varlena);
 
            /* Проверяем, что функция вывода существует */
            if (!OidIsValid(output_function_id))
            {
                ereport(ERROR,
                    (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                    errmsg("неподдерживаемый тип данных"),
                    errdetail("Тип OID %u не имеет функции вывода", type_id)));
            }
 
            char *str = OidOutputFunctionCall(output_function_id, value);
            text *result = cstring_to_text(str);
            pfree(str);
            *needs_free = true;
            return result;
        }
    }
}
 
/* Основная функция для добавления всех аргументов в буфер */
static void add_all_arguments(FunctionCallInfo fcinfo, const char* mode)
{
    /* Создаем временный буфер для агрегации всех аргументов */
    StringInfoData aggregated;
    initStringInfo(&aggregated);
 
    for (int i = 0; i < PG_NARGS(); i++)
    {
        Oid arg_type = get_fn_expr_argtype(fcinfo->flinfo, i);
 
        if (arg_type == InvalidOid)
        {
            ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("неизвестный тип данных"),
                 errhint("Убедитесь, что передаваемые типы данных поддерживаются")));
        }
 
        bool needs_free = false;
        text *arg_text = datum_to_text(PG_GETARG_DATUM(i), arg_type, PG_ARGISNULL(i), &needs_free);
 
        char *arg_str = text_to_cstring(arg_text);
        appendStringInfoString(&aggregated, arg_str);
        pfree(arg_str);
 
        if (needs_free) pfree(arg_text);
    }
 
    if (aggregated.len > 0)
    {
        text *final_text = cstring_to_text(aggregated.data);
 
        if (strcmp(mode, "put_line") == 0)
        {
            /* Для put_line объединяем накопленные данные из put с текущими аргументами */
            if (line_buffer != NULL && line_buffer_len > 0)
            {
                /* Добавляем текущие аргументы к накопленным данным */
                add_text_to_line_buffer(final_text);
 
                /* Теперь выводим объединенную строку */
                {
                    DirectFunctionCall0(dbms_output_flush_line_buffer);
                }
            }
            else
            {
                /* Если нет накопленных данных, просто выводим текущие аргументы */
                add_text_to_main_buffer(final_text);
            }
        }
        else if (strcmp(mode, "put") == 0)
            add_text_to_line_buffer(final_text);
 
        pfree(final_text);
    }
 
    pfree(aggregated.data);
}
 
/*
 * @qdb_func: dbms_output_enable(int8)
 * @ora_func: DBMS_OUTPUT.ENABLE(NUMBER)
 */
Datum dbms_output_enable(PG_FUNCTION_ARGS)
{
    int64 n_buf_size;
    if (PG_NARGS() == 0)
        n_buf_size = BUFSIZE_DEFAULT;
    else if (PG_ARGISNULL(0))
        n_buf_size = BUFSIZE_UNLIMITED;
    else
    {
        n_buf_size = PG_GETARG_INT64(0);
 
        if (n_buf_size > BUFSIZE_MAX)
        {
            ereport(WARNING,
                (errmsg("указанный размер буфера превышает максимальный"),
                 errdetail("Буфер будет установлен в максимальный размер %d байт", BUFSIZE_MAX),
                 errhint("Максимальный размер буфера ограничен %d байтами", BUFSIZE_MAX)));
            n_buf_size = BUFSIZE_MAX;
        }
        else if (n_buf_size < BUFSIZE_MIN)
        {
            ereport(WARNING,
                (errmsg("указанный размер буфера меньше минимального"),
                 errdetail("Буфер будет установлен в минимальный размер %d байт", BUFSIZE_MIN),
                 errhint("Минимальный размер буфера составляет %d байт", BUFSIZE_MIN)));
            n_buf_size = BUFSIZE_MIN;
        }
    }
 
    /* Если буфер уже активен - перевыделяем память по новому размеру */
    if (main_buffer != NULL)
    {
        int old_size = main_buffer_size;
 
        /* Перевыделяем память */
        char *new_buffer = (char *) realloc(main_buffer, n_buf_size);
        main_buffer = new_buffer;
        main_buffer_size = n_buf_size;
 
        /* Если новый размер больше старого, инициализируем новую память */
        if (n_buf_size > old_size)
        {
            memset(main_buffer + old_size, 0, n_buf_size - old_size);
        }
 
        /* Очищаем содержимое буфера при переинициализации */
        clear_main_buffer_internal();
    }
    else
    {
        /* Первоначальное выделение памяти */
        main_buffer = (char *) malloc(n_buf_size);
        main_buffer_size = n_buf_size;
        main_buffer_len = 0;
        main_buffer_get = 0;
        main_buffer[0] = '\0';
    }
 
    /* Очищаем временный буфер */
    clear_line_buffer_internal();
 
    PG_RETURN_VOID();
}
 
/*
 * @qdb_func: dbms_output_disable()
 * @ora_func: DBMS_OUTPUT.DISABLE()
 */
Datum dbms_output_disable(PG_FUNCTION_ARGS)
{
    if (main_buffer != NULL)
    {
        free(main_buffer);
        main_buffer = NULL;
    }
 
    main_buffer_size = 0;
    main_buffer_len = 0;
    main_buffer_get = 0;
 
    clear_line_buffer_internal();
 
    PG_RETURN_VOID();
}
 
static text *dbms_output_next(void)
{
    if (main_buffer == NULL || main_buffer_len == 0 || main_buffer_get >= main_buffer_len)
        return NULL;
 
    /* Находим начало следующей строки */
    char *line_start = main_buffer + main_buffer_get;
 
    /* Находим конец строки */
    char *line_end = line_start;
    while (line_end < main_buffer + main_buffer_len && *line_end != '\0')
        line_end++;
 
    /* Если не нашли нуль символ или это конец буфера */
    if (line_end >= main_buffer + main_buffer_len || *line_end != '\0')
        return NULL;
 
    /* Длина строки */
    int line_length = line_end - line_start;
 
    /* Создаем text объект */
    text *result = (text *) palloc(line_length + VARHDRSZ);
    SET_VARSIZE(result, line_length + VARHDRSZ);
    memcpy(VARDATA(result), line_start, line_length);
 
    /* Помечаем строку как прочитанную */
    memset(line_start, 0, line_length + 1);
 
    /* Обновляем позицию чтения */
    main_buffer_get = (line_end - main_buffer) + 1;
 
    /* Если дошли до конца буфера - сбрасываем */
    if (main_buffer_get >= main_buffer_len)
        clear_main_buffer_internal();
 
    return result;
}
 
/*
 * @qdb_func: dbms_output_get_line(text, numeric)
 * @ora_func: DBMS_OUTPUT.GET_LINE(VARCHAR2, NUMBER)
 */
Datum dbms_output_get_line(PG_FUNCTION_ARGS)
{
    TupleDesc   tupdesc;
    Datum       result;
    HeapTuple   tuple;
    Datum       values[2];
    bool        nulls[2] = { false, false };
    text       *line;
    bool        is_helper = called_as_sql_helper(fcinfo, "dbms_output_get_line_p");
 
    /* Build a tuple descriptor for our result type */
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "Тип возвращаемого значения должен быть составным типом");
 
    if ((line = dbms_output_next()) != NULL)
    {
        values[0] = PointerGetDatum(line);
        values[1] = Int32GetDatum(0);   /* 0: succeeded */
    }
    else
    {
        /*
         * QDB/SQL*Plus-like behavior: if client is fetching output via helper
         * wrapper (dbms_output_get_line_p) and there are no complete lines,
         * discard any pending partial line accumulated by PUT().
         *
         * This prevents PUT() fragments from leaking across separate SQL
         * statements in interactive clients that fetch output after each
         * statement.
         */
        if (is_helper)
            clear_line_buffer_internal();
        nulls[0] = true;
        values[1] = Int32GetDatum(1);   /* 1: failed */
    }
 
    tuple = heap_form_tuple(tupdesc, values, nulls);
    result = HeapTupleGetDatum(tuple);
 
    PG_RETURN_DATUM(result);
}
 
/*
 * @qdb_func: dbms_output_get_lines(arraytype_p, int4)
 * @ora_func: DBMS_OUTPUT.GET_LINES(LINES PL/SQL_TABLE, NUMBER)
 * @ora_func: DBMS_OUTPUT.GET_LINES(LINES VARRAY, NUMBER)
 */
Datum dbms_output_get_lines(PG_FUNCTION_ARGS)
{
    TupleDesc   tupdesc;
    Datum       result;
    HeapTuple   tuple;
    Datum       values[2];
    bool        nulls[2] = { false, false };
    text       *line;
    bool        is_helper = called_as_sql_helper(fcinfo, "dbms_output_get_lines_p");
    bool        reached_end = false;
 
    ArrayType  *lines_array = PG_GETARG_ARRAYTYPE_P(0);
    int32       max_lines = PG_GETARG_INT32(1);
    int32       n;
    ArrayBuildState *astate = NULL;
 
    /* Build a tuple descriptor for our result type */
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "Тип возвращаемого значения должен быть составным типом");
 
    for (n = 0; n < max_lines; n++)
    {
        line = dbms_output_next();
        if (line == NULL)
        {
            reached_end = true;
            break;
        }
        astate = accumArrayResult(astate, PointerGetDatum(line), false,
                                  TEXTOID, CurrentMemoryContext);
    }
 
    /*
     * Same rationale as in dbms_output_get_line(): if helper wrapper has
     * reached end of available complete lines, drop any pending partial line.
     * Do not do this when we stopped because max_lines was reached.
     */
    if (is_helper && reached_end)
        clear_line_buffer_internal();
 
    /* 0: lines as text array */
    if (n > 0)
        values[0] = makeArrayResult(astate, CurrentMemoryContext);
    else
    {
        int16       typlen;
        bool        typbyval;
        char        typalign;
        ArrayType  *arr;
 
        get_typlenbyvalalign(TEXTOID, &typlen, &typbyval, &typalign);
        arr = construct_md_array(
            NULL,
            NULL,
            0, NULL, NULL, TEXTOID, typlen, typbyval, typalign);
        values[0] = PointerGetDatum(arr);
    }
 
    /* 1: # of lines as integer */
    values[1] = Int32GetDatum(n);
 
    tuple = heap_form_tuple(tupdesc, values, nulls);
    result = HeapTupleGetDatum(tuple);
 
    PG_RETURN_DATUM(result);
}
 
/*
 * @qdb_func: dbms_output_put(variadic)
 * @ora_func: DBMS_OUTPUT.PUT(VARCHAR2)
 */
Datum dbms_output_put(PG_FUNCTION_ARGS)
{
    if (main_buffer != NULL)
        if (PG_NARGS() > 0)
            add_all_arguments(fcinfo, "put");
 
    PG_RETURN_VOID();
}
 
/*
 * @qdb_func: dbms_output_new_line()
 * @ora_func: DBMS_OUTPUT.NEW_LINE()
 */
Datum dbms_output_new_line(PG_FUNCTION_ARGS)
{
    if (main_buffer != NULL)
        DirectFunctionCall0(dbms_output_flush_line_buffer);
 
    PG_RETURN_VOID();
}
 
/*
 * @qdb_func: dbms_output_put_line(variadic)
 * @ora_func: DBMS_OUTPUT.PUT_LINE(VARCHAR2)
 */
Datum dbms_output_put_line(PG_FUNCTION_ARGS)
{
    if (main_buffer != NULL)
    {
        if (PG_NARGS() > 0)
            add_all_arguments(fcinfo, "put_line");
        else
            DirectFunctionCall0(dbms_output_flush_line_buffer);
    }
 
    PG_RETURN_VOID();
}
 
/// @brief Возвращает версию RUDB пакета DBMS_OUTPUT (Oracle DBMS_OUTPUT пакет)
Datum dbms_output_get_version(PG_FUNCTION_ARGS) {
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_OUTPUT_VERSION));
}
 
/* Отправка временного буфера в основной буфер */
Datum dbms_output_flush_line_buffer(PG_FUNCTION_ARGS)
{
    if (line_buffer != NULL && line_buffer_len > 0)
    {
        text *message = cstring_to_text(line_buffer);
        add_text_to_main_buffer(message);
        pfree(message);
 
        line_buffer_len = 0;
        line_buffer[0] = '\0';
    }
 
    PG_RETURN_VOID();
}
 
} // extern "C"