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  SlotErrCallbackArg
 
struct  ApplyExecutionData
 
struct  StreamXidHash
 
struct  SubXactInfo
 
struct  ApplySubXactData
 

Macros

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

Typedefs

typedef struct FlushPosition FlushPosition
 
typedef struct SlotErrCallbackArg SlotErrCallbackArg
 
typedef struct ApplyExecutionData ApplyExecutionData
 
typedef struct StreamXidHash StreamXidHash
 
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 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_error_callback (void *arg)
 
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 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 HTABxidhash = NULL
 
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

◆ ApplyExecutionData

◆ ApplySubXactData

◆ FlushPosition

typedef struct FlushPosition FlushPosition

◆ SlotErrCallbackArg

◆ StreamXidHash

typedef struct StreamXidHash StreamXidHash

◆ SubXactInfo

typedef struct SubXactInfo SubXactInfo

Function Documentation

◆ apply_dispatch()

static void apply_dispatch ( StringInfo  s)
static

Definition at line 2328 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(), ereport, errcode(), errmsg_internal(), 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_END, LOGICAL_REP_MSG_STREAM_PREPARE, LOGICAL_REP_MSG_STREAM_START, LOGICAL_REP_MSG_TRUNCATE, LOGICAL_REP_MSG_TYPE, LOGICAL_REP_MSG_UPDATE, and pq_getmsgbyte().

Referenced by apply_spooled_messages(), and LogicalRepApplyLoop().

2329 {
2331 
2332  switch (action)
2333  {
2334  case LOGICAL_REP_MSG_BEGIN:
2335  apply_handle_begin(s);
2336  return;
2337 
2340  return;
2341 
2344  return;
2345 
2348  return;
2349 
2352  return;
2353 
2356  return;
2357 
2360  return;
2361 
2362  case LOGICAL_REP_MSG_TYPE:
2363  apply_handle_type(s);
2364  return;
2365 
2368  return;
2369 
2371 
2372  /*
2373  * Logical replication does not use generic logical messages yet.
2374  * Although, it could be used by other applications that use this
2375  * output plugin.
2376  */
2377  return;
2378 
2381  return;
2382 
2385  return;
2386 
2389  return;
2390 
2393  return;
2394 
2397  return;
2398 
2401  return;
2402 
2405  return;
2406 
2409  return;
2410 
2413  return;
2414  }
2415 
2416  ereport(ERROR,
2417  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2418  errmsg_internal("invalid logical replication message type \"%c\"",
2419  action)));
2420 }
static void apply_handle_type(StringInfo s)
Definition: worker.c:1534
static void apply_handle_insert(StringInfo s)
Definition: worker.c:1567
static void apply_handle_stream_abort(StringInfo s)
Definition: worker.c:1221
static void apply_handle_stream_start(StringInfo s)
Definition: worker.c:1129
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
static void apply_handle_prepare(StringInfo s)
Definition: worker.c:926
static void apply_handle_stream_stop(StringInfo s)
Definition: worker.c:1189
static void apply_handle_delete(StringInfo s)
Definition: worker.c:1844
static void apply_handle_stream_prepare(StringInfo s)
Definition: worker.c:1063
static void apply_handle_begin(StringInfo s)
Definition: worker.c:825
static void apply_handle_begin_prepare(StringInfo s)
Definition: worker.c:869
static void apply_handle_commit(StringInfo s)
Definition: worker.c:844
static void apply_handle_stream_commit(StringInfo s)
Definition: worker.c:1451
static void apply_handle_update(StringInfo s)
Definition: worker.c:1684
static void apply_handle_relation(StringInfo s)
Definition: worker.c:1517
static void apply_handle_commit_prepared(StringInfo s)
Definition: worker.c:971
#define ereport(elevel,...)
Definition: elog.h:157
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static void apply_handle_origin(StringInfo s)
Definition: worker.c:1111
LogicalRepMsgType
Definition: logicalproto.h:51
static void apply_handle_rollback_prepared(StringInfo s)
Definition: worker.c:1010
static void apply_handle_truncate(StringInfo s)
Definition: worker.c:2213

◆ apply_handle_begin()

static void apply_handle_begin ( StringInfo  s)
static

Definition at line 825 of file worker.c.

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

Referenced by apply_dispatch().

826 {
827  LogicalRepBeginData begin_data;
828 
829  logicalrep_read_begin(s, &begin_data);
830 
831  remote_final_lsn = begin_data.final_lsn;
832 
833  in_remote_transaction = true;
834 
836 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:250
void logicalrep_read_begin(StringInfo in, LogicalRepBeginData *begin_data)
Definition: proto.c:60
bool in_remote_transaction
Definition: worker.c:249
XLogRecPtr final_lsn
Definition: logicalproto.h:123
void pgstat_report_activity(BackendState state, const char *cmd_str)

◆ apply_handle_begin_prepare()

static void apply_handle_begin_prepare ( StringInfo  s)
static

Definition at line 869 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, remote_final_lsn, and STATE_RUNNING.

Referenced by apply_dispatch().

870 {
871  LogicalRepPreparedTxnData begin_data;
872 
873  /* Tablesync should never receive prepare. */
874  if (am_tablesync_worker())
875  ereport(ERROR,
876  (errcode(ERRCODE_PROTOCOL_VIOLATION),
877  errmsg_internal("tablesync worker received a BEGIN PREPARE message")));
878 
879  logicalrep_read_begin_prepare(s, &begin_data);
880 
881  remote_final_lsn = begin_data.prepare_lsn;
882 
883  in_remote_transaction = true;
884 
886 }
void logicalrep_read_begin_prepare(StringInfo in, LogicalRepPreparedTxnData *begin_data)
Definition: proto.c:131
static XLogRecPtr remote_final_lsn
Definition: worker.c:250
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:249
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)

◆ apply_handle_commit()

static void apply_handle_commit ( StringInfo  s)
static

Definition at line 844 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, and STATE_IDLE.

Referenced by apply_dispatch().

845 {
846  LogicalRepCommitData commit_data;
847 
848  logicalrep_read_commit(s, &commit_data);
849 
850  if (commit_data.commit_lsn != remote_final_lsn)
851  ereport(ERROR,
852  (errcode(ERRCODE_PROTOCOL_VIOLATION),
853  errmsg_internal("incorrect commit LSN %X/%X in commit message (expected %X/%X)",
854  LSN_FORMAT_ARGS(commit_data.commit_lsn),
856 
857  apply_handle_commit_internal(&commit_data);
858 
859  /* Process any tables that are being synchronized in parallel. */
860  process_syncing_tables(commit_data.end_lsn);
861 
863 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:250
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
int errcode(int sqlerrcode)
Definition: elog.c:698
#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:1482
#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 1482 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().

1483 {
1484  if (IsTransactionState())
1485  {
1486  /*
1487  * Update origin state so we can restart streaming from correct
1488  * position in case of crash.
1489  */
1490  replorigin_session_origin_lsn = commit_data->end_lsn;
1492 
1494  pgstat_report_stat(false);
1495 
1496  store_flush_position(commit_data->end_lsn);
1497  }
1498  else
1499  {
1500  /* Process any invalidation messages that might have accumulated. */
1503  }
1504 
1505  in_remote_transaction = false;
1506 }
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2480
void AcceptInvalidationMessages(void)
Definition: inval.c:688
void CommitTransactionCommand(void)
Definition: xact.c:2939
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:843
bool in_remote_transaction
Definition: worker.c:249
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:2840
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 971 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, STATE_IDLE, store_flush_position(), TwoPhaseTransactionGid(), and LogicalRepCommitPreparedTxnData::xid.

Referenced by apply_dispatch().

972 {
973  LogicalRepCommitPreparedTxnData prepare_data;
974  char gid[GIDSIZE];
975 
976  logicalrep_read_commit_prepared(s, &prepare_data);
977 
978  /* Compute GID for two_phase transactions. */
980  gid, sizeof(gid));
981 
982  /* There is no transaction when COMMIT PREPARED is called */
984 
985  /*
986  * Update origin state so we can restart streaming from correct position
987  * in case of crash.
988  */
989  replorigin_session_origin_lsn = prepare_data.end_lsn;
991 
992  FinishPreparedTransaction(gid, true);
995  pgstat_report_stat(false);
996 
997  store_flush_position(prepare_data.end_lsn);
998  in_remote_transaction = false;
999 
1000  /* Process any tables that are being synchronized in parallel. */
1001  process_syncing_tables(prepare_data.end_lsn);
1002 
1004 }
Subscription * MySubscription
Definition: worker.c:246
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2480
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
void CommitTransactionCommand(void)
Definition: xact.c:2939
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:843
bool in_remote_transaction
Definition: worker.c:249
#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:3403

◆ apply_handle_delete()

static void apply_handle_delete ( StringInfo  s)
static

Definition at line 1844 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, RelationGetDescr, RowExclusiveLock, should_apply_changes_for_rel(), slot_store_data(), ApplyExecutionData::targetRelInfo, and TTSOpsVirtual.

Referenced by apply_dispatch().

1845 {
1846  LogicalRepRelMapEntry *rel;
1847  LogicalRepTupleData oldtup;
1848  LogicalRepRelId relid;
1849  ApplyExecutionData *edata;
1850  EState *estate;
1851  TupleTableSlot *remoteslot;
1852  MemoryContext oldctx;
1853 
1855  return;
1856 
1858 
1859  relid = logicalrep_read_delete(s, &oldtup);
1860  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1861  if (!should_apply_changes_for_rel(rel))
1862  {
1863  /*
1864  * The relation can't become interesting in the middle of the
1865  * transaction so it's safe to unlock it.
1866  */
1869  return;
1870  }
1871 
1872  /* Check if we can do the delete. */
1874 
1875  /* Initialize the executor state. */
1876  edata = create_edata_for_relation(rel);
1877  estate = edata->estate;
1878  remoteslot = ExecInitExtraTupleSlot(estate,
1879  RelationGetDescr(rel->localrel),
1880  &TTSOpsVirtual);
1881 
1882  /* Build the search tuple. */
1884  slot_store_data(remoteslot, rel, &oldtup);
1885  MemoryContextSwitchTo(oldctx);
1886 
1887  /* For a partitioned table, apply delete to correct partition. */
1888  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1890  remoteslot, NULL, CMD_DELETE);
1891  else
1893  remoteslot);
1894 
1895  finish_edata(edata);
1896 
1898 
1900 }
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:1989
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
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * targetRelInfo
Definition: worker.c:217
#define RowExclusiveLock
Definition: lockdefs.h:38
EState * estate
Definition: worker.c:214
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:1650
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:1908
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:609
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 1908 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().

1911 {
1912  EState *estate = edata->estate;
1913  Relation localrel = relinfo->ri_RelationDesc;
1914  LogicalRepRelation *remoterel = &edata->targetRel->remoterel;
1915  EPQState epqstate;
1916  TupleTableSlot *localslot;
1917  bool found;
1918 
1919  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
1920  ExecOpenIndices(relinfo, false);
1921 
1922  found = FindReplTupleInLocalRel(estate, localrel, remoterel,
1923  remoteslot, &localslot);
1924 
1925  /* If found delete it. */
1926  if (found)
1927  {
1928  EvalPlanQualSetSlot(&epqstate, localslot);
1929 
1930  /* Do the actual delete. */
1931  ExecSimpleRelationDelete(relinfo, estate, &epqstate, localslot);
1932  }
1933  else
1934  {
1935  /*
1936  * The tuple to be deleted could not be found. Do nothing except for
1937  * emitting a log message.
1938  *
1939  * XXX should this be promoted to ereport(LOG) perhaps?
1940  */
1941  elog(DEBUG1,
1942  "logical replication did not find row to be deleted "
1943  "in replication target relation \"%s\"",
1944  RelationGetRelationName(localrel));
1945  }
1946 
1947  /* Cleanup. */
1948  ExecCloseIndices(relinfo);
1949  EvalPlanQualEnd(&epqstate);
1950 }
#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:216
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:214
#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:1960
#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 1567 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, RelationGetDescr, RowExclusiveLock, should_apply_changes_for_rel(), slot_fill_defaults(), slot_store_data(), ApplyExecutionData::targetRelInfo, and TTSOpsVirtual.

Referenced by apply_dispatch().

1568 {
1569  LogicalRepRelMapEntry *rel;
1570  LogicalRepTupleData newtup;
1571  LogicalRepRelId relid;
1572  ApplyExecutionData *edata;
1573  EState *estate;
1574  TupleTableSlot *remoteslot;
1575  MemoryContext oldctx;
1576 
1578  return;
1579 
1581 
1582  relid = logicalrep_read_insert(s, &newtup);
1583  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1584  if (!should_apply_changes_for_rel(rel))
1585  {
1586  /*
1587  * The relation can't become interesting in the middle of the
1588  * transaction so it's safe to unlock it.
1589  */
1592  return;
1593  }
1594 
1595  /* Initialize the executor state. */
1596  edata = create_edata_for_relation(rel);
1597  estate = edata->estate;
1598  remoteslot = ExecInitExtraTupleSlot(estate,
1599  RelationGetDescr(rel->localrel),
1600  &TTSOpsVirtual);
1601 
1602  /* Process and store remote tuple in the slot */
1604  slot_store_data(remoteslot, rel, &newtup);
1605  slot_fill_defaults(rel, estate, remoteslot);
1606  MemoryContextSwitchTo(oldctx);
1607 
1608  /* For a partitioned table, insert the tuple into a partition. */
1609  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1611  remoteslot, NULL, CMD_INSERT);
1612  else
1614  remoteslot);
1615 
1616  finish_edata(edata);
1617 
1619 
1621 }
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:1989
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 void apply_handle_insert_internal(ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot)
Definition: worker.c:1629
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * targetRelInfo
Definition: worker.c:217
#define RowExclusiveLock
Definition: lockdefs.h:38
EState * estate
Definition: worker.c:214
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
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:609
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 1629 of file worker.c.

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

Referenced by apply_handle_insert(), and apply_handle_tuple_routing().

1632 {
1633  EState *estate = edata->estate;
1634 
1635  /* We must open indexes here. */
1636  ExecOpenIndices(relinfo, false);
1637 
1638  /* Do the insert. */
1639  ExecSimpleRelationInsert(relinfo, estate, remoteslot);
1640 
1641  /* Cleanup. */
1642  ExecCloseIndices(relinfo);
1643 }
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
EState * estate
Definition: worker.c:214
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 1111 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().

1112 {
1113  /*
1114  * ORIGIN message can only come inside streaming transaction or inside
1115  * remote transaction and before any actual writes.
1116  */
1117  if (!in_streamed_transaction &&
1120  ereport(ERROR,
1121  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1122  errmsg_internal("ORIGIN message sent out of order")));
1123 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:249
static bool in_streamed_transaction
Definition: worker.c:253
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 926 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, STATE_IDLE, and store_flush_position().

Referenced by apply_dispatch().

927 {
928  LogicalRepPreparedTxnData prepare_data;
929 
930  logicalrep_read_prepare(s, &prepare_data);
931 
932  if (prepare_data.prepare_lsn != remote_final_lsn)
933  ereport(ERROR,
934  (errcode(ERRCODE_PROTOCOL_VIOLATION),
935  errmsg_internal("incorrect prepare LSN %X/%X in prepare message (expected %X/%X)",
936  LSN_FORMAT_ARGS(prepare_data.prepare_lsn),
938 
939  /*
940  * Unlike commit, here, we always prepare the transaction even though no
941  * change has happened in this transaction. It is done this way because at
942  * commit prepared time, we won't know whether we have skipped preparing a
943  * transaction because of no change.
944  *
945  * XXX, We can optimize such that at commit prepared time, we first check
946  * whether we have prepared the transaction or not but that doesn't seem
947  * worthwhile because such cases shouldn't be common.
948  */
950 
951  apply_handle_prepare_internal(&prepare_data);
952 
955  pgstat_report_stat(false);
956 
957  store_flush_position(prepare_data.end_lsn);
958 
959  in_remote_transaction = false;
960 
961  /* Process any tables that are being synchronized in parallel. */
962  process_syncing_tables(prepare_data.end_lsn);
963 
965 }
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2480
static XLogRecPtr remote_final_lsn
Definition: worker.c:250
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
void CommitTransactionCommand(void)
Definition: xact.c:2939
int errcode(int sqlerrcode)
Definition: elog.c:698
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:843
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:249
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:892

◆ apply_handle_prepare_internal()

static void apply_handle_prepare_internal ( LogicalRepPreparedTxnData prepare_data)
static

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

893 {
894  char gid[GIDSIZE];
895 
896  /*
897  * Compute unique GID for two_phase transactions. We don't use GID of
898  * prepared transaction sent by server as that can lead to deadlock when
899  * we have multiple subscriptions from same node point to publications on
900  * the same node. See comments atop worker.c
901  */
903  gid, sizeof(gid));
904 
905  /*
906  * BeginTransactionBlock is necessary to balance the EndTransactionBlock
907  * called within the PrepareTransactionBlock below.
908  */
910  CommitTransactionCommand(); /* Completes the preceding Begin command. */
911 
912  /*
913  * Update origin state so we can restart streaming from correct position
914  * in case of crash.
915  */
916  replorigin_session_origin_lsn = prepare_data->end_lsn;
918 
920 }
Subscription * MySubscription
Definition: worker.c:246
void CommitTransactionCommand(void)
Definition: xact.c:2939
bool PrepareTransactionBlock(const char *gid)
Definition: xact.c:3705
#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:3637
static void TwoPhaseTransactionGid(Oid subid, TransactionId xid, char *gid, int szgid)
Definition: worker.c:3403

◆ apply_handle_relation()

static void apply_handle_relation ( StringInfo  s)
static

Definition at line 1517 of file worker.c.

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

Referenced by apply_dispatch().

1518 {
1519  LogicalRepRelation *rel;
1520 
1522  return;
1523 
1524  rel = logicalrep_read_rel(s);
1526 }
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 1010 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, LogicalRepRollbackPreparedTxnData::rollback_end_lsn, LogicalRepRollbackPreparedTxnData::rollback_time, STATE_IDLE, store_flush_position(), TwoPhaseTransactionGid(), and LogicalRepRollbackPreparedTxnData::xid.

Referenced by apply_dispatch().

1011 {
1012  LogicalRepRollbackPreparedTxnData rollback_data;
1013  char gid[GIDSIZE];
1014 
1015  logicalrep_read_rollback_prepared(s, &rollback_data);
1016 
1017  /* Compute GID for two_phase transactions. */
1018  TwoPhaseTransactionGid(MySubscription->oid, rollback_data.xid,
1019  gid, sizeof(gid));
1020 
1021  /*
1022  * It is possible that we haven't received prepare because it occurred
1023  * before walsender reached a consistent point or the two_phase was still
1024  * not enabled by that time, so in such cases, we need to skip rollback
1025  * prepared.
1026  */
1027  if (LookupGXact(gid, rollback_data.prepare_end_lsn,
1028  rollback_data.prepare_time))
1029  {
1030  /*
1031  * Update origin state so we can restart streaming from correct
1032  * position in case of crash.
1033  */
1036 
1037  /* There is no transaction when ABORT/ROLLBACK PREPARED is called */
1039  FinishPreparedTransaction(gid, false);
1042  }
1043 
1044  pgstat_report_stat(false);
1045 
1046  store_flush_position(rollback_data.rollback_end_lsn);
1047  in_remote_transaction = false;
1048 
1049  /* Process any tables that are being synchronized in parallel. */
1051 
1053 }
Subscription * MySubscription
Definition: worker.c:246
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2480
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
void CommitTransactionCommand(void)
Definition: xact.c:2939
bool LookupGXact(const char *gid, XLogRecPtr prepare_end_lsn, TimestampTz origin_prepare_timestamp)
Definition: twophase.c:2478
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:843
bool in_remote_transaction
Definition: worker.c:249
#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:3403

◆ apply_handle_stream_abort()

static void apply_handle_stream_abort ( StringInfo  s)
static

Definition at line 1221 of file worker.c.

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

Referenced by apply_dispatch().

1222 {
1223  TransactionId xid;
1224  TransactionId subxid;
1225 
1227  ereport(ERROR,
1228  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1229  errmsg_internal("STREAM ABORT message without STREAM STOP")));
1230 
1231  logicalrep_read_stream_abort(s, &xid, &subxid);
1232 
1233  /*
1234  * If the two XIDs are the same, it's in fact abort of toplevel xact, so
1235  * just delete the files with serialized info.
1236  */
1237  if (xid == subxid)
1239  else
1240  {
1241  /*
1242  * OK, so it's a subxact. We need to read the subxact file for the
1243  * toplevel transaction, determine the offset tracked for the subxact,
1244  * and truncate the file with changes. We also remove the subxacts
1245  * with higher offsets (or rather higher XIDs).
1246  *
1247  * We intentionally scan the array from the tail, because we're likely
1248  * aborting a change for the most recent subtransactions.
1249  *
1250  * We can't use the binary search here as subxact XIDs won't
1251  * necessarily arrive in sorted order, consider the case where we have
1252  * released the savepoint for multiple subtransactions and then
1253  * performed rollback to savepoint for one of the earlier
1254  * sub-transaction.
1255  */
1256  int64 i;
1257  int64 subidx;
1258  BufFile *fd;
1259  bool found = false;
1260  char path[MAXPGPATH];
1261  StreamXidHash *ent;
1262 
1263  subidx = -1;
1266 
1267  for (i = subxact_data.nsubxacts; i > 0; i--)
1268  {
1269  if (subxact_data.subxacts[i - 1].xid == subxid)
1270  {
1271  subidx = (i - 1);
1272  found = true;
1273  break;
1274  }
1275  }
1276 
1277  /*
1278  * If it's an empty sub-transaction then we will not find the subxid
1279  * here so just cleanup the subxact info and return.
1280  */
1281  if (!found)
1282  {
1283  /* Cleanup the subxact info */
1287  return;
1288  }
1289 
1290  ent = (StreamXidHash *) hash_search(xidhash,
1291  (void *) &xid,
1292  HASH_FIND,
1293  NULL);
1294  if (!ent)
1295  ereport(ERROR,
1296  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1297  errmsg_internal("transaction %u not found in stream XID hash table",
1298  xid)));
1299 
1300  /* open the changes file */
1302  fd = BufFileOpenShared(ent->stream_fileset, path, O_RDWR);
1303 
1304  /* OK, truncate the file at the right offset */
1306  subxact_data.subxacts[subidx].offset);
1307  BufFileClose(fd);
1308 
1309  /* discard the subxacts added later */
1310  subxact_data.nsubxacts = subidx;
1311 
1312  /* write the updated subxact list */
1314 
1317  }
1318 }
static void subxact_info_read(Oid subid, TransactionId xid)
Definition: worker.c:3033
int fileno
Definition: worker.c:269
uint32 TransactionId
Definition: c.h:587
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:3191
void CommitTransactionCommand(void)
Definition: xact.c:2939
void BufFileTruncateShared(BufFile *file, int fileno, off_t offset)
Definition: buffile.c:861
int errcode(int sqlerrcode)
Definition: elog.c:698
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
static int fd(const char *x, int i)
Definition: preproc-init.c:105
uint32 nsubxacts
Definition: worker.c:276
void BufFileClose(BufFile *file)
Definition: buffile.c:395
SubXactInfo * subxacts
Definition: worker.c:279
static void stream_cleanup_files(Oid subid, TransactionId xid)
Definition: worker.c:3204
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
#define MAXPGPATH
static bool in_streamed_transaction
Definition: worker.c:253
SharedFileSet * stream_fileset
Definition: worker.c:234
BufFile * BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)
Definition: buffile.c:284
TransactionId xid
Definition: worker.c:268
static void begin_replication_step(void)
Definition: worker.c:370
#define ereport(elevel,...)
Definition: elog.h:157
static HTAB * xidhash
Definition: worker.c:261
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:270
static void subxact_info_write(Oid subid, TransactionId xid)
Definition: worker.c:2956
static ApplySubXactData subxact_data
Definition: worker.c:282
int i
static void cleanup_subxact_info(void)
Definition: worker.c:3386
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 1451 of file worker.c.

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

Referenced by apply_dispatch().

1452 {
1453  TransactionId xid;
1454  LogicalRepCommitData commit_data;
1455 
1457  ereport(ERROR,
1458  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1459  errmsg_internal("STREAM COMMIT message without STREAM STOP")));
1460 
1461  xid = logicalrep_read_stream_commit(s, &commit_data);
1462 
1463  elog(DEBUG1, "received commit for streamed transaction %u", xid);
1464 
1465  apply_spooled_messages(xid, commit_data.commit_lsn);
1466 
1467  apply_handle_commit_internal(&commit_data);
1468 
1469  /* unlink the files with serialized changes and subxact info */
1471 
1472  /* Process any tables that are being synchronized in parallel. */
1473  process_syncing_tables(commit_data.end_lsn);
1474 
1476 }
#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 stream_cleanup_files(Oid subid, TransactionId xid)
Definition: worker.c:3204
static void apply_spooled_messages(TransactionId xid, XLogRecPtr lsn)
Definition: worker.c:1324
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
static bool in_streamed_transaction
Definition: worker.c:253
static void apply_handle_commit_internal(LogicalRepCommitData *commit_data)
Definition: worker.c:1482
#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

◆ apply_handle_stream_prepare()

static void apply_handle_stream_prepare ( StringInfo  s)
static

Definition at line 1063 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, process_syncing_tables(), STATE_IDLE, store_flush_position(), stream_cleanup_files(), LogicalRepWorker::subid, and LogicalRepPreparedTxnData::xid.

Referenced by apply_dispatch().

1064 {
1065  LogicalRepPreparedTxnData prepare_data;
1066 
1068  ereport(ERROR,
1069  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1070  errmsg_internal("STREAM PREPARE message without STREAM STOP")));
1071 
1072  /* Tablesync should never receive prepare. */
1073  if (am_tablesync_worker())
1074  ereport(ERROR,
1075  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1076  errmsg_internal("tablesync worker received a STREAM PREPARE message")));
1077 
1078  logicalrep_read_stream_prepare(s, &prepare_data);
1079 
1080  elog(DEBUG1, "received prepare for streamed transaction %u", prepare_data.xid);
1081 
1082  /* Replay all the spooled operations. */
1083  apply_spooled_messages(prepare_data.xid, prepare_data.prepare_lsn);
1084 
1085  /* Mark the transaction as prepared. */
1086  apply_handle_prepare_internal(&prepare_data);
1087 
1089 
1090  pgstat_report_stat(false);
1091 
1092  store_flush_position(prepare_data.end_lsn);
1093 
1094  in_remote_transaction = false;
1095 
1096  /* unlink the files with serialized changes and subxact info. */
1098 
1099  /* Process any tables that are being synchronized in parallel. */
1100  process_syncing_tables(prepare_data.end_lsn);
1101 
1103 }
#define DEBUG1
Definition: elog.h:25
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2480
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
void CommitTransactionCommand(void)
Definition: xact.c:2939
int errcode(int sqlerrcode)
Definition: elog.c:698
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:843
static void stream_cleanup_files(Oid subid, TransactionId xid)
Definition: worker.c:3204
static void apply_spooled_messages(TransactionId xid, XLogRecPtr lsn)
Definition: worker.c:1324
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:249
static bool in_streamed_transaction
Definition: worker.c:253
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 apply_handle_prepare_internal(LogicalRepPreparedTxnData *prepare_data)
Definition: worker.c:892

◆ apply_handle_stream_start()

static void apply_handle_stream_start ( StringInfo  s)
static

Definition at line 1129 of file worker.c.

References ApplyContext, begin_replication_step(), end_replication_step(), HASHCTL::entrysize, ereport, errcode(), errmsg_internal(), ERROR, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASHCTL::hcxt, in_streamed_transaction, HASHCTL::keysize, logicalrep_read_stream_start(), MyLogicalRepWorker, pgstat_report_activity(), STATE_RUNNING, stream_open_file(), stream_xid, LogicalRepWorker::subid, subxact_info_read(), and TransactionIdIsValid.

Referenced by apply_dispatch().

1130 {
1131  bool first_segment;
1132  HASHCTL hash_ctl;
1133 
1135  ereport(ERROR,
1136  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1137  errmsg_internal("duplicate STREAM START message")));
1138 
1139  /*
1140  * Start a transaction on stream start, this transaction will be committed
1141  * on the stream stop unless it is a tablesync worker in which case it
1142  * will be committed after processing all the messages. We need the
1143  * transaction for handling the buffile, used for serializing the
1144  * streaming data and subxact info.
1145  */
1147 
1148  /* notify handle methods we're processing a remote transaction */
1149  in_streamed_transaction = true;
1150 
1151  /* extract XID of the top-level transaction */
1152  stream_xid = logicalrep_read_stream_start(s, &first_segment);
1153 
1155  ereport(ERROR,
1156  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1157  errmsg_internal("invalid transaction ID in streamed replication transaction")));
1158 
1159  /*
1160  * Initialize the xidhash table if we haven't yet. This will be used for
1161  * the entire duration of the apply worker so create it in permanent
1162  * context.
1163  */
1164  if (xidhash == NULL)
1165  {
1166  hash_ctl.keysize = sizeof(TransactionId);
1167  hash_ctl.entrysize = sizeof(StreamXidHash);
1168  hash_ctl.hcxt = ApplyContext;
1169  xidhash = hash_create("StreamXidHash", 1024, &hash_ctl,
1171  }
1172 
1173  /* open the spool file for this transaction */
1175 
1176  /* if this is not the first segment, open existing subxact file */
1177  if (!first_segment)
1179 
1181 
1183 }
static void subxact_info_read(Oid subid, TransactionId xid)
Definition: worker.c:3033
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
uint32 TransactionId
Definition: c.h:587
MemoryContext hcxt
Definition: hsearch.h:86
Size entrysize
Definition: hsearch.h:76
int errcode(int sqlerrcode)
Definition: elog.c:698
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
static bool in_streamed_transaction
Definition: worker.c:253
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
MemoryContext ApplyContext
Definition: worker.c:239
#define HASH_BLOBS
Definition: hsearch.h:97
static void begin_replication_step(void)
Definition: worker.c:370
Size keysize
Definition: hsearch.h:75
#define ereport(elevel,...)
Definition: elog.h:157
static HTAB * xidhash
Definition: worker.c:261
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 pgstat_report_activity(BackendState state, const char *cmd_str)
static void stream_open_file(Oid subid, TransactionId xid, bool first)
Definition: worker.c:3253
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static TransactionId stream_xid
Definition: worker.c:255
struct StreamXidHash StreamXidHash

◆ apply_handle_stream_stop()

static void apply_handle_stream_stop ( StringInfo  s)
static

Definition at line 1189 of file worker.c.

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

Referenced by apply_dispatch().

1190 {
1192  ereport(ERROR,
1193  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1194  errmsg_internal("STREAM STOP message without STREAM START")));
1195 
1196  /*
1197  * Close the file with serialized changes, and serialize information about
1198  * subxacts for the toplevel transaction.
1199  */
1202 
1203  /* We must be in a valid transaction state */
1205 
1206  /* Commit the per-stream transaction */
1208 
1209  in_streamed_transaction = false;
1210 
1211  /* Reset per-stream context */
1213 
1215 }
static void stream_close_file(void)
Definition: worker.c:3338
void CommitTransactionCommand(void)
Definition: xact.c:2939
int errcode(int sqlerrcode)
Definition: elog.c:698
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:253
#define ereport(elevel,...)
Definition: elog.h:157
static MemoryContext LogicalStreamingContext
Definition: worker.c:242
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:2956
void pgstat_report_activity(BackendState state, const char *cmd_str)
static TransactionId stream_xid
Definition: worker.c:255

◆ apply_handle_truncate()

static void apply_handle_truncate ( StringInfo  s)
static

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

2214 {
2215  bool cascade = false;
2216  bool restart_seqs = false;
2217  List *remote_relids = NIL;
2218  List *remote_rels = NIL;
2219  List *rels = NIL;
2220  List *part_rels = NIL;
2221  List *relids = NIL;
2222  List *relids_logged = NIL;
2223  ListCell *lc;
2224  LOCKMODE lockmode = AccessExclusiveLock;
2225 
2227  return;
2228 
2230 
2231  remote_relids = logicalrep_read_truncate(s, &cascade, &restart_seqs);
2232 
2233  foreach(lc, remote_relids)
2234  {
2235  LogicalRepRelId relid = lfirst_oid(lc);
2236  LogicalRepRelMapEntry *rel;
2237 
2238  rel = logicalrep_rel_open(relid, lockmode);
2239  if (!should_apply_changes_for_rel(rel))
2240  {
2241  /*
2242  * The relation can't become interesting in the middle of the
2243  * transaction so it's safe to unlock it.
2244  */
2245  logicalrep_rel_close(rel, lockmode);
2246  continue;
2247  }
2248 
2249  remote_rels = lappend(remote_rels, rel);
2250  rels = lappend(rels, rel->localrel);
2251  relids = lappend_oid(relids, rel->localreloid);
2253  relids_logged = lappend_oid(relids_logged, rel->localreloid);
2254 
2255  /*
2256  * Truncate partitions if we got a message to truncate a partitioned
2257  * table.
2258  */
2259  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2260  {
2261  ListCell *child;
2262  List *children = find_all_inheritors(rel->localreloid,
2263  lockmode,
2264  NULL);
2265 
2266  foreach(child, children)
2267  {
2268  Oid childrelid = lfirst_oid(child);
2269  Relation childrel;
2270 
2271  if (list_member_oid(relids, childrelid))
2272  continue;
2273 
2274  /* find_all_inheritors already got lock */
2275  childrel = table_open(childrelid, NoLock);
2276 
2277  /*
2278  * Ignore temp tables of other backends. See similar code in
2279  * ExecuteTruncate().
2280  */
2281  if (RELATION_IS_OTHER_TEMP(childrel))
2282  {
2283  table_close(childrel, lockmode);
2284  continue;
2285  }
2286 
2287  rels = lappend(rels, childrel);
2288  part_rels = lappend(part_rels, childrel);
2289  relids = lappend_oid(relids, childrelid);
2290  /* Log this relation only if needed for logical decoding */
2291  if (RelationIsLogicallyLogged(childrel))
2292  relids_logged = lappend_oid(relids_logged, childrelid);
2293  }
2294  }
2295  }
2296 
2297  /*
2298  * Even if we used CASCADE on the upstream primary we explicitly default
2299  * to replaying changes without further cascading. This might be later
2300  * changeable with a user specified option.
2301  */
2302  ExecuteTruncateGuts(rels,
2303  relids,
2304  relids_logged,
2305  DROP_RESTRICT,
2306  restart_seqs);
2307  foreach(lc, remote_rels)
2308  {
2309  LogicalRepRelMapEntry *rel = lfirst(lc);
2310 
2312  }
2313  foreach(lc, part_rels)
2314  {
2315  Relation rel = lfirst(lc);
2316 
2317  table_close(rel, NoLock);
2318  }
2319 
2321 }
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:1736
#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 1989 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().

1993 {
1994  EState *estate = edata->estate;
1995  LogicalRepRelMapEntry *relmapentry = edata->targetRel;
1996  ResultRelInfo *relinfo = edata->targetRelInfo;
1997  Relation parentrel = relinfo->ri_RelationDesc;
1998  ModifyTableState *mtstate;
1999  PartitionTupleRouting *proute;
2000  ResultRelInfo *partrelinfo;
2001  Relation partrel;
2002  TupleTableSlot *remoteslot_part;
2003  TupleConversionMap *map;
2004  MemoryContext oldctx;
2005 
2006  /* ModifyTableState is needed for ExecFindPartition(). */
2007  edata->mtstate = mtstate = makeNode(ModifyTableState);
2008  mtstate->ps.plan = NULL;
2009  mtstate->ps.state = estate;
2010  mtstate->operation = operation;
2011  mtstate->resultRelInfo = relinfo;
2012 
2013  /* ... as is PartitionTupleRouting. */
2014  edata->proute = proute = ExecSetupPartitionTupleRouting(estate, parentrel);
2015 
2016  /*
2017  * Find the partition to which the "search tuple" belongs.
2018  */
2019  Assert(remoteslot != NULL);
2021  partrelinfo = ExecFindPartition(mtstate, relinfo, proute,
2022  remoteslot, estate);
2023  Assert(partrelinfo != NULL);
2024  partrel = partrelinfo->ri_RelationDesc;
2025 
2026  /*
2027  * To perform any of the operations below, the tuple must match the
2028  * partition's rowtype. Convert if needed or just copy, using a dedicated
2029  * slot to store the tuple in any case.
2030  */
2031  remoteslot_part = partrelinfo->ri_PartitionTupleSlot;
2032  if (remoteslot_part == NULL)
2033  remoteslot_part = table_slot_create(partrel, &estate->es_tupleTable);
2034  map = partrelinfo->ri_RootToPartitionMap;
2035  if (map != NULL)
2036  remoteslot_part = execute_attr_map_slot(map->attrMap, remoteslot,
2037  remoteslot_part);
2038  else
2039  {
2040  remoteslot_part = ExecCopySlot(remoteslot_part, remoteslot);
2041  slot_getallattrs(remoteslot_part);
2042  }
2043  MemoryContextSwitchTo(oldctx);
2044 
2045  switch (operation)
2046  {
2047  case CMD_INSERT:
2048  apply_handle_insert_internal(edata, partrelinfo,
2049  remoteslot_part);
2050  break;
2051 
2052  case CMD_DELETE:
2053  apply_handle_delete_internal(edata, partrelinfo,
2054  remoteslot_part);
2055  break;
2056 
2057  case CMD_UPDATE:
2058 
2059  /*
2060  * For UPDATE, depending on whether or not the updated tuple
2061  * satisfies the partition's constraint, perform a simple UPDATE
2062  * of the partition or move the updated tuple into a different
2063  * suitable partition.
2064  */
2065  {
2066  AttrMap *attrmap = map ? map->attrMap : NULL;
2067  LogicalRepRelMapEntry *part_entry;
2068  TupleTableSlot *localslot;
2069  ResultRelInfo *partrelinfo_new;
2070  bool found;
2071 
2072  part_entry = logicalrep_partition_open(relmapentry, partrel,
2073  attrmap);
2074 
2075  /* Get the matching local tuple from the partition. */
2076  found = FindReplTupleInLocalRel(estate, partrel,
2077  &part_entry->remoterel,
2078  remoteslot_part, &localslot);
2079  if (!found)
2080  {
2081  /*
2082  * The tuple to be updated could not be found. Do nothing
2083  * except for emitting a log message.
2084  *
2085  * XXX should this be promoted to ereport(LOG) perhaps?
2086  */
2087  elog(DEBUG1,
2088  "logical replication did not find row to be updated "
2089  "in replication target relation's partition \"%s\"",
2090  RelationGetRelationName(partrel));
2091  return;
2092  }
2093 
2094  /*
2095  * Apply the update to the local tuple, putting the result in
2096  * remoteslot_part.
2097  */
2099  slot_modify_data(remoteslot_part, localslot, part_entry,
2100  newtup);
2101  MemoryContextSwitchTo(oldctx);
2102 
2103  /*
2104  * Does the updated tuple still satisfy the current
2105  * partition's constraint?
2106  */
2107  if (!partrel->rd_rel->relispartition ||
2108  ExecPartitionCheck(partrelinfo, remoteslot_part, estate,
2109  false))
2110  {
2111  /*
2112  * Yes, so simply UPDATE the partition. We don't call
2113  * apply_handle_update_internal() here, which would
2114  * normally do the following work, to avoid repeating some
2115  * work already done above to find the local tuple in the
2116  * partition.
2117  */
2118  EPQState epqstate;
2119 
2120  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
2121  ExecOpenIndices(partrelinfo, false);
2122 
2123  EvalPlanQualSetSlot(&epqstate, remoteslot_part);
2124  ExecSimpleRelationUpdate(partrelinfo, estate, &epqstate,
2125  localslot, remoteslot_part);
2126  ExecCloseIndices(partrelinfo);
2127  EvalPlanQualEnd(&epqstate);
2128  }
2129  else
2130  {
2131  /* Move the tuple into the new partition. */
2132 
2133  /*
2134  * New partition will be found using tuple routing, which
2135  * can only occur via the parent table. We might need to
2136  * convert the tuple to the parent's rowtype. Note that
2137  * this is the tuple found in the partition, not the
2138  * original search tuple received by this function.
2139  */
2140  if (map)
2141  {
2142  TupleConversionMap *PartitionToRootMap =
2144  RelationGetDescr(parentrel));
2145 
2146  remoteslot =
2147  execute_attr_map_slot(PartitionToRootMap->attrMap,
2148  remoteslot_part, remoteslot);
2149  }
2150  else
2151  {
2152  remoteslot = ExecCopySlot(remoteslot, remoteslot_part);
2153  slot_getallattrs(remoteslot);
2154  }
2155 
2156 
2157  /* Find the new partition. */
2159  partrelinfo_new = ExecFindPartition(mtstate, relinfo,
2160  proute, remoteslot,
2161  estate);
2162  MemoryContextSwitchTo(oldctx);
2163  Assert(partrelinfo_new != partrelinfo);
2164 
2165  /* DELETE old tuple found in the old partition. */
2166  apply_handle_delete_internal(edata, partrelinfo,
2167  localslot);
2168 
2169  /* INSERT new tuple into the new partition. */
2170 
2171  /*
2172  * Convert the replacement tuple to match the destination
2173  * partition rowtype.
2174  */
2176  partrel = partrelinfo_new->ri_RelationDesc;
2177  remoteslot_part = partrelinfo_new->ri_PartitionTupleSlot;
2178  if (remoteslot_part == NULL)
2179  remoteslot_part = table_slot_create(partrel,
2180  &estate->es_tupleTable);
2181  map = partrelinfo_new->ri_RootToPartitionMap;
2182  if (map != NULL)
2183  {
2184  remoteslot_part = execute_attr_map_slot(map->attrMap,
2185  remoteslot,
2186  remoteslot_part);
2187  }
2188  else
2189  {
2190  remoteslot_part = ExecCopySlot(remoteslot_part,
2191  remoteslot);
2192  slot_getallattrs(remoteslot);
2193  }
2194  MemoryContextSwitchTo(oldctx);
2195  apply_handle_insert_internal(edata, partrelinfo_new,
2196  remoteslot_part);
2197  }
2198  }
2199  break;
2200 
2201  default:
2202  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
2203  break;
2204  }
2205 }
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:221
#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:216
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:220
#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:721
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:1629
ResultRelInfo * targetRelInfo
Definition: worker.c:217
EState * estate
Definition: worker.c:214
#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:1960
static void apply_handle_delete_internal(ApplyExecutionData *edata, ResultRelInfo *relinfo, TupleTableSlot *remoteslot)
Definition: worker.c:1908
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:587
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 1534 of file worker.c.

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

Referenced by apply_dispatch().

1535 {
1536  LogicalRepTyp typ;
1537 
1539  return;
1540 
1541  logicalrep_read_typ(s, &typ);
1542 }
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 1684 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, RelationGetDescr, RowExclusiveLock, should_apply_changes_for_rel(), slot_store_data(), ApplyExecutionData::targetRelInfo, TupleTableSlot::tts_tupleDescriptor, TTSOpsVirtual, TupleDescAttr, and RangeTblEntry::updatedCols.

Referenced by apply_dispatch().

1685 {
1686  LogicalRepRelMapEntry *rel;
1687  LogicalRepRelId relid;
1688  ApplyExecutionData *edata;
1689  EState *estate;
1690  LogicalRepTupleData oldtup;
1691  LogicalRepTupleData newtup;
1692  bool has_oldtup;
1693  TupleTableSlot *remoteslot;
1694  RangeTblEntry *target_rte;
1695  MemoryContext oldctx;
1696 
1698  return;
1699 
1701 
1702  relid = logicalrep_read_update(s, &has_oldtup, &oldtup,
1703  &newtup);
1704  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1705  if (!should_apply_changes_for_rel(rel))
1706  {
1707  /*
1708  * The relation can't become interesting in the middle of the
1709  * transaction so it's safe to unlock it.
1710  */
1713  return;
1714  }
1715 
1716  /* Check if we can do the update. */
1718 
1719  /* Initialize the executor state. */
1720  edata = create_edata_for_relation(rel);
1721  estate = edata->estate;
1722  remoteslot = ExecInitExtraTupleSlot(estate,
1723  RelationGetDescr(rel->localrel),
1724  &TTSOpsVirtual);
1725 
1726  /*
1727  * Populate updatedCols so that per-column triggers can fire, and so
1728  * executor can correctly pass down indexUnchanged hint. This could
1729  * include more columns than were actually changed on the publisher
1730  * because the logical replication protocol doesn't contain that
1731  * information. But it would for example exclude columns that only exist
1732  * on the subscriber, since we are not touching those.
1733  */
1734  target_rte = list_nth(estate->es_range_table, 0);
1735  for (int i = 0; i < remoteslot->tts_tupleDescriptor->natts; i++)
1736  {
1738  int remoteattnum = rel->attrmap->attnums[i];
1739 
1740  if (!att->attisdropped && remoteattnum >= 0)
1741  {
1742  Assert(remoteattnum < newtup.ncols);
1743  if (newtup.colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
1744  target_rte->updatedCols =
1745  bms_add_member(target_rte->updatedCols,
1747  }
1748  }
1749 
1750  /* Also populate extraUpdatedCols, in case we have generated columns */
1751  fill_extraUpdatedCols(target_rte, rel->localrel);
1752 
1753  /* Build the search tuple. */
1755  slot_store_data(remoteslot, rel,
1756  has_oldtup ? &oldtup : &newtup);
1757  MemoryContextSwitchTo(oldctx);
1758 
1759  /* For a partitioned table, apply update to correct partition. */
1760  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1762  remoteslot, &newtup, CMD_UPDATE);
1763  else
1765  remoteslot, &newtup);
1766 
1767  finish_edata(edata);
1768 
1770 
1772 }
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:1989
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:1780
#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 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:217
#define RowExclusiveLock
Definition: lockdefs.h:38
EState * estate
Definition: worker.c:214
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:1650
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
static void begin_replication_step(void)
Definition: worker.c:370
Bitmapset * updatedCols
Definition: parsenodes.h:1149
#define Assert(condition)
Definition: c.h:804
AttrNumber * attnums
Definition: attmap.h:36
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:609
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 1780 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().

1784 {
1785  EState *estate = edata->estate;
1786  LogicalRepRelMapEntry *relmapentry = edata->targetRel;
1787  Relation localrel = relinfo->ri_RelationDesc;
1788  EPQState epqstate;
1789  TupleTableSlot *localslot;
1790  bool found;
1791  MemoryContext oldctx;
1792 
1793  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
1794  ExecOpenIndices(relinfo, false);
1795 
1796  found = FindReplTupleInLocalRel(estate, localrel,
1797  &relmapentry->remoterel,
1798  remoteslot, &localslot);
1799  ExecClearTuple(remoteslot);
1800 
1801  /*
1802  * Tuple found.
1803  *
1804  * Note this will fail if there are other conflicting unique indexes.
1805  */
1806  if (found)
1807  {
1808  /* Process and store remote tuple in the slot */
1810  slot_modify_data(remoteslot, localslot, relmapentry, newtup);
1811  MemoryContextSwitchTo(oldctx);
1812 
1813  EvalPlanQualSetSlot(&epqstate, remoteslot);
1814 
1815  /* Do the actual update. */
1816  ExecSimpleRelationUpdate(relinfo, estate, &epqstate, localslot,
1817  remoteslot);
1818  }
1819  else
1820  {
1821  /*
1822  * The tuple to be updated could not be found. Do nothing except for
1823  * emitting a log message.
1824  *
1825  * XXX should this be promoted to ereport(LOG) perhaps?
1826  */
1827  elog(DEBUG1,
1828  "logical replication did not find row to be updated "
1829  "in replication target relation \"%s\"",
1830  RelationGetRelationName(localrel));
1831  }
1832 
1833  /* Cleanup. */
1834  ExecCloseIndices(relinfo);
1835  EvalPlanQualEnd(&epqstate);
1836 }
#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:216
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:721
EState * estate
Definition: worker.c:214
#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:1960
#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 1324 of file worker.c.

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

Referenced by apply_handle_stream_commit(), and apply_handle_stream_prepare().

1325 {
1327  int nchanges;
1328  char path[MAXPGPATH];
1329  char *buffer = NULL;
1330  StreamXidHash *ent;
1331  MemoryContext oldcxt;
1332  BufFile *fd;
1333 
1334  /* Make sure we have an open transaction */
1336 
1337  /*
1338  * Allocate file handle and memory required to process all the messages in
1339  * TopTransactionContext to avoid them getting reset after each message is
1340  * processed.
1341  */
1343 
1344  /* Open the spool file for the committed/prepared transaction */
1346  elog(DEBUG1, "replaying changes from file \"%s\"", path);
1347 
1348  ent = (StreamXidHash *) hash_search(xidhash,
1349  (void *) &xid,
1350  HASH_FIND,
1351  NULL);
1352  if (!ent)
1353  ereport(ERROR,
1354  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1355  errmsg_internal("transaction %u not found in stream XID hash table",
1356  xid)));
1357 
1358  fd = BufFileOpenShared(ent->stream_fileset, path, O_RDONLY);
1359 
1360  buffer = palloc(BLCKSZ);
1361  initStringInfo(&s2);
1362 
1363  MemoryContextSwitchTo(oldcxt);
1364 
1365  remote_final_lsn = lsn;
1366 
1367  /*
1368  * Make sure the handle apply_dispatch methods are aware we're in a remote
1369  * transaction.
1370  */
1371  in_remote_transaction = true;
1373 
1375 
1376  /*
1377  * Read the entries one by one and pass them through the same logic as in
1378  * apply_dispatch.
1379  */
1380  nchanges = 0;
1381  while (true)
1382  {
1383  int nbytes;
1384  int len;
1385 
1387 
1388  /* read length of the on-disk record */
1389  nbytes = BufFileRead(fd, &len, sizeof(len));
1390 
1391  /* have we reached end of the file? */
1392  if (nbytes == 0)
1393  break;
1394 
1395  /* do we have a correct length? */
1396  if (nbytes != sizeof(len))
1397  ereport(ERROR,
1399  errmsg("could not read from streaming transaction's changes file \"%s\": %m",
1400  path)));
1401 
1402  if (len <= 0)
1403  elog(ERROR, "incorrect length %d in streaming transaction's changes file \"%s\"",
1404  len, path);
1405 
1406  /* make sure we have sufficiently large buffer */
1407  buffer = repalloc(buffer, len);
1408 
1409  /* and finally read the data into the buffer */
1410  if (BufFileRead(fd, buffer, len) != len)
1411  ereport(ERROR,
1413  errmsg("could not read from streaming transaction's changes file \"%s\": %m",
1414  path)));
1415 
1416  /* copy the buffer to the stringinfo and call apply_dispatch */
1417  resetStringInfo(&s2);
1418  appendBinaryStringInfo(&s2, buffer, len);
1419 
1420  /* Ensure we are reading the data into our memory context. */
1422 
1423  apply_dispatch(&s2);
1424 
1426 
1427  MemoryContextSwitchTo(oldcxt);
1428 
1429  nchanges++;
1430 
1431  if (nchanges % 1000 == 0)
1432  elog(DEBUG1, "replayed %d changes from file \"%s\"",
1433  nchanges, path);
1434  }
1435 
1436  BufFileClose(fd);
1437 
1438  pfree(buffer);
1439  pfree(s2.data);
1440 
1441  elog(DEBUG1, "replayed %d (all) changes from file \"%s\"",
1442  nchanges, path);
1443 
1444  return;
1445 }
#define DEBUG1
Definition: elog.h:25
MemoryContext TopTransactionContext
Definition: mcxt.c:53
static XLogRecPtr remote_final_lsn
Definition: worker.c:250
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:3191
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void BufFileClose(BufFile *file)
Definition: buffile.c:395
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:249
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:721
SharedFileSet * stream_fileset
Definition: worker.c:234
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
BufFile * BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)
Definition: buffile.c:284
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 HTAB * xidhash
Definition: worker.c:261
static void apply_dispatch(StringInfo s)
Definition: worker.c:2328
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static MemoryContext ApplyMessageContext
Definition: worker.c:238
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:543
#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 3417 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.

3418 {
3419  int worker_slot = DatumGetInt32(main_arg);
3420  MemoryContext oldctx;
3421  char originname[NAMEDATALEN];
3422  XLogRecPtr origin_startpos;
3423  char *myslotname;
3425  int server_version;
3426 
3427  /* Attach to slot */
3428  logicalrep_worker_attach(worker_slot);
3429 
3430  /* Setup signal handling */
3432  pqsignal(SIGTERM, die);
3434 
3435  /*
3436  * We don't currently need any ResourceOwner in a walreceiver process, but
3437  * if we did, we could call CreateAuxProcessResourceOwner here.
3438  */
3439 
3440  /* Initialise stats to a sanish value */
3443 
3444  /* Load the libpq-specific functions */
3445  load_file("libpqwalreceiver", false);
3446 
3447  /* Run as replica session replication role. */
3448  SetConfigOption("session_replication_role", "replica",
3450 
3451  /* Connect to our database. */
3454  0);
3455 
3456  /*
3457  * Set always-secure search path, so malicious users can't redirect user
3458  * code (e.g. pg_index.indexprs).
3459  */
3460  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
3461 
3462  /* Load the subscription into persistent memory context. */
3464  "ApplyContext",
3468 
3470  if (!MySubscription)
3471  {
3472  ereport(LOG,
3473  (errmsg("logical replication apply worker for subscription %u will not "
3474  "start because the subscription was removed during startup",
3476  proc_exit(0);
3477  }
3478 
3479  MySubscriptionValid = true;
3480  MemoryContextSwitchTo(oldctx);
3481 
3482  if (!MySubscription->enabled)
3483  {
3484  ereport(LOG,
3485  (errmsg("logical replication apply worker for subscription \"%s\" will not "
3486  "start because the subscription was disabled during startup",
3487  MySubscription->name)));
3488 
3489  proc_exit(0);
3490  }
3491 
3492  /* Setup synchronous commit according to the user's wishes */
3493  SetConfigOption("synchronous_commit", MySubscription->synccommit,
3495 
3496  /* Keep us informed about subscription changes. */
3499  (Datum) 0);
3500 
3501  if (am_tablesync_worker())
3502  ereport(LOG,
3503  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has started",
3505  else
3506  ereport(LOG,
3507  (errmsg("logical replication apply worker for subscription \"%s\" has started",
3508  MySubscription->name)));
3509 
3511 
3512  /* Connect to the origin and start the replication. */
3513  elog(DEBUG1, "connecting to publisher using connection string \"%s\"",
3515 
3516  if (am_tablesync_worker())
3517  {
3518  char *syncslotname;
3519 
3520  /* This is table synchronization worker, call initial sync. */
3521  syncslotname = LogicalRepSyncTableStart(&origin_startpos);
3522 
3523  /* allocate slot name in long-lived context */
3524  myslotname = MemoryContextStrdup(ApplyContext, syncslotname);
3525 
3526  pfree(syncslotname);
3527  }
3528  else
3529  {
3530  /* This is main apply worker */
3531  RepOriginId originid;
3532  TimeLineID startpointTLI;
3533  char *err;
3534 
3535  myslotname = MySubscription->slotname;
3536 
3537  /*
3538  * This shouldn't happen if the subscription is enabled, but guard
3539  * against DDL bugs or manual catalog changes. (libpqwalreceiver will
3540  * crash if slot is NULL.)
3541  */
3542  if (!myslotname)
3543  ereport(ERROR,
3544  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3545  errmsg("subscription has no replication slot set")));
3546 
3547  /* Setup replication origin tracking. */
3549  snprintf(originname, sizeof(originname), "pg_%u", MySubscription->oid);
3550  originid = replorigin_by_name(originname, true);
3551  if (!OidIsValid(originid))
3552  originid = replorigin_create(originname);
3553  replorigin_session_setup(originid);
3554  replorigin_session_origin = originid;
3555  origin_startpos = replorigin_session_get_progress(false);
3557 
3559  MySubscription->name, &err);
3560  if (LogRepWorkerWalRcvConn == NULL)
3561  ereport(ERROR,
3562  (errcode(ERRCODE_CONNECTION_FAILURE),
3563  errmsg("could not connect to the publisher: %s", err)));
3564 
3565  /*
3566  * We don't really use the output identify_system for anything but it
3567  * does some initializations on the upstream so let's still call it.
3568  */
3569  (void) walrcv_identify_system(LogRepWorkerWalRcvConn, &startpointTLI);
3570  }
3571 
3572  /*
3573  * Setup callback for syscache so that we know when something changes in
3574  * the subscription relation state.
3575  */
3578  (Datum) 0);
3579 
3580  /* Build logical replication streaming options. */
3581  options.logical = true;
3582  options.startpoint = origin_startpos;
3583  options.slotname = myslotname;
3584 
3586  options.proto.logical.proto_version =
3587  server_version >= 150000 ? LOGICALREP_PROTO_TWOPHASE_VERSION_NUM :
3588  server_version >= 140000 ? LOGICALREP_PROTO_STREAM_VERSION_NUM :
3590 
3591  options.proto.logical.publication_names = MySubscription->publications;
3592  options.proto.logical.binary = MySubscription->binary;
3593  options.proto.logical.streaming = MySubscription->stream;
3594  options.proto.logical.twophase = false;
3595 
3596  if (!am_tablesync_worker())
3597  {
3598  /*
3599  * Even when the two_phase mode is requested by the user, it remains
3600  * as the tri-state PENDING until all tablesyncs have reached READY
3601  * state. Only then, can it become ENABLED.
3602  *
3603  * Note: If the subscription has no tables then leave the state as
3604  * PENDING, which allows ALTER SUBSCRIPTION ... REFRESH PUBLICATION to
3605  * work.
3606  */
3609  {
3610  /* Start streaming with two_phase enabled */
3611  options.proto.logical.twophase = true;
3613 
3618  }
3619  else
3620  {
3622  }
3623 
3624  ereport(DEBUG1,
3625  (errmsg("logical replication apply worker for subscription \"%s\" two_phase is %s.",
3630  "?")));
3631  }
3632  else
3633  {
3634  /* Start normal logical streaming replication. */
3636  }
3637 
3638  /* Run the main loop. */
3639  LogicalRepApplyLoop(origin_startpos);
3640 
3641  proc_exit(0);
3642 }
Subscription * MySubscription
Definition: worker.c:246
#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:244
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:2939
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:2941
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:564
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8086
#define LOGICALREP_TWOPHASE_STATE_PENDING
#define SIGHUP
Definition: win32_port.h:159
XLogRecPtr startpoint
Definition: walreceiver.h:170
MemoryContext TopMemoryContext
Definition: mcxt.c:48
MemoryContext ApplyContext
Definition: worker.c:239
static char ** options
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1435
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:5708
#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:2838
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:247
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:2515
#define elog(elevel,...)
Definition: elog.h:232
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define snprintf
Definition: port.h:216
#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:5737
#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:2840
static MemoryContext ApplyMessageContext
Definition: worker.c:238
void StartTransactionCommand(void)
Definition: xact.c:2838
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 3191 of file worker.c.

References MAXPGPATH, and snprintf.

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

3192 {
3193  snprintf(path, MAXPGPATH, "%u-%u.changes", subid, xid);
3194 }
#define MAXPGPATH
#define snprintf
Definition: port.h:216

◆ check_relation_updatable()

static void check_relation_updatable ( LogicalRepRelMapEntry rel)
static

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

1651 {
1652  /* Updatable, no error. */
1653  if (rel->updatable)
1654  return;
1655 
1656  /*
1657  * We are in error mode so it's fine this is somewhat slow. It's better to
1658  * give user correct error.
1659  */
1661  {
1662  ereport(ERROR,
1663  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1664  errmsg("publisher did not send replica identity column "
1665  "expected by the logical replication target relation \"%s.%s\"",
1666  rel->remoterel.nspname, rel->remoterel.relname)));
1667  }
1668 
1669  ereport(ERROR,
1670  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1671  errmsg("logical replication target relation \"%s.%s\" has "
1672  "neither REPLICA IDENTITY index nor PRIMARY "
1673  "KEY and published relation does not have "
1674  "REPLICA IDENTITY FULL",
1675  rel->remoterel.nspname, rel->remoterel.relname)));
1676 }
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:1550
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 3386 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().

3387 {
3388  if (subxact_data.subxacts)
3390 
3391  subxact_data.subxacts = NULL;
3393  subxact_data.nsubxacts = 0;
3395 }
TransactionId subxact_last
Definition: worker.c:278
uint32 nsubxacts
Definition: worker.c:276
void pfree(void *pointer)
Definition: mcxt.c:1169
SubXactInfo * subxacts
Definition: worker.c:279
#define InvalidTransactionId
Definition: transam.h:31
static ApplySubXactData subxact_data
Definition: worker.c:282
uint32 nsubxacts_max
Definition: worker.c:277

◆ 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:216
Form_pg_class rd_rel
Definition: rel.h:109
#define list_make1(x1)
Definition: pg_list.h:206
ResultRelInfo * targetRelInfo
Definition: worker.c:217
List * es_opened_result_relations
Definition: execnodes.h:578
EState * estate
Definition: worker.c:214
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:587
RTEKind rtekind
Definition: parsenodes.h:995
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 1960 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().

1964 {
1965  Oid idxoid;
1966  bool found;
1967 
1968  *localslot = table_slot_create(localrel, &estate->es_tupleTable);
1969 
1970  idxoid = GetRelationIdentityOrPK(localrel);
1971  Assert(OidIsValid(idxoid) ||
1972  (remoterel->replident == REPLICA_IDENTITY_FULL));
1973 
1974  if (OidIsValid(idxoid))
1975  found = RelationFindReplTupleByIndex(localrel, idxoid,
1977  remoteslot, *localslot);
1978  else
1979  found = RelationFindReplTupleSeq(localrel, LockTupleExclusive,
1980  remoteslot, *localslot);
1981 
1982  return found;
1983 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:1550
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:221
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
void pfree(void *pointer)
Definition: mcxt.c:1169
ModifyTableState * mtstate
Definition: worker.c:220
void ExecCleanupTupleRouting(ModifyTableState *mtstate, PartitionTupleRouting *proute)
EState * estate
Definition: worker.c:214
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 2436 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().

2438 {
2439  dlist_mutable_iter iter;
2440  XLogRecPtr local_flush = GetFlushRecPtr();
2441 
2443  *flush = InvalidXLogRecPtr;
2444 
2446  {
2447  FlushPosition *pos =
2448  dlist_container(FlushPosition, node, iter.cur);
2449 
2450  *write = pos->remote_end;
2451 
2452  if (pos->local_end <= local_flush)
2453  {
2454  *flush = pos->remote_end;
2455  dlist_delete(iter.cur);
2456  pfree(pos);
2457  }
2458  else
2459  {
2460  /*
2461  * Don't want to uselessly iterate over the rest of the list which
2462  * could potentially be long. Instead get the last element and
2463  * grab the write position from there.
2464  */
2465  pos = dlist_tail_element(FlushPosition, node,
2466  &lsn_mapping);
2467  *write = pos->remote_end;
2468  *have_pending_txes = true;
2469  return;
2470  }
2471  }
2472 
2473  *have_pending_txes = !dlist_is_empty(&lsn_mapping);
2474 }
#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:8563
#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 1550 of file worker.c.

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

Referenced by check_relation_updatable(), and FindReplTupleInLocalRel().

1551 {
1552  Oid idxoid;
1553 
1554  idxoid = RelationGetReplicaIndex(rel);
1555 
1556  if (!OidIsValid(idxoid))
1557  idxoid = RelationGetPrimaryKeyIndex(rel);
1558 
1559  return idxoid;
1560 }
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:3359
static void subxact_info_add(TransactionId xid)
Definition: worker.c:3106
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:253
#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:264
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:255

◆ IsLogicalWorker()

bool IsLogicalWorker ( void  )

Definition at line 3648 of file worker.c.

References MyLogicalRepWorker.

Referenced by ProcessInterrupts().

3649 {
3650  return MyLogicalRepWorker != NULL;
3651 }
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57

◆ LogicalRepApplyLoop()

static void LogicalRepApplyLoop ( XLogRecPtr  last_received)
static

Definition at line 2515 of file worker.c.

References AcceptInvalidationMessages(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, apply_dispatch(), buf, CHECK_FOR_INTERRUPTS, ConfigReloadPending, StringInfoData::cursor, StringInfoData::data, dlist_is_empty(), ereport, errcode(), errmsg(), ERROR, 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(), 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().

2516 {
2517  TimestampTz last_recv_timestamp = GetCurrentTimestamp();
2518  bool ping_sent = false;
2519  TimeLineID tli;
2520 
2521  /*
2522  * Init the ApplyMessageContext which we clean up after each replication
2523  * protocol message.
2524  */
2526  "ApplyMessageContext",
2528 
2529  /*
2530  * This memory context is used for per-stream data when the streaming mode
2531  * is enabled. This context is reset on each stream stop.
2532  */
2534  "LogicalStreamingContext",
2536 
2537  /* mark as idle, before starting to loop */
2539 
2540  /* This outer loop iterates once per wait. */
2541  for (;;)
2542  {
2544  int rc;
2545  int len;
2546  char *buf = NULL;
2547  bool endofstream = false;
2548  long wait_time;
2549 
2551 
2553 
2554  len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
2555 
2556  if (len != 0)
2557  {
2558  /* Loop to process all available data (without blocking). */
2559  for (;;)
2560  {
2562 
2563  if (len == 0)
2564  {
2565  break;
2566  }
2567  else if (len < 0)
2568  {
2569  ereport(LOG,
2570  (errmsg("data stream from publisher has ended")));
2571  endofstream = true;
2572  break;
2573  }
2574  else
2575  {
2576  int c;
2577  StringInfoData s;
2578 
2579  /* Reset timeout. */
2580  last_recv_timestamp = GetCurrentTimestamp();
2581  ping_sent = false;
2582 
2583  /* Ensure we are reading the data into our memory context. */
2585 
2586  s.data = buf;
2587  s.len = len;
2588  s.cursor = 0;
2589  s.maxlen = -1;
2590 
2591  c = pq_getmsgbyte(&s);
2592 
2593  if (c == 'w')
2594  {
2595  XLogRecPtr start_lsn;
2596  XLogRecPtr end_lsn;
2597  TimestampTz send_time;
2598 
2599  start_lsn = pq_getmsgint64(&s);
2600  end_lsn = pq_getmsgint64(&s);
2601  send_time = pq_getmsgint64(&s);
2602 
2603  if (last_received < start_lsn)
2604  last_received = start_lsn;
2605 
2606  if (last_received < end_lsn)
2607  last_received = end_lsn;
2608 
2609  UpdateWorkerStats(last_received, send_time, false);
2610 
2611  apply_dispatch(&s);
2612  }
2613  else if (c == 'k')
2614  {
2615  XLogRecPtr end_lsn;
2617  bool reply_requested;
2618 
2619  end_lsn = pq_getmsgint64(&s);
2620  timestamp = pq_getmsgint64(&s);
2621  reply_requested = pq_getmsgbyte(&s);
2622 
2623  if (last_received < end_lsn)
2624  last_received = end_lsn;
2625 
2626  send_feedback(last_received, reply_requested, false);
2627  UpdateWorkerStats(last_received, timestamp, true);
2628  }
2629  /* other message types are purposefully ignored */
2630 
2632  }
2633 
2634  len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
2635  }
2636  }
2637 
2638  /* confirm all writes so far */
2639  send_feedback(last_received, false, false);
2640 
2642  {
2643  /*
2644  * If we didn't get any transactions for a while there might be
2645  * unconsumed invalidation messages in the queue, consume them
2646  * now.
2647  */
2650 
2651  /* Process any table synchronization changes. */
2652  process_syncing_tables(last_received);
2653  }
2654 
2655  /* Cleanup the memory. */
2658 
2659  /* Check if we need to exit the streaming loop. */
2660  if (endofstream)
2661  break;
2662 
2663  /*
2664  * Wait for more data or latch. If we have unflushed transactions,
2665  * wake up after WalWriterDelay to see if they've been flushed yet (in
2666  * which case we should send a feedback message). Otherwise, there's
2667  * no particular urgency about waking up unless we get data or a
2668  * signal.
2669  */
2670  if (!dlist_is_empty(&lsn_mapping))
2671  wait_time = WalWriterDelay;
2672  else
2673  wait_time = NAPTIME_PER_CYCLE;
2674 
2678  fd, wait_time,
2680 
2681  if (rc & WL_LATCH_SET)
2682  {
2685  }
2686 
2687  if (ConfigReloadPending)
2688  {
2689  ConfigReloadPending = false;
2691  }
2692 
2693  if (rc & WL_TIMEOUT)
2694  {
2695  /*
2696  * We didn't receive anything new. If we haven't heard anything
2697  * from the server for more than wal_receiver_timeout / 2, ping
2698  * the server. Also, if it's been longer than
2699  * wal_receiver_status_interval since the last update we sent,
2700  * send a status update to the primary anyway, to report any
2701  * progress in applying WAL.
2702  */
2703  bool requestReply = false;
2704 
2705  /*
2706  * Check if time since last receive from primary has reached the
2707  * configured limit.
2708  */
2709  if (wal_receiver_timeout > 0)
2710  {
2712  TimestampTz timeout;
2713 
2714  timeout =
2715  TimestampTzPlusMilliseconds(last_recv_timestamp,
2717 
2718  if (now >= timeout)
2719  ereport(ERROR,
2720  (errcode(ERRCODE_CONNECTION_FAILURE),
2721  errmsg("terminating logical replication worker due to timeout")));
2722 
2723  /* Check to see if it's time for a ping. */
2724  if (!ping_sent)
2725  {
2726  timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
2727  (wal_receiver_timeout / 2));
2728  if (now >= timeout)
2729  {
2730  requestReply = true;
2731  ping_sent = true;
2732  }
2733  }
2734  }
2735 
2736  send_feedback(last_received, requestReply, requestReply);
2737  }
2738  }
2739 
2740  /* All done */
2742 }
static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
Definition: worker.c:2751
#define AllocSetContextCreate
Definition: memutils.h:173
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:420
WalReceiverConn * LogRepWorkerWalRcvConn
Definition: worker.c:244
uint32 TimeLineID
Definition: xlogdefs.h:59
void AcceptInvalidationMessages(void)
Definition: inval.c:688
#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:2499
#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
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
#define ERROR
Definition: elog.h:46
#define NAPTIME_PER_CYCLE
Definition: worker.c:195
bool in_remote_transaction
Definition: worker.c:249
static bool in_streamed_transaction
Definition: worker.c:253
#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:239
#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:242
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
static void apply_dispatch(StringInfo s)
Definition: worker.c:2328
static void maybe_reread_subscription(void)
Definition: worker.c:2840
static MemoryContext ApplyMessageContext
Definition: worker.c:238
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 2840 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().

2841 {
2842  MemoryContext oldctx;
2844  bool started_tx = false;
2845 
2846  /* When cache state is valid there is nothing to do here. */
2847  if (MySubscriptionValid)
2848  return;
2849 
2850  /* This function might be called inside or outside of transaction. */
2851  if (!IsTransactionState())
2852  {
2854  started_tx = true;
2855  }
2856 
2857  /* Ensure allocations in permanent context. */
2859 
2860  newsub = GetSubscription(MyLogicalRepWorker->subid, true);
2861 
2862  /*
2863  * Exit if the subscription was removed. This normally should not happen
2864  * as the worker gets killed during DROP SUBSCRIPTION.
2865  */
2866  if (!newsub)
2867  {
2868  ereport(LOG,
2869  (errmsg("logical replication apply worker for subscription \"%s\" will "
2870  "stop because the subscription was removed",
2871  MySubscription->name)));
2872 
2873  proc_exit(0);
2874  }
2875 
2876  /*
2877  * Exit if the subscription was disabled. This normally should not happen
2878  * as the worker gets killed during ALTER SUBSCRIPTION ... DISABLE.
2879  */
2880  if (!newsub->enabled)
2881  {
2882  ereport(LOG,
2883  (errmsg("logical replication apply worker for subscription \"%s\" will "
2884  "stop because the subscription was disabled",
2885  MySubscription->name)));
2886 
2887  proc_exit(0);
2888  }
2889 
2890  /* !slotname should never happen when enabled is true. */
2891  Assert(newsub->slotname);
2892 
2893  /* two-phase should not be altered */
2895 
2896  /*
2897  * Exit if any parameter that affects the remote connection was changed.
2898  * The launcher will start a new worker.
2899  */
2900  if (strcmp(newsub->conninfo, MySubscription->conninfo) != 0 ||
2901  strcmp(newsub->name, MySubscription->name) != 0 ||
2902  strcmp(newsub->slotname, MySubscription->slotname) != 0 ||
2903  newsub->binary != MySubscription->binary ||
2904  newsub->stream != MySubscription->stream ||
2906  {
2907  ereport(LOG,
2908  (errmsg("logical replication apply worker for subscription \"%s\" will restart because of a parameter change",
2909  MySubscription->name)));
2910 
2911  proc_exit(0);
2912  }
2913 
2914  /* Check for other changes that should never happen too. */
2915  if (newsub->dbid != MySubscription->dbid)
2916  {
2917  elog(ERROR, "subscription %u changed unexpectedly",
2919  }
2920 
2921  /* Clean old subscription info and switch to new one. */
2924 
2925  MemoryContextSwitchTo(oldctx);
2926 
2927  /* Change synchronous commit according to the user's wishes */
2928  SetConfigOption("synchronous_commit", MySubscription->synccommit,
2930 
2931  if (started_tx)
2933 
2934  MySubscriptionValid = true;
2935 }
Subscription * MySubscription
Definition: worker.c:246
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3122
void CommitTransactionCommand(void)
Definition: xact.c:2939
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:8086
MemoryContext ApplyContext
Definition: worker.c:239
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
void StartTransactionCommand(void)
Definition: xact.c:2838
bool IsTransactionState(void)
Definition: xact.c:371
bool MySubscriptionValid
Definition: worker.c:247
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

◆ send_feedback()

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

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

2752 {
2753  static StringInfo reply_message = NULL;
2754  static TimestampTz send_time = 0;
2755 
2756  static XLogRecPtr last_recvpos = InvalidXLogRecPtr;
2757  static XLogRecPtr last_writepos = InvalidXLogRecPtr;
2758  static XLogRecPtr last_flushpos = InvalidXLogRecPtr;
2759 
2760  XLogRecPtr writepos;
2761  XLogRecPtr flushpos;
2762  TimestampTz now;
2763  bool have_pending_txes;
2764 
2765  /*
2766  * If the user doesn't want status to be reported to the publisher, be
2767  * sure to exit before doing anything at all.
2768  */
2769  if (!force && wal_receiver_status_interval <= 0)
2770  return;
2771 
2772  /* It's legal to not pass a recvpos */
2773  if (recvpos < last_recvpos)
2774  recvpos = last_recvpos;
2775 
2776  get_flush_position(&writepos, &flushpos, &have_pending_txes);
2777 
2778  /*
2779  * No outstanding transactions to flush, we can report the latest received
2780  * position. This is important for synchronous replication.
2781  */
2782  if (!have_pending_txes)
2783  flushpos = writepos = recvpos;
2784 
2785  if (writepos < last_writepos)
2786  writepos = last_writepos;
2787 
2788  if (flushpos < last_flushpos)
2789  flushpos = last_flushpos;
2790 
2791  now = GetCurrentTimestamp();
2792 
2793  /* if we've already reported everything we're good */
2794  if (!force &&
2795  writepos == last_writepos &&
2796  flushpos == last_flushpos &&
2797  !TimestampDifferenceExceeds(send_time, now,
2799  return;
2800  send_time = now;
2801 
2802  if (!reply_message)
2803  {
2805 
2806  reply_message = makeStringInfo();
2807  MemoryContextSwitchTo(oldctx);
2808  }
2809  else
2810  resetStringInfo(reply_message);
2811 
2812  pq_sendbyte(reply_message, 'r');
2813  pq_sendint64(reply_message, recvpos); /* write */
2814  pq_sendint64(reply_message, flushpos); /* flush */
2815  pq_sendint64(reply_message, writepos); /* apply */
2816  pq_sendint64(reply_message, now); /* sendTime */
2817  pq_sendbyte(reply_message, requestReply); /* replyRequested */
2818 
2819  elog(DEBUG2, "sending feedback (force %d) to recv %X/%X, write %X/%X, flush %X/%X",
2820  force,
2821  LSN_FORMAT_ARGS(recvpos),
2822  LSN_FORMAT_ARGS(writepos),
2823  LSN_FORMAT_ARGS(flushpos));
2824 
2826  reply_message->data, reply_message->len);
2827 
2828  if (recvpos > last_recvpos)
2829  last_recvpos = recvpos;
2830  if (writepos > last_writepos)
2831  last_writepos = writepos;
2832  if (flushpos > last_flushpos)
2833  last_flushpos = flushpos;
2834 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
WalReceiverConn * LogRepWorkerWalRcvConn
Definition: worker.c:244
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:2436
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:239
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

◆ 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:250
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:5653
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 721 of file worker.c.

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

Referenced by apply_handle_tuple_routing(), and apply_handle_update_internal().

724 {
725  int natts = slot->tts_tupleDescriptor->natts;
726  int i;
727  SlotErrCallbackArg errarg;
728  ErrorContextCallback errcallback;
729 
730  /* We'll fill "slot" with a virtual tuple, so we must start with ... */
731  ExecClearTuple(slot);
732 
733  /*
734  * Copy all the column data from srcslot, so that we'll have valid values
735  * for unreplaced columns.
736  */
737  Assert(natts == srcslot->tts_tupleDescriptor->natts);
738  slot_getallattrs(srcslot);
739  memcpy(slot->tts_values, srcslot->tts_values, natts * sizeof(Datum));
740  memcpy(slot->tts_isnull, srcslot->tts_isnull, natts * sizeof(bool));
741 
742  /* For error reporting, push callback + info on the error context stack */
743  errarg.rel = rel;
744  errarg.remote_attnum = -1;
745  errcallback.callback = slot_store_error_callback;
746  errcallback.arg = (void *) &errarg;
747  errcallback.previous = error_context_stack;
748  error_context_stack = &errcallback;
749 
750  /* Call the "in" function for each replaced attribute */
751  Assert(natts == rel->attrmap->maplen);
752  for (i = 0; i < natts; i++)
753  {
755  int remoteattnum = rel->attrmap->attnums[i];
756 
757  if (remoteattnum < 0)
758  continue;
759 
760  Assert(remoteattnum < tupleData->ncols);
761 
762  if (tupleData->colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
763  {
764  StringInfo colvalue = &tupleData->colvalues[remoteattnum];
765 
766  errarg.remote_attnum = remoteattnum;
767 
768  if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
769  {
770  Oid typinput;
771  Oid typioparam;
772 
773  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
774  slot->tts_values[i] =
775  OidInputFunctionCall(typinput, colvalue->data,
776  typioparam, att->atttypmod);
777  slot->tts_isnull[i] = false;
778  }
779  else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
780  {
781  Oid typreceive;
782  Oid typioparam;
783 
784  /*
785  * In some code paths we may be asked to re-parse the same
786  * tuple data. Reset the StringInfo's cursor so that works.
787  */
788  colvalue->cursor = 0;
789 
790  getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
791  slot->tts_values[i] =
792  OidReceiveFunctionCall(typreceive, colvalue,
793  typioparam, att->atttypmod);
794 
795  /* Trouble if it didn't eat the whole buffer */
796  if (colvalue->cursor != colvalue->len)
797  ereport(ERROR,
798  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
799  errmsg("incorrect binary data format in logical replication column %d",
800  remoteattnum + 1)));
801  slot->tts_isnull[i] = false;
802  }
803  else
804  {
805  /* must be LOGICALREP_COLUMN_NULL */
806  slot->tts_values[i] = (Datum) 0;
807  slot->tts_isnull[i] = true;
808  }
809 
810  errarg.remote_attnum = -1;
811  }
812  }
813 
814  /* Pop the error context stack */
815  error_context_stack = errcallback.previous;
816 
817  /* And finally, declare that "slot" contains a valid virtual tuple */
818  ExecStoreVirtualTuple(slot);
819 }
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
LogicalRepRelMapEntry * rel
Definition: worker.c:208
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int maplen
Definition: attmap.h:37
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LOGICALREP_COLUMN_TEXT
Definition: logicalproto.h:92
Datum * tts_values
Definition: tuptable.h:126
StringInfoData * colvalues
Definition: logicalproto.h:81
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:247
struct ErrorContextCallback * previous
Definition: elog.h:246
#define LOGICALREP_COLUMN_BINARY
Definition: logicalproto.h:93
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define LOGICALREP_COLUMN_UNCHANGED
Definition: logicalproto.h:91
#define ERROR
Definition: elog.h:46
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:1662
bool * tts_isnull
Definition: tuptable.h:128
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2887
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2821
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
AttrNumber * attnums
Definition: attmap.h:36
static void slot_store_error_callback(void *arg)
Definition: worker.c:588
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1644
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1552

◆ slot_store_data()

static void slot_store_data ( TupleTableSlot slot,
LogicalRepRelMapEntry rel,
LogicalRepTupleData tupleData 
)
static

Definition at line 609 of file worker.c.

References ErrorContextCallback::arg, Assert, AttrMap::attnums, LogicalRepRelMapEntry::attrmap, ErrorContextCallback::callback, LogicalRepTupleData::colstatus, LogicalRepTupleData::colvalues, StringInfoData::cursor, StringInfoData::data, ereport, errcode(), errmsg(), ERROR, error_context_stack, ExecClearTuple(), ExecStoreVirtualTuple(), getTypeBinaryInputInfo(), getTypeInputInfo(), i, StringInfoData::len, LOGICALREP_COLUMN_BINARY, LOGICALREP_COLUMN_TEXT, AttrMap::maplen, TupleDescData::natts, OidInputFunctionCall(), OidReceiveFunctionCall(), ErrorContextCallback::previous, SlotErrCallbackArg::rel, SlotErrCallbackArg::remote_attnum, slot_store_error_callback(), TupleTableSlot::tts_isnull, TupleTableSlot::tts_tupleDescriptor, TupleTableSlot::tts_values, and TupleDescAttr.

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

611 {
612  int natts = slot->tts_tupleDescriptor->natts;
613  int i;
614  SlotErrCallbackArg errarg;
615  ErrorContextCallback errcallback;
616 
617  ExecClearTuple(slot);
618 
619  /* Push callback + info on the error context stack */
620  errarg.rel = rel;
621  errarg.remote_attnum = -1;
622  errcallback.callback = slot_store_error_callback;
623  errcallback.arg = (void *) &errarg;
624  errcallback.previous = error_context_stack;
625  error_context_stack = &errcallback;
626 
627  /* Call the "in" function for each non-dropped, non-null attribute */
628  Assert(natts == rel->attrmap->maplen);
629  for (i = 0; i < natts; i++)
630  {
632  int remoteattnum = rel->attrmap->attnums[i];
633 
634  if (!att->attisdropped && remoteattnum >= 0)
635  {
636  StringInfo colvalue = &tupleData->colvalues[remoteattnum];
637 
638  Assert(remoteattnum < tupleData->ncols);
639 
640  errarg.remote_attnum = remoteattnum;
641 
642  if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
643  {
644  Oid typinput;
645  Oid typioparam;
646 
647  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
648  slot->tts_values[i] =
649  OidInputFunctionCall(typinput, colvalue->data,
650  typioparam, att->atttypmod);
651  slot->tts_isnull[i] = false;
652  }
653  else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
654  {
655  Oid typreceive;
656  Oid typioparam;
657 
658  /*
659  * In some code paths we may be asked to re-parse the same
660  * tuple data. Reset the StringInfo's cursor so that works.
661  */
662  colvalue->cursor = 0;
663 
664  getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
665  slot->tts_values[i] =
666  OidReceiveFunctionCall(typreceive, colvalue,
667  typioparam, att->atttypmod);
668 
669  /* Trouble if it didn't eat the whole buffer */
670  if (colvalue->cursor != colvalue->len)
671  ereport(ERROR,
672  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
673  errmsg("incorrect binary data format in logical replication column %d",
674  remoteattnum + 1)));
675  slot->tts_isnull[i] = false;
676  }
677  else
678  {
679  /*
680  * NULL value from remote. (We don't expect to see
681  * LOGICALREP_COLUMN_UNCHANGED here, but if we do, treat it as
682  * NULL.)
683  */
684  slot->tts_values[i] = (Datum) 0;
685  slot->tts_isnull[i] = true;
686  }
687 
688  errarg.remote_attnum = -1;
689  }
690  else
691  {
692  /*
693  * We assign NULL to dropped attributes and missing values
694  * (missing values should be later filled using
695  * slot_fill_defaults).
696  */
697  slot->tts_values[i] = (Datum) 0;
698  slot->tts_isnull[i] = true;
699  }
700  }
701 
702  /* Pop the error context stack */
703  error_context_stack = errcallback.previous;
704 
705  ExecStoreVirtualTuple(slot);
706 }
static TupleTableSlot *