PostgreSQL Source Code  git master
subscriptioncmds.c File Reference
Include dependency graph for subscriptioncmds.c:

Go to the source code of this file.

Data Structures

struct  SubOpts
 

Macros

#define SUBOPT_CONNECT   0x00000001
 
#define SUBOPT_ENABLED   0x00000002
 
#define SUBOPT_CREATE_SLOT   0x00000004
 
#define SUBOPT_SLOT_NAME   0x00000008
 
#define SUBOPT_COPY_DATA   0x00000010
 
#define SUBOPT_SYNCHRONOUS_COMMIT   0x00000020
 
#define SUBOPT_REFRESH   0x00000040
 
#define SUBOPT_BINARY   0x00000080
 
#define SUBOPT_STREAMING   0x00000100
 
#define SUBOPT_TWOPHASE_COMMIT   0x00000200
 
#define SUBOPT_DISABLE_ON_ERR   0x00000400
 
#define SUBOPT_LSN   0x00000800
 
#define SUBOPT_ORIGIN   0x00001000
 
#define IsSet(val, bits)   (((val) & (bits)) == (bits))
 

Typedefs

typedef struct SubOpts SubOpts
 

Functions

static Listfetch_table_list (WalReceiverConn *wrconn, List *publications)
 
static void check_publications_origin (WalReceiverConn *wrconn, List *publications, bool copydata, char *origin, Oid *subrel_local_oids, int subrel_count, char *subname)
 
static void check_duplicates_in_publist (List *publist, Datum *datums)
 
static Listmerge_publications (List *oldpublist, List *newpublist, bool addpub, const char *subname)
 
static void ReportSlotConnectionError (List *rstates, Oid subid, char *slotname, char *err)
 
static void parse_subscription_options (ParseState *pstate, List *stmt_options, bits32 supported_opts, SubOpts *opts)
 
static void get_publications_str (List *publications, StringInfo dest, bool quote_literal)
 
static void check_publications (WalReceiverConn *wrconn, List *publications)
 
static Datum publicationListToArray (List *publist)
 
ObjectAddress CreateSubscription (ParseState *pstate, CreateSubscriptionStmt *stmt, bool isTopLevel)
 
static void AlterSubscription_refresh (Subscription *sub, bool copy_data, List *validate_publications)
 
ObjectAddress AlterSubscription (ParseState *pstate, AlterSubscriptionStmt *stmt, bool isTopLevel)
 
void DropSubscription (DropSubscriptionStmt *stmt, bool isTopLevel)
 
void ReplicationSlotDropAtPubNode (WalReceiverConn *wrconn, char *slotname, bool missing_ok)
 
static void AlterSubscriptionOwner_internal (Relation rel, HeapTuple tup, Oid newOwnerId)
 
ObjectAddress AlterSubscriptionOwner (const char *name, Oid newOwnerId)
 
void AlterSubscriptionOwner_oid (Oid subid, Oid newOwnerId)
 

Macro Definition Documentation

◆ IsSet

#define IsSet (   val,
  bits 
)    (((val) & (bits)) == (bits))

Definition at line 70 of file subscriptioncmds.c.

◆ SUBOPT_BINARY

#define SUBOPT_BINARY   0x00000080

Definition at line 62 of file subscriptioncmds.c.

◆ SUBOPT_CONNECT

#define SUBOPT_CONNECT   0x00000001

Definition at line 55 of file subscriptioncmds.c.

◆ SUBOPT_COPY_DATA

#define SUBOPT_COPY_DATA   0x00000010

Definition at line 59 of file subscriptioncmds.c.

◆ SUBOPT_CREATE_SLOT

#define SUBOPT_CREATE_SLOT   0x00000004

Definition at line 57 of file subscriptioncmds.c.

◆ SUBOPT_DISABLE_ON_ERR

#define SUBOPT_DISABLE_ON_ERR   0x00000400

Definition at line 65 of file subscriptioncmds.c.

◆ SUBOPT_ENABLED

#define SUBOPT_ENABLED   0x00000002

Definition at line 56 of file subscriptioncmds.c.

◆ SUBOPT_LSN

#define SUBOPT_LSN   0x00000800

Definition at line 66 of file subscriptioncmds.c.

◆ SUBOPT_ORIGIN

#define SUBOPT_ORIGIN   0x00001000

Definition at line 67 of file subscriptioncmds.c.

◆ SUBOPT_REFRESH

#define SUBOPT_REFRESH   0x00000040

Definition at line 61 of file subscriptioncmds.c.

◆ SUBOPT_SLOT_NAME

#define SUBOPT_SLOT_NAME   0x00000008

Definition at line 58 of file subscriptioncmds.c.

◆ SUBOPT_STREAMING

#define SUBOPT_STREAMING   0x00000100

Definition at line 63 of file subscriptioncmds.c.

◆ SUBOPT_SYNCHRONOUS_COMMIT

#define SUBOPT_SYNCHRONOUS_COMMIT   0x00000020

Definition at line 60 of file subscriptioncmds.c.

◆ SUBOPT_TWOPHASE_COMMIT

#define SUBOPT_TWOPHASE_COMMIT   0x00000200

Definition at line 64 of file subscriptioncmds.c.

Typedef Documentation

◆ SubOpts

typedef struct SubOpts SubOpts

Function Documentation

◆ AlterSubscription()

ObjectAddress AlterSubscription ( ParseState pstate,
AlterSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 1003 of file subscriptioncmds.c.

1005 {
1006  Relation rel;
1007  ObjectAddress myself;
1008  bool nulls[Natts_pg_subscription];
1009  bool replaces[Natts_pg_subscription];
1010  Datum values[Natts_pg_subscription];
1011  HeapTuple tup;
1012  Oid subid;
1013  bool update_tuple = false;
1014  Subscription *sub;
1015  Form_pg_subscription form;
1016  bits32 supported_opts;
1017  SubOpts opts = {0};
1018 
1019  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1020 
1021  /* Fetch the existing tuple. */
1023  CStringGetDatum(stmt->subname));
1024 
1025  if (!HeapTupleIsValid(tup))
1026  ereport(ERROR,
1027  (errcode(ERRCODE_UNDEFINED_OBJECT),
1028  errmsg("subscription \"%s\" does not exist",
1029  stmt->subname)));
1030 
1031  form = (Form_pg_subscription) GETSTRUCT(tup);
1032  subid = form->oid;
1033 
1034  /* must be owner */
1035  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1037  stmt->subname);
1038 
1039  sub = GetSubscription(subid, false);
1040 
1041  /* Lock the subscription so nobody else can do anything with it. */
1042  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1043 
1044  /* Form a new tuple. */
1045  memset(values, 0, sizeof(values));
1046  memset(nulls, false, sizeof(nulls));
1047  memset(replaces, false, sizeof(replaces));
1048 
1049  switch (stmt->kind)
1050  {
1052  {
1053  supported_opts = (SUBOPT_SLOT_NAME |
1056  SUBOPT_ORIGIN);
1057 
1058  parse_subscription_options(pstate, stmt->options,
1059  supported_opts, &opts);
1060 
1061  if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1062  {
1063  /*
1064  * The subscription must be disabled to allow slot_name as
1065  * 'none', otherwise, the apply worker will repeatedly try
1066  * to stream the data using that slot_name which neither
1067  * exists on the publisher nor the user will be allowed to
1068  * create it.
1069  */
1070  if (sub->enabled && !opts.slot_name)
1071  ereport(ERROR,
1072  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1073  errmsg("cannot set %s for enabled subscription",
1074  "slot_name = NONE")));
1075 
1076  if (opts.slot_name)
1077  values[Anum_pg_subscription_subslotname - 1] =
1079  else
1080  nulls[Anum_pg_subscription_subslotname - 1] = true;
1081  replaces[Anum_pg_subscription_subslotname - 1] = true;
1082  }
1083 
1084  if (opts.synchronous_commit)
1085  {
1086  values[Anum_pg_subscription_subsynccommit - 1] =
1087  CStringGetTextDatum(opts.synchronous_commit);
1088  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1089  }
1090 
1091  if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1092  {
1093  values[Anum_pg_subscription_subbinary - 1] =
1094  BoolGetDatum(opts.binary);
1095  replaces[Anum_pg_subscription_subbinary - 1] = true;
1096  }
1097 
1098  if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1099  {
1100  values[Anum_pg_subscription_substream - 1] =
1101  BoolGetDatum(opts.streaming);
1102  replaces[Anum_pg_subscription_substream - 1] = true;
1103  }
1104 
1105  if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1106  {
1107  values[Anum_pg_subscription_subdisableonerr - 1]
1108  = BoolGetDatum(opts.disableonerr);
1109  replaces[Anum_pg_subscription_subdisableonerr - 1]
1110  = true;
1111  }
1112 
1113  if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1114  {
1115  values[Anum_pg_subscription_suborigin - 1] =
1116  CStringGetTextDatum(opts.origin);
1117  replaces[Anum_pg_subscription_suborigin - 1] = true;
1118  }
1119 
1120  update_tuple = true;
1121  break;
1122  }
1123 
1125  {
1126  parse_subscription_options(pstate, stmt->options,
1127  SUBOPT_ENABLED, &opts);
1128  Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
1129 
1130  if (!sub->slotname && opts.enabled)
1131  ereport(ERROR,
1132  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1133  errmsg("cannot enable subscription that does not have a slot name")));
1134 
1135  values[Anum_pg_subscription_subenabled - 1] =
1136  BoolGetDatum(opts.enabled);
1137  replaces[Anum_pg_subscription_subenabled - 1] = true;
1138 
1139  if (opts.enabled)
1141 
1142  update_tuple = true;
1143  break;
1144  }
1145 
1147  /* Load the library providing us libpq calls. */
1148  load_file("libpqwalreceiver", false);
1149  /* Check the connection info string. */
1151 
1152  values[Anum_pg_subscription_subconninfo - 1] =
1154  replaces[Anum_pg_subscription_subconninfo - 1] = true;
1155  update_tuple = true;
1156  break;
1157 
1159  {
1160  supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1161  parse_subscription_options(pstate, stmt->options,
1162  supported_opts, &opts);
1163 
1164  values[Anum_pg_subscription_subpublications - 1] =
1166  replaces[Anum_pg_subscription_subpublications - 1] = true;
1167 
1168  update_tuple = true;
1169 
1170  /* Refresh if user asked us to. */
1171  if (opts.refresh)
1172  {
1173  if (!sub->enabled)
1174  ereport(ERROR,
1175  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1176  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1177  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1178 
1179  /*
1180  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1181  * not allowed.
1182  */
1183  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1184  ereport(ERROR,
1185  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1186  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1187  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1188 
1189  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1190 
1191  /* Make sure refresh sees the new list of publications. */
1192  sub->publications = stmt->publication;
1193 
1194  AlterSubscription_refresh(sub, opts.copy_data,
1195  stmt->publication);
1196  }
1197 
1198  break;
1199  }
1200 
1203  {
1204  List *publist;
1205  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1206 
1207  supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1208  parse_subscription_options(pstate, stmt->options,
1209  supported_opts, &opts);
1210 
1211  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1212  values[Anum_pg_subscription_subpublications - 1] =
1213  publicationListToArray(publist);
1214  replaces[Anum_pg_subscription_subpublications - 1] = true;
1215 
1216  update_tuple = true;
1217 
1218  /* Refresh if user asked us to. */
1219  if (opts.refresh)
1220  {
1221  /* We only need to validate user specified publications. */
1222  List *validate_publications = (isadd) ? stmt->publication : NULL;
1223 
1224  if (!sub->enabled)
1225  ereport(ERROR,
1226  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1227  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1228  /* translator: %s is an SQL ALTER command */
1229  errhint("Use %s instead.",
1230  isadd ?
1231  "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
1232  "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
1233 
1234  /*
1235  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1236  * not allowed.
1237  */
1238  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1239  ereport(ERROR,
1240  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1241  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1242  /* translator: %s is an SQL ALTER command */
1243  errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
1244  isadd ?
1245  "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
1246  "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
1247 
1248  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1249 
1250  /* Refresh the new list of publications. */
1251  sub->publications = publist;
1252 
1253  AlterSubscription_refresh(sub, opts.copy_data,
1254  validate_publications);
1255  }
1256 
1257  break;
1258  }
1259 
1261  {
1262  if (!sub->enabled)
1263  ereport(ERROR,
1264  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1265  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1266 
1267  parse_subscription_options(pstate, stmt->options,
1269 
1270  /*
1271  * The subscription option "two_phase" requires that
1272  * replication has passed the initial table synchronization
1273  * phase before the two_phase becomes properly enabled.
1274  *
1275  * But, having reached this two-phase commit "enabled" state
1276  * we must not allow any subsequent table initialization to
1277  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1278  * when the user had requested two_phase = on mode.
1279  *
1280  * The exception to this restriction is when copy_data =
1281  * false, because when copy_data is false the tablesync will
1282  * start already in READY state and will exit directly without
1283  * doing anything.
1284  *
1285  * For more details see comments atop worker.c.
1286  */
1287  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1288  ereport(ERROR,
1289  (errcode(ERRCODE_SYNTAX_ERROR),
1290  errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1291  errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1292 
1293  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1294 
1295  AlterSubscription_refresh(sub, opts.copy_data, NULL);
1296 
1297  break;
1298  }
1299 
1301  {
1303 
1304  /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
1305  Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
1306 
1307  if (!superuser())
1308  ereport(ERROR,
1309  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1310  errmsg("must be superuser to skip transaction")));
1311 
1312  /*
1313  * If the user sets subskiplsn, we do a sanity check to make
1314  * sure that the specified LSN is a probable value.
1315  */
1316  if (!XLogRecPtrIsInvalid(opts.lsn))
1317  {
1318  RepOriginId originid;
1319  char originname[NAMEDATALEN];
1320  XLogRecPtr remote_lsn;
1321 
1323  originname, sizeof(originname));
1324  originid = replorigin_by_name(originname, false);
1325  remote_lsn = replorigin_get_progress(originid, false);
1326 
1327  /* Check the given LSN is at least a future LSN */
1328  if (!XLogRecPtrIsInvalid(remote_lsn) && opts.lsn < remote_lsn)
1329  ereport(ERROR,
1330  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1331  errmsg("skip WAL location (LSN %X/%X) must be greater than origin LSN %X/%X",
1332  LSN_FORMAT_ARGS(opts.lsn),
1333  LSN_FORMAT_ARGS(remote_lsn))));
1334  }
1335 
1336  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
1337  replaces[Anum_pg_subscription_subskiplsn - 1] = true;
1338 
1339  update_tuple = true;
1340  break;
1341  }
1342 
1343  default:
1344  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1345  stmt->kind);
1346  }
1347 
1348  /* Update the catalog if needed. */
1349  if (update_tuple)
1350  {
1351  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1352  replaces);
1353 
1354  CatalogTupleUpdate(rel, &tup->t_self, tup);
1355 
1356  heap_freetuple(tup);
1357  }
1358 
1360 
1361  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1362 
1363  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1364 
1365  return myself;
1366 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3477
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4771
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition: worker.c:376
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:85
uint32 bits32
Definition: c.h:451
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
Oid MyDatabaseId
Definition: globals.c:89
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
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:785
Assert(fmt[strlen(fmt) - 1] !='\n')
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid GetUserId(void)
Definition: miscinit.c:497
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
RepOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition: origin.c:221
XLogRecPtr replorigin_get_progress(RepOriginId node, bool flush)
Definition: origin.c:1010
@ ALTER_SUBSCRIPTION_ENABLED
Definition: parsenodes.h:3808
@ ALTER_SUBSCRIPTION_DROP_PUBLICATION
Definition: parsenodes.h:3806
@ ALTER_SUBSCRIPTION_SET_PUBLICATION
Definition: parsenodes.h:3804
@ ALTER_SUBSCRIPTION_REFRESH
Definition: parsenodes.h:3807
@ ALTER_SUBSCRIPTION_SKIP
Definition: parsenodes.h:3809
@ ALTER_SUBSCRIPTION_OPTIONS
Definition: parsenodes.h:3802
@ ALTER_SUBSCRIPTION_CONNECTION
Definition: parsenodes.h:3803
@ ALTER_SUBSCRIPTION_ADD_PUBLICATION
Definition: parsenodes.h:3805
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:1898
static AmcheckOptions opts
Definition: pg_amcheck.c:110
#define NAMEDATALEN
static Datum LSNGetDatum(XLogRecPtr X)
Definition: pg_lsn.h:28
Subscription * GetSubscription(Oid subid, bool missing_ok)
#define LOGICALREP_TWOPHASE_STATE_ENABLED
FormData_pg_subscription * Form_pg_subscription
uintptr_t Datum
Definition: postgres.h:412
static Datum BoolGetDatum(bool X)
Definition: postgres.h:450
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:698
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:527
AlterSubscriptionType kind
Definition: parsenodes.h:3815
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:52
#define SUBOPT_STREAMING
#define SUBOPT_SYNCHRONOUS_COMMIT
#define SUBOPT_ENABLED
#define SUBOPT_ORIGIN
static Datum publicationListToArray(List *publist)
static void parse_subscription_options(ParseState *pstate, List *stmt_options, bits32 supported_opts, SubOpts *opts)
#define SUBOPT_SLOT_NAME
#define SUBOPT_COPY_DATA
static void AlterSubscription_refresh(Subscription *sub, bool copy_data, List *validate_publications)
#define SUBOPT_DISABLE_ON_ERR
#define SUBOPT_LSN
static List * merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
#define SUBOPT_BINARY
#define IsSet(val, bits)
#define SUBOPT_REFRESH
bool superuser(void)
Definition: superuser.c:46
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:181
@ SUBSCRIPTIONNAME
Definition: syscache.h:98
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
#define walrcv_check_conninfo(conninfo)
Definition: walreceiver.h:410
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3469
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint16 RepOriginId
Definition: xlogdefs.h:65
uint64 XLogRecPtr
Definition: xlogdefs.h:21

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ALTER_SUBSCRIPTION_ADD_PUBLICATION, ALTER_SUBSCRIPTION_CONNECTION, ALTER_SUBSCRIPTION_DROP_PUBLICATION, ALTER_SUBSCRIPTION_ENABLED, ALTER_SUBSCRIPTION_OPTIONS, ALTER_SUBSCRIPTION_REFRESH, ALTER_SUBSCRIPTION_SET_PUBLICATION, ALTER_SUBSCRIPTION_SKIP, AlterSubscription_refresh(), ApplyLauncherWakeupAtCommit(), Assert(), BoolGetDatum(), CatalogTupleUpdate(), AlterSubscriptionStmt::conninfo, CStringGetDatum(), CStringGetTextDatum, DirectFunctionCall1, elog(), Subscription::enabled, ereport, errcode(), errhint(), errmsg(), ERROR, GETSTRUCT, GetSubscription(), GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, if(), InvalidOid, InvokeObjectPostAlterHook, IsSet, AlterSubscriptionStmt::kind, load_file(), LockSharedObject(), LOGICALREP_TWOPHASE_STATE_ENABLED, LSN_FORMAT_ARGS, LSNGetDatum(), merge_publications(), MyDatabaseId, NAMEDATALEN, namein(), object_ownercheck(), OBJECT_SUBSCRIPTION, ObjectAddressSet, AlterSubscriptionStmt::options, opts, parse_subscription_options(), PreventInTransactionBlock(), AlterSubscriptionStmt::publication, publicationListToArray(), Subscription::publications, RelationGetDescr, ReplicationOriginNameForLogicalRep(), replorigin_by_name(), replorigin_get_progress(), RowExclusiveLock, SearchSysCacheCopy2, Subscription::slotname, AlterSubscriptionStmt::subname, SUBOPT_BINARY, SUBOPT_COPY_DATA, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_LSN, SUBOPT_ORIGIN, SUBOPT_REFRESH, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBSCRIPTIONNAME, superuser(), HeapTupleData::t_self, table_close(), table_open(), Subscription::twophasestate, values, walrcv_check_conninfo, and XLogRecPtrIsInvalid.

Referenced by ProcessUtilitySlow().

◆ AlterSubscription_refresh()

static void AlterSubscription_refresh ( Subscription sub,
bool  copy_data,
List validate_publications 
)
static

Definition at line 781 of file subscriptioncmds.c.

783 {
784  char *err;
785  List *pubrel_names;
786  List *subrel_states;
787  Oid *subrel_local_oids;
788  Oid *pubrel_local_oids;
789  ListCell *lc;
790  int off;
791  int remove_rel_len;
792  int subrel_count;
793  Relation rel = NULL;
794  typedef struct SubRemoveRels
795  {
796  Oid relid;
797  char state;
798  } SubRemoveRels;
799  SubRemoveRels *sub_remove_rels;
801 
802  /* Load the library providing us libpq calls. */
803  load_file("libpqwalreceiver", false);
804 
805  /* Try to connect to the publisher. */
806  wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
807  if (!wrconn)
808  ereport(ERROR,
809  (errcode(ERRCODE_CONNECTION_FAILURE),
810  errmsg("could not connect to the publisher: %s", err)));
811 
812  PG_TRY();
813  {
814  if (validate_publications)
815  check_publications(wrconn, validate_publications);
816 
817  /* Get the table list from publisher. */
818  pubrel_names = fetch_table_list(wrconn, sub->publications);
819 
820  /* Get local table list. */
821  subrel_states = GetSubscriptionRelations(sub->oid, false);
822  subrel_count = list_length(subrel_states);
823 
824  /*
825  * Build qsorted array of local table oids for faster lookup. This can
826  * potentially contain all tables in the database so speed of lookup
827  * is important.
828  */
829  subrel_local_oids = palloc(subrel_count * sizeof(Oid));
830  off = 0;
831  foreach(lc, subrel_states)
832  {
834 
835  subrel_local_oids[off++] = relstate->relid;
836  }
837  qsort(subrel_local_oids, subrel_count,
838  sizeof(Oid), oid_cmp);
839 
841  sub->origin, subrel_local_oids,
842  subrel_count, sub->name);
843 
844  /*
845  * Rels that we want to remove from subscription and drop any slots
846  * and origins corresponding to them.
847  */
848  sub_remove_rels = palloc(subrel_count * sizeof(SubRemoveRels));
849 
850  /*
851  * Walk over the remote tables and try to match them to locally known
852  * tables. If the table is not known locally create a new state for
853  * it.
854  *
855  * Also builds array of local oids of remote tables for the next step.
856  */
857  off = 0;
858  pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
859 
860  foreach(lc, pubrel_names)
861  {
862  RangeVar *rv = (RangeVar *) lfirst(lc);
863  Oid relid;
864 
865  relid = RangeVarGetRelid(rv, AccessShareLock, false);
866 
867  /* Check for supported relkind. */
869  rv->schemaname, rv->relname);
870 
871  pubrel_local_oids[off++] = relid;
872 
873  if (!bsearch(&relid, subrel_local_oids,
874  subrel_count, sizeof(Oid), oid_cmp))
875  {
876  AddSubscriptionRelState(sub->oid, relid,
877  copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
879  ereport(DEBUG1,
880  (errmsg_internal("table \"%s.%s\" added to subscription \"%s\"",
881  rv->schemaname, rv->relname, sub->name)));
882  }
883  }
884 
885  /*
886  * Next remove state for tables we should not care about anymore using
887  * the data we collected above
888  */
889  qsort(pubrel_local_oids, list_length(pubrel_names),
890  sizeof(Oid), oid_cmp);
891 
892  remove_rel_len = 0;
893  for (off = 0; off < subrel_count; off++)
894  {
895  Oid relid = subrel_local_oids[off];
896 
897  if (!bsearch(&relid, pubrel_local_oids,
898  list_length(pubrel_names), sizeof(Oid), oid_cmp))
899  {
900  char state;
901  XLogRecPtr statelsn;
902 
903  /*
904  * Lock pg_subscription_rel with AccessExclusiveLock to
905  * prevent any race conditions with the apply worker
906  * re-launching workers at the same time this code is trying
907  * to remove those tables.
908  *
909  * Even if new worker for this particular rel is restarted it
910  * won't be able to make any progress as we hold exclusive
911  * lock on subscription_rel till the transaction end. It will
912  * simply exit as there is no corresponding rel entry.
913  *
914  * This locking also ensures that the state of rels won't
915  * change till we are done with this refresh operation.
916  */
917  if (!rel)
918  rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
919 
920  /* Last known rel state. */
921  state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
922 
923  sub_remove_rels[remove_rel_len].relid = relid;
924  sub_remove_rels[remove_rel_len++].state = state;
925 
926  RemoveSubscriptionRel(sub->oid, relid);
927 
928  logicalrep_worker_stop(sub->oid, relid);
929 
930  /*
931  * For READY state, we would have already dropped the
932  * tablesync origin.
933  */
934  if (state != SUBREL_STATE_READY)
935  {
936  char originname[NAMEDATALEN];
937 
938  /*
939  * Drop the tablesync's origin tracking if exists.
940  *
941  * It is possible that the origin is not yet created for
942  * tablesync worker, this can happen for the states before
943  * SUBREL_STATE_FINISHEDCOPY. The tablesync worker or
944  * apply worker can also concurrently try to drop the
945  * origin and by this time the origin might be already
946  * removed. For these reasons, passing missing_ok = true.
947  */
948  ReplicationOriginNameForLogicalRep(sub->oid, relid, originname,
949  sizeof(originname));
950  replorigin_drop_by_name(originname, true, false);
951  }
952 
953  ereport(DEBUG1,
954  (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
956  get_rel_name(relid),
957  sub->name)));
958  }
959  }
960 
961  /*
962  * Drop the tablesync slots associated with removed tables. This has
963  * to be at the end because otherwise if there is an error while doing
964  * the database operations we won't be able to rollback dropped slots.
965  */
966  for (off = 0; off < remove_rel_len; off++)
967  {
968  if (sub_remove_rels[off].state != SUBREL_STATE_READY &&
969  sub_remove_rels[off].state != SUBREL_STATE_SYNCDONE)
970  {
971  char syncslotname[NAMEDATALEN] = {0};
972 
973  /*
974  * For READY/SYNCDONE states we know the tablesync slot has
975  * already been dropped by the tablesync worker.
976  *
977  * For other states, there is no certainty, maybe the slot
978  * does not exist yet. Also, if we fail after removing some of
979  * the slots, next time, it will again try to drop already
980  * dropped slots and fail. For these reasons, we allow
981  * missing_ok = true for the drop.
982  */
983  ReplicationSlotNameForTablesync(sub->oid, sub_remove_rels[off].relid,
984  syncslotname, sizeof(syncslotname));
985  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
986  }
987  }
988  }
989  PG_FINALLY();
990  {
992  }
993  PG_END_TRY();
994 
995  if (rel)
996  table_close(rel, NoLock);
997 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
#define PG_TRY(...)
Definition: elog.h:309
#define PG_END_TRY(...)
Definition: elog.h:334
#define DEBUG1
Definition: elog.h:26
#define PG_FINALLY(...)
Definition: elog.h:326
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:437
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3331
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1985
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1934
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1910
void * palloc(Size size)
Definition: mcxt.c:1199
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
int oid_cmp(const void *p1, const void *p2)
Definition: oid.c:336
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:426
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
void RemoveSubscriptionRel(Oid subid, Oid relid)
List * GetSubscriptionRelations(Oid subid, bool not_ready)
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define qsort(a, b, c, d)
Definition: port.h:445
char * relname
Definition: primnodes.h:77
char * schemaname
Definition: primnodes.h:74
Definition: regguts.h:318
static void check_publications(WalReceiverConn *wrconn, List *publications)
static void check_publications_origin(WalReceiverConn *wrconn, List *publications, bool copydata, char *origin, Oid *subrel_local_oids, int subrel_count, char *subname)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, Size szslot)
Definition: tablesync.c:1189
static WalReceiverConn * wrconn
Definition: walreceiver.c:95
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:408
#define walrcv_disconnect(conn)
Definition: walreceiver.h:436
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References AccessExclusiveLock, AccessShareLock, AddSubscriptionRelState(), check_publications(), check_publications_origin(), CheckSubscriptionRelkind(), Subscription::conninfo, DEBUG1, ereport, errcode(), errmsg(), errmsg_internal(), ERROR, fetch_table_list(), get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_relkind(), GetSubscriptionRelations(), GetSubscriptionRelState(), InvalidXLogRecPtr, lfirst, list_length(), load_file(), logicalrep_worker_stop(), Subscription::name, NAMEDATALEN, NoLock, Subscription::oid, oid_cmp(), Subscription::origin, palloc(), PG_END_TRY, PG_FINALLY, PG_TRY, Subscription::publications, qsort, RangeVarGetRelid, SubscriptionRelState::relid, RangeVar::relname, RemoveSubscriptionRel(), ReplicationOriginNameForLogicalRep(), ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), replorigin_drop_by_name(), RangeVar::schemaname, table_close(), table_open(), walrcv_connect, walrcv_disconnect, and wrconn.

Referenced by AlterSubscription().

◆ AlterSubscriptionOwner()

ObjectAddress AlterSubscriptionOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 1742 of file subscriptioncmds.c.

1743 {
1744  Oid subid;
1745  HeapTuple tup;
1746  Relation rel;
1747  ObjectAddress address;
1748  Form_pg_subscription form;
1749 
1750  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1751 
1754 
1755  if (!HeapTupleIsValid(tup))
1756  ereport(ERROR,
1757  (errcode(ERRCODE_UNDEFINED_OBJECT),
1758  errmsg("subscription \"%s\" does not exist", name)));
1759 
1760  form = (Form_pg_subscription) GETSTRUCT(tup);
1761  subid = form->oid;
1762 
1763  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1764 
1765  ObjectAddressSet(address, SubscriptionRelationId, subid);
1766 
1767  heap_freetuple(tup);
1768 
1770 
1771  return address;
1772 }
const char * name
Definition: encode.c:561
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)

References AlterSubscriptionOwner_internal(), CStringGetDatum(), ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, MyDatabaseId, name, ObjectAddressSet, RowExclusiveLock, SearchSysCacheCopy2, SUBSCRIPTIONNAME, table_close(), and table_open().

Referenced by ExecAlterOwnerStmt().

◆ AlterSubscriptionOwner_internal()

static void AlterSubscriptionOwner_internal ( Relation  rel,
HeapTuple  tup,
Oid  newOwnerId 
)
static

Definition at line 1703 of file subscriptioncmds.c.

1704 {
1705  Form_pg_subscription form;
1706 
1707  form = (Form_pg_subscription) GETSTRUCT(tup);
1708 
1709  if (form->subowner == newOwnerId)
1710  return;
1711 
1712  if (!object_ownercheck(SubscriptionRelationId, form->oid, GetUserId()))
1714  NameStr(form->subname));
1715 
1716  /* New owner must be a superuser */
1717  if (!superuser_arg(newOwnerId))
1718  ereport(ERROR,
1719  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1720  errmsg("permission denied to change owner of subscription \"%s\"",
1721  NameStr(form->subname)),
1722  errhint("The owner of a subscription must be a superuser.")));
1723 
1724  form->subowner = newOwnerId;
1725  CatalogTupleUpdate(rel, &tup->t_self, tup);
1726 
1727  /* Update owner dependency reference */
1728  changeDependencyOnOwner(SubscriptionRelationId,
1729  form->oid,
1730  newOwnerId);
1731 
1732  InvokeObjectPostAlterHook(SubscriptionRelationId,
1733  form->oid, 0);
1734 
1736 }
#define NameStr(name)
Definition: c.h:682
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:313
bool superuser_arg(Oid roleid)
Definition: superuser.c:56

References aclcheck_error(), ACLCHECK_NOT_OWNER, ApplyLauncherWakeupAtCommit(), CatalogTupleUpdate(), changeDependencyOnOwner(), ereport, errcode(), errhint(), errmsg(), ERROR, GETSTRUCT, GetUserId(), InvokeObjectPostAlterHook, NameStr, object_ownercheck(), OBJECT_SUBSCRIPTION, superuser_arg(), and HeapTupleData::t_self.

Referenced by AlterSubscriptionOwner(), and AlterSubscriptionOwner_oid().

◆ AlterSubscriptionOwner_oid()

void AlterSubscriptionOwner_oid ( Oid  subid,
Oid  newOwnerId 
)

Definition at line 1778 of file subscriptioncmds.c.

1779 {
1780  HeapTuple tup;
1781  Relation rel;
1782 
1783  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1784 
1786 
1787  if (!HeapTupleIsValid(tup))
1788  ereport(ERROR,
1789  (errcode(ERRCODE_UNDEFINED_OBJECT),
1790  errmsg("subscription with OID %u does not exist", subid)));
1791 
1792  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1793 
1794  heap_freetuple(tup);
1795 
1797 }
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ SUBSCRIPTIONOID
Definition: syscache.h:99

References AlterSubscriptionOwner_internal(), ereport, errcode(), errmsg(), ERROR, heap_freetuple(), HeapTupleIsValid, ObjectIdGetDatum(), RowExclusiveLock, SearchSysCacheCopy1, SUBSCRIPTIONOID, table_close(), and table_open().

Referenced by shdepReassignOwned().

◆ check_duplicates_in_publist()

static void check_duplicates_in_publist ( List publist,
Datum datums 
)
static

Definition at line 2032 of file subscriptioncmds.c.

2033 {
2034  ListCell *cell;
2035  int j = 0;
2036 
2037  foreach(cell, publist)
2038  {
2039  char *name = strVal(lfirst(cell));
2040  ListCell *pcell;
2041 
2042  foreach(pcell, publist)
2043  {
2044  char *pname = strVal(lfirst(pcell));
2045 
2046  if (pcell == cell)
2047  break;
2048 
2049  if (strcmp(name, pname) == 0)
2050  ereport(ERROR,
2052  errmsg("publication name \"%s\" used more than once",
2053  pname)));
2054  }
2055 
2056  if (datums)
2057  datums[j++] = CStringGetTextDatum(name);
2058  }
2059 }
int j
Definition: isn.c:74
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define strVal(v)
Definition: value.h:82

References CStringGetTextDatum, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, j, lfirst, name, and strVal.

Referenced by merge_publications(), and publicationListToArray().

◆ check_publications()

static void check_publications ( WalReceiverConn wrconn,
List publications 
)
static

Definition at line 443 of file subscriptioncmds.c.

444 {
446  StringInfo cmd;
447  TupleTableSlot *slot;
448  List *publicationsCopy = NIL;
449  Oid tableRow[1] = {TEXTOID};
450 
451  cmd = makeStringInfo();
452  appendStringInfoString(cmd, "SELECT t.pubname FROM\n"
453  " pg_catalog.pg_publication t WHERE\n"
454  " t.pubname IN (");
455  get_publications_str(publications, cmd, true);
456  appendStringInfoChar(cmd, ')');
457 
458  res = walrcv_exec(wrconn, cmd->data, 1, tableRow);
459  pfree(cmd->data);
460  pfree(cmd);
461 
462  if (res->status != WALRCV_OK_TUPLES)
463  ereport(ERROR,
464  errmsg("could not receive list of publications from the publisher: %s",
465  res->err));
466 
467  publicationsCopy = list_copy(publications);
468 
469  /* Process publication(s). */
470  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
471  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
472  {
473  char *pubname;
474  bool isnull;
475 
476  pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
477  Assert(!isnull);
478 
479  /* Delete the publication present in publisher from the list. */
480  publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
481  ExecClearTuple(slot);
482  }
483 
485 
487 
488  if (list_length(publicationsCopy))
489  {
490  /* Prepare the list of non-existent publication(s) for error message. */
491  StringInfo pubnames = makeStringInfo();
492 
493  get_publications_str(publicationsCopy, pubnames, false);
495  errcode(ERRCODE_UNDEFINED_OBJECT),
496  errmsg_plural("publication %s does not exist on the publisher",
497  "publications %s do not exist on the publisher",
498  list_length(publicationsCopy),
499  pubnames->data));
500  }
501 }
#define TextDatumGetCString(d)
Definition: builtins.h:86
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1016
#define WARNING
Definition: elog.h:32
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
List * list_copy(const List *oldlist)
Definition: list.c:1572
List * list_delete(List *list, void *datum)
Definition: list.c:852
void pfree(void *pointer)
Definition: mcxt.c:1306
#define NIL
Definition: pg_list.h:66
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
static void get_publications_str(List *publications, StringInfo dest, bool quote_literal)
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:433
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:389
String * makeString(char *str)
Definition: value.c:63
@ WALRCV_OK_TUPLES
Definition: walreceiver.h:207
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:440
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:434

References appendStringInfoChar(), appendStringInfoString(), Assert(), StringInfoData::data, ereport, errcode(), errmsg(), errmsg_plural(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), get_publications_str(), list_copy(), list_delete(), list_length(), MakeSingleTupleTableSlot(), makeString(), makeStringInfo(), NIL, pfree(), res, slot_getattr(), TextDatumGetCString, TTSOpsMinimalTuple, tuplestore_gettupleslot(), walrcv_clear_result(), walrcv_exec, WALRCV_OK_TUPLES, WARNING, and wrconn.

Referenced by AlterSubscription_refresh(), and CreateSubscription().

◆ check_publications_origin()

static void check_publications_origin ( WalReceiverConn wrconn,
List publications,
bool  copydata,
char *  origin,
Oid subrel_local_oids,
int  subrel_count,
char *  subname 
)
static

Definition at line 1814 of file subscriptioncmds.c.

1817 {
1819  StringInfoData cmd;
1820  TupleTableSlot *slot;
1821  Oid tableRow[1] = {TEXTOID};
1822  List *publist = NIL;
1823  int i;
1824 
1825  if (!copydata || !origin ||
1826  (pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) != 0))
1827  return;
1828 
1829  initStringInfo(&cmd);
1831  "SELECT DISTINCT P.pubname AS pubname\n"
1832  "FROM pg_publication P,\n"
1833  " LATERAL pg_get_publication_tables(P.pubname) GPT\n"
1834  " JOIN pg_subscription_rel PS ON (GPT.relid = PS.srrelid),\n"
1835  " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
1836  "WHERE C.oid = GPT.relid AND P.pubname IN (");
1837  get_publications_str(publications, &cmd, true);
1838  appendStringInfoString(&cmd, ")\n");
1839 
1840  /*
1841  * In case of ALTER SUBSCRIPTION ... REFRESH, subrel_local_oids contains
1842  * the list of relation oids that are already present on the subscriber.
1843  * This check should be skipped for these tables.
1844  */
1845  for (i = 0; i < subrel_count; i++)
1846  {
1847  Oid relid = subrel_local_oids[i];
1848  char *schemaname = get_namespace_name(get_rel_namespace(relid));
1849  char *tablename = get_rel_name(relid);
1850 
1851  appendStringInfo(&cmd, "AND NOT (N.nspname = '%s' AND C.relname = '%s')\n",
1852  schemaname, tablename);
1853  }
1854 
1855  res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
1856  pfree(cmd.data);
1857 
1858  if (res->status != WALRCV_OK_TUPLES)
1859  ereport(ERROR,
1860  (errcode(ERRCODE_CONNECTION_FAILURE),
1861  errmsg("could not receive list of replicated tables from the publisher: %s",
1862  res->err)));
1863 
1864  /* Process tables. */
1865  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
1866  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1867  {
1868  char *pubname;
1869  bool isnull;
1870 
1871  pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
1872  Assert(!isnull);
1873 
1874  ExecClearTuple(slot);
1875  publist = list_append_unique(publist, makeString(pubname));
1876  }
1877 
1878  /*
1879  * Log a warning if the publisher has subscribed to the same table from
1880  * some other publisher. We cannot know the origin of data during the
1881  * initial sync. Data origins can be found only from the WAL by looking at
1882  * the origin id.
1883  *
1884  * XXX: For simplicity, we don't check whether the table has any data or
1885  * not. If the table doesn't have any data then we don't need to
1886  * distinguish between data having origin and data not having origin so we
1887  * can avoid logging a warning in that case.
1888  */
1889  if (publist)
1890  {
1891  StringInfo pubnames = makeStringInfo();
1892 
1893  /* Prepare the list of publication(s) for warning message. */
1894  get_publications_str(publist, pubnames, false);
1895  ereport(WARNING,
1896  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1897  errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
1898  subname),
1899  errdetail_plural("Subscribed publication %s is subscribing to other publications.",
1900  "Subscribed publications %s are subscribing to other publications.",
1901  list_length(publist), pubnames->data),
1902  errhint("Verify that initial data copied from the publisher tables did not come from other origins."));
1903  }
1904 
1906 
1908 }
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1131
int i
Definition: isn.c:73
List * list_append_unique(List *list, void *datum)
Definition: list.c:1342
#define LOGICALREP_ORIGIN_NONE
NameData subname
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

References appendStringInfo(), appendStringInfoString(), Assert(), StringInfoData::data, ereport, errcode(), errdetail_plural(), errhint(), errmsg(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), get_namespace_name(), get_publications_str(), get_rel_name(), get_rel_namespace(), i, initStringInfo(), list_append_unique(), list_length(), LOGICALREP_ORIGIN_NONE, MakeSingleTupleTableSlot(), makeString(), makeStringInfo(), NIL, pfree(), pg_strcasecmp(), res, slot_getattr(), subname, TextDatumGetCString, TTSOpsMinimalTuple, tuplestore_gettupleslot(), walrcv_clear_result(), walrcv_exec, WALRCV_OK_TUPLES, WARNING, and wrconn.

Referenced by AlterSubscription_refresh(), and CreateSubscription().

◆ CreateSubscription()

ObjectAddress CreateSubscription ( ParseState pstate,
CreateSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 537 of file subscriptioncmds.c.

539 {
540  Relation rel;
541  ObjectAddress myself;
542  Oid subid;
543  bool nulls[Natts_pg_subscription];
544  Datum values[Natts_pg_subscription];
545  Oid owner = GetUserId();
546  HeapTuple tup;
547  char *conninfo;
548  char originname[NAMEDATALEN];
549  List *publications;
550  bits32 supported_opts;
551  SubOpts opts = {0};
552 
553  /*
554  * Parse and check options.
555  *
556  * Connection and publication should not be specified here.
557  */
558  supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
563  parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
564 
565  /*
566  * Since creating a replication slot is not transactional, rolling back
567  * the transaction leaves the created replication slot. So we cannot run
568  * CREATE SUBSCRIPTION inside a transaction block if creating a
569  * replication slot.
570  */
571  if (opts.create_slot)
572  PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
573 
574  if (!superuser())
575  ereport(ERROR,
576  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
577  errmsg("must be superuser to create subscriptions")));
578 
579  /*
580  * If built with appropriate switch, whine when regression-testing
581  * conventions for subscription names are violated.
582  */
583 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
584  if (strncmp(stmt->subname, "regress_", 8) != 0)
585  elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
586 #endif
587 
588  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
589 
590  /* Check if name is used */
591  subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
593  if (OidIsValid(subid))
594  {
595  ereport(ERROR,
597  errmsg("subscription \"%s\" already exists",
598  stmt->subname)));
599  }
600 
601  if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
602  opts.slot_name == NULL)
603  opts.slot_name = stmt->subname;
604 
605  /* The default for synchronous_commit of subscriptions is off. */
606  if (opts.synchronous_commit == NULL)
607  opts.synchronous_commit = "off";
608 
609  conninfo = stmt->conninfo;
610  publications = stmt->publication;
611 
612  /* Load the library providing us libpq calls. */
613  load_file("libpqwalreceiver", false);
614 
615  /* Check the connection info string. */
616  walrcv_check_conninfo(conninfo);
617 
618  /* Everything ok, form a new tuple. */
619  memset(values, 0, sizeof(values));
620  memset(nulls, false, sizeof(nulls));
621 
622  subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
623  Anum_pg_subscription_oid);
624  values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
625  values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
626  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
627  values[Anum_pg_subscription_subname - 1] =
629  values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
630  values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
631  values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
632  values[Anum_pg_subscription_substream - 1] = BoolGetDatum(opts.streaming);
633  values[Anum_pg_subscription_subtwophasestate - 1] =
634  CharGetDatum(opts.twophase ?
637  values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
638  values[Anum_pg_subscription_subconninfo - 1] =
639  CStringGetTextDatum(conninfo);
640  if (opts.slot_name)
641  values[Anum_pg_subscription_subslotname - 1] =
643  else
644  nulls[Anum_pg_subscription_subslotname - 1] = true;
645  values[Anum_pg_subscription_subsynccommit - 1] =
646  CStringGetTextDatum(opts.synchronous_commit);
647  values[Anum_pg_subscription_subpublications - 1] =
648  publicationListToArray(publications);
649  values[Anum_pg_subscription_suborigin - 1] =
650  CStringGetTextDatum(opts.origin);
651 
652  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
653 
654  /* Insert tuple into catalog. */
655  CatalogTupleInsert(rel, tup);
656  heap_freetuple(tup);
657 
658  recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
659 
660  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
661  replorigin_create(originname);
662 
663  /*
664  * Connect to remote side to execute requested commands and fetch table
665  * info.
666  */
667  if (opts.connect)
668  {
669  char *err;
671  List *tables;
672  ListCell *lc;
673  char table_state;
674 
675  /* Try to connect to the publisher. */
676  wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
677  if (!wrconn)
678  ereport(ERROR,
679  (errcode(ERRCODE_CONNECTION_FAILURE),
680  errmsg("could not connect to the publisher: %s", err)));
681 
682  PG_TRY();
683  {
684  check_publications(wrconn, publications);
685  check_publications_origin(wrconn, publications, opts.copy_data,
686  opts.origin, NULL, 0, stmt->subname);
687 
688  /*
689  * Set sync state based on if we were asked to do data copy or
690  * not.
691  */
692  table_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
693 
694  /*
695  * Get the table list from publisher and build local table status
696  * info.
697  */
698  tables = fetch_table_list(wrconn, publications);
699  foreach(lc, tables)
700  {
701  RangeVar *rv = (RangeVar *) lfirst(lc);
702  Oid relid;
703 
704  relid = RangeVarGetRelid(rv, AccessShareLock, false);
705 
706  /* Check for supported relkind. */
708  rv->schemaname, rv->relname);
709 
710  AddSubscriptionRelState(subid, relid, table_state,
712  }
713 
714  /*
715  * If requested, create permanent slot for the subscription. We
716  * won't use the initial snapshot for anything, so no need to
717  * export it.
718  */
719  if (opts.create_slot)
720  {
721  bool twophase_enabled = false;
722 
723  Assert(opts.slot_name);
724 
725  /*
726  * Even if two_phase is set, don't create the slot with
727  * two-phase enabled. Will enable it once all the tables are
728  * synced and ready. This avoids race-conditions like prepared
729  * transactions being skipped due to changes not being applied
730  * due to checks in should_apply_changes_for_rel() when
731  * tablesync for the corresponding tables are in progress. See
732  * comments atop worker.c.
733  *
734  * Note that if tables were specified but copy_data is false
735  * then it is safe to enable two_phase up-front because those
736  * tables are already initially in READY state. When the
737  * subscription has no tables, we leave the twophase state as
738  * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
739  * PUBLICATION to work.
740  */
741  if (opts.twophase && !opts.copy_data && tables != NIL)
742  twophase_enabled = true;
743 
744  walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
745  CRS_NOEXPORT_SNAPSHOT, NULL);
746 
747  if (twophase_enabled)
749 
750  ereport(NOTICE,
751  (errmsg("created replication slot \"%s\" on publisher",
752  opts.slot_name)));
753  }
754  }
755  PG_FINALLY();
756  {
758  }
759  PG_END_TRY();
760  }
761  else
763  (errmsg("subscription was created, but is not connected"),
764  errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and refresh the subscription.")));
765 
767 
769 
770  if (opts.enabled)
772 
773  ObjectAddressSet(myself, SubscriptionRelationId, subid);
774 
775  InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
776 
777  return myself;
778 }
#define OidIsValid(objectId)
Definition: c.h:711
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:393
#define NOTICE
Definition: elog.h:31
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:252
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define LOGICALREP_TWOPHASE_STATE_PENDING
void pgstat_create_subscription(Oid subid)
static Datum CharGetDatum(char X)
Definition: postgres.h:470
#define SUBOPT_CREATE_SLOT
#define SUBOPT_TWOPHASE_COMMIT
#define SUBOPT_CONNECT
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:199
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition: tablesync.c:1566
#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
Definition: walreceiver.h:430
@ CRS_NOEXPORT_SNAPSHOT
Definition: walsender.h:23

References AccessShareLock, AddSubscriptionRelState(), ApplyLauncherWakeupAtCommit(), Assert(), BoolGetDatum(), CatalogTupleInsert(), CharGetDatum(), check_publications(), check_publications_origin(), CheckSubscriptionRelkind(), CreateSubscriptionStmt::conninfo, CRS_NOEXPORT_SNAPSHOT, CStringGetDatum(), CStringGetTextDatum, DirectFunctionCall1, elog(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, fetch_table_list(), get_rel_relkind(), GetNewOidWithIndex(), GetSysCacheOid2, GetUserId(), heap_form_tuple(), heap_freetuple(), InvalidOid, InvalidXLogRecPtr, InvokeObjectPostCreateHook, IsSet, lfirst, load_file(), LOGICALREP_TWOPHASE_STATE_DISABLED, LOGICALREP_TWOPHASE_STATE_ENABLED, LOGICALREP_TWOPHASE_STATE_PENDING, LSNGetDatum(), MyDatabaseId, NAMEDATALEN, namein(), NIL, NOTICE, ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, CreateSubscriptionStmt::options, opts, parse_subscription_options(), PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_create_subscription(), PreventInTransactionBlock(), CreateSubscriptionStmt::publication, publicationListToArray(), RangeVarGetRelid, recordDependencyOnOwner(), RelationGetDescr, RangeVar::relname, ReplicationOriginNameForLogicalRep(), replorigin_create(), RowExclusiveLock, RangeVar::schemaname, CreateSubscriptionStmt::subname, SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_ORIGIN, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, SUBSCRIPTIONNAME, superuser(), table_close(), table_open(), UpdateTwoPhaseState(), values, walrcv_check_conninfo, walrcv_connect, walrcv_create_slot, walrcv_disconnect, WARNING, and wrconn.

Referenced by ProcessUtilitySlow().

◆ DropSubscription()

void DropSubscription ( DropSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 1372 of file subscriptioncmds.c.

1373 {
1374  Relation rel;
1375  ObjectAddress myself;
1376  HeapTuple tup;
1377  Oid subid;
1378  Datum datum;
1379  bool isnull;
1380  char *subname;
1381  char *conninfo;
1382  char *slotname;
1383  List *subworkers;
1384  ListCell *lc;
1385  char originname[NAMEDATALEN];
1386  char *err = NULL;
1388  Form_pg_subscription form;
1389  List *rstates;
1390 
1391  /*
1392  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1393  * launcher doesn't restart new worker during dropping the subscription
1394  */
1395  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1396 
1398  CStringGetDatum(stmt->subname));
1399 
1400  if (!HeapTupleIsValid(tup))
1401  {
1402  table_close(rel, NoLock);
1403 
1404  if (!stmt->missing_ok)
1405  ereport(ERROR,
1406  (errcode(ERRCODE_UNDEFINED_OBJECT),
1407  errmsg("subscription \"%s\" does not exist",
1408  stmt->subname)));
1409  else
1410  ereport(NOTICE,
1411  (errmsg("subscription \"%s\" does not exist, skipping",
1412  stmt->subname)));
1413 
1414  return;
1415  }
1416 
1417  form = (Form_pg_subscription) GETSTRUCT(tup);
1418  subid = form->oid;
1419 
1420  /* must be owner */
1421  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1423  stmt->subname);
1424 
1425  /* DROP hook for the subscription being removed */
1426  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1427 
1428  /*
1429  * Lock the subscription so nobody else can do anything with it (including
1430  * the replication workers).
1431  */
1432  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1433 
1434  /* Get subname */
1435  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1436  Anum_pg_subscription_subname, &isnull);
1437  Assert(!isnull);
1438  subname = pstrdup(NameStr(*DatumGetName(datum)));
1439 
1440  /* Get conninfo */
1441  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1442  Anum_pg_subscription_subconninfo, &isnull);
1443  Assert(!isnull);
1444  conninfo = TextDatumGetCString(datum);
1445 
1446  /* Get slotname */
1447  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1448  Anum_pg_subscription_subslotname, &isnull);
1449  if (!isnull)
1450  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1451  else
1452  slotname = NULL;
1453 
1454  /*
1455  * Since dropping a replication slot is not transactional, the replication
1456  * slot stays dropped even if the transaction rolls back. So we cannot
1457  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1458  * replication slot. Also, in this case, we report a message for dropping
1459  * the subscription to the cumulative stats system.
1460  *
1461  * XXX The command name should really be something like "DROP SUBSCRIPTION
1462  * of a subscription that is associated with a replication slot", but we
1463  * don't have the proper facilities for that.
1464  */
1465  if (slotname)
1466  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1467 
1468  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1469  EventTriggerSQLDropAddObject(&myself, true, true);
1470 
1471  /* Remove the tuple from catalog. */
1472  CatalogTupleDelete(rel, &tup->t_self);
1473 
1474  ReleaseSysCache(tup);
1475 
1476  /*
1477  * Stop all the subscription workers immediately.
1478  *
1479  * This is necessary if we are dropping the replication slot, so that the
1480  * slot becomes accessible.
1481  *
1482  * It is also necessary if the subscription is disabled and was disabled
1483  * in the same transaction. Then the workers haven't seen the disabling
1484  * yet and will still be running, leading to hangs later when we want to
1485  * drop the replication origin. If the subscription was disabled before
1486  * this transaction, then there shouldn't be any workers left, so this
1487  * won't make a difference.
1488  *
1489  * New workers won't be started because we hold an exclusive lock on the
1490  * subscription till the end of the transaction.
1491  */
1492  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1493  subworkers = logicalrep_workers_find(subid, false);
1494  LWLockRelease(LogicalRepWorkerLock);
1495  foreach(lc, subworkers)
1496  {
1498 
1500  }
1501  list_free(subworkers);
1502 
1503  /*
1504  * Cleanup of tablesync replication origins.
1505  *
1506  * Any READY-state relations would already have dealt with clean-ups.
1507  *
1508  * Note that the state can't change because we have already stopped both
1509  * the apply and tablesync workers and they can't restart because of
1510  * exclusive lock on the subscription.
1511  */
1512  rstates = GetSubscriptionRelations(subid, true);
1513  foreach(lc, rstates)
1514  {
1516  Oid relid = rstate->relid;
1517 
1518  /* Only cleanup resources of tablesync workers */
1519  if (!OidIsValid(relid))
1520  continue;
1521 
1522  /*
1523  * Drop the tablesync's origin tracking if exists.
1524  *
1525  * It is possible that the origin is not yet created for tablesync
1526  * worker so passing missing_ok = true. This can happen for the states
1527  * before SUBREL_STATE_FINISHEDCOPY.
1528  */
1529  ReplicationOriginNameForLogicalRep(subid, relid, originname,
1530  sizeof(originname));
1531  replorigin_drop_by_name(originname, true, false);
1532  }
1533 
1534  /* Clean up dependencies */
1535  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1536 
1537  /* Remove any associated relation synchronization states. */
1539 
1540  /* Remove the origin tracking if exists. */
1541  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
1542  replorigin_drop_by_name(originname, true, false);
1543 
1544  /*
1545  * If there is no slot associated with the subscription, we can finish
1546  * here.
1547  */
1548  if (!slotname && rstates == NIL)
1549  {
1550  table_close(rel, NoLock);
1551  return;
1552  }
1553 
1554  /*
1555  * Try to acquire the connection necessary for dropping slots.
1556  *
1557  * Note: If the slotname is NONE/NULL then we allow the command to finish
1558  * and users need to manually cleanup the apply and tablesync worker slots
1559  * later.
1560  *
1561  * This has to be at the end because otherwise if there is an error while
1562  * doing the database operations we won't be able to rollback dropped
1563  * slot.
1564  */
1565  load_file("libpqwalreceiver", false);
1566 
1567  wrconn = walrcv_connect(conninfo, true, subname, &err);
1568  if (wrconn == NULL)
1569  {
1570  if (!slotname)
1571  {
1572  /* be tidy */
1573  list_free(rstates);
1574  table_close(rel, NoLock);
1575  return;
1576  }
1577  else
1578  {
1579  ReportSlotConnectionError(rstates, subid, slotname, err);
1580  }
1581  }
1582 
1583  PG_TRY();
1584  {
1585  foreach(lc, rstates)
1586  {
1588  Oid relid = rstate->relid;
1589 
1590  /* Only cleanup resources of tablesync workers */
1591  if (!OidIsValid(relid))
1592  continue;
1593 
1594  /*
1595  * Drop the tablesync slots associated with removed tables.
1596  *
1597  * For SYNCDONE/READY states, the tablesync slot is known to have
1598  * already been dropped by the tablesync worker.
1599  *
1600  * For other states, there is no certainty, maybe the slot does
1601  * not exist yet. Also, if we fail after removing some of the
1602  * slots, next time, it will again try to drop already dropped
1603  * slots and fail. For these reasons, we allow missing_ok = true
1604  * for the drop.
1605  */
1606  if (rstate->state != SUBREL_STATE_SYNCDONE)
1607  {
1608  char syncslotname[NAMEDATALEN] = {0};
1609 
1610  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1611  sizeof(syncslotname));
1612  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1613  }
1614  }
1615 
1616  list_free(rstates);
1617 
1618  /*
1619  * If there is a slot associated with the subscription, then drop the
1620  * replication slot at the publisher.
1621  */
1622  if (slotname)
1623  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1624  }
1625  PG_FINALLY();
1626  {
1628  }
1629  PG_END_TRY();
1630 
1631  /*
1632  * Tell the cumulative stats system that the subscription is getting
1633  * dropped.
1634  */
1635  pgstat_drop_subscription(subid);
1636 
1637  table_close(rel, NoLock);
1638 }
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:243
void list_free(List *list)
Definition: list.c:1545
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1194
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1802
@ LW_SHARED
Definition: lwlock.h:113
char * pstrdup(const char *in)
Definition: mcxt.c:1483
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:182
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1002
void pgstat_drop_subscription(Oid subid)
static Name DatumGetName(Datum X)
Definition: postgres.h:708
static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1184

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, Assert(), CatalogTupleDelete(), CStringGetDatum(), DatumGetName(), deleteSharedDependencyRecordsFor(), ereport, errcode(), errmsg(), ERROR, EventTriggerSQLDropAddObject(), GETSTRUCT, GetSubscriptionRelations(), GetUserId(), HeapTupleIsValid, InvalidOid, InvokeObjectDropHook, lfirst, list_free(), load_file(), LockSharedObject(), logicalrep_worker_stop(), logicalrep_workers_find(), LW_SHARED, LWLockAcquire(), LWLockRelease(), DropSubscriptionStmt::missing_ok, MyDatabaseId, NAMEDATALEN, NameStr, NIL, NoLock, NOTICE, object_ownercheck(), OBJECT_SUBSCRIPTION, ObjectAddressSet, OidIsValid, PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_drop_subscription(), PreventInTransactionBlock(), pstrdup(), ReleaseSysCache(), SubscriptionRelState::relid, LogicalRepWorker::relid, RemoveSubscriptionRel(), ReplicationOriginNameForLogicalRep(), ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), replorigin_drop_by_name(), ReportSlotConnectionError(), SearchSysCache2(), SubscriptionRelState::state, LogicalRepWorker::subid, subname, DropSubscriptionStmt::subname, SUBSCRIPTIONNAME, SUBSCRIPTIONOID, SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), TextDatumGetCString, walrcv_connect, walrcv_disconnect, and wrconn.

Referenced by ProcessUtilitySlow().

◆ fetch_table_list()

static List * fetch_table_list ( WalReceiverConn wrconn,
List publications 
)
static

Definition at line 1920 of file subscriptioncmds.c.

1921 {
1923  StringInfoData cmd;
1924  TupleTableSlot *slot;
1925  Oid tableRow[3] = {TEXTOID, TEXTOID, NAMEARRAYOID};
1926  List *tablelist = NIL;
1927  bool check_columnlist = (walrcv_server_version(wrconn) >= 150000);
1928 
1929  initStringInfo(&cmd);
1930  appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename \n");
1931 
1932  /* Get column lists for each relation if the publisher supports it */
1933  if (check_columnlist)
1934  appendStringInfoString(&cmd, ", t.attnames\n");
1935 
1936  appendStringInfoString(&cmd, "FROM pg_catalog.pg_publication_tables t\n"
1937  " WHERE t.pubname IN (");
1938  get_publications_str(publications, &cmd, true);
1939  appendStringInfoChar(&cmd, ')');
1940 
1941  res = walrcv_exec(wrconn, cmd.data, check_columnlist ? 3 : 2, tableRow);
1942  pfree(cmd.data);
1943 
1944  if (res->status != WALRCV_OK_TUPLES)
1945  ereport(ERROR,
1946  (errcode(ERRCODE_CONNECTION_FAILURE),
1947  errmsg("could not receive list of replicated tables from the publisher: %s",
1948  res->err)));
1949 
1950  /* Process tables. */
1951  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
1952  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1953  {
1954  char *nspname;
1955  char *relname;
1956  bool isnull;
1957  RangeVar *rv;
1958 
1959  nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
1960  Assert(!isnull);
1961  relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
1962  Assert(!isnull);
1963 
1964  rv = makeRangeVar(nspname, relname, -1);
1965 
1966  if (check_columnlist && list_member(tablelist, rv))
1967  ereport(ERROR,
1968  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1969  errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
1970  nspname, relname));
1971  else
1972  tablelist = lappend(tablelist, rv);
1973 
1974  ExecClearTuple(slot);
1975  }
1977 
1979 
1980  return tablelist;
1981 }
List * lappend(List *list, void *datum)
Definition: list.c:338
bool list_member(const List *list, const void *datum)
Definition: list.c:660
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
NameData relname
Definition: pg_class.h:38
#define walrcv_server_version(conn)
Definition: walreceiver.h:418

References appendStringInfoChar(), appendStringInfoString(), Assert(), StringInfoData::data, ereport, errcode(), errmsg(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), get_publications_str(), initStringInfo(), lappend(), list_member(), makeRangeVar(), MakeSingleTupleTableSlot(), NIL, pfree(), relname, res, slot_getattr(), TextDatumGetCString, TTSOpsMinimalTuple, tuplestore_gettupleslot(), walrcv_clear_result(), walrcv_exec, WALRCV_OK_TUPLES, walrcv_server_version, and wrconn.

Referenced by AlterSubscription_refresh(), and CreateSubscription().

◆ get_publications_str()

static void get_publications_str ( List publications,
StringInfo  dest,
bool  quote_literal 
)
static

Definition at line 412 of file subscriptioncmds.c.

413 {
414  ListCell *lc;
415  bool first = true;
416 
417  Assert(publications != NIL);
418 
419  foreach(lc, publications)
420  {
421  char *pubname = strVal(lfirst(lc));
422 
423  if (first)
424  first = false;
425  else
427 
428  if (quote_literal)
430  else
431  {
433  appendStringInfoString(dest, pubname);
435  }
436  }
437 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
Datum quote_literal(PG_FUNCTION_ARGS)
Definition: quote.c:77

References appendStringInfoChar(), appendStringInfoString(), Assert(), generate_unaccent_rules::dest, lfirst, NIL, quote_literal(), quote_literal_cstr(), and strVal.

Referenced by check_publications(), check_publications_origin(), and fetch_table_list().

◆ merge_publications()

static List * merge_publications ( List oldpublist,
List newpublist,
bool  addpub,
const char *  subname 
)
static

Definition at line 2072 of file subscriptioncmds.c.

2073 {
2074  ListCell *lc;
2075 
2076  oldpublist = list_copy(oldpublist);
2077 
2078  check_duplicates_in_publist(newpublist, NULL);
2079 
2080  foreach(lc, newpublist)
2081  {
2082  char *name = strVal(lfirst(lc));
2083  ListCell *lc2;
2084  bool found = false;
2085 
2086  foreach(lc2, oldpublist)
2087  {
2088  char *pubname = strVal(lfirst(lc2));
2089 
2090  if (strcmp(name, pubname) == 0)
2091  {
2092  found = true;
2093  if (addpub)
2094  ereport(ERROR,
2096  errmsg("publication \"%s\" is already in subscription \"%s\"",
2097  name, subname)));
2098  else
2099  oldpublist = foreach_delete_current(oldpublist, lc2);
2100 
2101  break;
2102  }
2103  }
2104 
2105  if (addpub && !found)
2106  oldpublist = lappend(oldpublist, makeString(name));
2107  else if (!addpub && !found)
2108  ereport(ERROR,
2109  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2110  errmsg("publication \"%s\" is not in subscription \"%s\"",
2111  name, subname)));
2112  }
2113 
2114  /*
2115  * XXX Probably no strong reason for this, but for now it's to make ALTER
2116  * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
2117  */
2118  if (!oldpublist)
2119  ereport(ERROR,
2120  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2121  errmsg("cannot drop all the publications from a subscription")));
2122 
2123  return oldpublist;
2124 }
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:388
static void check_duplicates_in_publist(List *publist, Datum *datums)

References check_duplicates_in_publist(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, foreach_delete_current, lappend(), lfirst, list_copy(), makeString(), name, strVal, and subname.

Referenced by AlterSubscription().

◆ parse_subscription_options()

static void parse_subscription_options ( ParseState pstate,
List stmt_options,
bits32  supported_opts,
SubOpts opts 
)
static

Definition at line 111 of file subscriptioncmds.c.

113 {
114  ListCell *lc;
115 
116  /* Start out with cleared opts. */
117  memset(opts, 0, sizeof(SubOpts));
118 
119  /* caller must expect some option */
120  Assert(supported_opts != 0);
121 
122  /* If connect option is supported, these others also need to be. */
123  Assert(!IsSet(supported_opts, SUBOPT_CONNECT) ||
124  IsSet(supported_opts, SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
126 
127  /* Set default values for the supported options. */
128  if (IsSet(supported_opts, SUBOPT_CONNECT))
129  opts->connect = true;
130  if (IsSet(supported_opts, SUBOPT_ENABLED))
131  opts->enabled = true;
132  if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
133  opts->create_slot = true;
134  if (IsSet(supported_opts, SUBOPT_COPY_DATA))
135  opts->copy_data = true;
136  if (IsSet(supported_opts, SUBOPT_REFRESH))
137  opts->refresh = true;
138  if (IsSet(supported_opts, SUBOPT_BINARY))
139  opts->binary = false;
140  if (IsSet(supported_opts, SUBOPT_STREAMING))
141  opts->streaming = false;
142  if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
143  opts->twophase = false;
144  if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
145  opts->disableonerr = false;
146  if (IsSet(supported_opts, SUBOPT_ORIGIN))
148 
149  /* Parse options */
150  foreach(lc, stmt_options)
151  {
152  DefElem *defel = (DefElem *) lfirst(lc);
153 
154  if (IsSet(supported_opts, SUBOPT_CONNECT) &&
155  strcmp(defel->defname, "connect") == 0)
156  {
157  if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
158  errorConflictingDefElem(defel, pstate);
159 
160  opts->specified_opts |= SUBOPT_CONNECT;
161  opts->connect = defGetBoolean(defel);
162  }
163  else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
164  strcmp(defel->defname, "enabled") == 0)
165  {
166  if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
167  errorConflictingDefElem(defel, pstate);
168 
169  opts->specified_opts |= SUBOPT_ENABLED;
170  opts->enabled = defGetBoolean(defel);
171  }
172  else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
173  strcmp(defel->defname, "create_slot") == 0)
174  {
175  if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
176  errorConflictingDefElem(defel, pstate);
177 
178  opts->specified_opts |= SUBOPT_CREATE_SLOT;
179  opts->create_slot = defGetBoolean(defel);
180  }
181  else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
182  strcmp(defel->defname, "slot_name") == 0)
183  {
184  if (IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
185  errorConflictingDefElem(defel, pstate);
186 
187  opts->specified_opts |= SUBOPT_SLOT_NAME;
188  opts->slot_name = defGetString(defel);
189 
190  /* Setting slot_name = NONE is treated as no slot name. */
191  if (strcmp(opts->slot_name, "none") == 0)
192  opts->slot_name = NULL;
193  else
195  }
196  else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
197  strcmp(defel->defname, "copy_data") == 0)
198  {
199  if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
200  errorConflictingDefElem(defel, pstate);
201 
202  opts->specified_opts |= SUBOPT_COPY_DATA;
203  opts->copy_data = defGetBoolean(defel);
204  }
205  else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
206  strcmp(defel->defname, "synchronous_commit") == 0)
207  {
208  if (IsSet(opts->specified_opts, SUBOPT_SYNCHRONOUS_COMMIT))
209  errorConflictingDefElem(defel, pstate);
210 
211  opts->specified_opts |= SUBOPT_SYNCHRONOUS_COMMIT;
212  opts->synchronous_commit = defGetString(defel);
213 
214  /* Test if the given value is valid for synchronous_commit GUC. */
215  (void) set_config_option("synchronous_commit", opts->synchronous_commit,
217  false, 0, false);
218  }
219  else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
220  strcmp(defel->defname, "refresh") == 0)
221  {
222  if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
223  errorConflictingDefElem(defel, pstate);
224 
225  opts->specified_opts |= SUBOPT_REFRESH;
226  opts->refresh = defGetBoolean(defel);
227  }
228  else if (IsSet(supported_opts, SUBOPT_BINARY) &&
229  strcmp(defel->defname, "binary") == 0)
230  {
231  if (IsSet(opts->specified_opts, SUBOPT_BINARY))
232  errorConflictingDefElem(defel, pstate);
233 
234  opts->specified_opts |= SUBOPT_BINARY;
235  opts->binary = defGetBoolean(defel);
236  }
237  else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
238  strcmp(defel->defname, "streaming") == 0)
239  {
240  if (IsSet(opts->specified_opts, SUBOPT_STREAMING))
241  errorConflictingDefElem(defel, pstate);
242 
243  opts->specified_opts |= SUBOPT_STREAMING;
244  opts->streaming = defGetBoolean(defel);
245  }
246  else if (strcmp(defel->defname, "two_phase") == 0)
247  {
248  /*
249  * Do not allow toggling of two_phase option. Doing so could cause
250  * missing of transactions and lead to an inconsistent replica.
251  * See comments atop worker.c
252  *
253  * Note: Unsupported twophase indicates that this call originated
254  * from AlterSubscription.
255  */
256  if (!IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
257  ereport(ERROR,
258  (errcode(ERRCODE_SYNTAX_ERROR),
259  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
260 
261  if (IsSet(opts->specified_opts, SUBOPT_TWOPHASE_COMMIT))
262  errorConflictingDefElem(defel, pstate);
263 
264  opts->specified_opts |= SUBOPT_TWOPHASE_COMMIT;
265  opts->twophase = defGetBoolean(defel);
266  }
267  else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
268  strcmp(defel->defname, "disable_on_error") == 0)
269  {
270  if (IsSet(opts->specified_opts, SUBOPT_DISABLE_ON_ERR))
271  errorConflictingDefElem(defel, pstate);
272 
273  opts->specified_opts |= SUBOPT_DISABLE_ON_ERR;
274  opts->disableonerr = defGetBoolean(defel);
275  }
276  else if (IsSet(supported_opts, SUBOPT_ORIGIN) &&
277  strcmp(defel->defname, "origin") == 0)
278  {
279  if (IsSet(opts->specified_opts, SUBOPT_ORIGIN))
280  errorConflictingDefElem(defel, pstate);
281 
282  opts->specified_opts |= SUBOPT_ORIGIN;
283  pfree(opts->origin);
284 
285  /*
286  * Even though the "origin" parameter allows only "none" and "any"
287  * values, it is implemented as a string type so that the
288  * parameter can be extended in future versions to support
289  * filtering using origin names specified by the user.
290  */
291  opts->origin = defGetString(defel);
292 
293  if ((pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_NONE) != 0) &&
294  (pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_ANY) != 0))
295  ereport(ERROR,
296  errcode(ERRCODE_INVALID_PARAMETER_VALUE),
297  errmsg("unrecognized origin value: \"%s\"", opts->origin));
298  }
299  else if (IsSet(supported_opts, SUBOPT_LSN) &&
300  strcmp(defel->defname, "lsn") == 0)
301  {
302  char *lsn_str = defGetString(defel);
303  XLogRecPtr lsn;
304 
305  if (IsSet(opts->specified_opts, SUBOPT_LSN))
306  errorConflictingDefElem(defel, pstate);
307 
308  /* Setting lsn = NONE is treated as resetting LSN */
309  if (strcmp(lsn_str, "none") == 0)
310  lsn = InvalidXLogRecPtr;
311  else
312  {
313  /* Parse the argument as LSN */
315  CStringGetDatum(lsn_str)));
316 
317  if (XLogRecPtrIsInvalid(lsn))
318  ereport(ERROR,
319  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
320  errmsg("invalid WAL location (LSN): %s", lsn_str)));
321  }
322 
323  opts->specified_opts |= SUBOPT_LSN;
324  opts->lsn = lsn;
325  }
326  else
327  ereport(ERROR,
328  (errcode(ERRCODE_SYNTAX_ERROR),
329  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
330  }
331 
332  /*
333  * We've been explicitly asked to not connect, that requires some
334  * additional processing.
335  */
336  if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
337  {
338  /* Check for incompatible options from the user. */
339  if (opts->enabled &&
340  IsSet(opts->specified_opts, SUBOPT_ENABLED))
341  ereport(ERROR,
342  (errcode(ERRCODE_SYNTAX_ERROR),
343  /*- translator: both %s are strings of the form "option = value" */
344  errmsg("%s and %s are mutually exclusive options",
345  "connect = false", "enabled = true")));
346 
347  if (opts->create_slot &&
348  IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
349  ereport(ERROR,
350  (errcode(ERRCODE_SYNTAX_ERROR),
351  errmsg("%s and %s are mutually exclusive options",
352  "connect = false", "create_slot = true")));
353 
354  if (opts->copy_data &&
355  IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
356  ereport(ERROR,
357  (errcode(ERRCODE_SYNTAX_ERROR),
358  errmsg("%s and %s are mutually exclusive options",
359  "connect = false", "copy_data = true")));
360 
361  /* Change the defaults of other options. */
362  opts->enabled = false;
363  opts->create_slot = false;
364  opts->copy_data = false;
365  }
366 
367  /*
368  * Do additional checking for disallowed combination when slot_name = NONE
369  * was used.
370  */
371  if (!opts->slot_name &&
372  IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
373  {
374  if (opts->enabled)
375  {
376  if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
377  ereport(ERROR,
378  (errcode(ERRCODE_SYNTAX_ERROR),
379  /*- translator: both %s are strings of the form "option = value" */
380  errmsg("%s and %s are mutually exclusive options",
381  "slot_name = NONE", "enabled = true")));
382  else
383  ereport(ERROR,
384  (errcode(ERRCODE_SYNTAX_ERROR),
385  /*- translator: both %s are strings of the form "option = value" */
386  errmsg("subscription with %s must also set %s",
387  "slot_name = NONE", "enabled = false")));
388  }
389 
390  if (opts->create_slot)
391  {
392  if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
393  ereport(ERROR,
394  (errcode(ERRCODE_SYNTAX_ERROR),
395  /*- translator: both %s are strings of the form "option = value" */
396  errmsg("%s and %s are mutually exclusive options",
397  "slot_name = NONE", "create_slot = true")));
398  else
399  ereport(ERROR,
400  (errcode(ERRCODE_SYNTAX_ERROR),
401  /*- translator: both %s are strings of the form "option = value" */
402  errmsg("subscription with %s must also set %s",
403  "slot_name = NONE", "create_slot = false")));
404  }
405  }
406 }
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:385
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:3266
@ GUC_ACTION_SET
Definition: guc.h:197
@ PGC_S_TEST
Definition: guc.h:121
@ PGC_BACKEND
Definition: guc.h:73
Datum pg_lsn_in(PG_FUNCTION_ARGS)
Definition: pg_lsn.c:64
static XLogRecPtr DatumGetLSN(Datum X)
Definition: pg_lsn.h:22
#define LOGICALREP_ORIGIN_ANY
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:198
char * defname
Definition: parsenodes.h:775

References Assert(), CStringGetDatum(), DatumGetLSN(), defGetBoolean(), defGetString(), DefElem::defname, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, errorConflictingDefElem(), GUC_ACTION_SET, InvalidXLogRecPtr, IsSet, lfirst, LOGICALREP_ORIGIN_ANY, LOGICALREP_ORIGIN_NONE, opts, pfree(), pg_lsn_in(), pg_strcasecmp(), PGC_BACKEND, PGC_S_TEST, pstrdup(), ReplicationSlotValidateName(), set_config_option(), SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_LSN, SUBOPT_ORIGIN, SUBOPT_REFRESH, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, and XLogRecPtrIsInvalid.

Referenced by AlterSubscription(), and CreateSubscription().

◆ publicationListToArray()

static Datum publicationListToArray ( List publist)
static

Definition at line 507 of file subscriptioncmds.c.

508 {
509  ArrayType *arr;
510  Datum *datums;
511  MemoryContext memcxt;
512  MemoryContext oldcxt;
513 
514  /* Create memory context for temporary allocations. */
516  "publicationListToArray to array",
518  oldcxt = MemoryContextSwitchTo(memcxt);
519 
520  datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
521 
522  check_duplicates_in_publist(publist, datums);
523 
524  MemoryContextSwitchTo(oldcxt);
525 
526  arr = construct_array_builtin(datums, list_length(publist), TEXTOID);
527 
528  MemoryContextDelete(memcxt);
529 
530  return PointerGetDatum(arr);
531 }
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3338
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, check_duplicates_in_publist(), construct_array_builtin(), CurrentMemoryContext, list_length(), MemoryContextDelete(), MemoryContextSwitchTo(), palloc(), and PointerGetDatum().

Referenced by AlterSubscription(), and CreateSubscription().

◆ ReplicationSlotDropAtPubNode()

void ReplicationSlotDropAtPubNode ( WalReceiverConn wrconn,
char *  slotname,
bool  missing_ok 
)

Definition at line 1648 of file subscriptioncmds.c.

1649 {
1650  StringInfoData cmd;
1651 
1652  Assert(wrconn);
1653 
1654  load_file("libpqwalreceiver", false);
1655 
1656  initStringInfo(&cmd);
1657  appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1658 
1659  PG_TRY();
1660  {
1662 
1663  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1664 
1665  if (res->status == WALRCV_OK_COMMAND)
1666  {
1667  /* NOTICE. Success. */
1668  ereport(NOTICE,
1669  (errmsg("dropped replication slot \"%s\" on publisher",
1670  slotname)));
1671  }
1672  else if (res->status == WALRCV_ERROR &&
1673  missing_ok &&
1674  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1675  {
1676  /* LOG. Error, but missing_ok = true. */
1677  ereport(LOG,
1678  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1679  slotname, res->err)));
1680  }
1681  else
1682  {
1683  /* ERROR. */
1684  ereport(ERROR,
1685  (errcode(ERRCODE_CONNECTION_FAILURE),
1686  errmsg("could not drop replication slot \"%s\" on publisher: %s",
1687  slotname, res->err)));
1688  }
1689 
1691  }
1692  PG_FINALLY();
1693  {
1694  pfree(cmd.data);
1695  }
1696  PG_END_TRY();
1697 }
#define LOG
Definition: elog.h:27
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11529
@ WALRCV_OK_COMMAND
Definition: walreceiver.h:205
@ WALRCV_ERROR
Definition: walreceiver.h:204

References appendStringInfo(), Assert(), StringInfoData::data, ereport, errcode(), errmsg(), ERROR, initStringInfo(), load_file(), LOG, NOTICE, pfree(), PG_END_TRY, PG_FINALLY, PG_TRY, quote_identifier(), res, walrcv_clear_result(), WALRCV_ERROR, walrcv_exec, WALRCV_OK_COMMAND, and wrconn.

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

◆ ReportSlotConnectionError()

static void ReportSlotConnectionError ( List rstates,
Oid  subid,
char *  slotname,
char *  err 
)
static

Definition at line 1989 of file subscriptioncmds.c.

1990 {
1991  ListCell *lc;
1992 
1993  foreach(lc, rstates)
1994  {
1996  Oid relid = rstate->relid;
1997 
1998  /* Only cleanup resources of tablesync workers */
1999  if (!OidIsValid(relid))
2000  continue;
2001 
2002  /*
2003  * Caller needs to ensure that relstate doesn't change underneath us.
2004  * See DropSubscription where we get the relstates.
2005  */
2006  if (rstate->state != SUBREL_STATE_SYNCDONE)
2007  {
2008  char syncslotname[NAMEDATALEN] = {0};
2009 
2010  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
2011  sizeof(syncslotname));
2012  elog(WARNING, "could not drop tablesync replication slot \"%s\"",
2013  syncslotname);
2014  }
2015  }
2016 
2017  ereport(ERROR,
2018  (errcode(ERRCODE_CONNECTION_FAILURE),
2019  errmsg("could not connect to publisher when attempting to drop replication slot \"%s\": %s",
2020  slotname, err),
2021  /* translator: %s is an SQL ALTER command */
2022  errhint("Use %s to disassociate the subscription from the slot.",
2023  "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
2024 }

References elog(), ereport, errcode(), errhint(), errmsg(), ERROR, lfirst, NAMEDATALEN, OidIsValid, SubscriptionRelState::relid, ReplicationSlotNameForTablesync(), SubscriptionRelState::state, and WARNING.

Referenced by DropSubscription().