PostgreSQL Source Code  git master
tablesync.c File Reference
#include "postgres.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/indexing.h"
#include "catalog/pg_subscription_rel.h"
#include "catalog/pg_type.h"
#include "commands/copy.h"
#include "miscadmin.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "replication/logicallauncher.h"
#include "replication/logicalrelation.h"
#include "replication/walreceiver.h"
#include "replication/worker_internal.h"
#include "replication/slot.h"
#include "replication/origin.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "utils/acl.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rls.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for tablesync.c:

Go to the source code of this file.

Functions

static bool FetchTableStates (bool *started_tx)
 
static void pg_attribute_noreturn () finish_sync_worker(void)
 
static bool wait_for_relation_state_change (Oid relid, char expected_state)
 
static bool wait_for_worker_state_change (char expected_state)
 
void invalidate_syncing_table_states (Datum arg, int cacheid, uint32 hashvalue)
 
static void process_syncing_tables_for_sync (XLogRecPtr current_lsn)
 
static void process_syncing_tables_for_apply (XLogRecPtr current_lsn)
 
void process_syncing_tables (XLogRecPtr current_lsn)
 
static Listmake_copy_attnamelist (LogicalRepRelMapEntry *rel)
 
static int copy_read_data (void *outbuf, int minread, int maxread)
 
static void fetch_remote_table_info (char *nspname, char *relname, LogicalRepRelation *lrel, List **qual)
 
static void copy_table (Relation rel)
 
void ReplicationSlotNameForTablesync (Oid suboid, Oid relid, char *syncslotname, int szslot)
 
void ReplicationOriginNameForTablesync (Oid suboid, Oid relid, char *originname, int szorgname)
 
char * LogicalRepSyncTableStart (XLogRecPtr *origin_startpos)
 
bool AllTablesyncsReady (void)
 
void UpdateTwoPhaseState (Oid suboid, char new_state)
 

Variables

static bool table_states_valid = false
 
static Listtable_states_not_ready = NIL
 
static StringInfo copybuf = NULL
 

Function Documentation

◆ AllTablesyncsReady()

bool AllTablesyncsReady ( void  )

Definition at line 1515 of file tablesync.c.

1516 {
1517  bool started_tx = false;
1518  bool has_subrels = false;
1519 
1520  /* We need up-to-date sync state info for subscription tables here. */
1521  has_subrels = FetchTableStates(&started_tx);
1522 
1523  if (started_tx)
1524  {
1526  pgstat_report_stat(true);
1527  }
1528 
1529  /*
1530  * Return false when there are no tables in subscription or not all tables
1531  * are in ready state; true otherwise.
1532  */
1533  return has_subrels && list_length(table_states_not_ready) == 0;
1534 }
static int list_length(const List *l)
Definition: pg_list.h:149
long pgstat_report_stat(bool force)
Definition: pgstat.c:564
static List * table_states_not_ready
Definition: tablesync.c:124
static bool FetchTableStates(bool *started_tx)
Definition: tablesync.c:1454
void CommitTransactionCommand(void)
Definition: xact.c:3022

References CommitTransactionCommand(), FetchTableStates(), list_length(), pgstat_report_stat(), and table_states_not_ready.

Referenced by ApplyWorkerMain(), and process_syncing_tables_for_apply().

◆ copy_read_data()

static int copy_read_data ( void *  outbuf,
int  minread,
int  maxread 
)
static

Definition at line 622 of file tablesync.c.

623 {
624  int bytesread = 0;
625  int avail;
626 
627  /* If there are some leftover data from previous read, use it. */
628  avail = copybuf->len - copybuf->cursor;
629  if (avail)
630  {
631  if (avail > maxread)
632  avail = maxread;
633  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
634  copybuf->cursor += avail;
635  maxread -= avail;
636  bytesread += avail;
637  }
638 
639  while (maxread > 0 && bytesread < minread)
640  {
642  int len;
643  char *buf = NULL;
644 
645  for (;;)
646  {
647  /* Try read the data. */
649 
651 
652  if (len == 0)
653  break;
654  else if (len < 0)
655  return bytesread;
656  else
657  {
658  /* Process the data */
659  copybuf->data = buf;
660  copybuf->len = len;
661  copybuf->cursor = 0;
662 
663  avail = copybuf->len - copybuf->cursor;
664  if (avail > maxread)
665  avail = maxread;
666  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
667  outbuf = (void *) ((char *) outbuf + avail);
668  copybuf->cursor += avail;
669  maxread -= avail;
670  bytesread += avail;
671  }
672 
673  if (maxread <= 0 || bytesread >= minread)
674  return bytesread;
675  }
676 
677  /*
678  * Wait for more data or latch.
679  */
680  (void) WaitLatchOrSocket(MyLatch,
684 
686  }
687 
688  return bytesread;
689 }
WalReceiverConn * LogRepWorkerWalRcvConn
Definition: worker.c:251
struct Latch * MyLatch
Definition: globals.c:58
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:499
void ResetLatch(Latch *latch)
Definition: latch.c:658
#define WL_SOCKET_READABLE
Definition: latch.h:126
#define WL_TIMEOUT
Definition: latch.h:128
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
const void size_t len
static char * buf
Definition: pg_test_fsync.c:67
int pgsocket
Definition: port.h:29
#define PGINVALID_SOCKET
Definition: port.h:31
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static StringInfo copybuf
Definition: tablesync.c:127
@ WAIT_EVENT_LOGICAL_SYNC_DATA
Definition: wait_event.h:108
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:422

References buf, CHECK_FOR_INTERRUPTS, copybuf, StringInfoData::cursor, StringInfoData::data, fd(), StringInfoData::len, len, LogRepWorkerWalRcvConn, MyLatch, PGINVALID_SOCKET, ResetLatch(), WAIT_EVENT_LOGICAL_SYNC_DATA, WaitLatchOrSocket(), walrcv_receive, WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_SOCKET_READABLE, and WL_TIMEOUT.

Referenced by copy_table().

◆ copy_table()

static void copy_table ( Relation  rel)
static

Definition at line 1021 of file tablesync.c.

1022 {
1023  LogicalRepRelMapEntry *relmapentry;
1024  LogicalRepRelation lrel;
1025  List *qual = NIL;
1027  StringInfoData cmd;
1028  CopyFromState cstate;
1029  List *attnamelist;
1030  ParseState *pstate;
1031 
1032  /* Get the publisher relation info. */
1034  RelationGetRelationName(rel), &lrel, &qual);
1035 
1036  /* Put the relation into relmap. */
1037  logicalrep_relmap_update(&lrel);
1038 
1039  /* Map the publisher relation to local one. */
1040  relmapentry = logicalrep_rel_open(lrel.remoteid, NoLock);
1041  Assert(rel == relmapentry->localrel);
1042 
1043  /* Start copy on the publisher. */
1044  initStringInfo(&cmd);
1045 
1046  /* Regular table with no row filter */
1047  if (lrel.relkind == RELKIND_RELATION && qual == NIL)
1048  {
1049  appendStringInfo(&cmd, "COPY %s (",
1051 
1052  /*
1053  * XXX Do we need to list the columns in all cases? Maybe we're
1054  * replicating all columns?
1055  */
1056  for (int i = 0; i < lrel.natts; i++)
1057  {
1058  if (i > 0)
1059  appendStringInfoString(&cmd, ", ");
1060 
1062  }
1063 
1064  appendStringInfo(&cmd, ") TO STDOUT");
1065  }
1066  else
1067  {
1068  /*
1069  * For non-tables and tables with row filters, we need to do COPY
1070  * (SELECT ...), but we can't just do SELECT * because we need to not
1071  * copy generated columns. For tables with any row filters, build a
1072  * SELECT query with OR'ed row filters for COPY.
1073  */
1074  appendStringInfoString(&cmd, "COPY (SELECT ");
1075  for (int i = 0; i < lrel.natts; i++)
1076  {
1078  if (i < lrel.natts - 1)
1079  appendStringInfoString(&cmd, ", ");
1080  }
1081 
1082  appendStringInfoString(&cmd, " FROM ");
1083 
1084  /*
1085  * For regular tables, make sure we don't copy data from a child that
1086  * inherits the named table as those will be copied separately.
1087  */
1088  if (lrel.relkind == RELKIND_RELATION)
1089  appendStringInfoString(&cmd, "ONLY ");
1090 
1092  /* list of OR'ed filters */
1093  if (qual != NIL)
1094  {
1095  ListCell *lc;
1096  char *q = strVal(linitial(qual));
1097 
1098  appendStringInfo(&cmd, " WHERE %s", q);
1099  for_each_from(lc, qual, 1)
1100  {
1101  q = strVal(lfirst(lc));
1102  appendStringInfo(&cmd, " OR %s", q);
1103  }
1104  list_free_deep(qual);
1105  }
1106 
1107  appendStringInfoString(&cmd, ") TO STDOUT");
1108  }
1109  res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data, 0, NULL);
1110  pfree(cmd.data);
1111  if (res->status != WALRCV_OK_COPY_OUT)
1112  ereport(ERROR,
1113  (errcode(ERRCODE_CONNECTION_FAILURE),
1114  errmsg("could not start initial contents copy for table \"%s.%s\": %s",
1115  lrel.nspname, lrel.relname, res->err)));
1117 
1118  copybuf = makeStringInfo();
1119 
1120  pstate = make_parsestate(NULL);
1121  (void) addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1122  NULL, false, false);
1123 
1124  attnamelist = make_copy_attnamelist(relmapentry);
1125  cstate = BeginCopyFrom(pstate, rel, NULL, NULL, false, copy_read_data, attnamelist, NIL);
1126 
1127  /* Do the copy */
1128  (void) CopyFrom(cstate);
1129 
1130  logicalrep_rel_close(relmapentry, NoLock);
1131 }
CopyFromState BeginCopyFrom(ParseState *pstate, Relation rel, Node *whereClause, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copyfrom.c:1189
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:528
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
void list_free_deep(List *list)
Definition: list.c:1519
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
void pfree(void *pointer)
Definition: mcxt.c:1175
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
#define lfirst(lc)
Definition: pg_list.h:169
#define NIL
Definition: pg_list.h:65
#define for_each_from(cell, lst, N)
Definition: pg_list.h:393
#define linitial(l)
Definition: pg_list.h:174
#define RelationGetRelationName(relation)
Definition: rel.h:523
#define RelationGetNamespace(relation)
Definition: rel.h:530
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12192
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:12276
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:157
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:258
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:433
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Definition: pg_list.h:51
LogicalRepRelId remoteid
Definition: logicalproto.h:102
static int copy_read_data(void *outbuf, int minread, int maxread)
Definition: tablesync.c:622
static void fetch_remote_table_info(char *nspname, char *relname, LogicalRepRelation *lrel, List **qual)
Definition: tablesync.c:698
static List * make_copy_attnamelist(LogicalRepRelMapEntry *rel)
Definition: tablesync.c:602
#define strVal(v)
Definition: value.h:72
@ WALRCV_OK_COPY_OUT
Definition: walreceiver.h:205
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:436
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:430

References AccessShareLock, addRangeTableEntryForRelation(), appendStringInfo(), appendStringInfoString(), Assert(), LogicalRepRelation::attnames, BeginCopyFrom(), copy_read_data(), copybuf, CopyFrom(), StringInfoData::data, ereport, errcode(), errmsg(), ERROR, fetch_remote_table_info(), for_each_from, get_namespace_name(), i, initStringInfo(), lfirst, linitial, list_free_deep(), LogicalRepRelMapEntry::localrel, logicalrep_rel_close(), logicalrep_rel_open(), logicalrep_relmap_update(), LogRepWorkerWalRcvConn, make_copy_attnamelist(), make_parsestate(), makeStringInfo(), LogicalRepRelation::natts, NIL, NoLock, LogicalRepRelation::nspname, pfree(), quote_identifier(), quote_qualified_identifier(), RelationGetNamespace, RelationGetRelationName, LogicalRepRelation::relkind, LogicalRepRelation::relname, LogicalRepRelation::remoteid, res, strVal, walrcv_clear_result(), walrcv_exec, and WALRCV_OK_COPY_OUT.

Referenced by LogicalRepSyncTableStart().

◆ fetch_remote_table_info()

static void fetch_remote_table_info ( char *  nspname,
char *  relname,
LogicalRepRelation lrel,
List **  qual 
)
static

Definition at line 698 of file tablesync.c.

700 {
702  StringInfoData cmd;
703  TupleTableSlot *slot;
704  Oid tableRow[] = {OIDOID, CHAROID, CHAROID};
705  Oid attrRow[] = {INT2OID, TEXTOID, OIDOID, BOOLOID};
706  Oid qualRow[] = {TEXTOID};
707  bool isnull;
708  int natt;
709  ListCell *lc;
710  bool first;
711  Bitmapset *included_cols = NULL;
712 
713  lrel->nspname = nspname;
714  lrel->relname = relname;
715 
716  /* First fetch Oid and replica identity. */
717  initStringInfo(&cmd);
718  appendStringInfo(&cmd, "SELECT c.oid, c.relreplident, c.relkind"
719  " FROM pg_catalog.pg_class c"
720  " INNER JOIN pg_catalog.pg_namespace n"
721  " ON (c.relnamespace = n.oid)"
722  " WHERE n.nspname = %s"
723  " AND c.relname = %s",
724  quote_literal_cstr(nspname),
727  lengthof(tableRow), tableRow);
728 
729  if (res->status != WALRCV_OK_TUPLES)
730  ereport(ERROR,
731  (errcode(ERRCODE_CONNECTION_FAILURE),
732  errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
733  nspname, relname, res->err)));
734 
735  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
736  if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
737  ereport(ERROR,
738  (errcode(ERRCODE_UNDEFINED_OBJECT),
739  errmsg("table \"%s.%s\" not found on publisher",
740  nspname, relname)));
741 
742  lrel->remoteid = DatumGetObjectId(slot_getattr(slot, 1, &isnull));
743  Assert(!isnull);
744  lrel->replident = DatumGetChar(slot_getattr(slot, 2, &isnull));
745  Assert(!isnull);
746  lrel->relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
747  Assert(!isnull);
748 
751 
752 
753  /*
754  * Get column lists for each relation.
755  *
756  * For initial synchronization, column lists can be ignored in following
757  * cases:
758  *
759  * 1) one of the subscribed publications for the table hasn't specified
760  * any column list
761  *
762  * 2) one of the subscribed publications has puballtables set to true
763  *
764  * 3) one of the subscribed publications is declared as ALL TABLES IN
765  * SCHEMA that includes this relation
766  *
767  * We need to do this before fetching info about column names and types,
768  * so that we can skip columns that should not be replicated.
769  */
771  {
772  WalRcvExecResult *pubres;
773  TupleTableSlot *slot;
774  Oid attrsRow[] = {INT2OID};
775  StringInfoData pub_names;
776  bool first = true;
777 
778  initStringInfo(&pub_names);
779  foreach(lc, MySubscription->publications)
780  {
781  if (!first)
782  appendStringInfo(&pub_names, ", ");
784  first = false;
785  }
786 
787  /*
788  * Fetch info about column lists for the relation (from all the
789  * publications). We unnest the int2vector values, because that makes
790  * it easier to combine lists by simply adding the attnums to a new
791  * bitmap (without having to parse the int2vector data). This
792  * preserves NULL values, so that if one of the publications has no
793  * column list, we'll know that.
794  */
795  resetStringInfo(&cmd);
796  appendStringInfo(&cmd,
797  "SELECT DISTINCT unnest"
798  " FROM pg_publication p,"
799  " LATERAL pg_get_publication_tables(p.pubname) gpt"
800  " LEFT OUTER JOIN unnest(gpt.attrs) ON TRUE"
801  " WHERE gpt.relid = %u"
802  " AND p.pubname IN ( %s )",
803  lrel->remoteid,
804  pub_names.data);
805 
807  lengthof(attrsRow), attrsRow);
808 
809  if (pubres->status != WALRCV_OK_TUPLES)
810  ereport(ERROR,
811  (errcode(ERRCODE_CONNECTION_FAILURE),
812  errmsg("could not fetch column list info for table \"%s.%s\" from publisher: %s",
813  nspname, relname, pubres->err)));
814 
815  /*
816  * Merge the column lists (from different publications) by creating a
817  * single bitmap with all the attnums. If we find a NULL value, that
818  * means one of the publications has no column list for the table
819  * we're syncing.
820  */
822  while (tuplestore_gettupleslot(pubres->tuplestore, true, false, slot))
823  {
824  Datum cfval = slot_getattr(slot, 1, &isnull);
825 
826  /* NULL means empty column list, so we're done. */
827  if (isnull)
828  {
829  bms_free(included_cols);
830  included_cols = NULL;
831  break;
832  }
833 
834  included_cols = bms_add_member(included_cols,
835  DatumGetInt16(cfval));
836 
837  ExecClearTuple(slot);
838  }
840 
841  walrcv_clear_result(pubres);
842 
843  pfree(pub_names.data);
844  }
845 
846  /*
847  * Now fetch column names and types.
848  */
849  resetStringInfo(&cmd);
850  appendStringInfo(&cmd,
851  "SELECT a.attnum,"
852  " a.attname,"
853  " a.atttypid,"
854  " a.attnum = ANY(i.indkey)"
855  " FROM pg_catalog.pg_attribute a"
856  " LEFT JOIN pg_catalog.pg_index i"
857  " ON (i.indexrelid = pg_get_replica_identity_index(%u))"
858  " WHERE a.attnum > 0::pg_catalog.int2"
859  " AND NOT a.attisdropped %s"
860  " AND a.attrelid = %u"
861  " ORDER BY a.attnum",
862  lrel->remoteid,
864  "AND a.attgenerated = ''" : ""),
865  lrel->remoteid);
867  lengthof(attrRow), attrRow);
868 
869  if (res->status != WALRCV_OK_TUPLES)
870  ereport(ERROR,
871  (errcode(ERRCODE_CONNECTION_FAILURE),
872  errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
873  nspname, relname, res->err)));
874 
875  /* We don't know the number of rows coming, so allocate enough space. */
876  lrel->attnames = palloc0(MaxTupleAttributeNumber * sizeof(char *));
877  lrel->atttyps = palloc0(MaxTupleAttributeNumber * sizeof(Oid));
878  lrel->attkeys = NULL;
879 
880  /*
881  * Store the columns as a list of names. Ignore those that are not
882  * present in the column list, if there is one.
883  */
884  natt = 0;
885  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
886  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
887  {
888  char *rel_colname;
890 
891  attnum = DatumGetInt16(slot_getattr(slot, 1, &isnull));
892  Assert(!isnull);
893 
894  /* If the column is not in the column list, skip it. */
895  if (included_cols != NULL && !bms_is_member(attnum, included_cols))
896  {
897  ExecClearTuple(slot);
898  continue;
899  }
900 
901  rel_colname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
902  Assert(!isnull);
903 
904  lrel->attnames[natt] = rel_colname;
905  lrel->atttyps[natt] = DatumGetObjectId(slot_getattr(slot, 3, &isnull));
906  Assert(!isnull);
907 
908  if (DatumGetBool(slot_getattr(slot, 4, &isnull)))
909  lrel->attkeys = bms_add_member(lrel->attkeys, natt);
910 
911  /* Should never happen. */
912  if (++natt >= MaxTupleAttributeNumber)
913  elog(ERROR, "too many columns in remote table \"%s.%s\"",
914  nspname, relname);
915 
916  ExecClearTuple(slot);
917  }
919 
920  lrel->natts = natt;
921 
923 
924  /*
925  * Get relation's row filter expressions. DISTINCT avoids the same
926  * expression of a table in multiple publications from being included
927  * multiple times in the final expression.
928  *
929  * We need to copy the row even if it matches just one of the
930  * publications, so we later combine all the quals with OR.
931  *
932  * For initial synchronization, row filtering can be ignored in following
933  * cases:
934  *
935  * 1) one of the subscribed publications for the table hasn't specified
936  * any row filter
937  *
938  * 2) one of the subscribed publications has puballtables set to true
939  *
940  * 3) one of the subscribed publications is declared as ALL TABLES IN
941  * SCHEMA that includes this relation
942  */
944  {
945  StringInfoData pub_names;
946 
947  /* Build the pubname list. */
948  initStringInfo(&pub_names);
949  first = true;
950  foreach(lc, MySubscription->publications)
951  {
952  char *pubname = strVal(lfirst(lc));
953 
954  if (first)
955  first = false;
956  else
957  appendStringInfoString(&pub_names, ", ");
958 
959  appendStringInfoString(&pub_names, quote_literal_cstr(pubname));
960  }
961 
962  /* Check for row filters. */
963  resetStringInfo(&cmd);
964  appendStringInfo(&cmd,
965  "SELECT DISTINCT pg_get_expr(gpt.qual, gpt.relid)"
966  " FROM pg_publication p,"
967  " LATERAL pg_get_publication_tables(p.pubname) gpt"
968  " WHERE gpt.relid = %u"
969  " AND p.pubname IN ( %s )",
970  lrel->remoteid,
971  pub_names.data);
972 
973  res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data, 1, qualRow);
974 
975  if (res->status != WALRCV_OK_TUPLES)
976  ereport(ERROR,
977  (errmsg("could not fetch table WHERE clause info for table \"%s.%s\" from publisher: %s",
978  nspname, relname, res->err)));
979 
980  /*
981  * Multiple row filter expressions for the same table will be combined
982  * by COPY using OR. If any of the filter expressions for this table
983  * are null, it means the whole table will be copied. In this case it
984  * is not necessary to construct a unified row filter expression at
985  * all.
986  */
987  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
988  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
989  {
990  Datum rf = slot_getattr(slot, 1, &isnull);
991 
992  if (!isnull)
993  *qual = lappend(*qual, makeString(TextDatumGetCString(rf)));
994  else
995  {
996  /* Ignore filters and cleanup as necessary. */
997  if (*qual)
998  {
999  list_free_deep(*qual);
1000  *qual = NIL;
1001  }
1002  break;
1003  }
1004 
1005  ExecClearTuple(slot);
1006  }
1008 
1010  }
1011 
1012  pfree(cmd.data);
1013 }
int16 AttrNumber
Definition: attnum.h:21
Subscription * MySubscription
Definition: worker.c:253
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define lengthof(array)
Definition: c.h:734
#define elog(elevel,...)
Definition: elog.h:218
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
#define MaxTupleAttributeNumber
Definition: htup_details.h:33
List * lappend(List *list, void *datum)
Definition: list.c:336
void * palloc0(Size size)
Definition: mcxt.c:1099
int16 attnum
Definition: pg_attribute.h:83
NameData relname
Definition: pg_class.h:38
#define DatumGetObjectId(X)
Definition: postgres.h:544
uintptr_t Datum
Definition: postgres.h:411
#define DatumGetBool(X)
Definition: postgres.h:437
#define DatumGetChar(X)
Definition: postgres.h:453
#define DatumGetInt16(X)
Definition: postgres.h:488
unsigned int Oid
Definition: postgres_ext.h:31
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
Bitmapset * attkeys
Definition: logicalproto.h:110
Tuplestorestate * tuplestore
Definition: walreceiver.h:219
TupleDesc tupledesc
Definition: walreceiver.h:220
WalRcvExecStatus status
Definition: walreceiver.h:216
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
String * makeString(char *str)
Definition: value.c:63
@ WALRCV_OK_TUPLES
Definition: walreceiver.h:203
#define walrcv_server_version(conn)
Definition: walreceiver.h:414

References appendStringInfo(), appendStringInfoString(), Assert(), LogicalRepRelation::attkeys, LogicalRepRelation::attnames, attnum, LogicalRepRelation::atttyps, bms_add_member(), bms_free(), bms_is_member(), StringInfoData::data, DatumGetBool, DatumGetChar, DatumGetInt16, DatumGetObjectId, elog, ereport, WalRcvExecResult::err, errcode(), errmsg(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), initStringInfo(), lappend(), lengthof, lfirst, list_free_deep(), LogRepWorkerWalRcvConn, MakeSingleTupleTableSlot(), makeString(), MaxTupleAttributeNumber, MySubscription, LogicalRepRelation::natts, NIL, LogicalRepRelation::nspname, palloc0(), pfree(), Subscription::publications, quote_literal_cstr(), LogicalRepRelation::relkind, relname, LogicalRepRelation::relname, LogicalRepRelation::remoteid, LogicalRepRelation::replident, res, resetStringInfo(), slot_getattr(), WalRcvExecResult::status, strVal, TextDatumGetCString, TTSOpsMinimalTuple, WalRcvExecResult::tupledesc, WalRcvExecResult::tuplestore, tuplestore_gettupleslot(), walrcv_clear_result(), walrcv_exec, WALRCV_OK_TUPLES, and walrcv_server_version.

Referenced by copy_table().

◆ FetchTableStates()

static bool FetchTableStates ( bool started_tx)
static

Definition at line 1454 of file tablesync.c.

1455 {
1456  static bool has_subrels = false;
1457 
1458  *started_tx = false;
1459 
1460  if (!table_states_valid)
1461  {
1462  MemoryContext oldctx;
1463  List *rstates;
1464  ListCell *lc;
1465  SubscriptionRelState *rstate;
1466 
1467  /* Clean the old lists. */
1470 
1471  if (!IsTransactionState())
1472  {
1474  *started_tx = true;
1475  }
1476 
1477  /* Fetch all non-ready tables. */
1479 
1480  /* Allocate the tracking info in a permanent memory context. */
1482  foreach(lc, rstates)
1483  {
1484  rstate = palloc(sizeof(SubscriptionRelState));
1485  memcpy(rstate, lfirst(lc), sizeof(SubscriptionRelState));
1487  }
1488  MemoryContextSwitchTo(oldctx);
1489 
1490  /*
1491  * Does the subscription have tables?
1492  *
1493  * If there were not-READY relations found then we know it does. But
1494  * if table_state_not_ready was empty we still need to check again to
1495  * see if there are 0 tables.
1496  */
1497  has_subrels = (list_length(table_states_not_ready) > 0) ||
1499 
1500  table_states_valid = true;
1501  }
1502 
1503  return has_subrels;
1504 }
MemoryContext CacheMemoryContext
Definition: mcxt.c:51
void * palloc(Size size)
Definition: mcxt.c:1068
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * GetSubscriptionNotReadyRelations(Oid subid)
bool HasSubscriptionRelations(Oid subid)
static bool table_states_valid
Definition: tablesync.c:123
bool IsTransactionState(void)
Definition: xact.c:374
void StartTransactionCommand(void)
Definition: xact.c:2925

References CacheMemoryContext, GetSubscriptionNotReadyRelations(), HasSubscriptionRelations(), IsTransactionState(), lappend(), lfirst, list_free_deep(), list_length(), MemoryContextSwitchTo(), MySubscription, NIL, Subscription::oid, palloc(), StartTransactionCommand(), table_states_not_ready, and table_states_valid.

Referenced by AllTablesyncsReady(), and process_syncing_tables_for_apply().

◆ invalidate_syncing_table_states()

void invalidate_syncing_table_states ( Datum  arg,
int  cacheid,
uint32  hashvalue 
)

Definition at line 271 of file tablesync.c.

272 {
273  table_states_valid = false;
274 }

References table_states_valid.

Referenced by ApplyWorkerMain().

◆ LogicalRepSyncTableStart()

char* LogicalRepSyncTableStart ( XLogRecPtr origin_startpos)

Definition at line 1179 of file tablesync.c.

1180 {
1181  char *slotname;
1182  char *err;
1183  char relstate;
1184  XLogRecPtr relstate_lsn;
1185  Relation rel;
1186  AclResult aclresult;
1188  char originname[NAMEDATALEN];
1189  RepOriginId originid;
1190 
1191  /* Check the state of the table synchronization. */
1195  &relstate_lsn);
1197 
1199  MyLogicalRepWorker->relstate = relstate;
1200  MyLogicalRepWorker->relstate_lsn = relstate_lsn;
1202 
1203  /*
1204  * If synchronization is already done or no longer necessary, exit now
1205  * that we've updated shared memory state.
1206  */
1207  switch (relstate)
1208  {
1209  case SUBREL_STATE_SYNCDONE:
1210  case SUBREL_STATE_READY:
1211  case SUBREL_STATE_UNKNOWN:
1212  finish_sync_worker(); /* doesn't return */
1213  }
1214 
1215  /* Calculate the name of the tablesync slot. */
1216  slotname = (char *) palloc(NAMEDATALEN);
1219  slotname,
1220  NAMEDATALEN);
1221 
1222  /*
1223  * Here we use the slot name instead of the subscription name as the
1224  * application_name, so that it is different from the main apply worker,
1225  * so that synchronous replication can distinguish them.
1226  */
1228  walrcv_connect(MySubscription->conninfo, true, slotname, &err);
1229  if (LogRepWorkerWalRcvConn == NULL)
1230  ereport(ERROR,
1231  (errcode(ERRCODE_CONNECTION_FAILURE),
1232  errmsg("could not connect to the publisher: %s", err)));
1233 
1234  Assert(MyLogicalRepWorker->relstate == SUBREL_STATE_INIT ||
1235  MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC ||
1236  MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY);
1237 
1238  /* Assign the origin tracking record name. */
1241  originname,
1242  sizeof(originname));
1243 
1244  if (MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC)
1245  {
1246  /*
1247  * We have previously errored out before finishing the copy so the
1248  * replication slot might exist. We want to remove the slot if it
1249  * already exists and proceed.
1250  *
1251  * XXX We could also instead try to drop the slot, last time we failed
1252  * but for that, we might need to clean up the copy state as it might
1253  * be in the middle of fetching the rows. Also, if there is a network
1254  * breakdown then it wouldn't have succeeded so trying it next time
1255  * seems like a better bet.
1256  */
1258  }
1259  else if (MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY)
1260  {
1261  /*
1262  * The COPY phase was previously done, but tablesync then crashed
1263  * before it was able to finish normally.
1264  */
1266 
1267  /*
1268  * The origin tracking name must already exist. It was created first
1269  * time this tablesync was launched.
1270  */
1271  originid = replorigin_by_name(originname, false);
1272  replorigin_session_setup(originid);
1273  replorigin_session_origin = originid;
1274  *origin_startpos = replorigin_session_get_progress(false);
1275 
1277 
1278  goto copy_table_done;
1279  }
1280 
1282  MyLogicalRepWorker->relstate = SUBREL_STATE_DATASYNC;
1285 
1286  /* Update the state and make it visible to others. */
1293  pgstat_report_stat(true);
1294 
1296 
1297  /*
1298  * Use a standard write lock here. It might be better to disallow access
1299  * to the table while it's being synchronized. But we don't want to block
1300  * the main apply process from working and it has to open the relation in
1301  * RowExclusiveLock when remapping remote relation id to local one.
1302  */
1304 
1305  /*
1306  * Check that our table sync worker has permission to insert into the
1307  * target table.
1308  */
1309  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1310  ACL_INSERT);
1311  if (aclresult != ACLCHECK_OK)
1312  aclcheck_error(aclresult,
1313  get_relkind_objtype(rel->rd_rel->relkind),
1315 
1316  /*
1317  * COPY FROM does not honor RLS policies. That is not a problem for
1318  * subscriptions owned by roles with BYPASSRLS privilege (or superuser,
1319  * who has it implicitly), but other roles should not be able to
1320  * circumvent RLS. Disallow logical replication into RLS enabled
1321  * relations for such roles.
1322  */
1324  ereport(ERROR,
1325  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1326  errmsg("\"%s\" cannot replicate into relation with row-level security enabled: \"%s\"",
1327  GetUserNameFromId(GetUserId(), true),
1328  RelationGetRelationName(rel))));
1329 
1330  /*
1331  * Start a transaction in the remote node in REPEATABLE READ mode. This
1332  * ensures that both the replication slot we create (see below) and the
1333  * COPY are consistent with each other.
1334  */
1336  "BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ",
1337  0, NULL);
1338  if (res->status != WALRCV_OK_COMMAND)
1339  ereport(ERROR,
1340  (errcode(ERRCODE_CONNECTION_FAILURE),
1341  errmsg("table copy could not start transaction on publisher: %s",
1342  res->err)));
1344 
1345  /*
1346  * Create a new permanent logical decoding slot. This slot will be used
1347  * for the catchup phase after COPY is done, so tell it to use the
1348  * snapshot to make the final data consistent.
1349  *
1350  * Prevent cancel/die interrupts while creating slot here because it is
1351  * possible that before the server finishes this command, a concurrent
1352  * drop subscription happens which would complete without removing this
1353  * slot leading to a dangling slot on the server.
1354  */
1355  HOLD_INTERRUPTS();
1357  slotname, false /* permanent */ , false /* two_phase */ ,
1358  CRS_USE_SNAPSHOT, origin_startpos);
1360 
1361  /*
1362  * Setup replication origin tracking. The purpose of doing this before the
1363  * copy is to avoid doing the copy again due to any error in setting up
1364  * origin tracking.
1365  */
1366  originid = replorigin_by_name(originname, true);
1367  if (!OidIsValid(originid))
1368  {
1369  /*
1370  * Origin tracking does not exist, so create it now.
1371  *
1372  * Then advance to the LSN got from walrcv_create_slot. This is WAL
1373  * logged for the purpose of recovery. Locks are to prevent the
1374  * replication origin from vanishing while advancing.
1375  */
1376  originid = replorigin_create(originname);
1377 
1378  LockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1379  replorigin_advance(originid, *origin_startpos, InvalidXLogRecPtr,
1380  true /* go backward */ , true /* WAL log */ );
1381  UnlockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1382 
1383  replorigin_session_setup(originid);
1384  replorigin_session_origin = originid;
1385  }
1386  else
1387  {
1388  ereport(ERROR,
1390  errmsg("replication origin \"%s\" already exists",
1391  originname)));
1392  }
1393 
1394  /* Now do the initial data copy */
1396  copy_table(rel);
1398 
1399  res = walrcv_exec(LogRepWorkerWalRcvConn, "COMMIT", 0, NULL);
1400  if (res->status != WALRCV_OK_COMMAND)
1401  ereport(ERROR,
1402  (errcode(ERRCODE_CONNECTION_FAILURE),
1403  errmsg("table copy could not finish transaction on publisher: %s",
1404  res->err)));
1406 
1407  table_close(rel, NoLock);
1408 
1409  /* Make the copy visible. */
1411 
1412  /*
1413  * Update the persisted state to indicate the COPY phase is done; make it
1414  * visible to others.
1415  */
1418  SUBREL_STATE_FINISHEDCOPY,
1420 
1422 
1423 copy_table_done:
1424 
1425  elog(DEBUG1,
1426  "LogicalRepSyncTableStart: '%s' origin_startpos lsn %X/%X",
1427  originname, LSN_FORMAT_ARGS(*origin_startpos));
1428 
1429  /*
1430  * We are done with the initial data synchronization, update the state.
1431  */
1433  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCWAIT;
1434  MyLogicalRepWorker->relstate_lsn = *origin_startpos;
1436 
1437  /*
1438  * Finally, wait until the main apply worker tells us to catch up and then
1439  * return to let LogicalRepApplyLoop do it.
1440  */
1441  wait_for_worker_state_change(SUBREL_STATE_CATCHUP);
1442  return slotname;
1443 }
AclResult
Definition: acl.h:181
@ ACLCHECK_OK
Definition: acl.h:182
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3512
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:5007
#define OidIsValid(objectId)
Definition: c.h:710
#define DEBUG1
Definition: elog.h:24
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:58
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:228
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:134
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
char * GetUserNameFromId(Oid roleid, bool noerr)
Definition: miscinit.c:913
Oid GetUserId(void)
Definition: miscinit.c:492
ObjectType get_relkind_objtype(char relkind)
RepOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition: origin.c:209
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:240
void replorigin_session_setup(RepOriginId node)
Definition: origin.c:1071
RepOriginId replorigin_session_origin
Definition: origin.c:155
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:872
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1206
#define ACL_INSERT
Definition: parsenodes.h:82
#define NAMEDATALEN
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define InvalidOid
Definition: postgres_ext.h:36
#define RelationGetRelid(relation)
Definition: rel.h:489
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
@ RLS_ENABLED
Definition: rls.h:45
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void PopActiveSnapshot(void)
Definition: snapmgr.c:776
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:682
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
XLogRecPtr relstate_lsn
Form_pg_class rd_rel
Definition: rel.h:109
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static bool wait_for_worker_state_change(char expected_state)
Definition: tablesync.c:222
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:1164
static void copy_table(Relation rel)
Definition: tablesync.c:1021
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:1151
#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
Definition: walreceiver.h:426
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:404
@ WALRCV_OK_COMMAND
Definition: walreceiver.h:201
@ CRS_USE_SNAPSHOT
Definition: walsender.h:24
void CommandCounterIncrement(void)
Definition: xact.c:1074
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
uint16 RepOriginId
Definition: xlogdefs.h:65
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References ACL_INSERT, aclcheck_error(), ACLCHECK_OK, Assert(), check_enable_rls(), CommandCounterIncrement(), CommitTransactionCommand(), Subscription::conninfo, copy_table(), CRS_USE_SNAPSHOT, DEBUG1, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, get_relkind_objtype(), GetSubscriptionRelState(), GetTransactionSnapshot(), GetUserId(), GetUserNameFromId(), HOLD_INTERRUPTS, InvalidOid, InvalidXLogRecPtr, LockRelationOid(), LogRepWorkerWalRcvConn, LSN_FORMAT_ARGS, MyLogicalRepWorker, MySubscription, NAMEDATALEN, NoLock, Subscription::oid, OidIsValid, palloc(), pg_class_aclcheck(), pgstat_report_stat(), PopActiveSnapshot(), PushActiveSnapshot(), RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, LogicalRepWorker::relid, LogicalRepWorker::relmutex, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, ReplicationOriginNameForTablesync(), ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), replorigin_advance(), replorigin_by_name(), replorigin_create(), replorigin_session_get_progress(), replorigin_session_origin, replorigin_session_setup(), res, RESUME_INTERRUPTS, RLS_ENABLED, RowExclusiveLock, SpinLockAcquire, SpinLockRelease, StartTransactionCommand(), LogicalRepWorker::subid, table_close(), table_open(), UnlockRelationOid(), UpdateSubscriptionRelState(), wait_for_worker_state_change(), walrcv_clear_result(), walrcv_connect, walrcv_create_slot, walrcv_exec, and WALRCV_OK_COMMAND.

Referenced by start_table_sync().

◆ make_copy_attnamelist()

static List* make_copy_attnamelist ( LogicalRepRelMapEntry rel)
static

Definition at line 602 of file tablesync.c.

603 {
604  List *attnamelist = NIL;
605  int i;
606 
607  for (i = 0; i < rel->remoterel.natts; i++)
608  {
609  attnamelist = lappend(attnamelist,
610  makeString(rel->remoterel.attnames[i]));
611  }
612 
613 
614  return attnamelist;
615 }
LogicalRepRelation remoterel

References LogicalRepRelation::attnames, i, lappend(), makeString(), LogicalRepRelation::natts, NIL, and LogicalRepRelMapEntry::remoterel.

Referenced by copy_table().

◆ pg_attribute_noreturn()

static void pg_attribute_noreturn ( )
static

Definition at line 133 of file tablesync.c.

135 {
136  /*
137  * Commit any outstanding transaction. This is the usual case, unless
138  * there was nothing to do for the table.
139  */
140  if (IsTransactionState())
141  {
143  pgstat_report_stat(true);
144  }
145 
146  /* And flush all writes. */
148 
150  ereport(LOG,
151  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has finished",
155 
156  /* Find the main apply worker and signal it. */
158 
159  /* Stop gracefully */
160  proc_exit(0);
161 }
#define LOG
Definition: elog.h:25
void proc_exit(int code)
Definition: ipc.c:104
void logicalrep_worker_wakeup(Oid subid, Oid relid)
Definition: launcher.c:533
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1909
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:8819
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2509

References CommitTransactionCommand(), ereport, errmsg(), get_rel_name(), GetXLogWriteRecPtr(), InvalidOid, IsTransactionState(), LOG, logicalrep_worker_wakeup(), MyLogicalRepWorker, MySubscription, Subscription::name, pgstat_report_stat(), proc_exit(), LogicalRepWorker::relid, StartTransactionCommand(), LogicalRepWorker::subid, and XLogFlush().

◆ process_syncing_tables()

void process_syncing_tables ( XLogRecPtr  current_lsn)

Definition at line 590 of file tablesync.c.

591 {
592  if (am_tablesync_worker())
593  process_syncing_tables_for_sync(current_lsn);
594  else
596 }
static void process_syncing_tables_for_apply(XLogRecPtr current_lsn)
Definition: tablesync.c:365
static void process_syncing_tables_for_sync(XLogRecPtr current_lsn)
Definition: tablesync.c:285
static bool am_tablesync_worker(void)

References am_tablesync_worker(), process_syncing_tables_for_apply(), and process_syncing_tables_for_sync().

Referenced by apply_handle_commit(), apply_handle_commit_prepared(), apply_handle_prepare(), apply_handle_rollback_prepared(), apply_handle_stream_commit(), apply_handle_stream_prepare(), and LogicalRepApplyLoop().

◆ process_syncing_tables_for_apply()

static void process_syncing_tables_for_apply ( XLogRecPtr  current_lsn)
static

Definition at line 365 of file tablesync.c.

366 {
367  struct tablesync_start_time_mapping
368  {
369  Oid relid;
370  TimestampTz last_start_time;
371  };
372  static HTAB *last_start_times = NULL;
373  ListCell *lc;
374  bool started_tx = false;
375 
377 
378  /* We need up-to-date sync state info for subscription tables here. */
379  FetchTableStates(&started_tx);
380 
381  /*
382  * Prepare a hash table for tracking last start times of workers, to avoid
383  * immediate restarts. We don't need it if there are no tables that need
384  * syncing.
385  */
386  if (table_states_not_ready && !last_start_times)
387  {
388  HASHCTL ctl;
389 
390  ctl.keysize = sizeof(Oid);
391  ctl.entrysize = sizeof(struct tablesync_start_time_mapping);
392  last_start_times = hash_create("Logical replication table sync worker start times",
393  256, &ctl, HASH_ELEM | HASH_BLOBS);
394  }
395 
396  /*
397  * Clean up the hash table when we're done with all tables (just to
398  * release the bit of memory).
399  */
400  else if (!table_states_not_ready && last_start_times)
401  {
402  hash_destroy(last_start_times);
403  last_start_times = NULL;
404  }
405 
406  /*
407  * Even when the two_phase mode is requested by the user, it remains as
408  * 'pending' until all tablesyncs have reached READY state.
409  *
410  * When this happens, we restart the apply worker and (if the conditions
411  * are still ok) then the two_phase tri-state will become 'enabled' at
412  * that time.
413  *
414  * Note: If the subscription has no tables then leave the state as
415  * PENDING, which allows ALTER SUBSCRIPTION ... REFRESH PUBLICATION to
416  * work.
417  */
420  {
421  ereport(LOG,
422  (errmsg("logical replication apply worker for subscription \"%s\" will restart so that two_phase can be enabled",
423  MySubscription->name)));
424 
425  proc_exit(0);
426  }
427 
428  /*
429  * Process all tables that are being synchronized.
430  */
431  foreach(lc, table_states_not_ready)
432  {
434 
435  if (rstate->state == SUBREL_STATE_SYNCDONE)
436  {
437  /*
438  * Apply has caught up to the position where the table sync has
439  * finished. Mark the table as ready so that the apply will just
440  * continue to replicate it normally.
441  */
442  if (current_lsn >= rstate->lsn)
443  {
444  char originname[NAMEDATALEN];
445 
446  rstate->state = SUBREL_STATE_READY;
447  rstate->lsn = current_lsn;
448  if (!started_tx)
449  {
451  started_tx = true;
452  }
453 
454  /*
455  * Remove the tablesync origin tracking if exists.
456  *
457  * The normal case origin drop is done here instead of in the
458  * process_syncing_tables_for_sync function because we don't
459  * allow to drop the origin till the process owning the origin
460  * is alive.
461  *
462  * There is a chance that the user is concurrently performing
463  * refresh for the subscription where we remove the table
464  * state and its origin and by this time the origin might be
465  * already removed. So passing missing_ok = true.
466  */
468  rstate->relid,
469  originname,
470  sizeof(originname));
471  replorigin_drop_by_name(originname, true, false);
472 
473  /*
474  * Update the state to READY only after the origin cleanup.
475  */
477  rstate->relid, rstate->state,
478  rstate->lsn);
479  }
480  }
481  else
482  {
483  LogicalRepWorker *syncworker;
484 
485  /*
486  * Look for a sync worker for this relation.
487  */
488  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
489 
491  rstate->relid, false);
492 
493  if (syncworker)
494  {
495  /* Found one, update our copy of its state */
496  SpinLockAcquire(&syncworker->relmutex);
497  rstate->state = syncworker->relstate;
498  rstate->lsn = syncworker->relstate_lsn;
499  if (rstate->state == SUBREL_STATE_SYNCWAIT)
500  {
501  /*
502  * Sync worker is waiting for apply. Tell sync worker it
503  * can catchup now.
504  */
505  syncworker->relstate = SUBREL_STATE_CATCHUP;
506  syncworker->relstate_lsn =
507  Max(syncworker->relstate_lsn, current_lsn);
508  }
509  SpinLockRelease(&syncworker->relmutex);
510 
511  /* If we told worker to catch up, wait for it. */
512  if (rstate->state == SUBREL_STATE_SYNCWAIT)
513  {
514  /* Signal the sync worker, as it may be waiting for us. */
515  if (syncworker->proc)
516  logicalrep_worker_wakeup_ptr(syncworker);
517 
518  /* Now safe to release the LWLock */
519  LWLockRelease(LogicalRepWorkerLock);
520 
521  /*
522  * Enter busy loop and wait for synchronization worker to
523  * reach expected state (or die trying).
524  */
525  if (!started_tx)
526  {
528  started_tx = true;
529  }
530 
532  SUBREL_STATE_SYNCDONE);
533  }
534  else
535  LWLockRelease(LogicalRepWorkerLock);
536  }
537  else
538  {
539  /*
540  * If there is no sync worker for this table yet, count
541  * running sync workers for this subscription, while we have
542  * the lock.
543  */
544  int nsyncworkers =
546 
547  /* Now safe to release the LWLock */
548  LWLockRelease(LogicalRepWorkerLock);
549 
550  /*
551  * If there are free sync worker slot(s), start a new sync
552  * worker for the table.
553  */
554  if (nsyncworkers < max_sync_workers_per_subscription)
555  {
557  struct tablesync_start_time_mapping *hentry;
558  bool found;
559 
560  hentry = hash_search(last_start_times, &rstate->relid,
561  HASH_ENTER, &found);
562 
563  if (!found ||
564  TimestampDifferenceExceeds(hentry->last_start_time, now,
566  {
571  rstate->relid);
572  hentry->last_start_time = now;
573  }
574  }
575  }
576  }
577  }
578 
579  if (started_tx)
580  {
582  pgstat_report_stat(true);
583  }
584 }
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1705
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
#define Max(x, y)
Definition: c.h:980
int64 TimestampTz
Definition: timestamp.h:39
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:862
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:214
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:553
void logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
Definition: launcher.c:265
int max_sync_workers_per_subscription
Definition: launcher.c:56
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:663
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1196
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1800
@ LW_SHARED
Definition: lwlock.h:105
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
#define LOGICALREP_TWOPHASE_STATE_PENDING
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
Definition: dynahash.c:220
bool AllTablesyncsReady(void)
Definition: tablesync.c:1515
static bool wait_for_relation_state_change(Oid relid, char expected_state)
Definition: tablesync.c:174
int wal_retrieve_retry_interval
Definition: xlog.c:135

References AllTablesyncsReady(), Assert(), CommitTransactionCommand(), LogicalRepWorker::dbid, HASHCTL::entrysize, ereport, errmsg(), FetchTableStates(), GetCurrentTimestamp(), HASH_BLOBS, hash_create(), hash_destroy(), HASH_ELEM, HASH_ENTER, hash_search(), IsTransactionState(), HASHCTL::keysize, lfirst, LOG, logicalrep_sync_worker_count(), LOGICALREP_TWOPHASE_STATE_PENDING, logicalrep_worker_find(), logicalrep_worker_launch(), logicalrep_worker_wakeup_ptr(), SubscriptionRelState::lsn, LW_SHARED, LWLockAcquire(), LWLockRelease(), Max, max_sync_workers_per_subscription, MyLogicalRepWorker, MySubscription, Subscription::name, NAMEDATALEN, now(), Subscription::oid, pgstat_report_stat(), LogicalRepWorker::proc, proc_exit(), SubscriptionRelState::relid, LogicalRepWorker::relmutex, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, ReplicationOriginNameForTablesync(), replorigin_drop_by_name(), SpinLockAcquire, SpinLockRelease, StartTransactionCommand(), SubscriptionRelState::state, LogicalRepWorker::subid, table_states_not_ready, TimestampDifferenceExceeds(), Subscription::twophasestate, UpdateSubscriptionRelState(), LogicalRepWorker::userid, wait_for_relation_state_change(), and wal_retrieve_retry_interval.

Referenced by process_syncing_tables().

◆ process_syncing_tables_for_sync()

static void process_syncing_tables_for_sync ( XLogRecPtr  current_lsn)
static

Definition at line 285 of file tablesync.c.

286 {
288 
289  if (MyLogicalRepWorker->relstate == SUBREL_STATE_CATCHUP &&
290  current_lsn >= MyLogicalRepWorker->relstate_lsn)
291  {
292  TimeLineID tli;
293  char syncslotname[NAMEDATALEN] = {0};
294 
295  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCDONE;
296  MyLogicalRepWorker->relstate_lsn = current_lsn;
297 
299 
300  /*
301  * UpdateSubscriptionRelState must be called within a transaction.
302  * That transaction will be ended within the finish_sync_worker().
303  */
304  if (!IsTransactionState())
306 
311 
312  /*
313  * End streaming so that LogRepWorkerWalRcvConn can be used to drop
314  * the slot.
315  */
317 
318  /*
319  * Cleanup the tablesync slot.
320  *
321  * This has to be done after updating the state because otherwise if
322  * there is an error while doing the database operations we won't be
323  * able to rollback dropped slot.
324  */
327  syncslotname,
328  sizeof(syncslotname));
329 
330  /*
331  * It is important to give an error if we are unable to drop the slot,
332  * otherwise, it won't be dropped till the corresponding subscription
333  * is dropped. So passing missing_ok = false.
334  */
336 
337  finish_sync_worker();
338  }
339  else
341 }
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:420
uint32 TimeLineID
Definition: xlogdefs.h:59

References IsTransactionState(), LogRepWorkerWalRcvConn, MyLogicalRepWorker, NAMEDATALEN, LogicalRepWorker::relid, LogicalRepWorker::relmutex, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), SpinLockAcquire, SpinLockRelease, StartTransactionCommand(), LogicalRepWorker::subid, UpdateSubscriptionRelState(), and walrcv_endstreaming.

Referenced by process_syncing_tables().

◆ ReplicationOriginNameForTablesync()

void ReplicationOriginNameForTablesync ( Oid  suboid,
Oid  relid,
char *  originname,
int  szorgname 
)

Definition at line 1164 of file tablesync.c.

1166 {
1167  snprintf(originname, szorgname, "pg_%u_%u", suboid, relid);
1168 }
#define snprintf
Definition: port.h:225

References snprintf.

Referenced by AlterSubscription_refresh(), ApplyWorkerMain(), DropSubscription(), LogicalRepSyncTableStart(), and process_syncing_tables_for_apply().

◆ ReplicationSlotNameForTablesync()

void ReplicationSlotNameForTablesync ( Oid  suboid,
Oid  relid,
char *  syncslotname,
int  szslot 
)

Definition at line 1151 of file tablesync.c.

1153 {
1154  snprintf(syncslotname, szslot, "pg_%u_sync_%u_" UINT64_FORMAT, suboid,
1155  relid, GetSystemIdentifier());
1156 }
#define UINT64_FORMAT
Definition: c.h:484
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4206

References GetSystemIdentifier(), snprintf, and UINT64_FORMAT.

Referenced by AlterSubscription_refresh(), DropSubscription(), LogicalRepSyncTableStart(), process_syncing_tables_for_sync(), and ReportSlotConnectionError().

◆ UpdateTwoPhaseState()

void UpdateTwoPhaseState ( Oid  suboid,
char  new_state 
)

Definition at line 1540 of file tablesync.c.

1541 {
1542  Relation rel;
1543  HeapTuple tup;
1544  bool nulls[Natts_pg_subscription];
1545  bool replaces[Natts_pg_subscription];
1546  Datum values[Natts_pg_subscription];
1547 
1549  new_state == LOGICALREP_TWOPHASE_STATE_PENDING ||
1550  new_state == LOGICALREP_TWOPHASE_STATE_ENABLED);
1551 
1552  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1554  if (!HeapTupleIsValid(tup))
1555  elog(ERROR,
1556  "cache lookup failed for subscription oid %u",
1557  suboid);
1558 
1559  /* Form a new tuple. */
1560  memset(values, 0, sizeof(values));
1561  memset(nulls, false, sizeof(nulls));
1562  memset(replaces, false, sizeof(replaces));
1563 
1564  /* And update/set two_phase state */
1565  values[Anum_pg_subscription_subtwophasestate - 1] = CharGetDatum(new_state);
1566  replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
1567 
1568  tup = heap_modify_tuple(tup, RelationGetDescr(rel),
1569  values, nulls, replaces);
1570  CatalogTupleUpdate(rel, &tup->t_self, tup);
1571 
1572  heap_freetuple(tup);
1574 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define LOGICALREP_TWOPHASE_STATE_ENABLED
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define CharGetDatum(X)
Definition: postgres.h:460
#define RelationGetDescr(relation)
Definition: rel.h:515
ItemPointerData t_self
Definition: htup.h:65
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ SUBSCRIPTIONOID
Definition: syscache.h:99

References Assert(), CatalogTupleUpdate(), CharGetDatum, elog, ERROR, heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, LOGICALREP_TWOPHASE_STATE_DISABLED, LOGICALREP_TWOPHASE_STATE_ENABLED, LOGICALREP_TWOPHASE_STATE_PENDING, ObjectIdGetDatum, RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, SUBSCRIPTIONOID, HeapTupleData::t_self, table_close(), table_open(), and values.

Referenced by ApplyWorkerMain(), and CreateSubscription().

◆ wait_for_relation_state_change()

static bool wait_for_relation_state_change ( Oid  relid,
char  expected_state 
)
static

Definition at line 174 of file tablesync.c.

175 {
176  char state;
177 
178  for (;;)
179  {
180  LogicalRepWorker *worker;
181  XLogRecPtr statelsn;
182 
184 
187  relid, &statelsn);
188 
189  if (state == SUBREL_STATE_UNKNOWN)
190  break;
191 
192  if (state == expected_state)
193  return true;
194 
195  /* Check if the sync worker is still running and bail if not. */
196  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
198  false);
199  LWLockRelease(LogicalRepWorkerLock);
200  if (!worker)
201  break;
202 
203  (void) WaitLatch(MyLatch,
206 
208  }
209 
210  return false;
211 }
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:451
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:456
Definition: regguts.h:318
@ WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE
Definition: wait_event.h:109

References CHECK_FOR_INTERRUPTS, GetSubscriptionRelState(), InvalidateCatalogSnapshot(), logicalrep_worker_find(), LW_SHARED, LWLockAcquire(), LWLockRelease(), MyLatch, MyLogicalRepWorker, ResetLatch(), LogicalRepWorker::subid, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by process_syncing_tables_for_apply().

◆ wait_for_worker_state_change()

static bool wait_for_worker_state_change ( char  expected_state)
static

Definition at line 222 of file tablesync.c.

223 {
224  int rc;
225 
226  for (;;)
227  {
228  LogicalRepWorker *worker;
229 
231 
232  /*
233  * Done if already in correct state. (We assume this fetch is atomic
234  * enough to not give a misleading answer if we do it with no lock.)
235  */
236  if (MyLogicalRepWorker->relstate == expected_state)
237  return true;
238 
239  /*
240  * Bail out if the apply worker has died, else signal it we're
241  * waiting.
242  */
243  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
245  InvalidOid, false);
246  if (worker && worker->proc)
248  LWLockRelease(LogicalRepWorkerLock);
249  if (!worker)
250  break;
251 
252  /*
253  * Wait. We expect to get a latch signal back from the apply worker,
254  * but use a timeout in case it dies without sending one.
255  */
256  rc = WaitLatch(MyLatch,
259 
260  if (rc & WL_LATCH_SET)
262  }
263 
264  return false;
265 }

References CHECK_FOR_INTERRUPTS, InvalidOid, logicalrep_worker_find(), logicalrep_worker_wakeup_ptr(), LW_SHARED, LWLockAcquire(), LWLockRelease(), MyLatch, MyLogicalRepWorker, LogicalRepWorker::proc, LogicalRepWorker::relstate, ResetLatch(), LogicalRepWorker::subid, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by LogicalRepSyncTableStart().

Variable Documentation

◆ copybuf

◆ table_states_not_ready

List* table_states_not_ready = NIL
static

◆ table_states_valid

bool table_states_valid = false
static

Definition at line 123 of file tablesync.c.

Referenced by FetchTableStates(), and invalidate_syncing_table_states().