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/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  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 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 (StringInfo s, LogicalRepCommitData *commit_data)
 
static void apply_handle_insert_internal (ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot)
 
static void apply_handle_update_internal (ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry)
 
static void apply_handle_delete_internal (ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepRelation *remoterel)
 
static bool FindReplTupleInLocalRel (EState *estate, Relation localrel, LogicalRepRelation *remoterel, TupleTableSlot *remoteslot, TupleTableSlot **localslot)
 
static void apply_handle_tuple_routing (ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry, CmdType operation)
 
static bool should_apply_changes_for_rel (LogicalRepRelMapEntry *rel)
 
static bool ensure_transaction (void)
 
static bool handle_streamed_transaction (LogicalRepMsgType action, StringInfo s)
 
static EStatecreate_estate_for_relation (LogicalRepRelMapEntry *rel, ResultRelInfo **resultRelInfo)
 
static void finish_estate (EState *estate)
 
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_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
 
WalReceiverConnwrconn = NULL
 
SubscriptionMySubscription = NULL
 
bool MySubscriptionValid = false
 
bool in_remote_transaction = false
 
static XLogRecPtr remote_final_lsn = InvalidXLogRecPtr
 
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 121 of file worker.c.

Referenced by LogicalRepApplyLoop().

Typedef Documentation

◆ 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 1924 of file worker.c.

References generate_unaccent_rules::action, apply_handle_begin(), apply_handle_commit(), apply_handle_delete(), apply_handle_insert(), apply_handle_origin(), apply_handle_relation(), apply_handle_stream_abort(), apply_handle_stream_commit(), apply_handle_stream_start(), apply_handle_stream_stop(), apply_handle_truncate(), apply_handle_type(), apply_handle_update(), ereport, errcode(), errmsg(), ERROR, LOGICAL_REP_MSG_BEGIN, LOGICAL_REP_MSG_COMMIT, LOGICAL_REP_MSG_DELETE, LOGICAL_REP_MSG_INSERT, LOGICAL_REP_MSG_MESSAGE, LOGICAL_REP_MSG_ORIGIN, LOGICAL_REP_MSG_RELATION, LOGICAL_REP_MSG_STREAM_ABORT, LOGICAL_REP_MSG_STREAM_COMMIT, LOGICAL_REP_MSG_STREAM_END, LOGICAL_REP_MSG_STREAM_START, LOGICAL_REP_MSG_TRUNCATE, LOGICAL_REP_MSG_TYPE, LOGICAL_REP_MSG_UPDATE, and pq_getmsgbyte().

Referenced by apply_handle_stream_commit(), and LogicalRepApplyLoop().

1925 {
1927 
1928  switch (action)
1929  {
1930  case LOGICAL_REP_MSG_BEGIN:
1931  apply_handle_begin(s);
1932  return;
1933 
1936  return;
1937 
1940  return;
1941 
1944  return;
1945 
1948  return;
1949 
1952  return;
1953 
1956  return;
1957 
1958  case LOGICAL_REP_MSG_TYPE:
1959  apply_handle_type(s);
1960  return;
1961 
1964  return;
1965 
1967 
1968  /*
1969  * Logical replication does not use generic logical messages yet.
1970  * Although, it could be used by other applications that use this
1971  * output plugin.
1972  */
1973  return;
1974 
1977  return;
1978 
1981  return;
1982 
1985  return;
1986 
1989  return;
1990  }
1991 
1992  ereport(ERROR,
1993  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1994  errmsg("invalid logical replication message type \"%c\"", action)));
1995 }
static void apply_handle_type(StringInfo s)
Definition: worker.c:1148
static void apply_handle_insert(StringInfo s)
Definition: worker.c:1182
static void apply_handle_stream_abort(StringInfo s)
Definition: worker.c:864
static void apply_handle_stream_start(StringInfo s)
Definition: worker.c:785
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
static void apply_handle_stream_stop(StringInfo s)
Definition: worker.c:835
static void apply_handle_delete(StringInfo s)
Definition: worker.c:1449
static void apply_handle_begin(StringInfo s)
Definition: worker.c:726
static void apply_handle_commit(StringInfo s)
Definition: worker.c:745
static void apply_handle_stream_commit(StringInfo s)
Definition: worker.c:962
static void apply_handle_update(StringInfo s)
Definition: worker.c:1294
static void apply_handle_relation(StringInfo s)
Definition: worker.c:1130
#define ereport(elevel,...)
Definition: elog.h:157
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
static void apply_handle_origin(StringInfo s)
Definition: worker.c:767
LogicalRepMsgType
Definition: logicalproto.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:909
static void apply_handle_truncate(StringInfo s)
Definition: worker.c:1810

◆ apply_handle_begin()

static void apply_handle_begin ( StringInfo  s)
static

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

727 {
728  LogicalRepBeginData begin_data;
729 
730  logicalrep_read_begin(s, &begin_data);
731 
732  remote_final_lsn = begin_data.final_lsn;
733 
734  in_remote_transaction = true;
735 
737 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:165
void logicalrep_read_begin(StringInfo in, LogicalRepBeginData *begin_data)
Definition: proto.c:60
bool in_remote_transaction
Definition: worker.c:164
XLogRecPtr final_lsn
Definition: logicalproto.h:113
void pgstat_report_activity(BackendState state, const char *cmd_str)

◆ apply_handle_commit()

static void apply_handle_commit ( StringInfo  s)
static

Definition at line 745 of file worker.c.

References apply_handle_commit_internal(), Assert, LogicalRepCommitData::commit_lsn, LogicalRepCommitData::end_lsn, logicalrep_read_commit(), pgstat_report_activity(), process_syncing_tables(), remote_final_lsn, and STATE_IDLE.

Referenced by apply_dispatch().

746 {
747  LogicalRepCommitData commit_data;
748 
749  logicalrep_read_commit(s, &commit_data);
750 
751  Assert(commit_data.commit_lsn == remote_final_lsn);
752 
753  apply_handle_commit_internal(s, &commit_data);
754 
755  /* Process any tables that are being synchronized in parallel. */
756  process_syncing_tables(commit_data.end_lsn);
757 
759 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:165
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
static void apply_handle_commit_internal(StringInfo s, LogicalRepCommitData *commit_data)
Definition: worker.c:1095
#define Assert(condition)
Definition: c.h:804
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 ( StringInfo  s,
LogicalRepCommitData commit_data 
)
static

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

1096 {
1097  if (IsTransactionState())
1098  {
1099  /*
1100  * Update origin state so we can restart streaming from correct
1101  * position in case of crash.
1102  */
1103  replorigin_session_origin_lsn = commit_data->end_lsn;
1105 
1107  pgstat_report_stat(false);
1108 
1109  store_flush_position(commit_data->end_lsn);
1110  }
1111  else
1112  {
1113  /* Process any invalidation messages that might have accumulated. */
1116  }
1117 
1118  in_remote_transaction = false;
1119 }
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2055
void AcceptInvalidationMessages(void)
Definition: inval.c:687
void CommitTransactionCommand(void)
Definition: xact.c:2939
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:846
bool in_remote_transaction
Definition: worker.c:164
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:2413
bool IsTransactionState(void)
Definition: xact.c:371
TimestampTz committime
Definition: logicalproto.h:122

◆ apply_handle_delete()

static void apply_handle_delete ( StringInfo  s)
static

Definition at line 1449 of file worker.c.

References apply_handle_delete_internal(), apply_handle_tuple_routing(), check_relation_updatable(), CMD_DELETE, CommandCounterIncrement(), create_estate_for_relation(), ensure_transaction(), ExecInitExtraTupleSlot(), finish_estate(), GetPerTupleMemoryContext, GetTransactionSnapshot(), handle_streamed_transaction(), LogicalRepRelMapEntry::localrel, LOGICAL_REP_MSG_DELETE, logicalrep_read_delete(), logicalrep_rel_close(), logicalrep_rel_open(), MemoryContextSwitchTo(), NoLock, PopActiveSnapshot(), PushActiveSnapshot(), RelationData::rd_rel, RelationGetDescr, LogicalRepRelMapEntry::remoterel, RowExclusiveLock, should_apply_changes_for_rel(), slot_store_data(), and TTSOpsVirtual.

Referenced by apply_dispatch().

1450 {
1451  ResultRelInfo *resultRelInfo;
1452  LogicalRepRelMapEntry *rel;
1453  LogicalRepTupleData oldtup;
1454  LogicalRepRelId relid;
1455  EState *estate;
1456  TupleTableSlot *remoteslot;
1457  MemoryContext oldctx;
1458 
1460  return;
1461 
1463 
1464  relid = logicalrep_read_delete(s, &oldtup);
1465  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1466  if (!should_apply_changes_for_rel(rel))
1467  {
1468  /*
1469  * The relation can't become interesting in the middle of the
1470  * transaction so it's safe to unlock it.
1471  */
1473  return;
1474  }
1475 
1476  /* Check if we can do the delete. */
1478 
1479  /* Initialize the executor state. */
1480  estate = create_estate_for_relation(rel, &resultRelInfo);
1481  remoteslot = ExecInitExtraTupleSlot(estate,
1482  RelationGetDescr(rel->localrel),
1483  &TTSOpsVirtual);
1484 
1486 
1487  /* Build the search tuple. */
1489  slot_store_data(remoteslot, rel, &oldtup);
1490  MemoryContextSwitchTo(oldctx);
1491 
1492  /* For a partitioned table, apply delete to correct partition. */
1493  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1494  apply_handle_tuple_routing(resultRelInfo, estate,
1495  remoteslot, NULL, rel, CMD_DELETE);
1496  else
1497  apply_handle_delete_internal(resultRelInfo, estate,
1498  remoteslot, &rel->remoterel);
1499 
1501 
1502  finish_estate(estate);
1503 
1505 
1507 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:263
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:290
static void apply_handle_delete_internal(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepRelation *remoterel)
Definition: worker.c:1511
#define RelationGetDescr(relation)
Definition: rel.h:498
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:447
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Form_pg_class rd_rel
Definition: rel.h:110
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
static bool ensure_transaction(void)
Definition: worker.c:279
LogicalRepRelation remoterel
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define RowExclusiveLock
Definition: lockdefs.h:38
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:309
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:272
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel, ResultRelInfo **resultRelInfo)
Definition: worker.c:346
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:1260
static void apply_handle_tuple_routing(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry, CmdType operation)
Definition: worker.c:1585
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:537
static void finish_estate(EState *estate)
Definition: worker.c:395
static void slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:504
uint32 LogicalRepRelId
Definition: logicalproto.h:85

◆ apply_handle_delete_internal()

static void apply_handle_delete_internal ( ResultRelInfo relinfo,
EState estate,
TupleTableSlot remoteslot,
LogicalRepRelation remoterel 
)
static

Definition at line 1511 of file worker.c.

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

Referenced by apply_handle_delete(), and apply_handle_tuple_routing().

1514 {
1515  Relation localrel = relinfo->ri_RelationDesc;
1516  EPQState epqstate;
1517  TupleTableSlot *localslot;
1518  bool found;
1519 
1520  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
1521  ExecOpenIndices(relinfo, false);
1522 
1523  found = FindReplTupleInLocalRel(estate, localrel, remoterel,
1524  remoteslot, &localslot);
1525 
1526  /* If found delete it. */
1527  if (found)
1528  {
1529  EvalPlanQualSetSlot(&epqstate, localslot);
1530 
1531  /* Do the actual delete. */
1532  ExecSimpleRelationDelete(relinfo, estate, &epqstate, localslot);
1533  }
1534  else
1535  {
1536  /* The tuple to be deleted could not be found. */
1537  elog(DEBUG1,
1538  "logical replication did not find row for delete "
1539  "in replication target relation \"%s\"",
1540  RelationGetRelationName(localrel));
1541  }
1542 
1543  /* Cleanup. */
1544  ExecCloseIndices(relinfo);
1545  EvalPlanQualEnd(&epqstate);
1546 }
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:411
#define DEBUG1
Definition: elog.h:25
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2834
#define RelationGetRelationName(relation)
Definition: rel.h:506
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:1556
#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 1182 of file worker.c.

References apply_handle_insert_internal(), apply_handle_tuple_routing(), CMD_INSERT, CommandCounterIncrement(), create_estate_for_relation(), ensure_transaction(), ExecInitExtraTupleSlot(), finish_estate(), GetPerTupleMemoryContext, GetTransactionSnapshot(), handle_streamed_transaction(), LogicalRepRelMapEntry::localrel, LOGICAL_REP_MSG_INSERT, logicalrep_read_insert(), logicalrep_rel_close(), logicalrep_rel_open(), MemoryContextSwitchTo(), NoLock, PopActiveSnapshot(), PushActiveSnapshot(), RelationData::rd_rel, RelationGetDescr, RowExclusiveLock, should_apply_changes_for_rel(), slot_fill_defaults(), slot_store_data(), and TTSOpsVirtual.

Referenced by apply_dispatch().

1183 {
1184  ResultRelInfo *resultRelInfo;
1185  LogicalRepRelMapEntry *rel;
1186  LogicalRepTupleData newtup;
1187  LogicalRepRelId relid;
1188  EState *estate;
1189  TupleTableSlot *remoteslot;
1190  MemoryContext oldctx;
1191 
1193  return;
1194 
1196 
1197  relid = logicalrep_read_insert(s, &newtup);
1198  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1199  if (!should_apply_changes_for_rel(rel))
1200  {
1201  /*
1202  * The relation can't become interesting in the middle of the
1203  * transaction so it's safe to unlock it.
1204  */
1206  return;
1207  }
1208 
1209  /* Initialize the executor state. */
1210  estate = create_estate_for_relation(rel, &resultRelInfo);
1211  remoteslot = ExecInitExtraTupleSlot(estate,
1212  RelationGetDescr(rel->localrel),
1213  &TTSOpsVirtual);
1214 
1215  /* Input functions may need an active snapshot, so get one */
1217 
1218  /* Process and store remote tuple in the slot */
1220  slot_store_data(remoteslot, rel, &newtup);
1221  slot_fill_defaults(rel, estate, remoteslot);
1222  MemoryContextSwitchTo(oldctx);
1223 
1224  /* For a partitioned table, insert the tuple into a partition. */
1225  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1226  apply_handle_tuple_routing(resultRelInfo, estate,
1227  remoteslot, NULL, rel, CMD_INSERT);
1228  else
1229  apply_handle_insert_internal(resultRelInfo, estate,
1230  remoteslot);
1231 
1233 
1234  finish_estate(estate);
1235 
1237 
1239 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:263
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1831
#define RelationGetDescr(relation)
Definition: rel.h:498
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:447
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Form_pg_class rd_rel
Definition: rel.h:110
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
LogicalRepRelId logicalrep_read_insert(StringInfo in, LogicalRepTupleData *newtup)
Definition: proto.c:164
static void slot_fill_defaults(LogicalRepRelMapEntry *rel, EState *estate, TupleTableSlot *slot)
Definition: worker.c:413
static bool ensure_transaction(void)
Definition: worker.c:279
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define RowExclusiveLock
Definition: lockdefs.h:38
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:309
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:272
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel, ResultRelInfo **resultRelInfo)
Definition: worker.c:346
static void apply_handle_tuple_routing(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry, CmdType operation)
Definition: worker.c:1585
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:537
static void finish_estate(EState *estate)
Definition: worker.c:395
static void slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:504
uint32 LogicalRepRelId
Definition: logicalproto.h:85
static void apply_handle_insert_internal(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot)
Definition: worker.c:1243

◆ apply_handle_insert_internal()

static void apply_handle_insert_internal ( ResultRelInfo relinfo,
EState estate,
TupleTableSlot remoteslot 
)
static

Definition at line 1243 of file worker.c.

References ExecCloseIndices(), ExecOpenIndices(), and ExecSimpleRelationInsert().

Referenced by apply_handle_insert(), and apply_handle_tuple_routing().

1245 {
1246  ExecOpenIndices(relinfo, false);
1247 
1248  /* Do the insert. */
1249  ExecSimpleRelationInsert(relinfo, estate, remoteslot);
1250 
1251  /* Cleanup. */
1252  ExecCloseIndices(relinfo);
1253 }
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
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 767 of file worker.c.

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

Referenced by apply_dispatch().

768 {
769  /*
770  * ORIGIN message can only come inside streaming transaction or inside
771  * remote transaction and before any actual writes.
772  */
776  ereport(ERROR,
777  (errcode(ERRCODE_PROTOCOL_VIOLATION),
778  errmsg("ORIGIN message sent out of order")));
779 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
bool in_remote_transaction
Definition: worker.c:164
bool in_streamed_transaction
Definition: worker.c:168
static bool am_tablesync_worker(void)
#define ereport(elevel,...)
Definition: elog.h:157
bool IsTransactionState(void)
Definition: xact.c:371
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ apply_handle_relation()

static void apply_handle_relation ( StringInfo  s)
static

Definition at line 1130 of file worker.c.

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

Referenced by apply_dispatch().

1131 {
1132  LogicalRepRelation *rel;
1133 
1135  return;
1136 
1137  rel = logicalrep_read_rel(s);
1139 }
LogicalRepRelation * logicalrep_read_rel(StringInfo in)
Definition: proto.c:425
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:171
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:309

◆ apply_handle_stream_abort()

static void apply_handle_stream_abort ( StringInfo  s)
static

Definition at line 864 of file worker.c.

References Assert, BufFileClose(), BufFileOpenShared(), BufFileTruncateShared(), changes_filename(), cleanup_subxact_info(), CommitTransactionCommand(), ensure_transaction(), 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().

865 {
866  TransactionId xid;
867  TransactionId subxid;
868 
870 
871  logicalrep_read_stream_abort(s, &xid, &subxid);
872 
873  /*
874  * If the two XIDs are the same, it's in fact abort of toplevel xact, so
875  * just delete the files with serialized info.
876  */
877  if (xid == subxid)
879  else
880  {
881  /*
882  * OK, so it's a subxact. We need to read the subxact file for the
883  * toplevel transaction, determine the offset tracked for the subxact,
884  * and truncate the file with changes. We also remove the subxacts
885  * with higher offsets (or rather higher XIDs).
886  *
887  * We intentionally scan the array from the tail, because we're likely
888  * aborting a change for the most recent subtransactions.
889  *
890  * We can't use the binary search here as subxact XIDs won't
891  * necessarily arrive in sorted order, consider the case where we have
892  * released the savepoint for multiple subtransactions and then
893  * performed rollback to savepoint for one of the earlier
894  * sub-transaction.
895  */
896 
897  int64 i;
898  int64 subidx;
899  BufFile *fd;
900  bool found = false;
901  char path[MAXPGPATH];
902  StreamXidHash *ent;
903 
904  subidx = -1;
907 
908  for (i = subxact_data.nsubxacts; i > 0; i--)
909  {
910  if (subxact_data.subxacts[i - 1].xid == subxid)
911  {
912  subidx = (i - 1);
913  found = true;
914  break;
915  }
916  }
917 
918  /*
919  * If it's an empty sub-transaction then we will not find the subxid
920  * here so just cleanup the subxact info and return.
921  */
922  if (!found)
923  {
924  /* Cleanup the subxact info */
926 
928  return;
929  }
930 
931  Assert((subidx >= 0) && (subidx < subxact_data.nsubxacts));
932 
934  (void *) &xid,
935  HASH_FIND,
936  &found);
937  Assert(found);
938 
939  /* open the changes file */
941  fd = BufFileOpenShared(ent->stream_fileset, path, O_RDWR);
942 
943  /* OK, truncate the file at the right offset */
945  subxact_data.subxacts[subidx].offset);
946  BufFileClose(fd);
947 
948  /* discard the subxacts added later */
949  subxact_data.nsubxacts = subidx;
950 
951  /* write the updated subxact list */
953 
955  }
956 }
static void subxact_info_read(Oid subid, TransactionId xid)
Definition: worker.c:2604
int fileno
Definition: worker.c:184
uint32 TransactionId
Definition: c.h:587
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2759
void CommitTransactionCommand(void)
Definition: xact.c:2939
void BufFileTruncateShared(BufFile *file, int fileno, off_t offset)
Definition: buffile.c:861
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:191
void BufFileClose(BufFile *file)
Definition: buffile.c:395
SubXactInfo * subxacts
Definition: worker.c:194
static void stream_cleanup_files(Oid subid, TransactionId xid)
Definition: worker.c:2772
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
static bool ensure_transaction(void)
Definition: worker.c:279
#define MAXPGPATH
bool in_streamed_transaction
Definition: worker.c:168
SharedFileSet * stream_fileset
Definition: worker.c:149
BufFile * BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)
Definition: buffile.c:284
TransactionId xid
Definition: worker.c:183
static HTAB * xidhash
Definition: worker.c:176
#define Assert(condition)
Definition: c.h:804
off_t offset
Definition: worker.c:185
static void subxact_info_write(Oid subid, TransactionId xid)
Definition: worker.c:2526
static ApplySubXactData subxact_data
Definition: worker.c:197
int i
static void cleanup_subxact_info(void)
Definition: worker.c:2941
void logicalrep_read_stream_abort(StringInfo in, TransactionId *xid, TransactionId *subxid)
Definition: proto.c:893

◆ apply_handle_stream_commit()

static void apply_handle_stream_commit ( StringInfo  s)
static

Definition at line 962 of file worker.c.

References appendBinaryStringInfo(), apply_dispatch(), apply_handle_commit_internal(), Assert, BufFileClose(), BufFileOpenShared(), BufFileRead(), changes_filename(), CHECK_FOR_INTERRUPTS, LogicalRepCommitData::commit_lsn, StringInfoData::data, DEBUG1, elog, LogicalRepCommitData::end_lsn, ensure_transaction(), ereport, errcode_for_file_access(), errmsg(), ERROR, fd(), HASH_FIND, hash_search(), in_remote_transaction, in_streamed_transaction, initStringInfo(), logicalrep_read_stream_commit(), MAXPGPATH, MemoryContextReset(), MemoryContextSwitchTo(), MyLogicalRepWorker, palloc(), pfree(), pgstat_report_activity(), process_syncing_tables(), remote_final_lsn, repalloc(), resetStringInfo(), s2, STATE_IDLE, STATE_RUNNING, stream_cleanup_files(), StreamXidHash::stream_fileset, LogicalRepWorker::subid, and TopTransactionContext.

Referenced by apply_dispatch().

963 {
964  TransactionId xid;
966  int nchanges;
967  char path[MAXPGPATH];
968  char *buffer = NULL;
969  bool found;
970  LogicalRepCommitData commit_data;
971  StreamXidHash *ent;
972  MemoryContext oldcxt;
973  BufFile *fd;
974 
976 
977  xid = logicalrep_read_stream_commit(s, &commit_data);
978 
979  elog(DEBUG1, "received commit for streamed transaction %u", xid);
980 
982 
983  /*
984  * Allocate file handle and memory required to process all the messages in
985  * TopTransactionContext to avoid them getting reset after each message is
986  * processed.
987  */
989 
990  /* open the spool file for the committed transaction */
992  elog(DEBUG1, "replaying changes from file \"%s\"", path);
994  (void *) &xid,
995  HASH_FIND,
996  &found);
997  Assert(found);
998  fd = BufFileOpenShared(ent->stream_fileset, path, O_RDONLY);
999 
1000  buffer = palloc(BLCKSZ);
1001  initStringInfo(&s2);
1002 
1003  MemoryContextSwitchTo(oldcxt);
1004 
1005  remote_final_lsn = commit_data.commit_lsn;
1006 
1007  /*
1008  * Make sure the handle apply_dispatch methods are aware we're in a remote
1009  * transaction.
1010  */
1011  in_remote_transaction = true;
1013 
1014  /*
1015  * Read the entries one by one and pass them through the same logic as in
1016  * apply_dispatch.
1017  */
1018  nchanges = 0;
1019  while (true)
1020  {
1021  int nbytes;
1022  int len;
1023 
1025 
1026  /* read length of the on-disk record */
1027  nbytes = BufFileRead(fd, &len, sizeof(len));
1028 
1029  /* have we reached end of the file? */
1030  if (nbytes == 0)
1031  break;
1032 
1033  /* do we have a correct length? */
1034  if (nbytes != sizeof(len))
1035  ereport(ERROR,
1037  errmsg("could not read from streaming transaction's changes file \"%s\": %m",
1038  path)));
1039 
1040  Assert(len > 0);
1041 
1042  /* make sure we have sufficiently large buffer */
1043  buffer = repalloc(buffer, len);
1044 
1045  /* and finally read the data into the buffer */
1046  if (BufFileRead(fd, buffer, len) != len)
1047  ereport(ERROR,
1049  errmsg("could not read from streaming transaction's changes file \"%s\": %m",
1050  path)));
1051 
1052  /* copy the buffer to the stringinfo and call apply_dispatch */
1053  resetStringInfo(&s2);
1054  appendBinaryStringInfo(&s2, buffer, len);
1055 
1056  /* Ensure we are reading the data into our memory context. */
1058 
1059  apply_dispatch(&s2);
1060 
1062 
1063  MemoryContextSwitchTo(oldcxt);
1064 
1065  nchanges++;
1066 
1067  if (nchanges % 1000 == 0)
1068  elog(DEBUG1, "replayed %d changes from file '%s'",
1069  nchanges, path);
1070  }
1071 
1072  BufFileClose(fd);
1073 
1074  pfree(buffer);
1075  pfree(s2.data);
1076 
1077  elog(DEBUG1, "replayed %d (all) changes from file \"%s\"",
1078  nchanges, path);
1079 
1080  apply_handle_commit_internal(s, &commit_data);
1081 
1082  /* unlink the files with serialized changes and subxact info */
1084 
1085  /* Process any tables that are being synchronized in parallel. */
1086  process_syncing_tables(commit_data.end_lsn);
1087 
1089 }
#define DEBUG1
Definition: elog.h:25
MemoryContext TopTransactionContext
Definition: mcxt.c:53
static XLogRecPtr remote_final_lsn
Definition: worker.c:165
uint32 TransactionId
Definition: c.h:587
TransactionId logicalrep_read_stream_commit(StringInfo in, LogicalRepCommitData *commit_data)
Definition: proto.c:851
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2759
static void apply_handle_commit_internal(StringInfo s, LogicalRepCommitData *commit_data)
Definition: worker.c:1095
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
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
static void stream_cleanup_files(Oid subid, TransactionId xid)
Definition: worker.c:2772
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
static bool ensure_transaction(void)
Definition: worker.c:279
bool in_remote_transaction
Definition: worker.c:164
#define MAXPGPATH
bool in_streamed_transaction
Definition: worker.c:168
int errcode_for_file_access(void)
Definition: elog.c:721
SharedFileSet * stream_fileset
Definition: worker.c:149
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
#define ereport(elevel,...)
Definition: elog.h:157
static HTAB * xidhash
Definition: worker.c:176
static void apply_dispatch(StringInfo s)
Definition: worker.c:1924
static MemoryContext ApplyMessageContext
Definition: worker.c:153
#define Assert(condition)
Definition: c.h:804
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:102
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227

◆ apply_handle_stream_start()

static void apply_handle_stream_start ( StringInfo  s)
static

Definition at line 785 of file worker.c.

References ApplyContext, Assert, ensure_transaction(), HASHCTL::entrysize, 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, and subxact_info_read().

Referenced by apply_dispatch().

786 {
787  bool first_segment;
788  HASHCTL hash_ctl;
789 
791 
792  /*
793  * Start a transaction on stream start, this transaction will be committed
794  * on the stream stop unless it is a tablesync worker in which case it
795  * will be committed after processing all the messages. We need the
796  * transaction for handling the buffile, used for serializing the
797  * streaming data and subxact info.
798  */
800 
801  /* notify handle methods we're processing a remote transaction */
803 
804  /* extract XID of the top-level transaction */
805  stream_xid = logicalrep_read_stream_start(s, &first_segment);
806 
807  /*
808  * Initialize the xidhash table if we haven't yet. This will be used for
809  * the entire duration of the apply worker so create it in permanent
810  * context.
811  */
812  if (xidhash == NULL)
813  {
814  hash_ctl.keysize = sizeof(TransactionId);
815  hash_ctl.entrysize = sizeof(StreamXidHash);
816  hash_ctl.hcxt = ApplyContext;
817  xidhash = hash_create("StreamXidHash", 1024, &hash_ctl,
819  }
820 
821  /* open the spool file for this transaction */
823 
824  /* if this is not the first segment, open existing subxact file */
825  if (!first_segment)
827 
829 }
static void subxact_info_read(Oid subid, TransactionId xid)
Definition: worker.c:2604
#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
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
static bool ensure_transaction(void)
Definition: worker.c:279
bool in_streamed_transaction
Definition: worker.c:168
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
MemoryContext ApplyContext
Definition: worker.c:154
#define HASH_BLOBS
Definition: hsearch.h:97
Size keysize
Definition: hsearch.h:75
static HTAB * xidhash
Definition: worker.c:176
#define Assert(condition)
Definition: c.h:804
TransactionId logicalrep_read_stream_start(StringInfo in, bool *first_segment)
Definition: proto.c:801
void pgstat_report_activity(BackendState state, const char *cmd_str)
static void stream_open_file(Oid subid, TransactionId xid, bool first)
Definition: worker.c:2818
static TransactionId stream_xid
Definition: worker.c:170
struct StreamXidHash StreamXidHash

◆ apply_handle_stream_stop()

static void apply_handle_stream_stop ( StringInfo  s)
static

Definition at line 835 of file worker.c.

References Assert, CommitTransactionCommand(), 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().

836 {
838 
839  /*
840  * Close the file with serialized changes, and serialize information about
841  * subxacts for the toplevel transaction.
842  */
845 
846  /* We must be in a valid transaction state */
848 
849  /* Commit the per-stream transaction */
851 
852  in_streamed_transaction = false;
853 
854  /* Reset per-stream context */
856 
858 }
static void stream_close_file(void)
Definition: worker.c:2893
void CommitTransactionCommand(void)
Definition: xact.c:2939
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
bool in_streamed_transaction
Definition: worker.c:168
static MemoryContext LogicalStreamingContext
Definition: worker.c:157
#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:2526
void pgstat_report_activity(BackendState state, const char *cmd_str)
static TransactionId stream_xid
Definition: worker.c:170

◆ apply_handle_truncate()

static void apply_handle_truncate ( StringInfo  s)
static

Definition at line 1810 of file worker.c.

References CommandCounterIncrement(), DROP_RESTRICT, ensure_transaction(), 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, RowExclusiveLock, should_apply_changes_for_rel(), table_close(), and table_open().

Referenced by apply_dispatch().

1811 {
1812  bool cascade = false;
1813  bool restart_seqs = false;
1814  List *remote_relids = NIL;
1815  List *remote_rels = NIL;
1816  List *rels = NIL;
1817  List *part_rels = NIL;
1818  List *relids = NIL;
1819  List *relids_logged = NIL;
1820  ListCell *lc;
1821 
1823  return;
1824 
1826 
1827  remote_relids = logicalrep_read_truncate(s, &cascade, &restart_seqs);
1828 
1829  foreach(lc, remote_relids)
1830  {
1831  LogicalRepRelId relid = lfirst_oid(lc);
1832  LogicalRepRelMapEntry *rel;
1833 
1834  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1835  if (!should_apply_changes_for_rel(rel))
1836  {
1837  /*
1838  * The relation can't become interesting in the middle of the
1839  * transaction so it's safe to unlock it.
1840  */
1842  continue;
1843  }
1844 
1845  remote_rels = lappend(remote_rels, rel);
1846  rels = lappend(rels, rel->localrel);
1847  relids = lappend_oid(relids, rel->localreloid);
1849  relids_logged = lappend_oid(relids_logged, rel->localreloid);
1850 
1851  /*
1852  * Truncate partitions if we got a message to truncate a partitioned
1853  * table.
1854  */
1855  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1856  {
1857  ListCell *child;
1858  List *children = find_all_inheritors(rel->localreloid,
1860  NULL);
1861 
1862  foreach(child, children)
1863  {
1864  Oid childrelid = lfirst_oid(child);
1865  Relation childrel;
1866 
1867  if (list_member_oid(relids, childrelid))
1868  continue;
1869 
1870  /* find_all_inheritors already got lock */
1871  childrel = table_open(childrelid, NoLock);
1872 
1873  /*
1874  * Ignore temp tables of other backends. See similar code in
1875  * ExecuteTruncate().
1876  */
1877  if (RELATION_IS_OTHER_TEMP(childrel))
1878  {
1879  table_close(childrel, RowExclusiveLock);
1880  continue;
1881  }
1882 
1883  rels = lappend(rels, childrel);
1884  part_rels = lappend(part_rels, childrel);
1885  relids = lappend_oid(relids, childrelid);
1886  /* Log this relation only if needed for logical decoding */
1887  if (RelationIsLogicallyLogged(childrel))
1888  relids_logged = lappend_oid(relids_logged, childrelid);
1889  }
1890  }
1891  }
1892 
1893  /*
1894  * Even if we used CASCADE on the upstream primary we explicitly default
1895  * to replaying changes without further cascading. This might be later
1896  * changeable with a user specified option.
1897  */
1898  ExecuteTruncateGuts(rels,
1899  relids,
1900  relids_logged,
1901  DROP_RESTRICT,
1902  restart_seqs);
1903  foreach(lc, remote_rels)
1904  {
1905  LogicalRepRelMapEntry *rel = lfirst(lc);
1906 
1908  }
1909  foreach(lc, part_rels)
1910  {
1911  Relation rel = lfirst(lc);
1912 
1913  table_close(rel, NoLock);
1914  }
1915 
1917 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:263
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
List * logicalrep_read_truncate(StringInfo in, bool *cascade, bool *restart_seqs)
Definition: proto.c:344
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:447
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:658
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
static bool ensure_transaction(void)
Definition: worker.c:279
void ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs)
Definition: tablecmds.c:1745
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:309
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:272
List * lappend(List *list, void *datum)
Definition: list.c:336
void CommandCounterIncrement(void)
Definition: xact.c:1021
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:615
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:85
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ apply_handle_tuple_routing()

static void apply_handle_tuple_routing ( ResultRelInfo relinfo,
EState estate,
TupleTableSlot remoteslot,
LogicalRepTupleData newtup,
LogicalRepRelMapEntry relmapentry,
CmdType  operation 
)
static

Definition at line 1585 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, EvalPlanQualEnd(), EvalPlanQualInit(), EvalPlanQualSetSlot, ExecCleanupTupleRouting(), ExecCloseIndices(), ExecCopySlot(), ExecFindPartition(), ExecOpenIndices(), ExecPartitionCheck(), ExecSetupPartitionTupleRouting(), ExecSimpleRelationUpdate(), execute_attr_map_slot(), FindReplTupleInLocalRel(), GetPerTupleMemoryContext, logicalrep_partition_open(), makeNode, MemoryContextSwitchTo(), NIL, ModifyTableState::operation, PlanState::plan, 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, and table_slot_create().

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

1591 {
1592  Relation parentrel = relinfo->ri_RelationDesc;
1593  ModifyTableState *mtstate = NULL;
1594  PartitionTupleRouting *proute = NULL;
1595  ResultRelInfo *partrelinfo;
1596  Relation partrel;
1597  TupleTableSlot *remoteslot_part;
1598  TupleConversionMap *map;
1599  MemoryContext oldctx;
1600 
1601  /* ModifyTableState is needed for ExecFindPartition(). */
1602  mtstate = makeNode(ModifyTableState);
1603  mtstate->ps.plan = NULL;
1604  mtstate->ps.state = estate;
1605  mtstate->operation = operation;
1606  mtstate->resultRelInfo = relinfo;
1607  proute = ExecSetupPartitionTupleRouting(estate, parentrel);
1608 
1609  /*
1610  * Find the partition to which the "search tuple" belongs.
1611  */
1612  Assert(remoteslot != NULL);
1614  partrelinfo = ExecFindPartition(mtstate, relinfo, proute,
1615  remoteslot, estate);
1616  Assert(partrelinfo != NULL);
1617  partrel = partrelinfo->ri_RelationDesc;
1618 
1619  /*
1620  * To perform any of the operations below, the tuple must match the
1621  * partition's rowtype. Convert if needed or just copy, using a dedicated
1622  * slot to store the tuple in any case.
1623  */
1624  remoteslot_part = partrelinfo->ri_PartitionTupleSlot;
1625  if (remoteslot_part == NULL)
1626  remoteslot_part = table_slot_create(partrel, &estate->es_tupleTable);
1627  map = partrelinfo->ri_RootToPartitionMap;
1628  if (map != NULL)
1629  remoteslot_part = execute_attr_map_slot(map->attrMap, remoteslot,
1630  remoteslot_part);
1631  else
1632  {
1633  remoteslot_part = ExecCopySlot(remoteslot_part, remoteslot);
1634  slot_getallattrs(remoteslot_part);
1635  }
1636  MemoryContextSwitchTo(oldctx);
1637 
1638  switch (operation)
1639  {
1640  case CMD_INSERT:
1641  apply_handle_insert_internal(partrelinfo, estate,
1642  remoteslot_part);
1643  break;
1644 
1645  case CMD_DELETE:
1646  apply_handle_delete_internal(partrelinfo, estate,
1647  remoteslot_part,
1648  &relmapentry->remoterel);
1649  break;
1650 
1651  case CMD_UPDATE:
1652 
1653  /*
1654  * For UPDATE, depending on whether or not the updated tuple
1655  * satisfies the partition's constraint, perform a simple UPDATE
1656  * of the partition or move the updated tuple into a different
1657  * suitable partition.
1658  */
1659  {
1660  AttrMap *attrmap = map ? map->attrMap : NULL;
1661  LogicalRepRelMapEntry *part_entry;
1662  TupleTableSlot *localslot;
1663  ResultRelInfo *partrelinfo_new;
1664  bool found;
1665 
1666  part_entry = logicalrep_partition_open(relmapentry, partrel,
1667  attrmap);
1668 
1669  /* Get the matching local tuple from the partition. */
1670  found = FindReplTupleInLocalRel(estate, partrel,
1671  &part_entry->remoterel,
1672  remoteslot_part, &localslot);
1673 
1675  if (found)
1676  {
1677  /* Apply the update. */
1678  slot_modify_data(remoteslot_part, localslot,
1679  part_entry,
1680  newtup);
1681  MemoryContextSwitchTo(oldctx);
1682  }
1683  else
1684  {
1685  /*
1686  * The tuple to be updated could not be found.
1687  *
1688  * TODO what to do here, change the log level to LOG
1689  * perhaps?
1690  */
1691  elog(DEBUG1,
1692  "logical replication did not find row for update "
1693  "in replication target relation \"%s\"",
1694  RelationGetRelationName(partrel));
1695  }
1696 
1697  /*
1698  * Does the updated tuple still satisfy the current
1699  * partition's constraint?
1700  */
1701  if (!partrel->rd_rel->relispartition ||
1702  ExecPartitionCheck(partrelinfo, remoteslot_part, estate,
1703  false))
1704  {
1705  /*
1706  * Yes, so simply UPDATE the partition. We don't call
1707  * apply_handle_update_internal() here, which would
1708  * normally do the following work, to avoid repeating some
1709  * work already done above to find the local tuple in the
1710  * partition.
1711  */
1712  EPQState epqstate;
1713 
1714  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
1715  ExecOpenIndices(partrelinfo, false);
1716 
1717  EvalPlanQualSetSlot(&epqstate, remoteslot_part);
1718  ExecSimpleRelationUpdate(partrelinfo, estate, &epqstate,
1719  localslot, remoteslot_part);
1720  ExecCloseIndices(partrelinfo);
1721  EvalPlanQualEnd(&epqstate);
1722  }
1723  else
1724  {
1725  /* Move the tuple into the new partition. */
1726 
1727  /*
1728  * New partition will be found using tuple routing, which
1729  * can only occur via the parent table. We might need to
1730  * convert the tuple to the parent's rowtype. Note that
1731  * this is the tuple found in the partition, not the
1732  * original search tuple received by this function.
1733  */
1734  if (map)
1735  {
1736  TupleConversionMap *PartitionToRootMap =
1738  RelationGetDescr(parentrel));
1739 
1740  remoteslot =
1741  execute_attr_map_slot(PartitionToRootMap->attrMap,
1742  remoteslot_part, remoteslot);
1743  }
1744  else
1745  {
1746  remoteslot = ExecCopySlot(remoteslot, remoteslot_part);
1747  slot_getallattrs(remoteslot);
1748  }
1749 
1750 
1751  /* Find the new partition. */
1753  partrelinfo_new = ExecFindPartition(mtstate, relinfo,
1754  proute, remoteslot,
1755  estate);
1756  MemoryContextSwitchTo(oldctx);
1757  Assert(partrelinfo_new != partrelinfo);
1758 
1759  /* DELETE old tuple found in the old partition. */
1760  apply_handle_delete_internal(partrelinfo, estate,
1761  localslot,
1762  &relmapentry->remoterel);
1763 
1764  /* INSERT new tuple into the new partition. */
1765 
1766  /*
1767  * Convert the replacement tuple to match the destination
1768  * partition rowtype.
1769  */
1771  partrel = partrelinfo_new->ri_RelationDesc;
1772  remoteslot_part = partrelinfo_new->ri_PartitionTupleSlot;
1773  if (remoteslot_part == NULL)
1774  remoteslot_part = table_slot_create(partrel,
1775  &estate->es_tupleTable);
1776  map = partrelinfo_new->ri_RootToPartitionMap;
1777  if (map != NULL)
1778  {
1779  remoteslot_part = execute_attr_map_slot(map->attrMap,
1780  remoteslot,
1781  remoteslot_part);
1782  }
1783  else
1784  {
1785  remoteslot_part = ExecCopySlot(remoteslot_part,
1786  remoteslot);
1787  slot_getallattrs(remoteslot);
1788  }
1789  MemoryContextSwitchTo(oldctx);
1790  apply_handle_insert_internal(partrelinfo_new, estate,
1791  remoteslot_part);
1792  }
1793  }
1794  break;
1795 
1796  default:
1797  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1798  break;
1799  }
1800 
1801  ExecCleanupTupleRouting(mtstate, proute);
1802 }
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
static void apply_handle_delete_internal(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepRelation *remoterel)
Definition: worker.c:1511
#define RelationGetDescr(relation)
Definition: rel.h:498
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1188
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
CmdType operation
Definition: execnodes.h:1184
EState * state
Definition: execnodes.h:966
Form_pg_class rd_rel
Definition: rel.h:110
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
#define ERROR
Definition: elog.h:46
PlanState ps
Definition: execnodes.h:1183
LogicalRepRelation remoterel
void ExecCleanupTupleRouting(ModifyTableState *mtstate, PartitionTupleRouting *proute)
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:513
static void slot_modify_data(TupleTableSlot *slot, TupleTableSlot *srcslot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:619
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:102
#define RelationGetRelationName(relation)
Definition: rel.h:506
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:600
static bool FindReplTupleInLocalRel(EState *estate, Relation localrel, LogicalRepRelation *remoterel, TupleTableSlot *remoteslot, TupleTableSlot **localslot)
Definition: worker.c:1556
Plan * plan
Definition: execnodes.h:964
LogicalRepRelMapEntry * logicalrep_partition_open(LogicalRepRelMapEntry *root, Relation partrel, AttrMap *map)
Definition: relation.c:629
#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:537
TupleConversionMap * ri_RootToPartitionMap
Definition: execnodes.h:512
#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
static void apply_handle_insert_internal(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot)
Definition: worker.c:1243
PartitionTupleRouting * ExecSetupPartitionTupleRouting(EState *estate, Relation rel)

◆ apply_handle_type()

static void apply_handle_type ( StringInfo  s)
static

Definition at line 1148 of file worker.c.

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

Referenced by apply_dispatch().

1149 {
1150  LogicalRepTyp typ;
1151 
1153  return;
1154 
1155  logicalrep_read_typ(s, &typ);
1157 }
void logicalrep_read_typ(StringInfo in, LogicalRepTyp *ltyp)
Definition: proto.c:481
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:309
void logicalrep_typmap_update(LogicalRepTyp *remotetyp)
Definition: relation.c:467

◆ apply_handle_update()

static void apply_handle_update ( StringInfo  s)
static

Definition at line 1294 of file worker.c.

References apply_handle_tuple_routing(), apply_handle_update_internal(), Assert, AttrMap::attnums, LogicalRepRelMapEntry::attrmap, bms_add_member(), check_relation_updatable(), CMD_UPDATE, LogicalRepTupleData::colstatus, CommandCounterIncrement(), create_estate_for_relation(), ensure_transaction(), EState::es_range_table, ExecInitExtraTupleSlot(), fill_extraUpdatedCols(), finish_estate(), FirstLowInvalidHeapAttributeNumber, GetPerTupleMemoryContext, GetTransactionSnapshot(), 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, PopActiveSnapshot(), PushActiveSnapshot(), RelationData::rd_rel, RelationGetDescr, RowExclusiveLock, should_apply_changes_for_rel(), slot_store_data(), TupleTableSlot::tts_tupleDescriptor, TTSOpsVirtual, TupleDescAttr, and RangeTblEntry::updatedCols.

Referenced by apply_dispatch().

1295 {
1296  ResultRelInfo *resultRelInfo;
1297  LogicalRepRelMapEntry *rel;
1298  LogicalRepRelId relid;
1299  EState *estate;
1300  LogicalRepTupleData oldtup;
1301  LogicalRepTupleData newtup;
1302  bool has_oldtup;
1303  TupleTableSlot *remoteslot;
1304  RangeTblEntry *target_rte;
1305  MemoryContext oldctx;
1306 
1308  return;
1309 
1311 
1312  relid = logicalrep_read_update(s, &has_oldtup, &oldtup,
1313  &newtup);
1314  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1315  if (!should_apply_changes_for_rel(rel))
1316  {
1317  /*
1318  * The relation can't become interesting in the middle of the
1319  * transaction so it's safe to unlock it.
1320  */
1322  return;
1323  }
1324 
1325  /* Check if we can do the update. */
1327 
1328  /* Initialize the executor state. */
1329  estate = create_estate_for_relation(rel, &resultRelInfo);
1330  remoteslot = ExecInitExtraTupleSlot(estate,
1331  RelationGetDescr(rel->localrel),
1332  &TTSOpsVirtual);
1333 
1334  /*
1335  * Populate updatedCols so that per-column triggers can fire, and so
1336  * executor can correctly pass down indexUnchanged hint. This could
1337  * include more columns than were actually changed on the publisher
1338  * because the logical replication protocol doesn't contain that
1339  * information. But it would for example exclude columns that only exist
1340  * on the subscriber, since we are not touching those.
1341  */
1342  target_rte = list_nth(estate->es_range_table, 0);
1343  for (int i = 0; i < remoteslot->tts_tupleDescriptor->natts; i++)
1344  {
1346  int remoteattnum = rel->attrmap->attnums[i];
1347 
1348  if (!att->attisdropped && remoteattnum >= 0)
1349  {
1350  Assert(remoteattnum < newtup.ncols);
1351  if (newtup.colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
1352  target_rte->updatedCols =
1353  bms_add_member(target_rte->updatedCols,
1355  }
1356  }
1357 
1358  /* Also populate extraUpdatedCols, in case we have generated columns */
1359  fill_extraUpdatedCols(target_rte, rel->localrel);
1360 
1362 
1363  /* Build the search tuple. */
1365  slot_store_data(remoteslot, rel,
1366  has_oldtup ? &oldtup : &newtup);
1367  MemoryContextSwitchTo(oldctx);
1368 
1369  /* For a partitioned table, apply update to correct partition. */
1370  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1371  apply_handle_tuple_routing(resultRelInfo, estate,
1372  remoteslot, &newtup, rel, CMD_UPDATE);
1373  else
1374  apply_handle_update_internal(resultRelInfo, estate,
1375  remoteslot, &newtup, rel);
1376 
1378 
1379  finish_estate(estate);
1380 
1382 
1384 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:263
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1831
#define RelationGetDescr(relation)
Definition: rel.h:498
static void apply_handle_update_internal(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry)
Definition: worker.c:1388
#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:447
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
List * es_range_table
Definition: execnodes.h:558
Form_pg_class rd_rel
Definition: rel.h:110
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define LOGICALREP_COLUMN_UNCHANGED
Definition: logicalproto.h:81
static bool ensure_transaction(void)
Definition: worker.c:279
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
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:309
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:272
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel, ResultRelInfo **resultRelInfo)
Definition: worker.c:346
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:1260
static void apply_handle_tuple_routing(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry, CmdType operation)
Definition: worker.c:1585
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
void CommandCounterIncrement(void)
Definition: xact.c:1021
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:219
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:537
static void finish_estate(EState *estate)
Definition: worker.c:395
int i
static void slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:504
uint32 LogicalRepRelId
Definition: logicalproto.h:85

◆ apply_handle_update_internal()

static void apply_handle_update_internal ( ResultRelInfo relinfo,
EState estate,
TupleTableSlot remoteslot,
LogicalRepTupleData newtup,
LogicalRepRelMapEntry relmapentry 
)
static

Definition at line 1388 of file worker.c.

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

Referenced by apply_handle_update().

1392 {
1393  Relation localrel = relinfo->ri_RelationDesc;
1394  EPQState epqstate;
1395  TupleTableSlot *localslot;
1396  bool found;
1397  MemoryContext oldctx;
1398 
1399  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
1400  ExecOpenIndices(relinfo, false);
1401 
1402  found = FindReplTupleInLocalRel(estate, localrel,
1403  &relmapentry->remoterel,
1404  remoteslot, &localslot);
1405  ExecClearTuple(remoteslot);
1406 
1407  /*
1408  * Tuple found.
1409  *
1410  * Note this will fail if there are other conflicting unique indexes.
1411  */
1412  if (found)
1413  {
1414  /* Process and store remote tuple in the slot */
1416  slot_modify_data(remoteslot, localslot, relmapentry, newtup);
1417  MemoryContextSwitchTo(oldctx);
1418 
1419  EvalPlanQualSetSlot(&epqstate, remoteslot);
1420 
1421  /* Do the actual update. */
1422  ExecSimpleRelationUpdate(relinfo, estate, &epqstate, localslot,
1423  remoteslot);
1424  }
1425  else
1426  {
1427  /*
1428  * The tuple to be updated could not be found.
1429  *
1430  * TODO what to do here, change the log level to LOG perhaps?
1431  */
1432  elog(DEBUG1,
1433  "logical replication did not find row for update "
1434  "in replication target relation \"%s\"",
1435  RelationGetRelationName(localrel));
1436  }
1437 
1438  /* Cleanup. */
1439  ExecCloseIndices(relinfo);
1440  EvalPlanQualEnd(&epqstate);
1441 }
#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
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:619
#define RelationGetRelationName(relation)
Definition: rel.h:506
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:1556
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:537
#define elog(elevel,...)
Definition: elog.h:232
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:231
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:227

◆ ApplyWorkerMain()

void ApplyWorkerMain ( Datum  main_arg)

Definition at line 2954 of file worker.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_tablesync_worker(), BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), Subscription::binary, CacheRegisterSyscacheCallback(), CommitTransactionCommand(), Subscription::conninfo, DatumGetInt32, LogicalRepWorker::dbid, DEBUG1, die, elog, Subscription::enabled, ereport, errmsg(), ERROR, get_rel_name(), GetCurrentTimestamp(), GetSubscription(), invalidate_syncing_table_states(), LogicalRepWorker::last_recv_time, LogicalRepWorker::last_send_time, load_file(), LOG, WalRcvStreamOptions::logical, LOGICALREP_PROTO_STREAM_VERSION_NUM, LOGICALREP_PROTO_VERSION_NUM, 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, SetConfigOption(), SIGHUP, SignalHandlerForConfigReload(), Subscription::slotname, WalRcvStreamOptions::slotname, snprintf, WalRcvStreamOptions::startpoint, StartTransactionCommand(), Subscription::stream, LogicalRepWorker::subid, subscription_change_cb(), SUBSCRIPTIONOID, SUBSCRIPTIONRELMAP, Subscription::synccommit, TopMemoryContext, LogicalRepWorker::userid, walrcv_connect, walrcv_identify_system, walrcv_server_version, and walrcv_startstreaming.

2955 {
2956  int worker_slot = DatumGetInt32(main_arg);
2957  MemoryContext oldctx;
2958  char originname[NAMEDATALEN];
2959  XLogRecPtr origin_startpos;
2960  char *myslotname;
2962 
2963  /* Attach to slot */
2964  logicalrep_worker_attach(worker_slot);
2965 
2966  /* Setup signal handling */
2968  pqsignal(SIGTERM, die);
2970 
2971  /*
2972  * We don't currently need any ResourceOwner in a walreceiver process, but
2973  * if we did, we could call CreateAuxProcessResourceOwner here.
2974  */
2975 
2976  /* Initialise stats to a sanish value */
2979 
2980  /* Load the libpq-specific functions */
2981  load_file("libpqwalreceiver", false);
2982 
2983  /* Run as replica session replication role. */
2984  SetConfigOption("session_replication_role", "replica",
2986 
2987  /* Connect to our database. */
2990  0);
2991 
2992  /*
2993  * Set always-secure search path, so malicious users can't redirect user
2994  * code (e.g. pg_index.indexprs).
2995  */
2996  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
2997 
2998  /* Load the subscription into persistent memory context. */
3000  "ApplyContext",
3004 
3006  if (!MySubscription)
3007  {
3008  ereport(LOG,
3009  (errmsg("logical replication apply worker for subscription %u will not "
3010  "start because the subscription was removed during startup",
3012  proc_exit(0);
3013  }
3014 
3015  MySubscriptionValid = true;
3016  MemoryContextSwitchTo(oldctx);
3017 
3018  if (!MySubscription->enabled)
3019  {
3020  ereport(LOG,
3021  (errmsg("logical replication apply worker for subscription \"%s\" will not "
3022  "start because the subscription was disabled during startup",
3023  MySubscription->name)));
3024 
3025  proc_exit(0);
3026  }
3027 
3028  /* Setup synchronous commit according to the user's wishes */
3029  SetConfigOption("synchronous_commit", MySubscription->synccommit,
3031 
3032  /* Keep us informed about subscription changes. */
3035  (Datum) 0);
3036 
3037  if (am_tablesync_worker())
3038  ereport(LOG,
3039  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has started",
3041  else
3042  ereport(LOG,
3043  (errmsg("logical replication apply worker for subscription \"%s\" has started",
3044  MySubscription->name)));
3045 
3047 
3048  /* Connect to the origin and start the replication. */
3049  elog(DEBUG1, "connecting to publisher using connection string \"%s\"",
3051 
3052  if (am_tablesync_worker())
3053  {
3054  char *syncslotname;
3055 
3056  /* This is table synchronization worker, call initial sync. */
3057  syncslotname = LogicalRepSyncTableStart(&origin_startpos);
3058 
3059  /* allocate slot name in long-lived context */
3060  myslotname = MemoryContextStrdup(ApplyContext, syncslotname);
3061 
3062  pfree(syncslotname);
3063  }
3064  else
3065  {
3066  /* This is main apply worker */
3067  RepOriginId originid;
3068  TimeLineID startpointTLI;
3069  char *err;
3070 
3071  myslotname = MySubscription->slotname;
3072 
3073  /*
3074  * This shouldn't happen if the subscription is enabled, but guard
3075  * against DDL bugs or manual catalog changes. (libpqwalreceiver will
3076  * crash if slot is NULL.)
3077  */
3078  if (!myslotname)
3079  ereport(ERROR,
3080  (errmsg("subscription has no replication slot set")));
3081 
3082  /* Setup replication origin tracking. */
3084  snprintf(originname, sizeof(originname), "pg_%u", MySubscription->oid);
3085  originid = replorigin_by_name(originname, true);
3086  if (!OidIsValid(originid))
3087  originid = replorigin_create(originname);
3088  replorigin_session_setup(originid);
3089  replorigin_session_origin = originid;
3090  origin_startpos = replorigin_session_get_progress(false);
3092 
3094  &err);
3095  if (wrconn == NULL)
3096  ereport(ERROR,
3097  (errmsg("could not connect to the publisher: %s", err)));
3098 
3099  /*
3100  * We don't really use the output identify_system for anything but it
3101  * does some initializations on the upstream so let's still call it.
3102  */
3103  (void) walrcv_identify_system(wrconn, &startpointTLI);
3104  }
3105 
3106  /*
3107  * Setup callback for syscache so that we know when something changes in
3108  * the subscription relation state.
3109  */
3112  (Datum) 0);
3113 
3114  /* Build logical replication streaming options. */
3115  options.logical = true;
3116  options.startpoint = origin_startpos;
3117  options.slotname = myslotname;
3118  options.proto.logical.proto_version =
3119  walrcv_server_version(wrconn) >= 140000 ?
3121  options.proto.logical.publication_names = MySubscription->publications;
3122  options.proto.logical.binary = MySubscription->binary;
3123  options.proto.logical.streaming = MySubscription->stream;
3124 
3125  /* Start normal logical streaming replication. */
3126  walrcv_startstreaming(wrconn, &options);
3127 
3128  /* Run the main loop. */
3129  LogicalRepApplyLoop(origin_startpos);
3130 
3131  proc_exit(0);
3132 }
Subscription * MySubscription
Definition: worker.c:161
#define LOGICALREP_PROTO_VERSION_NUM
Definition: logicalproto.h:32
WalReceiverConn * wrconn
Definition: worker.c:159
#define AllocSetContextCreate
Definition: memutils.h:173
#define DEBUG1
Definition: elog.h:25
uint32 TimeLineID
Definition: xlogdefs.h:59
#define DatumGetInt32(X)
Definition: postgres.h:516
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
#define walrcv_identify_system(conn, primary_tli)
Definition: walreceiver.h:409
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void CommitTransactionCommand(void)
Definition: xact.c:2939
#define walrcv_server_version(conn)
Definition: walreceiver.h:411
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:415
void proc_exit(int code)
Definition: ipc.c:104
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1203
void replorigin_session_setup(RepOriginId node)
Definition: origin.c:1068
#define LOG
Definition: elog.h:26
char * LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
Definition: tablesync.c:913
#define OidIsValid(objectId)
Definition: c.h:710
RepOriginId replorigin_by_name(char *roname, bool missing_ok)
Definition: origin.c:209
#define NAMEDATALEN
Subscription * GetSubscription(Oid subid, bool missing_ok)
static void subscription_change_cb(Datum arg, int cacheid, uint32 hashvalue)
Definition: worker.c:2511
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:570
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8102
#define SIGHUP
Definition: win32_port.h:159
XLogRecPtr startpoint
Definition: walreceiver.h:170
List * publications
RepOriginId replorigin_create(char *roname)
Definition: origin.c:240
MemoryContext TopMemoryContext
Definition: mcxt.c:48
MemoryContext ApplyContext
Definition: worker.c:154
static char ** options
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1434
uintptr_t Datum
Definition: postgres.h:411
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: postmaster.c:5694
#define ereport(elevel,...)
Definition: elog.h:157
#define LOGICALREP_PROTO_STREAM_VERSION_NUM
Definition: logicalproto.h:33
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
TimestampTz last_recv_time
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
bool MySubscriptionValid
Definition: worker.c:162
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:2090
#define elog(elevel,...)
Definition: elog.h:232
union WalRcvStreamOptions::@103 proto
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:264
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5723
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:401

◆ changes_filename()

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

Definition at line 2759 of file worker.c.

References MAXPGPATH, and snprintf.

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

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

◆ check_relation_updatable()

static void check_relation_updatable ( LogicalRepRelMapEntry rel)
static

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

1261 {
1262  /* Updatable, no error. */
1263  if (rel->updatable)
1264  return;
1265 
1266  /*
1267  * We are in error mode so it's fine this is somewhat slow. It's better to
1268  * give user correct error.
1269  */
1271  {
1272  ereport(ERROR,
1273  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1274  errmsg("publisher did not send replica identity column "
1275  "expected by the logical replication target relation \"%s.%s\"",
1276  rel->remoterel.nspname, rel->remoterel.relname)));
1277  }
1278 
1279  ereport(ERROR,
1280  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1281  errmsg("logical replication target relation \"%s.%s\" has "
1282  "neither REPLICA IDENTITY index nor PRIMARY "
1283  "KEY and published relation does not have "
1284  "REPLICA IDENTITY FULL",
1285  rel->remoterel.nspname, rel->remoterel.relname)));
1286 }
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:1165
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 2941 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().

2942 {
2943  if (subxact_data.subxacts)
2945 
2946  subxact_data.subxacts = NULL;
2948  subxact_data.nsubxacts = 0;
2950 }
TransactionId subxact_last
Definition: worker.c:193
uint32 nsubxacts
Definition: worker.c:191
void pfree(void *pointer)
Definition: mcxt.c:1169
SubXactInfo * subxacts
Definition: worker.c:194
#define InvalidTransactionId
Definition: transam.h:31
static ApplySubXactData subxact_data
Definition: worker.c:197
uint32 nsubxacts_max
Definition: worker.c:192

◆ create_estate_for_relation()

static EState* create_estate_for_relation ( LogicalRepRelMapEntry rel,
ResultRelInfo **  resultRelInfo 
)
static

Definition at line 346 of file worker.c.

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

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

348 {
349  EState *estate;
350  RangeTblEntry *rte;
351 
352  estate = CreateExecutorState();
353 
354  rte = makeNode(RangeTblEntry);
355  rte->rtekind = RTE_RELATION;
356  rte->relid = RelationGetRelid(rel->localrel);
357  rte->relkind = rel->localrel->rd_rel->relkind;
359  ExecInitRangeTable(estate, list_make1(rte));
360 
361  *resultRelInfo = makeNode(ResultRelInfo);
362 
363  /*
364  * Use Relation opened by logicalrep_rel_open() instead of opening it
365  * again.
366  */
367  InitResultRelInfo(*resultRelInfo, rel->localrel, 1, NULL, 0);
368 
369  /*
370  * We put the ResultRelInfo in the es_opened_result_relations list, even
371  * though we don't populate the es_result_relations array. That's a bit
372  * bogus, but it's enough to make ExecGetTriggerResultRel() find them.
373  * Also, because we did not open the Relation ourselves here, there is no
374  * need to worry about closing it.
375  *
376  * ExecOpenIndices() is not called here either, each execution path doing
377  * an apply operation being responsible for that.
378  */
380  lappend(estate->es_opened_result_relations, *resultRelInfo);
381 
382  estate->es_output_cid = GetCurrentCommandId(true);
383 
384  /* Prepare to catch AFTER triggers. */
386 
387  return estate;
388 }
void ExecInitRangeTable(EState *estate, List *rangeTable)
Definition: execUtils.c:751
CommandId es_output_cid
Definition: execnodes.h:570
#define AccessShareLock
Definition: lockdefs.h:36
Form_pg_class rd_rel
Definition: rel.h:110
#define list_make1(x1)
Definition: pg_list.h:206
List * es_opened_result_relations
Definition: execnodes.h:576
EState * CreateExecutorState(void)
Definition: execUtils.c:90
List * lappend(List *list, void *datum)
Definition: list.c:336
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:4519
#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:472

◆ ensure_transaction()

static bool ensure_transaction ( void  )
static

Definition at line 279 of file worker.c.

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

Referenced by apply_handle_delete(), apply_handle_insert(), apply_handle_stream_abort(), apply_handle_stream_commit(), apply_handle_stream_start(), apply_handle_truncate(), and apply_handle_update().

280 {
281  if (IsTransactionState())
282  {
284 
287 
288  return false;
289  }
290 
293 
295 
297  return true;
298 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
static void maybe_reread_subscription(void)
Definition: worker.c:2413
static MemoryContext ApplyMessageContext
Definition: worker.c:153
void StartTransactionCommand(void)
Definition: xact.c:2838
bool IsTransactionState(void)
Definition: xact.c:371
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:833

◆ FindReplTupleInLocalRel()

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

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

1560 {
1561  Oid idxoid;
1562  bool found;
1563 
1564  *localslot = table_slot_create(localrel, &estate->es_tupleTable);
1565 
1566  idxoid = GetRelationIdentityOrPK(localrel);
1567  Assert(OidIsValid(idxoid) ||
1568  (remoterel->replident == REPLICA_IDENTITY_FULL));
1569 
1570  if (OidIsValid(idxoid))
1571  found = RelationFindReplTupleByIndex(localrel, idxoid,
1573  remoteslot, *localslot);
1574  else
1575  found = RelationFindReplTupleSeq(localrel, LockTupleExclusive,
1576  remoteslot, *localslot);
1577 
1578  return found;
1579 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:1165
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:600
#define Assert(condition)
Definition: c.h:804
bool RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)

◆ finish_estate()

static void finish_estate ( EState estate)
static

Definition at line 395 of file worker.c.

References AfterTriggerEndQuery(), EState::es_tupleTable, ExecResetTupleTable(), and FreeExecutorState().

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

396 {
397  /* Handle any queued AFTER triggers. */
398  AfterTriggerEndQuery(estate);
399 
400  /* Cleanup. */
401  ExecResetTupleTable(estate->es_tupleTable, false);
402  FreeExecutorState(estate);
403 }
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
List * es_tupleTable
Definition: execnodes.h:600
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1191
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4539

◆ get_flush_position()

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

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

2013 {
2014  dlist_mutable_iter iter;
2015  XLogRecPtr local_flush = GetFlushRecPtr();
2016 
2018  *flush = InvalidXLogRecPtr;
2019 
2021  {
2022  FlushPosition *pos =
2023  dlist_container(FlushPosition, node, iter.cur);
2024 
2025  *write = pos->remote_end;
2026 
2027  if (pos->local_end <= local_flush)
2028  {
2029  *flush = pos->remote_end;
2030  dlist_delete(iter.cur);
2031  pfree(pos);
2032  }
2033  else
2034  {
2035  /*
2036  * Don't want to uselessly iterate over the rest of the list which
2037  * could potentially be long. Instead get the last element and
2038  * grab the write position from there.
2039  */
2040  pos = dlist_tail_element(FlushPosition, node,
2041  &lsn_mapping);
2042  *write = pos->remote_end;
2043  *have_pending_txes = true;
2044  return;
2045  }
2046  }
2047 
2048  *have_pending_txes = !dlist_is_empty(&lsn_mapping);
2049 }
#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:130
#define write(a, b, c)
Definition: win32.h:14
XLogRecPtr remote_end
Definition: worker.c:127
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8589
#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:126
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 1165 of file worker.c.

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

Referenced by check_relation_updatable(), and FindReplTupleInLocalRel().

1166 {
1167  Oid idxoid;
1168 
1169  idxoid = RelationGetReplicaIndex(rel);
1170 
1171  if (!OidIsValid(idxoid))
1172  idxoid = RelationGetPrimaryKeyIndex(rel);
1173 
1174  return idxoid;
1175 }
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4780
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
Oid RelationGetPrimaryKeyIndex(Relation relation)
Definition: relcache.c:4759

◆ handle_streamed_transaction()

static bool handle_streamed_transaction ( LogicalRepMsgType  action,
StringInfo  s 
)
static

Definition at line 309 of file worker.c.

References Assert, 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().

310 {
311  TransactionId xid;
312 
313  /* not in streaming mode */
315  return false;
316 
317  Assert(stream_fd != NULL);
319 
320  /*
321  * We should have received XID of the subxact as the first part of the
322  * message, so extract it.
323  */
324  xid = pq_getmsgint(s, 4);
325 
327 
328  /* Add the new subxact to the array (unless already there). */
329  subxact_info_add(xid);
330 
331  /* write the change to the current file */
333 
334  return true;
335 }
static void stream_write_change(char action, StringInfo s)
Definition: worker.c:2914
static void subxact_info_add(TransactionId xid)
Definition: worker.c:2674
uint32 TransactionId
Definition: c.h:587
bool in_streamed_transaction
Definition: worker.c:168
#define Assert(condition)
Definition: c.h:804
static BufFile * stream_fd
Definition: worker.c:179
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:170

◆ IsLogicalWorker()

bool IsLogicalWorker ( void  )

Definition at line 3138 of file worker.c.

References MyLogicalRepWorker.

Referenced by ProcessInterrupts().

3139 {
3140  return MyLogicalRepWorker != NULL;
3141 }
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57

◆ LogicalRepApplyLoop()

static void LogicalRepApplyLoop ( XLogRecPtr  last_received)
static

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

2091 {
2092  TimestampTz last_recv_timestamp = GetCurrentTimestamp();
2093  bool ping_sent = false;
2094  TimeLineID tli;
2095 
2096  /*
2097  * Init the ApplyMessageContext which we clean up after each replication
2098  * protocol message.
2099  */
2101  "ApplyMessageContext",
2103 
2104  /*
2105  * This memory context is used for per-stream data when the streaming mode
2106  * is enabled. This context is reset on each stream stop.
2107  */
2109  "LogicalStreamingContext",
2111 
2112  /* mark as idle, before starting to loop */
2114 
2115  /* This outer loop iterates once per wait. */
2116  for (;;)
2117  {
2119  int rc;
2120  int len;
2121  char *buf = NULL;
2122  bool endofstream = false;
2123  long wait_time;
2124 
2126 
2128 
2129  len = walrcv_receive(wrconn, &buf, &fd);
2130 
2131  if (len != 0)
2132  {
2133  /* Loop to process all available data (without blocking). */
2134  for (;;)
2135  {
2137 
2138  if (len == 0)
2139  {
2140  break;
2141  }
2142  else if (len < 0)
2143  {
2144  ereport(LOG,
2145  (errmsg("data stream from publisher has ended")));
2146  endofstream = true;
2147  break;
2148  }
2149  else
2150  {
2151  int c;
2152  StringInfoData s;
2153 
2154  /* Reset timeout. */
2155  last_recv_timestamp = GetCurrentTimestamp();
2156  ping_sent = false;
2157 
2158  /* Ensure we are reading the data into our memory context. */
2160 
2161  s.data = buf;
2162  s.len = len;
2163  s.cursor = 0;
2164  s.maxlen = -1;
2165 
2166  c = pq_getmsgbyte(&s);
2167 
2168  if (c == 'w')
2169  {
2170  XLogRecPtr start_lsn;
2171  XLogRecPtr end_lsn;
2172  TimestampTz send_time;
2173 
2174  start_lsn = pq_getmsgint64(&s);
2175  end_lsn = pq_getmsgint64(&s);
2176  send_time = pq_getmsgint64(&s);
2177 
2178  if (last_received < start_lsn)
2179  last_received = start_lsn;
2180 
2181  if (last_received < end_lsn)
2182  last_received = end_lsn;
2183 
2184  UpdateWorkerStats(last_received, send_time, false);
2185 
2186  apply_dispatch(&s);
2187  }
2188  else if (c == 'k')
2189  {
2190  XLogRecPtr end_lsn;
2192  bool reply_requested;
2193 
2194  end_lsn = pq_getmsgint64(&s);
2195  timestamp = pq_getmsgint64(&s);
2196  reply_requested = pq_getmsgbyte(&s);
2197 
2198  if (last_received < end_lsn)
2199  last_received = end_lsn;
2200 
2201  send_feedback(last_received, reply_requested, false);
2202  UpdateWorkerStats(last_received, timestamp, true);
2203  }
2204  /* other message types are purposefully ignored */
2205 
2207  }
2208 
2209  len = walrcv_receive(wrconn, &buf, &fd);
2210  }
2211  }
2212 
2213  /* confirm all writes so far */
2214  send_feedback(last_received, false, false);
2215 
2217  {
2218  /*
2219  * If we didn't get any transactions for a while there might be
2220  * unconsumed invalidation messages in the queue, consume them
2221  * now.
2222  */
2225 
2226  /* Process any table synchronization changes. */
2227  process_syncing_tables(last_received);
2228  }
2229 
2230  /* Cleanup the memory. */
2233 
2234  /* Check if we need to exit the streaming loop. */
2235  if (endofstream)
2236  break;
2237 
2238  /*
2239  * Wait for more data or latch. If we have unflushed transactions,
2240  * wake up after WalWriterDelay to see if they've been flushed yet (in
2241  * which case we should send a feedback message). Otherwise, there's
2242  * no particular urgency about waking up unless we get data or a
2243  * signal.
2244  */
2245  if (!dlist_is_empty(&lsn_mapping))
2246  wait_time = WalWriterDelay;
2247  else
2248  wait_time = NAPTIME_PER_CYCLE;
2249 
2253  fd, wait_time,
2255 
2256  if (rc & WL_LATCH_SET)
2257  {
2260  }
2261 
2262  if (ConfigReloadPending)
2263  {
2264  ConfigReloadPending = false;
2266  }
2267 
2268  if (rc & WL_TIMEOUT)
2269  {
2270  /*
2271  * We didn't receive anything new. If we haven't heard anything
2272  * from the server for more than wal_receiver_timeout / 2, ping
2273  * the server. Also, if it's been longer than
2274  * wal_receiver_status_interval since the last update we sent,
2275  * send a status update to the primary anyway, to report any
2276  * progress in applying WAL.
2277  */
2278  bool requestReply = false;
2279 
2280  /*
2281  * Check if time since last receive from primary has reached the
2282  * configured limit.
2283  */
2284  if (wal_receiver_timeout > 0)
2285  {
2287  TimestampTz timeout;
2288 
2289  timeout =
2290  TimestampTzPlusMilliseconds(last_recv_timestamp,
2292 
2293  if (now >= timeout)
2294  ereport(ERROR,
2295  (errmsg("terminating logical replication worker due to timeout")));
2296 
2297  /* Check to see if it's time for a ping. */
2298  if (!ping_sent)
2299  {
2300  timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
2301  (wal_receiver_timeout / 2));
2302  if (now >= timeout)
2303  {
2304  requestReply = true;
2305  ping_sent = true;
2306  }
2307  }
2308  }
2309 
2310  send_feedback(last_received, requestReply, requestReply);
2311  }
2312  }
2313 
2314  /* All done */
2315  walrcv_endstreaming(wrconn, &tli);
2316 }
static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
Definition: worker.c:2325
WalReceiverConn * wrconn
Definition: worker.c:159
#define AllocSetContextCreate
Definition: memutils.h:173
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:417
uint32 TimeLineID
Definition: xlogdefs.h:59
void AcceptInvalidationMessages(void)
Definition: inval.c:687
#define WL_TIMEOUT
Definition: latch.h:128
void ProcessConfigFile(GucContext context)
static dlist_head lsn_mapping
Definition: worker.c:130
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:2074
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:419
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#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:121
bool in_remote_transaction
Definition: worker.c:164
bool in_streamed_transaction
Definition: worker.c:168
#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:154
#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:157
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
static void apply_dispatch(StringInfo s)
Definition: worker.c:1924
static void maybe_reread_subscription(void)
Definition: worker.c:2413
static MemoryContext ApplyMessageContext
Definition: worker.c:153
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:102
#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 2413 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, and Subscription::synccommit.

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

2414 {
2415  MemoryContext oldctx;
2417  bool started_tx = false;
2418 
2419  /* When cache state is valid there is nothing to do here. */
2420  if (MySubscriptionValid)
2421  return;
2422 
2423  /* This function might be called inside or outside of transaction. */
2424  if (!IsTransactionState())
2425  {
2427  started_tx = true;
2428  }
2429 
2430  /* Ensure allocations in permanent context. */
2432 
2433  newsub = GetSubscription(MyLogicalRepWorker->subid, true);
2434 
2435  /*
2436  * Exit if the subscription was removed. This normally should not happen
2437  * as the worker gets killed during DROP SUBSCRIPTION.
2438  */
2439  if (!newsub)
2440  {
2441  ereport(LOG,
2442  (errmsg("logical replication apply worker for subscription \"%s\" will "
2443  "stop because the subscription was removed",
2444  MySubscription->name)));
2445 
2446  proc_exit(0);
2447  }
2448 
2449  /*
2450  * Exit if the subscription was disabled. This normally should not happen
2451  * as the worker gets killed during ALTER SUBSCRIPTION ... DISABLE.
2452  */
2453  if (!newsub->enabled)
2454  {
2455  ereport(LOG,
2456  (errmsg("logical replication apply worker for subscription \"%s\" will "
2457  "stop because the subscription was disabled",
2458  MySubscription->name)));
2459 
2460  proc_exit(0);
2461  }
2462 
2463  /* !slotname should never happen when enabled is true. */
2464  Assert(newsub->slotname);
2465 
2466  /*
2467  * Exit if any parameter that affects the remote connection was changed.
2468  * The launcher will start a new worker.
2469  */
2470  if (strcmp(newsub->conninfo, MySubscription->conninfo) != 0 ||
2471  strcmp(newsub->name, MySubscription->name) != 0 ||
2472  strcmp(newsub->slotname, MySubscription->slotname) != 0 ||
2473  newsub->binary != MySubscription->binary ||
2474  newsub->stream != MySubscription->stream ||
2476  {
2477  ereport(LOG,
2478  (errmsg("logical replication apply worker for subscription \"%s\" will restart because of a parameter change",
2479  MySubscription->name)));
2480 
2481  proc_exit(0);
2482  }
2483 
2484  /* Check for other changes that should never happen too. */
2485  if (newsub->dbid != MySubscription->dbid)
2486  {
2487  elog(ERROR, "subscription %u changed unexpectedly",
2489  }
2490 
2491  /* Clean old subscription info and switch to new one. */
2494 
2495  MemoryContextSwitchTo(oldctx);
2496 
2497  /* Change synchronous commit according to the user's wishes */
2498  SetConfigOption("synchronous_commit", MySubscription->synccommit,
2500 
2501  if (started_tx)
2503 
2504  MySubscriptionValid = true;
2505 }
Subscription * MySubscription
Definition: worker.c:161
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3105
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:8102
List * publications
MemoryContext ApplyContext
Definition: worker.c:154
#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:162
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 2325 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().

2326 {
2327  static StringInfo reply_message = NULL;
2328  static TimestampTz send_time = 0;
2329 
2330  static XLogRecPtr last_recvpos = InvalidXLogRecPtr;
2331  static XLogRecPtr last_writepos = InvalidXLogRecPtr;
2332  static XLogRecPtr last_flushpos = InvalidXLogRecPtr;
2333 
2334  XLogRecPtr writepos;
2335  XLogRecPtr flushpos;
2336  TimestampTz now;
2337  bool have_pending_txes;
2338 
2339  /*
2340  * If the user doesn't want status to be reported to the publisher, be
2341  * sure to exit before doing anything at all.
2342  */
2343  if (!force && wal_receiver_status_interval <= 0)
2344  return;
2345 
2346  /* It's legal to not pass a recvpos */
2347  if (recvpos < last_recvpos)
2348  recvpos = last_recvpos;
2349 
2350  get_flush_position(&writepos, &flushpos, &have_pending_txes);
2351 
2352  /*
2353  * No outstanding transactions to flush, we can report the latest received
2354  * position. This is important for synchronous replication.
2355  */
2356  if (!have_pending_txes)
2357  flushpos = writepos = recvpos;
2358 
2359  if (writepos < last_writepos)
2360  writepos = last_writepos;
2361 
2362  if (flushpos < last_flushpos)
2363  flushpos = last_flushpos;
2364 
2365  now = GetCurrentTimestamp();
2366 
2367  /* if we've already reported everything we're good */
2368  if (!force &&
2369  writepos == last_writepos &&
2370  flushpos == last_flushpos &&
2371  !TimestampDifferenceExceeds(send_time, now,
2373  return;
2374  send_time = now;
2375 
2376  if (!reply_message)
2377  {
2379 
2380  reply_message = makeStringInfo();
2381  MemoryContextSwitchTo(oldctx);
2382  }
2383  else
2384  resetStringInfo(reply_message);
2385 
2386  pq_sendbyte(reply_message, 'r');
2387  pq_sendint64(reply_message, recvpos); /* write */
2388  pq_sendint64(reply_message, flushpos); /* flush */
2389  pq_sendint64(reply_message, writepos); /* apply */
2390  pq_sendint64(reply_message, now); /* sendTime */
2391  pq_sendbyte(reply_message, requestReply); /* replyRequested */
2392 
2393  elog(DEBUG2, "sending feedback (force %d) to recv %X/%X, write %X/%X, flush %X/%X",
2394  force,
2395  LSN_FORMAT_ARGS(recvpos),
2396  LSN_FORMAT_ARGS(writepos),
2397  LSN_FORMAT_ARGS(flushpos));
2398 
2399  walrcv_send(wrconn, reply_message->data, reply_message->len);
2400 
2401  if (recvpos > last_recvpos)
2402  last_recvpos = recvpos;
2403  if (writepos > last_writepos)
2404  last_writepos = writepos;
2405  if (flushpos > last_flushpos)
2406  last_flushpos = flushpos;
2407 }
WalReceiverConn * wrconn
Definition: worker.c:159
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
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:2011
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:154
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define walrcv_send(conn, buffer, nbytes)
Definition: walreceiver.h:421
#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 263 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().

264 {
265  if (am_tablesync_worker())
266  return MyLogicalRepWorker->relid == rel->localreloid;
267  else
268  return (rel->state == SUBREL_STATE_READY ||
269  (rel->state == SUBREL_STATE_SYNCDONE &&
270  rel->statelsn <= remote_final_lsn));
271 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:165
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 413 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().

415 {
416  TupleDesc desc = RelationGetDescr(rel->localrel);
417  int num_phys_attrs = desc->natts;
418  int i;
419  int attnum,
420  num_defaults = 0;
421  int *defmap;
422  ExprState **defexprs;
423  ExprContext *econtext;
424 
425  econtext = GetPerTupleExprContext(estate);
426 
427  /* We got all the data via replication, no need to evaluate anything. */
428  if (num_phys_attrs == rel->remoterel.natts)
429  return;
430 
431  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
432  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
433 
434  Assert(rel->attrmap->maplen == num_phys_attrs);
435  for (attnum = 0; attnum < num_phys_attrs; attnum++)
436  {
437  Expr *defexpr;
438 
439  if (TupleDescAttr(desc, attnum)->attisdropped || TupleDescAttr(desc, attnum)->attgenerated)
440  continue;
441 
442  if (rel->attrmap->attnums[attnum] >= 0)
443  continue;
444 
445  defexpr = (Expr *) build_column_default(rel->localrel, attnum + 1);
446 
447  if (defexpr != NULL)
448  {
449  /* Run the expression through planner */
450  defexpr = expression_planner(defexpr);
451 
452  /* Initialize executable expression in copycontext */
453  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
454  defmap[num_defaults] = attnum;
455  num_defaults++;
456  }
457 
458  }
459 
460  for (i = 0; i < num_defaults; i++)
461  slot->tts_values[defmap[i]] =
462  ExecEvalExpr(defexprs[i], econtext, &slot->tts_isnull[defmap[i]]);
463 }
#define RelationGetDescr(relation)
Definition: rel.h:498
#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:532
LogicalRepRelation remoterel
bool * tts_isnull
Definition: tuptable.h:128
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:315
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 619 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, SlotErrCallbackArg::local_attnum, 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().

622 {
623  int natts = slot->tts_tupleDescriptor->natts;
624  int i;
625  SlotErrCallbackArg errarg;
626  ErrorContextCallback errcallback;
627 
628  /* We'll fill "slot" with a virtual tuple, so we must start with ... */
629  ExecClearTuple(slot);
630 
631  /*
632  * Copy all the column data from srcslot, so that we'll have valid values
633  * for unreplaced columns.
634  */
635  Assert(natts == srcslot->tts_tupleDescriptor->natts);
636  slot_getallattrs(srcslot);
637  memcpy(slot->tts_values, srcslot->tts_values, natts * sizeof(Datum));
638  memcpy(slot->tts_isnull, srcslot->tts_isnull, natts * sizeof(bool));
639 
640  /* For error reporting, push callback + info on the error context stack */
641  errarg.rel = rel;
642  errarg.local_attnum = -1;
643  errarg.remote_attnum = -1;
644  errcallback.callback = slot_store_error_callback;
645  errcallback.arg = (void *) &errarg;
646  errcallback.previous = error_context_stack;
647  error_context_stack = &errcallback;
648 
649  /* Call the "in" function for each replaced attribute */
650  Assert(natts == rel->attrmap->maplen);
651  for (i = 0; i < natts; i++)
652  {
654  int remoteattnum = rel->attrmap->attnums[i];
655 
656  if (remoteattnum < 0)
657  continue;
658 
659  Assert(remoteattnum < tupleData->ncols);
660 
661  if (tupleData->colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
662  {
663  StringInfo colvalue = &tupleData->colvalues[remoteattnum];
664 
665  errarg.local_attnum = i;
666  errarg.remote_attnum = remoteattnum;
667 
668  if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
669  {
670  Oid typinput;
671  Oid typioparam;
672 
673  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
674  slot->tts_values[i] =
675  OidInputFunctionCall(typinput, colvalue->data,
676  typioparam, att->atttypmod);
677  slot->tts_isnull[i] = false;
678  }
679  else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
680  {
681  Oid typreceive;
682  Oid typioparam;
683 
684  /*
685  * In some code paths we may be asked to re-parse the same
686  * tuple data. Reset the StringInfo's cursor so that works.
687  */
688  colvalue->cursor = 0;
689 
690  getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
691  slot->tts_values[i] =
692  OidReceiveFunctionCall(typreceive, colvalue,
693  typioparam, att->atttypmod);
694 
695  /* Trouble if it didn't eat the whole buffer */
696  if (colvalue->cursor != colvalue->len)
697  ereport(ERROR,
698  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
699  errmsg("incorrect binary data format in logical replication column %d",
700  remoteattnum + 1)));
701  slot->tts_isnull[i] = false;
702  }
703  else
704  {
705  /* must be LOGICALREP_COLUMN_NULL */
706  slot->tts_values[i] = (Datum) 0;
707  slot->tts_isnull[i] = true;
708  }
709 
710  errarg.local_attnum = -1;
711  errarg.remote_attnum = -1;
712  }
713  }
714 
715  /* Pop the error context stack */
716  error_context_stack = errcallback.previous;
717 
718  /* And finally, declare that "slot" contains a valid virtual tuple */
719  ExecStoreVirtualTuple(slot);
720 }
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
LogicalRepRelMapEntry * rel
Definition: worker.c:134
#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:82
Datum * tts_values
Definition: tuptable.h:126
StringInfoData * colvalues
Definition: logicalproto.h:71
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:83
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define LOGICALREP_COLUMN_UNCHANGED
Definition: logicalproto.h:81
#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:203
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:469
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 504 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, SlotErrCallbackArg::local_attnum, 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().

506 {
507  int natts = slot->tts_tupleDescriptor->natts;
508  int i;
509  SlotErrCallbackArg errarg;
510  ErrorContextCallback errcallback;
511 
512  ExecClearTuple(slot);
513 
514  /* Push callback + info on the error context stack */
515  errarg.rel = rel;
516  errarg.local_attnum = -1;
517  errarg.remote_attnum = -1;
518  errcallback.callback = slot_store_error_callback;
519  errcallback.arg = (void *) &errarg;
520  errcallback.previous = error_context_stack;
521  error_context_stack = &errcallback;
522 
523  /* Call the "in" function for each non-dropped, non-null attribute */
524  Assert(natts == rel->attrmap->maplen);
525  for (i = 0; i < natts; i++)
526  {
528  int remoteattnum = rel->attrmap->attnums[i];
529 
530  if (!att->attisdropped && remoteattnum >= 0)
531  {
532  StringInfo colvalue = &tupleData->colvalues[remoteattnum];
533 
534  Assert(remoteattnum < tupleData->ncols);
535 
536  errarg.local_attnum = i;
537  errarg.remote_attnum = remoteattnum;
538 
539  if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
540  {
541  Oid typinput;
542  Oid typioparam;
543 
544  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
545  slot->tts_values[i] =
546  OidInputFunctionCall(typinput, colvalue->data,
547  typioparam, att->atttypmod);
548  slot->tts_isnull[i] = false;
549  }
550  else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
551  {
552  Oid typreceive;
553  Oid typioparam;
554 
555  /*
556  * In some code paths we may be asked to re-parse the same
557  * tuple data. Reset the StringInfo's cursor so that works.
558  */
559  colvalue->cursor = 0;
560 
561  getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
562  slot->tts_values[i] =
563  OidReceiveFunctionCall(typreceive, colvalue,
564  typioparam, att->atttypmod);
565 
566  /* Trouble if it didn't eat the whole buffer */
567  if (colvalue->cursor != colvalue->len)
568  ereport(ERROR,
569  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
570  errmsg("incorrect binary data format in logical replication column %d",
571  remoteattnum + 1)));
572  slot->tts_isnull[i] = false;
573  }
574  else
575  {
576  /*
577  * NULL value from remote. (We don't expect to see
578  * LOGICALREP_COLUMN_UNCHANGED here, but if we do, treat it as
579  * NULL.)
580  */
581  slot->tts_values[i] = (Datum) 0;
582  slot->tts_isnull[i] = true;
583  }
584 
585  errarg.local_attnum = -1;
586  errarg.remote_attnum = -1;
587  }
588  else
589  {
590  /*
591  * We assign NULL to dropped attributes and missing values
592  * (missing values should be later filled using
593  * slot_fill_defaults).
594  */
595  slot->tts_values[i] = (Datum) 0;
596  slot->tts_isnull[i] = true;
597  }
598  }
599 
600  /* Pop the error context stack */
601  error_context_stack = errcallback.previous;
602 
603  ExecStoreVirtualTuple(slot);
604 }
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
LogicalRepRelMapEntry * rel
Definition: worker.c:134
#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:82
Datum * tts_values
Definition: tuptable.h:126
StringInfoData * colvalues
Definition: logicalproto.h:71
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:83
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define ERROR
Definition: elog.h:46
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:203
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:469
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_error_callback()

static void slot_store_error_callback ( void *  arg)
static

Definition at line 469 of file worker.c.

References LogicalRepRelation::attnames, LogicalRepRelation::atttyps, errcontext, format_type_be(), get_atttype(), SlotErrCallbackArg::local_attnum, LogicalRepRelMapEntry::localreloid, logicalrep_typmap_gettypname(), LogicalRepRelation::nspname, SlotErrCallbackArg::rel, LogicalRepRelation::relname, SlotErrCallbackArg::remote_attnum, and LogicalRepRelMapEntry::remoterel.

Referenced by slot_modify_data(), and slot_store_data().

470 {
473  char *remotetypname;
474  Oid remotetypoid,
475  localtypoid;
476 
477  /* Nothing to do if remote attribute number is not set */
478  if (errarg->remote_attnum < 0)
479  return;
480 
481  rel = errarg->rel;
482  remotetypoid = rel->remoterel.atttyps[errarg->remote_attnum];
483 
484  /* Fetch remote type name from the LogicalRepTypMap cache */
485  remotetypname = logicalrep_typmap_gettypname(remotetypoid);
486 
487  /* Fetch local type OID from the local sys cache */
488  localtypoid = get_atttype(rel->localreloid, errarg->local_attnum + 1);
489 
490  errcontext("processing remote data for replication target relation \"%s.%s\" column \"%s\", "
491  "remote type %s, local type %s",
492  rel->remoterel.nspname, rel->remoterel.relname,
493  rel->remoterel.attnames[errarg->remote_attnum],
494  remotetypname,
495  format_type_be(localtypoid));
496 }
LogicalRepRelMapEntry * rel
Definition: worker.c:134
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
LogicalRepRelation remoterel
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:938
char * logicalrep_typmap_gettypname(Oid remoteid)
Definition: relation.c:501
#define errcontext
Definition: elog.h:204
void * arg

◆ store_flush_position()

static void store_flush_position ( XLogRecPtr  remote_lsn)
static

Definition at line 2055 of file worker.c.

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

Referenced by apply_handle_commit_internal().

2056 {
2057  FlushPosition *flushpos;
2058 
2059  /* Need to do this in permanent context */
2061 
2062  /* Track commit lsn */
2063  flushpos = (FlushPosition *) palloc(sizeof(FlushPosition));
2064  flushpos->local_end = XactLastCommitEnd;
2065  flushpos->remote_end = remote_lsn;
2066 
2067  dlist_push_tail(&lsn_mapping, &flushpos->node);
2069 }
static dlist_head lsn_mapping
Definition: worker.c:130
dlist_node node
Definition: worker.c:125
XLogRecPtr XactLastCommitEnd
Definition: xlog.c:366
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:317
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
XLogRecPtr remote_end
Definition: worker.c:127
MemoryContext ApplyContext
Definition: worker.c:154
XLogRecPtr local_end
Definition: worker.c:126
static MemoryContext ApplyMessageContext
Definition: worker.c:153
void * palloc(Size size)
Definition: mcxt.c:1062

◆ stream_cleanup_files()

static void stream_cleanup_files ( Oid  subid,
TransactionId  xid 
)
static

Definition at line 2772 of file worker.c.

References Assert, changes_filename(), HASH_FIND, HASH_REMOVE, hash_search(), MAXPGPATH, pfree(), SharedFileSetDeleteAll(), StreamXidHash::stream_fileset, subxact_filename(), and StreamXidHash::subxact_fileset.

Referenced by apply_handle_stream_abort(), and apply_handle_stream_commit().

2773 {
2774  char path[MAXPGPATH];
2775  StreamXidHash *ent;
2776  bool found = false;
2777 
2778  /* By this time we must have created the transaction entry */
2779  ent = (StreamXidHash *) hash_search(xidhash,
2780  (void *) &xid,
2781  HASH_FIND,
2782  &found);
2783  Assert(found);
2784 
2785  /* Delete the change file and release the stream fileset memory */
2786  changes_filename(path, subid, xid);
2788  pfree(ent->stream_fileset);
2789  ent->stream_fileset = NULL;
2790 
2791  /* Delete the subxact file and release the memory, if it exist */
2792  if (ent->subxact_fileset)
2793  {
2794  subxact_filename(path, subid, xid);
2796  pfree(ent->subxact_fileset);
2797  ent->subxact_fileset = NULL;
2798  }
2799 
2800  /* Remove the xid entry from the stream xid hash */
2801  hash_search(xidhash, (void *) &xid, HASH_REMOVE, NULL);
2802 }
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2759
static void subxact_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2752
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
void pfree(void *pointer)
Definition: mcxt.c:1169
#define MAXPGPATH
SharedFileSet * stream_fileset
Definition: worker.c:149
SharedFileSet * subxact_fileset
Definition: worker.c:150
static HTAB * xidhash
Definition: worker.c:176
void SharedFileSetDeleteAll(SharedFileSet *fileset)
#define Assert(condition)
Definition: c.h:804

◆ stream_close_file()

static void stream_close_file ( void  )
static

Definition at line 2893 of file worker.c.

References Assert, BufFileClose(), in_streamed_transaction, InvalidTransactionId, stream_xid, and TransactionIdIsValid.

Referenced by apply_handle_stream_stop().

2894 {
2897  Assert(stream_fd != NULL);
2898 
2900 
2902  stream_fd = NULL;
2903 }
void BufFileClose(BufFile *file)
Definition: buffile.c:395
bool in_streamed_transaction
Definition: worker.c:168
#define InvalidTransactionId
Definition: transam.h:31
#define Assert(condition)
Definition: c.h:804
static BufFile * stream_fd
Definition: worker.c:179
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static TransactionId stream_xid
Definition: worker.c:170

◆ stream_open_file()

static void stream_open_file ( Oid  subid,
TransactionId  xid,
bool  first 
)
static

Definition at line 2818 of file worker.c.

References Assert, BufFileCreateShared(), BufFileOpenShared(), BufFileSeek(), changes_filename(), DEBUG1, elog, HASH_ENTER, HASH_FIND, hash_search(), in_streamed_transaction, MAXPGPATH, MemoryContextSwitchTo(), OidIsValid, palloc(), SharedFileSetInit(), StreamXidHash::stream_fileset, StreamXidHash::subxact_fileset, TransactionIdIsValid, and StreamXidHash::xid.

Referenced by apply_handle_stream_start().

2819 {
2820  char path[MAXPGPATH];
2821  bool found;
2822  MemoryContext oldcxt;
2823  StreamXidHash *ent;
2824 
2826  Assert(OidIsValid(subid));
2828  Assert(stream_fd == NULL);
2829 
2830  /* create or find the xid entry in the xidhash */
2831  ent = (StreamXidHash *) hash_search(xidhash,
2832  (void *) &xid,
2834  &found);
2835  Assert(first_segment || found);
2836  changes_filename(path, subid, xid);
2837  elog(DEBUG1, "opening file \"%s\" for streamed changes", path);
2838 
2839  /*
2840  * Create/open the buffiles under the logical streaming context so that we
2841  * have those files until stream stop.
2842  */
2844 
2845  /*
2846  * If this is the first streamed segment, the file must not exist, so make
2847  * sure we're the ones creating it. Otherwise just open the file for
2848  * writing, in append mode.
2849  */
2850  if (first_segment)
2851  {
2852  MemoryContext savectx;
2853  SharedFileSet *fileset;
2854 
2855  /*
2856  * We need to maintain shared fileset across multiple stream
2857  * start/stop calls. So, need to allocate it in a persistent context.
2858  */
2860  fileset = palloc(sizeof(SharedFileSet));
2861 
2862  SharedFileSetInit(fileset, NULL);
2863  MemoryContextSwitchTo(savectx);
2864 
2865  stream_fd = BufFileCreateShared(fileset, path);
2866 
2867  /* Remember the fileset for the next stream of the same transaction */
2868  ent->xid = xid;
2869  ent->stream_fileset = fileset;
2870  ent->subxact_fileset = NULL;
2871  }
2872  else
2873  {
2874  /*
2875  * Open the file and seek to the end of the file because we always
2876  * append the changes file.
2877  */
2878  stream_fd = BufFileOpenShared(ent->stream_fileset, path, O_RDWR);
2879  BufFileSeek(stream_fd, 0, 0, SEEK_END);
2880  }
2881 
2882  MemoryContextSwitchTo(oldcxt);
2883 }
#define DEBUG1
Definition: elog.h:25
void SharedFileSetInit(SharedFileSet *fileset, dsm_segment *seg)
Definition: sharedfileset.c:64
int BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
Definition: buffile.c:650
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2759
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
#define OidIsValid(objectId)
Definition: c.h:710
#define MAXPGPATH
bool in_streamed_transaction
Definition: worker.c:168
BufFile * BufFileCreateShared(SharedFileSet *fileset, const char *name)
Definition: buffile.c:262
SharedFileSet * stream_fileset
Definition: worker.c:149
BufFile * BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)
Definition: buffile.c:284
MemoryContext ApplyContext
Definition: worker.c:154
SharedFileSet * subxact_fileset
Definition: worker.c:150
static MemoryContext LogicalStreamingContext
Definition: worker.c:157
static HTAB * xidhash
Definition: worker.c:176
#define Assert(condition)
Definition: c.h:804
TransactionId xid
Definition: worker.c:148
void * palloc(Size size)
Definition: mcxt.c:1062
static BufFile * stream_fd
Definition: worker.c:179
#define elog(elevel,...)
Definition: elog.h:232
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ stream_write_change()

static void stream_write_change ( char  action,
StringInfo  s 
)
static

Definition at line 2914 of file worker.c.

References Assert, BufFileWrite(), StringInfoData::cursor, StringInfoData::data, in_streamed_transaction, StringInfoData::len, stream_xid, and TransactionIdIsValid.

Referenced by handle_streamed_transaction().

2915 {
2916  int len;
2917 
2920  Assert(stream_fd != NULL);
2921 
2922  /* total on-disk size, including the action type character */
2923  len = (s->len - s->cursor) + sizeof(char);
2924 
2925  /* first write the size */
2926  BufFileWrite(stream_fd, &len, sizeof(len));
2927 
2928  /* then the action */
2929  BufFileWrite(stream_fd, &action, sizeof(action));
2930 
2931  /* and finally the remaining part of the buffer (after the XID) */
2932  len = (s->len - s->cursor);
2933 
2934  BufFileWrite(stream_fd, &s->data[s->cursor], len);
2935 }
bool in_streamed_transaction
Definition: worker.c:168
#define Assert(condition)
Definition: c.h:804
static BufFile * stream_fd
Definition: worker.c:179
void BufFileWrite(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:586
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static TransactionId stream_xid
Definition: worker.c:170

◆ subscription_change_cb()

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

Definition at line 2511 of file worker.c.

References MySubscriptionValid.

Referenced by ApplyWorkerMain().

2512 {
2513  MySubscriptionValid = false;
2514 }
bool MySubscriptionValid
Definition: worker.c:162

◆ subxact_filename()

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

Definition at line 2752 of file worker.c.

References MAXPGPATH, and snprintf.

Referenced by stream_cleanup_files(), subxact_info_read(), and subxact_info_write().

2753 {
2754  snprintf(path, MAXPGPATH, "%u-%u.subxacts", subid, xid);
2755 }
#define MAXPGPATH
#define snprintf
Definition: port.h:216

◆ subxact_info_add()

static void subxact_info_add ( TransactionId  xid)
static

Definition at line 2674 of file worker.c.

References Assert, BufFileTell(), SubXactInfo::fileno, i, MemoryContextSwitchTo(), ApplySubXactData::nsubxacts, ApplySubXactData::nsubxacts_max, SubXactInfo::offset, palloc(), repalloc(), stream_xid, ApplySubXactData::subxact_last, ApplySubXactData::subxacts, TransactionIdIsValid, and SubXactInfo::xid.

Referenced by handle_streamed_transaction().

2675 {
2676  SubXactInfo *subxacts = subxact_data.subxacts;
2677  int64 i;
2678 
2679  /* We must have a valid top level stream xid and a stream fd. */
2681  Assert(stream_fd != NULL);
2682 
2683  /*
2684  * If the XID matches the toplevel transaction, we don't want to add it.
2685  */
2686  if (stream_xid == xid)
2687  return;
2688 
2689  /*
2690  * In most cases we're checking the same subxact as we've already seen in
2691  * the last call, so make sure to ignore it (this change comes later).
2692  */
2693  if (subxact_data.subxact_last == xid)
2694  return;
2695 
2696  /* OK, remember we're processing this XID. */
2697  subxact_data.subxact_last = xid;
2698 
2699  /*
2700  * Check if the transaction is already present in the array of subxact. We
2701  * intentionally scan the array from the tail, because we're likely adding
2702  * a change for the most recent subtransactions.
2703  *
2704  * XXX Can we rely on the subxact XIDs arriving in sorted order? That
2705  * would allow us to use binary search here.
2706  */
2707  for (i = subxact_data.nsubxacts; i > 0; i--)
2708  {
2709  /* found, so we're done */
2710  if (subxacts[i - 1].xid == xid)
2711  return;
2712  }
2713 
2714  /* This is a new subxact, so we need to add it to the array. */
2715  if (subxact_data.nsubxacts == 0)
2716  {
2717  MemoryContext oldctx;
2718 
2720 
2721  /*
2722  * Allocate this memory for subxacts in per-stream context, see
2723  * subxact_info_read.
2724  */
2726  subxacts = palloc(subxact_data.nsubxacts_max * sizeof(SubXactInfo));
2727  MemoryContextSwitchTo(oldctx);
2728  }
2730  {
2732  subxacts = repalloc(subxacts,
2734  }
2735 
2736  subxacts[subxact_data.nsubxacts].xid = xid;
2737 
2738  /*
2739  * Get the current offset of the stream file and store it as offset of
2740  * this subxact.
2741  */
2743  &subxacts[subxact_data.nsubxacts].fileno,
2744  &subxacts[subxact_data.nsubxacts].offset);
2745 
2747  subxact_data.subxacts = subxacts;
2748 }
int fileno
Definition: worker.c:184
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
TransactionId subxact_last
Definition: worker.c:193
uint32 nsubxacts
Definition: worker.c:191
SubXactInfo * subxacts
Definition: worker.c:194
TransactionId xid
Definition: worker.c:183
static MemoryContext LogicalStreamingContext
Definition: worker.c:157
void BufFileTell(BufFile *file, int *fileno, off_t *offset)
Definition: buffile.c:743
#define Assert(condition)
Definition: c.h:804
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
off_t offset
Definition: worker.c:185
void * palloc(Size size)
Definition: mcxt.c:1062
static ApplySubXactData subxact_data
Definition: worker.c:197
static BufFile * stream_fd
Definition: worker.c:179
uint32 nsubxacts_max
Definition: worker.c:192
int i
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static TransactionId stream_xid
Definition: worker.c:170

◆ subxact_info_read()

static void subxact_info_read ( Oid  subid,
TransactionId  xid 
)
static

Definition at line 2604 of file worker.c.

References Assert, BufFileClose(), BufFileOpenShared(), BufFileRead(), ereport, errcode_for_file_access(), errmsg(), ERROR, fd(), HASH_FIND, hash_search(), MAXPGPATH, MemoryContextSwitchTo(), my_log2(), ApplySubXactData::nsubxacts, ApplySubXactData::nsubxacts_max, palloc(), subxact_filename(), StreamXidHash::subxact_fileset, ApplySubXactData::subxacts, and TransactionIdIsValid.

Referenced by apply_handle_stream_abort(), and apply_handle_stream_start().

2605 {
2606  char path[MAXPGPATH];
2607  bool found;
2608  Size len;
2609  BufFile *fd;
2610  StreamXidHash *ent;
2611  MemoryContext oldctx;
2612 
2617 
2618  /* Find the stream xid entry in the xidhash */
2619  ent = (StreamXidHash *) hash_search(xidhash,
2620  (void *) &xid,
2621  HASH_FIND,
2622  &found);
2623 
2624  /*
2625  * If subxact_fileset is not valid that mean we don't have any subxact
2626  * info
2627  */
2628  if (ent->subxact_fileset == NULL)
2629  return;
2630 
2631  subxact_filename(path, subid, xid);
2632 
2633  fd = BufFileOpenShared(ent->subxact_fileset, path, O_RDONLY);
2634 
2635  /* read number of subxact items */
2637  sizeof(subxact_data.nsubxacts)) !=
2638  sizeof(subxact_data.nsubxacts))
2639  ereport(ERROR,
2641  errmsg("could not read from streaming transaction's subxact file \"%s\": %m",
2642  path)));
2643 
2644  len = sizeof(SubXactInfo) * subxact_data.nsubxacts;
2645 
2646  /* we keep the maximum as a power of 2 */
2648 
2649  /*
2650  * Allocate subxact information in the logical streaming context. We need
2651  * this information during the complete stream so that we can add the sub
2652  * transaction info to this. On stream stop we will flush this information
2653  * to the subxact file and reset the logical streaming context.
2654  */
2657  sizeof(SubXactInfo));
2658  MemoryContextSwitchTo(oldctx);
2659 
2660  if ((len > 0) && ((BufFileRead(fd, subxact_data.subxacts, len)) != len))
2661  ereport(ERROR,
2663  errmsg("could not read from streaming transaction's subxact file \"%s\": %m",
2664  path)));
2665 
2666  BufFileClose(fd);
2667 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void subxact_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2752
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:191
void BufFileClose(BufFile *file)
Definition: buffile.c:395
SubXactInfo * subxacts
Definition: worker.c:194
#define ERROR
Definition: elog.h:46
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:721
BufFile * BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)
Definition: buffile.c:284
int my_log2(long num)
Definition: dynahash.c:1765
SharedFileSet * subxact_fileset
Definition: worker.c:150
#define ereport(elevel,...)
Definition: elog.h:157
static MemoryContext LogicalStreamingContext
Definition: worker.c:157
struct SubXactInfo SubXactInfo
static HTAB * xidhash
Definition: worker.c:176
#define Assert(condition)
Definition: c.h:804
size_t Size
Definition: c.h:540
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
static ApplySubXactData subxact_data
Definition: worker.c:197
uint32 nsubxacts_max
Definition: worker.c:192
size_t BufFileRead(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:543
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ subxact_info_write()

static void subxact_info_write ( Oid  subid,
TransactionId  xid 
)
static

Definition at line 2526 of file worker.c.

References Assert, BufFileClose(), BufFileCreateShared(), BufFileOpenShared(), BufFileWrite(), cleanup_subxact_info(), fd(), HASH_FIND, hash_search(), MAXPGPATH, MemoryContextSwitchTo(), ApplySubXactData::nsubxacts, palloc(), pfree(), SharedFileSetDeleteAll(), SharedFileSetInit(), subxact_filename(), StreamXidHash::subxact_fileset, ApplySubXactData::subxacts, and TransactionIdIsValid.

Referenced by apply_handle_stream_abort(), and apply_handle_stream_stop().

2527 {
2528  char path[MAXPGPATH];
2529  bool found;
2530  Size len;
2531  StreamXidHash *ent;
2532  BufFile *fd;
2533 
2535 
2536  /* find the xid entry in the xidhash */
2537  ent = (StreamXidHash *) hash_search(xidhash,
2538  (void *) &xid,
2539  HASH_FIND,
2540  &found);
2541  /* we must found the entry for its top transaction by this time */
2542  Assert(found);
2543 
2544  /*
2545  * If there is no subtransaction then nothing to do, but if already have
2546  * subxact file then delete that.
2547  */
2548  if (subxact_data.nsubxacts == 0)
2549  {
2550  if (ent->subxact_fileset)
2551  {
2554  pfree(ent->subxact_fileset);
2555  ent->subxact_fileset = NULL;
2556  }
2557  return;
2558  }
2559 
2560  subxact_filename(path, subid, xid);
2561 
2562  /*
2563  * Create the subxact file if it not already created, otherwise open the
2564  * existing file.
2565  */
2566  if (ent->subxact_fileset == NULL)
2567  {
2568  MemoryContext oldctx;
2569 
2570  /*
2571  * We need to maintain shared fileset across multiple stream
2572  * start/stop calls. So, need to allocate it in a persistent context.
2573  */
2575  ent->subxact_fileset = palloc(sizeof(SharedFileSet));
2576  SharedFileSetInit(ent->subxact_fileset, NULL);
2577  MemoryContextSwitchTo(oldctx);
2578 
2579  fd = BufFileCreateShared(ent->subxact_fileset, path);
2580  }
2581  else
2582  fd = BufFileOpenShared(ent->subxact_fileset, path, O_RDWR);
2583 
2584  len = sizeof(SubXactInfo) * subxact_data.nsubxacts;
2585 
2586  /* Write the subxact count and subxact info */
2589 
2590  BufFileClose(fd);
2591 
2592  /* free the memory allocated for subxact info */
2594 }
void SharedFileSetInit(SharedFileSet *fileset, dsm_segment *seg)
Definition: sharedfileset.c:64
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void subxact_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2752
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:191
void BufFileClose(BufFile *file)
Definition: buffile.c:395
void pfree(void *pointer)
Definition: mcxt.c:1169
SubXactInfo * subxacts
Definition: worker.c:194
#define MAXPGPATH
BufFile * BufFileCreateShared(SharedFileSet *fileset, const char *name)
Definition: buffile.c:262
BufFile * BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)
Definition: buffile.c:284
MemoryContext ApplyContex