-
Notifications
You must be signed in to change notification settings - Fork 152
/
pglogical_apply.c
2028 lines (1670 loc) · 51.7 KB
/
pglogical_apply.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
/*-------------------------------------------------------------------------
*
* pglogical_apply.c
* pglogical apply logic
*
* Copyright (c) 2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* pglogical.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "miscadmin.h"
#include "libpq-fe.h"
#include "pgstat.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "commands/dbcommands.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "libpq/pqformat.h"
#include "mb/pg_wchar.h"
#include "nodes/makefuncs.h"
#include "nodes/parsenodes.h"
#include "optimizer/planner.h"
#include "replication/origin.h"
#include "rewrite/rewriteHandler.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "tcop/pquery.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/int8.h"
#include "utils/jsonb.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#include "pglogical_conflict.h"
#include "pglogical_node.h"
#include "pglogical_proto.h"
#include "pglogical_queue.h"
#include "pglogical_relcache.h"
#include "pglogical_repset.h"
#include "pglogical_rpc.h"
#include "pglogical_sync.h"
#include "pglogical_worker.h"
#include "pglogical.h"
void pglogical_apply_main(Datum main_arg);
static bool in_remote_transaction = false;
static XLogRecPtr remote_origin_lsn = InvalidXLogRecPtr;
static RepOriginId remote_origin_id = InvalidRepOriginId;
static Oid QueueRelid = InvalidOid;
static List *SyncingTables = NIL;
PGLogicalApplyWorker *MyApplyWorker = NULL;
PGLogicalSubscription *MySubscription = NULL;
static PGconn *applyconn = NULL;
typedef struct PGLFlushPosition
{
dlist_node node;
XLogRecPtr local_end;
XLogRecPtr remote_end;
} PGLFlushPosition;
dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping);
typedef struct ApplyExecState {
EState *estate;
EPQState epqstate;
ResultRelInfo *resultRelInfo;
TupleTableSlot *slot;
} ApplyExecState;
static void handle_queued_message(HeapTuple msgtup, bool tx_just_started);
static void handle_startup_param(const char *key, const char *value);
static bool parse_bool_param(const char *key, const char *value);
static void process_syncing_tables(XLogRecPtr end_lsn);
static void start_sync_worker(RangeVar *rv);
/*
* Check if given relation is in process of being synchronized.
*
* TODO: performance
*/
static bool
check_syncing_relation(const char *nspname, const char *relname)
{
return list_length(SyncingTables) &&
list_member(SyncingTables, makeRangeVar((char *)nspname, (char *)relname, -1));
}
static bool
ensure_transaction(void)
{
if (IsTransactionState())
{
if (CurrentMemoryContext != MessageContext)
MemoryContextSwitchTo(MessageContext);
return false;
}
StartTransactionCommand();
MemoryContextSwitchTo(MessageContext);
return true;
}
static void
handle_begin(StringInfo s)
{
XLogRecPtr commit_lsn;
TimestampTz commit_time;
TransactionId remote_xid;
pglogical_read_begin(s, &commit_lsn, &commit_time, &remote_xid);
replorigin_session_origin_timestamp = commit_time;
replorigin_session_origin_lsn = commit_lsn;
remote_origin_id = InvalidRepOriginId;
in_remote_transaction = true;
pgstat_report_activity(STATE_RUNNING, NULL);
}
/*
* Handle COMMIT message.
*/
static void
handle_commit(StringInfo s)
{
XLogRecPtr commit_lsn;
XLogRecPtr end_lsn;
TimestampTz commit_time;
pglogical_read_commit(s, &commit_lsn, &end_lsn, &commit_time);
Assert(commit_lsn == replorigin_session_origin_lsn);
Assert(commit_time == replorigin_session_origin_timestamp);
if (IsTransactionState())
{
PGLFlushPosition *flushpos;
CommitTransactionCommand();
MemoryContextSwitchTo(TopMemoryContext);
/* Track commit lsn */
flushpos = (PGLFlushPosition *) palloc(sizeof(PGLFlushPosition));
flushpos->local_end = XactLastCommitEnd;
flushpos->remote_end = end_lsn;
dlist_push_tail(&lsn_mapping, &flushpos->node);
MemoryContextSwitchTo(MessageContext);
}
/*
* If the xact isn't from the immediate upstream, advance the slot of the
* node it originally came from so we start replay of that node's change
* data at the right place.
*
* This is only necessary when we're streaming data from one peer (A) that
* in turn receives from other peers (B, C), and we plan to later switch to
* replaying directly from B and/or C, no longer receiving forwarded xacts
* from A. When we do the switchover we need to know the right place at
* which to start replay from B and C. We don't actually do that yet, but
* we'll want to be able to do cascaded initialisation in future, so it's
* worth keeping track.
*
* A failure can occur here (see #79) if there's a cascading
* replication configuration like:
*
* X--> Y -> Z
* | ^
* | |
* \---------/
*
* where the direct and indirect connections from X to Z use different
* replication sets so as not to conflict, and where Y and Z are on the
* same PostgreSQL instance. In this case our attempt to advance the
* replication identifier here will ERROR because it's already in use
* for the direct connection from X to Z. So don't do that.
*/
if (remote_origin_id != InvalidRepOriginId &&
remote_origin_id != replorigin_session_origin)
{
elog(DEBUG3, "advancing origin oid %u for forwarded row to %X/%X",
remote_origin_id,
(uint32)(XactLastCommitEnd>>32), (uint32)XactLastCommitEnd);
replorigin_advance(remote_origin_id, remote_origin_lsn,
XactLastCommitEnd, false, false /* XXX ? */);
}
in_remote_transaction = false;
/*
* Stop replay if we're doing limited replay and we've replayed up to the
* last record we're supposed to process.
*/
if (MyApplyWorker->replay_stop_lsn != InvalidXLogRecPtr
&& MyApplyWorker->replay_stop_lsn <= end_lsn)
{
ereport(LOG,
(errmsg("pglogical %s finished processing; replayed to %X/%X of required %X/%X",
MyPGLogicalWorker->worker_type == PGLOGICAL_WORKER_SYNC ? "sync" : "apply",
(uint32)(end_lsn>>32), (uint32)end_lsn,
(uint32)(MyApplyWorker->replay_stop_lsn >>32),
(uint32)MyApplyWorker->replay_stop_lsn)));
/*
* Flush all writes so the latest position can be reported back to the
* sender.
*/
XLogFlush(GetXLogWriteRecPtr());
/*
* Disconnect.
*
* This needs to happen before the pglogical_sync_worker_finish()
* call otherwise slot drop will fail.
*/
PQfinish(applyconn);
/*
* If this is sync worker, finish it.
*/
if (MyPGLogicalWorker->worker_type == PGLOGICAL_WORKER_SYNC)
pglogical_sync_worker_finish();
/* Stop gracefully */
proc_exit(0);
}
process_syncing_tables(end_lsn);
pgstat_report_activity(STATE_IDLE, NULL);
}
/*
* Handle ORIGIN message.
*/
static void
handle_origin(StringInfo s)
{
char *origin;
/*
* ORIGIN message can only come inside remote transaction and before
* any actual writes.
*/
if (!in_remote_transaction || IsTransactionState())
elog(ERROR, "ORIGIN message sent out of order");
/* We have to start transaction here so that we can work with origins. */
ensure_transaction();
origin = pglogical_read_origin(s, &remote_origin_lsn);
remote_origin_id = replorigin_by_name(origin, true);
}
/*
* Handle RELATION message.
*
* Note we don't do validation against local schema here. The validation is
* posponed until first change for given relation comes.
*/
static void
handle_relation(StringInfo s)
{
(void) pglogical_read_rel(s);
}
static EState *
create_estate_for_relation(PGLogicalRelation *rel)
{
EState *estate;
ResultRelInfo *resultRelInfo;
RangeTblEntry *rte;
estate = CreateExecutorState();
rte = makeNode(RangeTblEntry);
rte->rtekind = RTE_RELATION;
rte->relid = RelationGetRelid(rel->rel);
rte->relkind = rel->rel->rd_rel->relkind;
estate->es_range_table = list_make1(rte);
resultRelInfo = makeNode(ResultRelInfo);
/* InitResultRelInfo(resultRelInfo,
rel,
1,
0);*/
resultRelInfo->ri_RangeTableIndex = 1;
resultRelInfo->ri_RelationDesc = rel->rel;
resultRelInfo->ri_TrigInstrument = NULL;
estate->es_result_relations = resultRelInfo;
estate->es_num_result_relations = 1;
estate->es_result_relation_info = resultRelInfo;
if (rel->hasTriggers)
resultRelInfo->ri_TrigDesc = CopyTriggerDesc(rel->rel->trigdesc);
if (resultRelInfo->ri_TrigDesc)
{
int n = resultRelInfo->ri_TrigDesc->numtriggers;
resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
palloc0(n * sizeof(FmgrInfo));
resultRelInfo->ri_TrigWhenExprs = (List **)
palloc0(n * sizeof(List *));
/* Triggers might need a slot */
estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
}
else
{
resultRelInfo->ri_TrigFunctions = NULL;
resultRelInfo->ri_TrigWhenExprs = NULL;
}
return estate;
}
static List *
UserTableUpdateOpenIndexes(EState *estate, TupleTableSlot *slot)
{
List *recheckIndexes = NIL;
if (estate->es_result_relation_info->ri_NumIndices > 0)
{
recheckIndexes = ExecInsertIndexTuples(slot,
&slot->tts_tuple->t_self,
estate
#if PG_VERSION_NUM >= 90500
, false, NULL, NIL
#endif
);
/* FIXME: recheck the indexes */
if (recheckIndexes != NIL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("pglogical doesn't support index rechecks")));
list_free(recheckIndexes);
}
return recheckIndexes;
}
static bool
physatt_in_attmap(PGLogicalRelation *rel, int attid)
{
AttrNumber i;
for (i = 0; i < rel->natts; i++)
if (rel->attmap[i] == attid)
return true;
return false;
}
/*
* Executes default values for columns for which we didn't get any data.
*
* TODO: this needs caching, it's not exactly fast.
*/
static void
fill_missing_defaults(PGLogicalRelation *rel, EState *estate,
PGLogicalTupleData *tuple)
{
TupleDesc desc = RelationGetDescr(rel->rel);
AttrNumber num_phys_attrs = desc->natts;
int i;
AttrNumber attnum,
num_defaults = 0;
int *defmap;
ExprState **defexprs;
ExprContext *econtext;
econtext = GetPerTupleExprContext(estate);
/* We got all the data via replication, no need to evaluate anything. */
if (num_phys_attrs == rel->natts)
return;
defmap = (int *) palloc(num_phys_attrs * sizeof(int));
defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
for (attnum = 0; attnum < num_phys_attrs; attnum++)
{
Expr *defexpr;
if (desc->attrs[attnum]->attisdropped)
continue;
if (physatt_in_attmap(rel, attnum))
continue;
defexpr = (Expr *) build_column_default(rel->rel, attnum + 1);
if (defexpr != NULL)
{
/* Run the expression through planner */
defexpr = expression_planner(defexpr);
/* Initialize executable expression in copycontext */
defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
defmap[num_defaults] = attnum;
num_defaults++;
}
}
for (i = 0; i < num_defaults; i++)
tuple->values[defmap[i]] = ExecEvalExpr(defexprs[i],
econtext,
&tuple->nulls[defmap[i]],
NULL);
}
static ApplyExecState *
init_apply_exec_state(PGLogicalRelation *rel)
{
ApplyExecState *aestate = palloc0(sizeof(ApplyExecState));
/* Initialize the executor state. */
aestate->estate = create_estate_for_relation(rel);
aestate->resultRelInfo = aestate->estate->es_result_relation_info;
aestate->slot = ExecInitExtraTupleSlot(aestate->estate);
ExecSetSlotDescriptor(aestate->slot, RelationGetDescr(rel->rel));
if (aestate->resultRelInfo->ri_TrigDesc)
EvalPlanQualInit(&aestate->epqstate, aestate->estate, NULL, NIL, -1);
/* Prepare to catch AFTER triggers. */
AfterTriggerBeginQuery();
return aestate;
}
static void
finish_apply_exec_state(ApplyExecState *aestate)
{
/* Handle queued AFTER triggers. */
AfterTriggerEndQuery(aestate->estate);
/* Terminate EPQ execution if active. */
EvalPlanQualEnd(&aestate->epqstate);
/* Cleanup tuple table. */
ExecResetTupleTable(aestate->estate->es_tupleTable, true);
/* Free the memory. */
FreeExecutorState(aestate->estate);
pfree(aestate);
}
static void
handle_insert(StringInfo s)
{
PGLogicalTupleData newtup;
PGLogicalRelation *rel;
ApplyExecState *aestate;
Oid conflicts;
TupleTableSlot *localslot;
HeapTuple remotetuple;
HeapTuple applytuple;
PGLogicalConflictResolution resolution;
bool started_tx = ensure_transaction();
List *recheckIndexes = NIL;
MemoryContext oldctx;
rel = pglogical_read_insert(s, RowExclusiveLock, &newtup);
/* If in list of relations which are being synchronized, skip. */
if (check_syncing_relation(rel->nspname, rel->relname))
{
pglogical_relation_close(rel, NoLock);
return;
}
/* Initialize the executor state. */
aestate = init_apply_exec_state(rel);
localslot = ExecInitExtraTupleSlot(aestate->estate);
ExecSetSlotDescriptor(localslot, RelationGetDescr(rel->rel));
/* Get snapshot */
PushActiveSnapshot(GetTransactionSnapshot());
ExecOpenIndices(aestate->resultRelInfo
#if PG_VERSION_NUM >= 90500
, false
#endif
);
/* Check for existing tuple with same key */
conflicts = pglogical_tuple_find_conflict(aestate->estate,
&newtup,
localslot);
/* Process and store remote tuple in the slot */
oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(aestate->estate));
fill_missing_defaults(rel, aestate->estate, &newtup);
remotetuple = heap_form_tuple(RelationGetDescr(rel->rel),
newtup.values, newtup.nulls);
MemoryContextSwitchTo(oldctx);
ExecStoreTuple(remotetuple, aestate->slot, InvalidBuffer, true);
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_insert_before_row)
{
aestate->slot = ExecBRInsertTriggers(aestate->estate,
aestate->resultRelInfo,
aestate->slot);
if (aestate->slot == NULL) /* "do nothing" */
{
PopActiveSnapshot();
finish_apply_exec_state(aestate);
pglogical_relation_close(rel, NoLock);
return;
}
}
/* trigger might have changed tuple */
remotetuple = ExecMaterializeSlot(aestate->slot);
if (OidIsValid(conflicts))
{
/* Tuple already exists, try resolving conflict. */
bool apply = try_resolve_conflict(rel->rel, localslot->tts_tuple,
remotetuple, &applytuple,
&resolution);
pglogical_report_conflict(CONFLICT_INSERT_INSERT, rel->rel,
localslot->tts_tuple, remotetuple,
applytuple, resolution);
if (apply)
{
if (applytuple != remotetuple)
ExecStoreTuple(applytuple, aestate->slot, InvalidBuffer, false);
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_update_before_row)
{
aestate->slot = ExecBRUpdateTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&localslot->tts_tuple->t_self,
NULL,
aestate->slot);
if (aestate->slot == NULL) /* "do nothing" */
{
PopActiveSnapshot();
finish_apply_exec_state(aestate);
pglogical_relation_close(rel, NoLock);
}
}
/* trigger might have changed tuple */
remotetuple = ExecMaterializeSlot(aestate->slot);
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, aestate->slot,
aestate->estate);
simple_heap_update(rel->rel, &localslot->tts_tuple->t_self,
aestate->slot->tts_tuple);
if (!HeapTupleIsHeapOnly(aestate->slot->tts_tuple))
recheckIndexes = UserTableUpdateOpenIndexes(aestate->estate,
aestate->slot);
/* AFTER ROW UPDATE Triggers */
ExecARUpdateTriggers(aestate->estate, aestate->resultRelInfo,
&localslot->tts_tuple->t_self,
NULL, applytuple, recheckIndexes);
}
}
else
{
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, aestate->slot,
aestate->estate);
simple_heap_insert(rel->rel, aestate->slot->tts_tuple);
UserTableUpdateOpenIndexes(aestate->estate, aestate->slot);
/* AFTER ROW INSERT Triggers */
ExecARInsertTriggers(aestate->estate, aestate->resultRelInfo,
remotetuple, recheckIndexes);
}
ExecCloseIndices(aestate->resultRelInfo);
PopActiveSnapshot();
/* if INSERT was into our queue, process the message. */
if (RelationGetRelid(rel->rel) == QueueRelid)
{
HeapTuple ht;
LockRelId lockid = rel->rel->rd_lockInfo.lockRelId;
TransactionId oldxid = GetTopTransactionId();
Relation qrel;
/*
* Release transaction bound resources for CONCURRENTLY support.
*/
MemoryContextSwitchTo(MessageContext);
ht = heap_copytuple(aestate->slot->tts_tuple);
finish_apply_exec_state(aestate);
LockRelationIdForSession(&lockid, RowExclusiveLock);
pglogical_relation_close(rel, NoLock);
handle_queued_message(ht, started_tx);
qrel = heap_open(QueueRelid, RowExclusiveLock);
UnlockRelationIdForSession(&lockid, RowExclusiveLock);
heap_close(qrel, NoLock);
if (oldxid != GetTopTransactionId())
CommitTransactionCommand();
}
else
{
/* Otherwise do normal cleanup. */
finish_apply_exec_state(aestate);
pglogical_relation_close(rel, NoLock);
}
CommandCounterIncrement();
}
static void
handle_update(StringInfo s)
{
PGLogicalTupleData oldtup;
PGLogicalTupleData newtup;
PGLogicalTupleData *searchtup;
PGLogicalRelation *rel;
ApplyExecState *aestate;
bool found;
bool hasoldtup;
TupleTableSlot *localslot;
HeapTuple remotetuple;
List *recheckIndexes = NIL;
MemoryContext oldctx;
ensure_transaction();
rel = pglogical_read_update(s, RowExclusiveLock, &hasoldtup, &oldtup,
&newtup);
/* If in list of relations which are being synchronized, skip. */
if (check_syncing_relation(rel->nspname, rel->relname))
{
pglogical_relation_close(rel, NoLock);
return;
}
/* Initialize the executor state. */
aestate = init_apply_exec_state(rel);
localslot = ExecInitExtraTupleSlot(aestate->estate);
ExecSetSlotDescriptor(localslot, RelationGetDescr(rel->rel));
PushActiveSnapshot(GetTransactionSnapshot());
/* Search for existing tuple with same key */
searchtup = hasoldtup ? &oldtup : &newtup;
found = pglogical_tuple_find_replidx(aestate->estate, searchtup, localslot);
/*
* Tuple found.
*
* Note this will fail if there are other conflicting unique indexes.
*/
if (found)
{
TransactionId xmin;
TimestampTz local_ts;
RepOriginId local_origin;
bool apply;
HeapTuple applytuple;
/* Process and store remote tuple in the slot */
oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(aestate->estate));
fill_missing_defaults(rel, aestate->estate, &newtup);
remotetuple = heap_modify_tuple(localslot->tts_tuple,
RelationGetDescr(rel->rel),
newtup.values,
newtup.nulls,
newtup.changed);
MemoryContextSwitchTo(oldctx);
ExecStoreTuple(remotetuple, aestate->slot, InvalidBuffer, true);
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_update_before_row)
{
aestate->slot = ExecBRUpdateTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&localslot->tts_tuple->t_self,
NULL, aestate->slot);
if (aestate->slot == NULL) /* "do nothing" */
{
PopActiveSnapshot();
finish_apply_exec_state(aestate);
pglogical_relation_close(rel, NoLock);
return;
}
}
/* trigger might have changed tuple */
remotetuple = ExecMaterializeSlot(aestate->slot);
get_tuple_origin(localslot->tts_tuple, &xmin, &local_origin,
&local_ts);
/*
* If the local tuple was previously updated by different transaction
* on different server, consider this to be conflict and resolve it.
*/
if (xmin != GetTopTransactionId() &&
local_origin != replorigin_session_origin)
{
PGLogicalConflictResolution resolution;
apply = try_resolve_conflict(rel->rel, localslot->tts_tuple,
remotetuple, &applytuple,
&resolution);
pglogical_report_conflict(CONFLICT_UPDATE_UPDATE, rel->rel,
localslot->tts_tuple, remotetuple,
applytuple, resolution);
if (applytuple != remotetuple)
ExecStoreTuple(applytuple, aestate->slot, InvalidBuffer, false);
}
else
{
apply = true;
applytuple = remotetuple;
}
if (apply)
{
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, aestate->slot,
aestate->estate);
simple_heap_update(rel->rel, &localslot->tts_tuple->t_self,
aestate->slot->tts_tuple);
/* Only update indexes if it's not HOT update. */
if (!HeapTupleIsHeapOnly(aestate->slot->tts_tuple))
{
ExecOpenIndices(aestate->resultRelInfo
#if PG_VERSION_NUM >= 90500
, false
#endif
);
recheckIndexes = UserTableUpdateOpenIndexes(aestate->estate,
aestate->slot);
ExecCloseIndices(aestate->resultRelInfo);
}
/* AFTER ROW UPDATE Triggers */
ExecARUpdateTriggers(aestate->estate, aestate->resultRelInfo,
&localslot->tts_tuple->t_self,
NULL, applytuple, recheckIndexes);
}
}
else
{
/*
* The tuple to be updated could not be found.
*
* We can't do INSERT here because we might not have whole tuple.
*/
remotetuple = heap_form_tuple(RelationGetDescr(rel->rel),
newtup.values,
newtup.nulls);
pglogical_report_conflict(CONFLICT_UPDATE_DELETE, rel->rel, NULL,
remotetuple, NULL, PGLogicalResolution_Skip);
}
/* Cleanup. */
PopActiveSnapshot();
finish_apply_exec_state(aestate);
pglogical_relation_close(rel, NoLock);
CommandCounterIncrement();
}
static void
handle_delete(StringInfo s)
{
PGLogicalTupleData oldtup;
PGLogicalRelation *rel;
ApplyExecState *aestate;
TupleTableSlot *localslot;
ensure_transaction();
rel = pglogical_read_delete(s, RowExclusiveLock, &oldtup);
/* If in list of relations which are being synchronized, skip. */
if (check_syncing_relation(rel->nspname, rel->relname))
{
pglogical_relation_close(rel, NoLock);
return;
}
/* Initialize the executor state. */
aestate = init_apply_exec_state(rel);
localslot = ExecInitExtraTupleSlot(aestate->estate);
ExecSetSlotDescriptor(localslot, RelationGetDescr(rel->rel));
PushActiveSnapshot(GetTransactionSnapshot());
if (pglogical_tuple_find_replidx(aestate->estate, &oldtup, localslot))
{
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_update_before_row)
{
bool dodelete = ExecBRDeleteTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&localslot->tts_tuple->t_self,
NULL);
if (!dodelete) /* "do nothing" */
{
PopActiveSnapshot();
finish_apply_exec_state(aestate);
pglogical_relation_close(rel, NoLock);
return;
}
}
/* Tuple found, delete it. */
simple_heap_delete(rel->rel, &localslot->tts_tuple->t_self);
/* AFTER ROW DELETE Triggers */
ExecARDeleteTriggers(aestate->estate, aestate->resultRelInfo,
&localslot->tts_tuple->t_self, NULL);
}
else
{
/* The tuple to be deleted could not be found. */
HeapTuple remotetuple = heap_form_tuple(RelationGetDescr(rel->rel),
oldtup.values, oldtup.nulls);
pglogical_report_conflict(CONFLICT_DELETE_DELETE, rel->rel, NULL,
remotetuple, NULL, PGLogicalResolution_Skip);
}
/* Cleanup. */
PopActiveSnapshot();
finish_apply_exec_state(aestate);
pglogical_relation_close(rel, NoLock);
CommandCounterIncrement();
}
inline static bool
getmsgisend(StringInfo msg)
{
return msg->cursor == msg->len;
}
static void
handle_startup(StringInfo s)
{
uint8 msgver = pq_getmsgbyte(s);
if (msgver != 1)
elog(ERROR, "Expected startup message version 1, but got %u", msgver);
/*
* The startup message consists of null-terminated strings as key/value
* pairs. The first entry is always the format identifier.
*/
do {
const char *k, *v;
k = pq_getmsgstring(s);
if (strlen(k) == 0)
ereport(ERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("invalid startup message: key has zero length")));
if (getmsgisend(s))
ereport(ERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("invalid startup message: key '%s' has no following value", k)));
/* It's OK to have a zero length value */
v = pq_getmsgstring(s);
handle_startup_param(k, v);
} while (!getmsgisend(s));
}
static bool
parse_bool_param(const char *key, const char *value)
{
bool result;
if (!parse_bool(value, &result))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("couldn't parse value '%s' for key '%s' as boolean",
value, key)));
return result;
}
static void
handle_startup_param(const char *key, const char *value)
{
elog(DEBUG2, "apply got pglogical startup msg param %s=%s", key, value);
if (strcmp(key, "pg_version") == 0)
elog(DEBUG1, "upstream Pg version is %s", value);
if (strcmp(key, "encoding") == 0)
{
int encoding = pg_char_to_encoding(value);
if (encoding != GetDatabaseEncoding())
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("expected encoding=%s from upstream but got %s",
GetDatabaseEncodingName(), value)));
}
if (strcmp(key, "forward_changeset_origins") == 0)
{
bool fwd = parse_bool_param(key, value);
/* FIXME: Store this somewhere */
elog(DEBUG1, "changeset origin forwarding enabled: %s", fwd ? "t" : "f");
}
if (strcmp(key, "hooks.startup_hook_enabled") == 0)
{
if (!parse_bool_param(key, value))
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("pglogical requested a startup hook, but it was not activated"),
errdetail("hooks.startup_hook_enabled='f' returned by upstream")));
}
if (strcmp(key, "hooks.row_filter_enabled") == 0)
{
if (!parse_bool_param(key, value))