forked from eulerto/wal2json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wal2json.c
1240 lines (1100 loc) · 34.4 KB
/
wal2json.c
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
/*-------------------------------------------------------------------------
*
* wal2json.c
* JSON output plugin for changeset extraction
*
* Copyright (c) 2013-2017, PostgreSQL Global Development Group
*
* IDENTIFICATION
* contrib/wal2json/wal2json.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "catalog/pg_type.h"
#include "replication/logical.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
#include "utils/rel.h"
#include "utils/syscache.h"
PG_MODULE_MAGIC;
char *VER = "1.6.3";
extern void _PG_init(void);
extern void _PG_output_plugin_init(OutputPluginCallbacks *cb);
typedef struct
{
MemoryContext context;
bool include_xids; /* include transaction ids */
bool include_timestamp; /* include transaction timestamp */
bool include_schemas; /* qualify tables */
bool include_types; /* include data types */
bool include_type_oids; /* include data type oids */
bool include_typmod; /* include typmod in types */
bool include_not_null; /* include not-null constraints */
bool pretty_print; /* pretty-print JSON? */
bool write_in_chunks; /* write in chunks? */
char *filter_tables; /* filter tables */
bool force_TOAST_table; /* force output TOAST content table */
bool is_writed_header;
/*
* LSN pointing to the end of commit record + 1 (txn->end_lsn)
* It is useful for tools that wants a position to restart from.
*/
bool include_lsn; /* include LSNs */
uint64 nr_changes; /* # of passes in pg_decode_change() */
/* FIXME replace with txn->nentries */
} JsonDecodingData;
/* These must be available to pg_dlsym() */
static void pg_decode_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init);
static void pg_decode_shutdown(LogicalDecodingContext *ctx);
static void pg_decode_begin_txn(LogicalDecodingContext *ctx,
ReorderBufferTXN *txn);
static void pg_decode_commit_txn(LogicalDecodingContext *ctx,
ReorderBufferTXN *txn, XLogRecPtr commit_lsn);
static void pg_decode_change(LogicalDecodingContext *ctx,
ReorderBufferTXN *txn, Relation rel,
ReorderBufferChange *change);
#if PG_VERSION_NUM >= 90600
static void pg_decode_message(LogicalDecodingContext *ctx,
ReorderBufferTXN *txn, XLogRecPtr lsn,
bool transactional, const char *prefix,
Size content_size, const char *content);
#endif
static int check_tables(LogicalDecodingContext *ctx, char *schema_name, char *table_name);
void
_PG_init(void)
{
}
/* Specify output plugin callbacks */
void
_PG_output_plugin_init(OutputPluginCallbacks *cb)
{
char ver[10];
AssertVariableIsOfType(&_PG_output_plugin_init, LogicalOutputPluginInit);
strcpy(ver, "V. ");
strcat(ver, VER);
elog(LOG, "%s", ver);
cb->startup_cb = pg_decode_startup;
cb->begin_cb = pg_decode_begin_txn;
cb->change_cb = pg_decode_change;
cb->commit_cb = pg_decode_commit_txn;
cb->shutdown_cb = pg_decode_shutdown;
#if PG_VERSION_NUM >= 90600
cb->message_cb = pg_decode_message;
#endif
}
/* Initialize this plugin */
static void
pg_decode_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
{
ListCell *option;
JsonDecodingData *data;
elog(DEBUG1, "---------> pg_decode_startup");
data = palloc0(sizeof(JsonDecodingData));
data->context = AllocSetContextCreate(TopMemoryContext,
"wal2json output context",
#if PG_VERSION_NUM >= 90600
ALLOCSET_DEFAULT_SIZES
#else
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE
#endif
);
data->include_xids = false;
data->include_timestamp = false;
data->include_schemas = true;
data->include_types = true;
data->include_type_oids = false;
data->include_typmod = true;
data->pretty_print = false;
data->write_in_chunks = false;
data->include_lsn = false;
data->include_not_null = false;
data->filter_tables = NULL;
data->force_TOAST_table = false;
data->is_writed_header = false;
data->nr_changes = 0;
ctx->output_plugin_private = data;
opt->output_type = OUTPUT_PLUGIN_TEXTUAL_OUTPUT;
foreach(option, ctx->output_plugin_options)
{
DefElem *elem = lfirst(option);
Assert(elem->arg == NULL || IsA(elem->arg, String));
if (strcmp(elem->defname, "include-xids") == 0)
{
/* If option does not provide a value, it means its value is true */
if (elem->arg == NULL)
{
elog(LOG, "include-xids argument is null");
data->include_xids = true;
}
else if (!parse_bool(strVal(elem->arg), &data->include_xids))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
else if (strcmp(elem->defname, "include-timestamp") == 0)
{
if (elem->arg == NULL)
{
elog(LOG, "include-timestamp argument is null");
data->include_timestamp = false;
}
else if (!parse_bool(strVal(elem->arg), &data->include_timestamp))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
else if (strcmp(elem->defname, "include-schemas") == 0)
{
if (elem->arg == NULL)
{
elog(LOG, "include-schemas argument is null");
data->include_schemas = true;
}
else if (!parse_bool(strVal(elem->arg), &data->include_schemas))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
else if (strcmp(elem->defname, "include-types") == 0)
{
if (elem->arg == NULL)
{
elog(LOG, "include-types argument is null");
data->include_types = true;
}
else if (!parse_bool(strVal(elem->arg), &data->include_types))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
else if (strcmp(elem->defname, "include-type-oids") == 0)
{
if (elem->arg == NULL)
{
elog(LOG, "include-type-oids argument is null");
data->include_type_oids = true;
}
else if (!parse_bool(strVal(elem->arg), &data->include_type_oids))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
else if (strcmp(elem->defname, "include-typmod") == 0)
{
if (elem->arg == NULL)
{
elog(LOG, "include-typmod argument is null");
data->include_typmod = true;
}
else if (!parse_bool(strVal(elem->arg), &data->include_typmod))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
else if (strcmp(elem->defname, "include-not-null") == 0)
{
if (elem->arg == NULL)
{
elog(LOG, "include-not-null argument is null");
data->include_not_null = true;
}
else if (!parse_bool(strVal(elem->arg), &data->include_not_null))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
else if (strcmp(elem->defname, "pretty-print") == 0)
{
if (elem->arg == NULL)
{
elog(LOG, "pretty-print argument is null");
data->pretty_print = true;
}
else if (!parse_bool(strVal(elem->arg), &data->pretty_print))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
else if (strcmp(elem->defname, "write-in-chunks") == 0)
{
if (elem->arg == NULL)
{
elog(LOG, "write-in-chunks argument is null");
data->write_in_chunks = true;
}
else if (!parse_bool(strVal(elem->arg), &data->write_in_chunks))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
else if (strcmp(elem->defname, "include-lsn") == 0)
{
if (elem->arg == NULL)
{
elog(LOG, "include-lsn argument is null");
data->include_lsn = true;
}
else if (!parse_bool(strVal(elem->arg), &data->include_lsn))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
// Filter Tables
else if (strcmp(elem->defname, "filter-tables") == 0)
{
if ( elem->arg == NULL || (strlen(strVal(elem->arg))==0) )
{
elog(LOG, "filter-tables argument is null or empty");
}
else
{
elog(LOG, "filter-tables argument is NOT null");
data->filter_tables = strVal(elem->arg);
elog(DEBUG1, "filter-tables-VAL: %s, %u", data->filter_tables, (unsigned)strlen(strVal(elem->arg)));
}
}
// Force write TOAST table content
else if (strcmp(elem->defname, "force-toast-table") == 0)
{
/* If option does not provide a value, it means its value is true */
if (elem->arg == NULL)
{
elog(LOG, "force-toast-table argument is null");
data->force_TOAST_table = false;
}
else if (!parse_bool(strVal(elem->arg), &data->force_TOAST_table))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("could not parse value \"%s\" for parameter \"%s\"",
strVal(elem->arg), elem->defname)));
}
//----
else
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("option \"%s\" = \"%s\" is unknown",
elem->defname,
elem->arg ? strVal(elem->arg) : "(null)")));
}
}
}
/* cleanup this plugin's resources */
static void
pg_decode_shutdown(LogicalDecodingContext *ctx)
{
JsonDecodingData *data = ctx->output_plugin_private;
if(data->filter_tables!=NULL)
{
pfree(data->filter_tables);
}
/* cleanup our own resources via memory context reset */
MemoryContextDelete(data->context);
}
/* BEGIN callback */
static void
pg_decode_begin_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
{
JsonDecodingData *data = ctx->output_plugin_private;
data->nr_changes = 0;
/* Transaction starts */
OutputPluginPrepareWrite(ctx, true);
if (data->pretty_print)
appendStringInfoString(ctx->out, "{\n");
else
appendStringInfoChar(ctx->out, '{');
if (data->include_xids)
{
if (data->pretty_print)
appendStringInfo(ctx->out, "\t\"xid\": %u,\n", txn->xid);
else
appendStringInfo(ctx->out, "\"xid\":%u,", txn->xid);
}
if (data->include_lsn)
{
char *lsn_str = DatumGetCString(DirectFunctionCall1(pg_lsn_out, txn->end_lsn));
if (data->pretty_print)
appendStringInfo(ctx->out, "\t\"nextlsn\": \"%s\",\n", lsn_str);
else
appendStringInfo(ctx->out, "\"nextlsn\":\"%s\",", lsn_str);
pfree(lsn_str);
}
if (data->include_timestamp)
{
if (data->pretty_print)
appendStringInfo(ctx->out, "\t\"timestamp\": \"%s\",\n", timestamptz_to_str(txn->commit_time));
else
appendStringInfo(ctx->out, "\"timestamp\":\"%s\",", timestamptz_to_str(txn->commit_time));
}
if (data->pretty_print)
appendStringInfoString(ctx->out, "\t\"change\": [");
else
appendStringInfoString(ctx->out, "\"change\":[");
//Dismissed and moved into 'pg_decode_change'
//if (data->write_in_chunks)
//OutputPluginWrite(ctx, true);
}
/* COMMIT callback */
static void
pg_decode_commit_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
XLogRecPtr commit_lsn)
{
JsonDecodingData *data = ctx->output_plugin_private;
if (txn->has_catalog_changes)
elog(DEBUG1, "txn has catalog changes: yes");
else
elog(DEBUG1, "txn has catalog changes: no");
elog(DEBUG1, "my change counter: %lu ; # of changes: %lu ; # of changes in memory: %lu", data->nr_changes, txn->nentries, txn->nentries_mem);
elog(DEBUG1, "# of subxacts: %d", txn->nsubtxns);
/* Transaction ends */
if (data->write_in_chunks)
OutputPluginPrepareWrite(ctx, true);
if (data->pretty_print)
{
/* if we don't write in chunks, we need a newline here */
if (!data->write_in_chunks)
appendStringInfoChar(ctx->out, '\n');
appendStringInfoString(ctx->out, "\t]\n}");
}
else
{
appendStringInfoString(ctx->out, "]}");
}
if (data->nr_changes>0)
{
OutputPluginWrite(ctx, true);
}
data->is_writed_header = false;
}
/*
* Format a string as a JSON literal
* XXX it doesn't do a sanity check for invalid input, does it?
* FIXME it doesn't handle \uxxxx
*/
static void
quote_escape_json(StringInfo buf, const char *val)
{
const char *valptr;
appendStringInfoChar(buf, '"');
for (valptr = val; *valptr; valptr++)
{
char ch = *valptr;
/* XXX suppress \x in bytea field? */
if (ch == '\\' && *(valptr + 1) == 'x')
{
valptr++;
continue;
}
switch (ch)
{
case '"':
case '\\':
case '/':
appendStringInfo(buf, "\\%c", ch);
break;
case '\b':
appendStringInfoString(buf, "\\b");
break;
case '\f':
appendStringInfoString(buf, "\\f");
break;
case '\n':
appendStringInfoString(buf, "\\n");
break;
case '\r':
appendStringInfoString(buf, "\\r");
break;
case '\t':
appendStringInfoString(buf, "\\t");
break;
default:
appendStringInfoChar(buf, ch);
break;
}
}
appendStringInfoChar(buf, '"');
}
/*
* Accumulate tuple information and stores it at the end
*
* replident: is this tuple a replica identity?
* hasreplident: does this tuple has an associated replica identity?
*/
static void
tuple_to_stringinfo(LogicalDecodingContext *ctx, TupleDesc tupdesc, HeapTuple tuple, TupleDesc indexdesc, bool replident, bool hasreplident)
{
JsonDecodingData *data;
int natt;
StringInfoData colnames;
StringInfoData coltypes;
StringInfoData coltypeoids;
StringInfoData colnotnulls;
StringInfoData colvalues;
char *comma = "";
data = ctx->output_plugin_private;
initStringInfo(&colnames);
initStringInfo(&coltypes);
if (data->include_type_oids)
initStringInfo(&coltypeoids);
if (data->include_not_null)
initStringInfo(&colnotnulls);
initStringInfo(&colvalues);
/*
* If replident is true, it will output info about replica identity. In this
* case, there are special JSON objects for it. Otherwise, it will print new
* tuple data.
*/
if (replident)
{
if (data->pretty_print)
{
appendStringInfoString(&colnames, "\t\t\t\"oldkeys\": {\n");
appendStringInfoString(&colnames, "\t\t\t\t\"keynames\": [");
appendStringInfoString(&coltypes, "\t\t\t\t\"keytypes\": [");
if (data->include_type_oids)
appendStringInfoString(&coltypeoids, "\t\t\t\"keytypeoids\": [");
appendStringInfoString(&colvalues, "\t\t\t\t\"keyvalues\": [");
}
else
{
appendStringInfoString(&colnames, "\"oldkeys\":{");
appendStringInfoString(&colnames, "\"keynames\":[");
appendStringInfoString(&coltypes, "\"keytypes\":[");
if (data->include_type_oids)
appendStringInfoString(&coltypeoids, "\"keytypeoids\": [");
appendStringInfoString(&colvalues, "\"keyvalues\":[");
}
}
else
{
if (data->pretty_print)
{
appendStringInfoString(&colnames, "\t\t\t\"columnnames\": [");
appendStringInfoString(&coltypes, "\t\t\t\"columntypes\": [");
if (data->include_type_oids)
appendStringInfoString(&coltypeoids, "\t\t\t\"columntypeoids\": [");
if (data->include_not_null)
appendStringInfoString(&colnotnulls, "\t\t\t\"columnoptionals\": [");
appendStringInfoString(&colvalues, "\t\t\t\"columnvalues\": [");
}
else
{
appendStringInfoString(&colnames, "\"columnnames\":[");
appendStringInfoString(&coltypes, "\"columntypes\":[");
if (data->include_type_oids)
appendStringInfoString(&coltypeoids, "\"columntypeoids\": [");
if (data->include_not_null)
appendStringInfoString(&colnotnulls, "\"columnoptionals\": [");
appendStringInfoString(&colvalues, "\"columnvalues\":[");
}
}
/* Print column information (name, type, value) */
for (natt = 0; natt < tupdesc->natts; natt++)
{
Form_pg_attribute attr; /* the attribute itself */
Oid typid; /* type of current attribute */
HeapTuple type_tuple; /* information about a type */
Oid typoutput; /* output function */
bool typisvarlena;
Datum origval; /* possibly toasted Datum */
Datum val; /* definitely detoasted Datum */
char *outputstr = NULL;
bool isnull; /* column is null? */
/*
* Commit d34a74dd064af959acd9040446925d9d53dff15b introduced
* TupleDescAttr() in back branches. If the version supports
* this macro, use it. Version 10 and later already support it.
*/
#if (PG_VERSION_NUM >= 90600 && PG_VERSION_NUM < 90605) || (PG_VERSION_NUM >= 90500 && PG_VERSION_NUM < 90509) || (PG_VERSION_NUM >= 90400 && PG_VERSION_NUM < 90414)
attr = tupdesc->attrs[natt];
#else
attr = TupleDescAttr(tupdesc, natt);
#endif
elog(DEBUG1, "attribute \"%s\" (%d/%d)", NameStr(attr->attname), natt, tupdesc->natts);
/* Do not print dropped or system columns */
if (attr->attisdropped || attr->attnum < 0)
continue;
/* Search indexed columns in whole heap tuple */
if (indexdesc != NULL)
{
int j;
bool found_col = false;
for (j = 0; j < indexdesc->natts; j++)
{
Form_pg_attribute iattr;
/* See explanation a few lines above. */
#if (PG_VERSION_NUM >= 90600 && PG_VERSION_NUM < 90605) || (PG_VERSION_NUM >= 90500 && PG_VERSION_NUM < 90509) || (PG_VERSION_NUM >= 90400 && PG_VERSION_NUM < 90414)
iattr = indexdesc->attrs[j];
#else
iattr = TupleDescAttr(indexdesc, j);
#endif
if (strcmp(NameStr(attr->attname), NameStr(iattr->attname)) == 0)
found_col = true;
}
/* Print only indexed columns */
if (!found_col)
continue;
}
typid = attr->atttypid;
/* Figure out type name */
type_tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
if (!HeapTupleIsValid(type_tuple))
elog(ERROR, "cache lookup failed for type %u", typid);
/* Get information needed for printing values of a type */
getTypeOutputInfo(typid, &typoutput, &typisvarlena);
/* Get Datum from tuple */
origval = heap_getattr(tuple, natt + 1, tupdesc, &isnull);
/* Skip nulls iif printing key/identity */
if (isnull && replident)
continue;
/* XXX Unchanged TOAST Datum does not need to be output */
/* Force extract record from TOAST tables */
/* TODO :: investigate because on deletion, there is a return error */
if (!isnull && typisvarlena && VARATT_IS_EXTERNAL_ONDISK(origval) && !data->force_TOAST_table)
{
elog(WARNING, "column \"%s\" has an unchanged TOAST", NameStr(attr->attname));
continue;
}
/* Accumulate each column info */
appendStringInfo(&colnames, "%s\"%s\"", comma, NameStr(attr->attname));
if (data->include_types)
{
if (data->include_typmod)
{
char *type_str;
type_str = TextDatumGetCString(DirectFunctionCall2(format_type, attr->atttypid, attr->atttypmod));
appendStringInfo(&coltypes, "%s\"%s\"", comma, type_str);
pfree(type_str);
}
else
{
Form_pg_type type_form = (Form_pg_type) GETSTRUCT(type_tuple);
appendStringInfo(&coltypes, "%s\"%s\"", comma, NameStr(type_form->typname));
}
/* oldkeys doesn't print not-null constraints */
if (!replident && data->include_not_null)
{
if (attr->attnotnull)
appendStringInfo(&colnotnulls, "%sfalse", comma);
else
appendStringInfo(&colnotnulls, "%strue", comma);
}
}
if (data->include_type_oids)
appendStringInfo(&coltypeoids, "%s%u", comma, typid);
ReleaseSysCache(type_tuple);
if (isnull)
{
appendStringInfo(&colvalues, "%snull", comma);
}
else
{
if (typisvarlena)
val = PointerGetDatum(PG_DETOAST_DATUM(origval));
else
val = origval;
/* Finally got the value */
outputstr = OidOutputFunctionCall(typoutput, val);
/*
* Data types are printed with quotes unless they are number, true,
* false, null, an array or an object.
*
* The NaN and Infinity are not valid JSON symbols. Hence,
* regardless of sign they are represented as the string null.
*/
switch (typid)
{
case INT2OID:
case INT4OID:
case INT8OID:
case OIDOID:
case FLOAT4OID:
case FLOAT8OID:
case NUMERICOID:
if (pg_strncasecmp(outputstr, "NaN", 3) == 0 ||
pg_strncasecmp(outputstr, "Infinity", 8) == 0 ||
pg_strncasecmp(outputstr, "-Infinity", 9) == 0)
{
appendStringInfo(&colvalues, "%snull", comma);
elog(DEBUG1, "attribute \"%s\" is special: %s", NameStr(attr->attname), outputstr);
}
else if (strspn(outputstr, "0123456789+-eE.") == strlen(outputstr))
appendStringInfo(&colvalues, "%s%s", comma, outputstr);
else
elog(ERROR, "%s is not a number", outputstr);
break;
case BOOLOID:
if (strcmp(outputstr, "t") == 0)
appendStringInfo(&colvalues, "%strue", comma);
else
appendStringInfo(&colvalues, "%sfalse", comma);
break;
default:
appendStringInfoString(&colvalues, comma);
quote_escape_json(&colvalues, outputstr);
break;
}
}
/* The first column does not have comma */
if (strcmp(comma, "") == 0)
{
if (data->pretty_print)
comma = ", ";
else
comma = ",";
}
}
/* Column info ends */
if (replident)
{
if (data->pretty_print)
{
appendStringInfoString(&colnames, "],\n");
if (data->include_types)
appendStringInfoString(&coltypes, "],\n");
if (data->include_type_oids)
appendStringInfoString(&coltypeoids, "],\n");
appendStringInfoString(&colvalues, "]\n");
appendStringInfoString(&colvalues, "\t\t\t}\n");
}
else
{
appendStringInfoString(&colnames, "],");
if (data->include_types)
appendStringInfoString(&coltypes, "],");
if (data->include_type_oids)
appendStringInfoString(&coltypeoids, "],");
appendStringInfoChar(&colvalues, ']');
appendStringInfoChar(&colvalues, '}');
}
}
else
{
if (data->pretty_print)
{
appendStringInfoString(&colnames, "],\n");
if (data->include_types)
appendStringInfoString(&coltypes, "],\n");
if (data->include_type_oids)
appendStringInfoString(&coltypeoids, "],\n");
if (data->include_not_null)
appendStringInfoString(&colnotnulls, "],\n");
if (hasreplident)
appendStringInfoString(&colvalues, "],\n");
else
appendStringInfoString(&colvalues, "]\n");
}
else
{
appendStringInfoString(&colnames, "],");
if (data->include_types)
appendStringInfoString(&coltypes, "],");
if (data->include_type_oids)
appendStringInfoString(&coltypeoids, "],");
if (data->include_not_null)
appendStringInfoString(&colnotnulls, "],");
if (hasreplident)
appendStringInfoString(&colvalues, "],");
else
appendStringInfoChar(&colvalues, ']');
}
}
/* Print data */
appendStringInfoString(ctx->out, colnames.data);
if (data->include_types)
appendStringInfoString(ctx->out, coltypes.data);
if (data->include_type_oids)
appendStringInfoString(ctx->out, coltypeoids.data);
if (data->include_not_null)
appendStringInfoString(ctx->out, colnotnulls.data);
appendStringInfoString(ctx->out, colvalues.data);
pfree(colnames.data);
pfree(coltypes.data);
if (data->include_type_oids)
pfree(coltypeoids.data);
if (data->include_not_null)
pfree(colnotnulls.data);
pfree(colvalues.data);
}
/* Print columns information */
static void
columns_to_stringinfo(LogicalDecodingContext *ctx, TupleDesc tupdesc, HeapTuple tuple, bool hasreplident)
{
tuple_to_stringinfo(ctx, tupdesc, tuple, NULL, false, hasreplident);
}
/* Print replica identity information */
static void
identity_to_stringinfo(LogicalDecodingContext *ctx, TupleDesc tupdesc, HeapTuple tuple, TupleDesc indexdesc)
{
/* Last parameter does not matter */
tuple_to_stringinfo(ctx, tupdesc, tuple, indexdesc, true, false);
}
/* Callback for individual changed tuples */
static void
pg_decode_change(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
Relation relation, ReorderBufferChange *change)
{
JsonDecodingData *data;
Form_pg_class class_form;
TupleDesc tupdesc;
MemoryContext old;
Relation indexrel;
TupleDesc indexdesc;
int table_to_process;
table_to_process = 1;
AssertVariableIsOfType(&pg_decode_change, LogicalDecodeChangeCB);
data = ctx->output_plugin_private;
class_form = RelationGetForm(relation);
tupdesc = RelationGetDescr(relation);
/* Avoid leaking memory by using and resetting our own context */
old = MemoryContextSwitchTo(data->context);
//Dismissed
//if (data->write_in_chunks)
// OutputPluginPrepareWrite(ctx, true);
/* Make sure rd_replidindex is set */
RelationGetIndexList(relation);
/* Sanity checks */
switch (change->action)
{
case REORDER_BUFFER_CHANGE_INSERT:
if (change->data.tp.newtuple == NULL)
{
elog(WARNING, "no tuple data for INSERT in table \"%s\"", NameStr(class_form->relname));
MemoryContextSwitchTo(old);
MemoryContextReset(data->context);
return;
}
break;
case REORDER_BUFFER_CHANGE_UPDATE:
/*
* Bail out iif:
* (i) doesn't have a pk and replica identity is not full;
* (ii) replica identity is nothing.
*/
if (!OidIsValid(relation->rd_replidindex) && relation->rd_rel->relreplident != REPLICA_IDENTITY_FULL)
{
/* FIXME this sentence is imprecise */
elog(WARNING, "table \"%s\" without primary key or replica identity is nothing", NameStr(class_form->relname));
MemoryContextSwitchTo(old);
MemoryContextReset(data->context);
return;
}
if (change->data.tp.newtuple == NULL)
{
elog(WARNING, "no tuple data for UPDATE in table \"%s\"", NameStr(class_form->relname));
MemoryContextSwitchTo(old);
MemoryContextReset(data->context);
return;
}
break;
case REORDER_BUFFER_CHANGE_DELETE:
/*
* Bail out iif:
* (i) doesn't have a pk and replica identity is not full;
* (ii) replica identity is nothing.
*/
if (!OidIsValid(relation->rd_replidindex) && relation->rd_rel->relreplident != REPLICA_IDENTITY_FULL)
{
/* FIXME this sentence is imprecise */
elog(WARNING, "table \"%s\" without primary key or replica identity is nothing", NameStr(class_form->relname));
MemoryContextSwitchTo(old);
MemoryContextReset(data->context);
return;
}
if (change->data.tp.oldtuple == NULL)
{
elog(WARNING, "no tuple data for DELETE in table \"%s\"", NameStr(class_form->relname));
MemoryContextSwitchTo(old);
MemoryContextReset(data->context);
return;
}
break;
default:
Assert(false);
}
//check if process tables
table_to_process = check_tables(ctx, get_namespace_name(class_form->relnamespace), NameStr(class_form->relname));
if (table_to_process == 1)
{
//Prepare Json's header
if(!data->is_writed_header)
{
//Write json's Header
if (data->write_in_chunks)
OutputPluginWrite(ctx, true);
data->is_writed_header = true;
}
/* Change counter */
data->nr_changes++;
if (data->write_in_chunks)
OutputPluginPrepareWrite(ctx, true);
//---------------
/* Change starts */
if (data->pretty_print)
{
/* if we don't write in chunks, we need a newline here */
if (!data->write_in_chunks)
appendStringInfoChar(ctx->out, '\n');
appendStringInfoString(ctx->out, "\t\t");
if (data->nr_changes > 1)
appendStringInfoChar(ctx->out, ',');
appendStringInfoString(ctx->out, "{\n");
}
else
{
if (data->nr_changes > 1)
appendStringInfoString(ctx->out, ",{");
else
appendStringInfoChar(ctx->out, '{');
}
/* Print change kind */
switch (change->action)
{
case REORDER_BUFFER_CHANGE_INSERT:
if (data->pretty_print)
appendStringInfoString(ctx->out, "\t\t\t\"kind\": \"insert\",\n");
else
appendStringInfoString(ctx->out, "\"kind\":\"insert\",");
break;
case REORDER_BUFFER_CHANGE_UPDATE:
if(data->pretty_print)
appendStringInfoString(ctx->out, "\t\t\t\"kind\": \"update\",\n");
else
appendStringInfoString(ctx->out, "\"kind\":\"update\",");
break;
case REORDER_BUFFER_CHANGE_DELETE:
if (data->pretty_print)
appendStringInfoString(ctx->out, "\t\t\t\"kind\": \"delete\",\n");
else
appendStringInfoString(ctx->out, "\"kind\":\"delete\",");
break;
default:
Assert(false);
}
/* Print table name (possibly) qualified */
if (data->pretty_print)
{
if (data->include_schemas)
appendStringInfo(ctx->out, "\t\t\t\"schema\": \"%s\",\n", get_namespace_name(class_form->relnamespace));
appendStringInfo(ctx->out, "\t\t\t\"table\": \"%s\",\n", NameStr(class_form->relname));