PostgreSQL Source Code  git master
subscriptioncmds.h File Reference
Include dependency graph for subscriptioncmds.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ObjectAddress CreateSubscription (ParseState *pstate, CreateSubscriptionStmt *stmt, bool isTopLevel)
 
ObjectAddress AlterSubscription (ParseState *pstate, AlterSubscriptionStmt *stmt, bool isTopLevel)
 
void DropSubscription (DropSubscriptionStmt *stmt, bool isTopLevel)
 
ObjectAddress AlterSubscriptionOwner (const char *name, Oid newOwnerId)
 
void AlterSubscriptionOwner_oid (Oid subid, Oid newOwnerId)
 
char defGetStreamingMode (DefElem *def)
 

Function Documentation

◆ AlterSubscription()

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

Definition at line 1071 of file subscriptioncmds.c.

1073 {
1074  Relation rel;
1075  ObjectAddress myself;
1076  bool nulls[Natts_pg_subscription];
1077  bool replaces[Natts_pg_subscription];
1078  Datum values[Natts_pg_subscription];
1079  HeapTuple tup;
1080  Oid subid;
1081  bool update_tuple = false;
1082  Subscription *sub;
1083  Form_pg_subscription form;
1084  bits32 supported_opts;
1085  SubOpts opts = {0};
1086 
1087  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1088 
1089  /* Fetch the existing tuple. */
1091  CStringGetDatum(stmt->subname));
1092 
1093  if (!HeapTupleIsValid(tup))
1094  ereport(ERROR,
1095  (errcode(ERRCODE_UNDEFINED_OBJECT),
1096  errmsg("subscription \"%s\" does not exist",
1097  stmt->subname)));
1098 
1099  form = (Form_pg_subscription) GETSTRUCT(tup);
1100  subid = form->oid;
1101 
1102  /* must be owner */
1103  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1105  stmt->subname);
1106 
1107  sub = GetSubscription(subid, false);
1108 
1109  /*
1110  * Don't allow non-superuser modification of a subscription with
1111  * password_required=false.
1112  */
1113  if (!sub->passwordrequired && !superuser())
1114  ereport(ERROR,
1115  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1116  errmsg("password_required=false is superuser-only"),
1117  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1118 
1119  /* Lock the subscription so nobody else can do anything with it. */
1120  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1121 
1122  /* Form a new tuple. */
1123  memset(values, 0, sizeof(values));
1124  memset(nulls, false, sizeof(nulls));
1125  memset(replaces, false, sizeof(replaces));
1126 
1127  switch (stmt->kind)
1128  {
1130  {
1131  supported_opts = (SUBOPT_SLOT_NAME |
1136 
1137  parse_subscription_options(pstate, stmt->options,
1138  supported_opts, &opts);
1139 
1140  if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1141  {
1142  /*
1143  * The subscription must be disabled to allow slot_name as
1144  * 'none', otherwise, the apply worker will repeatedly try
1145  * to stream the data using that slot_name which neither
1146  * exists on the publisher nor the user will be allowed to
1147  * create it.
1148  */
1149  if (sub->enabled && !opts.slot_name)
1150  ereport(ERROR,
1151  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1152  errmsg("cannot set %s for enabled subscription",
1153  "slot_name = NONE")));
1154 
1155  if (opts.slot_name)
1156  values[Anum_pg_subscription_subslotname - 1] =
1158  else
1159  nulls[Anum_pg_subscription_subslotname - 1] = true;
1160  replaces[Anum_pg_subscription_subslotname - 1] = true;
1161  }
1162 
1163  if (opts.synchronous_commit)
1164  {
1165  values[Anum_pg_subscription_subsynccommit - 1] =
1166  CStringGetTextDatum(opts.synchronous_commit);
1167  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1168  }
1169 
1170  if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1171  {
1172  values[Anum_pg_subscription_subbinary - 1] =
1173  BoolGetDatum(opts.binary);
1174  replaces[Anum_pg_subscription_subbinary - 1] = true;
1175  }
1176 
1177  if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1178  {
1179  values[Anum_pg_subscription_substream - 1] =
1180  CharGetDatum(opts.streaming);
1181  replaces[Anum_pg_subscription_substream - 1] = true;
1182  }
1183 
1184  if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1185  {
1186  values[Anum_pg_subscription_subdisableonerr - 1]
1187  = BoolGetDatum(opts.disableonerr);
1188  replaces[Anum_pg_subscription_subdisableonerr - 1]
1189  = true;
1190  }
1191 
1192  if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1193  {
1194  /* Non-superuser may not disable password_required. */
1195  if (!opts.passwordrequired && !superuser())
1196  ereport(ERROR,
1197  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1198  errmsg("password_required=false is superuser-only"),
1199  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1200 
1201  values[Anum_pg_subscription_subpasswordrequired - 1]
1202  = BoolGetDatum(opts.passwordrequired);
1203  replaces[Anum_pg_subscription_subpasswordrequired - 1]
1204  = true;
1205  }
1206 
1207  if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1208  {
1209  values[Anum_pg_subscription_suborigin - 1] =
1210  CStringGetTextDatum(opts.origin);
1211  replaces[Anum_pg_subscription_suborigin - 1] = true;
1212  }
1213 
1214  update_tuple = true;
1215  break;
1216  }
1217 
1219  {
1220  parse_subscription_options(pstate, stmt->options,
1221  SUBOPT_ENABLED, &opts);
1222  Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
1223 
1224  if (!sub->slotname && opts.enabled)
1225  ereport(ERROR,
1226  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1227  errmsg("cannot enable subscription that does not have a slot name")));
1228 
1229  values[Anum_pg_subscription_subenabled - 1] =
1230  BoolGetDatum(opts.enabled);
1231  replaces[Anum_pg_subscription_subenabled - 1] = true;
1232 
1233  if (opts.enabled)
1235 
1236  update_tuple = true;
1237  break;
1238  }
1239 
1241  /* Load the library providing us libpq calls. */
1242  load_file("libpqwalreceiver", false);
1243  /* Check the connection info string. */
1244  walrcv_check_conninfo(stmt->conninfo,
1245  sub->passwordrequired && !superuser_arg(sub->owner));
1246 
1247  values[Anum_pg_subscription_subconninfo - 1] =
1248  CStringGetTextDatum(stmt->conninfo);
1249  replaces[Anum_pg_subscription_subconninfo - 1] = true;
1250  update_tuple = true;
1251  break;
1252 
1254  {
1255  supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1256  parse_subscription_options(pstate, stmt->options,
1257  supported_opts, &opts);
1258 
1259  values[Anum_pg_subscription_subpublications - 1] =
1260  publicationListToArray(stmt->publication);
1261  replaces[Anum_pg_subscription_subpublications - 1] = true;
1262 
1263  update_tuple = true;
1264 
1265  /* Refresh if user asked us to. */
1266  if (opts.refresh)
1267  {
1268  if (!sub->enabled)
1269  ereport(ERROR,
1270  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1271  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1272  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1273 
1274  /*
1275  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1276  * not allowed.
1277  */
1278  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1279  ereport(ERROR,
1280  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1281  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1282  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1283 
1284  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1285 
1286  /* Make sure refresh sees the new list of publications. */
1287  sub->publications = stmt->publication;
1288 
1289  AlterSubscription_refresh(sub, opts.copy_data,
1290  stmt->publication);
1291  }
1292 
1293  break;
1294  }
1295 
1298  {
1299  List *publist;
1300  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1301 
1302  supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1303  parse_subscription_options(pstate, stmt->options,
1304  supported_opts, &opts);
1305 
1306  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1307  values[Anum_pg_subscription_subpublications - 1] =
1308  publicationListToArray(publist);
1309  replaces[Anum_pg_subscription_subpublications - 1] = true;
1310 
1311  update_tuple = true;
1312 
1313  /* Refresh if user asked us to. */
1314  if (opts.refresh)
1315  {
1316  /* We only need to validate user specified publications. */
1317  List *validate_publications = (isadd) ? stmt->publication : NULL;
1318 
1319  if (!sub->enabled)
1320  ereport(ERROR,
1321  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1322  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1323  /* translator: %s is an SQL ALTER command */
1324  errhint("Use %s instead.",
1325  isadd ?
1326  "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
1327  "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
1328 
1329  /*
1330  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1331  * not allowed.
1332  */
1333  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1334  ereport(ERROR,
1335  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1336  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1337  /* translator: %s is an SQL ALTER command */
1338  errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
1339  isadd ?
1340  "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
1341  "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
1342 
1343  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1344 
1345  /* Refresh the new list of publications. */
1346  sub->publications = publist;
1347 
1348  AlterSubscription_refresh(sub, opts.copy_data,
1349  validate_publications);
1350  }
1351 
1352  break;
1353  }
1354 
1356  {
1357  if (!sub->enabled)
1358  ereport(ERROR,
1359  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1360  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1361 
1362  parse_subscription_options(pstate, stmt->options,
1364 
1365  /*
1366  * The subscription option "two_phase" requires that
1367  * replication has passed the initial table synchronization
1368  * phase before the two_phase becomes properly enabled.
1369  *
1370  * But, having reached this two-phase commit "enabled" state
1371  * we must not allow any subsequent table initialization to
1372  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1373  * when the user had requested two_phase = on mode.
1374  *
1375  * The exception to this restriction is when copy_data =
1376  * false, because when copy_data is false the tablesync will
1377  * start already in READY state and will exit directly without
1378  * doing anything.
1379  *
1380  * For more details see comments atop worker.c.
1381  */
1382  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1383  ereport(ERROR,
1384  (errcode(ERRCODE_SYNTAX_ERROR),
1385  errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1386  errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1387 
1388  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1389 
1390  AlterSubscription_refresh(sub, opts.copy_data, NULL);
1391 
1392  break;
1393  }
1394 
1396  {
1397  parse_subscription_options(pstate, stmt->options, SUBOPT_LSN, &opts);
1398 
1399  /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
1400  Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
1401 
1402  /*
1403  * If the user sets subskiplsn, we do a sanity check to make
1404  * sure that the specified LSN is a probable value.
1405  */
1406  if (!XLogRecPtrIsInvalid(opts.lsn))
1407  {
1408  RepOriginId originid;
1409  char originname[NAMEDATALEN];
1410  XLogRecPtr remote_lsn;
1411 
1413  originname, sizeof(originname));
1414  originid = replorigin_by_name(originname, false);
1415  remote_lsn = replorigin_get_progress(originid, false);
1416 
1417  /* Check the given LSN is at least a future LSN */
1418  if (!XLogRecPtrIsInvalid(remote_lsn) && opts.lsn < remote_lsn)
1419  ereport(ERROR,
1420  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1421  errmsg("skip WAL location (LSN %X/%X) must be greater than origin LSN %X/%X",
1422  LSN_FORMAT_ARGS(opts.lsn),
1423  LSN_FORMAT_ARGS(remote_lsn))));
1424  }
1425 
1426  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
1427  replaces[Anum_pg_subscription_subskiplsn - 1] = true;
1428 
1429  update_tuple = true;
1430  break;
1431  }
1432 
1433  default:
1434  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1435  stmt->kind);
1436  }
1437 
1438  /* Update the catalog if needed. */
1439  if (update_tuple)
1440  {
1441  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1442  replaces);
1443 
1444  CatalogTupleUpdate(rel, &tup->t_self, tup);
1445 
1446  heap_freetuple(tup);
1447  }
1448 
1450 
1451  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1452 
1453  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1454 
1455  /* Wake up related replication workers to handle this change quickly. */
1457 
1458  return myself;
1459 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2673
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:3976
void LogicalRepWorkersWakeupAtCommit(Oid subid)
Definition: worker.c:5012
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition: worker.c:461
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:94
uint32 bits32
Definition: c.h:499
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
#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:653
#define stmt
Definition: indent_codes.h:59
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:1082
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:510
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:1014
@ ALTER_SUBSCRIPTION_ENABLED
Definition: parsenodes.h:4029
@ ALTER_SUBSCRIPTION_DROP_PUBLICATION
Definition: parsenodes.h:4027
@ ALTER_SUBSCRIPTION_SET_PUBLICATION
Definition: parsenodes.h:4025
@ ALTER_SUBSCRIPTION_REFRESH
Definition: parsenodes.h:4028
@ ALTER_SUBSCRIPTION_SKIP
Definition: parsenodes.h:4030
@ ALTER_SUBSCRIPTION_OPTIONS
Definition: parsenodes.h:4023
@ ALTER_SUBSCRIPTION_CONNECTION
Definition: parsenodes.h:4024
@ ALTER_SUBSCRIPTION_ADD_PUBLICATION
Definition: parsenodes.h:4026
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:2120
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:64
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350
static Datum CharGetDatum(char X)
Definition: postgres.h:122
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:530
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:54
#define SUBOPT_STREAMING
#define SUBOPT_PASSWORD_REQUIRED
#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_RUN_AS_OWNER
#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_arg(Oid roleid)
Definition: superuser.c:56
bool superuser(void)
Definition: superuser.c:46
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:184
@ 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, must_use_password)
Definition: walreceiver.h:412
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3480
#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(), CharGetDatum(), CStringGetDatum(), CStringGetTextDatum, DirectFunctionCall1, elog(), Subscription::enabled, ereport, errcode(), errhint(), errmsg(), ERROR, GETSTRUCT, GetSubscription(), GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, if(), InvalidOid, InvokeObjectPostAlterHook, IsSet, load_file(), LockSharedObject(), LOGICALREP_TWOPHASE_STATE_ENABLED, LogicalRepWorkersWakeupAtCommit(), LSN_FORMAT_ARGS, LSNGetDatum(), merge_publications(), MyDatabaseId, NAMEDATALEN, namein(), object_ownercheck(), OBJECT_SUBSCRIPTION, ObjectAddressSet, opts, Subscription::owner, parse_subscription_options(), Subscription::passwordrequired, PreventInTransactionBlock(), publicationListToArray(), Subscription::publications, RelationGetDescr, ReplicationOriginNameForLogicalRep(), replorigin_by_name(), replorigin_get_progress(), RowExclusiveLock, SearchSysCacheCopy2, Subscription::slotname, stmt, SUBOPT_BINARY, SUBOPT_COPY_DATA, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_LSN, SUBOPT_ORIGIN, SUBOPT_PASSWORD_REQUIRED, SUBOPT_REFRESH, SUBOPT_RUN_AS_OWNER, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBSCRIPTIONNAME, superuser(), superuser_arg(), HeapTupleData::t_self, table_close(), table_open(), Subscription::twophasestate, values, walrcv_check_conninfo, and XLogRecPtrIsInvalid.

Referenced by ProcessUtilitySlow().

◆ AlterSubscriptionOwner()

ObjectAddress AlterSubscriptionOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 1869 of file subscriptioncmds.c.

1870 {
1871  Oid subid;
1872  HeapTuple tup;
1873  Relation rel;
1874  ObjectAddress address;
1875  Form_pg_subscription form;
1876 
1877  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1878 
1881 
1882  if (!HeapTupleIsValid(tup))
1883  ereport(ERROR,
1884  (errcode(ERRCODE_UNDEFINED_OBJECT),
1885  errmsg("subscription \"%s\" does not exist", name)));
1886 
1887  form = (Form_pg_subscription) GETSTRUCT(tup);
1888  subid = form->oid;
1889 
1890  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1891 
1892  ObjectAddressSet(address, SubscriptionRelationId, subid);
1893 
1894  heap_freetuple(tup);
1895 
1897 
1898  return address;
1899 }
const char * name
Definition: encode.c:571
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_oid()

void AlterSubscriptionOwner_oid ( Oid  subid,
Oid  newOwnerId 
)

Definition at line 1905 of file subscriptioncmds.c.

1906 {
1907  HeapTuple tup;
1908  Relation rel;
1909 
1910  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1911 
1913 
1914  if (!HeapTupleIsValid(tup))
1915  ereport(ERROR,
1916  (errcode(ERRCODE_UNDEFINED_OBJECT),
1917  errmsg("subscription with OID %u does not exist", subid)));
1918 
1919  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1920 
1921  heap_freetuple(tup);
1922 
1924 }
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:182
@ 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().

◆ CreateSubscription()

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

Definition at line 567 of file subscriptioncmds.c.

569 {
570  Relation rel;
571  ObjectAddress myself;
572  Oid subid;
573  bool nulls[Natts_pg_subscription];
574  Datum values[Natts_pg_subscription];
575  Oid owner = GetUserId();
576  HeapTuple tup;
577  char *conninfo;
578  char originname[NAMEDATALEN];
579  List *publications;
580  bits32 supported_opts;
581  SubOpts opts = {0};
582  AclResult aclresult;
583 
584  /*
585  * Parse and check options.
586  *
587  * Connection and publication should not be specified here.
588  */
589  supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
595  parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
596 
597  /*
598  * Since creating a replication slot is not transactional, rolling back
599  * the transaction leaves the created replication slot. So we cannot run
600  * CREATE SUBSCRIPTION inside a transaction block if creating a
601  * replication slot.
602  */
603  if (opts.create_slot)
604  PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
605 
606  /*
607  * We don't want to allow unprivileged users to be able to trigger
608  * attempts to access arbitrary network destinations, so require the user
609  * to have been specifically authorized to create subscriptions.
610  */
611  if (!has_privs_of_role(owner, ROLE_PG_CREATE_SUBSCRIPTION))
612  ereport(ERROR,
613  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
614  errmsg("permission denied to create subscription"),
615  errdetail("Only roles with privileges of the \"%s\" role may create subscriptions.",
616  "pg_create_subscription")));
617 
618  /*
619  * Since a subscription is a database object, we also check for CREATE
620  * permission on the database.
621  */
622  aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
623  owner, ACL_CREATE);
624  if (aclresult != ACLCHECK_OK)
625  aclcheck_error(aclresult, OBJECT_DATABASE,
627 
628  /*
629  * Non-superusers are required to set a password for authentication, and
630  * that password must be used by the target server, but the superuser can
631  * exempt a subscription from this requirement.
632  */
633  if (!opts.passwordrequired && !superuser_arg(owner))
634  ereport(ERROR,
635  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
636  errmsg("password_required=false is superuser-only"),
637  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
638 
639  /*
640  * If built with appropriate switch, whine when regression-testing
641  * conventions for subscription names are violated.
642  */
643 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
644  if (strncmp(stmt->subname, "regress_", 8) != 0)
645  elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
646 #endif
647 
648  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
649 
650  /* Check if name is used */
651  subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
652  MyDatabaseId, CStringGetDatum(stmt->subname));
653  if (OidIsValid(subid))
654  {
655  ereport(ERROR,
657  errmsg("subscription \"%s\" already exists",
658  stmt->subname)));
659  }
660 
661  if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
662  opts.slot_name == NULL)
663  opts.slot_name = stmt->subname;
664 
665  /* The default for synchronous_commit of subscriptions is off. */
666  if (opts.synchronous_commit == NULL)
667  opts.synchronous_commit = "off";
668 
669  conninfo = stmt->conninfo;
670  publications = stmt->publication;
671 
672  /* Load the library providing us libpq calls. */
673  load_file("libpqwalreceiver", false);
674 
675  /* Check the connection info string. */
676  walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
677 
678  /* Everything ok, form a new tuple. */
679  memset(values, 0, sizeof(values));
680  memset(nulls, false, sizeof(nulls));
681 
682  subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
683  Anum_pg_subscription_oid);
684  values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
685  values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
686  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
687  values[Anum_pg_subscription_subname - 1] =
689  values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
690  values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
691  values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
692  values[Anum_pg_subscription_substream - 1] = CharGetDatum(opts.streaming);
693  values[Anum_pg_subscription_subtwophasestate - 1] =
694  CharGetDatum(opts.twophase ?
697  values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
698  values[Anum_pg_subscription_subpasswordrequired - 1] = BoolGetDatum(opts.passwordrequired);
699  values[Anum_pg_subscription_subrunasowner - 1] = BoolGetDatum(opts.runasowner);
700  values[Anum_pg_subscription_subconninfo - 1] =
701  CStringGetTextDatum(conninfo);
702  if (opts.slot_name)
703  values[Anum_pg_subscription_subslotname - 1] =
705  else
706  nulls[Anum_pg_subscription_subslotname - 1] = true;
707  values[Anum_pg_subscription_subsynccommit - 1] =
708  CStringGetTextDatum(opts.synchronous_commit);
709  values[Anum_pg_subscription_subpublications - 1] =
710  publicationListToArray(publications);
711  values[Anum_pg_subscription_suborigin - 1] =
712  CStringGetTextDatum(opts.origin);
713 
714  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
715 
716  /* Insert tuple into catalog. */
717  CatalogTupleInsert(rel, tup);
718  heap_freetuple(tup);
719 
720  recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
721 
722  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
723  replorigin_create(originname);
724 
725  /*
726  * Connect to remote side to execute requested commands and fetch table
727  * info.
728  */
729  if (opts.connect)
730  {
731  char *err;
733  List *tables;
734  ListCell *lc;
735  char table_state;
736  bool must_use_password;
737 
738  /* Try to connect to the publisher. */
739  must_use_password = !superuser_arg(owner) && opts.passwordrequired;
740  wrconn = walrcv_connect(conninfo, true, must_use_password,
741  stmt->subname, &err);
742  if (!wrconn)
743  ereport(ERROR,
744  (errcode(ERRCODE_CONNECTION_FAILURE),
745  errmsg("could not connect to the publisher: %s", err)));
746 
747  PG_TRY();
748  {
749  check_publications(wrconn, publications);
750  check_publications_origin(wrconn, publications, opts.copy_data,
751  opts.origin, NULL, 0, stmt->subname);
752 
753  /*
754  * Set sync state based on if we were asked to do data copy or
755  * not.
756  */
757  table_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
758 
759  /*
760  * Get the table list from publisher and build local table status
761  * info.
762  */
763  tables = fetch_table_list(wrconn, publications);
764  foreach(lc, tables)
765  {
766  RangeVar *rv = (RangeVar *) lfirst(lc);
767  Oid relid;
768 
769  relid = RangeVarGetRelid(rv, AccessShareLock, false);
770 
771  /* Check for supported relkind. */
773  rv->schemaname, rv->relname);
774 
775  AddSubscriptionRelState(subid, relid, table_state,
777  }
778 
779  /*
780  * If requested, create permanent slot for the subscription. We
781  * won't use the initial snapshot for anything, so no need to
782  * export it.
783  */
784  if (opts.create_slot)
785  {
786  bool twophase_enabled = false;
787 
788  Assert(opts.slot_name);
789 
790  /*
791  * Even if two_phase is set, don't create the slot with
792  * two-phase enabled. Will enable it once all the tables are
793  * synced and ready. This avoids race-conditions like prepared
794  * transactions being skipped due to changes not being applied
795  * due to checks in should_apply_changes_for_rel() when
796  * tablesync for the corresponding tables are in progress. See
797  * comments atop worker.c.
798  *
799  * Note that if tables were specified but copy_data is false
800  * then it is safe to enable two_phase up-front because those
801  * tables are already initially in READY state. When the
802  * subscription has no tables, we leave the twophase state as
803  * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
804  * PUBLICATION to work.
805  */
806  if (opts.twophase && !opts.copy_data && tables != NIL)
807  twophase_enabled = true;
808 
809  walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
810  CRS_NOEXPORT_SNAPSHOT, NULL);
811 
812  if (twophase_enabled)
814 
815  ereport(NOTICE,
816  (errmsg("created replication slot \"%s\" on publisher",
817  opts.slot_name)));
818  }
819  }
820  PG_FINALLY();
821  {
823  }
824  PG_END_TRY();
825  }
826  else
828  (errmsg("subscription was created, but is not connected"),
829  errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and refresh the subscription.")));
830 
832 
834 
835  if (opts.enabled)
837 
838  ObjectAddressSet(myself, SubscriptionRelationId, subid);
839 
840  InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
841 
842  return myself;
843 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4969
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3775
#define OidIsValid(objectId)
Definition: c.h:759
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:393
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3043
int errdetail(const char *fmt,...)
Definition: elog.c:1202
#define PG_TRY(...)
Definition: elog.h:370
#define WARNING
Definition: elog.h:36
#define PG_END_TRY(...)
Definition: elog.h:395
#define NOTICE
Definition: elog.h:35
#define PG_FINALLY(...)
Definition: elog.h:387
void err(int eval, const char *fmt,...)
Definition: err.c:43
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:233
#define AccessShareLock
Definition: lockdefs.h:36
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1985
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:252
@ OBJECT_DATABASE
Definition: parsenodes.h:2091
#define ACL_CREATE
Definition: parsenodes.h:92
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define LOGICALREP_TWOPHASE_STATE_PENDING
void pgstat_create_subscription(Oid subid)
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
char * relname
Definition: primnodes.h:74
char * schemaname
Definition: primnodes.h:71
#define SUBOPT_CREATE_SLOT
static void check_publications(WalReceiverConn *wrconn, List *publications)
#define SUBOPT_TWOPHASE_COMMIT
static void check_publications_origin(WalReceiverConn *wrconn, List *publications, bool copydata, char *origin, Oid *subrel_local_oids, int subrel_count, char *subname)
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
#define SUBOPT_CONNECT
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:202
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition: tablesync.c:1605
static WalReceiverConn * wrconn
Definition: walreceiver.c:95
#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
Definition: walreceiver.h:432
#define walrcv_connect(conninfo, logical, must_use_password, appname, err)
Definition: walreceiver.h:410
#define walrcv_disconnect(conn)
Definition: walreceiver.h:438
@ CRS_NOEXPORT_SNAPSHOT
Definition: walsender.h:23
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, AddSubscriptionRelState(), ApplyLauncherWakeupAtCommit(), Assert(), BoolGetDatum(), CatalogTupleInsert(), CharGetDatum(), check_publications(), check_publications_origin(), CheckSubscriptionRelkind(), CRS_NOEXPORT_SNAPSHOT, CStringGetDatum(), CStringGetTextDatum, DirectFunctionCall1, elog(), ereport, err(), errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errhint(), errmsg(), ERROR, fetch_table_list(), get_database_name(), get_rel_relkind(), GetNewOidWithIndex(), GetSysCacheOid2, GetUserId(), has_privs_of_role(), 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, object_aclcheck(), OBJECT_DATABASE, ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, opts, parse_subscription_options(), PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_create_subscription(), PreventInTransactionBlock(), publicationListToArray(), RangeVarGetRelid, recordDependencyOnOwner(), RelationGetDescr, RangeVar::relname, ReplicationOriginNameForLogicalRep(), replorigin_create(), RowExclusiveLock, RangeVar::schemaname, stmt, SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_ORIGIN, SUBOPT_PASSWORD_REQUIRED, SUBOPT_RUN_AS_OWNER, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, SUBSCRIPTIONNAME, superuser(), superuser_arg(), table_close(), table_open(), UpdateTwoPhaseState(), values, walrcv_check_conninfo, walrcv_connect, walrcv_create_slot, walrcv_disconnect, WARNING, and wrconn.

Referenced by ProcessUtilitySlow().

◆ defGetStreamingMode()

char defGetStreamingMode ( DefElem def)

Definition at line 2297 of file subscriptioncmds.c.

2298 {
2299  /*
2300  * If no parameter value given, assume "true" is meant.
2301  */
2302  if (!def->arg)
2303  return LOGICALREP_STREAM_ON;
2304 
2305  /*
2306  * Allow 0, 1, "false", "true", "off", "on" or "parallel".
2307  */
2308  switch (nodeTag(def->arg))
2309  {
2310  case T_Integer:
2311  switch (intVal(def->arg))
2312  {
2313  case 0:
2314  return LOGICALREP_STREAM_OFF;
2315  case 1:
2316  return LOGICALREP_STREAM_ON;
2317  default:
2318  /* otherwise, error out below */
2319  break;
2320  }
2321  break;
2322  default:
2323  {
2324  char *sval = defGetString(def);
2325 
2326  /*
2327  * The set of strings accepted here should match up with the
2328  * grammar's opt_boolean_or_string production.
2329  */
2330  if (pg_strcasecmp(sval, "false") == 0 ||
2331  pg_strcasecmp(sval, "off") == 0)
2332  return LOGICALREP_STREAM_OFF;
2333  if (pg_strcasecmp(sval, "true") == 0 ||
2334  pg_strcasecmp(sval, "on") == 0)
2335  return LOGICALREP_STREAM_ON;
2336  if (pg_strcasecmp(sval, "parallel") == 0)
2338  }
2339  break;
2340  }
2341 
2342  ereport(ERROR,
2343  (errcode(ERRCODE_SYNTAX_ERROR),
2344  errmsg("%s requires a Boolean value or \"parallel\"",
2345  def->defname)));
2346  return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
2347 }
char * defGetString(DefElem *def)
Definition: define.c:49
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define LOGICALREP_STREAM_ON
#define LOGICALREP_STREAM_OFF
#define LOGICALREP_STREAM_PARALLEL
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
char * defname
Definition: parsenodes.h:810
Node * arg
Definition: parsenodes.h:811
#define intVal(v)
Definition: value.h:79

References DefElem::arg, defGetString(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, intVal, LOGICALREP_STREAM_OFF, LOGICALREP_STREAM_ON, LOGICALREP_STREAM_PARALLEL, nodeTag, and pg_strcasecmp().

Referenced by parse_output_parameters(), and parse_subscription_options().

◆ DropSubscription()

void DropSubscription ( DropSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 1465 of file subscriptioncmds.c.

1466 {
1467  Relation rel;
1468  ObjectAddress myself;
1469  HeapTuple tup;
1470  Oid subid;
1471  Oid subowner;
1472  Datum datum;
1473  bool isnull;
1474  char *subname;
1475  char *conninfo;
1476  char *slotname;
1477  List *subworkers;
1478  ListCell *lc;
1479  char originname[NAMEDATALEN];
1480  char *err = NULL;
1482  Form_pg_subscription form;
1483  List *rstates;
1484  bool must_use_password;
1485 
1486  /*
1487  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1488  * launcher doesn't restart new worker during dropping the subscription
1489  */
1490  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1491 
1493  CStringGetDatum(stmt->subname));
1494 
1495  if (!HeapTupleIsValid(tup))
1496  {
1497  table_close(rel, NoLock);
1498 
1499  if (!stmt->missing_ok)
1500  ereport(ERROR,
1501  (errcode(ERRCODE_UNDEFINED_OBJECT),
1502  errmsg("subscription \"%s\" does not exist",
1503  stmt->subname)));
1504  else
1505  ereport(NOTICE,
1506  (errmsg("subscription \"%s\" does not exist, skipping",
1507  stmt->subname)));
1508 
1509  return;
1510  }
1511 
1512  form = (Form_pg_subscription) GETSTRUCT(tup);
1513  subid = form->oid;
1514  subowner = form->subowner;
1515  must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
1516 
1517  /* must be owner */
1518  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1520  stmt->subname);
1521 
1522  /* DROP hook for the subscription being removed */
1523  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1524 
1525  /*
1526  * Lock the subscription so nobody else can do anything with it (including
1527  * the replication workers).
1528  */
1529  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1530 
1531  /* Get subname */
1533  Anum_pg_subscription_subname);
1534  subname = pstrdup(NameStr(*DatumGetName(datum)));
1535 
1536  /* Get conninfo */
1538  Anum_pg_subscription_subconninfo);
1539  conninfo = TextDatumGetCString(datum);
1540 
1541  /* Get slotname */
1542  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1543  Anum_pg_subscription_subslotname, &isnull);
1544  if (!isnull)
1545  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1546  else
1547  slotname = NULL;
1548 
1549  /*
1550  * Since dropping a replication slot is not transactional, the replication
1551  * slot stays dropped even if the transaction rolls back. So we cannot
1552  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1553  * replication slot. Also, in this case, we report a message for dropping
1554  * the subscription to the cumulative stats system.
1555  *
1556  * XXX The command name should really be something like "DROP SUBSCRIPTION
1557  * of a subscription that is associated with a replication slot", but we
1558  * don't have the proper facilities for that.
1559  */
1560  if (slotname)
1561  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1562 
1563  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1564  EventTriggerSQLDropAddObject(&myself, true, true);
1565 
1566  /* Remove the tuple from catalog. */
1567  CatalogTupleDelete(rel, &tup->t_self);
1568 
1569  ReleaseSysCache(tup);
1570 
1571  /*
1572  * Stop all the subscription workers immediately.
1573  *
1574  * This is necessary if we are dropping the replication slot, so that the
1575  * slot becomes accessible.
1576  *
1577  * It is also necessary if the subscription is disabled and was disabled
1578  * in the same transaction. Then the workers haven't seen the disabling
1579  * yet and will still be running, leading to hangs later when we want to
1580  * drop the replication origin. If the subscription was disabled before
1581  * this transaction, then there shouldn't be any workers left, so this
1582  * won't make a difference.
1583  *
1584  * New workers won't be started because we hold an exclusive lock on the
1585  * subscription till the end of the transaction.
1586  */
1587  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1588  subworkers = logicalrep_workers_find(subid, false);
1589  LWLockRelease(LogicalRepWorkerLock);
1590  foreach(lc, subworkers)
1591  {
1593 
1595  }
1596  list_free(subworkers);
1597 
1598  /*
1599  * Remove the no-longer-useful entry in the launcher's table of apply
1600  * worker start times.
1601  *
1602  * If this transaction rolls back, the launcher might restart a failed
1603  * apply worker before wal_retrieve_retry_interval milliseconds have
1604  * elapsed, but that's pretty harmless.
1605  */
1607 
1608  /*
1609  * Cleanup of tablesync replication origins.
1610  *
1611  * Any READY-state relations would already have dealt with clean-ups.
1612  *
1613  * Note that the state can't change because we have already stopped both
1614  * the apply and tablesync workers and they can't restart because of
1615  * exclusive lock on the subscription.
1616  */
1617  rstates = GetSubscriptionRelations(subid, true);
1618  foreach(lc, rstates)
1619  {
1621  Oid relid = rstate->relid;
1622 
1623  /* Only cleanup resources of tablesync workers */
1624  if (!OidIsValid(relid))
1625  continue;
1626 
1627  /*
1628  * Drop the tablesync's origin tracking if exists.
1629  *
1630  * It is possible that the origin is not yet created for tablesync
1631  * worker so passing missing_ok = true. This can happen for the states
1632  * before SUBREL_STATE_FINISHEDCOPY.
1633  */
1634  ReplicationOriginNameForLogicalRep(subid, relid, originname,
1635  sizeof(originname));
1636  replorigin_drop_by_name(originname, true, false);
1637  }
1638 
1639  /* Clean up dependencies */
1640  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1641 
1642  /* Remove any associated relation synchronization states. */
1644 
1645  /* Remove the origin tracking if exists. */
1646  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
1647  replorigin_drop_by_name(originname, true, false);
1648 
1649  /*
1650  * If there is no slot associated with the subscription, we can finish
1651  * here.
1652  */
1653  if (!slotname && rstates == NIL)
1654  {
1655  table_close(rel, NoLock);
1656  return;
1657  }
1658 
1659  /*
1660  * Try to acquire the connection necessary for dropping slots.
1661  *
1662  * Note: If the slotname is NONE/NULL then we allow the command to finish
1663  * and users need to manually cleanup the apply and tablesync worker slots
1664  * later.
1665  *
1666  * This has to be at the end because otherwise if there is an error while
1667  * doing the database operations we won't be able to rollback dropped
1668  * slot.
1669  */
1670  load_file("libpqwalreceiver", false);
1671 
1672  wrconn = walrcv_connect(conninfo, true, must_use_password,
1673  subname, &err);
1674  if (wrconn == NULL)
1675  {
1676  if (!slotname)
1677  {
1678  /* be tidy */
1679  list_free(rstates);
1680  table_close(rel, NoLock);
1681  return;
1682  }
1683  else
1684  {
1685  ReportSlotConnectionError(rstates, subid, slotname, err);
1686  }
1687  }
1688 
1689  PG_TRY();
1690  {
1691  foreach(lc, rstates)
1692  {
1694  Oid relid = rstate->relid;
1695 
1696  /* Only cleanup resources of tablesync workers */
1697  if (!OidIsValid(relid))
1698  continue;
1699 
1700  /*
1701  * Drop the tablesync slots associated with removed tables.
1702  *
1703  * For SYNCDONE/READY states, the tablesync slot is known to have
1704  * already been dropped by the tablesync worker.
1705  *
1706  * For other states, there is no certainty, maybe the slot does
1707  * not exist yet. Also, if we fail after removing some of the
1708  * slots, next time, it will again try to drop already dropped
1709  * slots and fail. For these reasons, we allow missing_ok = true
1710  * for the drop.
1711  */
1712  if (rstate->state != SUBREL_STATE_SYNCDONE)
1713  {
1714  char syncslotname[NAMEDATALEN] = {0};
1715 
1716  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1717  sizeof(syncslotname));
1718  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1719  }
1720  }
1721 
1722  list_free(rstates);
1723 
1724  /*
1725  * If there is a slot associated with the subscription, then drop the
1726  * replication slot at the publisher.
1727  */
1728  if (slotname)
1729  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1730  }
1731  PG_FINALLY();
1732  {
1734  }
1735  PG_END_TRY();
1736 
1737  /*
1738  * Tell the cumulative stats system that the subscription is getting
1739  * dropped.
1740  */
1741  pgstat_drop_subscription(subid);
1742 
1743  table_close(rel, NoLock);
1744 }
#define TextDatumGetCString(d)
Definition: builtins.h:95
#define NameStr(name)
Definition: c.h:730
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:281
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:594
void ApplyLauncherForgetWorkerStartTime(Oid subid)
Definition: launcher.c:1052
void list_free(List *list)
Definition: list.c:1545
#define NoLock
Definition: lockdefs.h:34
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
@ LW_SHARED
Definition: lwlock.h:117
char * pstrdup(const char *in)
Definition: mcxt.c:1644
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:182
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:411
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1002
void RemoveSubscriptionRel(Oid subid, Oid relid)
List * GetSubscriptionRelations(Oid subid, bool not_ready)
NameData subname
void pgstat_drop_subscription(Oid subid)
static Name DatumGetName(Datum X)
Definition: postgres.h:360
static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:866
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1079
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:829
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:1110
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, Size szslot)
Definition: tablesync.c:1228

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ApplyLauncherForgetWorkerStartTime(), CatalogTupleDelete(), CStringGetDatum(), DatumGetName(), deleteSharedDependencyRecordsFor(), ereport, err(), 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(), 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, stmt, LogicalRepWorker::subid, subname, SUBSCRIPTIONNAME, SUBSCRIPTIONOID, superuser_arg(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), HeapTupleData::t_self, table_close(), table_open(), TextDatumGetCString, walrcv_connect, walrcv_disconnect, and wrconn.

Referenced by ProcessUtilitySlow().