PostgreSQL Source Code  git master
worker.c File Reference
#include "postgres.h"
#include <sys/stat.h>
#include <unistd.h>
#include "access/table.h"
#include "access/tableam.h"
#include "access/twophase.h"
#include "access/xact.h"
#include "access/xlog_internal.h"
#include "catalog/catalog.h"
#include "catalog/namespace.h"
#include "catalog/partition.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_subscription.h"
#include "catalog/pg_subscription_rel.h"
#include "catalog/pg_tablespace.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/execPartition.h"
#include "executor/nodeModifyTable.h"
#include "funcapi.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "optimizer/optimizer.h"
#include "pgstat.h"
#include "postmaster/bgworker.h"
#include "postmaster/interrupt.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/origin.h"
#include "replication/reorderbuffer.h"
#include "replication/snapbuild.h"
#include "replication/walreceiver.h"
#include "replication/worker_internal.h"
#include "rewrite/rewriteHandler.h"
#include "storage/buffile.h"
#include "storage/bufmgr.h"
#include "storage/fd.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/dynahash.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/rel.h"
#include "utils/syscache.h"
#include "utils/timeout.h"
Include dependency graph for worker.c:

Go to the source code of this file.

Data Structures

struct  FlushPosition
 
struct  ApplyExecutionData
 
struct  ApplyErrorCallbackArg
 
struct  SubXactInfo
 
struct  ApplySubXactData
 

Macros

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

Typedefs

typedef struct FlushPosition FlushPosition
 
typedef struct ApplyExecutionData ApplyExecutionData
 
typedef struct ApplyErrorCallbackArg ApplyErrorCallbackArg
 
typedef struct SubXactInfo SubXactInfo
 
typedef struct ApplySubXactData ApplySubXactData
 

Functions

static void subxact_filename (char *path, Oid subid, TransactionId xid)
 
static void changes_filename (char *path, Oid subid, TransactionId xid)
 
static void subxact_info_write (Oid subid, TransactionId xid)
 
static void subxact_info_read (Oid subid, TransactionId xid)
 
static void subxact_info_add (TransactionId xid)
 
static void cleanup_subxact_info (void)
 
static void stream_cleanup_files (Oid subid, TransactionId xid)
 
static void stream_open_file (Oid subid, TransactionId xid, bool first)
 
static void stream_write_change (char action, StringInfo s)
 
static void stream_close_file (void)
 
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 void apply_dispatch (StringInfo s)
 
static void apply_handle_commit_internal (LogicalRepCommitData *commit_data)
 
static void apply_handle_insert_internal (ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot)
 
static void apply_handle_update_internal (ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup)
 
static void apply_handle_delete_internal (ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot)
 
static bool FindReplTupleInLocalRel (EState *estate, Relation localrel, LogicalRepRelation *remoterel, TupleTableSlot *remoteslot, TupleTableSlot **localslot)
 
static void apply_handle_tuple_routing (ApplyExecutionData *edata, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, CmdType operation)
 
static void TwoPhaseTransactionGid (Oid subid, TransactionId xid, char *gid, int szgid)
 
static void apply_spooled_messages (TransactionId xid, XLogRecPtr lsn)
 
static void apply_error_callback (void *arg)
 
static void set_apply_error_context_xact (TransactionId xid, TimestampTz ts)
 
static void reset_apply_error_context_info (void)
 
static bool should_apply_changes_for_rel (LogicalRepRelMapEntry *rel)
 
static void begin_replication_step (void)
 
static void end_replication_step (void)
 
static bool handle_streamed_transaction (LogicalRepMsgType action, StringInfo s)
 
static ApplyExecutionDatacreate_edata_for_relation (LogicalRepRelMapEntry *rel)
 
static void finish_edata (ApplyExecutionData *edata)
 
static void slot_fill_defaults (LogicalRepRelMapEntry *rel, EState *estate, TupleTableSlot *slot)
 
static void slot_store_data (TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
 
static void slot_modify_data (TupleTableSlot *slot, TupleTableSlot *srcslot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
 
static void apply_handle_begin (StringInfo s)
 
static void apply_handle_commit (StringInfo s)
 
static void apply_handle_begin_prepare (StringInfo s)
 
static void apply_handle_prepare_internal (LogicalRepPreparedTxnData *prepare_data)
 
static void apply_handle_prepare (StringInfo s)
 
static void apply_handle_commit_prepared (StringInfo s)
 
static void apply_handle_rollback_prepared (StringInfo s)
 
static void apply_handle_stream_prepare (StringInfo s)
 
static void apply_handle_origin (StringInfo s)
 
static void apply_handle_stream_start (StringInfo s)
 
static void apply_handle_stream_stop (StringInfo s)
 
static void apply_handle_stream_abort (StringInfo s)
 
static void apply_handle_stream_commit (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_handle_truncate (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)
 
bool IsLogicalWorker (void)
 

Variables

static dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping)
 
static ApplyErrorCallbackArg apply_error_callback_arg
 
static MemoryContext ApplyMessageContext = NULL
 
MemoryContext ApplyContext = NULL
 
static MemoryContext LogicalStreamingContext = NULL
 
WalReceiverConnLogRepWorkerWalRcvConn = NULL
 
SubscriptionMySubscription = NULL
 
bool MySubscriptionValid = false
 
bool in_remote_transaction = false
 
static XLogRecPtr remote_final_lsn = InvalidXLogRecPtr
 
static bool in_streamed_transaction = false
 
static TransactionId stream_xid = InvalidTransactionId
 
static BufFilestream_fd = NULL
 
static ApplySubXactData subxact_data = {0, 0, InvalidTransactionId, NULL}
 

Macro Definition Documentation

◆ NAPTIME_PER_CYCLE

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

Definition at line 195 of file worker.c.

Referenced by LogicalRepApplyLoop().

Typedef Documentation

◆ ApplyErrorCallbackArg

◆ ApplyExecutionData

◆ ApplySubXactData

◆ FlushPosition

typedef struct FlushPosition FlushPosition

◆ SubXactInfo

typedef struct SubXactInfo SubXactInfo

Function Documentation

◆ apply_dispatch()

static void apply_dispatch ( StringInfo  s)
static

Definition at line 2314 of file worker.c.

References generate_unaccent_rules::action, apply_handle_begin(), apply_handle_begin_prepare(), apply_handle_commit(), apply_handle_commit_prepared(), apply_handle_delete(), apply_handle_insert(), apply_handle_origin(), apply_handle_prepare(), apply_handle_relation(), apply_handle_rollback_prepared(), apply_handle_stream_abort(), apply_handle_stream_commit(), apply_handle_stream_prepare(), apply_handle_stream_start(), apply_handle_stream_stop(), apply_handle_truncate(), apply_handle_type(), apply_handle_update(), ApplyErrorCallbackArg::command, ereport, errcode(), errmsg(), ERROR, LOGICAL_REP_MSG_BEGIN, LOGICAL_REP_MSG_BEGIN_PREPARE, LOGICAL_REP_MSG_COMMIT, LOGICAL_REP_MSG_COMMIT_PREPARED, LOGICAL_REP_MSG_DELETE, LOGICAL_REP_MSG_INSERT, LOGICAL_REP_MSG_MESSAGE, LOGICAL_REP_MSG_ORIGIN, LOGICAL_REP_MSG_PREPARE, LOGICAL_REP_MSG_RELATION, LOGICAL_REP_MSG_ROLLBACK_PREPARED, LOGICAL_REP_MSG_STREAM_ABORT, LOGICAL_REP_MSG_STREAM_COMMIT, LOGICAL_REP_MSG_STREAM_PREPARE, LOGICAL_REP_MSG_STREAM_START, LOGICAL_REP_MSG_STREAM_STOP, LOGICAL_REP_MSG_TRUNCATE, LOGICAL_REP_MSG_TYPE, LOGICAL_REP_MSG_UPDATE, and pq_getmsgbyte().

Referenced by apply_spooled_messages(), and LogicalRepApplyLoop().

2315 {
2317  LogicalRepMsgType saved_command;
2318 
2319  /*
2320  * Set the current command being applied. Since this function can be
2321  * called recusively when applying spooled changes, save the current
2322  * command.
2323  */
2324  saved_command = apply_error_callback_arg.command;
2326 
2327  switch (action)
2328  {
2329  case LOGICAL_REP_MSG_BEGIN:
2330  apply_handle_begin(s);
2331  break;
2332 
2335  break;
2336 
2339  break;
2340 
2343  break;
2344 
2347  break;
2348 
2351  break;
2352 
2355  break;
2356 
2357  case LOGICAL_REP_MSG_TYPE:
2358  apply_handle_type(s);
2359  break;
2360 
2363  break;
2364 
2366 
2367  /*
2368  * Logical replication does not use generic logical messages yet.
2369  * Although, it could be used by other applications that use this
2370  * output plugin.
2371  */
2372  break;
2373 
2376  break;
2377 
2380  break;
2381 
2384  break;
2385 
2388  break;
2389 
2392  break;
2393 
2396  break;
2397 
2400  break;
2401 
2404  break;
2405 
2408  break;
2409 
2410  default:
2411  ereport(ERROR,
2412  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2413  errmsg("invalid logical replication message type \"%c\"", action)));
2414  }
2415 
2416  /* Reset the current command */
2417  apply_error_callback_arg.command = saved_command;
2418 }
static void apply_handle_type(StringInfo s)
Definition: worker.c:1502
static void apply_handle_insert(StringInfo s)
Definition: worker.c:1535
LogicalRepMsgType command
Definition: worker.c:221
static void apply_handle_stream_abort(StringInfo s)
Definition: worker.c:1198
static void apply_handle_stream_start(StringInfo s)
Definition: worker.c:1098
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
static void apply_handle_prepare(StringInfo s)
Definition: worker.c:887
static ApplyErrorCallbackArg apply_error_callback_arg
Definition: worker.c:230
static void apply_handle_stream_stop(StringInfo s)
Definition: worker.c:1165
static void apply_handle_delete(StringInfo s)
Definition: worker.c:1824
static void apply_handle_stream_prepare(StringInfo s)
Definition: worker.c:1029
static void apply_handle_begin(StringInfo s)
Definition: worker.c:783
static void apply_handle_begin_prepare(StringInfo s)
Definition: worker.c:829
static void apply_handle_commit(StringInfo s)
Definition: worker.c:803
static void apply_handle_stream_commit(StringInfo s)
Definition: worker.c:1416
static void apply_handle_update(StringInfo s)
Definition: worker.c:1658
static void apply_handle_relation(StringInfo s)
Definition: worker.c:1485
static void apply_handle_commit_prepared(StringInfo s)
Definition: worker.c:933
#define ereport(elevel,...)
Definition: elog.h:157
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
static void apply_handle_origin(StringInfo s)
Definition: worker.c:1080
LogicalRepMsgType
Definition: logicalproto.h:51
int errmsg(const char *fmt,...)
Definition: elog.c:909
static void apply_handle_rollback_prepared(StringInfo s)
Definition: worker.c:974
static void apply_handle_truncate(StringInfo s)
Definition: worker.c:2199

◆ apply_error_callback()

static void apply_error_callback ( void *  arg)
static

Definition at line 3567 of file worker.c.

References _, appendStringInfo(), apply_error_callback_arg, LogicalRepRelation::attnames, buf, ApplyErrorCallbackArg::command, StringInfoData::data, errcontext, initStringInfo(), logicalrep_message_type(), LogicalRepRelation::nspname, pfree(), ApplyErrorCallbackArg::rel, LogicalRepRelation::relname, ApplyErrorCallbackArg::remote_attnum, ApplyErrorCallbackArg::remote_xid, LogicalRepRelMapEntry::remoterel, timestamptz_to_str(), TransactionIdIsNormal, and ApplyErrorCallbackArg::ts.

Referenced by LogicalRepApplyLoop().

3568 {
3571 
3573  return;
3574 
3575  initStringInfo(&buf);
3576  appendStringInfo(&buf, _("processing remote data during \"%s\""),
3577  logicalrep_message_type(errarg->command));
3578 
3579  /* append relation information */
3580  if (errarg->rel)
3581  {
3582  appendStringInfo(&buf, _(" for replication target relation \"%s.%s\""),
3583  errarg->rel->remoterel.nspname,
3584  errarg->rel->remoterel.relname);
3585  if (errarg->remote_attnum >= 0)
3586  appendStringInfo(&buf, _(" column \"%s\""),
3587  errarg->rel->remoterel.attnames[errarg->remote_attnum]);
3588  }
3589 
3590  /* append transaction information */
3591  if (TransactionIdIsNormal(errarg->remote_xid))
3592  {
3593  appendStringInfo(&buf, _(" in transaction %u"), errarg->remote_xid);
3594  if (errarg->ts != 0)
3595  appendStringInfo(&buf, _(" at %s"),
3596  timestamptz_to_str(errarg->ts));
3597  }
3598 
3599  errcontext("%s", buf.data);
3600  pfree(buf.data);
3601 }
LogicalRepMsgType command
Definition: worker.c:221
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
LogicalRepRelation remoterel
static ApplyErrorCallbackArg apply_error_callback_arg
Definition: worker.c:230
char * logicalrep_message_type(LogicalRepMsgType action)
Definition: proto.c:1164
static char * buf
Definition: pg_test_fsync.c:68
TimestampTz ts
Definition: worker.c:227
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
LogicalRepRelMapEntry * rel
Definition: worker.c:222
TransactionId remote_xid
Definition: worker.c:226
#define errcontext
Definition: elog.h:204
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
#define _(x)
Definition: elog.c:89
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1774

◆ apply_handle_begin()

static void apply_handle_begin ( StringInfo  s)
static

Definition at line 783 of file worker.c.

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

Referenced by apply_dispatch().

784 {
785  LogicalRepBeginData begin_data;
786 
787  logicalrep_read_begin(s, &begin_data);
788  set_apply_error_context_xact(begin_data.xid, begin_data.committime);
789 
790  remote_final_lsn = begin_data.final_lsn;
791 
792  in_remote_transaction = true;
793 
795 }
TransactionId xid
Definition: logicalproto.h:125
static XLogRecPtr remote_final_lsn
Definition: worker.c:251
void logicalrep_read_begin(StringInfo in, LogicalRepBeginData *begin_data)
Definition: proto.c:60
bool in_remote_transaction
Definition: worker.c:250
XLogRecPtr final_lsn
Definition: logicalproto.h:123
void pgstat_report_activity(BackendState state, const char *cmd_str)
static void set_apply_error_context_xact(TransactionId xid, TimestampTz ts)
Definition: worker.c:3605
TimestampTz committime
Definition: logicalproto.h:124

◆ apply_handle_begin_prepare()

static void apply_handle_begin_prepare ( StringInfo  s)
static

Definition at line 829 of file worker.c.

References am_tablesync_worker(), ereport, errcode(), errmsg_internal(), ERROR, in_remote_transaction, logicalrep_read_begin_prepare(), pgstat_report_activity(), LogicalRepPreparedTxnData::prepare_lsn, LogicalRepPreparedTxnData::prepare_time, remote_final_lsn, set_apply_error_context_xact(), STATE_RUNNING, and LogicalRepPreparedTxnData::xid.

Referenced by apply_dispatch().

830 {
831  LogicalRepPreparedTxnData begin_data;
832 
833  /* Tablesync should never receive prepare. */
834  if (am_tablesync_worker())
835  ereport(ERROR,
836  (errcode(ERRCODE_PROTOCOL_VIOLATION),
837  errmsg_internal("tablesync worker received a BEGIN PREPARE message")));
838 
839  logicalrep_read_begin_prepare(s, &begin_data);
840  set_apply_error_context_xact(begin_data.xid, begin_data.prepare_time);
841 
842  remote_final_lsn = begin_data.prepare_lsn;
843 
844  in_remote_transaction = true;
845 
847 }
void logicalrep_read_begin_prepare(StringInfo in, LogicalRepPreparedTxnData *begin_data)
Definition: proto.c:131
static XLogRecPtr remote_final_lsn
Definition: worker.c:251
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:250
static bool am_tablesync_worker(void)
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
void pgstat_report_activity(BackendState state, const char *cmd_str)
static void set_apply_error_context_xact(TransactionId xid, TimestampTz ts)
Definition: worker.c:3605

◆ apply_handle_commit()

static void apply_handle_commit ( StringInfo  s)
static

Definition at line 803 of file worker.c.

References apply_handle_commit_internal(), LogicalRepCommitData::commit_lsn, LogicalRepCommitData::end_lsn, ereport, errcode(), errmsg_internal(), ERROR, logicalrep_read_commit(), LSN_FORMAT_ARGS, pgstat_report_activity(), process_syncing_tables(), remote_final_lsn, reset_apply_error_context_info(), and STATE_IDLE.

Referenced by apply_dispatch().

804 {
805  LogicalRepCommitData commit_data;
806 
807  logicalrep_read_commit(s, &commit_data);
808 
809  if (commit_data.commit_lsn != remote_final_lsn)
810  ereport(ERROR,
811  (errcode(ERRCODE_PROTOCOL_VIOLATION),
812  errmsg_internal("incorrect commit LSN %X/%X in commit message (expected %X/%X)",
813  LSN_FORMAT_ARGS(commit_data.commit_lsn),
815 
816  apply_handle_commit_internal(&commit_data);
817 
818  /* Process any tables that are being synchronized in parallel. */
819  process_syncing_tables(commit_data.end_lsn);
820 
823 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:251
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
int errcode(int sqlerrcode)
Definition: elog.c:698
static void reset_apply_error_context_info(void)
Definition: worker.c:3613
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define ERROR
Definition: elog.h:46
static void apply_handle_commit_internal(LogicalRepCommitData *commit_data)
Definition: worker.c:1450
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
void logicalrep_read_commit(StringInfo in, LogicalRepCommitData *commit_data)
Definition: proto.c:95
void pgstat_report_activity(BackendState state, const char *cmd_str)

◆ apply_handle_commit_internal()

static void apply_handle_commit_internal ( LogicalRepCommitData commit_data)
static

Definition at line 1450 of file worker.c.

References AcceptInvalidationMessages(), LogicalRepCommitData::committime, CommitTransactionCommand(), LogicalRepCommitData::end_lsn, in_remote_transaction, IsTransactionState(), maybe_reread_subscription(), pgstat_report_stat(), replorigin_session_origin_lsn, replorigin_session_origin_timestamp, and store_flush_position().

Referenced by apply_handle_commit(), and apply_handle_stream_commit().

1451 {
1452  if (IsTransactionState())
1453  {
1454  /*
1455  * Update origin state so we can restart streaming from correct
1456  * position in case of crash.
1457  */
1458  replorigin_session_origin_lsn = commit_data->end_lsn;
1460 
1462  pgstat_report_stat(false);
1463 
1464  store_flush_position(commit_data->end_lsn);
1465  }
1466  else
1467  {
1468  /* Process any invalidation messages that might have accumulated. */
1471  }
1472 
1473  in_remote_transaction = false;
1474 }
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2478
void AcceptInvalidationMessages(void)
Definition: inval.c:725
void CommitTransactionCommand(void)
Definition: xact.c:2949
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:858
bool in_remote_transaction
Definition: worker.c:250
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:155
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:156
static void maybe_reread_subscription(void)
Definition: worker.c:2850
bool IsTransactionState(void)
Definition: xact.c:371
TimestampTz committime
Definition: logicalproto.h:132

◆ apply_handle_commit_prepared()

static void apply_handle_commit_prepared ( StringInfo  s)
static

Definition at line 933 of file worker.c.

References begin_replication_step(), LogicalRepCommitPreparedTxnData::commit_time, CommitTransactionCommand(), LogicalRepCommitPreparedTxnData::end_lsn, end_replication_step(), FinishPreparedTransaction(), GIDSIZE, in_remote_transaction, logicalrep_read_commit_prepared(), Subscription::oid, pgstat_report_activity(), pgstat_report_stat(), process_syncing_tables(), replorigin_session_origin_lsn, replorigin_session_origin_timestamp, reset_apply_error_context_info(), set_apply_error_context_xact(), STATE_IDLE, store_flush_position(), TwoPhaseTransactionGid(), and LogicalRepCommitPreparedTxnData::xid.

Referenced by apply_dispatch().

934 {
935  LogicalRepCommitPreparedTxnData prepare_data;
936  char gid[GIDSIZE];
937 
938  logicalrep_read_commit_prepared(s, &prepare_data);
939  set_apply_error_context_xact(prepare_data.xid, prepare_data.commit_time);
940 
941  /* Compute GID for two_phase transactions. */
943  gid, sizeof(gid));
944 
945  /* There is no transaction when COMMIT PREPARED is called */
947 
948  /*
949  * Update origin state so we can restart streaming from correct position
950  * in case of crash.
951  */
952  replorigin_session_origin_lsn = prepare_data.end_lsn;
954 
955  FinishPreparedTransaction(gid, true);
958  pgstat_report_stat(false);
959 
960  store_flush_position(prepare_data.end_lsn);
961  in_remote_transaction = false;
962 
963  /* Process any tables that are being synchronized in parallel. */
964  process_syncing_tables(prepare_data.end_lsn);
965 
968 }
Subscription * MySubscription
Definition: worker.c:247
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2478
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
void CommitTransactionCommand(void)
Definition: xact.c:2949
static void reset_apply_error_context_info(void)
Definition: worker.c:3613
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:858
bool in_remote_transaction
Definition: worker.c:250
#define GIDSIZE
Definition: xact.h:31
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:155
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:156
static void begin_replication_step(void)
Definition: worker.c:370
void FinishPreparedTransaction(const char *gid, bool isCommit)
Definition: twophase.c:1409
static void end_replication_step(void)
Definition: worker.c:393
void logicalrep_read_commit_prepared(StringInfo in, LogicalRepCommitPreparedTxnData *prepare_data)
Definition: proto.c:264
void pgstat_report_activity(BackendState state, const char *cmd_str)
static void TwoPhaseTransactionGid(Oid subid, TransactionId xid, char *gid, int szgid)
Definition: worker.c:3315
static void set_apply_error_context_xact(TransactionId xid, TimestampTz ts)
Definition: worker.c:3605

◆ apply_handle_delete()

static void apply_handle_delete ( StringInfo  s)
static

Definition at line 1824 of file worker.c.

References apply_handle_delete_internal(), apply_handle_tuple_routing(), begin_replication_step(), check_relation_updatable(), CMD_DELETE, create_edata_for_relation(), end_replication_step(), ApplyExecutionData::estate, ExecInitExtraTupleSlot(), finish_edata(), GetPerTupleMemoryContext, handle_streamed_transaction(), LogicalRepRelMapEntry::localrel, LOGICAL_REP_MSG_DELETE, logicalrep_read_delete(), logicalrep_rel_close(), logicalrep_rel_open(), MemoryContextSwitchTo(), NoLock, RelationData::rd_rel, ApplyErrorCallbackArg::rel, RelationGetDescr, RowExclusiveLock, should_apply_changes_for_rel(), slot_store_data(), ApplyExecutionData::targetRelInfo, and TTSOpsVirtual.

Referenced by apply_dispatch().

1825 {
1826  LogicalRepRelMapEntry *rel;
1827  LogicalRepTupleData oldtup;
1828  LogicalRepRelId relid;
1829  ApplyExecutionData *edata;
1830  EState *estate;
1831  TupleTableSlot *remoteslot;
1832  MemoryContext oldctx;
1833 
1835  return;
1836 
1838 
1839  relid = logicalrep_read_delete(s, &oldtup);
1840  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1841  if (!should_apply_changes_for_rel(rel))
1842  {
1843  /*
1844  * The relation can't become interesting in the middle of the
1845  * transaction so it's safe to unlock it.
1846  */
1849  return;
1850  }
1851 
1852  /* Set relation for error callback */
1854 
1855  /* Check if we can do the delete. */
1857 
1858  /* Initialize the executor state. */
1859  edata = create_edata_for_relation(rel);
1860  estate = edata->estate;
1861  remoteslot = ExecInitExtraTupleSlot(estate,
1862  RelationGetDescr(rel->localrel),
1863  &TTSOpsVirtual);
1864 
1865  /* Build the search tuple. */
1867  slot_store_data(remoteslot, rel, &oldtup);
1868  MemoryContextSwitchTo(oldctx);
1869 
1870  /* For a partitioned table, apply delete to correct partition. */
1871  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1873  remoteslot, NULL, CMD_DELETE);
1874  else
1876  remoteslot);
1877 
1878  finish_edata(edata);
1879 
1880  /* Reset relation for error callback */
1882 
1884 
1886 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:352
static void apply_handle_tuple_routing(ApplyExecutionData *edata, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, CmdType operation)
Definition: worker.c:1975
static ApplyExecutionData * create_edata_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:447
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1831
LogicalRepRelId logicalrep_read_delete(StringInfo in, LogicalRepTupleData *oldtup)
Definition: proto.c:548
#define RelationGetDescr(relation)
Definition: rel.h:503
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:433
Form_pg_class rd_rel
Definition: rel.h:109
static ApplyErrorCallbackArg apply_error_callback_arg
Definition: worker.c:230
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * targetRelInfo
Definition: worker.c:211
#define RowExclusiveLock
Definition: lockdefs.h:38
EState * estate
Definition: worker.c:208
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:409
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:258
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:1624
static void begin_replication_step(void)
Definition: worker.c:370
static void apply_handle_delete_internal(ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot)
Definition: worker.c:1894
LogicalRepRelMapEntry * rel
Definition: worker.c:222
static void end_replication_step(void)
Definition: worker.c:393
static void finish_edata(ApplyExecutionData *edata)
Definition: worker.c:500
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
static void slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:589
uint32 LogicalRepRelId
Definition: logicalproto.h:95

◆ apply_handle_delete_internal()

static void apply_handle_delete_internal ( ApplyExecutionData edata,
ResultRelInfo relinfo,
TupleTableSlot remoteslot 
)
static

Definition at line 1894 of file worker.c.

References DEBUG1, elog, ApplyExecutionData::estate, EvalPlanQualEnd(), EvalPlanQualInit(), EvalPlanQualSetSlot, ExecCloseIndices(), ExecOpenIndices(), ExecSimpleRelationDelete(), FindReplTupleInLocalRel(), NIL, RelationGetRelationName, LogicalRepRelMapEntry::remoterel, ResultRelInfo::ri_RelationDesc, and ApplyExecutionData::targetRel.

Referenced by apply_handle_delete(), and apply_handle_tuple_routing().

1897 {
1898  EState *estate = edata->estate;
1899  Relation localrel = relinfo->ri_RelationDesc;
1900  LogicalRepRelation *remoterel = &edata->targetRel->remoterel;
1901  EPQState epqstate;
1902  TupleTableSlot *localslot;
1903  bool found;
1904 
1905  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
1906  ExecOpenIndices(relinfo, false);
1907 
1908  found = FindReplTupleInLocalRel(estate, localrel, remoterel,
1909  remoteslot, &localslot);
1910 
1911  /* If found delete it. */
1912  if (found)
1913  {
1914  EvalPlanQualSetSlot(&epqstate, localslot);
1915 
1916  /* Do the actual delete. */
1917  ExecSimpleRelationDelete(relinfo, estate, &epqstate, localslot);
1918  }
1919  else
1920  {
1921  /*
1922  * The tuple to be deleted could not be found. Do nothing except for
1923  * emitting a log message.
1924  *
1925  * XXX should this be promoted to ereport(LOG) perhaps?
1926  */
1927  elog(DEBUG1,
1928  "logical replication did not find row to be deleted "
1929  "in replication target relation \"%s\"",
1930  RelationGetRelationName(localrel));
1931  }
1932 
1933  /* Cleanup. */
1934  ExecCloseIndices(relinfo);
1935  EvalPlanQualEnd(&epqstate);
1936 }
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:411
#define DEBUG1
Definition: elog.h:25
LogicalRepRelMapEntry * targetRel
Definition: worker.c:210
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2834
LogicalRepRelation remoterel
EState * estate
Definition: worker.c:208
#define RelationGetRelationName(relation)
Definition: rel.h:511
void EvalPlanQualInit(EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2413
void ExecSimpleRelationDelete(ResultRelInfo *resultRelInfo, EState *estate, EPQState *epqstate, TupleTableSlot *searchslot)
static bool FindReplTupleInLocalRel(EState *estate, Relation localrel, LogicalRepRelation *remoterel, TupleTableSlot *remoteslot, TupleTableSlot **localslot)
Definition: worker.c:1946
#define elog(elevel,...)
Definition: elog.h:232
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:231
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:227

◆ apply_handle_insert()

static void apply_handle_insert ( StringInfo  s)
static

Definition at line 1535 of file worker.c.

References apply_handle_insert_internal(), apply_handle_tuple_routing(), begin_replication_step(), CMD_INSERT, create_edata_for_relation(), end_replication_step(), ApplyExecutionData::estate, ExecInitExtraTupleSlot(), finish_edata(), GetPerTupleMemoryContext, handle_streamed_transaction(), LogicalRepRelMapEntry::localrel, LOGICAL_REP_MSG_INSERT, logicalrep_read_insert(), logicalrep_rel_close(), logicalrep_rel_open(), MemoryContextSwitchTo(), NoLock, RelationData::rd_rel, ApplyErrorCallbackArg::rel, RelationGetDescr, RowExclusiveLock, should_apply_changes_for_rel(), slot_fill_defaults(), slot_store_data(), ApplyExecutionData::targetRelInfo, and TTSOpsVirtual.

Referenced by apply_dispatch().

1536 {
1537  LogicalRepRelMapEntry *rel;
1538  LogicalRepTupleData newtup;
1539  LogicalRepRelId relid;
1540  ApplyExecutionData *edata;
1541  EState *estate;
1542  TupleTableSlot *remoteslot;
1543  MemoryContext oldctx;
1544 
1546  return;
1547 
1549 
1550  relid = logicalrep_read_insert(s, &newtup);
1551  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1552  if (!should_apply_changes_for_rel(rel))
1553  {
1554  /*
1555  * The relation can't become interesting in the middle of the
1556  * transaction so it's safe to unlock it.
1557  */
1560  return;
1561  }
1562 
1563  /* Set relation for error callback */
1565 
1566  /* Initialize the executor state. */
1567  edata = create_edata_for_relation(rel);
1568  estate = edata->estate;
1569  remoteslot = ExecInitExtraTupleSlot(estate,
1570  RelationGetDescr(rel->localrel),
1571  &TTSOpsVirtual);
1572 
1573  /* Process and store remote tuple in the slot */
1575  slot_store_data(remoteslot, rel, &newtup);
1576  slot_fill_defaults(rel, estate, remoteslot);
1577  MemoryContextSwitchTo(oldctx);
1578 
1579  /* For a partitioned table, insert the tuple into a partition. */
1580  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1582  remoteslot, NULL, CMD_INSERT);
1583  else
1585  remoteslot);
1586 
1587  finish_edata(edata);
1588 
1589  /* Reset relation for error callback */
1591 
1593 
1595 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:352
static void apply_handle_tuple_routing(ApplyExecutionData *edata, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, CmdType operation)
Definition: worker.c:1975
static ApplyExecutionData * create_edata_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:447
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1831
#define RelationGetDescr(relation)
Definition: rel.h:503
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:433
Form_pg_class rd_rel
Definition: rel.h:109
LogicalRepRelId logicalrep_read_insert(StringInfo in, LogicalRepTupleData *newtup)
Definition: proto.c:422
static void slot_fill_defaults(LogicalRepRelMapEntry *rel, EState *estate, TupleTableSlot *slot)
Definition: worker.c:531
static ApplyErrorCallbackArg apply_error_callback_arg
Definition: worker.c:230
static void apply_handle_insert_internal(ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot)
Definition: worker.c:1603
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * targetRelInfo
Definition: worker.c:211
#define RowExclusiveLock
Definition: lockdefs.h:38
EState * estate
Definition: worker.c:208
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:409
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:258
static void begin_replication_step(void)
Definition: worker.c:370
LogicalRepRelMapEntry * rel
Definition: worker.c:222
static void end_replication_step(void)
Definition: worker.c:393
static void finish_edata(ApplyExecutionData *edata)
Definition: worker.c:500
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
static void slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:589
uint32 LogicalRepRelId
Definition: logicalproto.h:95

◆ apply_handle_insert_internal()

static void apply_handle_insert_internal ( ApplyExecutionData edata,
ResultRelInfo relinfo,
TupleTableSlot remoteslot 
)
static

Definition at line 1603 of file worker.c.

References ApplyExecutionData::estate, ExecCloseIndices(), ExecOpenIndices(), and ExecSimpleRelationInsert().

Referenced by apply_handle_insert(), and apply_handle_tuple_routing().

1606 {
1607  EState *estate = edata->estate;
1608 
1609  /* We must open indexes here. */
1610  ExecOpenIndices(relinfo, false);
1611 
1612  /* Do the insert. */
1613  ExecSimpleRelationInsert(relinfo, estate, remoteslot);
1614 
1615  /* Cleanup. */
1616  ExecCloseIndices(relinfo);
1617 }
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
EState * estate
Definition: worker.c:208
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:231
void ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo, EState *estate, TupleTableSlot *slot)

◆ apply_handle_origin()

static void apply_handle_origin ( StringInfo  s)
static

Definition at line 1080 of file worker.c.

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

Referenced by apply_dispatch().

1081 {
1082  /*
1083  * ORIGIN message can only come inside streaming transaction or inside
1084  * remote transaction and before any actual writes.
1085  */
1086  if (!in_streamed_transaction &&
1089  ereport(ERROR,
1090  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1091  errmsg_internal("ORIGIN message sent out of order")));
1092 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:250
static bool in_streamed_transaction
Definition: worker.c:254
static bool am_tablesync_worker(void)
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
bool IsTransactionState(void)
Definition: xact.c:371

◆ apply_handle_prepare()

static void apply_handle_prepare ( StringInfo  s)
static

Definition at line 887 of file worker.c.

References apply_handle_prepare_internal(), begin_replication_step(), CommitTransactionCommand(), LogicalRepPreparedTxnData::end_lsn, end_replication_step(), ereport, errcode(), errmsg_internal(), ERROR, in_remote_transaction, logicalrep_read_prepare(), LSN_FORMAT_ARGS, pgstat_report_activity(), pgstat_report_stat(), LogicalRepPreparedTxnData::prepare_lsn, process_syncing_tables(), remote_final_lsn, reset_apply_error_context_info(), STATE_IDLE, and store_flush_position().

Referenced by apply_dispatch().

888 {
889  LogicalRepPreparedTxnData prepare_data;
890 
891  logicalrep_read_prepare(s, &prepare_data);
892 
893  if (prepare_data.prepare_lsn != remote_final_lsn)
894  ereport(ERROR,
895  (errcode(ERRCODE_PROTOCOL_VIOLATION),
896  errmsg_internal("incorrect prepare LSN %X/%X in prepare message (expected %X/%X)",
897  LSN_FORMAT_ARGS(prepare_data.prepare_lsn),
899 
900  /*
901  * Unlike commit, here, we always prepare the transaction even though no
902  * change has happened in this transaction. It is done this way because at
903  * commit prepared time, we won't know whether we have skipped preparing a
904  * transaction because of no change.
905  *
906  * XXX, We can optimize such that at commit prepared time, we first check
907  * whether we have prepared the transaction or not but that doesn't seem
908  * worthwhile because such cases shouldn't be common.
909  */
911 
912  apply_handle_prepare_internal(&prepare_data);
913 
916  pgstat_report_stat(false);
917 
918  store_flush_position(prepare_data.end_lsn);
919 
920  in_remote_transaction = false;
921 
922  /* Process any tables that are being synchronized in parallel. */
923  process_syncing_tables(prepare_data.end_lsn);
924 
927 }
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2478
static XLogRecPtr remote_final_lsn
Definition: worker.c:251
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
void CommitTransactionCommand(void)
Definition: xact.c:2949
int errcode(int sqlerrcode)
Definition: elog.c:698
static void reset_apply_error_context_info(void)
Definition: worker.c:3613
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:858
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:250
void logicalrep_read_prepare(StringInfo in, LogicalRepPreparedTxnData *prepare_data)
Definition: proto.c:225
static void begin_replication_step(void)
Definition: worker.c:370
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static void end_replication_step(void)
Definition: worker.c:393
void pgstat_report_activity(BackendState state, const char *cmd_str)
static void apply_handle_prepare_internal(LogicalRepPreparedTxnData *prepare_data)
Definition: worker.c:853

◆ apply_handle_prepare_internal()

static void apply_handle_prepare_internal ( LogicalRepPreparedTxnData prepare_data)
static

Definition at line 853 of file worker.c.

References BeginTransactionBlock(), CommitTransactionCommand(), LogicalRepPreparedTxnData::end_lsn, GIDSIZE, Subscription::oid, LogicalRepPreparedTxnData::prepare_time, PrepareTransactionBlock(), replorigin_session_origin_lsn, replorigin_session_origin_timestamp, TwoPhaseTransactionGid(), and LogicalRepPreparedTxnData::xid.

Referenced by apply_handle_prepare(), and apply_handle_stream_prepare().

854 {
855  char gid[GIDSIZE];
856 
857  /*
858  * Compute unique GID for two_phase transactions. We don't use GID of
859  * prepared transaction sent by server as that can lead to deadlock when
860  * we have multiple subscriptions from same node point to publications on
861  * the same node. See comments atop worker.c
862  */
864  gid, sizeof(gid));
865 
866  /*
867  * BeginTransactionBlock is necessary to balance the EndTransactionBlock
868  * called within the PrepareTransactionBlock below.
869  */
871  CommitTransactionCommand(); /* Completes the preceding Begin command. */
872 
873  /*
874  * Update origin state so we can restart streaming from correct position
875  * in case of crash.
876  */
877  replorigin_session_origin_lsn = prepare_data->end_lsn;
879 
881 }
Subscription * MySubscription
Definition: worker.c:247
void CommitTransactionCommand(void)
Definition: xact.c:2949
bool PrepareTransactionBlock(const char *gid)
Definition: xact.c:3715
#define GIDSIZE
Definition: xact.h:31
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:155
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:156
void BeginTransactionBlock(void)
Definition: xact.c:3647
static void TwoPhaseTransactionGid(Oid subid, TransactionId xid, char *gid, int szgid)
Definition: worker.c:3315

◆ apply_handle_relation()

static void apply_handle_relation ( StringInfo  s)
static

Definition at line 1485 of file worker.c.

References handle_streamed_transaction(), LOGICAL_REP_MSG_RELATION, logicalrep_read_rel(), and logicalrep_relmap_update().

Referenced by apply_dispatch().

1486 {
1487  LogicalRepRelation *rel;
1488 
1490  return;
1491 
1492  rel = logicalrep_read_rel(s);
1494 }
LogicalRepRelation * logicalrep_read_rel(StringInfo in)
Definition: proto.c:683
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:157
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:409

◆ apply_handle_rollback_prepared()

static void apply_handle_rollback_prepared ( StringInfo  s)
static

Definition at line 974 of file worker.c.

References begin_replication_step(), CommitTransactionCommand(), end_replication_step(), FinishPreparedTransaction(), GIDSIZE, in_remote_transaction, logicalrep_read_rollback_prepared(), LookupGXact(), Subscription::oid, pgstat_report_activity(), pgstat_report_stat(), LogicalRepRollbackPreparedTxnData::prepare_end_lsn, LogicalRepRollbackPreparedTxnData::prepare_time, process_syncing_tables(), replorigin_session_origin_lsn, replorigin_session_origin_timestamp, reset_apply_error_context_info(), LogicalRepRollbackPreparedTxnData::rollback_end_lsn, LogicalRepRollbackPreparedTxnData::rollback_time, set_apply_error_context_xact(), STATE_IDLE, store_flush_position(), TwoPhaseTransactionGid(), and LogicalRepRollbackPreparedTxnData::xid.

Referenced by apply_dispatch().

975 {
976  LogicalRepRollbackPreparedTxnData rollback_data;
977  char gid[GIDSIZE];
978 
979  logicalrep_read_rollback_prepared(s, &rollback_data);
980  set_apply_error_context_xact(rollback_data.xid, rollback_data.rollback_time);
981 
982  /* Compute GID for two_phase transactions. */
984  gid, sizeof(gid));
985 
986  /*
987  * It is possible that we haven't received prepare because it occurred
988  * before walsender reached a consistent point or the two_phase was still
989  * not enabled by that time, so in such cases, we need to skip rollback
990  * prepared.
991  */
992  if (LookupGXact(gid, rollback_data.prepare_end_lsn,
993  rollback_data.prepare_time))
994  {
995  /*
996  * Update origin state so we can restart streaming from correct
997  * position in case of crash.
998  */
1001 
1002  /* There is no transaction when ABORT/ROLLBACK PREPARED is called */
1004  FinishPreparedTransaction(gid, false);
1007  }
1008 
1009  pgstat_report_stat(false);
1010 
1011  store_flush_position(rollback_data.rollback_end_lsn);
1012  in_remote_transaction = false;
1013 
1014  /* Process any tables that are being synchronized in parallel. */
1016 
1019 }
Subscription * MySubscription
Definition: worker.c:247
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2478
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
void CommitTransactionCommand(void)
Definition: xact.c:2949
bool LookupGXact(const char *gid, XLogRecPtr prepare_end_lsn, TimestampTz origin_prepare_timestamp)
Definition: twophase.c:2482
static void reset_apply_error_context_info(void)
Definition: worker.c:3613
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:858
bool in_remote_transaction
Definition: worker.c:250
#define GIDSIZE
Definition: xact.h:31
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:155
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:156
static void begin_replication_step(void)
Definition: worker.c:370
void FinishPreparedTransaction(const char *gid, bool isCommit)
Definition: twophase.c:1409
static void end_replication_step(void)
Definition: worker.c:393
void logicalrep_read_rollback_prepared(StringInfo in, LogicalRepRollbackPreparedTxnData *rollback_data)
Definition: proto.c:322
void pgstat_report_activity(BackendState state, const char *cmd_str)
static void TwoPhaseTransactionGid(Oid subid, TransactionId xid, char *gid, int szgid)
Definition: worker.c:3315
static void set_apply_error_context_xact(TransactionId xid, TimestampTz ts)
Definition: worker.c:3605

◆ apply_handle_stream_abort()

static void apply_handle_stream_abort ( StringInfo  s)
static

Definition at line 1198 of file worker.c.

References begin_replication_step(), BufFileClose(), BufFileOpenFileSet(), BufFileTruncateFileSet(), changes_filename(), cleanup_subxact_info(), CommitTransactionCommand(), end_replication_step(), ereport, errcode(), errmsg_internal(), ERROR, fd(), SubXactInfo::fileno, i, in_streamed_transaction, logicalrep_read_stream_abort(), MAXPGPATH, MyLogicalRepWorker, ApplySubXactData::nsubxacts, SubXactInfo::offset, reset_apply_error_context_info(), set_apply_error_context_xact(), stream_cleanup_files(), LogicalRepWorker::stream_fileset, LogicalRepWorker::subid, subxact_info_read(), subxact_info_write(), ApplySubXactData::subxacts, and SubXactInfo::xid.

Referenced by apply_dispatch().

1199 {
1200  TransactionId xid;
1201  TransactionId subxid;
1202 
1204  ereport(ERROR,
1205  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1206  errmsg_internal("STREAM ABORT message without STREAM STOP")));
1207 
1208  logicalrep_read_stream_abort(s, &xid, &subxid);
1209 
1210  /*
1211  * If the two XIDs are the same, it's in fact abort of toplevel xact, so
1212  * just delete the files with serialized info.
1213  */
1214  if (xid == subxid)
1215  {
1218  }
1219  else
1220  {
1221  /*
1222  * OK, so it's a subxact. We need to read the subxact file for the
1223  * toplevel transaction, determine the offset tracked for the subxact,
1224  * and truncate the file with changes. We also remove the subxacts
1225  * with higher offsets (or rather higher XIDs).
1226  *
1227  * We intentionally scan the array from the tail, because we're likely
1228  * aborting a change for the most recent subtransactions.
1229  *
1230  * We can't use the binary search here as subxact XIDs won't
1231  * necessarily arrive in sorted order, consider the case where we have
1232  * released the savepoint for multiple subtransactions and then
1233  * performed rollback to savepoint for one of the earlier
1234  * sub-transaction.
1235  */
1236  int64 i;
1237  int64 subidx;
1238  BufFile *fd;
1239  bool found = false;
1240  char path[MAXPGPATH];
1241 
1242  set_apply_error_context_xact(subxid, 0);
1243 
1244  subidx = -1;
1247 
1248  for (i = subxact_data.nsubxacts; i > 0; i--)
1249  {
1250  if (subxact_data.subxacts[i - 1].xid == subxid)
1251  {
1252  subidx = (i - 1);
1253  found = true;
1254  break;
1255  }
1256  }
1257 
1258  /*
1259  * If it's an empty sub-transaction then we will not find the subxid
1260  * here so just cleanup the subxact info and return.
1261  */
1262  if (!found)
1263  {
1264  /* Cleanup the subxact info */
1269  return;
1270  }
1271 
1272  /* open the changes file */
1275  O_RDWR, false);
1276 
1277  /* OK, truncate the file at the right offset */
1279  subxact_data.subxacts[subidx].offset);
1280  BufFileClose(fd);
1281 
1282  /* discard the subxacts added later */
1283  subxact_data.nsubxacts = subidx;
1284 
1285  /* write the updated subxact list */
1287 
1290  }
1291 
1293 }
static void subxact_info_read(Oid subid, TransactionId xid)
Definition: worker.c:3015
int fileno
Definition: worker.c:264
uint32 TransactionId
Definition: c.h:587
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:3160
void CommitTransactionCommand(void)
Definition: xact.c:2949
void BufFileTruncateFileSet(BufFile *file, int fileno, off_t offset)
Definition: buffile.c:873
BufFile * BufFileOpenFileSet(FileSet *fileset, const char *name, int mode, bool missing_ok)
Definition: buffile.c:286
int errcode(int sqlerrcode)
Definition: elog.c:698
static void reset_apply_error_context_info(void)
Definition: worker.c:3613
static int fd(const char *x, int i)
Definition: preproc-init.c:105
uint32 nsubxacts
Definition: worker.c:271
void BufFileClose(BufFile *file)
Definition: buffile.c:407
FileSet * stream_fileset
SubXactInfo * subxacts
Definition: worker.c:274
static void stream_cleanup_files(Oid subid, TransactionId xid)
Definition: worker.c:3174
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
#define MAXPGPATH
static bool in_streamed_transaction
Definition: worker.c:254
TransactionId xid
Definition: worker.c:263
static void begin_replication_step(void)
Definition: worker.c:370
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static void end_replication_step(void)
Definition: worker.c:393
off_t offset
Definition: worker.c:265
static void subxact_info_write(Oid subid, TransactionId xid)
Definition: worker.c:2966
static ApplySubXactData subxact_data
Definition: worker.c:277
int i
static void cleanup_subxact_info(void)
Definition: worker.c:3298
static void set_apply_error_context_xact(TransactionId xid, TimestampTz ts)
Definition: worker.c:3605
void logicalrep_read_stream_abort(StringInfo in, TransactionId *xid, TransactionId *subxid)
Definition: proto.c:1151

◆ apply_handle_stream_commit()

static void apply_handle_stream_commit ( StringInfo  s)
static

Definition at line 1416 of file worker.c.

References apply_handle_commit_internal(), apply_spooled_messages(), LogicalRepCommitData::commit_lsn, LogicalRepCommitData::committime, DEBUG1, elog, LogicalRepCommitData::end_lsn, ereport, errcode(), errmsg_internal(), ERROR, in_streamed_transaction, logicalrep_read_stream_commit(), MyLogicalRepWorker, pgstat_report_activity(), process_syncing_tables(), reset_apply_error_context_info(), set_apply_error_context_xact(), STATE_IDLE, stream_cleanup_files(), and LogicalRepWorker::subid.

Referenced by apply_dispatch().

1417 {
1418  TransactionId xid;
1419  LogicalRepCommitData commit_data;
1420 
1422  ereport(ERROR,
1423  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1424  errmsg_internal("STREAM COMMIT message without STREAM STOP")));
1425 
1426  xid = logicalrep_read_stream_commit(s, &commit_data);
1427  set_apply_error_context_xact(xid, commit_data.committime);
1428 
1429  elog(DEBUG1, "received commit for streamed transaction %u", xid);
1430 
1431  apply_spooled_messages(xid, commit_data.commit_lsn);
1432 
1433  apply_handle_commit_internal(&commit_data);
1434 
1435  /* unlink the files with serialized changes and subxact info */
1437 
1438  /* Process any tables that are being synchronized in parallel. */
1439  process_syncing_tables(commit_data.end_lsn);
1440 
1442 
1444 }
#define DEBUG1
Definition: elog.h:25
uint32 TransactionId
Definition: c.h:587
TransactionId logicalrep_read_stream_commit(StringInfo in, LogicalRepCommitData *commit_data)
Definition: proto.c:1109
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
int errcode(int sqlerrcode)
Definition: elog.c:698
static void reset_apply_error_context_info(void)
Definition: worker.c:3613
static void stream_cleanup_files(Oid subid, TransactionId xid)
Definition: worker.c:3174
static void apply_spooled_messages(TransactionId xid, XLogRecPtr lsn)
Definition: worker.c:1299
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
static bool in_streamed_transaction
Definition: worker.c:254
static void apply_handle_commit_internal(LogicalRepCommitData *commit_data)
Definition: worker.c:1450
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
void pgstat_report_activity(BackendState state, const char *cmd_str)
#define elog(elevel,...)
Definition: elog.h:232
static void set_apply_error_context_xact(TransactionId xid, TimestampTz ts)
Definition: worker.c:3605
TimestampTz committime
Definition: logicalproto.h:132

◆ apply_handle_stream_prepare()

static void apply_handle_stream_prepare ( StringInfo  s)
static

Definition at line 1029 of file worker.c.

References am_tablesync_worker(), apply_handle_prepare_internal(), apply_spooled_messages(), CommitTransactionCommand(), DEBUG1, elog, LogicalRepPreparedTxnData::end_lsn, ereport, errcode(), errmsg_internal(), ERROR, in_remote_transaction, in_streamed_transaction, logicalrep_read_stream_prepare(), MyLogicalRepWorker, pgstat_report_activity(), pgstat_report_stat(), LogicalRepPreparedTxnData::prepare_lsn, LogicalRepPreparedTxnData::prepare_time, process_syncing_tables(), reset_apply_error_context_info(), set_apply_error_context_xact(), STATE_IDLE, store_flush_position(), stream_cleanup_files(), LogicalRepWorker::subid, and LogicalRepPreparedTxnData::xid.

Referenced by apply_dispatch().

1030 {
1031  LogicalRepPreparedTxnData prepare_data;
1032 
1034  ereport(ERROR,
1035  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1036  errmsg_internal("STREAM PREPARE message without STREAM STOP")));
1037 
1038  /* Tablesync should never receive prepare. */
1039  if (am_tablesync_worker())
1040  ereport(ERROR,
1041  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1042  errmsg_internal("tablesync worker received a STREAM PREPARE message")));
1043 
1044  logicalrep_read_stream_prepare(s, &prepare_data);
1045  set_apply_error_context_xact(prepare_data.xid, prepare_data.prepare_time);
1046 
1047  elog(DEBUG1, "received prepare for streamed transaction %u", prepare_data.xid);
1048 
1049  /* Replay all the spooled operations. */
1050  apply_spooled_messages(prepare_data.xid, prepare_data.prepare_lsn);
1051 
1052  /* Mark the transaction as prepared. */
1053  apply_handle_prepare_internal(&prepare_data);
1054 
1056 
1057  pgstat_report_stat(false);
1058 
1059  store_flush_position(prepare_data.end_lsn);
1060 
1061  in_remote_transaction = false;
1062 
1063  /* unlink the files with serialized changes and subxact info. */
1065 
1066  /* Process any tables that are being synchronized in parallel. */
1067  process_syncing_tables(prepare_data.end_lsn);
1068 
1070 
1072 }
#define DEBUG1
Definition: elog.h:25
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2478
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
void CommitTransactionCommand(void)
Definition: xact.c:2949
int errcode(int sqlerrcode)
Definition: elog.c:698
static void reset_apply_error_context_info(void)
Definition: worker.c:3613
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:858
static void stream_cleanup_files(Oid subid, TransactionId xid)
Definition: worker.c:3174
static void apply_spooled_messages(TransactionId xid, XLogRecPtr lsn)
Definition: worker.c:1299
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:250
static bool in_streamed_transaction
Definition: worker.c:254
static bool am_tablesync_worker(void)
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
void logicalrep_read_stream_prepare(StringInfo in, LogicalRepPreparedTxnData *prepare_data)
Definition: proto.c:362
void pgstat_report_activity(BackendState state, const char *cmd_str)
#define elog(elevel,...)
Definition: elog.h:232
static void set_apply_error_context_xact(TransactionId xid, TimestampTz ts)
Definition: worker.c:3605
static void apply_handle_prepare_internal(LogicalRepPreparedTxnData *prepare_data)
Definition: worker.c:853

◆ apply_handle_stream_start()

static void apply_handle_stream_start ( StringInfo  s)
static

Definition at line 1098 of file worker.c.

References begin_replication_step(), end_replication_step(), ereport, errcode(), errmsg_internal(), ERROR, FileSetInit(), in_streamed_transaction, logicalrep_read_stream_start(), MemoryContextSwitchTo(), MyLogicalRepWorker, palloc(), pgstat_report_activity(), set_apply_error_context_xact(), STATE_RUNNING, LogicalRepWorker::stream_fileset, stream_open_file(), stream_xid, LogicalRepWorker::subid, subxact_info_read(), and TransactionIdIsValid.

Referenced by apply_dispatch().

1099 {
1100  bool first_segment;
1101 
1103  ereport(ERROR,
1104  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1105  errmsg_internal("duplicate STREAM START message")));
1106 
1107  /*
1108  * Start a transaction on stream start, this transaction will be committed
1109  * on the stream stop unless it is a tablesync worker in which case it
1110  * will be committed after processing all the messages. We need the
1111  * transaction for handling the buffile, used for serializing the
1112  * streaming data and subxact info.
1113  */
1115 
1116  /* notify handle methods we're processing a remote transaction */
1117  in_streamed_transaction = true;
1118 
1119  /* extract XID of the top-level transaction */
1120  stream_xid = logicalrep_read_stream_start(s, &first_segment);
1121 
1123  ereport(ERROR,
1124  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1125  errmsg_internal("invalid transaction ID in streamed replication transaction")));
1126 
1128 
1129  /*
1130  * Initialize the worker's stream_fileset if we haven't yet. This will be
1131  * used for the entire duration of the worker so create it in a permanent
1132  * context. We create this on the very first streaming message from any
1133  * transaction and then use it for this and other streaming transactions.
1134  * Now, we could create a fileset at the start of the worker as well but
1135  * then we won't be sure that it will ever be used.
1136  */
1137  if (MyLogicalRepWorker->stream_fileset == NULL)
1138  {
1139  MemoryContext oldctx;
1140 
1142 
1145 
1146  MemoryContextSwitchTo(oldctx);
1147  }
1148 
1149  /* open the spool file for this transaction */
1151 
1152  /* if this is not the first segment, open existing subxact file */
1153  if (!first_segment)
1155 
1157 
1159 }
static void subxact_info_read(Oid subid, TransactionId xid)
Definition: worker.c:3015
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
void FileSetInit(FileSet *fileset)
Definition: fileset.c:54
FileSet * stream_fileset
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
static bool in_streamed_transaction
Definition: worker.c:254
MemoryContext ApplyContext
Definition: worker.c:240
static void begin_replication_step(void)
Definition: worker.c:370
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static void end_replication_step(void)
Definition: worker.c:393
TransactionId logicalrep_read_stream_start(StringInfo in, bool *first_segment)
Definition: proto.c:1059
void * palloc(Size size)
Definition: mcxt.c:1062
void pgstat_report_activity(BackendState state, const char *cmd_str)
static void stream_open_file(Oid subid, TransactionId xid, bool first)
Definition: worker.c:3201
static void set_apply_error_context_xact(TransactionId xid, TimestampTz ts)
Definition: worker.c:3605
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static TransactionId stream_xid
Definition: worker.c:256

◆ apply_handle_stream_stop()

static void apply_handle_stream_stop ( StringInfo  s)
static

Definition at line 1165 of file worker.c.

References Assert, CommitTransactionCommand(), ereport, errcode(), errmsg_internal(), ERROR, in_streamed_transaction, IsTransactionState(), MemoryContextReset(), MyLogicalRepWorker, pgstat_report_activity(), reset_apply_error_context_info(), STATE_IDLE, stream_close_file(), stream_xid, LogicalRepWorker::subid, and subxact_info_write().

Referenced by apply_dispatch().

1166 {
1168  ereport(ERROR,
1169  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1170  errmsg_internal("STREAM STOP message without STREAM START")));
1171 
1172  /*
1173  * Close the file with serialized changes, and serialize information about
1174  * subxacts for the toplevel transaction.
1175  */
1178 
1179  /* We must be in a valid transaction state */
1181 
1182  /* Commit the per-stream transaction */
1184 
1185  in_streamed_transaction = false;
1186 
1187  /* Reset per-stream context */
1189 
1192 }
static void stream_close_file(void)
Definition: worker.c:3250
void CommitTransactionCommand(void)
Definition: xact.c:2949
int errcode(int sqlerrcode)
Definition: elog.c:698
static void reset_apply_error_context_info(void)
Definition: worker.c:3613
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
static bool in_streamed_transaction
Definition: worker.c:254
#define ereport(elevel,...)
Definition: elog.h:157
static MemoryContext LogicalStreamingContext
Definition: worker.c:243
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define Assert(condition)
Definition: c.h:804
bool IsTransactionState(void)
Definition: xact.c:371
static void subxact_info_write(Oid subid, TransactionId xid)
Definition: worker.c:2966
void pgstat_report_activity(BackendState state, const char *cmd_str)
static TransactionId stream_xid
Definition: worker.c:256

◆ apply_handle_truncate()

static void apply_handle_truncate ( StringInfo  s)
static

Definition at line 2199 of file worker.c.

References AccessExclusiveLock, begin_replication_step(), DROP_RESTRICT, end_replication_step(), ExecuteTruncateGuts(), find_all_inheritors(), handle_streamed_transaction(), lappend(), lappend_oid(), lfirst, lfirst_oid, list_member_oid(), LogicalRepRelMapEntry::localrel, LogicalRepRelMapEntry::localreloid, LOGICAL_REP_MSG_TRUNCATE, logicalrep_read_truncate(), logicalrep_rel_close(), logicalrep_rel_open(), NIL, NoLock, RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationIsLogicallyLogged, should_apply_changes_for_rel(), table_close(), and table_open().

Referenced by apply_dispatch().

2200 {
2201  bool cascade = false;
2202  bool restart_seqs = false;
2203  List *remote_relids = NIL;
2204  List *remote_rels = NIL;
2205  List *rels = NIL;
2206  List *part_rels = NIL;
2207  List *relids = NIL;
2208  List *relids_logged = NIL;
2209  ListCell *lc;
2210  LOCKMODE lockmode = AccessExclusiveLock;
2211 
2213  return;
2214 
2216 
2217  remote_relids = logicalrep_read_truncate(s, &cascade, &restart_seqs);
2218 
2219  foreach(lc, remote_relids)
2220  {
2221  LogicalRepRelId relid = lfirst_oid(lc);
2222  LogicalRepRelMapEntry *rel;
2223 
2224  rel = logicalrep_rel_open(relid, lockmode);
2225  if (!should_apply_changes_for_rel(rel))
2226  {
2227  /*
2228  * The relation can't become interesting in the middle of the
2229  * transaction so it's safe to unlock it.
2230  */
2231  logicalrep_rel_close(rel, lockmode);
2232  continue;
2233  }
2234 
2235  remote_rels = lappend(remote_rels, rel);
2236  rels = lappend(rels, rel->localrel);
2237  relids = lappend_oid(relids, rel->localreloid);
2239  relids_logged = lappend_oid(relids_logged, rel->localreloid);
2240 
2241  /*
2242  * Truncate partitions if we got a message to truncate a partitioned
2243  * table.
2244  */
2245  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2246  {
2247  ListCell *child;
2248  List *children = find_all_inheritors(rel->localreloid,
2249  lockmode,
2250  NULL);
2251 
2252  foreach(child, children)
2253  {
2254  Oid childrelid = lfirst_oid(child);
2255  Relation childrel;
2256 
2257  if (list_member_oid(relids, childrelid))
2258  continue;
2259 
2260  /* find_all_inheritors already got lock */
2261  childrel = table_open(childrelid, NoLock);
2262 
2263  /*
2264  * Ignore temp tables of other backends. See similar code in
2265  * ExecuteTruncate().
2266  */
2267  if (RELATION_IS_OTHER_TEMP(childrel))
2268  {
2269  table_close(childrel, lockmode);
2270  continue;
2271  }
2272 
2273  rels = lappend(rels, childrel);
2274  part_rels = lappend(part_rels, childrel);
2275  relids = lappend_oid(relids, childrelid);
2276  /* Log this relation only if needed for logical decoding */
2277  if (RelationIsLogicallyLogged(childrel))
2278  relids_logged = lappend_oid(relids_logged, childrelid);
2279  }
2280  }
2281  }
2282 
2283  /*
2284  * Even if we used CASCADE on the upstream primary we explicitly default
2285  * to replaying changes without further cascading. This might be later
2286  * changeable with a user specified option.
2287  */
2288  ExecuteTruncateGuts(rels,
2289  relids,
2290  relids_logged,
2291  DROP_RESTRICT,
2292  restart_seqs);
2293  foreach(lc, remote_rels)
2294  {
2295  LogicalRepRelMapEntry *rel = lfirst(lc);
2296 
2298  }
2299  foreach(lc, part_rels)
2300  {
2301  Relation rel = lfirst(lc);
2302 
2303  table_close(rel, NoLock);
2304  }
2305 
2307 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:352
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int LOCKMODE
Definition: lockdefs.h:26
List * logicalrep_read_truncate(StringInfo in, bool *cascade, bool *restart_seqs)
Definition: proto.c:602
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:433
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:674
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
void ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs)
Definition: tablecmds.c:1735
#define NoLock
Definition: lockdefs.h:34
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:409
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:258
List * lappend(List *list, void *datum)
Definition: list.c:336
static void begin_replication_step(void)
Definition: worker.c:370
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
#define lfirst(lc)
Definition: pg_list.h:169
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:631
static void end_replication_step(void)
Definition: worker.c:393
#define AccessExclusiveLock
Definition: lockdefs.h:45
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:256
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
uint32 LogicalRepRelId
Definition: logicalproto.h:95
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ apply_handle_tuple_routing()

static void apply_handle_tuple_routing ( ApplyExecutionData edata,
TupleTableSlot remoteslot,
LogicalRepTupleData newtup,
CmdType  operation 
)
static

Definition at line 1975 of file worker.c.

References apply_handle_delete_internal(), apply_handle_insert_internal(), Assert, TupleConversionMap::attrMap, CMD_DELETE, CMD_INSERT, CMD_UPDATE, convert_tuples_by_name(), DEBUG1, elog, ERROR, EState::es_tupleTable, ApplyExecutionData::estate, EvalPlanQualEnd(), EvalPlanQualInit(), EvalPlanQualSetSlot, ExecCloseIndices(), ExecCopySlot(), ExecFindPartition(), ExecOpenIndices(), ExecPartitionCheck(), ExecSetupPartitionTupleRouting(), ExecSimpleRelationUpdate(), execute_attr_map_slot(), FindReplTupleInLocalRel(), GetPerTupleMemoryContext, logicalrep_partition_open(), makeNode, MemoryContextSwitchTo(), ApplyExecutionData::mtstate, NIL, ModifyTableState::operation, PlanState::plan, ApplyExecutionData::proute, ModifyTableState::ps, RelationData::rd_rel, RelationGetDescr, RelationGetRelationName, LogicalRepRelMapEntry::remoterel, ModifyTableState::resultRelInfo, ResultRelInfo::ri_PartitionTupleSlot, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootToPartitionMap, slot_getallattrs(), slot_modify_data(), PlanState::state, table_slot_create(), ApplyExecutionData::targetRel, and ApplyExecutionData::targetRelInfo.

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

1979 {
1980  EState *estate = edata->estate;
1981  LogicalRepRelMapEntry *relmapentry = edata->targetRel;
1982  ResultRelInfo *relinfo = edata->targetRelInfo;
1983  Relation parentrel = relinfo->ri_RelationDesc;
1984  ModifyTableState *mtstate;
1985  PartitionTupleRouting *proute;
1986  ResultRelInfo *partrelinfo;
1987  Relation partrel;
1988  TupleTableSlot *remoteslot_part;
1989  TupleConversionMap *map;
1990  MemoryContext oldctx;
1991 
1992  /* ModifyTableState is needed for ExecFindPartition(). */
1993  edata->mtstate = mtstate = makeNode(ModifyTableState);
1994  mtstate->ps.plan = NULL;
1995  mtstate->ps.state = estate;
1996  mtstate->operation = operation;
1997  mtstate->resultRelInfo = relinfo;
1998 
1999  /* ... as is PartitionTupleRouting. */
2000  edata->proute = proute = ExecSetupPartitionTupleRouting(estate, parentrel);
2001 
2002  /*
2003  * Find the partition to which the "search tuple" belongs.
2004  */
2005  Assert(remoteslot != NULL);
2007  partrelinfo = ExecFindPartition(mtstate, relinfo, proute,
2008  remoteslot, estate);
2009  Assert(partrelinfo != NULL);
2010  partrel = partrelinfo->ri_RelationDesc;
2011 
2012  /*
2013  * To perform any of the operations below, the tuple must match the
2014  * partition's rowtype. Convert if needed or just copy, using a dedicated
2015  * slot to store the tuple in any case.
2016  */
2017  remoteslot_part = partrelinfo->ri_PartitionTupleSlot;
2018  if (remoteslot_part == NULL)
2019  remoteslot_part = table_slot_create(partrel, &estate->es_tupleTable);
2020  map = partrelinfo->ri_RootToPartitionMap;
2021  if (map != NULL)
2022  remoteslot_part = execute_attr_map_slot(map->attrMap, remoteslot,
2023  remoteslot_part);
2024  else
2025  {
2026  remoteslot_part = ExecCopySlot(remoteslot_part, remoteslot);
2027  slot_getallattrs(remoteslot_part);
2028  }
2029  MemoryContextSwitchTo(oldctx);
2030 
2031  switch (operation)
2032  {
2033  case CMD_INSERT:
2034  apply_handle_insert_internal(edata, partrelinfo,
2035  remoteslot_part);
2036  break;
2037 
2038  case CMD_DELETE:
2039  apply_handle_delete_internal(edata, partrelinfo,
2040  remoteslot_part);
2041  break;
2042 
2043  case CMD_UPDATE:
2044 
2045  /*
2046  * For UPDATE, depending on whether or not the updated tuple
2047  * satisfies the partition's constraint, perform a simple UPDATE
2048  * of the partition or move the updated tuple into a different
2049  * suitable partition.
2050  */
2051  {
2052  AttrMap *attrmap = map ? map->attrMap : NULL;
2053  LogicalRepRelMapEntry *part_entry;
2054  TupleTableSlot *localslot;
2055  ResultRelInfo *partrelinfo_new;
2056  bool found;
2057 
2058  part_entry = logicalrep_partition_open(relmapentry, partrel,
2059  attrmap);
2060 
2061  /* Get the matching local tuple from the partition. */
2062  found = FindReplTupleInLocalRel(estate, partrel,
2063  &part_entry->remoterel,
2064  remoteslot_part, &localslot);
2065  if (!found)
2066  {
2067  /*
2068  * The tuple to be updated could not be found. Do nothing
2069  * except for emitting a log message.
2070  *
2071  * XXX should this be promoted to ereport(LOG) perhaps?
2072  */
2073  elog(DEBUG1,
2074  "logical replication did not find row to be updated "
2075  "in replication target relation's partition \"%s\"",
2076  RelationGetRelationName(partrel));
2077  return;
2078  }
2079 
2080  /*
2081  * Apply the update to the local tuple, putting the result in
2082  * remoteslot_part.
2083  */
2085  slot_modify_data(remoteslot_part, localslot, part_entry,
2086  newtup);
2087  MemoryContextSwitchTo(oldctx);
2088 
2089  /*
2090  * Does the updated tuple still satisfy the current
2091  * partition's constraint?
2092  */
2093  if (!partrel->rd_rel->relispartition ||
2094  ExecPartitionCheck(partrelinfo, remoteslot_part, estate,
2095  false))
2096  {
2097  /*
2098  * Yes, so simply UPDATE the partition. We don't call
2099  * apply_handle_update_internal() here, which would
2100  * normally do the following work, to avoid repeating some
2101  * work already done above to find the local tuple in the
2102  * partition.
2103  */
2104  EPQState epqstate;
2105 
2106  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
2107  ExecOpenIndices(partrelinfo, false);
2108 
2109  EvalPlanQualSetSlot(&epqstate, remoteslot_part);
2110  ExecSimpleRelationUpdate(partrelinfo, estate, &epqstate,
2111  localslot, remoteslot_part);
2112  ExecCloseIndices(partrelinfo);
2113  EvalPlanQualEnd(&epqstate);
2114  }
2115  else
2116  {
2117  /* Move the tuple into the new partition. */
2118 
2119  /*
2120  * New partition will be found using tuple routing, which
2121  * can only occur via the parent table. We might need to
2122  * convert the tuple to the parent's rowtype. Note that
2123  * this is the tuple found in the partition, not the
2124  * original search tuple received by this function.
2125  */
2126  if (map)
2127  {
2128  TupleConversionMap *PartitionToRootMap =
2130  RelationGetDescr(parentrel));
2131 
2132  remoteslot =
2133  execute_attr_map_slot(PartitionToRootMap->attrMap,
2134  remoteslot_part, remoteslot);
2135  }
2136  else
2137  {
2138  remoteslot = ExecCopySlot(remoteslot, remoteslot_part);
2139  slot_getallattrs(remoteslot);
2140  }
2141 
2142 
2143  /* Find the new partition. */
2145  partrelinfo_new = ExecFindPartition(mtstate, relinfo,
2146  proute, remoteslot,
2147  estate);
2148  MemoryContextSwitchTo(oldctx);
2149  Assert(partrelinfo_new != partrelinfo);
2150 
2151  /* DELETE old tuple found in the old partition. */
2152  apply_handle_delete_internal(edata, partrelinfo,
2153  localslot);
2154 
2155  /* INSERT new tuple into the new partition. */
2156 
2157  /*
2158  * Convert the replacement tuple to match the destination
2159  * partition rowtype.
2160  */
2162  partrel = partrelinfo_new->ri_RelationDesc;
2163  remoteslot_part = partrelinfo_new->ri_PartitionTupleSlot;
2164  if (remoteslot_part == NULL)
2165  remoteslot_part = table_slot_create(partrel,
2166  &estate->es_tupleTable);
2167  map = partrelinfo_new->ri_RootToPartitionMap;
2168  if (map != NULL)
2169  {
2170  remoteslot_part = execute_attr_map_slot(map->attrMap,
2171  remoteslot,
2172  remoteslot_part);
2173  }
2174  else
2175  {
2176  remoteslot_part = ExecCopySlot(remoteslot_part,
2177  remoteslot);
2178  slot_getallattrs(remoteslot);
2179  }
2180  MemoryContextSwitchTo(oldctx);
2181  apply_handle_insert_internal(edata, partrelinfo_new,
2182  remoteslot_part);
2183  }
2184  }
2185  break;
2186 
2187  default:
2188  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
2189  break;
2190  }
2191 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:411
#define DEBUG1
Definition: elog.h:25
PartitionTupleRouting * proute
Definition: worker.c:215
#define RelationGetDescr(relation)
Definition: rel.h:503
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1192
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
CmdType operation
Definition: execnodes.h:1188
LogicalRepRelMapEntry * targetRel
Definition: worker.c:210
EState * state
Definition: execnodes.h:968
Form_pg_class rd_rel
Definition: rel.h:109
void ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo, EState *estate, EPQState *epqstate, TupleTableSlot *searchslot, TupleTableSlot *slot)
Definition: attmap.h:34
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2834
ModifyTableState * mtstate
Definition: worker.c:214
#define ERROR
Definition: elog.h:46
PlanState ps
Definition: execnodes.h:1187
LogicalRepRelation remoterel
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:514
static void slot_modify_data(TupleTableSlot *slot, TupleTableSlot *srcslot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:690
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:102
static void apply_handle_insert_internal(ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot)
Definition: worker.c:1603
ResultRelInfo * targetRelInfo
Definition: worker.c:211
EState * estate
Definition: worker.c:208
#define RelationGetRelationName(relation)
Definition: rel.h:511
AttrMap * attrMap
Definition: tupconvert.h:28
void EvalPlanQualInit(EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2413
List * es_tupleTable
Definition: execnodes.h:602
static bool FindReplTupleInLocalRel(EState *estate, Relation localrel, LogicalRepRelation *remoterel, TupleTableSlot *remoteslot, TupleTableSlot **localslot)
Definition: worker.c:1946
static void apply_handle_delete_internal(ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot)
Definition: worker.c:1894
Plan * plan
Definition: execnodes.h:966
LogicalRepRelMapEntry * logicalrep_partition_open(LogicalRepRelMapEntry *root, Relation partrel, AttrMap *map)
Definition: relation.c:528
#define makeNode(_type_)
Definition: nodes.h:584
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
#define Assert(condition)
Definition: c.h:804
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
TupleConversionMap * ri_RootToPartitionMap
Definition: execnodes.h:513
#define elog(elevel,...)
Definition: elog.h:232
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1697
ResultRelInfo * ExecFindPartition(ModifyTableState *mtstate, ResultRelInfo *rootResultRelInfo, PartitionTupleRouting *proute, TupleTableSlot *slot, EState *estate)
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:231
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:227
PartitionTupleRouting * ExecSetupPartitionTupleRouting(EState *estate, Relation rel)

◆ apply_handle_type()

static void apply_handle_type ( StringInfo  s)
static

Definition at line 1502 of file worker.c.

References handle_streamed_transaction(), LOGICAL_REP_MSG_TYPE, and logicalrep_read_typ().

Referenced by apply_dispatch().

1503 {
1504  LogicalRepTyp typ;
1505 
1507  return;
1508 
1509  logicalrep_read_typ(s, &typ);
1510 }
void logicalrep_read_typ(StringInfo in, LogicalRepTyp *ltyp)
Definition: proto.c:739
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:409

◆ apply_handle_update()

static void apply_handle_update ( StringInfo  s)
static

Definition at line 1658 of file worker.c.

References apply_handle_tuple_routing(), apply_handle_update_internal(), Assert, AttrMap::attnums, LogicalRepRelMapEntry::attrmap, begin_replication_step(), bms_add_member(), check_relation_updatable(), CMD_UPDATE, LogicalRepTupleData::colstatus, create_edata_for_relation(), end_replication_step(), EState::es_range_table, ApplyExecutionData::estate, ExecInitExtraTupleSlot(), fill_extraUpdatedCols(), finish_edata(), FirstLowInvalidHeapAttributeNumber, GetPerTupleMemoryContext, handle_streamed_transaction(), i, list_nth(), LogicalRepRelMapEntry::localrel, LOGICAL_REP_MSG_UPDATE, LOGICALREP_COLUMN_UNCHANGED, logicalrep_read_update(), logicalrep_rel_close(), logicalrep_rel_open(), MemoryContextSwitchTo(), TupleDescData::natts, LogicalRepTupleData::ncols, NoLock, RelationData::rd_rel, ApplyErrorCallbackArg::rel, RelationGetDescr, RowExclusiveLock, should_apply_changes_for_rel(), slot_store_data(), ApplyExecutionData::targetRelInfo, TupleTableSlot::tts_tupleDescriptor, TTSOpsVirtual, TupleDescAttr, and RangeTblEntry::updatedCols.

Referenced by apply_dispatch().

1659 {
1660  LogicalRepRelMapEntry *rel;
1661  LogicalRepRelId relid;
1662  ApplyExecutionData *edata;
1663  EState *estate;
1664  LogicalRepTupleData oldtup;
1665  LogicalRepTupleData newtup;
1666  bool has_oldtup;
1667  TupleTableSlot *remoteslot;
1668  RangeTblEntry *target_rte;
1669  MemoryContext oldctx;
1670 
1672  return;
1673 
1675 
1676  relid = logicalrep_read_update(s, &has_oldtup, &oldtup,
1677  &newtup);
1678  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1679  if (!should_apply_changes_for_rel(rel))
1680  {
1681  /*
1682  * The relation can't become interesting in the middle of the
1683  * transaction so it's safe to unlock it.
1684  */
1687  return;
1688  }
1689 
1690  /* Set relation for error callback */
1692 
1693  /* Check if we can do the update. */
1695 
1696  /* Initialize the executor state. */
1697  edata = create_edata_for_relation(rel);
1698  estate = edata->estate;
1699  remoteslot = ExecInitExtraTupleSlot(estate,
1700  RelationGetDescr(rel->localrel),
1701  &TTSOpsVirtual);
1702 
1703  /*
1704  * Populate updatedCols so that per-column triggers can fire, and so
1705  * executor can correctly pass down indexUnchanged hint. This could
1706  * include more columns than were actually changed on the publisher
1707  * because the logical replication protocol doesn't contain that
1708  * information. But it would for example exclude columns that only exist
1709  * on the subscriber, since we are not touching those.
1710  */
1711  target_rte = list_nth(estate->es_range_table, 0);
1712  for (int i = 0; i < remoteslot->tts_tupleDescriptor->natts; i++)
1713  {
1715  int remoteattnum = rel->attrmap->attnums[i];
1716 
1717  if (!att->attisdropped && remoteattnum >= 0)
1718  {
1719  Assert(remoteattnum < newtup.ncols);
1720  if (newtup.colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
1721  target_rte->updatedCols =
1722  bms_add_member(target_rte->updatedCols,
1724  }
1725  }
1726 
1727  /* Also populate extraUpdatedCols, in case we have generated columns */
1728  fill_extraUpdatedCols(target_rte, rel->localrel);
1729 
1730  /* Build the search tuple. */
1732  slot_store_data(remoteslot, rel,
1733  has_oldtup ? &oldtup : &newtup);
1734  MemoryContextSwitchTo(oldctx);
1735 
1736  /* For a partitioned table, apply update to correct partition. */
1737  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1739  remoteslot, &newtup, CMD_UPDATE);
1740  else
1742  remoteslot, &newtup);
1743 
1744  finish_edata(edata);
1745 
1746  /* Reset relation for error callback */
1748 
1750 
1752 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:352
static void apply_handle_tuple_routing(ApplyExecutionData *edata, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, CmdType operation)
Definition: worker.c:1975
static ApplyExecutionData * create_edata_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:447
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1831
static void apply_handle_update_internal(ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup)
Definition: worker.c:1760
#define RelationGetDescr(relation)
Definition: rel.h:503
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:433
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
List * es_range_table
Definition: execnodes.h:560
Form_pg_class rd_rel
Definition: rel.h:109
#define LOGICALREP_COLUMN_UNCHANGED
Definition: logicalproto.h:91
static ApplyErrorCallbackArg apply_error_callback_arg
Definition: worker.c:230
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
void fill_extraUpdatedCols(RangeTblEntry *target_rte, Relation target_relation)
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * targetRelInfo
Definition: worker.c:211
#define RowExclusiveLock
Definition: lockdefs.h:38
EState * estate
Definition: worker.c:208
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:409
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:258
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:1624
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
static void begin_replication_step(void)
Definition: worker.c:370
Bitmapset * updatedCols
Definition: parsenodes.h:1161
#define Assert(condition)
Definition: c.h:804
AttrNumber * attnums
Definition: attmap.h:36
LogicalRepRelMapEntry * rel
Definition: worker.c:222
LogicalRepRelId logicalrep_read_update(StringInfo in, bool *has_oldtuple, LogicalRepTupleData *oldtup, LogicalRepTupleData *newtup)
Definition: proto.c:477
static void end_replication_step(void)
Definition: worker.c:393
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
static void finish_edata(ApplyExecutionData *edata)
Definition: worker.c:500
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
int i
static void slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:589
uint32 LogicalRepRelId
Definition: logicalproto.h:95

◆ apply_handle_update_internal()

static void apply_handle_update_internal ( ApplyExecutionData edata,
ResultRelInfo relinfo,
TupleTableSlot remoteslot,
LogicalRepTupleData newtup 
)
static

Definition at line 1760 of file worker.c.

References DEBUG1, elog, ApplyExecutionData::estate, EvalPlanQualEnd(), EvalPlanQualInit(), EvalPlanQualSetSlot, ExecClearTuple(), ExecCloseIndices(), ExecOpenIndices(), ExecSimpleRelationUpdate(), FindReplTupleInLocalRel(), GetPerTupleMemoryContext, MemoryContextSwitchTo(), NIL, RelationGetRelationName, LogicalRepRelMapEntry::remoterel, ResultRelInfo::ri_RelationDesc, slot_modify_data(), and ApplyExecutionData::targetRel.

Referenced by apply_handle_update().

1764 {
1765  EState *estate = edata->estate;
1766  LogicalRepRelMapEntry *relmapentry = edata->targetRel;
1767  Relation localrel = relinfo->ri_RelationDesc;
1768  EPQState epqstate;
1769  TupleTableSlot *localslot;
1770  bool found;
1771  MemoryContext oldctx;
1772 
1773  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
1774  ExecOpenIndices(relinfo, false);
1775 
1776  found = FindReplTupleInLocalRel(estate, localrel,
1777  &relmapentry->remoterel,
1778  remoteslot, &localslot);
1779  ExecClearTuple(remoteslot);
1780 
1781  /*
1782  * Tuple found.
1783  *
1784  * Note this will fail if there are other conflicting unique indexes.
1785  */
1786  if (found)
1787  {
1788  /* Process and store remote tuple in the slot */
1790  slot_modify_data(remoteslot, localslot, relmapentry, newtup);
1791  MemoryContextSwitchTo(oldctx);
1792 
1793  EvalPlanQualSetSlot(&epqstate, remoteslot);
1794 
1795  /* Do the actual update. */
1796  ExecSimpleRelationUpdate(relinfo, estate, &epqstate, localslot,
1797  remoteslot);
1798  }
1799  else
1800  {
1801  /*
1802  * The tuple to be updated could not be found. Do nothing except for
1803  * emitting a log message.
1804  *
1805  * XXX should this be promoted to ereport(LOG) perhaps?
1806  */
1807  elog(DEBUG1,
1808  "logical replication did not find row to be updated "
1809  "in replication target relation \"%s\"",
1810  RelationGetRelationName(localrel));
1811  }
1812 
1813  /* Cleanup. */
1814  ExecCloseIndices(relinfo);
1815  EvalPlanQualEnd(&epqstate);
1816 }
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:411
#define DEBUG1
Definition: elog.h:25
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
LogicalRepRelMapEntry * targetRel
Definition: worker.c:210
void ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo, EState *estate, EPQState *epqstate, TupleTableSlot *searchslot, TupleTableSlot *slot)
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2834
LogicalRepRelation remoterel
static void slot_modify_data(TupleTableSlot *slot, TupleTableSlot *srcslot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:690
EState * estate
Definition: worker.c:208
#define RelationGetRelationName(relation)
Definition: rel.h:511
void EvalPlanQualInit(EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2413
static bool FindReplTupleInLocalRel(EState *estate, Relation localrel, LogicalRepRelation *remoterel, TupleTableSlot *remoteslot, TupleTableSlot **localslot)
Definition: worker.c:1946
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
#define elog(elevel,...)
Definition: elog.h:232
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:231
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:227

◆ apply_spooled_messages()

static void apply_spooled_messages ( TransactionId  xid,
XLogRecPtr  lsn 
)
static

Definition at line 1299 of file worker.c.

References appendBinaryStringInfo(), apply_dispatch(), begin_replication_step(), BufFileClose(), BufFileOpenFileSet(), BufFileRead(), changes_filename(), CHECK_FOR_INTERRUPTS, StringInfoData::data, DEBUG1, elog, end_replication_step(), ereport, errcode_for_file_access(), errmsg(), ERROR, fd(), in_remote_transaction, initStringInfo(), MAXPGPATH, MemoryContextReset(), MemoryContextSwitchTo(), MyLogicalRepWorker, palloc(), pfree(), pgstat_report_activity(), remote_final_lsn, repalloc(), resetStringInfo(), s2, STATE_RUNNING, LogicalRepWorker::stream_fileset, LogicalRepWorker::subid, and TopTransactionContext.

Referenced by apply_handle_stream_commit(), and apply_handle_stream_prepare().

1300 {
1302  int nchanges;
1303  char path[MAXPGPATH];
1304  char *buffer = NULL;
1305  MemoryContext oldcxt;
1306  BufFile *fd;
1307 
1308  /* Make sure we have an open transaction */
1310 
1311  /*
1312  * Allocate file handle and memory required to process all the messages in
1313  * TopTransactionContext to avoid them getting reset after each message is
1314  * processed.
1315  */
1317 
1318  /* Open the spool file for the committed/prepared transaction */
1320  elog(DEBUG1, "replaying changes from file \"%s\"", path);
1321 
1323  false);
1324 
1325  buffer = palloc(BLCKSZ);
1326  initStringInfo(&s2);
1327 
1328  MemoryContextSwitchTo(oldcxt);
1329 
1330  remote_final_lsn = lsn;
1331 
1332  /*
1333  * Make sure the handle apply_dispatch methods are aware we're in a remote
1334  * transaction.
1335  */
1336  in_remote_transaction = true;
1338 
1340 
1341  /*
1342  * Read the entries one by one and pass them through the same logic as in
1343  * apply_dispatch.
1344  */
1345  nchanges = 0;
1346  while (true)
1347  {
1348  int nbytes;
1349  int len;
1350 
1352 
1353  /* read length of the on-disk record */
1354  nbytes = BufFileRead(fd, &len, sizeof(len));
1355 
1356  /* have we reached end of the file? */
1357  if (nbytes == 0)
1358  break;
1359 
1360  /* do we have a correct length? */
1361  if (nbytes != sizeof(len))
1362  ereport(ERROR,
1364  errmsg("could not read from streaming transaction's changes file \"%s\": %m",
1365  path)));
1366 
1367  if (len <= 0)
1368  elog(ERROR, "incorrect length %d in streaming transaction's changes file \"%s\"",
1369  len, path);
1370 
1371  /* make sure we have sufficiently large buffer */
1372  buffer = repalloc(buffer, len);
1373 
1374  /* and finally read the data into the buffer */
1375  if (BufFileRead(fd, buffer, len) != len)
1376  ereport(ERROR,
1378  errmsg("could not read from streaming transaction's changes file \"%s\": %m",
1379  path)));
1380 
1381  /* copy the buffer to the stringinfo and call apply_dispatch */
1382  resetStringInfo(&s2);
1383  appendBinaryStringInfo(&s2, buffer, len);
1384 
1385  /* Ensure we are reading the data into our memory context. */
1387 
1388  apply_dispatch(&s2);
1389 
1391 
1392  MemoryContextSwitchTo(oldcxt);
1393 
1394  nchanges++;
1395 
1396  if (nchanges % 1000 == 0)
1397  elog(DEBUG1, "replayed %d changes from file \"%s\"",
1398  nchanges, path);
1399  }
1400 
1401  BufFileClose(fd);
1402 
1403  pfree(buffer);
1404  pfree(s2.data);
1405 
1406  elog(DEBUG1, "replayed %d (all) changes from file \"%s\"",
1407  nchanges, path);
1408 
1409  return;
1410 }
#define DEBUG1
Definition: elog.h:25
MemoryContext TopTransactionContext
Definition: mcxt.c:53
static XLogRecPtr remote_final_lsn
Definition: worker.c:251
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:3160
BufFile * BufFileOpenFileSet(FileSet *fileset, const char *name, int mode, bool missing_ok)
Definition: buffile.c:286
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void BufFileClose(BufFile *file)
Definition: buffile.c:407
FileSet * stream_fileset
void pfree(void *pointer)
Definition: mcxt.c:1169
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:250
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:721
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char * s2
static void begin_replication_step(void)
Definition: worker.c:370
#define ereport(elevel,...)
Definition: elog.h:157
static void apply_dispatch(StringInfo s)
Definition: worker.c:2314
static MemoryContext ApplyMessageContext
Definition: worker.c:239
static void end_replication_step(void)
Definition: worker.c:393
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
void pgstat_report_activity(BackendState state, const char *cmd_str)
#define elog(elevel,...)
Definition: elog.h:232
size_t BufFileRead(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:555
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227

◆ ApplyWorkerMain()

void ApplyWorkerMain ( Datum  main_arg)

Definition at line 3329 of file worker.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AllTablesyncsReady(), am_tablesync_worker(), BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), Subscription::binary, CacheRegisterSyscacheCallback(), CommitTransactionCommand(), Subscription::conninfo, DatumGetInt32, LogicalRepWorker::dbid, DEBUG1, die, elog, Subscription::enabled, ereport, errcode(), 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_STREAM_VERSION_NUM, LOGICALREP_PROTO_TWOPHASE_VERSION_NUM, LOGICALREP_PROTO_VERSION_NUM, LOGICALREP_TWOPHASE_STATE_DISABLED, LOGICALREP_TWOPHASE_STATE_ENABLED, LOGICALREP_TWOPHASE_STATE_PENDING, logicalrep_worker_attach(), LogicalRepApplyLoop(), LogicalRepSyncTableStart(), MemoryContextStrdup(), MemoryContextSwitchTo(), MyLogicalRepWorker, MySubscriptionValid, Subscription::name, NAMEDATALEN, Subscription::oid, OidIsValid, options, pfree(), PGC_BACKEND, PGC_S_OVERRIDE, PGC_SUSET, pqsignal(), proc_exit(), WalRcvStreamOptions::proto, Subscription::publications, LogicalRepWorker::relid, replorigin_by_name(), replorigin_create(), replorigin_session_get_progress(), replorigin_session_origin, replorigin_session_setup(), LogicalRepWorker::reply_time, server_version, SetConfigOption(), SIGHUP, SignalHandlerForConfigReload(), Subscription::slotname, WalRcvStreamOptions::slotname, snprintf, WalRcvStreamOptions::startpoint, StartTransactionCommand(), Subscription::stream, LogicalRepWorker::subid, subscription_change_cb(), SUBSCRIPTIONOID, SUBSCRIPTIONRELMAP, Subscription::synccommit, TopMemoryContext, Subscription::twophasestate, UpdateTwoPhaseState(), LogicalRepWorker::userid, walrcv_connect, walrcv_identify_system, walrcv_server_version, and walrcv_startstreaming.

3330 {
3331  int worker_slot = DatumGetInt32(main_arg);
3332  MemoryContext oldctx;
3333  char originname[NAMEDATALEN];
3334  XLogRecPtr origin_startpos;
3335  char *myslotname;
3337  int server_version;
3338 
3339  /* Attach to slot */
3340  logicalrep_worker_attach(worker_slot);
3341 
3342  /* Setup signal handling */
3344  pqsignal(SIGTERM, die);
3346 
3347  /*
3348  * We don't currently need any ResourceOwner in a walreceiver process, but
3349  * if we did, we could call CreateAuxProcessResourceOwner here.
3350  */
3351 
3352  /* Initialise stats to a sanish value */
3355 
3356  /* Load the libpq-specific functions */
3357  load_file("libpqwalreceiver", false);
3358 
3359  /* Run as replica session replication role. */
3360  SetConfigOption("session_replication_role", "replica",
3362 
3363  /* Connect to our database. */
3366  0);
3367 
3368  /*
3369  * Set always-secure search path, so malicious users can't redirect user
3370  * code (e.g. pg_index.indexprs).
3371  */
3372  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
3373 
3374  /* Load the subscription into persistent memory context. */
3376  "ApplyContext",
3380 
3382  if (!MySubscription)
3383  {
3384  ereport(LOG,
3385  (errmsg("logical replication apply worker for subscription %u will not "
3386  "start because the subscription was removed during startup",
3388  proc_exit(0);
3389  }
3390 
3391  MySubscriptionValid = true;
3392  MemoryContextSwitchTo(oldctx);
3393 
3394  if (!MySubscription->enabled)
3395  {
3396  ereport(LOG,
3397  (errmsg("logical replication apply worker for subscription \"%s\" will not "
3398  "start because the subscription was disabled during startup",
3399  MySubscription->name)));
3400 
3401  proc_exit(0);
3402  }
3403 
3404  /* Setup synchronous commit according to the user's wishes */
3405  SetConfigOption("synchronous_commit", MySubscription->synccommit,
3407 
3408  /* Keep us informed about subscription changes. */
3411  (Datum) 0);
3412 
3413  if (am_tablesync_worker())
3414  ereport(LOG,
3415  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has started",
3417  else
3418  ereport(LOG,
3419  (errmsg("logical replication apply worker for subscription \"%s\" has started",
3420  MySubscription->name)));
3421 
3423 
3424  /* Connect to the origin and start the replication. */
3425  elog(DEBUG1, "connecting to publisher using connection string \"%s\"",
3427 
3428  if (am_tablesync_worker())
3429  {
3430  char *syncslotname;
3431 
3432  /* This is table synchronization worker, call initial sync. */
3433  syncslotname = LogicalRepSyncTableStart(&origin_startpos);
3434 
3435  /* allocate slot name in long-lived context */
3436  myslotname = MemoryContextStrdup(ApplyContext, syncslotname);
3437 
3438  pfree(syncslotname);
3439  }
3440  else
3441  {
3442  /* This is main apply worker */
3443  RepOriginId originid;
3444  TimeLineID startpointTLI;
3445  char *err;
3446 
3447  myslotname = MySubscription->slotname;
3448 
3449  /*
3450  * This shouldn't happen if the subscription is enabled, but guard
3451  * against DDL bugs or manual catalog changes. (libpqwalreceiver will
3452  * crash if slot is NULL.)
3453  */
3454  if (!myslotname)
3455  ereport(ERROR,
3456  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3457  errmsg("subscription has no replication slot set")));
3458 
3459  /* Setup replication origin tracking. */
3461  snprintf(originname, sizeof(originname), "pg_%u", MySubscription->oid);
3462  originid = replorigin_by_name(originname, true);
3463  if (!OidIsValid(originid))
3464  originid = replorigin_create(originname);
3465  replorigin_session_setup(originid);
3466  replorigin_session_origin = originid;
3467  origin_startpos = replorigin_session_get_progress(false);
3469 
3471  MySubscription->name, &err);
3472  if (LogRepWorkerWalRcvConn == NULL)
3473  ereport(ERROR,
3474  (errcode(ERRCODE_CONNECTION_FAILURE),
3475  errmsg("could not connect to the publisher: %s", err)));
3476 
3477  /*
3478  * We don't really use the output identify_system for anything but it
3479  * does some initializations on the upstream so let's still call it.
3480  */
3481  (void) walrcv_identify_system(LogRepWorkerWalRcvConn, &startpointTLI);
3482  }
3483 
3484  /*
3485  * Setup callback for syscache so that we know when something changes in
3486  * the subscription relation state.
3487  */
3490  (Datum) 0);
3491 
3492  /* Build logical replication streaming options. */
3493  options.logical = true;
3494  options.startpoint = origin_startpos;
3495  options.slotname = myslotname;
3496 
3498  options.proto.logical.proto_version =
3499  server_version >= 150000 ? LOGICALREP_PROTO_TWOPHASE_VERSION_NUM :
3500  server_version >= 140000 ? LOGICALREP_PROTO_STREAM_VERSION_NUM :
3502 
3503  options.proto.logical.publication_names = MySubscription->publications;
3504  options.proto.logical.binary = MySubscription->binary;
3505  options.proto.logical.streaming = MySubscription->stream;
3506  options.proto.logical.twophase = false;
3507 
3508  if (!am_tablesync_worker())
3509  {
3510  /*
3511  * Even when the two_phase mode is requested by the user, it remains
3512  * as the tri-state PENDING until all tablesyncs have reached READY
3513  * state. Only then, can it become ENABLED.
3514  *
3515  * Note: If the subscription has no tables then leave the state as
3516  * PENDING, which allows ALTER SUBSCRIPTION ... REFRESH PUBLICATION to
3517  * work.
3518  */
3521  {
3522  /* Start streaming with two_phase enabled */
3523  options.proto.logical.twophase = true;
3525 
3530  }
3531  else
3532  {
3534  }
3535 
3536  ereport(DEBUG1,
3537  (errmsg("logical replication apply worker for subscription \"%s\" two_phase is %s.",
3542  "?")));
3543  }
3544  else
3545  {
3546  /* Start normal logical streaming replication. */
3548  }
3549 
3550  /* Run the main loop. */
3551  LogicalRepApplyLoop(origin_startpos);
3552 
3553  proc_exit(0);
3554 }
Subscription * MySubscription
Definition: worker.c:247
#define LOGICALREP_PROTO_VERSION_NUM
Definition: logicalproto.h:36
#define AllocSetContextCreate
Definition: memutils.h:173
#define DEBUG1
Definition: elog.h:25
WalReceiverConn * LogRepWorkerWalRcvConn
Definition: worker.c:245
uint32 TimeLineID
Definition: xlogdefs.h:59
#define DatumGetInt32(X)
Definition: postgres.h:516
#define LOGICALREP_TWOPHASE_STATE_DISABLED
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
#define walrcv_identify_system(conn, primary_tli)
Definition: walreceiver.h:412
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void CommitTransactionCommand(void)
Definition: xact.c:2949
RepOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition: origin.c:209
#define walrcv_server_version(conn)
Definition: walreceiver.h:414
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
TimestampTz last_send_time
uint16 RepOriginId
Definition: xlogdefs.h:65
#define walrcv_startstreaming(conn, options)
Definition: walreceiver.h:418
union WalRcvStreamOptions::@104 proto
void proc_exit(int code)
Definition: ipc.c:104
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1206
int errcode(int sqlerrcode)
Definition: elog.c:698
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:240
void replorigin_session_setup(RepOriginId node)
Definition: origin.c:1071
#define LOG
Definition: elog.h:26
char * LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
Definition: tablesync.c:920
#define OidIsValid(objectId)
Definition: c.h:710
#define LOGICALREP_TWOPHASE_STATE_ENABLED
#define NAMEDATALEN
Subscription * GetSubscription(Oid subid, bool missing_ok)
static void subscription_change_cb(Datum arg, int cacheid, uint32 hashvalue)
Definition: worker.c:2951
void pfree(void *pointer)
Definition: mcxt.c:1169
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
Definition: guc.h:75
static bool am_tablesync_worker(void)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
void logicalrep_worker_attach(int slot)
Definition: launcher.c:565
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8110
#define LOGICALREP_TWOPHASE_STATE_PENDING
#define SIGHUP
Definition: win32_port.h:167
XLogRecPtr startpoint
Definition: walreceiver.h:170
MemoryContext TopMemoryContext
Definition: mcxt.c:48
MemoryContext ApplyContext
Definition: worker.c:240
static char ** options
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1498
uintptr_t Datum
Definition: postgres.h:411
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition: tablesync.c:1255
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: postmaster.c:5752
#define ereport(elevel,...)
Definition: elog.h:157
#define LOGICALREP_PROTO_STREAM_VERSION_NUM
Definition: logicalproto.h:37
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
#define LOGICALREP_PROTO_TWOPHASE_VERSION_NUM
Definition: logicalproto.h:38
TimestampTz last_recv_time
bool AllTablesyncsReady(void)
Definition: tablesync.c:1230
uint64 XLogRecPtr
Definition: xlogdefs.h:21
RepOriginId replorigin_session_origin
Definition: origin.c:154
void StartTransactionCommand(void)
Definition: xact.c:2848
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
static int server_version
Definition: pg_dumpall.c:83
bool MySubscriptionValid
Definition: worker.c:248
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1286
static void LogicalRepApplyLoop(XLogRecPtr last_received)
Definition: worker.c:2513
#define elog(elevel,...)
Definition: elog.h:232
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define snprintf
Definition: port.h:217
#define die(msg)
Definition: pg_test_fsync.c:97
TimestampTz reply_time
void invalidate_syncing_table_states(Datum arg, int cacheid, uint32 hashvalue)
Definition: tablesync.c:268
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5781
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:404

◆ begin_replication_step()

static void begin_replication_step ( void  )
static

Definition at line 370 of file worker.c.

References GetTransactionSnapshot(), IsTransactionState(), maybe_reread_subscription(), MemoryContextSwitchTo(), PushActiveSnapshot(), SetCurrentStatementStartTimestamp(), and StartTransactionCommand().

Referenced by apply_handle_commit_prepared(), apply_handle_delete(), apply_handle_insert(), apply_handle_prepare(), apply_handle_rollback_prepared(), apply_handle_stream_abort(), apply_handle_stream_start(), apply_handle_truncate(), apply_handle_update(), and apply_spooled_messages().

371 {
373 
374  if (!IsTransactionState())
375  {
378  }
379 
381 
383 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
static void maybe_reread_subscription(void)
Definition: worker.c:2850
static MemoryContext ApplyMessageContext
Definition: worker.c:239
void StartTransactionCommand(void)
Definition: xact.c:2848
bool IsTransactionState(void)
Definition: xact.c:371
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:833

◆ changes_filename()

static void changes_filename ( char *  path,
Oid  subid,
TransactionId  xid 
)
inlinestatic

Definition at line 3160 of file worker.c.

References MAXPGPATH, and snprintf.

Referenced by apply_handle_stream_abort(), apply_spooled_messages(), stream_cleanup_files(), and stream_open_file().

3161 {
3162  snprintf(path, MAXPGPATH, "%u-%u.changes", subid, xid);
3163 }
#define MAXPGPATH
#define snprintf
Definition: port.h:217

◆ check_relation_updatable()

static void check_relation_updatable ( LogicalRepRelMapEntry rel)
static

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

1625 {
1626  /* Updatable, no error. */
1627  if (rel->updatable)
1628  return;
1629 
1630  /*
1631  * We are in error mode so it's fine this is somewhat slow. It's better to
1632  * give user correct error.
1633  */
1635  {
1636  ereport(ERROR,
1637  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1638  errmsg("publisher did not send replica identity column "
1639  "expected by the logical replication target relation \"%s.%s\"",
1640  rel->remoterel.nspname, rel->remoterel.relname)));
1641  }
1642 
1643  ereport(ERROR,
1644  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1645  errmsg("logical replication target relation \"%s.%s\" has "
1646  "neither REPLICA IDENTITY index nor PRIMARY "
1647  "KEY and published relation does not have "
1648  "REPLICA IDENTITY FULL",
1649  rel->remoterel.nspname, rel->remoterel.relname)));
1650 }
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:1518
int errcode(int sqlerrcode)
Definition: elog.c:698
#define OidIsValid(objectId)
Definition: c.h:710
#define ERROR
Definition: elog.h:46
LogicalRepRelation remoterel
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ cleanup_subxact_info()

static void cleanup_subxact_info ( void  )
inlinestatic

Definition at line 3298 of file worker.c.

References InvalidTransactionId, ApplySubXactData::nsubxacts, ApplySubXactData::nsubxacts_max, pfree(), ApplySubXactData::subxact_last, and ApplySubXactData::subxacts.

Referenced by apply_handle_stream_abort(), and subxact_info_write().

3299 {
3300  if (subxact_data.subxacts)
3302 
3303  subxact_data.subxacts = NULL;
3305  subxact_data.nsubxacts = 0;
3307 }
TransactionId subxact_last
Definition: worker.c:273
uint32 nsubxacts
Definition: worker.c:271
void pfree(void *pointer)
Definition: mcxt.c:1169
SubXactInfo * subxacts
Definition: worker.c:274
#define InvalidTransactionId
Definition: transam.h:31
static ApplySubXactData subxact_data
Definition: worker.c:277
uint32 nsubxacts_max
Definition: worker.c:272

◆ create_edata_for_relation()

static ApplyExecutionData* create_edata_for_relation ( LogicalRepRelMapEntry rel)
static

Definition at line 447 of file worker.c.

References AccessShareLock, AfterTriggerBeginQuery(), CreateExecutorState(), EState::es_opened_result_relations, EState::es_output_cid, ApplyExecutionData::estate, ExecInitRangeTable(), GetCurrentCommandId(), InitResultRelInfo(), lappend(), list_make1, LogicalRepRelMapEntry::localrel, makeNode, palloc0(), RelationData::rd_rel, RelationGetRelid, RangeTblEntry::relid, RangeTblEntry::relkind, RangeTblEntry::rellockmode, RTE_RELATION, RangeTblEntry::rtekind, ApplyExecutionData::targetRel, and ApplyExecutionData::targetRelInfo.

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

448 {
449  ApplyExecutionData *edata;
450  EState *estate;
451  RangeTblEntry *rte;
452  ResultRelInfo *resultRelInfo;
453 
454  edata = (ApplyExecutionData *) palloc0(sizeof(ApplyExecutionData));
455  edata->targetRel = rel;
456 
457  edata->estate = estate = CreateExecutorState();
458 
459  rte = makeNode(RangeTblEntry);
460  rte->rtekind = RTE_RELATION;
461  rte->relid = RelationGetRelid(rel->localrel);
462  rte->relkind = rel->localrel->rd_rel->relkind;
464  ExecInitRangeTable(estate, list_make1(rte));
465 
466  edata->targetRelInfo = resultRelInfo = makeNode(ResultRelInfo);
467 
468  /*
469  * Use Relation opened by logicalrep_rel_open() instead of opening it
470  * again.
471  */
472  InitResultRelInfo(resultRelInfo, rel->localrel, 1, NULL, 0);
473 
474  /*
475  * We put the ResultRelInfo in the es_opened_result_relations list, even
476  * though we don't populate the es_result_relations array. That's a bit
477  * bogus, but it's enough to make ExecGetTriggerResultRel() find them.
478  *
479  * ExecOpenIndices() is not called here either, each execution path doing
480  * an apply operation being responsible for that.
481  */
483  lappend(estate->es_opened_result_relations, resultRelInfo);
484 
485  estate->es_output_cid = GetCurrentCommandId(true);
486 
487  /* Prepare to catch AFTER triggers. */
489 
490  /* other fields of edata remain NULL for now */
491 
492  return edata;
493 }
void ExecInitRangeTable(EState *estate, List *rangeTable)
Definition: execUtils.c:751
CommandId es_output_cid
Definition: execnodes.h:572
#define AccessShareLock
Definition: lockdefs.h:36
LogicalRepRelMapEntry * targetRel
Definition: worker.c:210
Form_pg_class rd_rel
Definition: rel.h:109
#define list_make1(x1)
Definition: pg_list.h:206
ResultRelInfo * targetRelInfo
Definition: worker.c:211
List * es_opened_result_relations
Definition: execnodes.h:578
EState * estate
Definition: worker.c:208
EState * CreateExecutorState(void)
Definition: execUtils.c:90
List * lappend(List *list, void *datum)
Definition: list.c:336
void * palloc0(Size size)
Definition: mcxt.c:1093
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition: execMain.c:1193
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4670
#define makeNode(_type_)
Definition: nodes.h:584
RTEKind rtekind
Definition: parsenodes.h:1007
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:761
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ end_replication_step()

◆ FindReplTupleInLocalRel()

static bool FindReplTupleInLocalRel ( EState estate,
Relation  localrel,
LogicalRepRelation remoterel,
TupleTableSlot remoteslot,
TupleTableSlot **  localslot 
)
static

Definition at line 1946 of file worker.c.

References Assert, EState::es_tupleTable, GetRelationIdentityOrPK(), LockTupleExclusive, OidIsValid, RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), LogicalRepRelation::replident, and table_slot_create().

Referenced by apply_handle_delete_internal(), apply_handle_tuple_routing(), and apply_handle_update_internal().

1950 {
1951  Oid idxoid;
1952  bool found;
1953 
1954  *localslot = table_slot_create(localrel, &estate->es_tupleTable);
1955 
1956  idxoid = GetRelationIdentityOrPK(localrel);
1957  Assert(OidIsValid(idxoid) ||
1958  (remoterel->replident == REPLICA_IDENTITY_FULL));
1959 
1960  if (OidIsValid(idxoid))
1961  found = RelationFindReplTupleByIndex(localrel, idxoid,
1963  remoteslot, *localslot);
1964  else
1965  found = RelationFindReplTupleSeq(localrel, LockTupleExclusive,
1966  remoteslot, *localslot);
1967 
1968  return found;
1969 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:1518
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
bool RelationFindReplTupleByIndex(Relation rel, Oid idxoid, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)
List * es_tupleTable
Definition: execnodes.h:602
#define Assert(condition)
Definition: c.h:804
bool RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)

◆ finish_edata()

static void finish_edata ( ApplyExecutionData edata)
static

Definition at line 500 of file worker.c.

References AfterTriggerEndQuery(), EState::es_tupleTable, ApplyExecutionData::estate, ExecCleanupTupleRouting(), ExecResetTupleTable(), FreeExecutorState(), ApplyExecutionData::mtstate, pfree(), and ApplyExecutionData::proute.

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

501 {
502  EState *estate = edata->estate;
503 
504  /* Handle any queued AFTER triggers. */
505  AfterTriggerEndQuery(estate);
506 
507  /* Shut down tuple routing, if any was done. */
508  if (edata->proute)
509  ExecCleanupTupleRouting(edata->mtstate, edata->proute);
510 
511  /*
512  * Cleanup. It might seem that we should call ExecCloseResultRelations()
513  * here, but we intentionally don't. It would close the rel we added to
514  * es_opened_result_relations above, which is wrong because we took no
515  * corresponding refcount. We rely on ExecCleanupTupleRouting() to close
516  * any other relations opened during execution.
517  */
518  ExecResetTupleTable(estate->es_tupleTable, false);
519  FreeExecutorState(estate);
520  pfree(edata);
521 }
PartitionTupleRouting * proute
Definition: worker.c:215
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
void pfree(void *pointer)
Definition: mcxt.c:1169
ModifyTableState * mtstate
Definition: worker.c:214
void ExecCleanupTupleRouting(ModifyTableState *mtstate, PartitionTupleRouting *proute)
EState * estate
Definition: worker.c:208
List * es_tupleTable
Definition: execnodes.h:602
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1191
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4690

◆ get_flush_position()

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

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

2436 {
2437  dlist_mutable_iter iter;
2438  XLogRecPtr local_flush = GetFlushRecPtr();
2439 
2441  *flush = InvalidXLogRecPtr;
2442 
2444  {
2445  FlushPosition *pos =
2446  dlist_container(FlushPosition, node, iter.cur);
2447 
2448  *write = pos->remote_end;
2449 
2450  if (pos->local_end <= local_flush)
2451  {
2452  *flush = pos->remote_end;
2453  dlist_delete(iter.cur);
2454  pfree(pos);
2455  }
2456  else
2457  {
2458  /*
2459  * Don't want to uselessly iterate over the rest of the list which
2460  * could potentially be long. Instead get the last element and
2461  * grab the write position from there.
2462  */
2463  pos = dlist_tail_element(FlushPosition, node,
2464  &lsn_mapping);
2465  *write = pos->remote_end;
2466  *have_pending_txes = true;
2467  return;
2468  }
2469  }
2470 
2471  *have_pending_txes = !dlist_is_empty(&lsn_mapping);
2472 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:543
static dlist_head lsn_mapping
Definition: worker.c:204
#define write(a, b, c)
Definition: win32.h:14
XLogRecPtr remote_end
Definition: worker.c:201
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8680
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
void pfree(void *pointer)
Definition: mcxt.c:1169
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:515
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
XLogRecPtr local_end
Definition: worker.c:200
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 1518 of file worker.c.

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

Referenced by check_relation_updatable(), and FindReplTupleInLocalRel().

1519 {
1520  Oid idxoid;
1521 
1522  idxoid = RelationGetReplicaIndex(rel);
1523 
1524  if (!OidIsValid(idxoid))
1525  idxoid = RelationGetPrimaryKeyIndex(rel);
1526 
1527  return idxoid;
1528 }
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4782
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
Oid RelationGetPrimaryKeyIndex(Relation relation)
Definition: relcache.c:4761

◆ handle_streamed_transaction()

static bool handle_streamed_transaction ( LogicalRepMsgType  action,
StringInfo  s 
)
static

Definition at line 409 of file worker.c.

References Assert, ereport, errcode(), errmsg_internal(), ERROR, in_streamed_transaction, pq_getmsgint(), stream_write_change(), stream_xid, subxact_info_add(), and TransactionIdIsValid.

Referenced by apply_handle_delete(), apply_handle_insert(), apply_handle_relation(), apply_handle_truncate(), apply_handle_type(), and apply_handle_update().

410 {
411  TransactionId xid;
412 
413  /* not in streaming mode */
415  return false;
416 
417  Assert(stream_fd != NULL);
419 
420  /*
421  * We should have received XID of the subxact as the first part of the
422  * message, so extract it.
423  */
424  xid = pq_getmsgint(s, 4);
425 
426  if (!TransactionIdIsValid(xid))
427  ereport(ERROR,
428  (errcode(ERRCODE_PROTOCOL_VIOLATION),
429  errmsg_internal("invalid transaction ID in streamed replication transaction")));
430 
431  /* Add the new subxact to the array (unless already there). */
432  subxact_info_add(xid);
433 
434  /* write the change to the current file */
436 
437  return true;
438 }
static void stream_write_change(char action, StringInfo s)
Definition: worker.c:3271
static void subxact_info_add(TransactionId xid)
Definition: worker.c:3075
uint32 TransactionId
Definition: c.h:587
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
static bool in_streamed_transaction
Definition: worker.c:254
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define Assert(condition)
Definition: c.h:804
static BufFile * stream_fd
Definition: worker.c:259
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static TransactionId stream_xid
Definition: worker.c:256

◆ IsLogicalWorker()

bool IsLogicalWorker ( void  )

Definition at line 3560 of file worker.c.

References MyLogicalRepWorker.

Referenced by ProcessInterrupts().

3561 {
3562  return MyLogicalRepWorker != NULL;
3563 }
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57

◆ LogicalRepApplyLoop()

static void LogicalRepApplyLoop ( XLogRecPtr  last_received)
static

Definition at line 2513 of file worker.c.

References AcceptInvalidationMessages(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, apply_dispatch(), apply_error_callback(), buf, ErrorContextCallback::callback, CHECK_FOR_INTERRUPTS, ConfigReloadPending, StringInfoData::cursor, StringInfoData::data, dlist_is_empty(), ereport, errcode(), errmsg(), ERROR, error_context_stack, fd(), GetCurrentTimestamp(), in_remote_transaction, in_streamed_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(), ErrorContextCallback::previous, 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_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_SOCKET_READABLE, and WL_TIMEOUT.

Referenced by ApplyWorkerMain().

2514 {
2515  TimestampTz last_recv_timestamp = GetCurrentTimestamp();
2516  bool ping_sent = false;
2517  TimeLineID tli;
2518  ErrorContextCallback errcallback;
2519 
2520  /*
2521  * Init the ApplyMessageContext which we clean up after each replication
2522  * protocol message.
2523  */
2525  "ApplyMessageContext",
2527 
2528  /*
2529  * This memory context is used for per-stream data when the streaming mode
2530  * is enabled. This context is reset on each stream stop.
2531  */
2533  "LogicalStreamingContext",
2535 
2536  /* mark as idle, before starting to loop */
2538 
2539  /*
2540  * Push apply error context callback. Fields will be filled during
2541  * applying a change.
2542  */
2543  errcallback.callback = apply_error_callback;
2544  errcallback.previous = error_context_stack;
2545  error_context_stack = &errcallback;
2546 
2547  /* This outer loop iterates once per wait. */
2548  for (;;)
2549  {
2551  int rc;
2552  int len;
2553  char *buf = NULL;
2554  bool endofstream = false;
2555  long wait_time;
2556 
2558 
2560 
2561  len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
2562 
2563  if (len != 0)
2564  {
2565  /* Loop to process all available data (without blocking). */
2566  for (;;)
2567  {
2569 
2570  if (len == 0)
2571  {
2572  break;
2573  }
2574  else if (len < 0)
2575  {
2576  ereport(LOG,
2577  (errmsg("data stream from publisher has ended")));
2578  endofstream = true;
2579  break;
2580  }
2581  else
2582  {
2583  int c;
2584  StringInfoData s;
2585 
2586  /* Reset timeout. */
2587  last_recv_timestamp = GetCurrentTimestamp();
2588  ping_sent = false;
2589 
2590  /* Ensure we are reading the data into our memory context. */
2592 
2593  s.data = buf;
2594  s.len = len;
2595  s.cursor = 0;
2596  s.maxlen = -1;
2597 
2598  c = pq_getmsgbyte(&s);
2599 
2600  if (c == 'w')
2601  {
2602  XLogRecPtr start_lsn;
2603  XLogRecPtr end_lsn;
2604  TimestampTz send_time;
2605 
2606  start_lsn = pq_getmsgint64(&s);
2607  end_lsn = pq_getmsgint64(&s);
2608  send_time = pq_getmsgint64(&s);
2609 
2610  if (last_received < start_lsn)
2611  last_received = start_lsn;
2612 
2613  if (last_received < end_lsn)
2614  last_received = end_lsn;
2615 
2616  UpdateWorkerStats(last_received, send_time, false);
2617 
2618  apply_dispatch(&s);
2619  }
2620  else if (c == 'k')
2621  {
2622  XLogRecPtr end_lsn;
2624  bool reply_requested;
2625 
2626  end_lsn = pq_getmsgint64(&s);
2627  timestamp = pq_getmsgint64(&s);
2628  reply_requested = pq_getmsgbyte(&s);
2629 
2630  if (last_received < end_lsn)
2631  last_received = end_lsn;
2632 
2633  send_feedback(last_received, reply_requested, false);
2634  UpdateWorkerStats(last_received, timestamp, true);
2635  }
2636  /* other message types are purposefully ignored */
2637 
2639  }
2640 
2641  len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
2642  }
2643  }
2644 
2645  /* confirm all writes so far */
2646  send_feedback(last_received, false, false);
2647 
2649  {
2650  /*
2651  * If we didn't get any transactions for a while there might be
2652  * unconsumed invalidation messages in the queue, consume them
2653  * now.
2654  */
2657 
2658  /* Process any table synchronization changes. */
2659  process_syncing_tables(last_received);
2660  }
2661 
2662  /* Cleanup the memory. */
2665 
2666  /* Check if we need to exit the streaming loop. */
2667  if (endofstream)
2668  break;
2669 
2670  /*
2671  * Wait for more data or latch. If we have unflushed transactions,
2672  * wake up after WalWriterDelay to see if they've been flushed yet (in
2673  * which case we should send a feedback message). Otherwise, there's
2674  * no particular urgency about waking up unless we get data or a
2675  * signal.
2676  */
2677  if (!dlist_is_empty(&lsn_mapping))
2678  wait_time = WalWriterDelay;
2679  else
2680  wait_time = NAPTIME_PER_CYCLE;
2681 
2685  fd, wait_time,
2687 
2688  if (rc & WL_LATCH_SET)
2689  {
2692  }
2693 
2694  if (ConfigReloadPending)
2695  {
2696  ConfigReloadPending = false;
2698  }
2699 
2700  if (rc & WL_TIMEOUT)
2701  {
2702  /*
2703  * We didn't receive anything new. If we haven't heard anything
2704  * from the server for more than wal_receiver_timeout / 2, ping
2705  * the server. Also, if it's been longer than
2706  * wal_receiver_status_interval since the last update we sent,
2707  * send a status update to the primary anyway, to report any
2708  * progress in applying WAL.
2709  */
2710  bool requestReply = false;
2711 
2712  /*
2713  * Check if time since last receive from primary has reached the
2714  * configured limit.
2715  */
2716  if (wal_receiver_timeout > 0)
2717  {
2719  TimestampTz timeout;
2720 
2721  timeout =
2722  TimestampTzPlusMilliseconds(last_recv_timestamp,
2724 
2725  if (now >= timeout)
2726  ereport(ERROR,
2727  (errcode(ERRCODE_CONNECTION_FAILURE),
2728  errmsg("terminating logical replication worker due to timeout")));
2729 
2730  /* Check to see if it's time for a ping. */
2731  if (!ping_sent)
2732  {
2733  timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
2734  (wal_receiver_timeout / 2));
2735  if (now >= timeout)
2736  {
2737  requestReply = true;
2738  ping_sent = true;
2739  }
2740  }
2741  }
2742 
2743  send_feedback(last_received, requestReply, requestReply);
2744  }
2745  }
2746 
2747  /* Pop the error context stack */
2748  error_context_stack = errcallback.previous;
2749 
2750  /* All done */
2752 }
static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
Definition: worker.c:2761
#define AllocSetContextCreate
Definition: memutils.h:173
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:420
WalReceiverConn * LogRepWorkerWalRcvConn
Definition: worker.c:245
uint32 TimeLineID
Definition: xlogdefs.h:59
void AcceptInvalidationMessages(void)
Definition: inval.c:725
#define WL_TIMEOUT
Definition: latch.h:128
void ProcessConfigFile(GucContext context)
static dlist_head lsn_mapping
Definition: worker.c:204
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 timestamp
int64 TimestampTz
Definition: timestamp.h:39
static void UpdateWorkerStats(XLogRecPtr last_lsn, TimestampTz send_time, bool reply)
Definition: worker.c:2497
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:422
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
#define WL_SOCKET_READABLE
Definition: latch.h:126
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
#define LOG
Definition: elog.h:26
void(* callback)(void *arg)
Definition: elog.h:247
struct ErrorContextCallback * previous
Definition: elog.h:246
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void ResetLatch(Latch *latch)
Definition: latch.c:660
int wal_receiver_timeout
Definition: walreceiver.c:90
ErrorContextCallback * error_context_stack
Definition: elog.c:93
static void apply_error_callback(void *arg)
Definition: worker.c:3567
#define ERROR
Definition: elog.h:46
#define NAPTIME_PER_CYCLE
Definition: worker.c:195
bool in_remote_transaction
Definition: worker.c:250
static bool in_streamed_transaction
Definition: worker.c:254
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
char * c
static char * buf
Definition: pg_test_fsync.c:68
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:500
int pgsocket
Definition: port.h:31
MemoryContext TopMemoryContext
Definition: mcxt.c:48
Definition: guc.h:72
MemoryContext ApplyContext
Definition: worker.c:240
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define PGINVALID_SOCKET
Definition: port.h:33
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define ereport(elevel,...)
Definition: elog.h:157
static MemoryContext LogicalStreamingContext
Definition: worker.c:243
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
static void apply_dispatch(StringInfo s)
Definition: worker.c:2314
static void maybe_reread_subscription(void)
Definition: worker.c:2850
static MemoryContext ApplyMessageContext
Definition: worker.c:239
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
int WalWriterDelay
Definition: walwriter.c:70
int errmsg(const char *fmt,...)
Definition: elog.c:909
void pgstat_report_activity(BackendState state, const char *cmd_str)
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:455
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
#define WL_LATCH_SET
Definition: latch.h:125
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130

◆ maybe_reread_subscription()

static void maybe_reread_subscription ( void  )
static

Definition at line 2850 of file worker.c.

References Assert, Subscription::binary, 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(), Subscription::stream, LogicalRepWorker::subid, Subscription::synccommit, and Subscription::twophasestate.

Referenced by apply_handle_commit_internal(), begin_replication_step(), and LogicalRepApplyLoop().

2851 {
2852  MemoryContext oldctx;
2854  bool started_tx = false;
2855 
2856  /* When cache state is valid there is nothing to do here. */
2857  if (MySubscriptionValid)
2858  return;
2859 
2860  /* This function might be called inside or outside of transaction. */
2861  if (!IsTransactionState())
2862  {
2864  started_tx = true;
2865  }
2866 
2867  /* Ensure allocations in permanent context. */
2869 
2870  newsub = GetSubscription(MyLogicalRepWorker->subid, true);
2871 
2872  /*
2873  * Exit if the subscription was removed. This normally should not happen
2874  * as the worker gets killed during DROP SUBSCRIPTION.
2875  */
2876  if (!newsub)
2877  {
2878  ereport(LOG,
2879  (errmsg("logical replication apply worker for subscription \"%s\" will "
2880  "stop because the subscription was removed",
2881  MySubscription->name)));
2882 
2883  proc_exit(0);
2884  }
2885 
2886  /*
2887  * Exit if the subscription was disabled. This normally should not happen
2888  * as the worker gets killed during ALTER SUBSCRIPTION ... DISABLE.
2889  */
2890  if (!newsub->enabled)
2891  {
2892  ereport(LOG,
2893  (errmsg("logical replication apply worker for subscription \"%s\" will "
2894  "stop because the subscription was disabled",
2895  MySubscription->name)));
2896 
2897  proc_exit(0);
2898  }
2899 
2900  /* !slotname should never happen when enabled is true. */
2901  Assert(newsub->slotname);
2902 
2903  /* two-phase should not be altered */
2905 
2906  /*
2907  * Exit if any parameter that affects the remote connection was changed.
2908  * The launcher will start a new worker.
2909  */
2910  if (strcmp(newsub->conninfo, MySubscription->conninfo) != 0 ||
2911  strcmp(newsub->name, MySubscription->name) != 0 ||
2912  strcmp(newsub->slotname, MySubscription->slotname) != 0 ||
2913  newsub->binary != MySubscription->binary ||
2914  newsub->stream != MySubscription->stream ||
2916  {
2917  ereport(LOG,
2918  (errmsg("logical replication apply worker for subscription \"%s\" will restart because of a parameter change",
2919  MySubscription->name)));
2920 
2921  proc_exit(0);
2922  }
2923 
2924  /* Check for other changes that should never happen too. */
2925  if (newsub->dbid != MySubscription->dbid)
2926  {
2927  elog(ERROR, "subscription %u changed unexpectedly",
2929  }
2930 
2931  /* Clean old subscription info and switch to new one. */
2934 
2935  MemoryContextSwitchTo(oldctx);
2936 
2937  /* Change synchronous commit according to the user's wishes */
2938  SetConfigOption("synchronous_commit", MySubscription->synccommit,
2940 
2941  if (started_tx)
2943 
2944  MySubscriptionValid = true;
2945 }
Subscription * MySubscription
Definition: worker.c:247
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3149
void CommitTransactionCommand(void)
Definition: xact.c:2949
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void proc_exit(int code)
Definition: ipc.c:104
#define LOG
Definition: elog.h:26
Subscription * GetSubscription(Oid subid, bool missing_ok)
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8110
MemoryContext ApplyContext
Definition: worker.c:240
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
void StartTransactionCommand(void)
Definition: xact.c:2848
bool IsTransactionState(void)
Definition: xact.c:371
bool MySubscriptionValid
Definition: worker.c:248
void FreeSubscription(Subscription *sub)
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
static color newsub(struct colormap *cm, color co)
Definition: regc_color.c:389

◆ reset_apply_error_context_info()

static void reset_apply_error_context_info ( void  )
inlinestatic

◆ send_feedback()

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

Definition at line 2761 of file worker.c.

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

Referenced by LogicalRepApplyLoop().

2762 {
2763  static StringInfo reply_message = NULL;
2764  static TimestampTz send_time = 0;
2765 
2766  static XLogRecPtr last_recvpos = InvalidXLogRecPtr;
2767  static XLogRecPtr last_writepos = InvalidXLogRecPtr;
2768  static XLogRecPtr last_flushpos = InvalidXLogRecPtr;
2769 
2770  XLogRecPtr writepos;
2771  XLogRecPtr flushpos;
2772  TimestampTz now;
2773  bool have_pending_txes;
2774 
2775  /*
2776  * If the user doesn't want status to be reported to the publisher, be
2777  * sure to exit before doing anything at all.
2778  */
2779  if (!force && wal_receiver_status_interval <= 0)
2780  return;
2781 
2782  /* It's legal to not pass a recvpos */
2783  if (recvpos < last_recvpos)
2784  recvpos = last_recvpos;
2785 
2786  get_flush_position(&writepos, &flushpos, &have_pending_txes);
2787 
2788  /*
2789  * No outstanding transactions to flush, we can report the latest received
2790  * position. This is important for synchronous replication.
2791  */
2792  if (!have_pending_txes)
2793  flushpos = writepos = recvpos;
2794 
2795  if (writepos < last_writepos)
2796  writepos = last_writepos;
2797 
2798  if (flushpos < last_flushpos)
2799  flushpos = last_flushpos;
2800 
2801  now = GetCurrentTimestamp();
2802 
2803  /* if we've already reported everything we're good */
2804  if (!force &&
2805  writepos == last_writepos &&
2806  flushpos == last_flushpos &&
2807  !TimestampDifferenceExceeds(send_time, now,
2809  return;
2810  send_time = now;
2811 
2812  if (!reply_message)
2813  {
2815 
2816  reply_message = makeStringInfo();
2817  MemoryContextSwitchTo(oldctx);
2818  }
2819  else
2820  resetStringInfo(reply_message);
2821 
2822  pq_sendbyte(reply_message, 'r');
2823  pq_sendint64(reply_message, recvpos); /* write */
2824  pq_sendint64(reply_message, flushpos); /* flush */
2825  pq_sendint64(reply_message, writepos); /* apply */
2826  pq_sendint64(reply_message, now); /* sendTime */
2827  pq_sendbyte(reply_message, requestReply); /* replyRequested */
2828 
2829  elog(DEBUG2, "sending feedback (force %d) to recv %X/%X, write %X/%X, flush %X/%X",
2830  force,
2831  LSN_FORMAT_ARGS(recvpos),
2832  LSN_FORMAT_ARGS(writepos),
2833  LSN_FORMAT_ARGS(flushpos));
2834 
2836  reply_message->data, reply_message->len);
2837 
2838  if (recvpos > last_recvpos)
2839  last_recvpos = recvpos;
2840  if (writepos > last_writepos)
2841  last_writepos = writepos;
2842  if (flushpos > last_flushpos)
2843  last_flushpos = flushpos;
2844 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
WalReceiverConn * LogRepWorkerWalRcvConn
Definition: worker.c:245
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void pq_sendint64(StringInfo buf, uint64 i)
Definition: pqformat.h:153
int wal_receiver_status_interval
Definition: walreceiver.c:89
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
static void get_flush_position(XLogRecPtr *write, XLogRecPtr *flush, bool *have_pending_txes)
Definition: worker.c:2434
static void pq_sendbyte(StringInfo buf, uint8 byt)
Definition: pqformat.h:161
static StringInfoData reply_message
Definition: walreceiver.c:118
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define DEBUG2
Definition: elog.h:24
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
MemoryContext ApplyContext
Definition: worker.c:240
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define walrcv_send(conn, buffer, nbytes)
Definition: walreceiver.h:424
#define elog(elevel,...)
Definition: elog.h:232
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544

◆ set_apply_error_context_xact()

◆ should_apply_changes_for_rel()

static bool should_apply_changes_for_rel ( LogicalRepRelMapEntry rel)
static

Definition at line 352 of file worker.c.

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

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

353 {
354  if (am_tablesync_worker())
355  return MyLogicalRepWorker->relid == rel->localreloid;
356  else
357  return (rel->state == SUBREL_STATE_READY ||
358  (rel->state == SUBREL_STATE_SYNCDONE &&
359  rel->statelsn <= remote_final_lsn));
360 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:251
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
static bool am_tablesync_worker(void)

◆ slot_fill_defaults()

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

Definition at line 531 of file worker.c.

References Assert, attnum, AttrMap::attnums, LogicalRepRelMapEntry::attrmap, build_column_default(), ExecEvalExpr(), ExecInitExpr(), expression_planner(), GetPerTupleExprContext, i, LogicalRepRelMapEntry::localrel, AttrMap::maplen, TupleDescData::natts, LogicalRepRelation::natts, palloc(), RelationGetDescr, LogicalRepRelMapEntry::remoterel, TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, and TupleDescAttr.

Referenced by apply_handle_insert().

533 {
534  TupleDesc desc = RelationGetDescr(rel->localrel);
535  int num_phys_attrs = desc->natts;
536  int i;
537  int attnum,
538  num_defaults = 0;
539  int *defmap;
540  ExprState **defexprs;
541  ExprContext *econtext;
542 
543  econtext = GetPerTupleExprContext(estate);
544 
545  /* We got all the data via replication, no need to evaluate anything. */
546  if (num_phys_attrs == rel->remoterel.natts)
547  return;
548 
549  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
550  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
551 
552  Assert(rel->attrmap->maplen == num_phys_attrs);
553  for (attnum = 0; attnum < num_phys_attrs; attnum++)
554  {
555  Expr *defexpr;
556 
557  if (TupleDescAttr(desc, attnum)->attisdropped || TupleDescAttr(desc, attnum)->attgenerated)
558  continue;
559 
560  if (rel->attrmap->attnums[attnum] >= 0)
561  continue;
562 
563  defexpr = (Expr *) build_column_default(rel->localrel, attnum + 1);
564 
565  if (defexpr != NULL)
566  {
567  /* Run the expression through planner */
568  defexpr = expression_planner(defexpr);
569 
570  /* Initialize executable expression in copycontext */
571  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
572  defmap[num_defaults] = attnum;
573  num_defaults++;
574  }
575 
576  }
577 
578  for (i = 0; i < num_defaults; i++)
579  slot->tts_values[defmap[i]] =
580  ExecEvalExpr(defexprs[i], econtext, &slot->tts_isnull[defmap[i]]);
581 }
#define RelationGetDescr(relation)
Definition: rel.h:503
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Expr * expression_planner(Expr *expr)
Definition: planner.c:5807
int maplen
Definition: attmap.h:37
Datum * tts_values
Definition: tuptable.h:126
#define GetPerTupleExprContext(estate)
Definition: executor.h:533
LogicalRepRelation remoterel
bool * tts_isnull
Definition: tuptable.h:128
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:316
Node * build_column_default(Relation rel, int attrno)
int16 attnum
Definition: pg_attribute.h:83
#define Assert(condition)
Definition: c.h:804
AttrNumber * attnums
Definition: attmap.h:36
void * palloc(Size size)
Definition: mcxt.c:1062
int i
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:123

◆ slot_modify_data()

static void slot_modify_data ( TupleTableSlot slot,
TupleTableSlot srcslot,
LogicalRepRelMapEntry rel,
LogicalRepTupleData tupleData 
)
static

Definition at line 690 of file worker.c.

References Assert, AttrMap::attnums, LogicalRepRelMapEntry::attrmap, LogicalRepTupleData::colstatus, LogicalRepTupleData::colvalues, StringInfoData::cursor, StringInfoData::data, ereport, errcode(), errmsg(), ERROR, ExecClearTuple(), ExecStoreVirtualTuple(), getTypeBinaryInputInfo(), getTypeInputInfo(), i, StringInfoData::len, LOGICALREP_COLUMN_BINARY, LOGICALREP_COLUMN_TEXT, LOGICALREP_COLUMN_UNCHANGED, AttrMap::maplen, TupleDescData::natts, OidInputFunctionCall(), OidReceiveFunctionCall(), ApplyErrorCallbackArg::remote_attnum, slot_getallattrs(), TupleTableSlot::tts_isnull, TupleTableSlot::tts_tupleDescriptor, TupleTableSlot::tts_values, and TupleDescAttr.

Referenced by apply_handle_tuple_routing(), and apply_handle_update_internal().

693 {
694  int natts = slot->tts_tupleDescriptor->natts;
695  int i;
696 
697  /* We'll fill "slot" with a virtual tuple, so we must start with ... */
698  ExecClearTuple(slot);
699 
700  /*
701  * Copy all the column data from srcslot, so that we'll have valid values
702  * for unreplaced columns.
703  */
704  Assert(natts == srcslot->tts_tupleDescriptor->natts);
705  slot_getallattrs(srcslot);
706  memcpy(slot->tts_values, srcslot->tts_values, natts * sizeof(Datum));
707  memcpy(slot->tts_isnull, srcslot->tts_isnull, natts * sizeof(bool));
708 
709  /* Call the "in" function for each replaced attribute */
710  Assert(natts == rel->