Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2026-04-30 9f2ef60949ced4fab4d077a7e1c6d913f3620c9b
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
#include "postgres.h"
 
#include "catalog/pg_type.h"
 
#include "replication/logical.h"
#include "replication/origin.h"
 
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/catcache.h"
#include "utils/timestamp.h"
#include "utils/cash.h"
#include "utils/pg_locale.h"
#include "utils/date.h"
#include "utils/datetime.h"
 
#include "mchar.h"
 
PG_MODULE_MAGIC;
 
 
static Oid MCHAROID = InvalidOid;
static Oid MVARCHAROID = InvalidOid;
static const char cQuoteChar = '\'';
static const char cContinueChar = '!';
 
extern PGDLLEXPORT void _PG_init(void);
extern PGDLLEXPORT void _PG_output_plugin_init(OutputPluginCallbacks* cb);
 
typedef struct
{
    MemoryContext context;
    int record_buf_size;
    //Заказанный размер записи
    int prepare_header_size;
    //Размер заголовка, который записывает OutputPluginPrepareWrite в ctx->out
    bool include_xids;
    //флаг Записывать идентификатор транзакции
    bool skip_change;
    //флаг пропустить все, ничего не выводить
    bool xact_wrote_changes;
    //Признак того, что старт транзакции уже выведен.
} DecodingData;
 
static void decode_startup(LogicalDecodingContext* ctx,
    OutputPluginOptions* opt, bool is_init);
static void decode_shutdown(LogicalDecodingContext* ctx
    );
static void decode_begin_txn(LogicalDecodingContext* ctx,
    ReorderBufferTXN* txn);
static void decode_commit_txn(LogicalDecodingContext* ctx,
    ReorderBufferTXN* txn, XLogRecPtr commit_lsn);
static void decode_change(LogicalDecodingContext* ctx,
    ReorderBufferTXN* txn, Relation rel, ReorderBufferChange* change);
static void decode_truncate(LogicalDecodingContext* ctx,
    ReorderBufferTXN* txn, int nrelations, Relation relations[],
    ReorderBufferChange* change);
static bool filter_by_origin(LogicalDecodingContext *ctx,
    RepOriginId origin_id);
 
#ifndef U8_TRUNCATE_IF_INCOMPLETE
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
*   Copyright (C) 1999-2015, International Business Machines
*   Corporation and others.  All Rights Reserved.
*
*******************************************************************************
*   file name:  utf8.h
*   encoding:   UTF-8
*   tab size:   8 (not used)
*   indentation:4
*
*   created on: 1999sep13
*   created by: Markus W. Scherer
*/
#define U8_LEAD4_T1_BITS \
"\x00\x00\x00\x00\x00\x00\x00\x00\x1E\x0F\x0F\x0F\x00\x00\x00\x00"
#define U8_IS_VALID_LEAD4_AND_T1(lead, t1) \
(U8_LEAD4_T1_BITS[(uint8_t)(t1)>>4]&(1<<((lead)&7)))
#define U8_LEAD3_T1_BITS \
"\x20\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x10\x30\x30"
#define U8_IS_VALID_LEAD3_AND_T1(lead, t1) \
(U8_LEAD3_T1_BITS[(lead)&0xf]&(1<<((uint8_t)(t1)>>5)))
#define U8_TRUNCATE_IF_INCOMPLETE(s, start, length) { \
    if((length)>(start)) { \
        uint8_t __b1=s[(length)-1]; \
        if(U8_IS_SINGLE(__b1)) { \
            /* common ASCII character */ \
        } else if(U8_IS_LEAD(__b1)) { \
            --(length); \
        } else if(U8_IS_TRAIL(__b1) && ((length)-2)>=(start)) { \
            uint8_t __b2=s[(length)-2]; \
            if(0xe0<=__b2 && __b2<=0xf4) { \
                if(__b2<0xf0 ? U8_IS_VALID_LEAD3_AND_T1(__b2, __b1) : \
                        U8_IS_VALID_LEAD4_AND_T1(__b2, __b1)) { \
                    (length)-=2; \
                } \
            } else if(U8_IS_TRAIL(__b2) && ((length)-3)>=(start)) { \
                uint8_t __b3=s[(length)-3]; \
                if(0xf0<=__b3 && __b3<=0xf4 && \
                    U8_IS_VALID_LEAD4_AND_T1(__b3, __b2)) { \
                    (length)-=3; \
                } \
            } \
        } \
    } \
}
 
#endif
 
void _PG_init(void)
{
}
 
void _PG_output_plugin_init(OutputPluginCallbacks* cb)
{
    AssertVariableIsOfType(&_PG_output_plugin_init, LogicalOutputPluginInit);
 
    cb->startup_cb = decode_startup;
    cb->begin_cb = decode_begin_txn;
    cb->change_cb = decode_change;
    cb->truncate_cb = decode_truncate;
    cb->commit_cb = decode_commit_txn;
    cb->shutdown_cb = decode_shutdown;
    cb->filter_by_origin_cb = filter_by_origin;
}
 
static bool tryExtractBoolOption(DefElem* elem, const char* name, bool* dest)
{
    if (strcmp(elem->defname, name) == 0)
    {
        if (elem->arg != NULL)
        {
            if (!parse_bool(strVal(elem->arg), dest))
                ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                    errmsg("could not parse value \"%s\" for parameter \"%s\"",
                        strVal(elem->arg), elem->defname)));
        }
        return true;
    }
    else
        return false;
}
 
static bool tryExtractIntOption(DefElem* elem, const char* name, int32* dest)
{
    if (strcmp(elem->defname, name) == 0)
    {
        if (elem->arg != NULL)
            *dest = pg_strtoint32(strVal(elem->arg));
        return true;
    }
    else
        return false;
}
 
static void readTypeOID(char* typeName, Oid* typeOid)
{
    if (*typeOid == InvalidOid)
    {
        CatCList* catlist = SearchSysCacheList(TYPENAMENSP,
            1, CStringGetDatum(typeName), 0, 0);
        if (catlist->n_members == 1)
            *typeOid = ((Form_pg_type)GETSTRUCT(
                &catlist->members[0]->tuple))->oid;
        ReleaseSysCacheList(catlist);
 
        if (*typeOid == InvalidOid)
            elog(WARNING, "OID of type %s not defined!", typeName);
    }
}
 
static void decode_startup(LogicalDecodingContext* ctx,
    OutputPluginOptions* opt, bool is_init)
{
    ListCell* option;
    DecodingData* data = palloc0(sizeof(DecodingData));
 
    data->include_xids = true;
    data->skip_change = false;
    data->record_buf_size = ALLOCSET_DEFAULT_MAXSIZE / 4;
    foreach(option, ctx->output_plugin_options)
    {
        DefElem* elem = lfirst(option);
        Assert(elem->arg == NULL || IsA(elem->arg, String));
 
        if (!tryExtractBoolOption(elem, "include-xids",
            &data->include_xids))
            if (!tryExtractBoolOption(elem, "skip-change",
                &data->skip_change))
                if (!tryExtractIntOption(elem, "slice_size",
                    &data->record_buf_size))
                {
                    ereport(ERROR,
                        (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                            errmsg("option \"%s\" = \"%s\" is unknown",
                            elem->defname,
                            elem->arg ? strVal(elem->arg) : "(null)")
                        )
                    );
                }
    }
    data->context = AllocSetContextCreate(ctx->context,
        "text conversion context",
        ALLOCSET_DEFAULT_SIZES);
    ctx->output_plugin_private = data;
 
    opt->output_type = OUTPUT_PLUGIN_TEXTUAL_OUTPUT;
    opt->receive_rewrites = false;
}
 
static void decode_shutdown(LogicalDecodingContext* ctx)
{
    DecodingData* data = ctx->output_plugin_private;
 
    MemoryContextDelete(data->context);
}
 
static bool filter_by_origin(LogicalDecodingContext *ctx,
    RepOriginId origin_id)
{
    DecodingData* data = ctx->output_plugin_private;
    return data && data->skip_change;
}
 
static void decode_begin_txn(LogicalDecodingContext* ctx,
    ReorderBufferTXN* txn)
{
    DecodingData* data = ctx->output_plugin_private;
 
    data->xact_wrote_changes = false;
}
 
static void decode_commit_txn(LogicalDecodingContext* ctx,
    ReorderBufferTXN* txn, XLogRecPtr commit_lsn)
{
    DecodingData* data = ctx->output_plugin_private;
 
    if (!data->xact_wrote_changes || data->skip_change)
        return;
 
    OutputPluginPrepareWrite(ctx, true);
    if (data->include_xids)
        appendStringInfo(ctx->out, "C %u", txn->xid);
    else
        appendStringInfo(ctx->out, "C");
    OutputPluginWrite(ctx, true);
}
 
static int record_buf_size(LogicalDecodingContext* ctx) {
    return ((DecodingData*)(ctx->output_plugin_private))->record_buf_size;
}
 
static void prepareFlushedCtx(LogicalDecodingContext* ctx)
{
    ctx->out->len = 0;
    OutputPluginPrepareWrite(ctx, true);
    ((DecodingData*)(ctx->output_plugin_private)
    )->prepare_header_size = ctx->out->len;
}
 
static int checkFlushCtx(LogicalDecodingContext* ctx, int toWriteSize)
{   //возвращает максимальное число байт,
    //которое можно записать до превышения лимита длинны
    int overflowRemain = record_buf_size(ctx) - ctx->out->len - 1;
    if (overflowRemain <= toWriteSize)
    {
        appendStringInfoChar(ctx->out, cContinueChar);
        switch (((DecodingData*)(ctx->output_plugin_private)
                )->prepare_header_size)
        {
        case 0:
            break;
        case 1 + sizeof(int64) * 3:
            memset(&ctx->out->data[1], 0, sizeof(int64) * 2);
            break;
        default:
            ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                    errmsg("Unsupported ctx->prepare_write function!")));
 
        }
        OutputPluginWrite(ctx, false);
        prepareFlushedCtx(ctx);
        return record_buf_size(ctx) - ctx->out->len - 1;
    }
    else
        return overflowRemain;
}
 
static void printByts(LogicalDecodingContext* ctx, Datum val)
{
    const char n[] = { "0123456789abcdef" };
    const int cDig = 16;
    char* bytsData = VARDATA(val);
    int32 bytsLen = VARSIZE_ANY_EXHDR(val);
    int resultSize = 3 + bytsLen * 2 + 1; //остаток, который требуется записать
    int overflowRemain = checkFlushCtx(ctx, 3);
    if (resultSize > overflowRemain)
        enlargeStringInfo(ctx->out, overflowRemain);
    else
        enlargeStringInfo(ctx->out, resultSize);
 
    appendStringInfoString(ctx->out, "\'\\x");
    overflowRemain -= 3;
    resultSize -= 3;
 
    {
        int32 i;
        for (i = 0; i < bytsLen; ++i)
        {
            int x;
            if (overflowRemain < 2)
            {
                overflowRemain = checkFlushCtx(ctx, 2);
                if (resultSize > overflowRemain)
                    enlargeStringInfo(ctx->out, overflowRemain);
                else
                    enlargeStringInfo(ctx->out, resultSize);
            }
            x = bytsData[i] & 255;
            ctx->out->data[ctx->out->len] = n[x / cDig];
            ctx->out->data[ctx->out->len + 1] = n[x % cDig];
            ctx->out->len += 2;
            overflowRemain -= 2;
            resultSize -= 2;
        }
    }
    if (overflowRemain < 1)
        checkFlushCtx(ctx, 1);
    appendStringInfoChar(ctx->out, cQuoteChar);
}
 
static bool truncateIfIncmoplete(const int maxCharSize, const char* str, int* len)
{
    if (maxCharSize == 1)
        return true;
    else
    {
        int dbEnc = GetDatabaseEncoding();
        if (dbEnc == PG_UTF8)
        {
            U8_TRUNCATE_IF_INCOMPLETE(str, 0, *len);
            return (len > 0);
        }
        else
        {   //медленный экзотичный вариант
            int truncCount;
            for (truncCount = 1; truncCount < maxCharSize; ++truncCount)
            {
                int charLen;
                for (charLen = 1;
                    charLen <= maxCharSize && *len >= charLen;
                    ++charLen)
                    if (pg_verify_mbstr(dbEnc, &str[*len - charLen],
                                        charLen, true))
                        return true;
 
                --(*len);
            }
        }
    }
 
    return false;
}
 
static void printCharVarchar(LogicalDecodingContext* ctx, Datum val)
{
    const int maxCharSize = pg_database_encoding_max_length();
    char* bytsData = VARDATA(val);
    int32 bytsLen = VARSIZE_ANY_EXHDR(val);
    int overflowRemain = checkFlushCtx(ctx, 1 + maxCharSize);
 
    appendStringInfoChar(ctx->out, cQuoteChar);
    --overflowRemain;
    {
        char* pBegin = bytsData;
        int L = 0;
        int i;
        for (i = 0; i < bytsLen; ++i)
        {
            bool overflow;
            ++L;
            overflow = (L >= overflowRemain);
            if (bytsData[i] == cQuoteChar || overflow || i + 1 == bytsLen)
            {
                if (overflow &&
                    !(bytsData[i] == cQuoteChar || i + 1 == bytsLen))
                {
                    if (!truncateIfIncmoplete(maxCharSize, pBegin, &L))
 
                        ereport(ERROR,
                            (errcode(ERRCODE_INVALID_CHARACTER_VALUE_FOR_CAST),
                                errmsg("invalid string value")
                            )
                        );
                }
                appendBinaryStringInfo(ctx->out, pBegin, L);
                pBegin += L;
                if (bytsData[i] == cQuoteChar)
                {
                    overflowRemain = checkFlushCtx(ctx, maxCharSize+1);
                    appendStringInfoChar(ctx->out, bytsData[i]);
                    --overflowRemain;
                }
                else if (overflow) //гарантированный сброс буфера
                    overflowRemain = checkFlushCtx(ctx, record_buf_size(ctx));
                else
                    overflowRemain = checkFlushCtx(ctx, maxCharSize);
                L = 0;
            }
 
        }
    }
    if (overflowRemain < 1)
        checkFlushCtx(ctx, 1);
    appendStringInfoChar(ctx->out, cQuoteChar);
}
 
static int printM(const UChar* wordsData,
    int wordsLen, LogicalDecodingContext* ctx)
{
    const int maxCharSize = pg_database_encoding_max_length();
    const UChar cQuoteUChar = L'\'';
    int overflowRemain = checkFlushCtx(ctx, 1 + maxCharSize);
 
    appendStringInfoChar(ctx->out, cQuoteChar);
    --overflowRemain;
    {
        const UChar* pBegin = wordsData;
        int L = 0;
        int i;
        for (i = 0; i < wordsLen; ++i)
        {
            bool overflow;
            ++L;
            overflow = (L*maxCharSize >= overflowRemain);
            if (wordsData[i] == cQuoteUChar ||
                overflow ||
                i + 1 == wordsLen)
            {
                if (overflow &&
                    !(wordsData[i] == cQuoteUChar || i + 1 == wordsLen))
                {
                    if (U16_IS_LEAD(wordsData[i]))
                        --L;
 
                    if (L == 0 || (i > 0 && U16_IS_LEAD(wordsData[i - 1])))
                        ereport(ERROR,
                            (errcode(ERRCODE_INVALID_CHARACTER_VALUE_FOR_CAST),
                                errmsg("invalid utf16 string value")
                            )
                        );
                }
                enlargeStringInfo(ctx->out, L * maxCharSize);
                ctx->out->len += UChar2Char(pBegin, L,
                    &ctx->out->data[ctx->out->len]);
                pBegin += L;
 
                if (wordsData[i] == cQuoteUChar)
                {
                    overflowRemain = checkFlushCtx(ctx, maxCharSize+1);
                    appendStringInfoChar(ctx->out, cQuoteChar);
                    --overflowRemain;
                }
                else if (overflow)
                    overflowRemain = checkFlushCtx(ctx, record_buf_size(ctx));
                else
                    overflowRemain = checkFlushCtx(ctx, maxCharSize);
                L = 0;
            }
        }
    }
    return overflowRemain;
}
 
static void printMVarchar(LogicalDecodingContext* ctx, Datum val)
{
    const UChar* pBegin = (UChar*)(DatumGetPointer(val) + MVARCHARHDRSZ);
    if (printM(pBegin, UVARCHARLENGTH(val), ctx) < 1)
        checkFlushCtx(ctx, 1);
    appendStringInfoChar(ctx->out, cQuoteChar);
}
 
static void printMChar(LogicalDecodingContext* ctx, Datum val)
{
    const UChar* pBegin = (UChar*)(DatumGetPointer(val) + MCHARHDRSZ);
    int32  trailBlanksCount =
        DatumGetMChar(val)->typmod - u_countChar32(pBegin, UCHARLENGTH(val));
    int overflowRemain = printM(pBegin, UCHARLENGTH(val), ctx);
    while (trailBlanksCount > 0)
    {
 
        if (trailBlanksCount > overflowRemain)
        {
            appendStringInfoSpaces(ctx->out, overflowRemain);
            trailBlanksCount -= overflowRemain;
            overflowRemain = checkFlushCtx(ctx, 1);
        }
        else
        {
            appendStringInfoSpaces(ctx->out, trailBlanksCount);
            overflowRemain -= trailBlanksCount;
            trailBlanksCount = 0;
        }
    }
    if (overflowRemain < 1)
        checkFlushCtx(ctx, 1);
    appendStringInfoChar(ctx->out, cQuoteChar);
}
 
static void appendCtxString(LogicalDecodingContext* ctx, char* str)
{
    int l = strlen(str);
    checkFlushCtx(ctx, l);
    appendBinaryStringInfo(ctx->out, str, l);
}
 
static void printTimestamp(LogicalDecodingContext* ctx, Datum val)
{
    Timestamp ts = DatumGetTimestamp(val);
    if (!TIMESTAMP_NOT_FINITE(ts))
    {
        struct pg_tm tm;
        fsec_t      fsec;
        if (timestamp2tm(ts, NULL, &tm, &fsec, NULL, NULL) == 0)
        {   //отсутствие в параметрах указателя на tz
            //приводит к конвертации часов (ts with timezone)
            //например было 10:23:54.123+02 получим 08:23:54
            char* str;
            checkFlushCtx(ctx, 14);
            enlargeStringInfo(ctx->out, 14);
            str = ctx->out->data + ctx->out->len;
            ctx->out->len += 14;
            str = pg_ultostr_zeropad(str,
                (tm.tm_year > 0) ? tm.tm_year : -(tm.tm_year - 1), 4);
            str = pg_ultostr_zeropad(str, tm.tm_mon, 2);
            str = pg_ultostr_zeropad(str, tm.tm_mday, 2);
            str = pg_ultostr_zeropad(str, tm.tm_hour, 2);
            str = pg_ultostr_zeropad(str, tm.tm_min, 2);
            str = pg_ultostr_zeropad(str, abs(tm.tm_sec), 2);
            return;
        }
    }
    appendCtxString(ctx, "'invalid timestamp'");
}
 
static void printDate(LogicalDecodingContext* ctx, Datum val)
{
    DateADT d = DatumGetDateADT(val);
    if (!DATE_NOT_FINITE(d))
    {
        char* str;
        int year, mon, day;
        j2date(d + POSTGRES_EPOCH_JDATE, &year, &mon, &day);
        checkFlushCtx(ctx, 8);
        enlargeStringInfo(ctx->out, 8);
        str = ctx->out->data + ctx->out->len;
        ctx->out->len += 8;
        str = pg_ultostr_zeropad(str, (year > 0) ? year : -(year - 1), 4);
        str = pg_ultostr_zeropad(str, mon, 2);
        str = pg_ultostr_zeropad(str, day, 2);
        return;
    }
    appendCtxString(ctx, "'invalid date'");
}
 
static void printTime(LogicalDecodingContext* ctx, Datum val)
{
    TimeADT t = DatumGetTimeADT(val);
    char* str;
    struct pg_tm tm;
    fsec_t      fsec;
    time2tm(t, &tm, &fsec);
    checkFlushCtx(ctx, 14);
    enlargeStringInfo(ctx->out, 14);
    str = ctx->out->data + ctx->out->len;
    ctx->out->len += 14;
    str = pg_ultostr_zeropad(str, 0, 4);
    str = pg_ultostr_zeropad(str, 0, 2);
    str = pg_ultostr_zeropad(str, 0, 2);
    str = pg_ultostr_zeropad(str, tm.tm_hour, 2);
    str = pg_ultostr_zeropad(str, tm.tm_min, 2);
    str = pg_ultostr_zeropad(str, abs(tm.tm_sec), 2);
}
 
static void printMoney(LogicalDecodingContext* ctx, Datum val)
{
    Cash v = DatumGetCash(val);
    char buf[128];
    char* pBuf = &buf[127];
    bool minus = (v < 0);
    struct lconv *lconvert = PGLC_localeconv();
    int points = lconvert->frac_digits;
 
    if (points < 0 || points > 10)
        points = 2;
 
    buf[127] = 0;
    if (minus)
        v = -v;
 
    do {
        *(--pBuf) = ((uint64)v % 10) + '0';
        --points;
 
        if (points == 0)
            *(--pBuf) = '.';
 
        if (v)
            v = ((uint64)v) / 10;
    } while (v || points >= 0);
    if (minus)
        *(--pBuf) = '-';
 
    appendCtxString(ctx, pBuf);
}
 
static void printBool(LogicalDecodingContext* ctx, Datum val)
{
    appendCtxString(ctx, DatumGetBool(val) ? "true" : "false");
}
 
static void printDefault(LogicalDecodingContext* ctx,
                            Datum val, Oid typid, Oid   typoutput)
{   // Вывод с помощью стандартной OUTPUT функции ..._out
    char* dataAsChar = OidOutputFunctionCall(typoutput, val);
    switch (typid)
    {
    case INT2OID:
    case INT4OID:
    case INT8OID:
    case OIDOID:
    case FLOAT4OID:
    case FLOAT8OID:
    case NUMERICOID:
        appendCtxString(ctx, dataAsChar);
        break;
 
    case BITOID:
    case VARBITOID:
        checkFlushCtx(ctx, (int)strlen(dataAsChar) + 3);
        appendStringInfo(ctx->out, "B'%s'", dataAsChar);
        break;
 
    default:
        {
            const int maxCharSize = pg_database_encoding_max_length();
            const char* pBegin;
            const char* pEnd = dataAsChar;
            int overflowRemain = checkFlushCtx(ctx, maxCharSize + 1);
 
            appendStringInfoChar(ctx->out, cQuoteChar);
            --overflowRemain;
            //в отличие от printCharVarchar,
            //здесь я не знаю длинну, но точно знаю, что на конце ноль
            for (pBegin = dataAsChar; *pBegin; pBegin = pEnd)
            {
                bool overflow;
                while (*pEnd &&
                        *pEnd != cQuoteChar &&
                        (int)(pEnd - pBegin) < overflowRemain)
                    ++pEnd;
                overflow = (int)(pEnd - pBegin) >= overflowRemain;
                if (pEnd != pBegin)
                {
                    if (overflow && *pEnd && *pEnd != cQuoteChar)
                    {
                        int32 L = (int32)(pEnd - pBegin);
                        if (!truncateIfIncmoplete(maxCharSize, pBegin, &L))
                            ereport(ERROR,
                            (errcode(ERRCODE_INVALID_CHARACTER_VALUE_FOR_CAST),
                                errmsg("invalid string value")
                                ));
                        pEnd = pBegin + L;
                    }
                    appendBinaryStringInfo(ctx->out,
                        pBegin, (int)(pEnd - pBegin));
                }
 
                if (*pEnd == cQuoteChar)
                {
                    overflowRemain = checkFlushCtx(ctx, maxCharSize + 2);
                    appendStringInfoChar(ctx->out, *pEnd);
                    appendStringInfoChar(ctx->out, *pEnd);
                    ++pEnd;
                    overflowRemain -= 2;
                }
                else if (overflow)
                    overflowRemain = checkFlushCtx(ctx, record_buf_size(ctx));
                else
                    overflowRemain = checkFlushCtx(ctx, maxCharSize);
            }
            if (overflowRemain < 1)
                checkFlushCtx(ctx, 1);
            appendStringInfoChar(ctx->out, cQuoteChar);
        }
        break;
    }
    pfree(dataAsChar);
}
 
static void printTuple(LogicalDecodingContext* ctx,
    TupleDesc tupdesc, HeapTuple tuple,
    bool skip_nulls, char* tableName)
{
 
    if (tuple == NULL)
        appendCtxString(ctx, " (no-tuple-data)");
    else
    {
        int natt;
        for (natt = 0; natt < tupdesc->natts; natt++)
        {
            bool typisvarlena;
            Oid typoutput;
            Form_pg_attribute attr = TupleDescAttr(tupdesc, natt);
            Oid typid = attr->atttypid;
            bool isnull;
            Datum origval;
 
            if (attr->attisdropped)
                continue;
            if (attr->attnum < 0) // Don't print system columns,
                continue;//oid will already have been printed if present.
 
            origval = heap_getattr(tuple, natt + 1, tupdesc, &isnull);
            if (isnull)
            {
                if (!skip_nulls)
                    appendCtxString(ctx, " null");
                continue;
            }
 
            checkFlushCtx(ctx, 1);
            appendStringInfoChar(ctx->out, ' ');
 
            getTypeOutputInfo(typid, &typoutput, &typisvarlena);
 
            if (typisvarlena)
            {
                if (VARATT_IS_EXTERNAL_ONDISK(origval))
                    appendCtxString(ctx, "unchanged-toast-datum");
                else
                {
                    Datum val = PointerGetDatum(PG_DETOAST_DATUM(origval));
 
                    if (typid == BPCHAROID ||
                        typid == VARCHAROID ||
                        typid == TEXTOID)
                        printCharVarchar(ctx, val);
                    else if (typid == BYTEAOID)
                        printByts(ctx, val);
                    else if (typid > FirstNormalObjectId)  {
                        readTypeOID("mchar", &MCHAROID);
                        readTypeOID("mvarchar", &MVARCHAROID);
 
                        if (typid == MCHAROID)
                            printMChar(ctx, val);
                        else if (typid == MVARCHAROID)
                            printMVarchar(ctx, val);
                        else
                            printDefault(ctx, val, typid, typoutput);
                    } else
                        printDefault(ctx, val, typid, typoutput);
 
                    if (DatumGetPointer(val) != DatumGetPointer(origval))
                        pfree(DatumGetPointer(val));
                }
 
            }
            else
            {
                switch (typid)
                {
                case MONEYOID:
                    printMoney(ctx, origval);
                    break;
                case TIMESTAMPOID:
                case TIMESTAMPTZOID:
                    printTimestamp(ctx, origval);
                    break;
                case DATEOID:
                    printDate(ctx, origval);
                    break;
                case TIMEOID:
                    printTime(ctx, origval);
                    break;
                case BOOLOID:
                    printBool(ctx, origval);
                    break;
                default:
                    printDefault(ctx, origval, typid, typoutput);
                    break;
                }
            }
        }
    }
}
 
static void printTransaction(DecodingData* data,
    LogicalDecodingContext* ctx, ReorderBufferTXN* txn)
{
    if (data->xact_wrote_changes)
        return;
 
    OutputPluginPrepareWrite(ctx, false);
    if (data->include_xids)
        appendStringInfo(ctx->out, "B %u", txn->xid);
    else
        appendStringInfoString(ctx->out, "B");
    OutputPluginWrite(ctx, false);
    data->xact_wrote_changes = true;
}
 
static void decode_change(LogicalDecodingContext* ctx,
    ReorderBufferTXN* txn, Relation relation, ReorderBufferChange* change)
{
    DecodingData* data = ctx->output_plugin_private;
    if (data->skip_change)
        return;
    {
        MemoryContext old = MemoryContextSwitchTo(data->context);
        TupleDesc tupdesc = RelationGetDescr(relation);
        char* tableName = RelationGetRelationName(relation);
 
        printTransaction(data, ctx, txn);
        prepareFlushedCtx(ctx);
        switch (change->action)
        {
        case REORDER_BUFFER_CHANGE_INSERT:
        {
            appendStringInfoString(ctx->out, "I ");
            appendStringInfoString(ctx->out, tableName);
            printTuple(ctx, tupdesc, change->data.tp.newtuple, false, tableName);
        }
        break;
        case REORDER_BUFFER_CHANGE_UPDATE:
        {
            appendStringInfoString(ctx->out, "U ");
            appendStringInfoString(ctx->out, tableName);
            printTuple(ctx, tupdesc, change->data.tp.newtuple, false, tableName);
        }
        break;
        case REORDER_BUFFER_CHANGE_DELETE:
        {
            appendStringInfoString(ctx->out, "D ");
            appendStringInfoString(ctx->out, tableName);
            printTuple(ctx, tupdesc, change->data.tp.oldtuple, true, tableName);
        }
        break;
        default:
            Assert(false);
        }
        MemoryContextSwitchTo(old);
    }
    OutputPluginWrite(ctx, true);
    MemoryContextReset(data->context);
}
 
static void decode_truncate(LogicalDecodingContext* ctx,
    ReorderBufferTXN* txn, int nrelations,
    Relation relations[], ReorderBufferChange* change)
{
    int i;
    DecodingData* data = ctx->output_plugin_private;
    if (data->skip_change)
        return;
 
    printTransaction(data, ctx, txn);
    {
        MemoryContext old = MemoryContextSwitchTo(data->context);
 
        OutputPluginPrepareWrite(ctx, true);
 
        appendStringInfoString(ctx->out, "T ");
 
        for (i = 0; i < nrelations; i++)
        {
            if (i > 0)
                appendStringInfoString(ctx->out, ", ");
 
            appendStringInfoString(ctx->out,
                RelationGetRelationName(relations[i]));
        }
 
        MemoryContextSwitchTo(old);
    }
    OutputPluginWrite(ctx, true);
    MemoryContextReset(data->context);
}