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)
 
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 1907 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_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().

1908 {
1910 
1911  switch (action)
1912  {
1913  case LOGICAL_REP_MSG_BEGIN:
1914  apply_handle_begin(s);
1915  return;
1916 
1919  return;
1920 
1923  return;
1924 
1927  return;
1928 
1931  return;
1932 
1935  return;
1936 
1939  return;
1940 
1941  case LOGICAL_REP_MSG_TYPE:
1942  apply_handle_type(s);
1943  return;
1944 
1947  return;
1948 
1951  return;
1952 
1955  return;
1956 
1959  return;
1960 
1963  return;
1964  }
1965 
1966  ereport(ERROR,
1967  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1968  errmsg("invalid logical replication message type \"%c\"", action)));
1969 }
static void apply_handle_type(StringInfo s)
Definition: worker.c:1117
static void apply_handle_insert(StringInfo s)
Definition: worker.c:1151
static void apply_handle_stream_abort(StringInfo s)
Definition: worker.c:829
static void apply_handle_stream_start(StringInfo s)
Definition: worker.c:746
int errcode(int sqlerrcode)
Definition: elog.c:691
#define ERROR
Definition: elog.h:43
static void apply_handle_stream_stop(StringInfo s)
Definition: worker.c:796
static void apply_handle_delete(StringInfo s)
Definition: worker.c:1429
static void apply_handle_begin(StringInfo s)
Definition: worker.c:687
static void apply_handle_commit(StringInfo s)
Definition: worker.c:706
static void apply_handle_stream_commit(StringInfo s)
Definition: worker.c:930
static void apply_handle_update(StringInfo s)
Definition: worker.c:1269
static void apply_handle_relation(StringInfo s)
Definition: worker.c:1099
#define ereport(elevel,...)
Definition: elog.h:155
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
static void apply_handle_origin(StringInfo s)
Definition: worker.c:728
LogicalRepMsgType
Definition: logicalproto.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:902
static void apply_handle_truncate(StringInfo s)
Definition: worker.c:1796

◆ apply_handle_begin()

static void apply_handle_begin ( StringInfo  s)
static

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

688 {
689  LogicalRepBeginData begin_data;
690 
691  logicalrep_read_begin(s, &begin_data);
692 
693  remote_final_lsn = begin_data.final_lsn;
694 
695  in_remote_transaction = true;
696 
698 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:165
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3296
void logicalrep_read_begin(StringInfo in, LogicalRepBeginData *begin_data)
Definition: proto.c:59
bool in_remote_transaction
Definition: worker.c:164
XLogRecPtr final_lsn
Definition: logicalproto.h:112

◆ apply_handle_commit()

static void apply_handle_commit ( StringInfo  s)
static

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

707 {
708  LogicalRepCommitData commit_data;
709 
710  logicalrep_read_commit(s, &commit_data);
711 
712  Assert(commit_data.commit_lsn == remote_final_lsn);
713 
714  apply_handle_commit_internal(s, &commit_data);
715 
716  /* Process any tables that are being synchronized in parallel. */
717  process_syncing_tables(commit_data.end_lsn);
718 
720 }
static XLogRecPtr remote_final_lsn
Definition: worker.c:165
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:530
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3296
static void apply_handle_commit_internal(StringInfo s, LogicalRepCommitData *commit_data)
Definition: worker.c:1063
#define Assert(condition)
Definition: c.h:800
void logicalrep_read_commit(StringInfo in, LogicalRepCommitData *commit_data)
Definition: proto.c:94

◆ apply_handle_commit_internal()

static void apply_handle_commit_internal ( StringInfo  s,
LogicalRepCommitData commit_data 
)
static

Definition at line 1063 of file worker.c.

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

1064 {
1065  /* The synchronization worker runs in single transaction. */
1067  {
1068  /*
1069  * Update origin state so we can restart streaming from correct
1070  * position in case of crash.
1071  */
1072  replorigin_session_origin_lsn = commit_data->end_lsn;
1074 
1076  pgstat_report_stat(false);
1077 
1078  store_flush_position(commit_data->end_lsn);
1079  }
1080  else
1081  {
1082  /* Process any invalidation messages that might have accumulated. */
1085  }
1086 
1087  in_remote_transaction = false;
1088 }
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:2029
void AcceptInvalidationMessages(void)
Definition: inval.c:684
void CommitTransactionCommand(void)
Definition: xact.c:2948
bool in_remote_transaction
Definition: worker.c:164
static bool am_tablesync_worker(void)
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:2388
bool IsTransactionState(void)
Definition: xact.c:371
TimestampTz committime
Definition: logicalproto.h:121
void pgstat_report_stat(bool force)
Definition: pgstat.c:861

◆ apply_handle_delete()

static void apply_handle_delete ( StringInfo  s)
static

Definition at line 1429 of file worker.c.

References AfterTriggerEndQuery(), apply_handle_delete_internal(), apply_handle_tuple_routing(), check_relation_updatable(), CMD_DELETE, CommandCounterIncrement(), create_estate_for_relation(), ensure_transaction(), EState::es_tupleTable, ExecInitExtraTupleSlot(), ExecResetTupleTable(), FreeExecutorState(), GetPerTupleMemoryContext, GetTransactionSnapshot(), handle_streamed_transaction(), InitResultRelInfo(), LogicalRepRelMapEntry::localrel, LOGICAL_REP_MSG_DELETE, logicalrep_read_delete(), logicalrep_rel_close(), logicalrep_rel_open(), makeNode, 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().

1430 {
1431  ResultRelInfo *resultRelInfo;
1432  LogicalRepRelMapEntry *rel;
1433  LogicalRepTupleData oldtup;
1434  LogicalRepRelId relid;
1435  EState *estate;
1436  TupleTableSlot *remoteslot;
1437  MemoryContext oldctx;
1438 
1440  return;
1441 
1443 
1444  relid = logicalrep_read_delete(s, &oldtup);
1445  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1446  if (!should_apply_changes_for_rel(rel))
1447  {
1448  /*
1449  * The relation can't become interesting in the middle of the
1450  * transaction so it's safe to unlock it.
1451  */
1453  return;
1454  }
1455 
1456  /* Check if we can do the delete. */
1458 
1459  /* Initialize the executor state. */
1460  estate = create_estate_for_relation(rel);
1461  remoteslot = ExecInitExtraTupleSlot(estate,
1462  RelationGetDescr(rel->localrel),
1463  &TTSOpsVirtual);
1464  resultRelInfo = makeNode(ResultRelInfo);
1465  InitResultRelInfo(resultRelInfo, rel->localrel, 1, NULL, 0);
1466 
1468 
1469  /* Build the search tuple. */
1471  slot_store_data(remoteslot, rel, &oldtup);
1472  MemoryContextSwitchTo(oldctx);
1473 
1474  /* For a partitioned table, apply delete to correct partition. */
1475  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1476  apply_handle_tuple_routing(resultRelInfo, estate,
1477  remoteslot, NULL, rel, CMD_DELETE);
1478  else
1479  apply_handle_delete_internal(resultRelInfo, estate,
1480  remoteslot, &rel->remoterel);
1481 
1483 
1484  /* Handle queued AFTER triggers. */
1485  AfterTriggerEndQuery(estate);
1486 
1487  ExecResetTupleTable(estate->es_tupleTable, false);
1488  FreeExecutorState(estate);
1489 
1491 
1493 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:263
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:344
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1196
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1801
LogicalRepRelId logicalrep_read_delete(StringInfo in, LogicalRepTupleData *oldtup)
Definition: proto.c:289
static void apply_handle_delete_internal(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepRelation *remoterel)
Definition: worker.c:1497
#define RelationGetDescr(relation)
Definition: rel.h:483
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:449
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Form_pg_class rd_rel
Definition: rel.h:110
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
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:274
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:1235
static void apply_handle_tuple_routing(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry, CmdType operation)
Definition: worker.c:1571
List * es_tupleTable
Definition: execnodes.h:561
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1161
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define makeNode(_type_)
Definition: nodes.h:575
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4522
static void slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:465
uint32 LogicalRepRelId
Definition: logicalproto.h:84

◆ apply_handle_delete_internal()

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

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

1500 {
1501  Relation localrel = relinfo->ri_RelationDesc;
1502  EPQState epqstate;
1503  TupleTableSlot *localslot;
1504  bool found;
1505 
1506  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
1507  ExecOpenIndices(relinfo, false);
1508 
1509  found = FindReplTupleInLocalRel(estate, localrel, remoterel,
1510  remoteslot, &localslot);
1511 
1512  /* If found delete it. */
1513  if (found)
1514  {
1515  EvalPlanQualSetSlot(&epqstate, localslot);
1516 
1517  /* Do the actual delete. */
1518  ExecSimpleRelationDelete(relinfo, estate, &epqstate, localslot);
1519  }
1520  else
1521  {
1522  /* The tuple to be deleted could not be found. */
1523  elog(DEBUG1,
1524  "logical replication could not find row for delete "
1525  "in replication target relation \"%s\"",
1526  RelationGetRelationName(localrel));
1527  }
1528 
1529  /* Cleanup. */
1530  ExecCloseIndices(relinfo);
1531  EvalPlanQualEnd(&epqstate);
1532 }
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:412
#define DEBUG1
Definition: elog.h:25
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:151
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2810
#define RelationGetRelationName(relation)
Definition: rel.h:491
void EvalPlanQualInit(EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2390
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:1542
#define elog(elevel,...)
Definition: elog.h:228
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:226
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:217

◆ apply_handle_insert()

static void apply_handle_insert ( StringInfo  s)
static

Definition at line 1151 of file worker.c.

References AfterTriggerEndQuery(), apply_handle_insert_internal(), apply_handle_tuple_routing(), CMD_INSERT, CommandCounterIncrement(), create_estate_for_relation(), ensure_transaction(), EState::es_tupleTable, ExecInitExtraTupleSlot(), ExecResetTupleTable(), FreeExecutorState(), GetPerTupleMemoryContext, GetTransactionSnapshot(), handle_streamed_transaction(), InitResultRelInfo(), LogicalRepRelMapEntry::localrel, LOGICAL_REP_MSG_INSERT, logicalrep_read_insert(), logicalrep_rel_close(), logicalrep_rel_open(), makeNode, 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().

1152 {
1153  ResultRelInfo *resultRelInfo;
1154  LogicalRepRelMapEntry *rel;
1155  LogicalRepTupleData newtup;
1156  LogicalRepRelId relid;
1157  EState *estate;
1158  TupleTableSlot *remoteslot;
1159  MemoryContext oldctx;
1160 
1162  return;
1163 
1165 
1166  relid = logicalrep_read_insert(s, &newtup);
1167  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1168  if (!should_apply_changes_for_rel(rel))
1169  {
1170  /*
1171  * The relation can't become interesting in the middle of the
1172  * transaction so it's safe to unlock it.
1173  */
1175  return;
1176  }
1177 
1178  /* Initialize the executor state. */
1179  estate = create_estate_for_relation(rel);
1180  remoteslot = ExecInitExtraTupleSlot(estate,
1181  RelationGetDescr(rel->localrel),
1182  &TTSOpsVirtual);
1183  resultRelInfo = makeNode(ResultRelInfo);
1184  InitResultRelInfo(resultRelInfo, rel->localrel, 1, NULL, 0);
1185 
1186  /* Input functions may need an active snapshot, so get one */
1188 
1189  /* Process and store remote tuple in the slot */
1191  slot_store_data(remoteslot, rel, &newtup);
1192  slot_fill_defaults(rel, estate, remoteslot);
1193  MemoryContextSwitchTo(oldctx);
1194 
1195  /* For a partitioned table, insert the tuple into a partition. */
1196  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1197  apply_handle_tuple_routing(resultRelInfo, estate,
1198  remoteslot, NULL, rel, CMD_INSERT);
1199  else
1200  apply_handle_insert_internal(resultRelInfo, estate,
1201  remoteslot);
1202 
1204 
1205  /* Handle queued AFTER triggers. */
1206  AfterTriggerEndQuery(estate);
1207 
1208  ExecResetTupleTable(estate->es_tupleTable, false);
1209  FreeExecutorState(estate);
1210 
1212 
1214 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:263
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:344
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1196
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1801
#define RelationGetDescr(relation)
Definition: rel.h:483
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:449
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:163
static void slot_fill_defaults(LogicalRepRelMapEntry *rel, EState *estate, TupleTableSlot *slot)
Definition: worker.c:374
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
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:274
static void apply_handle_tuple_routing(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry, CmdType operation)
Definition: worker.c:1571
List * es_tupleTable
Definition: execnodes.h:561
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1161
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define makeNode(_type_)
Definition: nodes.h:575
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4522
static void slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:465
uint32 LogicalRepRelId
Definition: logicalproto.h:84
static void apply_handle_insert_internal(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot)
Definition: worker.c:1218

◆ apply_handle_insert_internal()

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

Definition at line 1218 of file worker.c.

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

Referenced by apply_handle_insert(), and apply_handle_tuple_routing().

1220 {
1221  ExecOpenIndices(relinfo, false);
1222 
1223  /* Do the insert. */
1224  ExecSimpleRelationInsert(relinfo, estate, remoteslot);
1225 
1226  /* Cleanup. */
1227  ExecCloseIndices(relinfo);
1228 }
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:151
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:226
void ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo, EState *estate, TupleTableSlot *slot)

◆ apply_handle_origin()

static void apply_handle_origin ( StringInfo  s)
static

Definition at line 728 of file worker.c.

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

Referenced by apply_dispatch().

729 {
730  /*
731  * ORIGIN message can only come inside streaming transaction or inside
732  * remote transaction and before any actual writes.
733  */
737  ereport(ERROR,
738  (errcode(ERRCODE_PROTOCOL_VIOLATION),
739  errmsg("ORIGIN message sent out of order")));
740 }
int errcode(int sqlerrcode)
Definition: elog.c:691
#define ERROR
Definition: elog.h:43
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:155
bool IsTransactionState(void)
Definition: xact.c:371
int errmsg(const char *fmt,...)
Definition: elog.c:902

◆ apply_handle_relation()

static void apply_handle_relation ( StringInfo  s)
static

Definition at line 1099 of file worker.c.

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

Referenced by apply_dispatch().

1100 {
1101  LogicalRepRelation *rel;
1102 
1104  return;
1105 
1106  rel = logicalrep_read_rel(s);
1108 }
LogicalRepRelation * logicalrep_read_rel(StringInfo in)
Definition: proto.c:397
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:173
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 829 of file worker.c.

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

830 {
831  TransactionId xid;
832  TransactionId subxid;
833 
835 
836  logicalrep_read_stream_abort(s, &xid, &subxid);
837 
838  /*
839  * If the two XIDs are the same, it's in fact abort of toplevel xact, so
840  * just delete the files with serialized info.
841  */
842  if (xid == subxid)
844  else
845  {
846  /*
847  * OK, so it's a subxact. We need to read the subxact file for the
848  * toplevel transaction, determine the offset tracked for the subxact,
849  * and truncate the file with changes. We also remove the subxacts
850  * with higher offsets (or rather higher XIDs).
851  *
852  * We intentionally scan the array from the tail, because we're likely
853  * aborting a change for the most recent subtransactions.
854  *
855  * We can't use the binary search here as subxact XIDs won't
856  * necessarily arrive in sorted order, consider the case where we have
857  * released the savepoint for multiple subtransactions and then
858  * performed rollback to savepoint for one of the earlier
859  * sub-transaction.
860  */
861 
862  int64 i;
863  int64 subidx;
864  BufFile *fd;
865  bool found = false;
866  char path[MAXPGPATH];
867  StreamXidHash *ent;
868 
869  subidx = -1;
872 
873  for (i = subxact_data.nsubxacts; i > 0; i--)
874  {
875  if (subxact_data.subxacts[i - 1].xid == subxid)
876  {
877  subidx = (i - 1);
878  found = true;
879  break;
880  }
881  }
882 
883  /*
884  * If it's an empty sub-transaction then we will not find the subxid
885  * here so just cleanup the subxact info and return.
886  */
887  if (!found)
888  {
889  /* Cleanup the subxact info */
891 
892  /* The synchronization worker runs in single transaction */
893  if (!am_tablesync_worker())
895  return;
896  }
897 
898  Assert((subidx >= 0) && (subidx < subxact_data.nsubxacts));
899 
901  (void *) &xid,
902  HASH_FIND,
903  &found);
904  Assert(found);
905 
906  /* open the changes file */
908  fd = BufFileOpenShared(ent->stream_fileset, path, O_RDWR);
909 
910  /* OK, truncate the file at the right offset */
912  subxact_data.subxacts[subidx].offset);
913  BufFileClose(fd);
914 
915  /* discard the subxacts added later */
916  subxact_data.nsubxacts = subidx;
917 
918  /* write the updated subxact list */
920 
921  if (!am_tablesync_worker())
923  }
924 }
static void subxact_info_read(Oid subid, TransactionId xid)
Definition: worker.c:2579
int fileno
Definition: worker.c:184
uint32 TransactionId
Definition: c.h:575
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2734
void CommitTransactionCommand(void)
Definition: xact.c:2948
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:919
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:2747
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
static bool am_tablesync_worker(void)
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:800
off_t offset
Definition: worker.c:185
static void subxact_info_write(Oid subid, TransactionId xid)
Definition: worker.c:2501
static ApplySubXactData subxact_data
Definition: worker.c:197
int i
static void cleanup_subxact_info(void)
Definition: worker.c:2913
void logicalrep_read_stream_abort(StringInfo in, TransactionId *xid, TransactionId *subxid)
Definition: proto.c:865

◆ apply_handle_stream_commit()

static void apply_handle_stream_commit ( StringInfo  s)
static

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

931 {
932  TransactionId xid;
934  int nchanges;
935  char path[MAXPGPATH];
936  char *buffer = NULL;
937  bool found;
938  LogicalRepCommitData commit_data;
939  StreamXidHash *ent;
940  MemoryContext oldcxt;
941  BufFile *fd;
942 
944 
945  xid = logicalrep_read_stream_commit(s, &commit_data);
946 
947  elog(DEBUG1, "received commit for streamed transaction %u", xid);
948 
950 
951  /*
952  * Allocate file handle and memory required to process all the messages in
953  * TopTransactionContext to avoid them getting reset after each message is
954  * processed.
955  */
957 
958  /* open the spool file for the committed transaction */
960  elog(DEBUG1, "replaying changes from file \"%s\"", path);
962  (void *) &xid,
963  HASH_FIND,
964  &found);
965  Assert(found);
966  fd = BufFileOpenShared(ent->stream_fileset, path, O_RDONLY);
967 
968  buffer = palloc(BLCKSZ);
969  initStringInfo(&s2);
970 
971  MemoryContextSwitchTo(oldcxt);
972 
973  remote_final_lsn = commit_data.commit_lsn;
974 
975  /*
976  * Make sure the handle apply_dispatch methods are aware we're in a remote
977  * transaction.
978  */
979  in_remote_transaction = true;
981 
982  /*
983  * Read the entries one by one and pass them through the same logic as in
984  * apply_dispatch.
985  */
986  nchanges = 0;
987  while (true)
988  {
989  int nbytes;
990  int len;
991 
993 
994  /* read length of the on-disk record */
995  nbytes = BufFileRead(fd, &len, sizeof(len));
996 
997  /* have we reached end of the file? */
998  if (nbytes == 0)
999  break;
1000 
1001  /* do we have a correct length? */
1002  if (nbytes != sizeof(len))
1003  ereport(ERROR,
1005  errmsg("could not read from streaming transaction's changes file \"%s\": %m",
1006  path)));
1007 
1008  Assert(len > 0);
1009 
1010  /* make sure we have sufficiently large buffer */
1011  buffer = repalloc(buffer, len);
1012 
1013  /* and finally read the data into the buffer */
1014  if (BufFileRead(fd, buffer, len) != len)
1015  ereport(ERROR,
1017  errmsg("could not read from streaming transaction's changes file \"%s\": %m",
1018  path)));
1019 
1020  /* copy the buffer to the stringinfo and call apply_dispatch */
1021  resetStringInfo(&s2);
1022  appendBinaryStringInfo(&s2, buffer, len);
1023 
1024  /* Ensure we are reading the data into our memory context. */
1026 
1027  apply_dispatch(&s2);
1028 
1030 
1031  MemoryContextSwitchTo(oldcxt);
1032 
1033  nchanges++;
1034 
1035  if (nchanges % 1000 == 0)
1036  elog(DEBUG1, "replayed %d changes from file '%s'",
1037  nchanges, path);
1038  }
1039 
1040  BufFileClose(fd);
1041 
1042  pfree(buffer);
1043  pfree(s2.data);
1044 
1045  elog(DEBUG1, "replayed %d (all) changes from file \"%s\"",
1046  nchanges, path);
1047 
1048  apply_handle_commit_internal(s, &commit_data);
1049 
1050  /* unlink the files with serialized changes and subxact info */
1052 
1053  /* Process any tables that are being synchronized in parallel. */
1054  process_syncing_tables(commit_data.end_lsn);
1055 
1057 }
#define DEBUG1
Definition: elog.h:25
MemoryContext TopTransactionContext
Definition: mcxt.c:49
static XLogRecPtr remote_final_lsn
Definition: worker.c:165
uint32 TransactionId
Definition: c.h:575
TransactionId logicalrep_read_stream_commit(StringInfo in, LogicalRepCommitData *commit_data)
Definition: proto.c:823
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:530
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2734
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3296
static void apply_handle_commit_internal(StringInfo s, LogicalRepCommitData *commit_data)
Definition: worker.c:1063
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
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:1057
static void stream_cleanup_files(Oid subid, TransactionId xid)
Definition: worker.c:2747
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:43
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:714
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:155
static HTAB * xidhash
Definition: worker.c:176
static void apply_dispatch(StringInfo s)
Definition: worker.c:1907
static MemoryContext ApplyMessageContext
Definition: worker.c:153
#define Assert(condition)
Definition: c.h:800
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1070
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
size_t BufFileRead(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:543
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
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 746 of file worker.c.

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

747 {
748  bool first_segment;
749  HASHCTL hash_ctl;
750 
752 
753  /*
754  * Start a transaction on stream start, this transaction will be committed
755  * on the stream stop unless it is a tablesync worker in which case it will
756  * be committed after processing all the messages. We need the transaction
757  * for handling the buffile, used for serializing the streaming data and
758  * subxact info.
759  */
761 
762  /* notify handle methods we're processing a remote transaction */
764 
765  /* extract XID of the top-level transaction */
766  stream_xid = logicalrep_read_stream_start(s, &first_segment);
767 
768  /*
769  * Initialize the xidhash table if we haven't yet. This will be used for
770  * the entire duration of the apply worker so create it in permanent
771  * context.
772  */
773  if (xidhash == NULL)
774  {
775  hash_ctl.keysize = sizeof(TransactionId);
776  hash_ctl.entrysize = sizeof(StreamXidHash);
777  hash_ctl.hcxt = ApplyContext;
778  xidhash = hash_create("StreamXidHash", 1024, &hash_ctl,
780  }
781 
782  /* open the spool file for this transaction */
784 
785  /* if this is not the first segment, open existing subxact file */
786  if (!first_segment)
788 
790 }
static void subxact_info_read(Oid subid, TransactionId xid)
Definition: worker.c:2579
#define HASH_CONTEXT
Definition: hsearch.h:91
#define HASH_ELEM
Definition: hsearch.h:85
uint32 TransactionId
Definition: c.h:575
MemoryContext hcxt
Definition: hsearch.h:77
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3296
Size entrysize
Definition: hsearch.h:72
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
static bool ensure_transaction(void)
Definition: worker.c:279
bool in_streamed_transaction
Definition: worker.c:168
MemoryContext ApplyContext
Definition: worker.c:154
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:326
Size keysize
Definition: hsearch.h:71
static HTAB * xidhash
Definition: worker.c:176
#define Assert(condition)
Definition: c.h:800
TransactionId logicalrep_read_stream_start(StringInfo in, bool *first_segment)
Definition: proto.c:773
static void stream_open_file(Oid subid, TransactionId xid, bool first)
Definition: worker.c:2790
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 796 of file worker.c.

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

797 {
799 
800  /*
801  * Close the file with serialized changes, and serialize information about
802  * subxacts for the toplevel transaction.
803  */
806 
807  /* We must be in a valid transaction state */
809 
810  /* The synchronization worker runs in single transaction. */
811  if (!am_tablesync_worker())
812  {
813  /* Commit the per-stream transaction */
815  }
816 
817  in_streamed_transaction = false;
818 
819  /* Reset per-stream context */
821 
823 }
static void stream_close_file(void)
Definition: worker.c:2865
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3296
void CommitTransactionCommand(void)
Definition: xact.c:2948
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
bool in_streamed_transaction
Definition: worker.c:168
static bool am_tablesync_worker(void)
static MemoryContext LogicalStreamingContext
Definition: worker.c:157
#define Assert(condition)
Definition: c.h:800
bool IsTransactionState(void)
Definition: xact.c:371
static void subxact_info_write(Oid subid, TransactionId xid)
Definition: worker.c:2501
static TransactionId stream_xid
Definition: worker.c:170

◆ apply_handle_truncate()

static void apply_handle_truncate ( StringInfo  s)
static

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

1797 {
1798  bool cascade = false;
1799  bool restart_seqs = false;
1800  List *remote_relids = NIL;
1801  List *remote_rels = NIL;
1802  List *rels = NIL;
1803  List *part_rels = NIL;
1804  List *relids = NIL;
1805  List *relids_logged = NIL;
1806  ListCell *lc;
1807 
1809  return;
1810 
1812 
1813  remote_relids = logicalrep_read_truncate(s, &cascade, &restart_seqs);
1814 
1815  foreach(lc, remote_relids)
1816  {
1817  LogicalRepRelId relid = lfirst_oid(lc);
1818  LogicalRepRelMapEntry *rel;
1819 
1820  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1821  if (!should_apply_changes_for_rel(rel))
1822  {
1823  /*
1824  * The relation can't become interesting in the middle of the
1825  * transaction so it's safe to unlock it.
1826  */
1828  continue;
1829  }
1830 
1831  remote_rels = lappend(remote_rels, rel);
1832  rels = lappend(rels, rel->localrel);
1833  relids = lappend_oid(relids, rel->localreloid);
1835  relids_logged = lappend_oid(relids_logged, rel->localreloid);
1836 
1837  /*
1838  * Truncate partitions if we got a message to truncate a partitioned
1839  * table.
1840  */
1841  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1842  {
1843  ListCell *child;
1844  List *children = find_all_inheritors(rel->localreloid,
1846  NULL);
1847 
1848  foreach(child, children)
1849  {
1850  Oid childrelid = lfirst_oid(child);
1851  Relation childrel;
1852 
1853  if (list_member_oid(relids, childrelid))
1854  continue;
1855 
1856  /* find_all_inheritors already got lock */
1857  childrel = table_open(childrelid, NoLock);
1858 
1859  /*
1860  * Ignore temp tables of other backends. See similar code in
1861  * ExecuteTruncate().
1862  */
1863  if (RELATION_IS_OTHER_TEMP(childrel))
1864  {
1865  table_close(childrel, RowExclusiveLock);
1866  continue;
1867  }
1868 
1869  rels = lappend(rels, childrel);
1870  part_rels = lappend(part_rels, childrel);
1871  relids = lappend_oid(relids, childrelid);
1872  /* Log this relation only if needed for logical decoding */
1873  if (RelationIsLogicallyLogged(childrel))
1874  relids_logged = lappend_oid(relids_logged, childrelid);
1875  }
1876  }
1877  }
1878 
1879  /*
1880  * Even if we used CASCADE on the upstream primary we explicitly default
1881  * to replaying changes without further cascading. This might be later
1882  * changeable with a user specified option.
1883  */
1884  ExecuteTruncateGuts(rels, relids, relids_logged, DROP_RESTRICT, restart_seqs);
1885 
1886  foreach(lc, remote_rels)
1887  {
1888  LogicalRepRelMapEntry *rel = lfirst(lc);
1889 
1891  }
1892  foreach(lc, part_rels)
1893  {
1894  Relation rel = lfirst(lc);
1895 
1896  table_close(rel, NoLock);
1897  }
1898 
1900 }
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:343
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:449
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:636
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:357
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:1686
#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:274
List * lappend(List *list, void *datum)
Definition: list.c:321
void CommandCounterIncrement(void)
Definition: xact.c:1021
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
#define lfirst(lc)
Definition: pg_list.h:169
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:594
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:165
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
uint32 LogicalRepRelId
Definition: logicalproto.h:84
#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 1571 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().

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

◆ apply_handle_type()

static void apply_handle_type ( StringInfo  s)
static

Definition at line 1117 of file worker.c.

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

Referenced by apply_dispatch().

1118 {
1119  LogicalRepTyp typ;
1120 
1122  return;
1123 
1124  logicalrep_read_typ(s, &typ);
1126 }
void logicalrep_read_typ(StringInfo in, LogicalRepTyp *ltyp)
Definition: proto.c:453
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:309
void logicalrep_typmap_update(LogicalRepTyp *remotetyp)
Definition: relation.c:469

◆ apply_handle_update()

static void apply_handle_update ( StringInfo  s)
static

Definition at line 1269 of file worker.c.

References AfterTriggerEndQuery(), 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, EState::es_tupleTable, ExecInitExtraTupleSlot(), ExecResetTupleTable(), fill_extraUpdatedCols(), FirstLowInvalidHeapAttributeNumber, FreeExecutorState(), GetPerTupleMemoryContext, GetTransactionSnapshot(), handle_streamed_transaction(), i, InitResultRelInfo(), list_nth(), LogicalRepRelMapEntry::localrel, LOGICAL_REP_MSG_UPDATE, LOGICALREP_COLUMN_UNCHANGED, logicalrep_read_update(), logicalrep_rel_close(), logicalrep_rel_open(), makeNode, 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().

1270 {
1271  ResultRelInfo *resultRelInfo;
1272  LogicalRepRelMapEntry *rel;
1273  LogicalRepRelId relid;
1274  EState *estate;
1275  LogicalRepTupleData oldtup;
1276  LogicalRepTupleData newtup;
1277  bool has_oldtup;
1278  TupleTableSlot *remoteslot;
1279  RangeTblEntry *target_rte;
1280  MemoryContext oldctx;
1281 
1283  return;
1284 
1286 
1287  relid = logicalrep_read_update(s, &has_oldtup, &oldtup,
1288  &newtup);
1289  rel = logicalrep_rel_open(relid, RowExclusiveLock);
1290  if (!should_apply_changes_for_rel(rel))
1291  {
1292  /*
1293  * The relation can't become interesting in the middle of the
1294  * transaction so it's safe to unlock it.
1295  */
1297  return;
1298  }
1299 
1300  /* Check if we can do the update. */
1302 
1303  /* Initialize the executor state. */
1304  estate = create_estate_for_relation(rel);
1305  remoteslot = ExecInitExtraTupleSlot(estate,
1306  RelationGetDescr(rel->localrel),
1307  &TTSOpsVirtual);
1308  resultRelInfo = makeNode(ResultRelInfo);
1309  InitResultRelInfo(resultRelInfo, rel->localrel, 1, NULL, 0);
1310 
1311  /*
1312  * Populate updatedCols so that per-column triggers can fire. This could
1313  * include more columns than were actually changed on the publisher
1314  * because the logical replication protocol doesn't contain that
1315  * information. But it would for example exclude columns that only exist
1316  * on the subscriber, since we are not touching those.
1317  */
1318  target_rte = list_nth(estate->es_range_table, 0);
1319  for (int i = 0; i < remoteslot->tts_tupleDescriptor->natts; i++)
1320  {
1322  int remoteattnum = rel->attrmap->attnums[i];
1323 
1324  if (!att->attisdropped && remoteattnum >= 0)
1325  {
1326  Assert(remoteattnum < newtup.ncols);
1327  if (newtup.colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
1328  target_rte->updatedCols =
1329  bms_add_member(target_rte->updatedCols,
1331  }
1332  }
1333 
1334  /* Also populate extraUpdatedCols, in case we have generated columns */
1335  fill_extraUpdatedCols(target_rte, rel->localrel);
1336 
1338 
1339  /* Build the search tuple. */
1341  slot_store_data(remoteslot, rel,
1342  has_oldtup ? &oldtup : &newtup);
1343  MemoryContextSwitchTo(oldctx);
1344 
1345  /* For a partitioned table, apply update to correct partition. */
1346  if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1347  apply_handle_tuple_routing(resultRelInfo, estate,
1348  remoteslot, &newtup, rel, CMD_UPDATE);
1349  else
1350  apply_handle_update_internal(resultRelInfo, estate,
1351  remoteslot, &newtup, rel);
1352 
1354 
1355  /* Handle queued AFTER triggers. */
1356  AfterTriggerEndQuery(estate);
1357 
1358  ExecResetTupleTable(estate->es_tupleTable, false);
1359  FreeExecutorState(estate);
1360 
1362 
1364 }
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:263
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:344
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1196
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1801
#define RelationGetDescr(relation)
Definition: rel.h:483
static void apply_handle_update_internal(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry)
Definition: worker.c:1368
#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:449
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
List * es_range_table
Definition: execnodes.h:519
Form_pg_class rd_rel
Definition: rel.h:110
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
#define LOGICALREP_COLUMN_UNCHANGED
Definition: logicalproto.h:80
static bool ensure_transaction(void)
Definition: worker.c:279
static void * list_nth(const List *list, int n)
Definition: pg_list.h:266
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:193
static bool handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
Definition: worker.c:309
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:274
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:1235
static void apply_handle_tuple_routing(ResultRelInfo *relinfo, EState *estate, TupleTableSlot *remoteslot, LogicalRepTupleData *newtup, LogicalRepRelMapEntry *relmapentry, CmdType operation)
Definition: worker.c:1571
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
List * es_tupleTable
Definition: execnodes.h:561
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1161
void CommandCounterIncrement(void)
Definition: xact.c:1021
Bitmapset * updatedCols
Definition: parsenodes.h:1129
#define makeNode(_type_)
Definition: nodes.h:575
#define Assert(condition)
Definition: c.h:800
AttrNumber * attnums
Definition: attmap.h:36
LogicalRepRelId logicalrep_read_update(StringInfo in, bool *has_oldtuple, LogicalRepTupleData *oldtup, LogicalRepTupleData *newtup)
Definition: proto.c:218
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4522
int i
static void slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:465
uint32 LogicalRepRelId
Definition: logicalproto.h:84

◆ apply_handle_update_internal()

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

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

1372 {
1373  Relation localrel = relinfo->ri_RelationDesc;
1374  EPQState epqstate;
1375  TupleTableSlot *localslot;
1376  bool found;
1377  MemoryContext oldctx;
1378 
1379  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
1380  ExecOpenIndices(relinfo, false);
1381 
1382  found = FindReplTupleInLocalRel(estate, localrel,
1383  &relmapentry->remoterel,
1384  remoteslot, &localslot);
1385  ExecClearTuple(remoteslot);
1386 
1387  /*
1388  * Tuple found.
1389  *
1390  * Note this will fail if there are other conflicting unique indexes.
1391  */
1392  if (found)
1393  {
1394  /* Process and store remote tuple in the slot */
1396  slot_modify_data(remoteslot, localslot, relmapentry, newtup);
1397  MemoryContextSwitchTo(oldctx);
1398 
1399  EvalPlanQualSetSlot(&epqstate, remoteslot);
1400 
1401  /* Do the actual update. */
1402  ExecSimpleRelationUpdate(relinfo, estate, &epqstate, localslot,
1403  remoteslot);
1404  }
1405  else
1406  {
1407  /*
1408  * The tuple to be updated could not be found.
1409  *
1410  * TODO what to do here, change the log level to LOG perhaps?
1411  */
1412  elog(DEBUG1,
1413  "logical replication did not find row for update "
1414  "in replication target relation \"%s\"",
1415  RelationGetRelationName(localrel));
1416  }
1417 
1418  /* Cleanup. */
1419  ExecCloseIndices(relinfo);
1420  EvalPlanQualEnd(&epqstate);
1421 }
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:412
#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:151
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2810
LogicalRepRelation remoterel
static void slot_modify_data(TupleTableSlot *slot, TupleTableSlot *srcslot, LogicalRepRelMapEntry *rel, LogicalRepTupleData *tupleData)
Definition: worker.c:580
#define RelationGetRelationName(relation)
Definition: rel.h:491
void EvalPlanQualInit(EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2390
static bool FindReplTupleInLocalRel(EState *estate, Relation localrel, LogicalRepRelation *remoterel, TupleTableSlot *remoteslot, TupleTableSlot **localslot)
Definition: worker.c:1542
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
#define elog(elevel,...)
Definition: elog.h:228
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:226
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:217

◆ ApplyWorkerMain()

void ApplyWorkerMain ( Datum  main_arg)

Definition at line 2926 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.

2927 {
2928  int worker_slot = DatumGetInt32(main_arg);
2929  MemoryContext oldctx;
2930  char originname[NAMEDATALEN];
2931  XLogRecPtr origin_startpos;
2932  char *myslotname;
2934 
2935  /* Attach to slot */
2936  logicalrep_worker_attach(worker_slot);
2937 
2938  /* Setup signal handling */
2940  pqsignal(SIGTERM, die);
2942 
2943  /*
2944  * We don't currently need any ResourceOwner in a walreceiver process, but
2945  * if we did, we could call CreateAuxProcessResourceOwner here.
2946  */
2947 
2948  /* Initialise stats to a sanish value */
2951 
2952  /* Load the libpq-specific functions */
2953  load_file("libpqwalreceiver", false);
2954 
2955  /* Run as replica session replication role. */
2956  SetConfigOption("session_replication_role", "replica",
2958 
2959  /* Connect to our database. */
2962  0);
2963 
2964  /*
2965  * Set always-secure search path, so malicious users can't redirect user
2966  * code (e.g. pg_index.indexprs).
2967  */
2968  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
2969 
2970  /* Load the subscription into persistent memory context. */
2972  "ApplyContext",
2976 
2978  if (!MySubscription)
2979  {
2980  ereport(LOG,
2981  (errmsg("logical replication apply worker for subscription %u will not "
2982  "start because the subscription was removed during startup",
2984  proc_exit(0);
2985  }
2986 
2987  MySubscriptionValid = true;
2988  MemoryContextSwitchTo(oldctx);
2989 
2990  if (!MySubscription->enabled)
2991  {
2992  ereport(LOG,
2993  (errmsg("logical replication apply worker for subscription \"%s\" will not "
2994  "start because the subscription was disabled during startup",
2995  MySubscription->name)));
2996 
2997  proc_exit(0);
2998  }
2999 
3000  /* Setup synchronous commit according to the user's wishes */
3001  SetConfigOption("synchronous_commit", MySubscription->synccommit,
3003 
3004  /* Keep us informed about subscription changes. */
3007  (Datum) 0);
3008 
3009  if (am_tablesync_worker())
3010  ereport(LOG,
3011  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has started",
3013  else
3014  ereport(LOG,
3015  (errmsg("logical replication apply worker for subscription \"%s\" has started",
3016  MySubscription->name)));
3017 
3019 
3020  /* Connect to the origin and start the replication. */
3021  elog(DEBUG1, "connecting to publisher using connection string \"%s\"",
3023 
3024  if (am_tablesync_worker())
3025  {
3026  char *syncslotname;
3027 
3028  /* This is table synchronization worker, call initial sync. */
3029  syncslotname = LogicalRepSyncTableStart(&origin_startpos);
3030 
3031  /* allocate slot name in long-lived context */
3032  myslotname = MemoryContextStrdup(ApplyContext, syncslotname);
3033 
3034  pfree(syncslotname);
3035  }
3036  else
3037  {
3038  /* This is main apply worker */
3039  RepOriginId originid;
3040  TimeLineID startpointTLI;
3041  char *err;
3042 
3043  myslotname = MySubscription->slotname;
3044 
3045  /*
3046  * This shouldn't happen if the subscription is enabled, but guard
3047  * against DDL bugs or manual catalog changes. (libpqwalreceiver will
3048  * crash if slot is NULL.)
3049  */
3050  if (!myslotname)
3051  ereport(ERROR,
3052  (errmsg("subscription has no replication slot set")));
3053 
3054  /* Setup replication origin tracking. */
3056  snprintf(originname, sizeof(originname), "pg_%u", MySubscription->oid);
3057  originid = replorigin_by_name(originname, true);
3058  if (!OidIsValid(originid))
3059  originid = replorigin_create(originname);
3060  replorigin_session_setup(originid);
3061  replorigin_session_origin = originid;
3062  origin_startpos = replorigin_session_get_progress(false);
3064 
3066  &err);
3067  if (wrconn == NULL)
3068  ereport(ERROR,
3069  (errmsg("could not connect to the publisher: %s", err)));
3070 
3071  /*
3072  * We don't really use the output identify_system for anything but it
3073  * does some initializations on the upstream so let's still call it.
3074  */
3075  (void) walrcv_identify_system(wrconn, &startpointTLI);
3076  }
3077 
3078  /*
3079  * Setup callback for syscache so that we know when something changes in
3080  * the subscription relation state.
3081  */
3084  (Datum) 0);
3085 
3086  /* Build logical replication streaming options. */
3087  options.logical = true;
3088  options.startpoint = origin_startpos;
3089  options.slotname = myslotname;
3090  options.proto.logical.proto_version =
3091  walrcv_server_version(wrconn) >= 140000 ?
3093  options.proto.logical.publication_names = MySubscription->publications;
3094  options.proto.logical.binary = MySubscription->binary;
3095  options.proto.logical.streaming = MySubscription->stream;
3096 
3097  /* Start normal logical streaming replication. */
3098  walrcv_startstreaming(wrconn, &options);
3099 
3100  /* Run the main loop. */
3101  LogicalRepApplyLoop(origin_startpos);
3102 
3103  proc_exit(0);
3104 }
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:170
#define DEBUG1
Definition: elog.h:25
uint32 TimeLineID
Definition: xlogdefs.h:52
#define DatumGetInt32(X)
Definition: postgres.h:472
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
#define walrcv_identify_system(conn, primary_tli)
Definition: walreceiver.h:406
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void CommitTransactionCommand(void)
Definition: xact.c:2948
#define walrcv_server_version(conn)
Definition: walreceiver.h:408
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
TimestampTz last_send_time
uint16 RepOriginId
Definition: xlogdefs.h:58
#define walrcv_startstreaming(conn, options)
Definition: walreceiver.h:412
union WalRcvStreamOptions::@104 proto
void proc_exit(int code)
Definition: ipc.c:104
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1187
void replorigin_session_setup(RepOriginId node)
Definition: origin.c:1052
#define LOG
Definition: elog.h:26
char * LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
Definition: tablesync.c:820
#define OidIsValid(objectId)
Definition: c.h:706
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:2486
void pfree(void *pointer)
Definition: mcxt.c:1057
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:43
Definition: guc.h:75
static bool am_tablesync_worker(void)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void logicalrep_worker_attach(int slot)
Definition: launcher.c:629
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7808
#define SIGHUP
Definition: win32_port.h:159
XLogRecPtr startpoint
Definition: walreceiver.h:168
List * publications
RepOriginId replorigin_create(char *roname)
Definition: origin.c:240
MemoryContext TopMemoryContext
Definition: mcxt.c:44
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:367
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: postmaster.c:5718
#define ereport(elevel,...)
Definition: elog.h:155
#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:2847
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:902
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1174
static void LogicalRepApplyLoop(XLogRecPtr last_received)
Definition: worker.c:2064
#define elog(elevel,...)
Definition: elog.h:228
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1845
#define snprintf
Definition: port.h:215
#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:257
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5747
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:398

◆ changes_filename()

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

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

2735 {
2736  snprintf(path, MAXPGPATH, "%u-%u.changes", subid, xid);
2737 }
#define MAXPGPATH
#define snprintf
Definition: port.h:215

◆ check_relation_updatable()

static void check_relation_updatable ( LogicalRepRelMapEntry rel)
static

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

1236 {
1237  /* Updatable, no error. */
1238  if (rel->updatable)
1239  return;
1240 
1241  /*
1242  * We are in error mode so it's fine this is somewhat slow. It's better to
1243  * give user correct error.
1244  */
1246  {
1247  ereport(ERROR,
1248  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1249  errmsg("publisher did not send replica identity column "
1250  "expected by the logical replication target relation \"%s.%s\"",
1251  rel->remoterel.nspname, rel->remoterel.relname)));
1252  }
1253 
1254  ereport(ERROR,
1255  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1256  errmsg("logical replication target relation \"%s.%s\" has "
1257  "neither REPLICA IDENTITY index nor PRIMARY "
1258  "KEY and published relation does not have "
1259  "REPLICA IDENTITY FULL",
1260  rel->remoterel.nspname, rel->remoterel.relname)));
1261 }
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:1134
int errcode(int sqlerrcode)
Definition: elog.c:691
#define OidIsValid(objectId)
Definition: c.h:706
#define ERROR
Definition: elog.h:43
LogicalRepRelation remoterel
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:902

◆ cleanup_subxact_info()

static void cleanup_subxact_info ( void  )
inlinestatic

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

2914 {
2915  if (subxact_data.subxacts)
2917 
2918  subxact_data.subxacts = NULL;
2920  subxact_data.nsubxacts = 0;
2922 }
TransactionId subxact_last
Definition: worker.c:193
uint32 nsubxacts
Definition: worker.c:191
void pfree(void *pointer)
Definition: mcxt.c:1057
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)
static

Definition at line 344 of file worker.c.

References AccessShareLock, AfterTriggerBeginQuery(), CreateExecutorState(), EState::es_output_cid, ExecInitRangeTable(), GetCurrentCommandId(), 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().

345 {
346  EState *estate;
347  RangeTblEntry *rte;
348 
349  estate = CreateExecutorState();
350 
351  rte = makeNode(RangeTblEntry);
352  rte->rtekind = RTE_RELATION;
353  rte->relid = RelationGetRelid(rel->localrel);
354  rte->relkind = rel->localrel->rd_rel->relkind;
356  ExecInitRangeTable(estate, list_make1(rte));
357 
358  estate->es_output_cid = GetCurrentCommandId(true);
359 
360  /* Prepare to catch AFTER triggers. */
362 
363  return estate;
364 }
void ExecInitRangeTable(EState *estate, List *rangeTable)
Definition: execUtils.c:750
CommandId es_output_cid
Definition: execnodes.h:531
#define AccessShareLock
Definition: lockdefs.h:36
Form_pg_class rd_rel
Definition: rel.h:110
#define list_make1(x1)
Definition: pg_list.h:206
EState * CreateExecutorState(void)
Definition: execUtils.c:89
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4502
#define makeNode(_type_)
Definition: nodes.h:575
RTEKind rtekind
Definition: parsenodes.h:982
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:761
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ 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:38
static void maybe_reread_subscription(void)
Definition: worker.c:2388
static MemoryContext ApplyMessageContext
Definition: worker.c:153
void StartTransactionCommand(void)
Definition: xact.c:2847
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 1542 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().

1546 {
1547  Oid idxoid;
1548  bool found;
1549 
1550  *localslot = table_slot_create(localrel, &estate->es_tupleTable);
1551 
1552  idxoid = GetRelationIdentityOrPK(localrel);
1553  Assert(OidIsValid(idxoid) ||
1554  (remoterel->replident == REPLICA_IDENTITY_FULL));
1555 
1556  if (OidIsValid(idxoid))
1557  found = RelationFindReplTupleByIndex(localrel, idxoid,
1559  remoteslot, *localslot);
1560  else
1561  found = RelationFindReplTupleSeq(localrel, LockTupleExclusive,
1562  remoteslot, *localslot);
1563 
1564  return found;
1565 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:1134
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:706
bool RelationFindReplTupleByIndex(Relation rel, Oid idxoid, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)
List * es_tupleTable
Definition: execnodes.h:561
#define Assert(condition)
Definition: c.h:800
bool RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)

◆ get_flush_position()

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

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

1987 {
1988  dlist_mutable_iter iter;
1989  XLogRecPtr local_flush = GetFlushRecPtr();
1990 
1992  *flush = InvalidXLogRecPtr;
1993 
1995  {
1996  FlushPosition *pos =
1997  dlist_container(FlushPosition, node, iter.cur);
1998 
1999  *write = pos->remote_end;
2000 
2001  if (pos->local_end <= local_flush)
2002  {
2003  *flush = pos->remote_end;
2004  dlist_delete(iter.cur);
2005  pfree(pos);
2006  }
2007  else
2008  {
2009  /*
2010  * Don't want to uselessly iterate over the rest of the list which
2011  * could potentially be long. Instead get the last element and
2012  * grab the write position from there.
2013  */
2014  pos = dlist_tail_element(FlushPosition, node,
2015  &lsn_mapping);
2016  *write = pos->remote_end;
2017  *have_pending_txes = true;
2018  return;
2019  }
2020  }
2021 
2022  *have_pending_txes = !dlist_is_empty(&lsn_mapping);
2023 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
static dlist_head lsn_mapping
Definition: worker.c:130
#define write(a, b, c)
Definition: win32.h:14
XLogRecPtr remote_end
Definition: worker.c:127
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8423
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
void pfree(void *pointer)
Definition: mcxt.c:1057
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:496
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
XLogRecPtr local_end
Definition: worker.c: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 1134 of file worker.c.

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

Referenced by check_relation_updatable(), and FindReplTupleInLocalRel().

1135 {
1136  Oid idxoid;
1137 
1138  idxoid = RelationGetReplicaIndex(rel);
1139 
1140  if (!OidIsValid(idxoid))
1141  idxoid = RelationGetPrimaryKeyIndex(rel);
1142 
1143  return idxoid;
1144 }
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4724
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:706
Oid RelationGetPrimaryKeyIndex(Relation relation)
Definition: relcache.c:4703

◆ 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:2886
static void subxact_info_add(TransactionId xid)
Definition: worker.c:2649
uint32 TransactionId
Definition: c.h:575
bool in_streamed_transaction
Definition: worker.c:168
#define Assert(condition)
Definition: c.h:800
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 3110 of file worker.c.

References MyLogicalRepWorker.

Referenced by ProcessInterrupts().

3111 {
3112  return MyLogicalRepWorker != NULL;
3113 }
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57

◆ LogicalRepApplyLoop()

static void LogicalRepApplyLoop ( XLogRecPtr  last_received)
static

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

2065 {
2066  TimestampTz last_recv_timestamp = GetCurrentTimestamp();
2067  bool ping_sent = false;
2068  TimeLineID tli;
2069 
2070  /*
2071  * Init the ApplyMessageContext which we clean up after each replication
2072  * protocol message.
2073  */
2075  "ApplyMessageContext",
2077 
2078  /*
2079  * This memory context is used for per-stream data when the streaming mode
2080  * is enabled. This context is reset on each stream stop.
2081  */
2083  "LogicalStreamingContext",
2085 
2086  /* mark as idle, before starting to loop */
2088 
2089  /* This outer loop iterates once per wait. */
2090  for (;;)
2091  {
2093  int rc;
2094  int len;
2095  char *buf = NULL;
2096  bool endofstream = false;
2097  long wait_time;
2098 
2100 
2102 
2103  len = walrcv_receive(wrconn, &buf, &fd);
2104 
2105  if (len != 0)
2106  {
2107  /* Loop to process all available data (without blocking). */
2108  for (;;)
2109  {
2111 
2112  if (len == 0)
2113  {
2114  break;
2115  }
2116  else if (len < 0)
2117  {
2118  ereport(LOG,
2119  (errmsg("data stream from publisher has ended")));
2120  endofstream = true;
2121  break;
2122  }
2123  else
2124  {
2125  int c;
2126  StringInfoData s;
2127 
2128  /* Reset timeout. */
2129  last_recv_timestamp = GetCurrentTimestamp();
2130  ping_sent = false;
2131 
2132  /* Ensure we are reading the data into our memory context. */
2134 
2135  s.data = buf;
2136  s.len = len;
2137  s.cursor = 0;
2138  s.maxlen = -1;
2139 
2140  c = pq_getmsgbyte(&s);
2141 
2142  if (c == 'w')
2143  {
2144  XLogRecPtr start_lsn;
2145  XLogRecPtr end_lsn;
2146  TimestampTz send_time;
2147 
2148  start_lsn = pq_getmsgint64(&s);
2149  end_lsn = pq_getmsgint64(&s);
2150  send_time = pq_getmsgint64(&s);
2151 
2152  if (last_received < start_lsn)
2153  last_received = start_lsn;
2154 
2155  if (last_received < end_lsn)
2156  last_received = end_lsn;
2157 
2158  UpdateWorkerStats(last_received, send_time, false);
2159 
2160  apply_dispatch(&s);
2161  }
2162  else if (c == 'k')
2163  {
2164  XLogRecPtr end_lsn;
2166  bool reply_requested;
2167 
2168  end_lsn = pq_getmsgint64(&s);
2169  timestamp = pq_getmsgint64(&s);
2170  reply_requested = pq_getmsgbyte(&s);
2171 
2172  if (last_received < end_lsn)
2173  last_received = end_lsn;
2174 
2175  send_feedback(last_received, reply_requested, false);
2176  UpdateWorkerStats(last_received, timestamp, true);
2177  }
2178  /* other message types are purposefully ignored */
2179 
2181  }
2182 
2183  len = walrcv_receive(wrconn, &buf, &fd);
2184  }
2185  }
2186 
2187  /* confirm all writes so far */
2188  send_feedback(last_received, false, false);
2189 
2191  {
2192  /*
2193  * If we didn't get any transactions for a while there might be
2194  * unconsumed invalidation messages in the queue, consume them
2195  * now.
2196  */
2199 
2200  /* Process any table synchronization changes. */
2201  process_syncing_tables(last_received);
2202  }
2203 
2204  /* Cleanup the memory. */
2207 
2208  /* Check if we need to exit the streaming loop. */
2209  if (endofstream)
2210  break;
2211 
2212  /*
2213  * Wait for more data or latch. If we have unflushed transactions,
2214  * wake up after WalWriterDelay to see if they've been flushed yet (in
2215  * which case we should send a feedback message). Otherwise, there's
2216  * no particular urgency about waking up unless we get data or a
2217  * signal.
2218  */
2219  if (!dlist_is_empty(&lsn_mapping))
2220  wait_time = WalWriterDelay;
2221  else
2222  wait_time = NAPTIME_PER_CYCLE;
2223 
2227  fd, wait_time,
2229 
2230  if (rc & WL_LATCH_SET)
2231  {
2234  }
2235 
2236  if (ConfigReloadPending)
2237  {
2238  ConfigReloadPending = false;
2240  }
2241 
2242  if (rc & WL_TIMEOUT)
2243  {
2244  /*
2245  * We didn't receive anything new. If we haven't heard anything
2246  * from the server for more than wal_receiver_timeout / 2, ping
2247  * the server. Also, if it's been longer than
2248  * wal_receiver_status_interval since the last update we sent,
2249  * send a status update to the primary anyway, to report any
2250  * progress in applying WAL.
2251  */
2252  bool requestReply = false;
2253 
2254  /*
2255  * Check if time since last receive from standby has reached the
2256  * configured limit.
2257  */
2258  if (wal_receiver_timeout > 0)
2259  {
2261  TimestampTz timeout;
2262 
2263  timeout =
2264  TimestampTzPlusMilliseconds(last_recv_timestamp,
2266 
2267  if (now >= timeout)
2268  ereport(ERROR,
2269  (errmsg("terminating logical replication worker due to timeout")));
2270 
2271  /* Check to see if it's time for a ping. */
2272  if (!ping_sent)
2273  {
2274  timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
2275  (wal_receiver_timeout / 2));
2276  if (now >= timeout)
2277  {
2278  requestReply = true;
2279  ping_sent = true;
2280  }
2281  }
2282  }
2283 
2284  send_feedback(last_received, requestReply, requestReply);
2285  }
2286  }
2287 
2288  /* All done */
2289  walrcv_endstreaming(wrconn, &tli);
2290 }
static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
Definition: worker.c:2299
WalReceiverConn * wrconn
Definition: worker.c:159
#define AllocSetContextCreate
Definition: memutils.h:170
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:414
uint32 TimeLineID
Definition: xlogdefs.h:52
void AcceptInvalidationMessages(void)
Definition: inval.c:684
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
static dlist_head lsn_mapping
Definition: worker.c:130
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:530
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3296
int64 timestamp
int64 TimestampTz
Definition: timestamp.h:39
static void UpdateWorkerStats(XLogRecPtr last_lsn, TimestampTz send_time, bool reply)
Definition: worker.c:2048
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:416
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define WL_SOCKET_READABLE
Definition: latch.h:125
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
#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:588
int wal_receiver_timeout
Definition: walreceiver.c:89
#define ERROR
Definition: elog.h:43
#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:192
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:438
int pgsocket
Definition: port.h:31
MemoryContext TopMemoryContext
Definition: mcxt.c:44
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:155
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:1907
static void maybe_reread_subscription(void)
Definition: worker.c:2388
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:902
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:455
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1542
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ maybe_reread_subscription()

static void maybe_reread_subscription ( void  )
static

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

2389 {
2390  MemoryContext oldctx;
2392  bool started_tx = false;
2393 
2394  /* When cache state is valid there is nothing to do here. */
2395  if (MySubscriptionValid)
2396  return;
2397 
2398  /* This function might be called inside or outside of transaction. */
2399  if (!IsTransactionState())
2400  {
2402  started_tx = true;
2403  }
2404 
2405  /* Ensure allocations in permanent context. */
2407 
2408  newsub = GetSubscription(MyLogicalRepWorker->subid, true);
2409 
2410  /*
2411  * Exit if the subscription was removed. This normally should not happen
2412  * as the worker gets killed during DROP SUBSCRIPTION.
2413  */
2414  if (!newsub)
2415  {
2416  ereport(LOG,
2417  (errmsg("logical replication apply worker for subscription \"%s\" will "
2418  "stop because the subscription was removed",
2419  MySubscription->name)));
2420 
2421  proc_exit(0);
2422  }
2423 
2424  /*
2425  * Exit if the subscription was disabled. This normally should not happen
2426  * as the worker gets killed during ALTER SUBSCRIPTION ... DISABLE.
2427  */
2428  if (!newsub->enabled)
2429  {
2430  ereport(LOG,
2431  (errmsg("logical replication apply worker for subscription \"%s\" will "
2432  "stop because the subscription was disabled",
2433  MySubscription->name)));
2434 
2435  proc_exit(0);
2436  }
2437 
2438  /* !slotname should never happen when enabled is true. */
2439  Assert(newsub->slotname);
2440 
2441  /*
2442  * Exit if any parameter that affects the remote connection was changed.
2443  * The launcher will start a new worker.
2444  */
2445  if (strcmp(newsub->conninfo, MySubscription->conninfo) != 0 ||
2446  strcmp(newsub->name, MySubscription->name) != 0 ||
2447  strcmp(newsub->slotname, MySubscription->slotname) != 0 ||
2448  newsub->binary != MySubscription->binary ||
2449  newsub->stream != MySubscription->stream ||
2451  {
2452  ereport(LOG,
2453  (errmsg("logical replication apply worker for subscription \"%s\" will restart because of a parameter change",
2454  MySubscription->name)));
2455 
2456  proc_exit(0);
2457  }
2458 
2459  /* Check for other changes that should never happen too. */
2460  if (newsub->dbid != MySubscription->dbid)
2461  {
2462  elog(ERROR, "subscription %u changed unexpectedly",
2464  }
2465 
2466  /* Clean old subscription info and switch to new one. */
2469 
2470  MemoryContextSwitchTo(oldctx);
2471 
2472  /* Change synchronous commit according to the user's wishes */
2473  SetConfigOption("synchronous_commit", MySubscription->synccommit,
2475 
2476  if (started_tx)
2478 
2479  MySubscriptionValid = true;
2480 }
Subscription * MySubscription
Definition: worker.c:161
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3029
void CommitTransactionCommand(void)
Definition: xact.c:2948
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:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7808
List * publications
MemoryContext ApplyContext
Definition: worker.c:154
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:800
void StartTransactionCommand(void)
Definition: xact.c:2847
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:902
#define elog(elevel,...)
Definition: elog.h:228
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 2299 of file worker.c.

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

Referenced by LogicalRepApplyLoop().

2300 {
2301  static StringInfo reply_message = NULL;
2302  static TimestampTz send_time = 0;
2303 
2304  static XLogRecPtr last_recvpos = InvalidXLogRecPtr;
2305  static XLogRecPtr last_writepos = InvalidXLogRecPtr;
2306  static XLogRecPtr last_flushpos = InvalidXLogRecPtr;
2307 
2308  XLogRecPtr writepos;
2309  XLogRecPtr flushpos;
2310  TimestampTz now;
2311  bool have_pending_txes;
2312 
2313  /*
2314  * If the user doesn't want status to be reported to the publisher, be
2315  * sure to exit before doing anything at all.
2316  */
2317  if (!force && wal_receiver_status_interval <= 0)
2318  return;
2319 
2320  /* It's legal to not pass a recvpos */
2321  if (recvpos < last_recvpos)
2322  recvpos = last_recvpos;
2323 
2324  get_flush_position(&writepos, &flushpos, &have_pending_txes);
2325 
2326  /*
2327  * No outstanding transactions to flush, we can report the latest received
2328  * position. This is important for synchronous replication.
2329  */
2330  if (!have_pending_txes)
2331  flushpos = writepos = recvpos;
2332 
2333  if (writepos < last_writepos)
2334  writepos = last_writepos;
2335 
2336  if (flushpos < last_flushpos)
2337  flushpos = last_flushpos;
2338 
2339  now = GetCurrentTimestamp();
2340 
2341  /* if we've already reported everything we're good */
2342  if (!force &&
2343  writepos == last_writepos &&
2344  flushpos == last_flushpos &&
2345  !TimestampDifferenceExceeds(send_time, now,
2347  return;
2348  send_time = now;
2349 
2350  if (!reply_message)
2351  {
2353 
2354  reply_message = makeStringInfo();
2355  MemoryContextSwitchTo(oldctx);
2356  }
2357  else
2358  resetStringInfo(reply_message);
2359 
2360  pq_sendbyte(reply_message, 'r');
2361  pq_sendint64(reply_message, recvpos); /* write */
2362  pq_sendint64(reply_message, flushpos); /* flush */
2363  pq_sendint64(reply_message, writepos); /* apply */
2364  pq_sendint64(reply_message, now); /* sendTime */
2365  pq_sendbyte(reply_message, requestReply); /* replyRequested */
2366 
2367  elog(DEBUG2, "sending feedback (force %d) to recv %X/%X, write %X/%X, flush %X/%X",
2368  force,
2369  (uint32) (recvpos >> 32), (uint32) recvpos,
2370  (uint32) (writepos >> 32), (uint32) writepos,
2371  (uint32) (flushpos >> 32), (uint32) flushpos
2372  );
2373 
2374  walrcv_send(wrconn, reply_message->data, reply_message->len);
2375 
2376  if (recvpos > last_recvpos)
2377  last_recvpos = recvpos;
2378  if (writepos > last_writepos)
2379  last_writepos = writepos;
2380  if (flushpos > last_flushpos)
2381  last_flushpos = flushpos;
2382 }
WalReceiverConn * wrconn
Definition: worker.c:159
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
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:88
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1709
static void get_flush_position(XLogRecPtr *write, XLogRecPtr *flush, bool *have_pending_txes)
Definition: worker.c:1985
static void pq_sendbyte(StringInfo buf, uint8 byt)
Definition: pqformat.h:161
static StringInfoData reply_message
Definition: walreceiver.c:117
#define DEBUG2
Definition: elog.h:24
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
unsigned int uint32
Definition: c.h:429
MemoryContext ApplyContext
Definition: worker.c:154
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define walrcv_send(conn, buffer, nbytes)
Definition: walreceiver.h:418
#define elog(elevel,...)
Definition: elog.h:228
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1542

◆ 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 374 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().

376 {
377  TupleDesc desc = RelationGetDescr(rel->localrel);
378  int num_phys_attrs = desc->natts;
379  int i;
380  int attnum,
381  num_defaults = 0;
382  int *defmap;
383  ExprState **defexprs;
384  ExprContext *econtext;
385 
386  econtext = GetPerTupleExprContext(estate);
387 
388  /* We got all the data via replication, no need to evaluate anything. */
389  if (num_phys_attrs == rel->remoterel.natts)
390  return;
391 
392  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
393  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
394 
395  Assert(rel->attrmap->maplen == num_phys_attrs);
396  for (attnum = 0; attnum < num_phys_attrs; attnum++)
397  {
398  Expr *defexpr;
399 
400  if (TupleDescAttr(desc, attnum)->attisdropped || TupleDescAttr(desc, attnum)->attgenerated)
401  continue;
402 
403  if (rel->attrmap->attnums[attnum] >= 0)
404  continue;
405 
406  defexpr = (Expr *) build_column_default(rel->localrel, attnum + 1);
407 
408  if (defexpr != NULL)
409  {
410  /* Run the expression through planner */
411  defexpr = expression_planner(defexpr);
412 
413  /* Initialize executable expression in copycontext */
414  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
415  defmap[num_defaults] = attnum;
416  num_defaults++;
417  }
418 
419  }
420 
421  for (i = 0; i < num_defaults; i++)
422  slot->tts_values[defmap[i]] =
423  ExecEvalExpr(defexprs[i], econtext, &slot->tts_isnull[defmap[i]]);
424 }
#define RelationGetDescr(relation)
Definition: rel.h:483
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Expr * expression_planner(Expr *expr)
Definition: planner.c:6166
int maplen
Definition: attmap.h:37
Datum * tts_values
Definition: tuptable.h:126
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
LogicalRepRelation remoterel
bool * tts_isnull
Definition: tuptable.h:128
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:292
Node * build_column_default(Relation rel, int attrno)
int16 attnum
Definition: pg_attribute.h:79
#define Assert(condition)
Definition: c.h:800
AttrNumber * attnums
Definition: attmap.h:36
void * palloc(Size size)
Definition: mcxt.c:950
int i
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:122

◆ slot_modify_data()

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

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

583 {
584  int natts = slot->tts_tupleDescriptor->natts;
585  int i;
586  SlotErrCallbackArg errarg;
587  ErrorContextCallback errcallback;
588 
589  /* We'll fill "slot" with a virtual tuple, so we must start with ... */
590  ExecClearTuple(slot);
591 
592  /*
593  * Copy all the column data from srcslot, so that we'll have valid values
594  * for unreplaced columns.
595  */
596  Assert(natts == srcslot->tts_tupleDescriptor->natts);
597  slot_getallattrs(srcslot);
598  memcpy(slot->tts_values, srcslot->tts_values, natts * sizeof(Datum));
599  memcpy(slot->tts_isnull, srcslot->tts_isnull, natts * sizeof(bool));
600 
601  /* For error reporting, push callback + info on the error context stack */
602  errarg.rel = rel;
603  errarg.local_attnum = -1;
604  errarg.remote_attnum = -1;
605  errcallback.callback = slot_store_error_callback;
606  errcallback.arg = (void *) &errarg;
607  errcallback.previous = error_context_stack;
608  error_context_stack = &errcallback;
609 
610  /* Call the "in" function for each replaced attribute */
611  Assert(natts == rel->attrmap->maplen);
612  for (i = 0; i < natts; i++)
613  {
615  int remoteattnum = rel->attrmap->attnums[i];
616 
617  if (remoteattnum < 0)
618  continue;
619 
620  Assert(remoteattnum < tupleData->ncols);
621 
622  if (tupleData->colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
623  {
624  StringInfo colvalue = &tupleData->colvalues[remoteattnum];
625 
626  errarg.local_attnum = i;
627  errarg.remote_attnum = remoteattnum;
628 
629  if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
630  {
631  Oid typinput;
632  Oid typioparam;
633 
634  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
635  slot->tts_values[i] =
636  OidInputFunctionCall(typinput, colvalue->data,
637  typioparam, att->atttypmod);
638  slot->tts_isnull[i] = false;
639  }
640  else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
641  {
642  Oid typreceive;
643  Oid typioparam;
644 
645  /*
646  * In some code paths we may be asked to re-parse the same
647  * tuple data. Reset the StringInfo's cursor so that works.
648  */
649  colvalue->cursor = 0;
650 
651  getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
652  slot->tts_values[i] =
653  OidReceiveFunctionCall(typreceive, colvalue,
654  typioparam, att->atttypmod);
655 
656  /* Trouble if it didn't eat the whole buffer */
657  if (colvalue->cursor != colvalue->len)
658  ereport(ERROR,
659  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
660  errmsg("incorrect binary data format in logical replication column %d",
661  remoteattnum + 1)));
662  slot->tts_isnull[i] = false;
663  }
664  else
665  {
666  /* must be LOGICALREP_COLUMN_NULL */
667  slot->tts_values[i] = (Datum) 0;
668  slot->tts_isnull[i] = true;
669  }
670 
671  errarg.local_attnum = -1;
672  errarg.remote_attnum = -1;
673  }
674  }
675 
676  /* Pop the error context stack */
677  error_context_stack = errcallback.previous;
678 
679  /* And finally, declare that "slot" contains a valid virtual tuple */
680  ExecStoreVirtualTuple(slot);
681 }
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:691
#define LOGICALREP_COLUMN_TEXT
Definition: logicalproto.h:81
Datum * tts_values
Definition: tuptable.h:126
StringInfoData * colvalues
Definition: logicalproto.h:70
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:243
struct ErrorContextCallback * previous
Definition: elog.h:242
#define LOGICALREP_COLUMN_BINARY
Definition: logicalproto.h:82
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#define LOGICALREP_COLUMN_UNCHANGED
Definition: logicalproto.h:80
#define ERROR
Definition: elog.h:43
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:1666
bool * tts_isnull
Definition: tuptable.h:128
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2822
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2756
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:800
AttrNumber * attnums
Definition: attmap.h:36
static void slot_store_error_callback(void *arg)
Definition: worker.c:430
int errmsg(const char *fmt,...)
Definition: elog.c:902
int i
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1648
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1522

◆ slot_store_data()

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

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

467 {
468  int natts = slot->tts_tupleDescriptor->natts;
469  int i;
470  SlotErrCallbackArg errarg;
471  ErrorContextCallback errcallback;
472 
473  ExecClearTuple(slot);
474 
475  /* Push callback + info on the error context stack */
476  errarg.rel = rel;
477  errarg.local_attnum = -1;
478  errarg.remote_attnum = -1;
479  errcallback.callback = slot_store_error_callback;
480  errcallback.arg = (void *) &errarg;
481  errcallback.previous = error_context_stack;
482  error_context_stack = &errcallback;
483 
484  /* Call the "in" function for each non-dropped, non-null attribute */
485  Assert(natts == rel->attrmap->maplen);
486  for (i = 0; i < natts; i++)
487  {
489  int remoteattnum = rel->attrmap->attnums[i];
490 
491  if (!att->attisdropped && remoteattnum >= 0)
492  {
493  StringInfo colvalue = &tupleData->colvalues[remoteattnum];
494 
495  Assert(remoteattnum < tupleData->ncols);
496 
497  errarg.local_attnum = i;
498  errarg.remote_attnum = remoteattnum;
499 
500  if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
501  {
502  Oid typinput;
503  Oid typioparam;
504 
505  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
506  slot->tts_values[i] =
507  OidInputFunctionCall(typinput, colvalue->data,
508  typioparam, att->atttypmod);
509  slot->tts_isnull[i] = false;
510  }
511  else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
512  {
513  Oid typreceive;
514  Oid typioparam;
515 
516  /*
517  * In some code paths we may be asked to re-parse the same
518  * tuple data. Reset the StringInfo's cursor so that works.
519  */
520  colvalue->cursor = 0;
521 
522  getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
523  slot->tts_values[i] =
524  OidReceiveFunctionCall(typreceive, colvalue,
525  typioparam, att->atttypmod);
526 
527  /* Trouble if it didn't eat the whole buffer */
528  if (colvalue->cursor != colvalue->len)
529  ereport(ERROR,
530  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
531  errmsg("incorrect binary data format in logical replication column %d",
532  remoteattnum + 1)));
533  slot->tts_isnull[i] = false;
534  }
535  else
536  {
537  /*
538  * NULL value from remote. (We don't expect to see
539  * LOGICALREP_COLUMN_UNCHANGED here, but if we do, treat it as
540  * NULL.)
541  */
542  slot->tts_values[i] = (Datum) 0;
543  slot->tts_isnull[i] = true;
544  }
545 
546  errarg.local_attnum = -1;
547  errarg.remote_attnum = -1;
548  }
549  else
550  {
551  /*
552  * We assign NULL to dropped attributes and missing values
553  * (missing values should be later filled using
554  * slot_fill_defaults).
555  */
556  slot->tts_values[i] = (Datum) 0;
557  slot->tts_isnull[i] = true;
558  }
559  }
560 
561  /* Pop the error context stack */
562  error_context_stack = errcallback.previous;
563 
564  ExecStoreVirtualTuple(slot);
565 }
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:691
#define LOGICALREP_COLUMN_TEXT
Definition: logicalproto.h:81
Datum * tts_values
Definition: tuptable.h:126
StringInfoData * colvalues
Definition: logicalproto.h:70
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:243
struct ErrorContextCallback * previous
Definition: elog.h:242
#define LOGICALREP_COLUMN_BINARY
Definition: logicalproto.h:82
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#define ERROR
Definition: elog.h:43
Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:1666
bool * tts_isnull
Definition: tuptable.h:128
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2822
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2756
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:800
AttrNumber * attnums
Definition: attmap.h:36
static void slot_store_error_callback(void *arg)
Definition: worker.c:430
int errmsg(const char *fmt,...)
Definition: elog.c:902
int i
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1648
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1522

◆ slot_store_error_callback()

static void slot_store_error_callback ( void *  arg)
static

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

431 {
434  char *remotetypname;
435  Oid remotetypoid,
436  localtypoid;
437 
438  /* Nothing to do if remote attribute number is not set */
439  if (errarg->remote_attnum < 0)
440  return;
441 
442  rel = errarg->rel;
443  remotetypoid = rel->remoterel.atttyps[errarg->remote_attnum];
444 
445  /* Fetch remote type name from the LogicalRepTypMap cache */
446  remotetypname = logicalrep_typmap_gettypname(remotetypoid);
447 
448  /* Fetch local type OID from the local sys cache */
449  localtypoid = get_atttype(rel->localreloid, errarg->local_attnum + 1);
450 
451  errcontext("processing remote data for replication target relation \"%s.%s\" column \"%s\", "
452  "remote type %s, local type %s",
453  rel->remoterel.nspname, rel->remoterel.relname,
454  rel->remoterel.attnames[errarg->remote_attnum],
455  remotetypname,
456  format_type_be(localtypoid));
457 }
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:911
char * logicalrep_typmap_gettypname(Oid remoteid)
Definition: relation.c:503
#define errcontext
Definition: elog.h:199
void * arg

◆ store_flush_position()

static void store_flush_position ( XLogRecPtr  remote_lsn)
static

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

2030 {
2031  FlushPosition *flushpos;
2032 
2033  /* Need to do this in permanent context */
2035 
2036  /* Track commit lsn */
2037  flushpos = (FlushPosition *) palloc(sizeof(FlushPosition));
2038  flushpos->local_end = XactLastCommitEnd;
2039  flushpos->remote_end = remote_lsn;
2040 
2041  dlist_push_tail(&lsn_mapping, &flushpos->node);
2043 }
static dlist_head lsn_mapping
Definition: worker.c:130
dlist_node node
Definition: worker.c:125
XLogRecPtr XactLastCommitEnd
Definition: xlog.c:362
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:950

◆ stream_cleanup_files()

static void stream_cleanup_files ( Oid  subid,
TransactionId  xid 
)
static

Definition at line 2747 of file worker.c.

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

2748 {
2749  char path[MAXPGPATH];
2750  StreamXidHash *ent;
2751 
2752  /* Remove the xid entry from the stream xid hash */
2753  ent = (StreamXidHash *) hash_search(xidhash,
2754  (void *) &xid,
2755  HASH_REMOVE,
2756  NULL);
2757  /* By this time we must have created the transaction entry */
2758  Assert(ent != NULL);
2759 
2760  /* Delete the change file and release the stream fileset memory */
2761  changes_filename(path, subid, xid);
2763  pfree(ent->stream_fileset);
2764  ent->stream_fileset = NULL;
2765 
2766  /* Delete the subxact file and release the memory, if it exist */
2767  if (ent->subxact_fileset)
2768  {
2769  subxact_filename(path, subid, xid);
2771  pfree(ent->subxact_fileset);
2772  ent->subxact_fileset = NULL;
2773  }
2774 }
static void changes_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2734
static void subxact_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2727
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
void pfree(void *pointer)
Definition: mcxt.c:1057
#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:800

◆ stream_close_file()

static void stream_close_file ( void  )
static

Definition at line 2865 of file worker.c.

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

Referenced by apply_handle_stream_stop().

2866 {
2869  Assert(stream_fd != NULL);
2870 
2872 
2874  stream_fd = NULL;
2875 }
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:800
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 2790 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().

2791 {
2792  char path[MAXPGPATH];
2793  bool found;
2794  MemoryContext oldcxt;
2795  StreamXidHash *ent;
2796 
2798  Assert(OidIsValid(subid));
2800  Assert(stream_fd == NULL);
2801 
2802  /* create or find the xid entry in the xidhash */
2803  ent = (StreamXidHash *) hash_search(xidhash,
2804  (void *) &xid,
2806  &found);
2807  Assert(first_segment || found);
2808  changes_filename(path, subid, xid);
2809  elog(DEBUG1, "opening file \"%s\" for streamed changes", path);
2810 
2811  /*
2812  * Create/open the buffiles under the logical streaming context so that we
2813  * have those files until stream stop.
2814  */
2816 
2817  /*
2818  * If this is the first streamed segment, the file must not exist, so make
2819  * sure we're the ones creating it. Otherwise just open the file for
2820  * writing, in append mode.
2821  */
2822  if (first_segment)
2823  {
2824  MemoryContext savectx;
2825  SharedFileSet *fileset;
2826 
2827  /*
2828  * We need to maintain shared fileset across multiple stream
2829  * start/stop calls. So, need to allocate it in a persistent context.
2830  */
2832  fileset = palloc(sizeof(SharedFileSet));
2833 
2834  SharedFileSetInit(fileset, NULL);
2835  MemoryContextSwitchTo(savectx);
2836 
2837  stream_fd = BufFileCreateShared(fileset, path);
2838 
2839  /* Remember the fileset for the next stream of the same transaction */
2840  ent->xid = xid;
2841  ent->stream_fileset = fileset;
2842  ent->subxact_fileset = NULL;
2843  }
2844  else
2845  {
2846  /*
2847  * Open the file and seek to the end of the file because we always
2848  * append the changes file.
2849  */
2850  stream_fd = BufFileOpenShared(ent->stream_fileset, path, O_RDWR);
2851  BufFileSeek(stream_fd, 0, 0, SEEK_END);
2852  }
2853 
2854  MemoryContextSwitchTo(oldcxt);
2855 }
#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:2734
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
#define OidIsValid(objectId)
Definition: c.h:706
#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:800
TransactionId xid
Definition: worker.c:148
void * palloc(Size size)
Definition: mcxt.c:950
static BufFile * stream_fd
Definition: worker.c:179
#define elog(elevel,...)
Definition: elog.h:228
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ stream_write_change()

static void stream_write_change ( char  action,
StringInfo  s 
)
static

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

2887 {
2888  int len;
2889 
2892  Assert(stream_fd != NULL);
2893 
2894  /* total on-disk size, including the action type character */
2895  len = (s->len - s->cursor) + sizeof(char);
2896 
2897  /* first write the size */
2898  BufFileWrite(stream_fd, &len, sizeof(len));
2899 
2900  /* then the action */
2901  BufFileWrite(stream_fd, &action, sizeof(action));
2902 
2903  /* and finally the remaining part of the buffer (after the XID) */
2904  len = (s->len - s->cursor);
2905 
2906  BufFileWrite(stream_fd, &s->data[s->cursor], len);
2907 }
bool in_streamed_transaction
Definition: worker.c:168
#define Assert(condition)
Definition: c.h:800
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 2486 of file worker.c.

References MySubscriptionValid.

Referenced by ApplyWorkerMain().

2487 {
2488  MySubscriptionValid = false;
2489 }
bool MySubscriptionValid
Definition: worker.c:162

◆ subxact_filename()

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

Definition at line 2727 of file worker.c.

References MAXPGPATH, and snprintf.

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

2728 {
2729  snprintf(path, MAXPGPATH, "%u-%u.subxacts", subid, xid);
2730 }
#define MAXPGPATH
#define snprintf
Definition: port.h:215

◆ subxact_info_add()

static void subxact_info_add ( TransactionId  xid)
static

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

2650 {
2651  SubXactInfo *subxacts = subxact_data.subxacts;
2652  int64 i;
2653 
2654  /* We must have a valid top level stream xid and a stream fd. */
2656  Assert(stream_fd != NULL);
2657 
2658  /*
2659  * If the XID matches the toplevel transaction, we don't want to add it.
2660  */
2661  if (stream_xid == xid)
2662  return;
2663 
2664  /*
2665  * In most cases we're checking the same subxact as we've already seen in
2666  * the last call, so make sure to ignore it (this change comes later).
2667  */
2668  if (subxact_data.subxact_last == xid)
2669  return;
2670 
2671  /* OK, remember we're processing this XID. */
2672  subxact_data.subxact_last = xid;
2673 
2674  /*
2675  * Check if the transaction is already present in the array of subxact. We
2676  * intentionally scan the array from the tail, because we're likely adding
2677  * a change for the most recent subtransactions.
2678  *
2679  * XXX Can we rely on the subxact XIDs arriving in sorted order? That
2680  * would allow us to use binary search here.
2681  */
2682  for (i = subxact_data.nsubxacts; i > 0; i--)
2683  {
2684  /* found, so we're done */
2685  if (subxacts[i - 1].xid == xid)
2686  return;
2687  }
2688 
2689  /* This is a new subxact, so we need to add it to the array. */
2690  if (subxact_data.nsubxacts == 0)
2691  {
2692  MemoryContext oldctx;
2693 
2695 
2696  /*
2697  * Allocate this memory for subxacts in per-stream context, see
2698  * subxact_info_read.
2699  */
2701  subxacts = palloc(subxact_data.nsubxacts_max * sizeof(SubXactInfo));
2702  MemoryContextSwitchTo(oldctx);
2703  }
2705  {
2707  subxacts = repalloc(subxacts,
2709  }
2710 
2711  subxacts[subxact_data.nsubxacts].xid = xid;
2712 
2713  /*
2714  * Get the current offset of the stream file and store it as offset of
2715  * this subxact.
2716  */
2718  &subxacts[subxact_data.nsubxacts].fileno,
2719  &subxacts[subxact_data.nsubxacts].offset);
2720 
2722  subxact_data.subxacts = subxacts;
2723 }
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:800
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1070
off_t offset
Definition: worker.c:185
void * palloc(Size size)
Definition: mcxt.c:950
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 2579 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().

2580 {
2581  char path[MAXPGPATH];
2582  bool found;
2583  Size len;
2584  BufFile *fd;
2585  StreamXidHash *ent;
2586  MemoryContext oldctx;
2587 
2592 
2593  /* Find the stream xid entry in the xidhash */
2594  ent = (StreamXidHash *) hash_search(xidhash,
2595  (void *) &xid,
2596  HASH_FIND,
2597  &found);
2598 
2599  /*
2600  * If subxact_fileset is not valid that mean we don't have any subxact
2601  * info
2602  */
2603  if (ent->subxact_fileset == NULL)
2604  return;
2605 
2606  subxact_filename(path, subid, xid);
2607 
2608  fd = BufFileOpenShared(ent->subxact_fileset, path, O_RDONLY);
2609 
2610  /* read number of subxact items */
2612  sizeof(subxact_data.nsubxacts)) !=
2613  sizeof(subxact_data.nsubxacts))
2614  ereport(ERROR,
2616  errmsg("could not read from streaming transaction's subxact file \"%s\": %m",
2617  path)));
2618 
2619  len = sizeof(SubXactInfo) * subxact_data.nsubxacts;
2620 
2621  /* we keep the maximum as a power of 2 */
2623 
2624  /*
2625  * Allocate subxact information in the logical streaming context. We need
2626  * this information during the complete stream so that we can add the sub
2627  * transaction info to this. On stream stop we will flush this information
2628  * to the subxact file and reset the logical streaming context.
2629  */
2632  sizeof(SubXactInfo));
2633  MemoryContextSwitchTo(oldctx);
2634 
2635  if ((len > 0) && ((BufFileRead(fd, subxact_data.subxacts, len)) != len))
2636  ereport(ERROR,
2638  errmsg("could not read from streaming transaction's subxact file \"%s\": %m",
2639  path)));
2640 
2641  BufFileClose(fd);
2642 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void subxact_filename(char *path, Oid subid, TransactionId xid)
Definition: worker.c:2727
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
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:43
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:714
BufFile * BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)
Definition: buffile.c:284
int my_log2(long num)
Definition: dynahash.c:1730
SharedFileSet * subxact_fileset
Definition: worker.c:150
#define ereport(elevel,...)
Definition: elog.h:155
static MemoryContext LogicalStreamingContext
Definition: worker.c:157
struct SubXactInfo SubXactInfo
static HTAB * xidhash
Definition: worker.c:176
#define Assert(condition)
Definition: c.h:800
size_t Size
Definition: c.h:528
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:902
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 2501 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().

2502 {
2503  char path[MAXPGPATH];
2504  bool found;
2505  Size len;
2506  StreamXidHash *ent;
2507  BufFile *fd;
2508 
2510 
2511  /* find the xid entry in the xidhash */
2512  ent = (StreamXidHash *) hash_search(xidhash,
2513  (void *) &xid,
2514  HASH_FIND,
2515  &found);
2516  /* we must found the entry for its top transaction by this time */
2517  Assert(found);
2518 
2519  /*
2520  * If there is no subtransaction then nothing to do, but if already have
2521  * subxact file then delete that.
2522  */
2523  if (subxact_data.nsubxacts == 0)
2524  {
2525  if (ent->subxact_fileset)
2526  {
2529  pfree(ent->subxact_fileset);
2530  ent->subxact_fileset = NULL;
2531  }
2532  return;
2533  }
2534 
2535  subxact_filename(path, subid, xid);
2536 
2537  /*
2538  * Create the subxact file if it not already created, otherwise open the
2539  * existing file.
2540  */
2541  if (ent->subxact_fileset == NULL)
2542  {
2543  MemoryContext oldctx;
2544 
2545  /*
2546  * We need to maintain shared fileset across multiple stream
2547  * start/stop calls. So, need to allocate it in a persistent context.
2548  */
2550  ent->subxact_fileset = palloc(sizeof(SharedFileSet));
2551  SharedFileSetInit(ent->subxact_fileset, NULL);
2552  MemoryContextSwitchTo(oldctx);
2553 
2554  fd = BufFileCreateShared(ent->subxact_fileset, path);
2555  }
2556  else
2557  fd = BufFileOpenShared(ent->subxact_fileset, path, O_RDWR);
2558 
2559  len = sizeof(SubXactInfo) * subxact_data.nsubxacts;
2560 
2561  /* Write the subxact count and subxact info */
2564 
2565  BufFileClose(fd);
2566 
2567  /* free the memory allocated for subxact info */
2569 }
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:2727
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
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:1057
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 ApplyContext
Definition: worker.c:154
SharedFileSet * subxact_fileset
Definition: worker.c:150
struct SubXactInfo SubXactInfo
static HTAB * xidhash
Definition: worker.c: