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 1084 of file subscriptioncmds.c.

1086 {
1087  Relation rel;
1088  ObjectAddress myself;
1089  bool nulls[Natts_pg_subscription];
1090  bool replaces[Natts_pg_subscription];
1091  Datum values[Natts_pg_subscription];
1092  HeapTuple tup;
1093  Oid subid;
1094  bool update_tuple = false;
1095  Subscription *sub;
1096  Form_pg_subscription form;
1097  bits32 supported_opts;
1098  SubOpts opts = {0};
1099 
1100  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1101 
1102  /* Fetch the existing tuple. */
1103  tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, MyDatabaseId,
1104  CStringGetDatum(stmt->subname));
1105 
1106  if (!HeapTupleIsValid(tup))
1107  ereport(ERROR,
1108  (errcode(ERRCODE_UNDEFINED_OBJECT),
1109  errmsg("subscription \"%s\" does not exist",
1110  stmt->subname)));
1111 
1112  form = (Form_pg_subscription) GETSTRUCT(tup);
1113  subid = form->oid;
1114 
1115  /* must be owner */
1116  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1118  stmt->subname);
1119 
1120  sub = GetSubscription(subid, false);
1121 
1122  /*
1123  * Don't allow non-superuser modification of a subscription with
1124  * password_required=false.
1125  */
1126  if (!sub->passwordrequired && !superuser())
1127  ereport(ERROR,
1128  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1129  errmsg("password_required=false is superuser-only"),
1130  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1131 
1132  /* Lock the subscription so nobody else can do anything with it. */
1133  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1134 
1135  /* Form a new tuple. */
1136  memset(values, 0, sizeof(values));
1137  memset(nulls, false, sizeof(nulls));
1138  memset(replaces, false, sizeof(replaces));
1139 
1140  switch (stmt->kind)
1141  {
1143  {
1144  supported_opts = (SUBOPT_SLOT_NAME |
1149  SUBOPT_ORIGIN);
1150 
1151  parse_subscription_options(pstate, stmt->options,
1152  supported_opts, &opts);
1153 
1154  if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1155  {
1156  /*
1157  * The subscription must be disabled to allow slot_name as
1158  * 'none', otherwise, the apply worker will repeatedly try
1159  * to stream the data using that slot_name which neither
1160  * exists on the publisher nor the user will be allowed to
1161  * create it.
1162  */
1163  if (sub->enabled && !opts.slot_name)
1164  ereport(ERROR,
1165  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1166  errmsg("cannot set %s for enabled subscription",
1167  "slot_name = NONE")));
1168 
1169  if (opts.slot_name)
1170  values[Anum_pg_subscription_subslotname - 1] =
1172  else
1173  nulls[Anum_pg_subscription_subslotname - 1] = true;
1174  replaces[Anum_pg_subscription_subslotname - 1] = true;
1175  }
1176 
1177  if (opts.synchronous_commit)
1178  {
1179  values[Anum_pg_subscription_subsynccommit - 1] =
1180  CStringGetTextDatum(opts.synchronous_commit);
1181  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1182  }
1183 
1184  if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1185  {
1186  values[Anum_pg_subscription_subbinary - 1] =
1187  BoolGetDatum(opts.binary);
1188  replaces[Anum_pg_subscription_subbinary - 1] = true;
1189  }
1190 
1191  if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1192  {
1193  values[Anum_pg_subscription_substream - 1] =
1194  CharGetDatum(opts.streaming);
1195  replaces[Anum_pg_subscription_substream - 1] = true;
1196  }
1197 
1198  if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1199  {
1200  values[Anum_pg_subscription_subdisableonerr - 1]
1201  = BoolGetDatum(opts.disableonerr);
1202  replaces[Anum_pg_subscription_subdisableonerr - 1]
1203  = true;
1204  }
1205 
1206  if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1207  {
1208  /* Non-superuser may not disable password_required. */
1209  if (!opts.passwordrequired && !superuser())
1210  ereport(ERROR,
1211  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1212  errmsg("password_required=false is superuser-only"),
1213  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1214 
1215  values[Anum_pg_subscription_subpasswordrequired - 1]
1216  = BoolGetDatum(opts.passwordrequired);
1217  replaces[Anum_pg_subscription_subpasswordrequired - 1]
1218  = true;
1219  }
1220 
1221  if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
1222  {
1223  values[Anum_pg_subscription_subrunasowner - 1] =
1224  BoolGetDatum(opts.runasowner);
1225  replaces[Anum_pg_subscription_subrunasowner - 1] = true;
1226  }
1227 
1228  if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1229  {
1230  if (!sub->slotname)
1231  ereport(ERROR,
1232  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1233  errmsg("cannot set %s for a subscription that does not have a slot name",
1234  "failover")));
1235 
1236  /*
1237  * Do not allow changing the failover state if the
1238  * subscription is enabled. This is because the failover
1239  * state of the slot on the publisher cannot be modified
1240  * if the slot is currently acquired by the apply worker.
1241  */
1242  if (sub->enabled)
1243  ereport(ERROR,
1244  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1245  errmsg("cannot set %s for enabled subscription",
1246  "failover")));
1247 
1248  /*
1249  * The changed failover option of the slot can't be rolled
1250  * back.
1251  */
1252  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... SET (failover)");
1253 
1254  values[Anum_pg_subscription_subfailover - 1] =
1255  BoolGetDatum(opts.failover);
1256  replaces[Anum_pg_subscription_subfailover - 1] = true;
1257  }
1258 
1259  if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1260  {
1261  values[Anum_pg_subscription_suborigin - 1] =
1262  CStringGetTextDatum(opts.origin);
1263  replaces[Anum_pg_subscription_suborigin - 1] = true;
1264  }
1265 
1266  update_tuple = true;
1267  break;
1268  }
1269 
1271  {
1272  parse_subscription_options(pstate, stmt->options,
1273  SUBOPT_ENABLED, &opts);
1274  Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
1275 
1276  if (!sub->slotname && opts.enabled)
1277  ereport(ERROR,
1278  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1279  errmsg("cannot enable subscription that does not have a slot name")));
1280 
1281  values[Anum_pg_subscription_subenabled - 1] =
1282  BoolGetDatum(opts.enabled);
1283  replaces[Anum_pg_subscription_subenabled - 1] = true;
1284 
1285  if (opts.enabled)
1287 
1288  update_tuple = true;
1289  break;
1290  }
1291 
1293  /* Load the library providing us libpq calls. */
1294  load_file("libpqwalreceiver", false);
1295  /* Check the connection info string. */
1296  walrcv_check_conninfo(stmt->conninfo,
1297  sub->passwordrequired && !sub->ownersuperuser);
1298 
1299  values[Anum_pg_subscription_subconninfo - 1] =
1300  CStringGetTextDatum(stmt->conninfo);
1301  replaces[Anum_pg_subscription_subconninfo - 1] = true;
1302  update_tuple = true;
1303  break;
1304 
1306  {
1307  supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1308  parse_subscription_options(pstate, stmt->options,
1309  supported_opts, &opts);
1310 
1311  values[Anum_pg_subscription_subpublications - 1] =
1312  publicationListToArray(stmt->publication);
1313  replaces[Anum_pg_subscription_subpublications - 1] = true;
1314 
1315  update_tuple = true;
1316 
1317  /* Refresh if user asked us to. */
1318  if (opts.refresh)
1319  {
1320  if (!sub->enabled)
1321  ereport(ERROR,
1322  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1323  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1324  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1325 
1326  /*
1327  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1328  * not allowed.
1329  */
1330  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1331  ereport(ERROR,
1332  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1333  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1334  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1335 
1336  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1337 
1338  /* Make sure refresh sees the new list of publications. */
1339  sub->publications = stmt->publication;
1340 
1341  AlterSubscription_refresh(sub, opts.copy_data,
1342  stmt->publication);
1343  }
1344 
1345  break;
1346  }
1347 
1350  {
1351  List *publist;
1352  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1353 
1354  supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1355  parse_subscription_options(pstate, stmt->options,
1356  supported_opts, &opts);
1357 
1358  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1359  values[Anum_pg_subscription_subpublications - 1] =
1360  publicationListToArray(publist);
1361  replaces[Anum_pg_subscription_subpublications - 1] = true;
1362 
1363  update_tuple = true;
1364 
1365  /* Refresh if user asked us to. */
1366  if (opts.refresh)
1367  {
1368  /* We only need to validate user specified publications. */
1369  List *validate_publications = (isadd) ? stmt->publication : NULL;
1370 
1371  if (!sub->enabled)
1372  ereport(ERROR,
1373  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1374  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1375  /* translator: %s is an SQL ALTER command */
1376  errhint("Use %s instead.",
1377  isadd ?
1378  "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
1379  "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
1380 
1381  /*
1382  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1383  * not allowed.
1384  */
1385  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1386  ereport(ERROR,
1387  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1388  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1389  /* translator: %s is an SQL ALTER command */
1390  errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
1391  isadd ?
1392  "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
1393  "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
1394 
1395  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1396 
1397  /* Refresh the new list of publications. */
1398  sub->publications = publist;
1399 
1400  AlterSubscription_refresh(sub, opts.copy_data,
1401  validate_publications);
1402  }
1403 
1404  break;
1405  }
1406 
1408  {
1409  if (!sub->enabled)
1410  ereport(ERROR,
1411  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1412  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1413 
1414  parse_subscription_options(pstate, stmt->options,
1416 
1417  /*
1418  * The subscription option "two_phase" requires that
1419  * replication has passed the initial table synchronization
1420  * phase before the two_phase becomes properly enabled.
1421  *
1422  * But, having reached this two-phase commit "enabled" state
1423  * we must not allow any subsequent table initialization to
1424  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1425  * when the user had requested two_phase = on mode.
1426  *
1427  * The exception to this restriction is when copy_data =
1428  * false, because when copy_data is false the tablesync will
1429  * start already in READY state and will exit directly without
1430  * doing anything.
1431  *
1432  * For more details see comments atop worker.c.
1433  */
1434  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1435  ereport(ERROR,
1436  (errcode(ERRCODE_SYNTAX_ERROR),
1437  errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1438  errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1439 
1440  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1441 
1442  AlterSubscription_refresh(sub, opts.copy_data, NULL);
1443 
1444  break;
1445  }
1446 
1448  {
1449  parse_subscription_options(pstate, stmt->options, SUBOPT_LSN, &opts);
1450 
1451  /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
1452  Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
1453 
1454  /*
1455  * If the user sets subskiplsn, we do a sanity check to make
1456  * sure that the specified LSN is a probable value.
1457  */
1458  if (!XLogRecPtrIsInvalid(opts.lsn))
1459  {
1460  RepOriginId originid;
1461  char originname[NAMEDATALEN];
1462  XLogRecPtr remote_lsn;
1463 
1465  originname, sizeof(originname));
1466  originid = replorigin_by_name(originname, false);
1467  remote_lsn = replorigin_get_progress(originid, false);
1468 
1469  /* Check the given LSN is at least a future LSN */
1470  if (!XLogRecPtrIsInvalid(remote_lsn) && opts.lsn < remote_lsn)
1471  ereport(ERROR,
1472  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1473  errmsg("skip WAL location (LSN %X/%X) must be greater than origin LSN %X/%X",
1474  LSN_FORMAT_ARGS(opts.lsn),
1475  LSN_FORMAT_ARGS(remote_lsn))));
1476  }
1477 
1478  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
1479  replaces[Anum_pg_subscription_subskiplsn - 1] = true;
1480 
1481  update_tuple = true;
1482  break;
1483  }
1484 
1485  default:
1486  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1487  stmt->kind);
1488  }
1489 
1490  /* Update the catalog if needed. */
1491  if (update_tuple)
1492  {
1493  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1494  replaces);
1495 
1496  CatalogTupleUpdate(rel, &tup->t_self, tup);
1497 
1498  heap_freetuple(tup);
1499  }
1500 
1501  /*
1502  * Try to acquire the connection necessary for altering slot.
1503  *
1504  * This has to be at the end because otherwise if there is an error while
1505  * doing the database operations we won't be able to rollback altered
1506  * slot.
1507  */
1508  if (replaces[Anum_pg_subscription_subfailover - 1])
1509  {
1510  bool must_use_password;
1511  char *err;
1513 
1514  /* Load the library providing us libpq calls. */
1515  load_file("libpqwalreceiver", false);
1516 
1517  /* Try to connect to the publisher. */
1518  must_use_password = sub->passwordrequired && !sub->ownersuperuser;
1519  wrconn = walrcv_connect(sub->conninfo, true, true, must_use_password,
1520  sub->name, &err);
1521  if (!wrconn)
1522  ereport(ERROR,
1523  (errcode(ERRCODE_CONNECTION_FAILURE),
1524  errmsg("could not connect to the publisher: %s", err)));
1525 
1526  PG_TRY();
1527  {
1528  walrcv_alter_slot(wrconn, sub->slotname, opts.failover);
1529  }
1530  PG_FINALLY();
1531  {
1533  }
1534  PG_END_TRY();
1535  }
1536 
1538 
1539  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1540 
1541  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1542 
1543  /* Wake up related replication workers to handle this change quickly. */
1545 
1546  return myself;
1547 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2702
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4144
void LogicalRepWorkersWakeupAtCommit(Oid subid)
Definition: worker.c:4989
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition: worker.c:428
static Datum values[MAXATTR]
Definition: bootstrap.c:152
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define Assert(condition)
Definition: c.h:858
uint32 bits32
Definition: c.h:515
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:857
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#define PG_FINALLY(...)
Definition: elog.h:387
#define ereport(elevel,...)
Definition: elog.h:149
void err(int eval, const char *fmt,...)
Definition: err.c:43
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
Oid MyDatabaseId
Definition: globals.c:91
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1209
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
#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:1105
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1083
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid GetUserId(void)
Definition: miscinit.c:514
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:4223
@ ALTER_SUBSCRIPTION_DROP_PUBLICATION
Definition: parsenodes.h:4221
@ ALTER_SUBSCRIPTION_SET_PUBLICATION
Definition: parsenodes.h:4219
@ ALTER_SUBSCRIPTION_REFRESH
Definition: parsenodes.h:4222
@ ALTER_SUBSCRIPTION_SKIP
Definition: parsenodes.h:4224
@ ALTER_SUBSCRIPTION_OPTIONS
Definition: parsenodes.h:4217
@ ALTER_SUBSCRIPTION_CONNECTION
Definition: parsenodes.h:4218
@ ALTER_SUBSCRIPTION_ADD_PUBLICATION
Definition: parsenodes.h:4220
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:2301
static AmcheckOptions opts
Definition: pg_amcheck.c:111
#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:531
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)
#define SUBOPT_FAILOVER
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(void)
Definition: superuser.c:46
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:88
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
static WalReceiverConn * wrconn
Definition: walreceiver.c:92
#define walrcv_alter_slot(conn, slotname, failover)
Definition: walreceiver.h:458
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
Definition: walreceiver.h:432
#define walrcv_check_conninfo(conninfo, must_use_password)
Definition: walreceiver.h:434
#define walrcv_disconnect(conn)
Definition: walreceiver.h:464
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3584
#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(), Subscription::conninfo, CStringGetDatum(), CStringGetTextDatum, DirectFunctionCall1, elog, Subscription::enabled, ereport, err(), 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, Subscription::name, NAMEDATALEN, namein(), object_ownercheck(), OBJECT_SUBSCRIPTION, ObjectAddressSet, opts, Subscription::ownersuperuser, parse_subscription_options(), Subscription::passwordrequired, PG_END_TRY, PG_FINALLY, PG_TRY, 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_FAILOVER, SUBOPT_LSN, SUBOPT_ORIGIN, SUBOPT_PASSWORD_REQUIRED, SUBOPT_REFRESH, SUBOPT_RUN_AS_OWNER, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, superuser(), HeapTupleData::t_self, table_close(), table_open(), Subscription::twophasestate, values, walrcv_alter_slot, walrcv_check_conninfo, walrcv_connect, walrcv_disconnect, wrconn, and XLogRecPtrIsInvalid.

Referenced by ProcessUtilitySlow().

◆ AlterSubscriptionOwner()

ObjectAddress AlterSubscriptionOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 1957 of file subscriptioncmds.c.

1958 {
1959  Oid subid;
1960  HeapTuple tup;
1961  Relation rel;
1962  ObjectAddress address;
1963  Form_pg_subscription form;
1964 
1965  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1966 
1967  tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, MyDatabaseId,
1969 
1970  if (!HeapTupleIsValid(tup))
1971  ereport(ERROR,
1972  (errcode(ERRCODE_UNDEFINED_OBJECT),
1973  errmsg("subscription \"%s\" does not exist", name)));
1974 
1975  form = (Form_pg_subscription) GETSTRUCT(tup);
1976  subid = form->oid;
1977 
1978  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1979 
1980  ObjectAddressSet(address, SubscriptionRelationId, subid);
1981 
1982  heap_freetuple(tup);
1983 
1985 
1986  return address;
1987 }
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
const char * name

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

Referenced by ExecAlterOwnerStmt().

◆ AlterSubscriptionOwner_oid()

void AlterSubscriptionOwner_oid ( Oid  subid,
Oid  newOwnerId 
)

Definition at line 1993 of file subscriptioncmds.c.

1994 {
1995  HeapTuple tup;
1996  Relation rel;
1997 
1998  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1999 
2000  tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
2001 
2002  if (!HeapTupleIsValid(tup))
2003  ereport(ERROR,
2004  (errcode(ERRCODE_UNDEFINED_OBJECT),
2005  errmsg("subscription with OID %u does not exist", subid)));
2006 
2007  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
2008 
2009  heap_freetuple(tup);
2010 
2012 }
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86

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

Referenced by shdepReassignOwned().

◆ CreateSubscription()

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

Definition at line 579 of file subscriptioncmds.c.

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

2387 {
2388  /*
2389  * If no parameter value given, assume "true" is meant.
2390  */
2391  if (!def->arg)
2392  return LOGICALREP_STREAM_ON;
2393 
2394  /*
2395  * Allow 0, 1, "false", "true", "off", "on" or "parallel".
2396  */
2397  switch (nodeTag(def->arg))
2398  {
2399  case T_Integer:
2400  switch (intVal(def->arg))
2401  {
2402  case 0:
2403  return LOGICALREP_STREAM_OFF;
2404  case 1:
2405  return LOGICALREP_STREAM_ON;
2406  default:
2407  /* otherwise, error out below */
2408  break;
2409  }
2410  break;
2411  default:
2412  {
2413  char *sval = defGetString(def);
2414 
2415  /*
2416  * The set of strings accepted here should match up with the
2417  * grammar's opt_boolean_or_string production.
2418  */
2419  if (pg_strcasecmp(sval, "false") == 0 ||
2420  pg_strcasecmp(sval, "off") == 0)
2421  return LOGICALREP_STREAM_OFF;
2422  if (pg_strcasecmp(sval, "true") == 0 ||
2423  pg_strcasecmp(sval, "on") == 0)
2424  return LOGICALREP_STREAM_ON;
2425  if (pg_strcasecmp(sval, "parallel") == 0)
2427  }
2428  break;
2429  }
2430 
2431  ereport(ERROR,
2432  (errcode(ERRCODE_SYNTAX_ERROR),
2433  errmsg("%s requires a Boolean value or \"parallel\"",
2434  def->defname)));
2435  return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
2436 }
char * defGetString(DefElem *def)
Definition: define.c:48
#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:815
Node * arg
Definition: parsenodes.h:816
#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 1553 of file subscriptioncmds.c.

1554 {
1555  Relation rel;
1556  ObjectAddress myself;
1557  HeapTuple tup;
1558  Oid subid;
1559  Oid subowner;
1560  Datum datum;
1561  bool isnull;
1562  char *subname;
1563  char *conninfo;
1564  char *slotname;
1565  List *subworkers;
1566  ListCell *lc;
1567  char originname[NAMEDATALEN];
1568  char *err = NULL;
1570  Form_pg_subscription form;
1571  List *rstates;
1572  bool must_use_password;
1573 
1574  /*
1575  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1576  * launcher doesn't restart new worker during dropping the subscription
1577  */
1578  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1579 
1580  tup = SearchSysCache2(SUBSCRIPTIONNAME, MyDatabaseId,
1581  CStringGetDatum(stmt->subname));
1582 
1583  if (!HeapTupleIsValid(tup))
1584  {
1585  table_close(rel, NoLock);
1586 
1587  if (!stmt->missing_ok)
1588  ereport(ERROR,
1589  (errcode(ERRCODE_UNDEFINED_OBJECT),
1590  errmsg("subscription \"%s\" does not exist",
1591  stmt->subname)));
1592  else
1593  ereport(NOTICE,
1594  (errmsg("subscription \"%s\" does not exist, skipping",
1595  stmt->subname)));
1596 
1597  return;
1598  }
1599 
1600  form = (Form_pg_subscription) GETSTRUCT(tup);
1601  subid = form->oid;
1602  subowner = form->subowner;
1603  must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
1604 
1605  /* must be owner */
1606  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1608  stmt->subname);
1609 
1610  /* DROP hook for the subscription being removed */
1611  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1612 
1613  /*
1614  * Lock the subscription so nobody else can do anything with it (including
1615  * the replication workers).
1616  */
1617  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1618 
1619  /* Get subname */
1620  datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
1621  Anum_pg_subscription_subname);
1622  subname = pstrdup(NameStr(*DatumGetName(datum)));
1623 
1624  /* Get conninfo */
1625  datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
1626  Anum_pg_subscription_subconninfo);
1627  conninfo = TextDatumGetCString(datum);
1628 
1629  /* Get slotname */
1630  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1631  Anum_pg_subscription_subslotname, &isnull);
1632  if (!isnull)
1633  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1634  else
1635  slotname = NULL;
1636 
1637  /*
1638  * Since dropping a replication slot is not transactional, the replication
1639  * slot stays dropped even if the transaction rolls back. So we cannot
1640  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1641  * replication slot. Also, in this case, we report a message for dropping
1642  * the subscription to the cumulative stats system.
1643  *
1644  * XXX The command name should really be something like "DROP SUBSCRIPTION
1645  * of a subscription that is associated with a replication slot", but we
1646  * don't have the proper facilities for that.
1647  */
1648  if (slotname)
1649  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1650 
1651  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1652  EventTriggerSQLDropAddObject(&myself, true, true);
1653 
1654  /* Remove the tuple from catalog. */
1655  CatalogTupleDelete(rel, &tup->t_self);
1656 
1657  ReleaseSysCache(tup);
1658 
1659  /*
1660  * Stop all the subscription workers immediately.
1661  *
1662  * This is necessary if we are dropping the replication slot, so that the
1663  * slot becomes accessible.
1664  *
1665  * It is also necessary if the subscription is disabled and was disabled
1666  * in the same transaction. Then the workers haven't seen the disabling
1667  * yet and will still be running, leading to hangs later when we want to
1668  * drop the replication origin. If the subscription was disabled before
1669  * this transaction, then there shouldn't be any workers left, so this
1670  * won't make a difference.
1671  *
1672  * New workers won't be started because we hold an exclusive lock on the
1673  * subscription till the end of the transaction.
1674  */
1675  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1676  subworkers = logicalrep_workers_find(subid, false);
1677  LWLockRelease(LogicalRepWorkerLock);
1678  foreach(lc, subworkers)
1679  {
1681 
1683  }
1684  list_free(subworkers);
1685 
1686  /*
1687  * Remove the no-longer-useful entry in the launcher's table of apply
1688  * worker start times.
1689  *
1690  * If this transaction rolls back, the launcher might restart a failed
1691  * apply worker before wal_retrieve_retry_interval milliseconds have
1692  * elapsed, but that's pretty harmless.
1693  */
1695 
1696  /*
1697  * Cleanup of tablesync replication origins.
1698  *
1699  * Any READY-state relations would already have dealt with clean-ups.
1700  *
1701  * Note that the state can't change because we have already stopped both
1702  * the apply and tablesync workers and they can't restart because of
1703  * exclusive lock on the subscription.
1704  */
1705  rstates = GetSubscriptionRelations(subid, true);
1706  foreach(lc, rstates)
1707  {
1709  Oid relid = rstate->relid;
1710 
1711  /* Only cleanup resources of tablesync workers */
1712  if (!OidIsValid(relid))
1713  continue;
1714 
1715  /*
1716  * Drop the tablesync's origin tracking if exists.
1717  *
1718  * It is possible that the origin is not yet created for tablesync
1719  * worker so passing missing_ok = true. This can happen for the states
1720  * before SUBREL_STATE_FINISHEDCOPY.
1721  */
1722  ReplicationOriginNameForLogicalRep(subid, relid, originname,
1723  sizeof(originname));
1724  replorigin_drop_by_name(originname, true, false);
1725  }
1726 
1727  /* Clean up dependencies */
1728  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1729 
1730  /* Remove any associated relation synchronization states. */
1732 
1733  /* Remove the origin tracking if exists. */
1734  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
1735  replorigin_drop_by_name(originname, true, false);
1736 
1737  /*
1738  * Tell the cumulative stats system that the subscription is getting
1739  * dropped.
1740  */
1741  pgstat_drop_subscription(subid);
1742 
1743  /*
1744  * If there is no slot associated with the subscription, we can finish
1745  * here.
1746  */
1747  if (!slotname && rstates == NIL)
1748  {
1749  table_close(rel, NoLock);
1750  return;
1751  }
1752 
1753  /*
1754  * Try to acquire the connection necessary for dropping slots.
1755  *
1756  * Note: If the slotname is NONE/NULL then we allow the command to finish
1757  * and users need to manually cleanup the apply and tablesync worker slots
1758  * later.
1759  *
1760  * This has to be at the end because otherwise if there is an error while
1761  * doing the database operations we won't be able to rollback dropped
1762  * slot.
1763  */
1764  load_file("libpqwalreceiver", false);
1765 
1766  wrconn = walrcv_connect(conninfo, true, true, must_use_password,
1767  subname, &err);
1768  if (wrconn == NULL)
1769  {
1770  if (!slotname)
1771  {
1772  /* be tidy */
1773  list_free(rstates);
1774  table_close(rel, NoLock);
1775  return;
1776  }
1777  else
1778  {
1779  ReportSlotConnectionError(rstates, subid, slotname, err);
1780  }
1781  }
1782 
1783  PG_TRY();
1784  {
1785  foreach(lc, rstates)
1786  {
1788  Oid relid = rstate->relid;
1789 
1790  /* Only cleanup resources of tablesync workers */
1791  if (!OidIsValid(relid))
1792  continue;
1793 
1794  /*
1795  * Drop the tablesync slots associated with removed tables.
1796  *
1797  * For SYNCDONE/READY states, the tablesync slot is known to have
1798  * already been dropped by the tablesync worker.
1799  *
1800  * For other states, there is no certainty, maybe the slot does
1801  * not exist yet. Also, if we fail after removing some of the
1802  * slots, next time, it will again try to drop already dropped
1803  * slots and fail. For these reasons, we allow missing_ok = true
1804  * for the drop.
1805  */
1806  if (rstate->state != SUBREL_STATE_SYNCDONE)
1807  {
1808  char syncslotname[NAMEDATALEN] = {0};
1809 
1810  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1811  sizeof(syncslotname));
1812  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1813  }
1814  }
1815 
1816  list_free(rstates);
1817 
1818  /*
1819  * If there is a slot associated with the subscription, then drop the
1820  * replication slot at the publisher.
1821  */
1822  if (slotname)
1823  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1824  }
1825  PG_FINALLY();
1826  {
1828  }
1829  PG_END_TRY();
1830 
1831  table_close(rel, NoLock);
1832 }
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define NameStr(name)
Definition: c.h:746
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:275
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:609
void ApplyLauncherForgetWorkerStartTime(Oid subid)
Definition: launcher.c:1075
void list_free(List *list)
Definition: list.c:1546
#define NoLock
Definition: lockdefs.h:34
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1170
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1783
@ LW_SHARED
Definition: lwlock.h:115
char * pstrdup(const char *in)
Definition: mcxt.c:1695
#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:1039
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:266
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:479
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:229
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:510
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, Size szslot)
Definition: tablesync.c:1267

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, superuser_arg(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), HeapTupleData::t_self, table_close(), table_open(), TextDatumGetCString, walrcv_connect, walrcv_disconnect, and wrconn.

Referenced by ProcessUtilitySlow().