PostgreSQL Source Code  git master
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 "postmaster/walwriter.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 "tcop/tcopprot.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 maybe_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)
 
static void logicalrep_worker_sighup (SIGNAL_ARGS)
 
void ApplyWorkerMain (Datum main_arg)
 
bool IsLogicalWorker (void)
 

Variables

static dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping)
 
static MemoryContext ApplyMessageContext = NULL
 
MemoryContext ApplyContext = NULL
 
WalReceiverConnwrconn = NULL
 
SubscriptionMySubscription = NULL
 
bool MySubscriptionValid = false
 
bool in_remote_transaction = false
 
static XLogRecPtr remote_final_lsn = InvalidXLogRecPtr
 
static volatile sig_atomic_t got_SIGHUP = false
 

Macro Definition Documentation

◆ NAPTIME_PER_CYCLE

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

Definition at line 90 of file worker.c.

Referenced by LogicalRepApplyLoop().

Typedef Documentation

◆ FlushPosition

◆ SlotErrCallbackArg

Function Documentation

◆ apply_dispatch()

static void apply_dispatch ( StringInfo  s)
static

Definition at line 877 of file worker.c.

References generate_unaccent_rules::action, 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().

878 {
879  char action = pq_getmsgbyte(s);
880 
881  switch (action)
882  {
883  /* BEGIN */
884  case 'B':
886  break;
887  /* COMMIT */
888  case 'C':
890  break;
891  /* INSERT */
892  case 'I':
894  break;
895  /* UPDATE */
896  case 'U':
898  break;
899  /* DELETE */
900  case 'D':
902  break;
903  /* RELATION */
904  case 'R':
906  break;
907  /* TYPE */
908  case 'Y':
910  break;
911  /* ORIGIN */
912  case 'O':
914  break;
915  default:
916  ereport(ERROR,
917  (errcode(ERRCODE_PROTOCOL_VIOLATION),
918  errmsg("invalid logical replication message type \"%c\"", action)));
919  }
920 }
static void apply_handle_type(StringInfo s)
Definition: worker.c:533
static void apply_handle_insert(StringInfo s)
Definition: worker.c:563
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static void apply_handle_delete(StringInfo s)
Definition: worker.c:778
static void apply_handle_begin(StringInfo s)
Definition: worker.c:433
#define ereport(elevel, rest)
Definition: elog.h:122
static void apply_handle_commit(StringInfo s)
Definition: worker.c:452
static void apply_handle_update(StringInfo s)
Definition: worker.c:657
static void apply_handle_relation(StringInfo s)
Definition: worker.c:518
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
static void apply_handle_origin(StringInfo s)
Definition: worker.c:496
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ apply_handle_begin()

static void apply_handle_begin ( StringInfo  s)
static

Definition at line 433 of file worker.c.

References LogicalRepBeginData::final_lsn, in_remote_transaction, logicalrep_read_begin(), pgstat_report_activity(), remote_final_lsn, and STATE_RUNNING.

Referenced by apply_dispatch().

434 {
435  LogicalRepBeginData begin_data;
436 
437  logicalrep_read_begin(s, &begin_data);
438 
439  remote_final_lsn = begin_data.final_lsn;
440 
441  in_remote_transaction = true;
442 
444 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:116
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
void logicalrep_read_begin(StringInfo in, LogicalRepBeginData *begin_data)
Definition: proto.c:57
bool in_remote_transaction
Definition: worker.c:115
XLogRecPtr final_lsn
Definition: logicalproto.h:67

◆ apply_handle_commit()

static void apply_handle_commit ( StringInfo  s)
static

Definition at line 452 of file worker.c.

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

Referenced by apply_dispatch().

453 {
454  LogicalRepCommitData commit_data;
455 
456  logicalrep_read_commit(s, &commit_data);
457 
458  Assert(commit_data.commit_lsn == remote_final_lsn);
459 
460  /* The synchronization worker runs in single transaction. */
462  {
463  /*
464  * Update origin state so we can restart streaming from correct
465  * position in case of crash.
466  */
469 
471  pgstat_report_stat(false);
472 
473  store_flush_position(commit_data.end_lsn);
474  }
475  else
476  {
477  /* Process any invalidation messages that might have accumulated. */
480  }
481 
482  in_remote_transaction = false;
483 
484  /* Process any tables that are being synchronized in parallel. */
485  process_syncing_tables(commit_data.end_lsn);
486 
488 }
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:980
void AcceptInvalidationMessages(void)
Definition: inval.c:679
static XLogRecPtr remote_final_lsn
Definition: worker.c:116
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:544
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
void CommitTransactionCommand(void)
Definition: xact.c:2744
bool in_remote_transaction
Definition: worker.c:115
static bool am_tablesync_worker(void)
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:156
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:157
static void maybe_reread_subscription(void)
Definition: worker.c:1337
#define Assert(condition)
Definition: c.h:670
bool IsTransactionState(void)
Definition: xact.c:351
void logicalrep_read_commit(StringInfo in, LogicalRepCommitData *commit_data)
Definition: proto.c:92
XLogRecPtr commit_lsn
Definition: logicalproto.h:74
TimestampTz committime
Definition: logicalproto.h:76
void pgstat_report_stat(bool force)
Definition: pgstat.c:812

◆ apply_handle_delete()

static void apply_handle_delete ( StringInfo  s)
static

Definition at line 778 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, 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().

779 {
781  LogicalRepTupleData oldtup;
782  LogicalRepRelId relid;
783  Oid idxoid;
784  EState *estate;
785  EPQState epqstate;
786  TupleTableSlot *remoteslot;
787  TupleTableSlot *localslot;
788  bool found;
789  MemoryContext oldctx;
790 
792 
793  relid = logicalrep_read_delete(s, &oldtup);
796  {
797  /*
798  * The relation can't become interesting in the middle of the
799  * transaction so it's safe to unlock it.
800  */
802  return;
803  }
804 
805  /* Check if we can do the delete. */
807 
808  /* Initialize the executor state. */
809  estate = create_estate_for_relation(rel);
810  remoteslot = ExecInitExtraTupleSlot(estate);
812  localslot = ExecInitExtraTupleSlot(estate);
814  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
815 
818 
819  /* Find the tuple using the replica identity index. */
821  slot_store_cstrings(remoteslot, rel, oldtup.values);
822  MemoryContextSwitchTo(oldctx);
823 
824  /*
825  * Try to find tuple using either replica identity index, primary key or
826  * if needed, sequential scan.
827  */
828  idxoid = GetRelationIdentityOrPK(rel->localrel);
829  Assert(OidIsValid(idxoid) ||
831 
832  if (OidIsValid(idxoid))
833  found = RelationFindReplTupleByIndex(rel->localrel, idxoid,
835  remoteslot, localslot);
836  else
838  remoteslot, localslot);
839  /* If found delete it. */
840  if (found)
841  {
842  EvalPlanQualSetSlot(&epqstate, localslot);
843 
844  /* Do the actual delete. */
845  ExecSimpleRelationDelete(estate, &epqstate, localslot);
846  }
847  else
848  {
849  /* The tuple to be deleted could not be found. */
850  ereport(DEBUG1,
851  (errmsg("logical replication could not find row for delete "
852  "in replication target relation \"%s\"",
854  }
855 
856  /* Cleanup. */
859 
860  /* Handle queued AFTER triggers. */
861  AfterTriggerEndQuery(estate);
862 
863  EvalPlanQualEnd(&epqstate);
864  ExecResetTupleTable(estate->es_tupleTable, false);
865  FreeExecutorState(estate);
866 
868 
870 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:141
#define NIL
Definition: pg_list.h:69
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:186
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:547
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:437
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:372
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define OidIsValid(objectId)
Definition: c.h:576
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:3208
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define REPLICA_IDENTITY_FULL
Definition: pg_class.h:179
static bool ensure_transaction(void)
Definition: worker.c:157
LogicalRepRelation remoterel
static void slot_store_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values)
Definition: worker.c:307
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
void ExecSimpleRelationDelete(EState *estate, EPQState *epqstate, TupleTableSlot *searchslot)
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:445
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:223
#define ereport(elevel, rest)
Definition: elog.h:122
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:623
List * es_tupleTable
Definition: execnodes.h:474
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
void CommandCounterIncrement(void)
Definition: xact.c:915
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:2794
#define Assert(condition)
Definition: c.h:670
char * values[MaxTupleAttributeNumber]
Definition: logicalproto.h:34
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:472
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4546
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:39
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:212
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:444

◆ apply_handle_insert()

static void apply_handle_insert ( StringInfo  s)
static

Definition at line 563 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().

564 {
566  LogicalRepTupleData newtup;
567  LogicalRepRelId relid;
568  EState *estate;
569  TupleTableSlot *remoteslot;
570  MemoryContext oldctx;
571 
573 
574  relid = logicalrep_read_insert(s, &newtup);
577  {
578  /*
579  * The relation can't become interesting in the middle of the
580  * transaction so it's safe to unlock it.
581  */
583  return;
584  }
585 
586  /* Initialize the executor state. */
587  estate = create_estate_for_relation(rel);
588  remoteslot = ExecInitExtraTupleSlot(estate);
590 
591  /* Process and store remote tuple in the slot */
593  slot_store_cstrings(remoteslot, rel, newtup.values);
594  slot_fill_defaults(rel, estate, remoteslot);
595  MemoryContextSwitchTo(oldctx);
596 
599 
600  /* Do the insert. */
601  ExecSimpleRelationInsert(estate, remoteslot);
602 
603  /* Cleanup. */
606 
607  /* Handle queued AFTER triggers. */
608  AfterTriggerEndQuery(estate);
609 
610  ExecResetTupleTable(estate->es_tupleTable, false);
611  FreeExecutorState(estate);
612 
614 
616 }
void ExecSimpleRelationInsert(EState *estate, TupleTableSlot *slot)
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:141
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:186
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
#define RelationGetDescr(relation)
Definition: rel.h:437
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:372
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
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:227
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
static bool ensure_transaction(void)
Definition: worker.c:157
static void slot_store_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values)
Definition: worker.c:307
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
#define RowExclusiveLock
Definition: lockdefs.h:38
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:223
List * es_tupleTable
Definition: execnodes.h:474
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
void CommandCounterIncrement(void)
Definition: xact.c:915
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
char * values[MaxTupleAttributeNumber]
Definition: logicalproto.h:34
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:472
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4546
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
uint32 LogicalRepRelId
Definition: logicalproto.h:39
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:444

◆ apply_handle_origin()

static void apply_handle_origin ( StringInfo  s)
static

Definition at line 496 of file worker.c.

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

Referenced by apply_dispatch().

497 {
498  /*
499  * ORIGIN message can only come inside remote transaction and before any
500  * actual writes.
501  */
502  if (!in_remote_transaction ||
504  ereport(ERROR,
505  (errcode(ERRCODE_PROTOCOL_VIOLATION),
506  errmsg("ORIGIN message sent out of order")));
507 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
bool in_remote_transaction
Definition: worker.c:115
static bool am_tablesync_worker(void)
#define ereport(elevel, rest)
Definition: elog.h:122
bool IsTransactionState(void)
Definition: xact.c:351
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ apply_handle_relation()

static void apply_handle_relation ( StringInfo  s)
static

Definition at line 518 of file worker.c.

References logicalrep_read_rel(), and logicalrep_relmap_update().

Referenced by apply_dispatch().

519 {
520  LogicalRepRelation *rel;
521 
522  rel = logicalrep_read_rel(s);
524 }
LogicalRepRelation * logicalrep_read_rel(StringInfo in)
Definition: proto.c:324
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:158

◆ apply_handle_type()

static void apply_handle_type ( StringInfo  s)
static

Definition at line 533 of file worker.c.

References logicalrep_read_typ(), and logicalrep_typmap_update().

Referenced by apply_dispatch().

534 {
535  LogicalRepTyp typ;
536 
537  logicalrep_read_typ(s, &typ);
539 }
void logicalrep_read_typ(StringInfo in, LogicalRepTyp *ltyp)
Definition: proto.c:376
void logicalrep_typmap_update(LogicalRepTyp *remotetyp)
Definition: relation.c:415

◆ apply_handle_update()

static void apply_handle_update ( StringInfo  s)
static

Definition at line 657 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, 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().

658 {
660  LogicalRepRelId relid;
661  Oid idxoid;
662  EState *estate;
663  EPQState epqstate;
664  LogicalRepTupleData oldtup;
665  LogicalRepTupleData newtup;
666  bool has_oldtup;
667  TupleTableSlot *localslot;
668  TupleTableSlot *remoteslot;
669  bool found;
670  MemoryContext oldctx;
671 
673 
674  relid = logicalrep_read_update(s, &has_oldtup, &oldtup,
675  &newtup);
678  {
679  /*
680  * The relation can't become interesting in the middle of the
681  * transaction so it's safe to unlock it.
682  */
684  return;
685  }
686 
687  /* Check if we can do the update. */
689 
690  /* Initialize the executor state. */
691  estate = create_estate_for_relation(rel);
692  remoteslot = ExecInitExtraTupleSlot(estate);
694  localslot = ExecInitExtraTupleSlot(estate);
696  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
697 
700 
701  /* Build the search tuple. */
703  slot_store_cstrings(remoteslot, rel,
704  has_oldtup ? oldtup.values : newtup.values);
705  MemoryContextSwitchTo(oldctx);
706 
707  /*
708  * Try to find tuple using either replica identity index, primary key or
709  * if needed, sequential scan.
710  */
711  idxoid = GetRelationIdentityOrPK(rel->localrel);
712  Assert(OidIsValid(idxoid) ||
713  (rel->remoterel.replident == REPLICA_IDENTITY_FULL && has_oldtup));
714 
715  if (OidIsValid(idxoid))
716  found = RelationFindReplTupleByIndex(rel->localrel, idxoid,
718  remoteslot, localslot);
719  else
721  remoteslot, localslot);
722 
723  ExecClearTuple(remoteslot);
724 
725  /*
726  * Tuple found.
727  *
728  * Note this will fail if there are other conflicting unique indexes.
729  */
730  if (found)
731  {
732  /* Process and store remote tuple in the slot */
734  ExecStoreTuple(localslot->tts_tuple, remoteslot, InvalidBuffer, false);
735  slot_modify_cstrings(remoteslot, rel, newtup.values, newtup.changed);
736  MemoryContextSwitchTo(oldctx);
737 
738  EvalPlanQualSetSlot(&epqstate, remoteslot);
739 
740  /* Do the actual update. */
741  ExecSimpleRelationUpdate(estate, &epqstate, localslot, remoteslot);
742  }
743  else
744  {
745  /*
746  * The tuple to be updated could not be found.
747  *
748  * TODO what to do here, change the log level to LOG perhaps?
749  */
750  elog(DEBUG1,
751  "logical replication did not find row for update "
752  "in replication target relation \"%s\"",
754  }
755 
756  /* Cleanup. */
759 
760  /* Handle queued AFTER triggers. */
761  AfterTriggerEndQuery(estate);
762 
763  EvalPlanQualEnd(&epqstate);
764  ExecResetTupleTable(estate->es_tupleTable, false);
765  FreeExecutorState(estate);
766 
768 
770 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:141
#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:186
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:547
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
#define DEBUG1
Definition: elog.h:25
#define RelationGetDescr(relation)
Definition: rel.h:437
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:372
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define OidIsValid(objectId)
Definition: c.h:576
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:3208
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define REPLICA_IDENTITY_FULL
Definition: pg_class.h:179
static bool ensure_transaction(void)
Definition: worker.c:157
LogicalRepRelation remoterel
static void slot_store_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values)
Definition: worker.c:307
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
bool changed[MaxTupleAttributeNumber]
Definition: logicalproto.h:36
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:445
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:223
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:623
List * es_tupleTable
Definition: execnodes.h:474
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
void CommandCounterIncrement(void)
Definition: xact.c:915
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:2794
#define Assert(condition)
Definition: c.h:670
LogicalRepRelId logicalrep_read_update(StringInfo in, bool *has_oldtuple, LogicalRepTupleData *oldtup, LogicalRepTupleData *newtup)
Definition: proto.c:211
char * values[MaxTupleAttributeNumber]
Definition: logicalproto.h:34
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:472
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4546
static void slot_modify_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values, bool *replaces)
Definition: worker.c:371
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:39
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:212
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:444

◆ ApplyWorkerMain()

void ApplyWorkerMain ( Datum  main_arg)

Definition at line 1494 of file worker.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), am_tablesync_worker(), Assert, BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), CacheRegisterSyscacheCallback(), CommitTransactionCommand(), Subscription::conninfo, CurrentResourceOwner, DatumGetInt32, LogicalRepWorker::dbid, DEBUG1, die(), 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_sighup(), LogicalRepApplyLoop(), LogicalRepSyncTableStart(), MemoryContextSwitchTo(), MyLogicalRepWorker, MySubscriptionValid, Subscription::name, NAMEDATALEN, Subscription::oid, OidIsValid, options, pfree(), PGC_BACKEND, PGC_S_OVERRIDE, PGC_SUSET, 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(), SIGHUP, Subscription::slotname, WalRcvStreamOptions::slotname, snprintf(), WalRcvStreamOptions::startpoint, StartTransactionCommand(), LogicalRepWorker::subid, subscription_change_cb(), SUBSCRIPTIONOID, SUBSCRIPTIONRELMAP, Subscription::synccommit, TopMemoryContext, LogicalRepWorker::userid, walrcv_connect, walrcv_identify_system, and walrcv_startstreaming.

1495 {
1496  int worker_slot = DatumGetInt32(main_arg);
1497  MemoryContext oldctx;
1498  char originname[NAMEDATALEN];
1499  XLogRecPtr origin_startpos;
1500  char *myslotname;
1502 
1503  /* Attach to slot */
1504  logicalrep_worker_attach(worker_slot);
1505 
1506  /* Setup signal handling */
1508  pqsignal(SIGTERM, die);
1510 
1511  /* Initialise stats to a sanish value */
1514 
1515  /* Load the libpq-specific functions */
1516  load_file("libpqwalreceiver", false);
1517 
1518  Assert(CurrentResourceOwner == NULL);
1520  "logical replication apply");
1521 
1522  /* Run as replica session replication role. */
1523  SetConfigOption("session_replication_role", "replica",
1525 
1526  /* Connect to our database. */
1529 
1530  /* Load the subscription into persistent memory context. */
1532  "ApplyContext",
1537  MySubscriptionValid = true;
1538  MemoryContextSwitchTo(oldctx);
1539 
1540  /* Setup synchronous commit according to the user's wishes */
1541  SetConfigOption("synchronous_commit", MySubscription->synccommit,
1543 
1544  if (!MySubscription->enabled)
1545  {
1546  ereport(LOG,
1547  (errmsg("logical replication apply worker for subscription \"%s\" will not "
1548  "start because the subscription was disabled during startup",
1549  MySubscription->name)));
1550 
1551  proc_exit(0);
1552  }
1553 
1554  /* Keep us informed about subscription changes. */
1557  (Datum) 0);
1558 
1559  if (am_tablesync_worker())
1560  ereport(LOG,
1561  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has started",
1563  else
1564  ereport(LOG,
1565  (errmsg("logical replication apply worker for subscription \"%s\" has started",
1566  MySubscription->name)));
1567 
1569 
1570  /* Connect to the origin and start the replication. */
1571  elog(DEBUG1, "connecting to publisher using connection string \"%s\"",
1573 
1574  if (am_tablesync_worker())
1575  {
1576  char *syncslotname;
1577 
1578  /* This is table synchroniation worker, call initial sync. */
1579  syncslotname = LogicalRepSyncTableStart(&origin_startpos);
1580 
1581  /* The slot name needs to be allocated in permanent memory context. */
1583  myslotname = pstrdup(syncslotname);
1584  MemoryContextSwitchTo(oldctx);
1585 
1586  pfree(syncslotname);
1587  }
1588  else
1589  {
1590  /* This is main apply worker */
1591  RepOriginId originid;
1592  TimeLineID startpointTLI;
1593  char *err;
1594  int server_version;
1595 
1596  myslotname = MySubscription->slotname;
1597 
1598  /*
1599  * This shouldn't happen if the subscription is enabled, but guard
1600  * against DDL bugs or manual catalog changes. (libpqwalreceiver will
1601  * crash if slot is NULL.)
1602  */
1603  if (!myslotname)
1604  ereport(ERROR,
1605  (errmsg("subscription has no replication slot set")));
1606 
1607  /* Setup replication origin tracking. */
1609  snprintf(originname, sizeof(originname), "pg_%u", MySubscription->oid);
1610  originid = replorigin_by_name(originname, true);
1611  if (!OidIsValid(originid))
1612  originid = replorigin_create(originname);
1613  replorigin_session_setup(originid);
1614  replorigin_session_origin = originid;
1615  origin_startpos = replorigin_session_get_progress(false);
1617 
1619  &err);
1620  if (wrconn == NULL)
1621  ereport(ERROR,
1622  (errmsg("could not connect to the publisher: %s", err)));
1623 
1624  /*
1625  * We don't really use the output identify_system for anything but it
1626  * does some initializations on the upstream so let's still call it.
1627  */
1628  (void) walrcv_identify_system(wrconn, &startpointTLI,
1629  &server_version);
1630 
1631  }
1632 
1633  /*
1634  * Setup callback for syscache so that we know when something changes in
1635  * the subscription relation state.
1636  */
1639  (Datum) 0);
1640 
1641  /* Build logical replication streaming options. */
1642  options.logical = true;
1643  options.startpoint = origin_startpos;
1644  options.slotname = myslotname;
1645  options.proto.logical.proto_version = LOGICALREP_PROTO_VERSION_NUM;
1646  options.proto.logical.publication_names = MySubscription->publications;
1647 
1648  /* Start normal logical streaming replication. */
1649  walrcv_startstreaming(wrconn, &options);
1650 
1651  /* Run the main loop. */
1652  LogicalRepApplyLoop(origin_startpos);
1653 
1654  proc_exit(0);
1655 }
Subscription * MySubscription
Definition: worker.c:112
#define LOGICALREP_PROTO_VERSION_NUM
Definition: logicalproto.h:28
WalReceiverConn * wrconn
Definition: worker.c:110
#define DEBUG1
Definition: elog.h:25
uint32 TimeLineID
Definition: xlogdefs.h:45
#define DatumGetInt32(X)
Definition: postgres.h:478
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
char * pstrdup(const char *in)
Definition: mcxt.c:1076
void CommitTransactionCommand(void)
Definition: xact.c:2744
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:253
void proc_exit(int code)
Definition: ipc.c:99
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1148
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
void replorigin_session_setup(RepOriginId node)
Definition: origin.c:1013
#define LOG
Definition: elog.h:26
char * LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
Definition: tablesync.c:815
#define OidIsValid(objectId)
Definition: c.h:576
RepOriginId replorigin_by_name(char *roname, bool missing_ok)
Definition: origin.c:211
#define NAMEDATALEN
Subscription * GetSubscription(Oid subid, bool missing_ok)
static void subscription_change_cb(Datum arg, int cacheid, uint32 hashvalue)
Definition: worker.c:1473
void pfree(void *pointer)
Definition: mcxt.c:949
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
#define ERROR
Definition: elog.h:43
Definition: guc.h:75
static bool am_tablesync_worker(void)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:170
#define walrcv_identify_system(conn, primary_tli, server_version)
Definition: walreceiver.h:249
void logicalrep_worker_attach(int slot)
Definition: launcher.c:612
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6700
#define SIGHUP
Definition: win32_port.h:163
XLogRecPtr startpoint
Definition: walreceiver.h:146
List * publications
RepOriginId replorigin_create(char *roname)
Definition: origin.c:242
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid)
Definition: postmaster.c:5611
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
MemoryContext ApplyContext
Definition: worker.c:108
static char ** options
union WalRcvStreamOptions::@97 proto
static void logicalrep_worker_sighup(SIGNAL_ARGS)
Definition: worker.c:1480
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:342
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1389
uintptr_t Datum
Definition: postgres.h:372
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
TimestampTz last_recv_time
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:670
RepOriginId replorigin_session_origin
Definition: origin.c:155
void StartTransactionCommand(void)
Definition: xact.c:2673
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:137
static int server_version
Definition: pg_dumpall.c:82
bool MySubscriptionValid
Definition: worker.c:113
int errmsg(const char *fmt,...)
Definition: elog.c:797
void die(SIGNAL_ARGS)
Definition: postgres.c:2652
static void LogicalRepApplyLoop(XLogRecPtr last_received)
Definition: worker.c:1015
#define elog
Definition: elog.h:219
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1745
TimestampTz reply_time
void invalidate_syncing_table_states(Datum arg, int cacheid, uint32 hashvalue)
Definition: tablesync.c:271
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5640
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:243

◆ check_relation_updatable()

static void check_relation_updatable ( LogicalRepRelMapEntry rel)
static

Definition at line 623 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().

624 {
625  /* Updatable, no error. */
626  if (rel->updatable)
627  return;
628 
629  /*
630  * We are in error mode so it's fine this is somewhat slow. It's better to
631  * give user correct error.
632  */
634  {
635  ereport(ERROR,
636  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
637  errmsg("publisher did not send replica identity column "
638  "expected by the logical replication target relation \"%s.%s\"",
639  rel->remoterel.nspname, rel->remoterel.relname)));
640  }
641 
642  ereport(ERROR,
643  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
644  errmsg("logical replication target relation \"%s.%s\" has "
645  "neither REPLICA IDENTITY index nor PRIMARY "
646  "KEY and published relation does not have "
647  "REPLICA IDENTITY FULL",
648  rel->remoterel.nspname, rel->remoterel.relname)));
649 }
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:547
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:576
#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

◆ create_estate_for_relation()

static EState* create_estate_for_relation ( LogicalRepRelMapEntry rel)
static

Definition at line 186 of file worker.c.

References AfterTriggerBeginQuery(), CreateExecutorState(), EState::es_num_result_relations, EState::es_output_cid, EState::es_range_table, EState::es_result_relation_info, EState::es_result_relations, EState::es_trig_tuple_slot, ExecInitExtraTupleSlot(), GetCurrentCommandId(), InitResultRelInfo(), list_make1, LogicalRepRelMapEntry::localrel, makeNode, 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().

187 {
188  EState *estate;
189  ResultRelInfo *resultRelInfo;
190  RangeTblEntry *rte;
191 
192  estate = CreateExecutorState();
193 
194  rte = makeNode(RangeTblEntry);
195  rte->rtekind = RTE_RELATION;
196  rte->relid = RelationGetRelid(rel->localrel);
197  rte->relkind = rel->localrel->rd_rel->relkind;
198  estate->es_range_table = list_make1(rte);
199 
200  resultRelInfo = makeNode(ResultRelInfo);
201  InitResultRelInfo(resultRelInfo, rel->localrel, 1, NULL, 0);
202 
203  estate->es_result_relations = resultRelInfo;
204  estate->es_num_result_relations = 1;
205  estate->es_result_relation_info = resultRelInfo;
206 
207  estate->es_output_cid = GetCurrentCommandId(true);
208 
209  /* Triggers might need a slot */
210  if (resultRelInfo->ri_TrigDesc)
211  estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
212 
213  /* Prepare to catch AFTER triggers. */
215 
216  return estate;
217 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1306
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
CommandId es_output_cid
Definition: execnodes.h:439
List * es_range_table
Definition: execnodes.h:432
Form_pg_class rd_rel
Definition: rel.h:114
#define list_make1(x1)
Definition: pg_list.h:139
ResultRelInfo * es_result_relations
Definition: execnodes.h:442
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:461
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:367
EState * CreateExecutorState(void)
Definition: execUtils.c:81
int es_num_result_relations
Definition: execnodes.h:443
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4526
#define makeNode(_type_)
Definition: nodes.h:560
RTEKind rtekind
Definition: parsenodes.h:951
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:680
#define RelationGetRelid(relation)
Definition: rel.h:425
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:444

◆ ensure_transaction()

static bool ensure_transaction ( void  )
static

Definition at line 157 of file worker.c.

References CurrentMemoryContext, IsTransactionState(), maybe_reread_subscription(), MemoryContextSwitchTo(), SetCurrentStatementStartTimestamp(), and StartTransactionCommand().

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

158 {
159  if (IsTransactionState())
160  {
162 
165 
166  return false;
167  }
168 
171 
173 
175  return true;
176 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static void maybe_reread_subscription(void)
Definition: worker.c:1337
static MemoryContext ApplyMessageContext
Definition: worker.c:107
void StartTransactionCommand(void)
Definition: xact.c:2673
bool IsTransactionState(void)
Definition: xact.c:351
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:733

◆ get_flush_position()

static void get_flush_position ( XLogRecPtr write,
XLogRecPtr flush,
bool have_pending_txes 
)
static

Definition at line 936 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, FlushPosition::node, pfree(), and FlushPosition::remote_end.

Referenced by send_feedback().

938 {
939  dlist_mutable_iter iter;
940  XLogRecPtr local_flush = GetFlushRecPtr();
941 
943  *flush = InvalidXLogRecPtr;
944 
946  {
947  FlushPosition *pos =
948  dlist_container(FlushPosition, node, iter.cur);
949 
950  *write = pos->remote_end;
951 
952  if (pos->local_end <= local_flush)
953  {
954  *flush = pos->remote_end;
955  dlist_delete(iter.cur);
956  pfree(pos);
957  }
958  else
959  {
960  /*
961  * Don't want to uselessly iterate over the rest of the list which
962  * could potentially be long. Instead get the last element and
963  * grab the write position from there.
964  */
965  pos = dlist_tail_element(FlushPosition, node,
966  &lsn_mapping);
967  *write = pos->remote_end;
968  *have_pending_txes = true;
969  return;
970  }
971  }
972 
973  *have_pending_txes = !dlist_is_empty(&lsn_mapping);
974 }
#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:99
#define write(a, b, c)
Definition: win32.h:14
XLogRecPtr remote_end
Definition: worker.c:96
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8254
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
void pfree(void *pointer)
Definition: mcxt.c:949
#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:95
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289

◆ GetRelationIdentityOrPK()

static Oid GetRelationIdentityOrPK ( Relation  rel)
static

Definition at line 547 of file worker.c.

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

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

548 {
549  Oid idxoid;
550 
551  idxoid = RelationGetReplicaIndex(rel);
552 
553  if (!OidIsValid(idxoid))
554  idxoid = RelationGetPrimaryKeyIndex(rel);
555 
556  return idxoid;
557 }
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4691
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
Oid RelationGetPrimaryKeyIndex(Relation relation)
Definition: relcache.c:4670

◆ IsLogicalWorker()

bool IsLogicalWorker ( void  )

Definition at line 1661 of file worker.c.

References MyLogicalRepWorker.

Referenced by ProcessInterrupts().

1662 {
1663  return MyLogicalRepWorker != NULL;
1664 }
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63

◆ logicalrep_worker_sighup()

static void logicalrep_worker_sighup ( SIGNAL_ARGS  )
static

Definition at line 1480 of file worker.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by ApplyWorkerMain().

1481 {
1482  int save_errno = errno;
1483 
1484  got_SIGHUP = true;
1485 
1486  /* Waken anything waiting on the process latch */
1487  SetLatch(MyLatch);
1488 
1489  errno = save_errno;
1490 }
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:52
static volatile sig_atomic_t got_SIGHUP
Definition: worker.c:125

◆ LogicalRepApplyLoop()

static void LogicalRepApplyLoop ( XLogRecPtr  last_received)
static

Definition at line 1015 of file worker.c.

References AcceptInvalidationMessages(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), apply_dispatch(), buf, CHECK_FOR_INTERRUPTS, StringInfoData::cursor, StringInfoData::data, dlist_is_empty(), ereport, errmsg(), ERROR, fd(), GetCurrentTimestamp(), got_SIGHUP, in_remote_transaction, StringInfoData::len, LOG, StringInfoData::maxlen, maybe_reread_subscription(), MemoryContextReset(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MyLatch, NAPTIME_PER_CYCLE, now(), PGC_SIGHUP, PGINVALID_SOCKET, pgstat_report_activity(), pq_getmsgbyte(), pq_getmsgint64(), proc_exit(), process_syncing_tables(), ProcessConfigFile(), ResetLatch(), send_feedback(), STATE_IDLE, TimestampTzPlusMilliseconds, TopMemoryContext, UpdateWorkerStats(), WAIT_EVENT_LOGICAL_APPLY_MAIN, WaitLatchOrSocket(), wal_receiver_timeout, walrcv_endstreaming, walrcv_receive, WalWriterDelay, WL_LATCH_SET, WL_POSTMASTER_DEATH, WL_SOCKET_READABLE, and WL_TIMEOUT.

Referenced by ApplyWorkerMain().

1016 {
1017  /*
1018  * Init the ApplyMessageContext which we clean up after each replication
1019  * protocol message.
1020  */
1022  "ApplyMessageContext",
1024 
1025  /* mark as idle, before starting to loop */
1027 
1028  for (;;)
1029  {
1031  int rc;
1032  int len;
1033  char *buf = NULL;
1034  bool endofstream = false;
1035  TimestampTz last_recv_timestamp = GetCurrentTimestamp();
1036  bool ping_sent = false;
1037  long wait_time;
1038 
1040 
1042 
1043  len = walrcv_receive(wrconn, &buf, &fd);
1044 
1045  if (len != 0)
1046  {
1047  /* Process the data */
1048  for (;;)
1049  {
1051 
1052  if (len == 0)
1053  {
1054  break;
1055  }
1056  else if (len < 0)
1057  {
1058  ereport(LOG,
1059  (errmsg("data stream from publisher has ended")));
1060  endofstream = true;
1061  break;
1062  }
1063  else
1064  {
1065  int c;
1066  StringInfoData s;
1067 
1068  /* Reset timeout. */
1069  last_recv_timestamp = GetCurrentTimestamp();
1070  ping_sent = false;
1071 
1072  /* Ensure we are reading the data into our memory context. */
1074 
1075  s.data = buf;
1076  s.len = len;
1077  s.cursor = 0;
1078  s.maxlen = -1;
1079 
1080  c = pq_getmsgbyte(&s);
1081 
1082  if (c == 'w')
1083  {
1084  XLogRecPtr start_lsn;
1085  XLogRecPtr end_lsn;
1086  TimestampTz send_time;
1087 
1088  start_lsn = pq_getmsgint64(&s);
1089  end_lsn = pq_getmsgint64(&s);
1090  send_time = pq_getmsgint64(&s);
1091 
1092  if (last_received < start_lsn)
1093  last_received = start_lsn;
1094 
1095  if (last_received < end_lsn)
1096  last_received = end_lsn;
1097 
1098  UpdateWorkerStats(last_received, send_time, false);
1099 
1100  apply_dispatch(&s);
1101  }
1102  else if (c == 'k')
1103  {
1104  XLogRecPtr end_lsn;
1106  bool reply_requested;
1107 
1108  end_lsn = pq_getmsgint64(&s);
1109  timestamp = pq_getmsgint64(&s);
1110  reply_requested = pq_getmsgbyte(&s);
1111 
1112  if (last_received < end_lsn)
1113  last_received = end_lsn;
1114 
1115  send_feedback(last_received, reply_requested, false);
1116  UpdateWorkerStats(last_received, timestamp, true);
1117  }
1118  /* other message types are purposefully ignored */
1119 
1121  }
1122 
1123  len = walrcv_receive(wrconn, &buf, &fd);
1124  }
1125  }
1126 
1127  /* confirm all writes so far */
1128  send_feedback(last_received, false, false);
1129 
1130  if (!in_remote_transaction)
1131  {
1132  /*
1133  * If we didn't get any transactions for a while there might be
1134  * unconsumed invalidation messages in the queue, consume them
1135  * now.
1136  */
1139 
1140  /* Process any table synchronization changes. */
1141  process_syncing_tables(last_received);
1142  }
1143 
1144  /* Cleanup the memory. */
1147 
1148  /* Check if we need to exit the streaming loop. */
1149  if (endofstream)
1150  {
1151  TimeLineID tli;
1152 
1153  walrcv_endstreaming(wrconn, &tli);
1154  break;
1155  }
1156 
1157  /*
1158  * Wait for more data or latch. If we have unflushed transactions,
1159  * wake up after WalWriterDelay to see if they've been flushed yet (in
1160  * which case we should send a feedback message). Otherwise, there's
1161  * no particular urgency about waking up unless we get data or a
1162  * signal.
1163  */
1164  if (!dlist_is_empty(&lsn_mapping))
1165  wait_time = WalWriterDelay;
1166  else
1167  wait_time = NAPTIME_PER_CYCLE;
1168 
1172  fd, wait_time,
1174 
1175  /* Emergency bailout if postmaster has died */
1176  if (rc & WL_POSTMASTER_DEATH)
1177  proc_exit(1);
1178 
1179  if (rc & WL_LATCH_SET)
1180  {
1183  }
1184 
1185  if (got_SIGHUP)
1186  {
1187  got_SIGHUP = false;
1189  }
1190 
1191  if (rc & WL_TIMEOUT)
1192  {
1193  /*
1194  * We didn't receive anything new. If we haven't heard anything
1195  * from the server for more than wal_receiver_timeout / 2, ping
1196  * the server. Also, if it's been longer than
1197  * wal_receiver_status_interval since the last update we sent,
1198  * send a status update to the master anyway, to report any
1199  * progress in applying WAL.
1200  */
1201  bool requestReply = false;
1202 
1203  /*
1204  * Check if time since last receive from standby has reached the
1205  * configured limit.
1206  */
1207  if (wal_receiver_timeout > 0)
1208  {
1210  TimestampTz timeout;
1211 
1212  timeout =
1213  TimestampTzPlusMilliseconds(last_recv_timestamp,
1215 
1216  if (now >= timeout)
1217  ereport(ERROR,
1218  (errmsg("terminating logical replication worker due to timeout")));
1219 
1220  /*
1221  * We didn't receive anything new, for half of receiver
1222  * replication timeout. Ping the server.
1223  */
1224  if (!ping_sent)
1225  {
1226  timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
1227  (wal_receiver_timeout / 2));
1228  if (now >= timeout)
1229  {
1230  requestReply = true;
1231  ping_sent = true;
1232  }
1233  }
1234  }
1235 
1236  send_feedback(last_received, requestReply, requestReply);
1237  }
1238  }
1239 }
static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
Definition: worker.c:1248
WalReceiverConn * wrconn
Definition: worker.c:110
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:255
uint32 TimeLineID
Definition: xlogdefs.h:45
void AcceptInvalidationMessages(void)
Definition: inval.c:679
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
static dlist_head lsn_mapping
Definition: worker.c:99
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:544
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
int64 timestamp
int64 TimestampTz
Definition: timestamp.h:39
static void UpdateWorkerStats(XLogRecPtr last_lsn, TimestampTz send_time, bool reply)
Definition: worker.c:999
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:257
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 MemoryContextReset(MemoryContext context)
Definition: mcxt.c:135
void ResetLatch(volatile Latch *latch)
Definition: latch.c:497
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
int wal_receiver_timeout
Definition: walreceiver.c:75
#define ERROR
Definition: elog.h:43
#define NAPTIME_PER_CYCLE
Definition: worker.c:90
bool in_remote_transaction
Definition: worker.c:115
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:170
char * c
static char * buf
Definition: pg_test_fsync.c:67
int pgsocket
Definition: port.h:31
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
MemoryContext ApplyContext
Definition: worker.c:108
#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:342
#define PGINVALID_SOCKET
Definition: port.h:33
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
static void apply_dispatch(StringInfo s)
Definition: worker.c:877
static void maybe_reread_subscription(void)
Definition: worker.c:1337
static MemoryContext ApplyMessageContext
Definition: worker.c:107
uint64 XLogRecPtr
Definition: xlogdefs.h:21
int WaitLatchOrSocket(volatile Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:356
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
int WalWriterDelay
Definition: walwriter.c:68
int errmsg(const char *fmt,...)
Definition: elog.c:797
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:455
struct Latch * MyLatch
Definition: globals.c:52
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
static volatile sig_atomic_t got_SIGHUP
Definition: worker.c:125

◆ maybe_reread_subscription()

static void maybe_reread_subscription ( void  )
static

Definition at line 1337 of file worker.c.

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

Referenced by apply_handle_commit(), ensure_transaction(), and LogicalRepApplyLoop().

1338 {
1339  MemoryContext oldctx;
1341  bool started_tx = false;
1342 
1343  /* When cache state is valid there is nothing to do here. */
1344  if (MySubscriptionValid)
1345  return;
1346 
1347  /* This function might be called inside or outside of transaction. */
1348  if (!IsTransactionState())
1349  {
1351  started_tx = true;
1352  }
1353 
1354  /* Ensure allocations in permanent context. */
1356 
1357  newsub = GetSubscription(MyLogicalRepWorker->subid, true);
1358 
1359  /*
1360  * Exit if the subscription was removed. This normally should not happen
1361  * as the worker gets killed during DROP SUBSCRIPTION.
1362  */
1363  if (!newsub)
1364  {
1365  ereport(LOG,
1366  (errmsg("logical replication apply worker for subscription \"%s\" will "
1367  "stop because the subscription was removed",
1368  MySubscription->name)));
1369 
1370  proc_exit(0);
1371  }
1372 
1373  /*
1374  * Exit if the subscription was disabled. This normally should not happen
1375  * as the worker gets killed during ALTER SUBSCRIPTION ... DISABLE.
1376  */
1377  if (!newsub->enabled)
1378  {
1379  ereport(LOG,
1380  (errmsg("logical replication apply worker for subscription \"%s\" will "
1381  "stop because the subscription was disabled",
1382  MySubscription->name)));
1383 
1384  proc_exit(0);
1385  }
1386 
1387  /*
1388  * Exit if connection string was changed. The launcher will start new
1389  * worker.
1390  */
1391  if (strcmp(newsub->conninfo, MySubscription->conninfo) != 0)
1392  {
1393  ereport(LOG,
1394  (errmsg("logical replication apply worker for subscription \"%s\" will "
1395  "restart because the connection information was changed",
1396  MySubscription->name)));
1397 
1398  proc_exit(0);
1399  }
1400 
1401  /*
1402  * Exit if subscription name was changed (it's used for
1403  * fallback_application_name). The launcher will start new worker.
1404  */
1405  if (strcmp(newsub->name, MySubscription->name) != 0)
1406  {
1407  ereport(LOG,
1408  (errmsg("logical replication apply worker for subscription \"%s\" will "
1409  "restart because subscription was renamed",
1410  MySubscription->name)));
1411 
1412  proc_exit(0);
1413  }
1414 
1415  /* !slotname should never happen when enabled is true. */
1416  Assert(newsub->slotname);
1417 
1418  /*
1419  * We need to make new connection to new slot if slot name has changed so
1420  * exit here as well if that's the case.
1421  */
1422  if (strcmp(newsub->slotname, MySubscription->slotname) != 0)
1423  {
1424  ereport(LOG,
1425  (errmsg("logical replication apply worker for subscription \"%s\" will "
1426  "restart because the replication slot name was changed",
1427  MySubscription->name)));
1428 
1429  proc_exit(0);
1430  }
1431 
1432  /*
1433  * Exit if publication list was changed. The launcher will start new
1434  * worker.
1435  */
1437  {
1438  ereport(LOG,
1439  (errmsg("logical replication apply worker for subscription \"%s\" will "
1440  "restart because subscription's publications were changed",
1441  MySubscription->name)));
1442 
1443  proc_exit(0);
1444  }
1445 
1446  /* Check for other changes that should never happen too. */
1447  if (newsub->dbid != MySubscription->dbid)
1448  {
1449  elog(ERROR, "subscription %u changed unexpectedly",
1451  }
1452 
1453  /* Clean old subscription info and switch to new one. */
1456 
1457  MemoryContextSwitchTo(oldctx);
1458 
1459  /* Change synchronous commit according to the user's wishes */
1460  SetConfigOption("synchronous_commit", MySubscription->synccommit,
1462 
1463  if (started_tx)
1465 
1466  MySubscriptionValid = true;
1467 }
Subscription * MySubscription
Definition: worker.c:112
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
void CommitTransactionCommand(void)
Definition: xact.c:2744
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:63
#define ERROR
Definition: elog.h:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6700
List * publications
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext ApplyContext
Definition: worker.c:108
#define Assert(condition)
Definition: c.h:670
void StartTransactionCommand(void)
Definition: xact.c:2673
bool IsTransactionState(void)
Definition: xact.c:351
bool MySubscriptionValid
Definition: worker.c:113
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

◆ send_feedback()

static void send_feedback ( XLogRecPtr  recvpos,
bool  force,
bool  requestReply 
)
static

Definition at line 1248 of file worker.c.

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

Referenced by LogicalRepApplyLoop().

1249 {
1250  static StringInfo reply_message = NULL;
1251  static TimestampTz send_time = 0;
1252 
1253  static XLogRecPtr last_recvpos = InvalidXLogRecPtr;
1254  static XLogRecPtr last_writepos = InvalidXLogRecPtr;
1255  static XLogRecPtr last_flushpos = InvalidXLogRecPtr;
1256 
1257  XLogRecPtr writepos;
1258  XLogRecPtr flushpos;
1259  TimestampTz now;
1260  bool have_pending_txes;
1261 
1262  /*
1263  * If the user doesn't want status to be reported to the publisher, be
1264  * sure to exit before doing anything at all.
1265  */
1266  if (!force && wal_receiver_status_interval <= 0)
1267  return;
1268 
1269  /* It's legal to not pass a recvpos */
1270  if (recvpos < last_recvpos)
1271  recvpos = last_recvpos;
1272 
1273  get_flush_position(&writepos, &flushpos, &have_pending_txes);
1274 
1275  /*
1276  * No outstanding transactions to flush, we can report the latest received
1277  * position. This is important for synchronous replication.
1278  */
1279  if (!have_pending_txes)
1280  flushpos = writepos = recvpos;
1281 
1282  if (writepos < last_writepos)
1283  writepos = last_writepos;
1284 
1285  if (flushpos < last_flushpos)
1286  flushpos = last_flushpos;
1287 
1288  now = GetCurrentTimestamp();
1289 
1290  /* if we've already reported everything we're good */
1291  if (!force &&
1292  writepos == last_writepos &&
1293  flushpos == last_flushpos &&
1294  !TimestampDifferenceExceeds(send_time, now,
1296  return;
1297  send_time = now;
1298 
1299  if (!reply_message)
1300  {
1302 
1303  reply_message = makeStringInfo();
1304  MemoryContextSwitchTo(oldctx);
1305  }
1306  else
1307  resetStringInfo(reply_message);
1308 
1309  pq_sendbyte(reply_message, 'r');
1310  pq_sendint64(reply_message, recvpos); /* write */
1311  pq_sendint64(reply_message, flushpos); /* flush */
1312  pq_sendint64(reply_message, writepos); /* apply */
1313  pq_sendint64(reply_message, now); /* sendTime */
1314  pq_sendbyte(reply_message, requestReply); /* replyRequested */
1315 
1316  elog(DEBUG2, "sending feedback (force %d) to recv %X/%X, write %X/%X, flush %X/%X",
1317  force,
1318  (uint32) (recvpos >> 32), (uint32) recvpos,
1319  (uint32) (writepos >> 32), (uint32) writepos,
1320  (uint32) (flushpos >> 32), (uint32) flushpos
1321  );
1322 
1323  walrcv_send(wrconn, reply_message->data, reply_message->len);
1324 
1325  if (recvpos > last_recvpos)
1326  last_recvpos = recvpos;
1327  if (writepos > last_writepos)
1328  last_writepos = writepos;
1329  if (flushpos > last_flushpos)
1330  last_flushpos = flushpos;
1331 }
WalReceiverConn * wrconn
Definition: worker.c:110
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
StringInfo makeStringInfo(void)
Definition: stringinfo.c:28
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void pq_sendint64(StringInfo buf, int64 i)
Definition: pqformat.h:156
static void pq_sendbyte(StringInfo buf, int8 byt)
Definition: pqformat.h:164
int wal_receiver_status_interval
Definition: walreceiver.c:74
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
static void get_flush_position(XLogRecPtr *write, XLogRecPtr *flush, bool *have_pending_txes)
Definition: worker.c:936
static StringInfoData reply_message
Definition: walreceiver.c:111
#define DEBUG2
Definition: elog.h:24
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
unsigned int uint32
Definition: c.h:296
MemoryContext ApplyContext
Definition: worker.c:108
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define walrcv_send(conn, buffer, nbytes)
Definition: walreceiver.h:259
#define elog
Definition: elog.h:219
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534

◆ should_apply_changes_for_rel()

static bool should_apply_changes_for_rel ( LogicalRepRelMapEntry rel)
static

Definition at line 141 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().

142 {
143  if (am_tablesync_worker())
144  return MyLogicalRepWorker->relid == rel->localreloid;
145  else
146  return (rel->state == SUBREL_STATE_READY ||
147  (rel->state == SUBREL_STATE_SYNCDONE &&
148  rel->statelsn <= remote_final_lsn));
149 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:116
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
static bool am_tablesync_worker(void)
#define SUBREL_STATE_SYNCDONE
#define SUBREL_STATE_READY

◆ slot_fill_defaults()

static void slot_fill_defaults ( LogicalRepRelMapEntry rel,
EState estate,
TupleTableSlot slot 
)
static

Definition at line 227 of file worker.c.

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

Referenced by apply_handle_insert().

229 {
230  TupleDesc desc = RelationGetDescr(rel->localrel);
231  int num_phys_attrs = desc->natts;
232  int i;
233  int attnum,
234  num_defaults = 0;
235  int *defmap;
236  ExprState **defexprs;
237  ExprContext *econtext;
238 
239  econtext = GetPerTupleExprContext(estate);
240 
241  /* We got all the data via replication, no need to evaluate anything. */
242  if (num_phys_attrs == rel->remoterel.natts)
243  return;
244 
245  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
246  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
247 
248  for (attnum = 0; attnum < num_phys_attrs; attnum++)
249  {
250  Expr *defexpr;
251 
252  if (TupleDescAttr(desc, attnum)->attisdropped)
253  continue;
254 
255  if (rel->attrmap[attnum] >= 0)
256  continue;
257 
258  defexpr = (Expr *) build_column_default(rel->localrel, attnum + 1);
259 
260  if (defexpr != NULL)
261  {
262  /* Run the expression through planner */
263  defexpr = expression_planner(defexpr);
264 
265  /* Initialize executable expression in copycontext */
266  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
267  defmap[num_defaults] = attnum;
268  num_defaults++;
269  }
270 
271  }
272 
273  for (i = 0; i < num_defaults; i++)
274  slot->tts_values[defmap[i]] =
275  ExecEvalExpr(defexprs[i], econtext, &slot->tts_isnull[defmap[i]]);
276 }
#define RelationGetDescr(relation)
Definition: rel.h:437
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
Expr * expression_planner(Expr *expr)
Definition: planner.c:6026
Datum * tts_values
Definition: tuptable.h:125
int natts
Definition: tupdesc.h:79
#define GetPerTupleExprContext(estate)
Definition: executor.h:467
LogicalRepRelation remoterel
bool * tts_isnull
Definition: tuptable.h:126
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:276
Node * build_column_default(Relation rel, int attrno)
void * palloc(Size size)
Definition: mcxt.c:848
int i
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:113

◆ slot_modify_cstrings()

static void slot_modify_cstrings ( TupleTableSlot slot,
LogicalRepRelMapEntry rel,
char **  values,
bool replaces 
)
static

Definition at line 371 of file worker.c.

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

Referenced by apply_handle_update().

373 {
374  int natts = slot->tts_tupleDescriptor->natts;
375  int i;
376  SlotErrCallbackArg errarg;
377  ErrorContextCallback errcallback;
378 
379  slot_getallattrs(slot);
380  ExecClearTuple(slot);
381 
382  /* Push callback + info on the error context stack */
383  errarg.rel = &rel->remoterel;
384  errarg.attnum = -1;
385  errcallback.callback = slot_store_error_callback;
386  errcallback.arg = (void *) &errarg;
387  errcallback.previous = error_context_stack;
388  error_context_stack = &errcallback;
389 
390  /* Call the "in" function for each replaced attribute */
391  for (i = 0; i < natts; i++)
392  {
394  int remoteattnum = rel->attrmap[i];
395 
396  if (remoteattnum < 0)
397  continue;
398 
399  if (!replaces[remoteattnum])
400  continue;
401 
402  if (values[remoteattnum] != NULL)
403  {
404  Oid typinput;
405  Oid typioparam;
406 
407  errarg.attnum = remoteattnum;
408 
409  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
410  slot->tts_values[i] = OidInputFunctionCall(typinput,
411  values[remoteattnum],
412  typioparam,
413  att->atttypmod);
414  slot->tts_isnull[i] = false;
415  }
416  else
417  {
418  slot->tts_values[i] = (Datum) 0;
419  slot->tts_isnull[i] = true;
420  }
421  }
422 
423  /* Pop the error context stack */
424  error_context_stack = errcallback.previous;
425 
426  ExecStoreVirtualTuple(slot);
427 }
LogicalRepRelation * rel
Definition: worker.c:103
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
Datum * tts_values
Definition: tuptable.h:125
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:239
struct ErrorContextCallback * previous
Definition: elog.h:238
int natts
Definition: tupdesc.h:79
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:187
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2632
void slot_getallattrs(TupleTableSlot *slot)
Definition: heaptuple.c:1238
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
uintptr_t Datum
Definition: postgres.h:372
static void slot_store_error_callback(void *arg)
Definition: worker.c:282
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int i
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1733
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:488

◆ slot_store_cstrings()

static void slot_store_cstrings ( TupleTableSlot slot,
LogicalRepRelMapEntry rel,
char **  values 
)
static

Definition at line 307 of file worker.c.

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

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

309 {
310  int natts = slot->tts_tupleDescriptor->natts;
311  int i;
312  SlotErrCallbackArg errarg;
313  ErrorContextCallback errcallback;
314 
315  ExecClearTuple(slot);
316 
317  /* Push callback + info on the error context stack */
318  errarg.rel = &rel->remoterel;
319  errarg.attnum = -1;
320  errcallback.callback = slot_store_error_callback;
321  errcallback.arg = (void *) &errarg;
322  errcallback.previous = error_context_stack;
323  error_context_stack = &errcallback;
324 
325  /* Call the "in" function for each non-dropped attribute */
326  for (i = 0; i < natts; i++)
327  {
329  int remoteattnum = rel->attrmap[i];
330 
331  if (!att->attisdropped && remoteattnum >= 0 &&
332  values[remoteattnum] != NULL)
333  {
334  Oid typinput;
335  Oid typioparam;
336 
337  errarg.attnum = remoteattnum;
338 
339  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
340  slot->tts_values[i] = OidInputFunctionCall(typinput,
341  values[remoteattnum],
342  typioparam,
343  att->atttypmod);
344  slot->tts_isnull[i] = false;
345  }
346  else
347  {
348  /*
349  * We assign NULL to dropped attributes, NULL values, and missing
350  * values (missing values should be later filled using
351  * slot_fill_defaults).
352  */
353  slot->tts_values[i] = (Datum) 0;
354  slot->tts_isnull[i] = true;
355  }
356  }
357 
358  /* Pop the error context stack */
359  error_context_stack = errcallback.previous;
360 
361  ExecStoreVirtualTuple(slot);
362 }
LogicalRepRelation * rel
Definition: worker.c:103
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
Datum * tts_values
Definition: tuptable.h:125
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:239
struct ErrorContextCallback * previous
Definition: elog.h:238
int natts
Definition: tupdesc.h:79
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:187
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2632
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
uintptr_t Datum
Definition: postgres.h:372
static void slot_store_error_callback(void *arg)
Definition: worker.c:282
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int i
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1733
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:488

◆ slot_store_error_callback()

static void slot_store_error_callback ( void *  arg)
static

Definition at line 282 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().

283 {
285  Oid remotetypoid,
286  localtypoid;
287 
288  if (errarg->attnum < 0)
289  return;
290 
291  remotetypoid = errarg->rel->atttyps[errarg->attnum];
292  localtypoid = logicalrep_typmap_getid(remotetypoid);
293  errcontext("processing remote data for replication target relation \"%s.%s\" column \"%s\", "
294  "remote type %s, local type %s",
295  errarg->rel->nspname, errarg->rel->relname,
296  errarg->rel->attnames[errarg->attnum],
297  format_type_be(remotetypoid),
298  format_type_be(localtypoid));
299 }
LogicalRepRelation * rel
Definition: worker.c:103
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
Oid logicalrep_typmap_getid(Oid remoteid)
Definition: relation.c:446
unsigned int Oid
Definition: postgres_ext.h:31
#define errcontext
Definition: elog.h:164
void * arg

◆ store_flush_position()

static void store_flush_position ( XLogRecPtr  remote_lsn)
static

Definition at line 980 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().

981 {
982  FlushPosition *flushpos;
983 
984  /* Need to do this in permanent context */
986 
987  /* Track commit lsn */
988  flushpos = (FlushPosition *) palloc(sizeof(FlushPosition));
989  flushpos->local_end = XactLastCommitEnd;
990  flushpos->remote_end = remote_lsn;
991 
992  dlist_push_tail(&lsn_mapping, &flushpos->node);
994 }
static dlist_head lsn_mapping
Definition: worker.c:99
dlist_node node
Definition: worker.c:94
XLogRecPtr XactLastCommitEnd
Definition: xlog.c:340
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:96
MemoryContext ApplyContext
Definition: worker.c:108
XLogRecPtr local_end
Definition: worker.c:95
static MemoryContext ApplyMessageContext
Definition: worker.c:107
void * palloc(Size size)
Definition: mcxt.c:848

◆ subscription_change_cb()

static void subscription_change_cb ( Datum  arg,
int  cacheid,
uint32  hashvalue 
)
static

Definition at line 1473 of file worker.c.

References MySubscriptionValid.

Referenced by ApplyWorkerMain().

1474 {
1475  MySubscriptionValid = false;
1476 }
bool MySubscriptionValid
Definition: worker.c:113

◆ UpdateWorkerStats()

static void UpdateWorkerStats ( XLogRecPtr  last_lsn,
TimestampTz  send_time,
bool  reply 
)
static

Definition at line 999 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().

1000 {
1002  MyLogicalRepWorker->last_send_time = send_time;
1004  if (reply)
1005  {
1007  MyLogicalRepWorker->reply_time = send_time;
1008  }
1009 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
TimestampTz last_send_time
XLogRecPtr last_lsn
XLogRecPtr last_lsn
Definition: walsender.c:213
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
XLogRecPtr reply_lsn
TimestampTz last_recv_time
TimestampTz reply_time

Variable Documentation

◆ ApplyContext

MemoryContext ApplyContext = NULL

Definition at line 108 of file worker.c.

◆ ApplyMessageContext

MemoryContext ApplyMessageContext = NULL
static

Definition at line 107 of file worker.c.

◆ got_SIGHUP

volatile sig_atomic_t got_SIGHUP = false
static

Definition at line 125 of file worker.c.

Referenced by logicalrep_worker_sighup(), and LogicalRepApplyLoop().

◆ in_remote_transaction

bool in_remote_transaction = false

◆ lsn_mapping

dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping)
static

Definition at line 99 of file worker.c.

◆ MySubscription

◆ MySubscriptionValid

bool MySubscriptionValid = false

Definition at line 113 of file worker.c.

Referenced by ApplyWorkerMain(), maybe_reread_subscription(), and subscription_change_cb().

◆ remote_final_lsn

XLogRecPtr remote_final_lsn = InvalidXLogRecPtr
static

Definition at line 116 of file worker.c.

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

◆ wrconn