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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
|
/*-------------------------------------------------------------------------
*
* pglogical_apply_heap.c
* pglogical apply functions using heap api
*
* Copyright (c) 2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* pglogical_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 "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/clauses.h"
#if PG_VERSION_NUM >= 120000
#include "optimizer/optimizer.h"
#else
#include "optimizer/planner.h"
#endif
#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/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_executor.h"
#include "pglogical_node.h"
#include "pglogical_proto_native.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_apply_heap.h"
typedef struct ApplyExecState {
EState *estate;
EPQState epqstate;
ResultRelInfo *resultRelInfo;
TupleTableSlot *slot;
} ApplyExecState;
/* State related to bulk insert */
typedef struct ApplyMIState
{
PGLogicalRelation *rel;
ApplyExecState *aestate;
CommandId cid;
BulkInsertState bistate;
#if PG_VERSION_NUM >= 120000
TupleTableSlot **buffered_tuples;
#else
HeapTuple *buffered_tuples;
#endif
int maxbuffered_tuples;
int nbuffered_tuples;
} ApplyMIState;
#if PG_VERSION_NUM >= 120000
#define TTS_TUP(slot) (((HeapTupleTableSlot *)slot)->tuple)
#else
#define TTS_TUP(slot) (slot->tts_tuple)
#endif
static ApplyMIState *pglmistate = NULL;
void
pglogical_apply_heap_begin(void)
{
}
void
pglogical_apply_heap_commit(void)
{
}
static List *
UserTableUpdateOpenIndexes(EState *estate, TupleTableSlot *slot)
{
List *recheckIndexes = NIL;
if (estate->es_result_relation_info->ri_NumIndices > 0)
{
recheckIndexes = ExecInsertIndexTuples(slot,
#if PG_VERSION_NUM < 120000
&slot->tts_tuple->t_self,
#endif
estate
#if PG_VERSION_NUM >= 90500
, false, NULL, NIL
#endif
);
/* FIXME: recheck the indexes */
if (recheckIndexes != NIL)
{
StringInfoData si;
ListCell *lc;
const char *idxname, *relname, *nspname;
Relation target_rel = estate->es_result_relation_info->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("pglogical 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(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 (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);
}
static ApplyExecState *
init_apply_exec_state(PGLogicalRelation *rel)
{
ApplyExecState *aestate = palloc0(sizeof(ApplyExecState));
PushActiveSnapshot(GetTransactionSnapshot());
/* Initialize the executor state. */
aestate->estate = create_estate_for_relation(rel->rel, true);
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)
{
/* 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);
/* Cleanup tuple table. */
ExecResetTupleTable(aestate->estate->es_tupleTable, true);
/* Free the memory. */
FreeExecutorState(aestate->estate);
pfree(aestate);
PopActiveSnapshot();
}
/*
* Handle insert via low level api.
*/
void
pglogical_apply_heap_insert(PGLogicalRelation *rel, PGLogicalTupleData *newtup)
{
ApplyExecState *aestate;
Oid conflicts_idx_id;
TupleTableSlot *localslot;
HeapTuple remotetuple;
HeapTuple applytuple;
PGLogicalConflictResolution resolution;
List *recheckIndexes = NIL;
MemoryContext oldctx;
bool has_before_triggers = false;
/* Initialize the executor state. */
aestate = init_apply_exec_state(rel);
#if PG_VERSION_NUM >= 120000
localslot = table_slot_create(rel->rel, &aestate->estate->es_tupleTable);
#else
localslot = ExecInitExtraTupleSlot(aestate->estate);
ExecSetSlotDescriptor(localslot, RelationGetDescr(rel->rel));
#endif
ExecOpenIndices(aestate->resultRelInfo
#if PG_VERSION_NUM >= 90500
, false
#endif
);
/*
* 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 = 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);
ExecStoreHeapTuple(remotetuple, aestate->slot, true);
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_insert_before_row)
{
has_before_triggers = true;
#if PG_VERSION_NUM >= 120000
if (!ExecBRInsertTriggers(aestate->estate,
aestate->resultRelInfo,
aestate->slot))
#else
aestate->slot = ExecBRInsertTriggers(aestate->estate,
aestate->resultRelInfo,
aestate->slot);
if (aestate->slot == NULL) /* "do nothing" */
#endif
{
finish_apply_exec_state(aestate);
return;
}
}
/* trigger might have changed tuple */
#if PG_VERSION_NUM >= 120000
remotetuple = ExecFetchSlotHeapTuple(aestate->slot, true, NULL);
#else
remotetuple = ExecMaterializeSlot(aestate->slot);
#endif
/* 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(TTS_TUP(localslot), &xmin,
&local_origin, &local_ts);
/* Tuple already exists, try resolving conflict. */
apply = try_resolve_conflict(rel->rel, TTS_TUP(localslot),
remotetuple, &applytuple,
&resolution);
pglogical_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 >= 120000
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 PG_VERSION_NUM >= 120000
if (!ExecBRUpdateTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL,
aestate->slot))
#else
aestate->slot = ExecBRUpdateTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL,
aestate->slot);
if (aestate->slot == NULL) /* "do nothing" */
#endif
{
finish_apply_exec_state(aestate);
return;
}
}
/* trigger might have changed tuple */
#if PG_VERSION_NUM >= 120000
remotetuple = ExecFetchSlotHeapTuple(aestate->slot, true, NULL);
#else
remotetuple = ExecMaterializeSlot(aestate->slot);
#endif
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, aestate->slot,
aestate->estate);
#if PG_VERSION_NUM >= 120000
simple_table_tuple_update(rel->rel,
&(localslot->tts_tid),
aestate->slot,
aestate->estate->es_snapshot,
&update_indexes);
if (update_indexes)
#else
simple_heap_update(rel->rel, &(TTS_TUP(localslot)->t_self),
TTS_TUP(aestate->slot));
if (!HeapTupleIsHeapOnly(TTS_TUP(aestate->slot)))
#endif
recheckIndexes = UserTableUpdateOpenIndexes(aestate->estate,
aestate->slot);
/* AFTER ROW UPDATE Triggers */
#if PG_VERSION_NUM >= 120000
ExecARUpdateTriggers(aestate->estate, aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL, aestate->slot, recheckIndexes);
#else
ExecARUpdateTriggers(aestate->estate, aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL, applytuple, recheckIndexes);
#endif
}
}
else
{
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, aestate->slot,
aestate->estate);
#if PG_VERSION_NUM >= 120000
simple_table_tuple_insert(aestate->resultRelInfo->ri_RelationDesc, aestate->slot);
#else
simple_heap_insert(rel->rel, TTS_TUP(aestate->slot));
#endif
UserTableUpdateOpenIndexes(aestate->estate, aestate->slot);
/* AFTER ROW INSERT Triggers */
#if PG_VERSION_NUM >= 120000
ExecARInsertTriggers(aestate->estate, aestate->resultRelInfo,
aestate->slot, recheckIndexes);
#else
ExecARInsertTriggers(aestate->estate, aestate->resultRelInfo,
remotetuple, recheckIndexes);
#endif
}
finish_apply_exec_state(aestate);
CommandCounterIncrement();
}
/*
* Handle update via low level api.
*/
void
pglogical_apply_heap_update(PGLogicalRelation *rel, PGLogicalTupleData *oldtup,
PGLogicalTupleData *newtup)
{
ApplyExecState *aestate;
bool found;
TupleTableSlot *localslot;
HeapTuple remotetuple;
List *recheckIndexes = NIL;
MemoryContext oldctx;
Oid replident_idx_id;
bool has_before_triggers = false;
/* Initialize the executor state. */
aestate = init_apply_exec_state(rel);
#if PG_VERSION_NUM >= 120000
localslot = table_slot_create(rel->rel, &aestate->estate->es_tupleTable);
#else
localslot = ExecInitExtraTupleSlot(aestate->estate);
ExecSetSlotDescriptor(localslot, RelationGetDescr(rel->rel));
#endif
PushActiveSnapshot(GetTransactionSnapshot());
/* Search for existing tuple with same key */
found = pglogical_tuple_find_replidx(aestate->estate, 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 PG_VERSION_NUM >= 120000
if (!ExecBRUpdateTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL, aestate->slot))
#else
aestate->slot = ExecBRUpdateTriggers(aestate->estate,
&aestate->epqstate,
aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL, aestate->slot);
if (aestate->slot == NULL) /* "do nothing" */
#endif
{
finish_apply_exec_state(aestate);
return;
}
}
/* trigger might have changed tuple */
#if PG_VERSION_NUM >= 120000
remotetuple = ExecFetchSlotHeapTuple(aestate->slot, true, NULL);
#else
remotetuple = ExecMaterializeSlot(aestate->slot);
#endif
local_origin_found = get_tuple_origin(TTS_TUP(localslot), &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 (local_origin_found &&
xmin != GetTopTransactionId() &&
local_origin != replorigin_session_origin)
{
PGLogicalConflictResolution resolution;
apply = try_resolve_conflict(rel->rel, TTS_TUP(localslot),
remotetuple, &applytuple,
&resolution);
pglogical_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);
if (applytuple != remotetuple)
ExecStoreHeapTuple(applytuple, aestate->slot, false);
}
else
{
apply = true;
applytuple = remotetuple;
}
if (apply)
{
#if PG_VERSION_NUM >= 120000
bool update_indexes;
#endif
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, aestate->slot,
aestate->estate);
#if PG_VERSION_NUM >= 120000
simple_table_tuple_update(rel->rel,
&(localslot->tts_tid),
aestate->slot,
aestate->estate->es_snapshot,
&update_indexes);
if (update_indexes)
#else
simple_heap_update(rel->rel, &(TTS_TUP(localslot)->t_self),
TTS_TUP(aestate->slot));
/* Only update indexes if it's not HOT update. */
if (!HeapTupleIsHeapOnly(TTS_TUP(aestate->slot)))
#endif
{
ExecOpenIndices(aestate->resultRelInfo
#if PG_VERSION_NUM >= 90500
, false
#endif
);
recheckIndexes = UserTableUpdateOpenIndexes(aestate->estate,
aestate->slot);
}
/* AFTER ROW UPDATE Triggers */
#if PG_VERSION_NUM >= 120000
ExecARUpdateTriggers(aestate->estate, aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL, aestate->slot, recheckIndexes);
#else
ExecARUpdateTriggers(aestate->estate, aestate->resultRelInfo,
&(TTS_TUP(localslot)->t_self),
NULL, applytuple, recheckIndexes);
#endif
}
}
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, NULL, oldtup,
remotetuple, NULL, PGLogicalResolution_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
pglogical_apply_heap_delete(PGLogicalRelation *rel, PGLogicalTupleData *oldtup)
{
ApplyExecState *aestate;
TupleTableSlot *localslot;
Oid replident_idx_id;
bool has_before_triggers = false;
/* Initialize the executor state. */
aestate = init_apply_exec_state(rel);
#if PG_VERSION_NUM >= 120000
localslot = table_slot_create(rel->rel, &aestate->estate->es_tupleTable);
#else
localslot = ExecInitExtraTupleSlot(aestate->estate);
ExecSetSlotDescriptor(localslot, RelationGetDescr(rel->rel));
#endif
PushActiveSnapshot(GetTransactionSnapshot());
if (pglogical_tuple_find_replidx(aestate->estate, oldtup, localslot,
&replident_idx_id))
{
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_delete_before_row)
{
bool dodelete = ExecBRDeleteTriggers(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);
pglogical_relation_close(rel, NoLock);
return;
}
}
/* Tuple found, delete it. */
simple_heap_delete(rel->rel, &(TTS_TUP(localslot)->t_self));
/* AFTER ROW DELETE Triggers */
ExecARDeleteTriggers(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);
pglogical_report_conflict(CONFLICT_DELETE_DELETE, rel, NULL, oldtup,
remotetuple, NULL, PGLogicalResolution_Skip,
InvalidTransactionId, false,
InvalidRepOriginId, (TimestampTz)0,
replident_idx_id, has_before_triggers);
}
/* Cleanup. */
finish_apply_exec_state(aestate);
CommandCounterIncrement();
}
bool
pglogical_apply_heap_can_mi(PGLogicalRelation *rel)
{
/* Multi insert is only supported when conflicts result in errors. */
return pglogical_conflict_resolver == PGLOGICAL_RESOLVE_ERROR;
}
/*
* MultiInsert initialization.
*/
static void
pglogical_apply_heap_mi_start(PGLogicalRelation *rel)
{
MemoryContext oldctx;
ApplyExecState *aestate;
ResultRelInfo *resultRelInfo;
TupleDesc desc;
bool volatile_defexprs = false;
if (pglmistate && pglmistate->rel == rel)
return;
if (pglmistate && pglmistate->rel != rel)
pglogical_apply_heap_mi_finish(pglmistate->rel);
oldctx = MemoryContextSwitchTo(TopTransactionContext);
/* Initialize new MultiInsert state. */
pglmistate = palloc0(sizeof(ApplyMIState));
pglmistate->rel = rel;
/* Initialize the executor state. */
pglmistate->aestate = aestate = init_apply_exec_state(rel);
MemoryContextSwitchTo(TopTransactionContext);
resultRelInfo = aestate->resultRelInfo;
ExecOpenIndices(resultRelInfo
#if PG_VERSION_NUM >= 90500
, false
#endif
);
/* 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++)
{
Expr *defexpr;
if (TupleDescAttr(desc,attnum)->attisdropped)
continue;
defexpr = (Expr *) build_column_default(rel->rel, attnum + 1);
if (defexpr != NULL)
{
/* Run the expression through planner */
defexpr = expression_planner(defexpr);
volatile_defexprs = contain_volatile_functions_not_nextval((Node *) defexpr);
if (volatile_defexprs)
break;
}
}
}
/*
* Decide if to buffer tuples based on the collected information
* about the table.
*/
if ((resultRelInfo->ri_TrigDesc != NULL &&
(resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
resultRelInfo->ri_TrigDesc->trig_insert_instead_row)) ||
volatile_defexprs)
{
pglmistate->maxbuffered_tuples = 1;
}
else
{
pglmistate->maxbuffered_tuples = 1000;
}
pglmistate->cid = GetCurrentCommandId(true);
pglmistate->bistate = GetBulkInsertState();
/* Make the space for buffer. */
#if PG_VERSION_NUM >= 120000
pglmistate->buffered_tuples = palloc0(pglmistate->maxbuffered_tuples * sizeof(TupleTableSlot *));
#else
pglmistate->buffered_tuples = palloc0(pglmistate->maxbuffered_tuples * sizeof(HeapTuple));
#endif
pglmistate->nbuffered_tuples = 0;
MemoryContextSwitchTo(oldctx);
}
/* Write the buffered tuples. */
static void
pglogical_apply_heap_mi_flush(void)
{
MemoryContext oldctx;
ResultRelInfo *resultRelInfo;
int i;
if (!pglmistate || pglmistate->nbuffered_tuples == 0)
return;
oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(pglmistate->aestate->estate));
heap_multi_insert(pglmistate->rel->rel,
pglmistate->buffered_tuples,
pglmistate->nbuffered_tuples,
pglmistate->cid,
0, /* hi_options */
pglmistate->bistate);
MemoryContextSwitchTo(oldctx);
resultRelInfo = pglmistate->aestate->resultRelInfo;
/*
* If there are any indexes, update them for all the inserted tuples, and
* run AFTER ROW INSERT triggers.
*/
if (resultRelInfo->ri_NumIndices > 0)
{
for (i = 0; i < pglmistate->nbuffered_tuples; i++)
{
List *recheckIndexes = NIL;
#if PG_VERSION_NUM < 120000
ExecStoreTuple(pglmistate->buffered_tuples[i],
pglmistate->aestate->slot,
InvalidBuffer, false);
#endif
recheckIndexes =
ExecInsertIndexTuples(
#if PG_VERSION_NUM >= 120000
pglmistate->buffered_tuples[i],
#else
pglmistate->aestate->slot,
&(pglmistate->buffered_tuples[i]->t_self),
#endif
pglmistate->aestate->estate
#if PG_VERSION_NUM >= 90500
, false, NULL, NIL
#endif
);
ExecARInsertTriggers(pglmistate->aestate->estate, resultRelInfo,
pglmistate->buffered_tuples[i],
recheckIndexes);
list_free(recheckIndexes);
}
}
/*
* There's no indexes, but see if we need to run AFTER ROW INSERT triggers
* anyway.
*/
else if (resultRelInfo->ri_TrigDesc != NULL &&
resultRelInfo->ri_TrigDesc->trig_insert_after_row)
{
for (i = 0; i < pglmistate->nbuffered_tuples; i++)
{
ExecARInsertTriggers(pglmistate->aestate->estate, resultRelInfo,
pglmistate->buffered_tuples[i],
NIL);
}
}
pglmistate->nbuffered_tuples = 0;
}
/* Add tuple to the MultiInsert. */
void
pglogical_apply_heap_mi_add_tuple(PGLogicalRelation *rel,
PGLogicalTupleData *tup)
{
MemoryContext oldctx;
ApplyExecState *aestate;
HeapTuple remotetuple;
TupleTableSlot *slot;
pglogical_apply_heap_mi_start(rel);
/*
* If sufficient work is pending, process that first
*/
if (pglmistate->nbuffered_tuples >= pglmistate->maxbuffered_tuples)
pglogical_apply_heap_mi_flush();
/* Process and store remote tuple in the slot */
aestate = pglmistate->aestate;
if (pglmistate->nbuffered_tuples == 0)
{
/*
* Reset the per-tuple exprcontext. We can only do this if the
* tuple buffer is empty. (Calling the context the per-tuple
* memory context is a bit of a misnomer now.)
*/
ResetPerTupleExprContext(aestate->estate);
}
oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(aestate->estate));
fill_missing_defaults(rel, aestate->estate, tup);
remotetuple = heap_form_tuple(RelationGetDescr(rel->rel),
tup->values, tup->nulls);
MemoryContextSwitchTo(TopTransactionContext);
slot = aestate->slot;
/* Store the tuple in slot, but make sure it's not freed. */
ExecStoreHeapTuple(remotetuple, slot, false);
if (aestate->resultRelInfo->ri_TrigDesc &&
aestate->resultRelInfo->ri_TrigDesc->trig_insert_before_row)
{
#if PG_VERSION_NUM >= 120000
if (!ExecBRInsertTriggers(aestate->estate,
aestate->resultRelInfo,
slot))
#else
slot = ExecBRInsertTriggers(aestate->estate,
aestate->resultRelInfo,
slot);
if (slot == NULL)
#endif
{
MemoryContextSwitchTo(oldctx);
return;
}
#if PG_VERSION_NUM < 120000
else
remotetuple = ExecMaterializeSlot(slot);
#endif
}
/* Check the constraints of the tuple */
if (rel->rel->rd_att->constr)
ExecConstraints(aestate->resultRelInfo, slot,
aestate->estate);
pglmistate->buffered_tuples[pglmistate->nbuffered_tuples++] =
#if PG_VERSION_NUM >= 120000
slot
#else
remotetuple
#endif
;
MemoryContextSwitchTo(oldctx);
}
void
pglogical_apply_heap_mi_finish(PGLogicalRelation *rel)
{
if (!pglmistate)
return;
Assert(pglmistate->rel == rel);
pglogical_apply_heap_mi_flush();
FreeBulkInsertState(pglmistate->bistate);
finish_apply_exec_state(pglmistate->aestate);
pfree(pglmistate->buffered_tuples);
pfree(pglmistate);
pglmistate = NULL;
}
|