PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
worker.c File Reference
#include "postgres.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "funcapi.h"
#include "access/xact.h"
#include "access/xlog_internal.h"
#include "catalog/namespace.h"
#include "catalog/pg_subscription.h"
#include "catalog/pg_subscription_rel.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/nodeModifyTable.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "mb/pg_wchar.h"
#include "nodes/makefuncs.h"
#include "optimizer/planner.h"
#include "parser/parse_relation.h"
#include "postmaster/bgworker.h"
#include "postmaster/postmaster.h"
#include "replication/decode.h"
#include "replication/logical.h"
#include "replication/logicalproto.h"
#include "replication/logicalrelation.h"
#include "replication/logicalworker.h"
#include "replication/reorderbuffer.h"
#include "replication/origin.h"
#include "replication/snapbuild.h"
#include "replication/walreceiver.h"
#include "replication/worker_internal.h"
#include "rewrite/rewriteHandler.h"
#include "storage/bufmgr.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/timeout.h"
#include "utils/tqual.h"
#include "utils/syscache.h"
Include dependency graph for worker.c:

Go to the source code of this file.

Data Structures

struct  FlushPosition
 
struct  SlotErrCallbackArg
 

Macros

#define NAPTIME_PER_CYCLE   1000 /* max sleep time between cycles (1s) */
 

Typedefs

typedef struct FlushPosition FlushPosition
 
typedef struct SlotErrCallbackArg SlotErrCallbackArg
 

Functions

static void send_feedback (XLogRecPtr recvpos, bool force, bool requestReply)
 
static void store_flush_position (XLogRecPtr remote_lsn)
 
static void reread_subscription (void)
 
static bool should_apply_changes_for_rel (LogicalRepRelMapEntry *rel)
 
static bool ensure_transaction (void)
 
static EStatecreate_estate_for_relation (LogicalRepRelMapEntry *rel)
 
static void slot_fill_defaults (LogicalRepRelMapEntry *rel, EState *estate, TupleTableSlot *slot)
 
static void slot_store_error_callback (void *arg)
 
static void slot_store_cstrings (TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values)
 
static void slot_modify_cstrings (TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values, bool *replaces)
 
static void apply_handle_begin (StringInfo s)
 
static void apply_handle_commit (StringInfo s)
 
static void apply_handle_origin (StringInfo s)
 
static void apply_handle_relation (StringInfo s)
 
static void apply_handle_type (StringInfo s)
 
static Oid GetRelationIdentityOrPK (Relation rel)
 
static void apply_handle_insert (StringInfo s)
 
static void check_relation_updatable (LogicalRepRelMapEntry *rel)
 
static void apply_handle_update (StringInfo s)
 
static void apply_handle_delete (StringInfo s)
 
static void apply_dispatch (StringInfo s)
 
static void get_flush_position (XLogRecPtr *write, XLogRecPtr *flush, bool *have_pending_txes)
 
static void UpdateWorkerStats (XLogRecPtr last_lsn, TimestampTz send_time, bool reply)
 
static void LogicalRepApplyLoop (XLogRecPtr last_received)
 
static void subscription_change_cb (Datum arg, int cacheid, uint32 hashvalue)
 
void ApplyWorkerMain (Datum main_arg)
 

Variables

static dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping)
 
static MemoryContext ApplyContext = NULL
 
MemoryContext ApplyCacheContext = NULL
 
WalReceiverConnwrconn = NULL
 
SubscriptionMySubscription = NULL
 
bool MySubscriptionValid = false
 
bool in_remote_transaction = false
 
static XLogRecPtr remote_final_lsn = InvalidXLogRecPtr
 

Macro Definition Documentation

#define NAPTIME_PER_CYCLE   1000 /* max sleep time between cycles (1s) */

Definition at line 87 of file worker.c.

Referenced by LogicalRepApplyLoop().

Typedef Documentation

Function Documentation

static void apply_dispatch ( StringInfo  s)
static

Definition at line 854 of file worker.c.

References apply_handle_begin(), apply_handle_commit(), apply_handle_delete(), apply_handle_insert(), apply_handle_origin(), apply_handle_relation(), apply_handle_type(), apply_handle_update(), ereport, errcode(), errmsg(), ERROR, and pq_getmsgbyte().

Referenced by LogicalRepApplyLoop().

855 {
856  char action = pq_getmsgbyte(s);
857 
858  switch (action)
859  {
860  /* BEGIN */
861  case 'B':
863  break;
864  /* COMMIT */
865  case 'C':
867  break;
868  /* INSERT */
869  case 'I':
871  break;
872  /* UPDATE */
873  case 'U':
875  break;
876  /* DELETE */
877  case 'D':
879  break;
880  /* RELATION */
881  case 'R':
883  break;
884  /* TYPE */
885  case 'Y':
887  break;
888  /* ORIGIN */
889  case 'O':
891  break;
892  default:
893  ereport(ERROR,
894  (errcode(ERRCODE_PROTOCOL_VIOLATION),
895  errmsg("invalid logical replication message type %c", action)));
896  }
897 }
static void apply_handle_type(StringInfo s)
Definition: worker.c:510
static void apply_handle_insert(StringInfo s)
Definition: worker.c:540
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static void apply_handle_delete(StringInfo s)
Definition: worker.c:755
static void apply_handle_begin(StringInfo s)
Definition: worker.c:418
#define ereport(elevel, rest)
Definition: elog.h:122
static void apply_handle_commit(StringInfo s)
Definition: worker.c:440
static void apply_handle_update(StringInfo s)
Definition: worker.c:634
static void apply_handle_relation(StringInfo s)
Definition: worker.c:495
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:432
static void apply_handle_origin(StringInfo s)
Definition: worker.c:473
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void apply_handle_begin ( StringInfo  s)
static

Definition at line 418 of file worker.c.

References LogicalRepBeginData::committime, LogicalRepBeginData::final_lsn, in_remote_transaction, logicalrep_read_begin(), NULL, pgstat_report_activity(), remote_final_lsn, replorigin_session_origin_lsn, replorigin_session_origin_timestamp, and STATE_RUNNING.

Referenced by apply_dispatch().

419 {
420  LogicalRepBeginData begin_data;
421 
422  logicalrep_read_begin(s, &begin_data);
423 
426 
427  remote_final_lsn = begin_data.final_lsn;
428 
429  in_remote_transaction = true;
430 
432 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:113
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2957
void logicalrep_read_begin(StringInfo in, LogicalRepBeginData *begin_data)
Definition: proto.c:57
bool in_remote_transaction
Definition: worker.c:112
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:151
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:152
XLogRecPtr final_lsn
Definition: logicalproto.h:65
#define NULL
Definition: c.h:229
TimestampTz committime
Definition: logicalproto.h:66
static void apply_handle_commit ( StringInfo  s)
static

Definition at line 440 of file worker.c.

References am_tablesync_worker(), Assert, LogicalRepCommitData::commit_lsn, LogicalRepCommitData::committime, CommitTransactionCommand(), LogicalRepCommitData::end_lsn, in_remote_transaction, IsTransactionState(), logicalrep_read_commit(), NULL, pgstat_report_activity(), process_syncing_tables(), remote_final_lsn, replorigin_session_origin_lsn, replorigin_session_origin_timestamp, STATE_IDLE, and store_flush_position().

Referenced by apply_dispatch().

441 {
442  LogicalRepCommitData commit_data;
443 
444  logicalrep_read_commit(s, &commit_data);
445 
448 
449  Assert(commit_data.commit_lsn == remote_final_lsn);
450 
451  /* The synchronization worker runs in single transaction. */
453  {
455 
456  store_flush_position(commit_data.end_lsn);
457  }
458 
459  in_remote_transaction = false;
460 
461  /* Process any tables that are being synchronized in parallel. */
462  process_syncing_tables(commit_data.end_lsn);
463 
465 }
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:957
static XLogRecPtr remote_final_lsn
Definition: worker.c:113
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:412
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2957
void CommitTransactionCommand(void)
Definition: xact.c:2747
bool in_remote_transaction
Definition: worker.c:112
static bool am_tablesync_worker(void)
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:151
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:152
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
bool IsTransactionState(void)
Definition: xact.c:350
void logicalrep_read_commit(StringInfo in, LogicalRepCommitData *commit_data)
Definition: proto.c:92
XLogRecPtr commit_lsn
Definition: logicalproto.h:72
TimestampTz committime
Definition: logicalproto.h:74
static void apply_handle_delete ( StringInfo  s)
static

Definition at line 755 of file worker.c.

References AfterTriggerEndQuery(), Assert, check_relation_updatable(), CommandCounterIncrement(), create_estate_for_relation(), DEBUG1, ensure_transaction(), ereport, errmsg(), EState::es_result_relation_info, EState::es_tupleTable, EvalPlanQualEnd(), EvalPlanQualInit(), EvalPlanQualSetSlot, ExecCloseIndices(), ExecInitExtraTupleSlot(), ExecOpenIndices(), ExecResetTupleTable(), ExecSetSlotDescriptor(), ExecSimpleRelationDelete(), FreeExecutorState(), GetPerTupleMemoryContext, GetRelationIdentityOrPK(), GetTransactionSnapshot(), LogicalRepRelMapEntry::localrel, LockTupleExclusive, logicalrep_read_delete(), logicalrep_rel_close(), logicalrep_rel_open(), MemoryContextSwitchTo(), NIL, NoLock, NULL, OidIsValid, PopActiveSnapshot(), PushActiveSnapshot(), RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), RelationGetDescr, RelationGetRelationName, LogicalRepRelMapEntry::remoterel, REPLICA_IDENTITY_FULL, LogicalRepRelation::replident, RowExclusiveLock, should_apply_changes_for_rel(), slot_store_cstrings(), and LogicalRepTupleData::values.

Referenced by apply_dispatch().

756 {
758  LogicalRepTupleData oldtup;
759  LogicalRepRelId relid;
760  Oid idxoid;
761  EState *estate;
762  EPQState epqstate;
763  TupleTableSlot *remoteslot;
764  TupleTableSlot *localslot;
765  bool found;
766  MemoryContext oldctx;
767 
769 
770  relid = logicalrep_read_delete(s, &oldtup);
773  {
774  /*
775  * The relation can't become interesting in the middle of the
776  * transaction so it's safe to unlock it.
777  */
779  return;
780  }
781 
782  /* Check if we can do the delete. */
784 
785  /* Initialize the executor state. */
786  estate = create_estate_for_relation(rel);
787  remoteslot = ExecInitExtraTupleSlot(estate);
789  localslot = ExecInitExtraTupleSlot(estate);
791  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
792 
795 
796  /* Find the tuple using the replica identity index. */
798  slot_store_cstrings(remoteslot, rel, oldtup.values);
799  MemoryContextSwitchTo(oldctx);
800 
801  /*
802  * Try to find tuple using either replica identity index, primary key
803  * or if needed, sequential scan.
804  */
805  idxoid = GetRelationIdentityOrPK(rel->localrel);
806  Assert(OidIsValid(idxoid) ||
808 
809  if (OidIsValid(idxoid))
810  found = RelationFindReplTupleByIndex(rel->localrel, idxoid,
812  remoteslot, localslot);
813  else
815  remoteslot, localslot);
816  /* If found delete it. */
817  if (found)
818  {
819  EvalPlanQualSetSlot(&epqstate, localslot);
820 
821  /* Do the actual delete. */
822  ExecSimpleRelationDelete(estate, &epqstate, localslot);
823  }
824  else
825  {
826  /* The tuple to be deleted could not be found.*/
827  ereport(DEBUG1,
828  (errmsg("logical replication could not find row for delete "
829  "in replication target %s",
831  }
832 
833  /* Cleanup. */
836 
837  /* Handle queued AFTER triggers. */
838  AfterTriggerEndQuery(estate);
839 
840  EvalPlanQualEnd(&epqstate);
841  ExecResetTupleTable(estate->es_tupleTable, false);
842  FreeExecutorState(estate);
843 
845 
847 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:135
#define NIL
Definition: pg_list.h:69
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:177
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:524
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
#define DEBUG1
Definition: elog.h:25
LogicalRepRelId logicalrep_read_delete(StringInfo in, LogicalRepTupleData *oldtup)
Definition: proto.c:277
#define RelationGetDescr(relation)
Definition: rel.h:429
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:374
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
#define OidIsValid(objectId)
Definition: c.h:538
bool RelationFindReplTupleByIndex(Relation rel, Oid idxoid, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:149
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3066
void FreeExecutorState(EState *estate)
Definition: execUtils.c:173
#define REPLICA_IDENTITY_FULL
Definition: pg_class.h:179
static bool ensure_transaction(void)
Definition: worker.c:151
LogicalRepRelation remoterel
static void slot_store_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values)
Definition: worker.c:296
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
void ExecSimpleRelationDelete(EState *estate, EPQState *epqstate, TupleTableSlot *searchslot)
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:437
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:231
#define ereport(elevel, rest)
Definition: elog.h:122
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:600
List * es_tupleTable
Definition: execnodes.h:437
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
void CommandCounterIncrement(void)
Definition: xact.c:922
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
void EvalPlanQualInit(EPQState *epqstate, EState *estate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2655
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
char * values[MaxTupleAttributeNumber]
Definition: logicalproto.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:461
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4170
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
uint32 LogicalRepRelId
Definition: logicalproto.h:37
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:220
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:422
static void apply_handle_insert ( StringInfo  s)
static

Definition at line 540 of file worker.c.

References AfterTriggerEndQuery(), CommandCounterIncrement(), create_estate_for_relation(), ensure_transaction(), EState::es_result_relation_info, EState::es_tupleTable, ExecCloseIndices(), ExecInitExtraTupleSlot(), ExecOpenIndices(), ExecResetTupleTable(), ExecSetSlotDescriptor(), ExecSimpleRelationInsert(), FreeExecutorState(), GetPerTupleMemoryContext, GetTransactionSnapshot(), LogicalRepRelMapEntry::localrel, logicalrep_read_insert(), logicalrep_rel_close(), logicalrep_rel_open(), MemoryContextSwitchTo(), NoLock, PopActiveSnapshot(), PushActiveSnapshot(), RelationGetDescr, RowExclusiveLock, should_apply_changes_for_rel(), slot_fill_defaults(), slot_store_cstrings(), and LogicalRepTupleData::values.

Referenced by apply_dispatch().

541 {
543  LogicalRepTupleData newtup;
544  LogicalRepRelId relid;
545  EState *estate;
546  TupleTableSlot *remoteslot;
547  MemoryContext oldctx;
548 
550 
551  relid = logicalrep_read_insert(s, &newtup);
554  {
555  /*
556  * The relation can't become interesting in the middle of the
557  * transaction so it's safe to unlock it.
558  */
560  return;
561  }
562 
563  /* Initialize the executor state. */
564  estate = create_estate_for_relation(rel);
565  remoteslot = ExecInitExtraTupleSlot(estate);
567 
568  /* Process and store remote tuple in the slot */
570  slot_store_cstrings(remoteslot, rel, newtup.values);
571  slot_fill_defaults(rel, estate, remoteslot);
572  MemoryContextSwitchTo(oldctx);
573 
576 
577  /* Do the insert. */
578  ExecSimpleRelationInsert(estate, remoteslot);
579 
580  /* Cleanup. */
583 
584  /* Handle queued AFTER triggers. */
585  AfterTriggerEndQuery(estate);
586 
587  ExecResetTupleTable(estate->es_tupleTable, false);
588  FreeExecutorState(estate);
589 
591 
593 }
void ExecSimpleRelationInsert(EState *estate, TupleTableSlot *slot)
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:135
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:177
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
#define RelationGetDescr(relation)
Definition: rel.h:429
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:374
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:149
LogicalRepRelId logicalrep_read_insert(StringInfo in, LogicalRepTupleData *newtup)
Definition: proto.c:160
static void slot_fill_defaults(LogicalRepRelMapEntry *rel, EState *estate, TupleTableSlot *slot)
Definition: worker.c:216
void FreeExecutorState(EState *estate)
Definition: execUtils.c:173
static bool ensure_transaction(void)
Definition: worker.c:151
static void slot_store_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values)
Definition: worker.c:296
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
#define RowExclusiveLock
Definition: lockdefs.h:38
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:231
List * es_tupleTable
Definition: execnodes.h:437
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
void CommandCounterIncrement(void)
Definition: xact.c:922
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
char * values[MaxTupleAttributeNumber]
Definition: logicalproto.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:461
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4170
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
uint32 LogicalRepRelId
Definition: logicalproto.h:37
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:422
static void apply_handle_origin ( StringInfo  s)
static

Definition at line 473 of file worker.c.

References am_tablesync_worker(), ereport, errcode(), errmsg(), ERROR, in_remote_transaction, and IsTransactionState().

Referenced by apply_dispatch().

474 {
475  /*
476  * ORIGIN message can only come inside remote transaction and before
477  * any actual writes.
478  */
479  if (!in_remote_transaction ||
481  ereport(ERROR,
482  (errcode(ERRCODE_PROTOCOL_VIOLATION),
483  errmsg("ORIGIN message sent out of order")));
484 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
bool in_remote_transaction
Definition: worker.c:112
static bool am_tablesync_worker(void)
#define ereport(elevel, rest)
Definition: elog.h:122
bool IsTransactionState(void)
Definition: xact.c:350
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void apply_handle_relation ( StringInfo  s)
static

Definition at line 495 of file worker.c.

References logicalrep_read_rel(), and logicalrep_relmap_update().

Referenced by apply_dispatch().

496 {
497  LogicalRepRelation *rel;
498 
499  rel = logicalrep_read_rel(s);
501 }
LogicalRepRelation * logicalrep_read_rel(StringInfo in)
Definition: proto.c:324
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:166
static void apply_handle_type ( StringInfo  s)
static

Definition at line 510 of file worker.c.

References logicalrep_read_typ(), and logicalrep_typmap_update().

Referenced by apply_dispatch().

511 {
512  LogicalRepTyp typ;
513 
514  logicalrep_read_typ(s, &typ);
516 }
void logicalrep_read_typ(StringInfo in, LogicalRepTyp *ltyp)
Definition: proto.c:376
void logicalrep_typmap_update(LogicalRepTyp *remotetyp)
Definition: relation.c:417
static void apply_handle_update ( StringInfo  s)
static

Definition at line 634 of file worker.c.

References AfterTriggerEndQuery(), Assert, LogicalRepTupleData::changed, check_relation_updatable(), CommandCounterIncrement(), create_estate_for_relation(), DEBUG1, elog, ensure_transaction(), EState::es_result_relation_info, EState::es_tupleTable, EvalPlanQualEnd(), EvalPlanQualInit(), EvalPlanQualSetSlot, ExecClearTuple(), ExecCloseIndices(), ExecInitExtraTupleSlot(), ExecOpenIndices(), ExecResetTupleTable(), ExecSetSlotDescriptor(), ExecSimpleRelationUpdate(), ExecStoreTuple(), FreeExecutorState(), GetPerTupleMemoryContext, GetRelationIdentityOrPK(), GetTransactionSnapshot(), InvalidBuffer, LogicalRepRelMapEntry::localrel, LockTupleExclusive, logicalrep_read_update(), logicalrep_rel_close(), logicalrep_rel_open(), MemoryContextSwitchTo(), NIL, NoLock, NULL, OidIsValid, PopActiveSnapshot(), PushActiveSnapshot(), RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), RelationGetDescr, RelationGetRelationName, LogicalRepRelMapEntry::remoterel, REPLICA_IDENTITY_FULL, LogicalRepRelation::replident, RowExclusiveLock, should_apply_changes_for_rel(), slot_modify_cstrings(), slot_store_cstrings(), TupleTableSlot::tts_tuple, and LogicalRepTupleData::values.

Referenced by apply_dispatch().

635 {
637  LogicalRepRelId relid;
638  Oid idxoid;
639  EState *estate;
640  EPQState epqstate;
641  LogicalRepTupleData oldtup;
642  LogicalRepTupleData newtup;
643  bool has_oldtup;
644  TupleTableSlot *localslot;
645  TupleTableSlot *remoteslot;
646  bool found;
647  MemoryContext oldctx;
648 
650 
651  relid = logicalrep_read_update(s, &has_oldtup, &oldtup,
652  &newtup);
655  {
656  /*
657  * The relation can't become interesting in the middle of the
658  * transaction so it's safe to unlock it.
659  */
661  return;
662  }
663 
664  /* Check if we can do the update. */
666 
667  /* Initialize the executor state. */
668  estate = create_estate_for_relation(rel);
669  remoteslot = ExecInitExtraTupleSlot(estate);
671  localslot = ExecInitExtraTupleSlot(estate);
673  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
674 
677 
678  /* Build the search tuple. */
680  slot_store_cstrings(remoteslot, rel,
681  has_oldtup ? oldtup.values : newtup.values);
682  MemoryContextSwitchTo(oldctx);
683 
684  /*
685  * Try to find tuple using either replica identity index, primary key
686  * or if needed, sequential scan.
687  */
688  idxoid = GetRelationIdentityOrPK(rel->localrel);
689  Assert(OidIsValid(idxoid) ||
690  (rel->remoterel.replident == REPLICA_IDENTITY_FULL && has_oldtup));
691 
692  if (OidIsValid(idxoid))
693  found = RelationFindReplTupleByIndex(rel->localrel, idxoid,
695  remoteslot, localslot);
696  else
698  remoteslot, localslot);
699 
700  ExecClearTuple(remoteslot);
701 
702  /*
703  * Tuple found.
704  *
705  * Note this will fail if there are other conflicting unique indexes.
706  */
707  if (found)
708  {
709  /* Process and store remote tuple in the slot */
711  ExecStoreTuple(localslot->tts_tuple, remoteslot, InvalidBuffer, false);
712  slot_modify_cstrings(remoteslot, rel, newtup.values, newtup.changed);
713  MemoryContextSwitchTo(oldctx);
714 
715  EvalPlanQualSetSlot(&epqstate, remoteslot);
716 
717  /* Do the actual update. */
718  ExecSimpleRelationUpdate(estate, &epqstate, localslot, remoteslot);
719  }
720  else
721  {
722  /*
723  * The tuple to be updated could not be found.
724  *
725  * TODO what to do here, change the log level to LOG perhaps?
726  */
727  elog(DEBUG1,
728  "logical replication did not find row for update "
729  "in replication target relation \"%s\"",
731  }
732 
733  /* Cleanup. */
736 
737  /* Handle queued AFTER triggers. */
738  AfterTriggerEndQuery(estate);
739 
740  EvalPlanQualEnd(&epqstate);
741  ExecResetTupleTable(estate->es_tupleTable, false);
742  FreeExecutorState(estate);
743 
745 
747 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:135
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:177
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:524
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
#define DEBUG1
Definition: elog.h:25
#define RelationGetDescr(relation)
Definition: rel.h:429
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:374
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
#define OidIsValid(objectId)
Definition: c.h:538
bool RelationFindReplTupleByIndex(Relation rel, Oid idxoid, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:149
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3066
void FreeExecutorState(EState *estate)
Definition: execUtils.c:173
#define REPLICA_IDENTITY_FULL
Definition: pg_class.h:179
static bool ensure_transaction(void)
Definition: worker.c:151
LogicalRepRelation remoterel
static void slot_store_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values)
Definition: worker.c:296
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
bool changed[MaxTupleAttributeNumber]
Definition: logicalproto.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:437
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:231
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:600
List * es_tupleTable
Definition: execnodes.h:437
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
void CommandCounterIncrement(void)
Definition: xact.c:922
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
void EvalPlanQualInit(EPQState *epqstate, EState *estate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2655
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
LogicalRepRelId logicalrep_read_update(StringInfo in, bool *has_oldtuple, LogicalRepTupleData *oldtup, LogicalRepTupleData *newtup)
Definition: proto.c:211
char * values[MaxTupleAttributeNumber]
Definition: logicalproto.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:461
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4170
static void slot_modify_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values, bool *replaces)
Definition: worker.c:360
bool RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)
HeapTuple tts_tuple
Definition: tuptable.h:120
#define elog
Definition: elog.h:219
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
void ExecSimpleRelationUpdate(EState *estate, EPQState *epqstate, TupleTableSlot *searchslot, TupleTableSlot *slot)
uint32 LogicalRepRelId
Definition: logicalproto.h:37
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:220
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:422
void ApplyWorkerMain ( Datum  main_arg)

Definition at line 1416 of file worker.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), am_tablesync_worker(), Assert, BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), BackgroundWorker::bgw_name, CacheMemoryContext, CacheRegisterSyscacheCallback(), CommitTransactionCommand(), Subscription::conninfo, CreateCacheMemoryContext(), CurrentResourceOwner, DatumGetObjectId, LogicalRepWorker::dbid, DEBUG1, elog, Subscription::enabled, ereport, errmsg(), ERROR, get_rel_name(), GetCurrentTimestamp(), GetSubscription(), invalidate_syncing_table_states(), LogicalRepWorker::last_recv_time, LogicalRepWorker::last_send_time, load_file(), LOG, WalRcvStreamOptions::logical, LOGICALREP_PROTO_VERSION_NUM, logicalrep_worker_attach(), logicalrep_worker_sigterm(), LogicalRepApplyLoop(), LogicalRepSyncTableStart(), MemoryContextSwitchTo(), MyBgworkerEntry, MyLogicalRepWorker, MySubscriptionValid, Subscription::name, NAMEDATALEN, NULL, Subscription::oid, OidIsValid, options, pfree(), PGC_S_OVERRIDE, PGC_S_SESSION, PGC_SUSET, PGC_USERSET, pqsignal(), proc_exit(), WalRcvStreamOptions::proto, pstrdup(), Subscription::publications, LogicalRepWorker::relid, replorigin_by_name(), replorigin_create(), replorigin_session_get_progress(), replorigin_session_origin, replorigin_session_setup(), LogicalRepWorker::reply_time, ResourceOwnerCreate(), server_version, SetConfigOption(), Subscription::slotname, WalRcvStreamOptions::slotname, snprintf(), WalRcvStreamOptions::startpoint, StartTransactionCommand(), LogicalRepWorker::subid, subscription_change_cb(), SUBSCRIPTIONOID, SUBSCRIPTIONRELMAP, LogicalRepWorker::userid, walrcv_connect, walrcv_disconnect, walrcv_identify_system, and walrcv_startstreaming.

Referenced by logicalrep_worker_launch().

1417 {
1418  int worker_slot = DatumGetObjectId(main_arg);
1419  MemoryContext oldctx;
1420  char originname[NAMEDATALEN];
1421  XLogRecPtr origin_startpos;
1422  char *myslotname;
1424 
1425  /* Attach to slot */
1426  logicalrep_worker_attach(worker_slot);
1427 
1428  /* Setup signal handling */
1431 
1432  /* Initialise stats to a sanish value */
1435 
1436  /* Make it easy to identify our processes. */
1437  SetConfigOption("application_name", MyBgworkerEntry->bgw_name,
1439 
1440  /* Load the libpq-specific functions */
1441  load_file("libpqwalreceiver", false);
1442 
1445  "logical replication apply");
1446 
1447  /* Run as replica session replication role. */
1448  SetConfigOption("session_replication_role", "replica",
1450 
1451  /* Connect to our database. */
1454 
1455  /* Load the subscription into persistent memory context. */
1458  "ApplyCacheContext",
1463  MySubscriptionValid = true;
1464  MemoryContextSwitchTo(oldctx);
1465 
1466  if (!MySubscription->enabled)
1467  {
1468  ereport(LOG,
1469  (errmsg("logical replication worker for subscription \"%s\" will not "
1470  "start because the subscription was disabled during startup",
1471  MySubscription->name)));
1472 
1473  proc_exit(0);
1474  }
1475 
1476  /* Keep us informed about subscription changes. */
1479  (Datum) 0);
1480 
1481  if (am_tablesync_worker())
1482  elog(LOG, "logical replication sync for subscription %s, table %s started",
1484  else
1485  elog(LOG, "logical replication apply for subscription %s started",
1486  MySubscription->name);
1487 
1489 
1490  /* Connect to the origin and start the replication. */
1491  elog(DEBUG1, "connecting to publisher using connection string \"%s\"",
1493 
1494  if (am_tablesync_worker())
1495  {
1496  char *syncslotname;
1497 
1498  /* This is table synchroniation worker, call initial sync. */
1499  syncslotname = LogicalRepSyncTableStart(&origin_startpos);
1500 
1501  /* The slot name needs to be allocated in permanent memory context. */
1503  myslotname = pstrdup(syncslotname);
1504  MemoryContextSwitchTo(oldctx);
1505 
1506  pfree(syncslotname);
1507  }
1508  else
1509  {
1510  /* This is main apply worker */
1511  RepOriginId originid;
1512  TimeLineID startpointTLI;
1513  char *err;
1514  int server_version;
1515 
1516  myslotname = MySubscription->slotname;
1517 
1518  /* Setup replication origin tracking. */
1520  snprintf(originname, sizeof(originname), "pg_%u", MySubscription->oid);
1521  originid = replorigin_by_name(originname, true);
1522  if (!OidIsValid(originid))
1523  originid = replorigin_create(originname);
1524  replorigin_session_setup(originid);
1525  replorigin_session_origin = originid;
1526  origin_startpos = replorigin_session_get_progress(false);
1528 
1529  wrconn = walrcv_connect(MySubscription->conninfo, true, myslotname,
1530  &err);
1531  if (wrconn == NULL)
1532  ereport(ERROR,
1533  (errmsg("could not connect to the publisher: %s", err)));
1534 
1535  /*
1536  * We don't really use the output identify_system for anything
1537  * but it does some initializations on the upstream so let's still
1538  * call it.
1539  */
1540  (void) walrcv_identify_system(wrconn, &startpointTLI,
1541  &server_version);
1542 
1543  }
1544 
1545  /*
1546  * Setup callback for syscache so that we know when something
1547  * changes in the subscription relation state.
1548  */
1551  (Datum) 0);
1552 
1553  /* Build logical replication streaming options. */
1554  options.logical = true;
1555  options.startpoint = origin_startpos;
1556  options.slotname = myslotname;
1557  options.proto.logical.proto_version = LOGICALREP_PROTO_VERSION_NUM;
1558  options.proto.logical.publication_names = MySubscription->publications;
1559 
1560  /* Start normal logical streaming replication. */
1561  walrcv_startstreaming(wrconn, &options);
1562 
1563  /* Run the main loop. */
1564  LogicalRepApplyLoop(origin_startpos);
1565 
1567 
1568  /* We should only get here if we received SIGTERM */
1569  proc_exit(0);
1570 }
Subscription * MySubscription
Definition: worker.c:109
#define LOGICALREP_PROTO_VERSION_NUM
Definition: logicalproto.h:28
WalReceiverConn * wrconn
Definition: worker.c:107
#define DEBUG1
Definition: elog.h:25
MemoryContext ApplyCacheContext
Definition: worker.c:105
uint32 TimeLineID
Definition: xlogdefs.h:45
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
#define DatumGetObjectId(X)
Definition: postgres.h:506
char * pstrdup(const char *in)
Definition: mcxt.c:1077
void CommitTransactionCommand(void)
Definition: xact.c:2747
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
TimestampTz last_send_time
uint16 RepOriginId
Definition: xlogdefs.h:51
#define walrcv_startstreaming(conn, options)
Definition: walreceiver.h:252
void proc_exit(int code)
Definition: ipc.c:99
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1107
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:189
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
void replorigin_session_setup(RepOriginId node)
Definition: origin.c:980
#define LOG
Definition: elog.h:26
char * LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
Definition: tablesync.c:693
#define OidIsValid(objectId)
Definition: c.h:538
RepOriginId replorigin_by_name(char *roname, bool missing_ok)
Definition: origin.c:206
#define NAMEDATALEN
Subscription * GetSubscription(Oid subid, bool missing_ok)
static void subscription_change_cb(Datum arg, int cacheid, uint32 hashvalue)
Definition: worker.c:1408
void pfree(void *pointer)
Definition: mcxt.c:950
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:62
#define ERROR
Definition: elog.h:43
Definition: guc.h:75
static bool am_tablesync_worker(void)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
#define walrcv_identify_system(conn, primary_tli, server_version)
Definition: walreceiver.h:248
void logicalrep_worker_attach(int slot)
Definition: launcher.c:445
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6651
XLogRecPtr startpoint
Definition: walreceiver.h:147
List * publications
RepOriginId replorigin_create(char *roname)
Definition: origin.c:235
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid)
Definition: postmaster.c:5475
#define ereport(elevel, rest)
Definition: elog.h:122
static char ** options
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1381
uintptr_t Datum
Definition: postgres.h:372
void logicalrep_worker_sigterm(SIGNAL_ARGS)
Definition: launcher.c:495
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
TimestampTz last_recv_time
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:675
RepOriginId replorigin_session_origin
Definition: origin.c:150
void StartTransactionCommand(void)
Definition: xact.c:2677
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:133
static int server_version
Definition: pg_dumpall.c:80
void CreateCacheMemoryContext(void)
Definition: catcache.c:525
#define walrcv_disconnect(conn)
Definition: walreceiver.h:264
bool MySubscriptionValid
Definition: worker.c:110
union WalRcvStreamOptions::@90 proto
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void LogicalRepApplyLoop(XLogRecPtr last_received)
Definition: worker.c:992
#define elog
Definition: elog.h:219
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
TimestampTz reply_time
void invalidate_syncing_table_states(Datum arg, int cacheid, uint32 hashvalue)
Definition: tablesync.c:185
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416
MemoryContext CacheMemoryContext
Definition: mcxt.c:46
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5504
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:242
static void check_relation_updatable ( LogicalRepRelMapEntry rel)
static

Definition at line 600 of file worker.c.

References ereport, errcode(), errmsg(), ERROR, GetRelationIdentityOrPK(), LogicalRepRelMapEntry::localrel, LogicalRepRelation::nspname, OidIsValid, LogicalRepRelation::relname, LogicalRepRelMapEntry::remoterel, and LogicalRepRelMapEntry::updatable.

Referenced by apply_handle_delete(), and apply_handle_update().

601 {
602  /* Updatable, no error. */
603  if (rel->updatable)
604  return;
605 
606  /*
607  * We are in error mode so it's fine this is somewhat slow.
608  * It's better to give user correct error.
609  */
611  {
612  ereport(ERROR,
613  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
614  errmsg("publisher does not send replica identity column "
615  "expected by the logical replication target relation \"%s.%s\"",
616  rel->remoterel.nspname, rel->remoterel.relname)));
617  }
618 
619  ereport(ERROR,
620  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
621  errmsg("logical replication target relation \"%s.%s\" has "
622  "neither REPLICA IDENTITY index nor PRIMARY "
623  "KEY and published relation does not have "
624  "REPLICA IDENTITY FULL",
625  rel->remoterel.nspname, rel->remoterel.relname)));
626 }
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:524
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:538
#define ERROR
Definition: elog.h:43
LogicalRepRelation remoterel
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
static EState* create_estate_for_relation ( LogicalRepRelMapEntry rel)
static

Definition at line 177 of file worker.c.

References AfterTriggerBeginQuery(), CreateExecutorState(), EState::es_num_result_relations, EState::es_range_table, EState::es_result_relation_info, EState::es_result_relations, EState::es_trig_tuple_slot, ExecInitExtraTupleSlot(), InitResultRelInfo(), list_make1, LogicalRepRelMapEntry::localrel, makeNode, NULL, RelationData::rd_rel, RelationGetRelid, RangeTblEntry::relid, RangeTblEntry::relkind, ResultRelInfo::ri_TrigDesc, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by apply_handle_delete(), apply_handle_insert(), and apply_handle_update().

178 {
179  EState *estate;
180  ResultRelInfo *resultRelInfo;
181  RangeTblEntry *rte;
182 
183  estate = CreateExecutorState();
184 
185  rte = makeNode(RangeTblEntry);
186  rte->rtekind = RTE_RELATION;
187  rte->relid = RelationGetRelid(rel->localrel);
188  rte->relkind = rel->localrel->rd_rel->relkind;
189  estate->es_range_table = list_make1(rte);
190 
191  resultRelInfo = makeNode(ResultRelInfo);
192  InitResultRelInfo(resultRelInfo, rel->localrel, 1, NULL, 0);
193 
194  estate->es_result_relations = resultRelInfo;
195  estate->es_num_result_relations = 1;
196  estate->es_result_relation_info = resultRelInfo;
197 
198  /* Triggers might need a slot */
199  if (resultRelInfo->ri_TrigDesc)
200  estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
201 
202  /* Prepare to catch AFTER triggers. */
204 
205  return estate;
206 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1255
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
List * es_range_table
Definition: execnodes.h:410
Form_pg_class rd_rel
Definition: rel.h:114
#define list_make1(x1)
Definition: pg_list.h:133
ResultRelInfo * es_result_relations
Definition: execnodes.h:420
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:426
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:377
EState * CreateExecutorState(void)
Definition: execUtils.c:77
int es_num_result_relations
Definition: execnodes.h:421
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4150
#define makeNode(_type_)
Definition: nodes.h:554
#define NULL
Definition: c.h:229
RTEKind rtekind
Definition: parsenodes.h:916
#define RelationGetRelid(relation)
Definition: rel.h:417
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:422
static bool ensure_transaction ( void  )
static

Definition at line 151 of file worker.c.

References CurrentMemoryContext, IsTransactionState(), MemoryContextSwitchTo(), MySubscriptionValid, reread_subscription(), and StartTransactionCommand().

Referenced by apply_handle_delete(), apply_handle_insert(), and apply_handle_update().

152 {
153  if (IsTransactionState())
154  {
157  return false;
158  }
159 
161 
162  if (!MySubscriptionValid)
164 
166  return true;
167 }
static void reread_subscription(void)
Definition: worker.c:1289
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static MemoryContext ApplyContext
Definition: worker.c:104
void StartTransactionCommand(void)
Definition: xact.c:2677
bool IsTransactionState(void)
Definition: xact.c:350
bool MySubscriptionValid
Definition: worker.c:110
static void get_flush_position ( XLogRecPtr write,
XLogRecPtr flush,
bool have_pending_txes 
)
static

Definition at line 913 of file worker.c.

References dlist_mutable_iter::cur, dlist_container, dlist_delete(), dlist_foreach_modify, dlist_is_empty(), dlist_tail_element, GetFlushRecPtr(), InvalidXLogRecPtr, FlushPosition::local_end, pfree(), and FlushPosition::remote_end.

Referenced by send_feedback().

915 {
916  dlist_mutable_iter iter;
917  XLogRecPtr local_flush = GetFlushRecPtr();
918 
920  *flush = InvalidXLogRecPtr;
921 
923  {
924  FlushPosition *pos =
925  dlist_container(FlushPosition, node, iter.cur);
926 
927  *write = pos->remote_end;
928 
929  if (pos->local_end <= local_flush)
930  {
931  *flush = pos->remote_end;
932  dlist_delete(iter.cur);
933  pfree(pos);
934  }
935  else
936  {
937  /*
938  * Don't want to uselessly iterate over the rest of the list which
939  * could potentially be long. Instead get the last element and
940  * grab the write position from there.
941  */
942  pos = dlist_tail_element(FlushPosition, node,
943  &lsn_mapping);
944  *write = pos->remote_end;
945  *have_pending_txes = true;
946  return;
947  }
948  }
949 
950  *have_pending_txes = !dlist_is_empty(&lsn_mapping);
951 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
static dlist_head lsn_mapping
Definition: worker.c:96
#define write(a, b, c)
Definition: win32.h:19
XLogRecPtr remote_end
Definition: worker.c:93
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8209
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
void pfree(void *pointer)
Definition: mcxt.c:950
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:496
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
XLogRecPtr local_end
Definition: worker.c:92
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
static Oid GetRelationIdentityOrPK ( Relation  rel)
static

Definition at line 524 of file worker.c.

References OidIsValid, RelationGetPrimaryKeyIndex(), and RelationGetReplicaIndex().

Referenced by apply_handle_delete(), apply_handle_update(), and check_relation_updatable().

525 {
526  Oid idxoid;
527 
528  idxoid = RelationGetReplicaIndex(rel);
529 
530  if (!OidIsValid(idxoid))
531  idxoid = RelationGetPrimaryKeyIndex(rel);
532 
533  return idxoid;
534 }
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4665
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
Oid RelationGetPrimaryKeyIndex(Relation relation)
Definition: relcache.c:4644
static void LogicalRepApplyLoop ( XLogRecPtr  last_received)
static

Definition at line 992 of file worker.c.

References AcceptInvalidationMessages(), ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE, ALLOCSET_DEFAULT_MINSIZE, AllocSetContextCreate(), apply_dispatch(), buf, CHECK_FOR_INTERRUPTS, StringInfoData::cursor, StringInfoData::data, ereport, errmsg(), ERROR, fd(), GetCurrentTimestamp(), got_SIGTERM, in_remote_transaction, StringInfoData::len, LOG, StringInfoData::maxlen, MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MyProc, MySubscriptionValid, NAPTIME_PER_CYCLE, now(), NULL, PGINVALID_SOCKET, pgstat_report_activity(), pq_getmsgbyte(), pq_getmsgint64(), proc_exit(), process_syncing_tables(), PGPROC::procLatch, reread_subscription(), ResetLatch(), send_feedback(), STATE_IDLE, TimestampTzPlusMilliseconds, TopMemoryContext, UpdateWorkerStats(), WAIT_EVENT_LOGICAL_APPLY_MAIN, WaitLatchOrSocket(), wal_receiver_timeout, walrcv_endstreaming, walrcv_receive, WL_LATCH_SET, WL_POSTMASTER_DEATH, WL_SOCKET_READABLE, and WL_TIMEOUT.

Referenced by ApplyWorkerMain().

993 {
994  /* Init the ApplyContext which we use for easier cleanup. */
996  "ApplyContext",
1000 
1001  /* mark as idle, before starting to loop */
1003 
1004  while (!got_SIGTERM)
1005  {
1007  int rc;
1008  int len;
1009  char *buf = NULL;
1010  bool endofstream = false;
1011  TimestampTz last_recv_timestamp = GetCurrentTimestamp();
1012  bool ping_sent = false;
1013 
1015 
1016  len = walrcv_receive(wrconn, &buf, &fd);
1017 
1018  if (len != 0)
1019  {
1020  /* Process the data */
1021  for (;;)
1022  {
1024 
1025  if (len == 0)
1026  {
1027  break;
1028  }
1029  else if (len < 0)
1030  {
1031  ereport(LOG,
1032  (errmsg("data stream from publisher has ended")));
1033  endofstream = true;
1034  break;
1035  }
1036  else
1037  {
1038  int c;
1039  StringInfoData s;
1040 
1041  /* Reset timeout. */
1042  last_recv_timestamp = GetCurrentTimestamp();
1043  ping_sent = false;
1044 
1045  /* Ensure we are reading the data into our memory context. */
1047 
1048  s.data = buf;
1049  s.len = len;
1050  s.cursor = 0;
1051  s.maxlen = -1;
1052 
1053  c = pq_getmsgbyte(&s);
1054 
1055  if (c == 'w')
1056  {
1057  XLogRecPtr start_lsn;
1058  XLogRecPtr end_lsn;
1059  TimestampTz send_time;
1060 
1061  start_lsn = pq_getmsgint64(&s);
1062  end_lsn = pq_getmsgint64(&s);
1063  send_time = pq_getmsgint64(&s);
1064 
1065  if (last_received < start_lsn)
1066  last_received = start_lsn;
1067 
1068  if (last_received < end_lsn)
1069  last_received = end_lsn;
1070 
1071  UpdateWorkerStats(last_received, send_time, false);
1072 
1073  apply_dispatch(&s);
1074  }
1075  else if (c == 'k')
1076  {
1077  XLogRecPtr end_lsn;
1079  bool reply_requested;
1080 
1081  end_lsn = pq_getmsgint64(&s);
1082  timestamp = pq_getmsgint64(&s);
1083  reply_requested = pq_getmsgbyte(&s);
1084 
1085  if (last_received < end_lsn)
1086  last_received = end_lsn;
1087 
1088  send_feedback(last_received, reply_requested, false);
1089  UpdateWorkerStats(last_received, timestamp, true);
1090  }
1091  /* other message types are purposefully ignored */
1092  }
1093 
1094  len = walrcv_receive(wrconn, &buf, &fd);
1095  }
1096 
1097  /* confirm all writes at once */
1098  send_feedback(last_received, false, false);
1099  }
1100 
1101  if (!in_remote_transaction)
1102  {
1103  /*
1104  * If we didn't get any transactions for a while there might be
1105  * unconsumed invalidation messages in the queue, consume them now.
1106  */
1108  if (!MySubscriptionValid)
1110 
1111  /* Process any table synchronization changes. */
1112  process_syncing_tables(last_received);
1113  }
1114 
1115  /* Cleanup the memory. */
1118 
1119  /* Check if we need to exit the streaming loop. */
1120  if (endofstream)
1121  {
1122  TimeLineID tli;
1123  walrcv_endstreaming(wrconn, &tli);
1124  break;
1125  }
1126 
1127  /*
1128  * Wait for more data or latch.
1129  */
1133  fd, NAPTIME_PER_CYCLE,
1135 
1136  /* Emergency bailout if postmaster has died */
1137  if (rc & WL_POSTMASTER_DEATH)
1138  proc_exit(1);
1139 
1140  if (rc & WL_TIMEOUT)
1141  {
1142  /*
1143  * We didn't receive anything new. If we haven't heard
1144  * anything from the server for more than
1145  * wal_receiver_timeout / 2, ping the server. Also, if
1146  * it's been longer than wal_receiver_status_interval
1147  * since the last update we sent, send a status update to
1148  * the master anyway, to report any progress in applying
1149  * WAL.
1150  */
1151  bool requestReply = false;
1152 
1153  /*
1154  * Check if time since last receive from standby has
1155  * reached the configured limit.
1156  */
1157  if (wal_receiver_timeout > 0)
1158  {
1160  TimestampTz timeout;
1161 
1162  timeout =
1163  TimestampTzPlusMilliseconds(last_recv_timestamp,
1165 
1166  if (now >= timeout)
1167  ereport(ERROR,
1168  (errmsg("terminating logical replication worker due to timeout")));
1169 
1170  /*
1171  * We didn't receive anything new, for half of
1172  * receiver replication timeout. Ping the server.
1173  */
1174  if (!ping_sent)
1175  {
1176  timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
1177  (wal_receiver_timeout / 2));
1178  if (now >= timeout)
1179  {
1180  requestReply = true;
1181  ping_sent = true;
1182  }
1183  }
1184  }
1185 
1186  send_feedback(last_received, requestReply, requestReply);
1187  }
1188 
1190  }
1191 }
static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
Definition: worker.c:1200
WalReceiverConn * wrconn
Definition: worker.c:107
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:254
uint32 TimeLineID
Definition: xlogdefs.h:45
void AcceptInvalidationMessages(void)
Definition: inval.c:672
#define WL_TIMEOUT
Definition: latch.h:127
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:412
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2957
int64 timestamp
PGPROC * MyProc
Definition: proc.c:67
int64 TimestampTz
Definition: timestamp.h:39
static void UpdateWorkerStats(XLogRecPtr last_lsn, TimestampTz send_time, bool reply)
Definition: worker.c:976
static void reread_subscription(void)
Definition: worker.c:1289
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:256
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void proc_exit(int code)
Definition: ipc.c:99
#define WL_SOCKET_READABLE
Definition: latch.h:125
void ResetLatch(volatile Latch *latch)
Definition: latch.c:461
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:162
int wal_receiver_timeout
Definition: walreceiver.c:74
Latch procLatch
Definition: proc.h:103
#define ERROR
Definition: elog.h:43
#define NAPTIME_PER_CYCLE
Definition: worker.c:87
bool in_remote_transaction
Definition: worker.c:112
static volatile sig_atomic_t got_SIGTERM
Definition: autovacuum.c:140
char * c
static char * buf
Definition: pg_test_fsync.c:65
int pgsocket
Definition: port.h:22
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
static MemoryContext ApplyContext
Definition: worker.c:104
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
#define PGINVALID_SOCKET
Definition: port.h:24
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:432
static void apply_dispatch(StringInfo s)
Definition: worker.c:854
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
int WaitLatchOrSocket(volatile Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:320
bool MySubscriptionValid
Definition: worker.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:163
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:486
#define ALLOCSET_DEFAULT_MAXSIZE
Definition: memutils.h:164
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533
static void reread_subscription ( void  )
static

Definition at line 1289 of file worker.c.

References CommitTransactionCommand(), Subscription::conninfo, Subscription::dbid, elog, Subscription::enabled, equal(), ereport, errmsg(), ERROR, FreeSubscription(), GetSubscription(), IsTransactionState(), LOG, MemoryContextSwitchTo(), MyLogicalRepWorker, MySubscriptionValid, Subscription::name, newsub(), proc_exit(), Subscription::publications, Subscription::slotname, StartTransactionCommand(), LogicalRepWorker::subid, and walrcv_disconnect.

Referenced by ensure_transaction(), and LogicalRepApplyLoop().

1290 {
1291  MemoryContext oldctx;
1293  bool started_tx = false;
1294 
1295  /* This function might be called inside or outside of transaction. */
1296  if (!IsTransactionState())
1297  {
1299  started_tx = true;
1300  }
1301 
1302  /* Ensure allocations in permanent context. */
1304 
1305  newsub = GetSubscription(MyLogicalRepWorker->subid, true);
1306 
1307  /*
1308  * Exit if the subscription was removed.
1309  * This normally should not happen as the worker gets killed
1310  * during DROP SUBSCRIPTION.
1311  */
1312  if (!newsub)
1313  {
1314  ereport(LOG,
1315  (errmsg("logical replication worker for subscription \"%s\" will "
1316  "stop because the subscription was removed",
1317  MySubscription->name)));
1318 
1320  proc_exit(0);
1321  }
1322 
1323  /*
1324  * Exit if connection string was changed. The launcher will start
1325  * new worker.
1326  */
1327  if (strcmp(newsub->conninfo, MySubscription->conninfo) != 0)
1328  {
1329  ereport(LOG,
1330  (errmsg("logical replication worker for subscription \"%s\" will "
1331  "restart because the connection information was changed",
1332  MySubscription->name)));
1333 
1335  proc_exit(0);
1336  }
1337 
1338  /*
1339  * Exit if subscription name was changed (it's used for
1340  * fallback_application_name). The launcher will start new worker.
1341  */
1342  if (strcmp(newsub->name, MySubscription->name) != 0)
1343  {
1344  ereport(LOG,
1345  (errmsg("logical replication worker for subscription \"%s\" will "
1346  "restart because subscription was renamed",
1347  MySubscription->name)));
1348 
1350  proc_exit(0);
1351  }
1352 
1353  /*
1354  * Exit if publication list was changed. The launcher will start
1355  * new worker.
1356  */
1358  {
1359  ereport(LOG,
1360  (errmsg("logical replication worker for subscription \"%s\" will "
1361  "restart because subscription's publications were changed",
1362  MySubscription->name)));
1363 
1365  proc_exit(0);
1366  }
1367 
1368  /*
1369  * Exit if the subscription was disabled.
1370  * This normally should not happen as the worker gets killed
1371  * during ALTER SUBSCRIPTION ... DISABLE.
1372  */
1373  if (!newsub->enabled)
1374  {
1375  ereport(LOG,
1376  (errmsg("logical replication worker for subscription \"%s\" will "
1377  "stop because the subscription was disabled",
1378  MySubscription->name)));
1379 
1381  proc_exit(0);
1382  }
1383 
1384  /* Check for other changes that should never happen too. */
1385  if (newsub->dbid != MySubscription->dbid ||
1386  strcmp(newsub->slotname, MySubscription->slotname) != 0)
1387  {
1388  elog(ERROR, "subscription %u changed unexpectedly",
1390  }
1391 
1392  /* Clean old subscription info and switch to new one. */
1395 
1396  MemoryContextSwitchTo(oldctx);
1397 
1398  if (started_tx)
1400 
1401  MySubscriptionValid = true;
1402 }
Subscription * MySubscription
Definition: worker.c:109
WalReceiverConn * wrconn
Definition: worker.c:107
MemoryContext ApplyCacheContext
Definition: worker.c:105
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2946
void CommitTransactionCommand(void)
Definition: xact.c:2747
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void proc_exit(int code)
Definition: ipc.c:99
#define LOG
Definition: elog.h:26
Subscription * GetSubscription(Oid subid, bool missing_ok)
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:62
#define ERROR
Definition: elog.h:43
List * publications
#define ereport(elevel, rest)
Definition: elog.h:122
void StartTransactionCommand(void)
Definition: xact.c:2677
bool IsTransactionState(void)
Definition: xact.c:350
#define walrcv_disconnect(conn)
Definition: walreceiver.h:264
bool MySubscriptionValid
Definition: worker.c:110
void FreeSubscription(Subscription *sub)
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
static color newsub(struct colormap *cm, color co)
Definition: regc_color.c:389
static void send_feedback ( XLogRecPtr  recvpos,
bool  force,
bool  requestReply 
)
static

Definition at line 1200 of file worker.c.

References StringInfoData::data, DEBUG2, elog, get_flush_position(), GetCurrentTimestamp(), InvalidXLogRecPtr, StringInfoData::len, makeStringInfo(), MemoryContextSwitchTo(), now(), NULL, pq_sendbyte(), pq_sendint64(), reply_message, resetStringInfo(), TimestampDifferenceExceeds(), wal_receiver_status_interval, and walrcv_send.

Referenced by LogicalRepApplyLoop().

1201 {
1202  static StringInfo reply_message = NULL;
1203  static TimestampTz send_time = 0;
1204 
1205  static XLogRecPtr last_recvpos = InvalidXLogRecPtr;
1206  static XLogRecPtr last_writepos = InvalidXLogRecPtr;
1207  static XLogRecPtr last_flushpos = InvalidXLogRecPtr;
1208 
1209  XLogRecPtr writepos;
1210  XLogRecPtr flushpos;
1211  TimestampTz now;
1212  bool have_pending_txes;
1213 
1214  /*
1215  * If the user doesn't want status to be reported to the publisher, be
1216  * sure to exit before doing anything at all.
1217  */
1218  if (!force && wal_receiver_status_interval <= 0)
1219  return;
1220 
1221  /* It's legal to not pass a recvpos */
1222  if (recvpos < last_recvpos)
1223  recvpos = last_recvpos;
1224 
1225  get_flush_position(&writepos, &flushpos, &have_pending_txes);
1226 
1227  /*
1228  * No outstanding transactions to flush, we can report the latest
1229  * received position. This is important for synchronous replication.
1230  */
1231  if (!have_pending_txes)
1232  flushpos = writepos = recvpos;
1233 
1234  if (writepos < last_writepos)
1235  writepos = last_writepos;
1236 
1237  if (flushpos < last_flushpos)
1238  flushpos = last_flushpos;
1239 
1240  now = GetCurrentTimestamp();
1241 
1242  /* if we've already reported everything we're good */
1243  if (!force &&
1244  writepos == last_writepos &&
1245  flushpos == last_flushpos &&
1246  !TimestampDifferenceExceeds(send_time, now,
1248  return;
1249  send_time = now;
1250 
1251  if (!reply_message)
1252  {
1254  reply_message = makeStringInfo();
1255  MemoryContextSwitchTo(oldctx);
1256  }
1257  else
1258  resetStringInfo(reply_message);
1259 
1260  pq_sendbyte(reply_message, 'r');
1261  pq_sendint64(reply_message, recvpos); /* write */
1262  pq_sendint64(reply_message, flushpos); /* flush */
1263  pq_sendint64(reply_message, writepos); /* apply */
1264  pq_sendint64(reply_message, now); /* sendTime */
1265  pq_sendbyte(reply_message, requestReply); /* replyRequested */
1266 
1267  elog(DEBUG2, "sending feedback (force %d) to recv %X/%X, write %X/%X, flush %X/%X",
1268  force,
1269  (uint32) (recvpos >> 32), (uint32) recvpos,
1270  (uint32) (writepos >> 32), (uint32) writepos,
1271  (uint32) (flushpos >> 32), (uint32) flushpos
1272  );
1273 
1274  walrcv_send(wrconn, reply_message->data, reply_message->len);
1275 
1276  if (recvpos > last_recvpos)
1277  last_recvpos = recvpos;
1278  if (writepos > last_writepos)
1279  last_writepos = writepos;
1280  if (flushpos > last_flushpos)
1281  last_flushpos = flushpos;
1282 }
WalReceiverConn * wrconn
Definition: worker.c:107
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
MemoryContext ApplyCacheContext
Definition: worker.c:105
void pq_sendbyte(StringInfo buf, int byt)
Definition: pqformat.c:105
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
int64 TimestampTz
Definition: timestamp.h:39
StringInfo makeStringInfo(void)
Definition: stringinfo.c:29
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int wal_receiver_status_interval
Definition: walreceiver.c:73
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1648
static void get_flush_position(XLogRecPtr *write, XLogRecPtr *flush, bool *have_pending_txes)
Definition: worker.c:913
static StringInfoData reply_message
Definition: walreceiver.c:110
#define DEBUG2
Definition: elog.h:24
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:94
unsigned int uint32
Definition: c.h:268
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define walrcv_send(conn, buffer, nbytes)
Definition: walreceiver.h:258
#define elog
Definition: elog.h:219
void pq_sendint64(StringInfo buf, int64 i)
Definition: pqformat.c:271
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533
static bool should_apply_changes_for_rel ( LogicalRepRelMapEntry rel)
static

Definition at line 135 of file worker.c.

References am_tablesync_worker(), LogicalRepRelMapEntry::localreloid, MyLogicalRepWorker, LogicalRepWorker::relid, remote_final_lsn, LogicalRepRelMapEntry::state, LogicalRepRelMapEntry::statelsn, SUBREL_STATE_READY, and SUBREL_STATE_SYNCDONE.

Referenced by apply_handle_delete(), apply_handle_insert(), and apply_handle_update().

136 {
137  if (am_tablesync_worker())
138  return MyLogicalRepWorker->relid == rel->localreloid;
139  else
140  return (rel->state == SUBREL_STATE_READY ||
141  (rel->state == SUBREL_STATE_SYNCDONE &&
142  rel->statelsn <= remote_final_lsn));
143 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:113
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:62
static bool am_tablesync_worker(void)
#define SUBREL_STATE_SYNCDONE
#define SUBREL_STATE_READY
static void slot_fill_defaults ( LogicalRepRelMapEntry rel,
EState estate,
TupleTableSlot slot 
)
static

Definition at line 216 of file worker.c.

References LogicalRepRelMapEntry::attrmap, tupleDesc::attrs, build_column_default(), ExecEvalExpr(), ExecInitExpr(), expression_planner(), GetPerTupleExprContext, i, LogicalRepRelMapEntry::localrel, LogicalRepRelation::natts, tupleDesc::natts, NULL, palloc(), RelationGetDescr, LogicalRepRelMapEntry::remoterel, TupleTableSlot::tts_isnull, and TupleTableSlot::tts_values.

Referenced by apply_handle_insert().

218 {
219  TupleDesc desc = RelationGetDescr(rel->localrel);
220  int num_phys_attrs = desc->natts;
221  int i;
222  int attnum,
223  num_defaults = 0;
224  int *defmap;
225  ExprState **defexprs;
226  ExprContext *econtext;
227 
228  econtext = GetPerTupleExprContext(estate);
229 
230  /* We got all the data via replication, no need to evaluate anything. */
231  if (num_phys_attrs == rel->remoterel.natts)
232  return;
233 
234  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
235  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
236 
237  for (attnum = 0; attnum < num_phys_attrs; attnum++)
238  {
239  Expr *defexpr;
240 
241  if (desc->attrs[attnum]->attisdropped)
242  continue;
243 
244  if (rel->attrmap[attnum] >= 0)
245  continue;
246 
247  defexpr = (Expr *) build_column_default(rel->localrel, attnum + 1);
248 
249  if (defexpr != NULL)
250  {
251  /* Run the expression through planner */
252  defexpr = expression_planner(defexpr);
253 
254  /* Initialize executable expression in copycontext */
255  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
256  defmap[num_defaults] = attnum;
257  num_defaults++;
258  }
259 
260  }
261 
262  for (i = 0; i < num_defaults; i++)
263  slot->tts_values[defmap[i]] =
264  ExecEvalExpr(defexprs[i], econtext, &slot->tts_isnull[defmap[i]]);
265 }
#define RelationGetDescr(relation)
Definition: rel.h:429
Expr * expression_planner(Expr *expr)
Definition: planner.c:5927
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Datum * tts_values
Definition: tuptable.h:125
int natts
Definition: tupdesc.h:73
#define GetPerTupleExprContext(estate)
Definition: executor.h:456
LogicalRepRelation remoterel
bool * tts_isnull
Definition: tuptable.h:126
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:266
Node * build_column_default(Relation rel, int attrno)
#define NULL
Definition: c.h:229
void * palloc(Size size)
Definition: mcxt.c:849
int i
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:113
static void slot_modify_cstrings ( TupleTableSlot slot,
LogicalRepRelMapEntry rel,
char **  values,
bool replaces 
)
static

Definition at line 360 of file worker.c.

References ErrorContextCallback::arg, SlotErrCallbackArg::attnum, LogicalRepRelMapEntry::attrmap, tupleDesc::attrs, ErrorContextCallback::callback, error_context_stack, ExecClearTuple(), ExecStoreVirtualTuple(), getTypeInputInfo(), i, tupleDesc::natts, NULL, OidInputFunctionCall(), ErrorContextCallback::previous, SlotErrCallbackArg::rel, LogicalRepRelMapEntry::remoterel, slot_getallattrs(), slot_store_error_callback(), TupleTableSlot::tts_isnull, TupleTableSlot::tts_tupleDescriptor, and TupleTableSlot::tts_values.

Referenced by apply_handle_update().

362 {
363  int natts = slot->tts_tupleDescriptor->natts;
364  int i;
365  SlotErrCallbackArg errarg;
366  ErrorContextCallback errcallback;
367 
368  slot_getallattrs(slot);
369  ExecClearTuple(slot);
370 
371  /* Push callback + info on the error context stack */
372  errarg.rel = &rel->remoterel;
373  errarg.attnum = -1;
374  errcallback.callback = slot_store_error_callback;
375  errcallback.arg = (void *) &errarg;
376  errcallback.previous = error_context_stack;
377  error_context_stack = &errcallback;
378 
379  /* Call the "in" function for each replaced attribute */
380  for (i = 0; i < natts; i++)
381  {
383  int remoteattnum = rel->attrmap[i];
384 
385  if (remoteattnum >= 0 && !replaces[remoteattnum])
386  continue;
387 
388  if (remoteattnum >= 0 && values[remoteattnum] != NULL)
389  {
390  Oid typinput;
391  Oid typioparam;
392 
393  errarg.attnum = remoteattnum;
394 
395  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
396  slot->tts_values[i] = OidInputFunctionCall(typinput, values[i],
397  typioparam,
398  att->atttypmod);
399  slot->tts_isnull[i] = false;
400  }
401  else
402  {
403  slot->tts_values[i] = (Datum) 0;
404  slot->tts_isnull[i] = true;
405  }
406  }
407 
408  /* Pop the error context stack */
409  error_context_stack = errcallback.previous;
410 
411  ExecStoreVirtualTuple(slot);
412 }
LogicalRepRelation * rel
Definition: worker.c:100
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Datum * tts_values
Definition: tuptable.h:125
unsigned int Oid
Definition: postgres_ext.h:31
struct ErrorContextCallback * previous
Definition: elog.h:238
int natts
Definition: tupdesc.h:73
ErrorContextCallback * error_context_stack
Definition: elog.c:88
LogicalRepRelation remoterel
bool * tts_isnull
Definition: tuptable.h:126
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2567
void slot_getallattrs(TupleTableSlot *slot)
Definition: heaptuple.c:1239
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
uintptr_t Datum
Definition: postgres.h:372
#define NULL
Definition: c.h:229
static void slot_store_error_callback(void *arg)
Definition: worker.c:271
static Datum values[MAXATTR]
Definition: bootstrap.c:162
void(* callback)(void *arg)
Definition: elog.h:239
int i
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:2047
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:488
static void slot_store_cstrings ( TupleTableSlot slot,
LogicalRepRelMapEntry rel,
char **  values 
)
static

Definition at line 296 of file worker.c.

References ErrorContextCallback::arg, SlotErrCallbackArg::attnum, LogicalRepRelMapEntry::attrmap, tupleDesc::attrs, ErrorContextCallback::callback, error_context_stack, ExecClearTuple(), ExecStoreVirtualTuple(), getTypeInputInfo(), i, tupleDesc::natts, NULL, OidInputFunctionCall(), ErrorContextCallback::previous, SlotErrCallbackArg::rel, LogicalRepRelMapEntry::remoterel, slot_store_error_callback(), TupleTableSlot::tts_isnull, TupleTableSlot::tts_tupleDescriptor, and TupleTableSlot::tts_values.

Referenced by apply_handle_delete(), apply_handle_insert(), and apply_handle_update().

298 {
299  int natts = slot->tts_tupleDescriptor->natts;
300  int i;
301  SlotErrCallbackArg errarg;
302  ErrorContextCallback errcallback;
303 
304  ExecClearTuple(slot);
305 
306  /* Push callback + info on the error context stack */
307  errarg.rel = &rel->remoterel;
308  errarg.attnum = -1;
309  errcallback.callback = slot_store_error_callback;
310  errcallback.arg = (void *) &errarg;
311  errcallback.previous = error_context_stack;
312  error_context_stack = &errcallback;
313 
314  /* Call the "in" function for each non-dropped attribute */
315  for (i = 0; i < natts; i++)
316  {
318  int remoteattnum = rel->attrmap[i];
319 
320  if (!att->attisdropped && remoteattnum >= 0 &&
321  values[remoteattnum] != NULL)
322  {
323  Oid typinput;
324  Oid typioparam;
325 
326  errarg.attnum = remoteattnum;
327 
328  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
329  slot->tts_values[i] = OidInputFunctionCall(typinput,
330  values[remoteattnum],
331  typioparam,
332  att->atttypmod);
333  slot->tts_isnull[i] = false;
334  }
335  else
336  {
337  /*
338  * We assign NULL to dropped attributes, NULL values, and missing
339  * values (missing values should be later filled using
340  * slot_fill_defaults).
341  */
342  slot->tts_values[i] = (Datum) 0;
343  slot->tts_isnull[i] = true;
344  }
345  }
346 
347  /* Pop the error context stack */
348  error_context_stack = errcallback.previous;
349 
350  ExecStoreVirtualTuple(slot);
351 }
LogicalRepRelation * rel
Definition: worker.c:100
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Datum * tts_values
Definition: tuptable.h:125
unsigned int Oid
Definition: postgres_ext.h:31
struct ErrorContextCallback * previous
Definition: elog.h:238
int natts
Definition: tupdesc.h:73
ErrorContextCallback * error_context_stack
Definition: elog.c:88
LogicalRepRelation remoterel
bool * tts_isnull
Definition: tuptable.h:126
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2567
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
uintptr_t Datum
Definition: postgres.h:372
#define NULL
Definition: c.h:229
static void slot_store_error_callback(void *arg)
Definition: worker.c:271
static Datum values[MAXATTR]
Definition: bootstrap.c:162
void(* callback)(void *arg)
Definition: elog.h:239
int i
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:2047
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:488
static void slot_store_error_callback ( void *  arg)
static

Definition at line 271 of file worker.c.

References LogicalRepRelation::attnames, SlotErrCallbackArg::attnum, LogicalRepRelation::atttyps, errcontext, format_type_be(), logicalrep_typmap_getid(), LogicalRepRelation::nspname, SlotErrCallbackArg::rel, and LogicalRepRelation::relname.

Referenced by slot_modify_cstrings(), and slot_store_cstrings().

272 {
274  Oid remotetypoid,
275  localtypoid;
276 
277  if (errarg->attnum < 0)
278  return;
279 
280  remotetypoid = errarg->rel->atttyps[errarg->attnum];
281  localtypoid = logicalrep_typmap_getid(remotetypoid);
282  errcontext("processing remote data for replication target relation \"%s.%s\" column \"%s\", "
283  "remote type %s, local type %s",
284  errarg->rel->nspname, errarg->rel->relname,
285  errarg->rel->attnames[errarg->attnum],
286  format_type_be(remotetypoid),
287  format_type_be(localtypoid));
288 }
LogicalRepRelation * rel
Definition: worker.c:100
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
Oid logicalrep_typmap_getid(Oid remoteid)
Definition: relation.c:448
unsigned int Oid
Definition: postgres_ext.h:31
#define errcontext
Definition: elog.h:164
void * arg
static void store_flush_position ( XLogRecPtr  remote_lsn)
static

Definition at line 957 of file worker.c.

References dlist_push_tail(), FlushPosition::local_end, MemoryContextSwitchTo(), FlushPosition::node, palloc(), FlushPosition::remote_end, and XactLastCommitEnd.

Referenced by apply_handle_commit().

958 {
959  FlushPosition *flushpos;
960 
961  /* Need to do this in permanent context */
963 
964  /* Track commit lsn */
965  flushpos = (FlushPosition *) palloc(sizeof(FlushPosition));
966  flushpos->local_end = XactLastCommitEnd;
967  flushpos->remote_end = remote_lsn;
968 
969  dlist_push_tail(&lsn_mapping, &flushpos->node);
971 }
MemoryContext ApplyCacheContext
Definition: worker.c:105
static dlist_head lsn_mapping
Definition: worker.c:96
dlist_node node
Definition: worker.c:91
XLogRecPtr XactLastCommitEnd
Definition: xlog.c:338
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:317
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
XLogRecPtr remote_end
Definition: worker.c:93
static MemoryContext ApplyContext
Definition: worker.c:104
XLogRecPtr local_end
Definition: worker.c:92
void * palloc(Size size)
Definition: mcxt.c:849
static void subscription_change_cb ( Datum  arg,
int  cacheid,
uint32  hashvalue 
)
static

Definition at line 1408 of file worker.c.

References MySubscriptionValid.

Referenced by ApplyWorkerMain().

1409 {
1410  MySubscriptionValid = false;
1411 }
bool MySubscriptionValid
Definition: worker.c:110
static void UpdateWorkerStats ( XLogRecPtr  last_lsn,
TimestampTz  send_time,
bool  reply 
)
static

Definition at line 976 of file worker.c.

References GetCurrentTimestamp(), LogicalRepWorker::last_lsn, last_lsn, LogicalRepWorker::last_recv_time, LogicalRepWorker::last_send_time, MyLogicalRepWorker, LogicalRepWorker::reply_lsn, and LogicalRepWorker::reply_time.

Referenced by LogicalRepApplyLoop().

977 {
979  MyLogicalRepWorker->last_send_time = send_time;
981  if (reply)
982  {
984  MyLogicalRepWorker->reply_time = send_time;
985  }
986 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
TimestampTz last_send_time
XLogRecPtr last_lsn
XLogRecPtr last_lsn
Definition: walsender.c:206
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:62
XLogRecPtr reply_lsn
TimestampTz last_recv_time
TimestampTz reply_time

Variable Documentation

MemoryContext ApplyCacheContext = NULL

Definition at line 105 of file worker.c.

MemoryContext ApplyContext = NULL
static

Definition at line 104 of file worker.c.

bool in_remote_transaction = false
dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping)
static

Definition at line 96 of file worker.c.

Subscription* MySubscription = NULL
bool MySubscriptionValid = false
XLogRecPtr remote_final_lsn = InvalidXLogRecPtr
static

Definition at line 113 of file worker.c.

Referenced by apply_handle_begin(), apply_handle_commit(), and should_apply_changes_for_rel().