-
Notifications
You must be signed in to change notification settings - Fork 15
/
spock_apply_heap.c
1211 lines (1020 loc) · 31.2 KB
/
spock_apply_heap.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
/*-------------------------------------------------------------------------
*
* spock_apply_heap.c
* spock apply functions using heap api
*
* Copyright (c) 2022-2023, pgEdge, Inc.
* Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, The Regents of the University of California
*
* IDENTIFICATION
* spock_apply_heap.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 "executor/executor.h"
#include "libpq/pqformat.h"
#include "mb/pg_wchar.h"
#include "nodes/makefuncs.h"
#include "nodes/parsenodes.h"
#include "optimizer/clauses.h"
#include "optimizer/optimizer.h"
#include "replication/origin.h"
#include "replication/reorderbuffer.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/attoptcache.h"
#include "utils/builtins.h"
#include "utils/jsonb.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#include "spock_common.h"
#include "spock_conflict.h"
#include "spock_executor.h"
#include "spock_node.h"
#include "spock_proto_native.h"
#include "spock_queue.h"
#include "spock_relcache.h"
#include "spock_repset.h"
#include "spock_rpc.h"
#include "spock_sync.h"
#include "spock_worker.h"
#include "spock_apply_heap.h"
typedef struct ApplyExecState {
EState *estate;
EPQState epqstate;
ResultRelInfo *resultRelInfo;
TupleTableSlot *slot;
} ApplyExecState;
/* State related to bulk insert */
typedef struct ApplyMIState
{
SpockRelation *rel;
ApplyExecState *aestate;
CommandId cid;
BulkInsertState bistate;
TupleTableSlot **buffered_tuples;
int maxbuffered_tuples;
int nbuffered_tuples;
} ApplyMIState;
#define TTS_TUP(slot) (((HeapTupleTableSlot *)slot)->tuple)
static ApplyMIState *spkmistate = NULL;
#ifndef NO_LOG_OLD_VALUE
static bool relation_has_delta_columns(SpockRelation *rel);
static void build_delta_tuple(SpockRelation *rel, SpockTupleData *oldtup,
SpockTupleData *newtup, SpockTupleData *deltatup,
TupleTableSlot *localslot);
#endif
void
spock_apply_heap_begin(void)
{
return;
}
void
spock_apply_heap_commit(void)
{
TimestampTz next_prune;
TimestampTz now;
int32 num_pruned;
/*
* For pruning of the Conflict Tracking Hash we remember our
* assigned origin and the last commit timestamp.
*/
LWLockAcquire(SpockCtx->lock, LW_EXCLUSIVE);
if (MySpockWorker->worker.apply.replorigin != replorigin_session_origin)
{
if (MySpockWorker->worker.apply.replorigin != InvalidRepOriginId)
/* This should never happen */
elog(LOG, "SPOCK: remote origin id changes from %d to %d",
MySpockWorker->worker.apply.replorigin,
replorigin_session_origin);
MySpockWorker->worker.apply.replorigin = replorigin_session_origin;
}
MySpockWorker->worker.apply.last_ts = replorigin_session_origin_timestamp;
LWLockRelease(SpockCtx->lock);
next_prune = TimestampTzPlusMilliseconds(SpockCtx->ctt_last_prune,
SpockCtx->ctt_prune_interval * 1000);
now = GetCurrentTimestamp();
if (next_prune <= now)
{
SpockCtx->ctt_last_prune = now;
PushActiveSnapshot(GetTransactionSnapshot());
num_pruned = spock_ctt_prune();
PopActiveSnapshot();
CommandCounterIncrement();
elog(DEBUG1, "SPOCK: %d entries pruned from CTT", num_pruned);
}
spock_ctt_close();
}
static List *
UserTableUpdateOpenIndexes(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *slot, bool update)
{
List *recheckIndexes = NIL;
if (relinfo->ri_NumIndices > 0)
{
recheckIndexes = ExecInsertIndexTuples(
#if PG_VERSION_NUM >= 140000
relinfo,
#endif
slot,
estate
#if PG_VERSION_NUM >= 140000
, update
#endif
, false, NULL, NIL
#if PG_VERSION_NUM >= 160000
, false
#endif
);
/* FIXME: recheck the indexes */
if (recheckIndexes != NIL)
{
StringInfoData si;
ListCell *lc;
const char *idxname, *relname, *nspname;
Relation target_rel = relinfo->ri_RelationDesc;
relname = RelationGetRelationName(target_rel);
nspname = get_namespace_name(RelationGetNamespace(target_rel));
initStringInfo(&si);
foreach (lc, recheckIndexes)
{
Oid idxoid = lfirst_oid(lc);
idxname = get_rel_name(idxoid);
if (idxname == NULL)
elog(ERROR, "cache lookup failed for index oid %u", idxoid);
if (si.len > 0)
appendStringInfoString(&si, ", ");
appendStringInfoString(&si, quote_identifier(idxname));
}
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("spock doesn't support deferrable indexes"),
errdetail("relation %s.%s has deferrable indexes: %s",
quote_identifier(nspname),
quote_identifier(relname),
si.data)));
}
list_free(recheckIndexes);
}
return recheckIndexes;
}
static bool
physatt_in_attmap(SpockRelation *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(SpockRelation *rel, EState *estate,
SpockTupleData *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 (TupleDescAttr(desc,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);
}
#ifndef NO_LOG_OLD_VALUE
static bool
relation_has_delta_columns(SpockRelation *rel)
{
TupleDesc tupdesc = RelationGetDescr(rel->rel);
AttributeOpts *aopt;
int attno;
for (attno = 1; attno <= tupdesc->natts; attno++)
{
/* check the attribute options */
aopt = get_attribute_options(rel->rel->rd_id, attno);
if (aopt != NULL && aopt->log_old_value)
return true;
}
return false;
}
static void
build_delta_tuple(SpockRelation *rel, SpockTupleData *oldtup,
SpockTupleData *newtup,
SpockTupleData *deltatup,
TupleTableSlot *localslot)
{
TupleDesc tupdesc = RelationGetDescr(rel->rel);
Form_pg_attribute att;
AttributeOpts *aopt;
int attidx;
Datum loc_value;
Datum delta;
bool loc_isnull;
PGFunction func_add;
PGFunction func_sub;
for (attidx = 0; attidx < tupdesc->natts; attidx++)
{
/* Get the attribute options */
aopt = get_attribute_options(rel->rel->rd_id, attidx + 1);
if (aopt == NULL || !aopt->log_old_value)
{
deltatup->values[attidx] = 0xdeadbeef;
deltatup->nulls[attidx] = true;
deltatup->changed[attidx] = false;
continue;
}
/*
* Column is marked LOG_OLD_VALUE=true. We use that as flag
* to apply the delta between the remote old and new instead
* of the plain new value.
*
* To perform the actual delta math we need the functions behind
* the '+' and '-' operators for the data type.
*
* XXX: This is currently hardcoded for the builtin data types
* we support. Ideally we would lookup those operators in the
* system cache, but that isn't straight forward and we get into
* all sorts of trouble when it comes to user defined data types
* and the search path.
*/
att = TupleDescAttr(tupdesc, attidx);
switch (att->atttypid)
{
case INT2OID:
func_add = int2pl;
func_sub = int2mi;
break;
case INT4OID:
func_add = int4pl;
func_sub = int4mi;
break;
case INT8OID:
func_add = int8pl;
func_sub = int8mi;
break;
case FLOAT4OID:
func_add = float4pl;
func_sub = float4mi;
break;
case FLOAT8OID:
func_add = float8pl;
func_sub = float8mi;
break;
case NUMERICOID:
func_add = numeric_add;
func_sub = numeric_sub;
break;
case MONEYOID:
func_add = cash_pl;
func_sub = cash_mi;
break;
#if 0
/*
* BOOL is supposed to follow OR logic. But this code only
* works if we have a conflict. A local transaction is not
* prevented from changing it back to false, and it won't
* propagate. We need to come up with a different solution.
*/
case BOOLOID:
func_add = boolor_statefunc;
func_sub = boolor_statefunc;
break;
#endif
default:
elog(ERROR, "spock delta replication for type %d not supported",
att->atttypid);
}
if (oldtup->nulls[attidx])
{
/*
* This is a special case. Columns for delta apply need to
* be marked NOT NULL and LOG_OLD_VALUE=true. During this
* remote UPDATE LOG_OLD_VALUE setting was false. We use this
* as a flag to force plain NEW value application. This is
* useful in case a server ever gets out of sync.
*/
deltatup->values[attidx] = newtup->values[attidx];
deltatup->nulls[attidx] = false;
deltatup->changed[attidx] = true;
}
else
{
/* We also need the old value of the current local tuple */
loc_value = heap_getattr(TTS_TUP(localslot), attidx + 1, tupdesc,
&loc_isnull);
/* Finally we can do the actual delta apply */
delta = DirectFunctionCall2(func_sub,
newtup->values[attidx],
oldtup->values[attidx]);
deltatup->values[attidx] = DirectFunctionCall2(func_add, loc_value,
delta);
deltatup->nulls[attidx] = false;
deltatup->changed[attidx] = true;
}
}
}
#endif /* NO_LOG_OLD_VALUE */
static ApplyExecState *
init_apply_exec_state(SpockRelation *rel)
{
ApplyExecState *aestate = palloc0(sizeof(ApplyExecState));
/* Initialize the executor state. */
aestate->estate = create_estate_for_relation(rel->rel, true);
aestate->resultRelInfo = makeNode(ResultRelInfo);
InitResultRelInfo(aestate->resultRelInfo, rel->rel, 1, 0);
#if PG_VERSION_NUM < 140000
aestate->estate->es_result_relations = aestate->resultRelInfo;
aestate->estate->es_num_result_relations = 1;
aestate->estate->es_result_relation_info = aestate->resultRelInfo;
#endif
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)
{
/* Close indexes */
ExecCloseIndices(aestate->resultRelInfo);
/* Handle queued AFTER triggers. */
AfterTriggerEndQuery(aestate->estate);
/* Terminate EPQ execution if active. */
if (aestate->resultRelInfo->ri_TrigDesc)
{
EvalPlanQualEnd(&aestate->epqstate);
ExecCloseResultRelations(aestate->estate);
}
/* Cleanup tuple table. */
ExecResetTupleTable(aestate->estate->es_tupleTable, true);
/* Free the memory. */
FreeExecutorState(aestate->estate);
pfree(aestate);
}
/*
* Handle insert via low level api.
*/
void
spock_apply_heap_insert(SpockRelation *rel, SpockTupleData *newtup)
{
ApplyExecState *aestate;
Oid conflicts_idx_id;
TupleTableSlot *localslot;
HeapTuple remotetuple;
HeapTuple applytuple;
SpockConflictResolution resolution;
List *recheckIndexes = NIL;
MemoryContext oldctx;
bool has_before_triggers = false;
/* Initialize the executor state. */
aestate = init_apply_exec_state(rel);
localslot = table_slot_create(rel->rel, &aestate->estate->es_tupleTable);
/* update stats */
handle_stats_counter(rel->rel, MyApplyWorker->subid,
SPOCK_STATS_INSERT_COUNT, 1);
ExecOpenIndices(aestate->resultRelInfo
, false
);
/*
* Check for existing tuple with same key in any unique index containing
* only normal columns. This doesn't just check the replica identity index,
* but it'll prefer it and use it first.
*/
conflicts_idx_id = spock_tuple_find_conflict(aestate->resultRelInfo,
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);
ExecStoreHeapTuple(remotetuple, aestate->slot, true);
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_insert_before_row)
{
has_before_triggers = true;
if (!SPKExecBRInsertTriggers(aestate->estate,
aestate->resultRelInfo,
aestate->slot))
{
finish_apply_exec_state(aestate);
return;
}
}
/* trigger might have changed tuple */
remotetuple = ExecFetchSlotHeapTuple(aestate->slot, true, NULL);
/* Did we find matching key in any candidate-key index? */
if (OidIsValid(conflicts_idx_id))
{
TransactionId xmin;
TimestampTz local_ts;
RepOriginId local_origin;
bool apply;
bool local_origin_found;
local_origin_found = get_tuple_origin(RelationGetRelid(rel->rel),
TTS_TUP(localslot),
NULL, &xmin,
&local_origin, &local_ts);
/* Tuple already exists, try resolving conflict. */
apply = try_resolve_conflict(rel->rel, TTS_TUP(localslot),
remotetuple, &applytuple,
local_origin, local_ts,
&resolution);
spock_report_conflict(CONFLICT_INSERT_INSERT, rel,
TTS_TUP(localslot), NULL, remotetuple,
applytuple, resolution, xmin,
local_origin_found, local_origin,
local_ts, conflicts_idx_id,
has_before_triggers);
if (apply)
{
#if PG_VERSION_NUM >= 160000
TU_UpdateIndexes update_indexes;
#else
bool update_indexes;
#endif
if (applytuple != remotetuple)
ExecStoreHeapTuple(applytuple, aestate->slot, false);
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_update_before_row)
{
if (!SPKExecBRUpdateTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL,
aestate->slot))
{
finish_apply_exec_state(aestate);
return;
}
}
/* trigger might have changed tuple */
remotetuple = ExecFetchSlotHeapTuple(aestate->slot, true, NULL);
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, aestate->slot,
aestate->estate);
simple_table_tuple_update(rel->rel,
&(localslot->tts_tid),
aestate->slot,
aestate->estate->es_snapshot,
&update_indexes);
if (update_indexes)
recheckIndexes = UserTableUpdateOpenIndexes(aestate->resultRelInfo,
aestate->estate,
aestate->slot,
true);
/* AFTER ROW UPDATE Triggers */
SPKExecARUpdateTriggers(aestate->estate, aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL, aestate->slot, recheckIndexes);
}
}
else
{
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, aestate->slot,
aestate->estate);
simple_table_tuple_insert(aestate->resultRelInfo->ri_RelationDesc, aestate->slot);
UserTableUpdateOpenIndexes(aestate->resultRelInfo, aestate->estate, aestate->slot, false);
/* AFTER ROW INSERT Triggers */
SPKExecARInsertTriggers(aestate->estate, aestate->resultRelInfo,
aestate->slot, recheckIndexes);
}
finish_apply_exec_state(aestate);
CommandCounterIncrement();
}
/*
* Handle update via low level api.
*/
void
spock_apply_heap_update(SpockRelation *rel, SpockTupleData *oldtup,
SpockTupleData *newtup)
{
ApplyExecState *aestate;
bool found;
TupleTableSlot *localslot;
HeapTuple remotetuple;
List *recheckIndexes = NIL;
MemoryContext oldctx;
Oid replident_idx_id;
bool has_before_triggers = false;
bool is_delta_apply = false;
/* Initialize the executor state. */
aestate = init_apply_exec_state(rel);
localslot = table_slot_create(rel->rel, &aestate->estate->es_tupleTable);
/* update stats */
handle_stats_counter(rel->rel, MyApplyWorker->subid,
SPOCK_STATS_UPDATE_COUNT, 1);
/* Search for existing tuple with same key */
found = spock_tuple_find_replidx(aestate->resultRelInfo, oldtup, localslot,
&replident_idx_id);
/*
* Tuple found, update the local tuple.
*
* Note this will fail if there are other unique indexes and one or more of
* them would be violated by the new tuple.
*/
if (found)
{
TransactionId xmin;
TimestampTz local_ts;
RepOriginId local_origin;
bool local_origin_found;
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(TTS_TUP(localslot),
RelationGetDescr(rel->rel),
newtup->values,
newtup->nulls,
newtup->changed);
MemoryContextSwitchTo(oldctx);
ExecStoreHeapTuple(remotetuple, aestate->slot, true);
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_update_before_row)
{
has_before_triggers = true;
if (!SPKExecBRUpdateTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL, aestate->slot))
{
finish_apply_exec_state(aestate);
return;
}
}
/* trigger might have changed tuple */
remotetuple = ExecFetchSlotHeapTuple(aestate->slot, true, NULL);
local_origin_found = get_tuple_origin(RelationGetRelid(rel->rel),
TTS_TUP(localslot),
&(localslot->tts_tid), &xmin,
&local_origin, &local_ts);
/*
* If we found the original commit timestamp for the
* local tuple, perform conflict resolution.
*/
if (local_origin_found)
{
SpockConflictResolution resolution;
apply = try_resolve_conflict(rel->rel, TTS_TUP(localslot),
remotetuple, &applytuple,
local_origin, local_ts,
&resolution);
spock_report_conflict(CONFLICT_UPDATE_UPDATE, rel,
TTS_TUP(localslot), oldtup,
remotetuple, applytuple, resolution,
xmin, local_origin_found, local_origin,
local_ts, replident_idx_id,
has_before_triggers);
/*
* Remote tuple won, so we go forward with that as a base.
*/
if (apply && applytuple != remotetuple)
ExecStoreHeapTuple(applytuple, aestate->slot, false);
}
else
{
/*
* We didn't even find the commit timestamp for the current
* local tuple. So the remote tuple must be newer than that.
*/
apply = true;
applytuple = remotetuple;
}
#ifndef NO_LOG_OLD_VALUE
/*
* If the relation has columns that are marked LOG_OLD_VALUE
* we apply the delta between the remote new and old values.
*/
if (relation_has_delta_columns(rel))
{
SpockTupleData deltatup;
HeapTuple currenttuple;
/*
* Depending on previous conflict resolution our final NEW
* tuple will be based on either the incoming remote tuple
* or the existing local one and then the delta processing
* on top of that.
*/
if (apply)
{
currenttuple = ExecFetchSlotHeapTuple(aestate->slot,
true, NULL);
}
else
{
currenttuple = ExecFetchSlotHeapTuple(localslot,
true, NULL);
}
oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(aestate->estate));
build_delta_tuple(rel, oldtup, newtup, &deltatup, localslot);
applytuple = heap_modify_tuple(currenttuple,
RelationGetDescr(rel->rel),
deltatup.values,
deltatup.nulls,
deltatup.changed);
MemoryContextSwitchTo(oldctx);
ExecStoreHeapTuple(applytuple, aestate->slot, true);
if (!apply)
{
is_delta_apply = true;
apply = true;
/* Count the DCA event in stats */
handle_stats_counter(rel->rel, MyApplyWorker->subid,
SPOCK_STATS_DCA_COUNT, 1);
}
}
#endif /* NO_LOG_OLD_VALUE */
if (apply)
{
#if PG_VERSION_NUM >= 160000
TU_UpdateIndexes update_indexes;
#else
bool update_indexes;
#endif
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, aestate->slot,
aestate->estate);
simple_table_tuple_update(rel->rel,
&(localslot->tts_tid),
aestate->slot,
aestate->estate->es_snapshot,
&update_indexes);
if (update_indexes)
{
ExecOpenIndices(aestate->resultRelInfo
, false
);
recheckIndexes = UserTableUpdateOpenIndexes(aestate->resultRelInfo,
aestate->estate,
aestate->slot,
true);
}
if (is_delta_apply)
{
/*
* We forced an update to a row that we normally had
* to skip because it has delta resolve columns. Remember
* the correct origin, xmin and commit timestamp for
* get_tuple_origion() to figure it out.
*/
spock_ctt_store(RelationGetRelid(rel->rel),
&(aestate->slot->tts_tid), local_origin,
GetTopTransactionId(), local_ts);
}
/* AFTER ROW UPDATE Triggers */
SPKExecARUpdateTriggers(aestate->estate, aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL, aestate->slot, 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);
spock_report_conflict(CONFLICT_UPDATE_DELETE, rel, NULL, oldtup,
remotetuple, NULL, SpockResolution_Skip,
InvalidTransactionId, false,
InvalidRepOriginId, (TimestampTz)0,
replident_idx_id, has_before_triggers);
}
/* Cleanup. */
finish_apply_exec_state(aestate);
CommandCounterIncrement();
}
/*
* Handle delete via low level api.
*/
void
spock_apply_heap_delete(SpockRelation *rel, SpockTupleData *oldtup)
{
ApplyExecState *aestate;
TupleTableSlot *localslot;
Oid replident_idx_id;
bool has_before_triggers = false;
/* Initialize the executor state. */
aestate = init_apply_exec_state(rel);
localslot = table_slot_create(rel->rel, &aestate->estate->es_tupleTable);
/* update stats */
handle_stats_counter(rel->rel, MyApplyWorker->subid,
SPOCK_STATS_DELETE_COUNT, 1);
if (spock_tuple_find_replidx(aestate->resultRelInfo, oldtup, localslot,
&replident_idx_id))
{
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_delete_before_row)
{
bool dodelete = SPKExecBRDeleteTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL);
has_before_triggers = true;
if (!dodelete) /* "do nothing" */
{
finish_apply_exec_state(aestate);
return;
}
}
/* Tuple found, delete it. */
simple_heap_delete(rel->rel, &(TTS_TUP(localslot)->t_self));
/* AFTER ROW DELETE Triggers */
SPKExecARDeleteTriggers(aestate->estate, aestate->resultRelInfo,
&(TTS_TUP(localslot)->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);
spock_report_conflict(CONFLICT_DELETE_DELETE, rel, NULL, oldtup,
remotetuple, NULL, SpockResolution_Skip,
InvalidTransactionId, false,
InvalidRepOriginId, (TimestampTz)0,
replident_idx_id, has_before_triggers);
}
/* Cleanup. */
finish_apply_exec_state(aestate);
CommandCounterIncrement();
}
bool
spock_apply_heap_can_mi(SpockRelation *rel)
{
/* Multi insert is only supported when conflicts result in errors. */
return spock_conflict_resolver == SPOCK_RESOLVE_ERROR;
}
/*
* MultiInsert initialization.
*/
static void
spock_apply_heap_mi_start(SpockRelation *rel)
{
MemoryContext oldctx;
ApplyExecState *aestate;
ResultRelInfo *resultRelInfo;
TupleDesc desc;
bool volatile_defexprs = false;
if (spkmistate && spkmistate->rel == rel)
return;
if (spkmistate && spkmistate->rel != rel)
spock_apply_heap_mi_finish(spkmistate->rel);
oldctx = MemoryContextSwitchTo(TopTransactionContext);
/* Initialize new MultiInsert state. */
spkmistate = palloc0(sizeof(ApplyMIState));
spkmistate->rel = rel;
/* Initialize the executor state. */
spkmistate->aestate = aestate = init_apply_exec_state(rel);
MemoryContextSwitchTo(TopTransactionContext);
resultRelInfo = aestate->resultRelInfo;
ExecOpenIndices(resultRelInfo
, false
);
/* Check if table has any volatile default expressions. */
desc = RelationGetDescr(rel->rel);
if (desc->natts != rel->natts)
{
int attnum;
for (attnum = 0; attnum < desc->natts; attnum++)
{