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

1133 {
1134  Relation rel;
1135  ObjectAddress myself;
1136  bool nulls[Natts_pg_subscription];
1137  bool replaces[Natts_pg_subscription];
1138  Datum values[Natts_pg_subscription];
1139  HeapTuple tup;
1140  Oid subid;
1141  bool update_tuple = false;
1142  bool update_failover = false;
1143  bool update_two_phase = false;
1144  Subscription *sub;
1145  Form_pg_subscription form;
1146  bits32 supported_opts;
1147  SubOpts opts = {0};
1148 
1149  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1150 
1151  /* Fetch the existing tuple. */
1152  tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, MyDatabaseId,
1153  CStringGetDatum(stmt->subname));
1154 
1155  if (!HeapTupleIsValid(tup))
1156  ereport(ERROR,
1157  (errcode(ERRCODE_UNDEFINED_OBJECT),
1158  errmsg("subscription \"%s\" does not exist",
1159  stmt->subname)));
1160 
1161  form = (Form_pg_subscription) GETSTRUCT(tup);
1162  subid = form->oid;
1163 
1164  /* must be owner */
1165  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1167  stmt->subname);
1168 
1169  sub = GetSubscription(subid, false);
1170 
1171  /*
1172  * Don't allow non-superuser modification of a subscription with
1173  * password_required=false.
1174  */
1175  if (!sub->passwordrequired && !superuser())
1176  ereport(ERROR,
1177  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1178  errmsg("password_required=false is superuser-only"),
1179  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1180 
1181  /* Lock the subscription so nobody else can do anything with it. */
1182  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1183 
1184  /* Form a new tuple. */
1185  memset(values, 0, sizeof(values));
1186  memset(nulls, false, sizeof(nulls));
1187  memset(replaces, false, sizeof(replaces));
1188 
1189  switch (stmt->kind)
1190  {
1192  {
1193  supported_opts = (SUBOPT_SLOT_NAME |
1199  SUBOPT_ORIGIN);
1200 
1201  parse_subscription_options(pstate, stmt->options,
1202  supported_opts, &opts);
1203 
1204  if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1205  {
1206  /*
1207  * The subscription must be disabled to allow slot_name as
1208  * 'none', otherwise, the apply worker will repeatedly try
1209  * to stream the data using that slot_name which neither
1210  * exists on the publisher nor the user will be allowed to
1211  * create it.
1212  */
1213  if (sub->enabled && !opts.slot_name)
1214  ereport(ERROR,
1215  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1216  errmsg("cannot set %s for enabled subscription",
1217  "slot_name = NONE")));
1218 
1219  if (opts.slot_name)
1220  values[Anum_pg_subscription_subslotname - 1] =
1222  else
1223  nulls[Anum_pg_subscription_subslotname - 1] = true;
1224  replaces[Anum_pg_subscription_subslotname - 1] = true;
1225  }
1226 
1227  if (opts.synchronous_commit)
1228  {
1229  values[Anum_pg_subscription_subsynccommit - 1] =
1230  CStringGetTextDatum(opts.synchronous_commit);
1231  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1232  }
1233 
1234  if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1235  {
1236  values[Anum_pg_subscription_subbinary - 1] =
1237  BoolGetDatum(opts.binary);
1238  replaces[Anum_pg_subscription_subbinary - 1] = true;
1239  }
1240 
1241  if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1242  {
1243  values[Anum_pg_subscription_substream - 1] =
1244  CharGetDatum(opts.streaming);
1245  replaces[Anum_pg_subscription_substream - 1] = true;
1246  }
1247 
1248  if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1249  {
1250  values[Anum_pg_subscription_subdisableonerr - 1]
1251  = BoolGetDatum(opts.disableonerr);
1252  replaces[Anum_pg_subscription_subdisableonerr - 1]
1253  = true;
1254  }
1255 
1256  if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1257  {
1258  /* Non-superuser may not disable password_required. */
1259  if (!opts.passwordrequired && !superuser())
1260  ereport(ERROR,
1261  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1262  errmsg("password_required=false is superuser-only"),
1263  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1264 
1265  values[Anum_pg_subscription_subpasswordrequired - 1]
1266  = BoolGetDatum(opts.passwordrequired);
1267  replaces[Anum_pg_subscription_subpasswordrequired - 1]
1268  = true;
1269  }
1270 
1271  if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
1272  {
1273  values[Anum_pg_subscription_subrunasowner - 1] =
1274  BoolGetDatum(opts.runasowner);
1275  replaces[Anum_pg_subscription_subrunasowner - 1] = true;
1276  }
1277 
1278  if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT))
1279  {
1280  /*
1281  * We need to update both the slot and the subscription
1282  * for the two_phase option. We can enable the two_phase
1283  * option for a slot only once the initial data
1284  * synchronization is done. This is to avoid missing some
1285  * data as explained in comments atop worker.c.
1286  */
1287  update_two_phase = !opts.twophase;
1288 
1289  CheckAlterSubOption(sub, "two_phase", update_two_phase,
1290  isTopLevel);
1291 
1292  /*
1293  * Modifying the two_phase slot option requires a slot
1294  * lookup by slot name, so changing the slot name at the
1295  * same time is not allowed.
1296  */
1297  if (update_two_phase &&
1298  IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1299  ereport(ERROR,
1300  (errcode(ERRCODE_SYNTAX_ERROR),
1301  errmsg("slot_name and two_phase cannot be altered at the same time")));
1302 
1303  /*
1304  * Note that workers may still survive even if the
1305  * subscription has been disabled.
1306  *
1307  * Ensure workers have already been exited to avoid
1308  * getting prepared transactions while we are disabling
1309  * the two_phase option. Otherwise, the changes of an
1310  * already prepared transaction can be replicated again
1311  * along with its corresponding commit, leading to
1312  * duplicate data or errors.
1313  */
1314  if (logicalrep_workers_find(subid, true, true))
1315  ereport(ERROR,
1316  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1317  errmsg("cannot alter two_phase when logical replication worker is still running"),
1318  errhint("Try again after some time.")));
1319 
1320  /*
1321  * two_phase cannot be disabled if there are any
1322  * uncommitted prepared transactions present otherwise it
1323  * can lead to duplicate data or errors as explained in
1324  * the comment above.
1325  */
1326  if (update_two_phase &&
1328  LookupGXactBySubid(subid))
1329  ereport(ERROR,
1330  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1331  errmsg("cannot disable two_phase when prepared transactions are present"),
1332  errhint("Resolve these transactions and try again.")));
1333 
1334  /* Change system catalog accordingly */
1335  values[Anum_pg_subscription_subtwophasestate - 1] =
1336  CharGetDatum(opts.twophase ?
1339  replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
1340  }
1341 
1342  if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1343  {
1344  /*
1345  * Similar to the two_phase case above, we need to update
1346  * the failover option for both the slot and the
1347  * subscription.
1348  */
1349  update_failover = true;
1350 
1351  CheckAlterSubOption(sub, "failover", update_failover,
1352  isTopLevel);
1353 
1354  values[Anum_pg_subscription_subfailover - 1] =
1355  BoolGetDatum(opts.failover);
1356  replaces[Anum_pg_subscription_subfailover - 1] = true;
1357  }
1358 
1359  if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1360  {
1361  values[Anum_pg_subscription_suborigin - 1] =
1362  CStringGetTextDatum(opts.origin);
1363  replaces[Anum_pg_subscription_suborigin - 1] = true;
1364  }
1365 
1366  update_tuple = true;
1367  break;
1368  }
1369 
1371  {
1372  parse_subscription_options(pstate, stmt->options,
1373  SUBOPT_ENABLED, &opts);
1374  Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
1375 
1376  if (!sub->slotname && opts.enabled)
1377  ereport(ERROR,
1378  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1379  errmsg("cannot enable subscription that does not have a slot name")));
1380 
1381  values[Anum_pg_subscription_subenabled - 1] =
1382  BoolGetDatum(opts.enabled);
1383  replaces[Anum_pg_subscription_subenabled - 1] = true;
1384 
1385  if (opts.enabled)
1387 
1388  update_tuple = true;
1389  break;
1390  }
1391 
1393  /* Load the library providing us libpq calls. */
1394  load_file("libpqwalreceiver", false);
1395  /* Check the connection info string. */
1396  walrcv_check_conninfo(stmt->conninfo,
1397  sub->passwordrequired && !sub->ownersuperuser);
1398 
1399  values[Anum_pg_subscription_subconninfo - 1] =
1400  CStringGetTextDatum(stmt->conninfo);
1401  replaces[Anum_pg_subscription_subconninfo - 1] = true;
1402  update_tuple = true;
1403  break;
1404 
1406  {
1407  supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1408  parse_subscription_options(pstate, stmt->options,
1409  supported_opts, &opts);
1410 
1411  values[Anum_pg_subscription_subpublications - 1] =
1412  publicationListToArray(stmt->publication);
1413  replaces[Anum_pg_subscription_subpublications - 1] = true;
1414 
1415  update_tuple = true;
1416 
1417  /* Refresh if user asked us to. */
1418  if (opts.refresh)
1419  {
1420  if (!sub->enabled)
1421  ereport(ERROR,
1422  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1423  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1424  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1425 
1426  /*
1427  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1428  * not allowed.
1429  */
1430  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1431  ereport(ERROR,
1432  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1433  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1434  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1435 
1436  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1437 
1438  /* Make sure refresh sees the new list of publications. */
1439  sub->publications = stmt->publication;
1440 
1441  AlterSubscription_refresh(sub, opts.copy_data,
1442  stmt->publication);
1443  }
1444 
1445  break;
1446  }
1447 
1450  {
1451  List *publist;
1452  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1453 
1454  supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1455  parse_subscription_options(pstate, stmt->options,
1456  supported_opts, &opts);
1457 
1458  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1459  values[Anum_pg_subscription_subpublications - 1] =
1460  publicationListToArray(publist);
1461  replaces[Anum_pg_subscription_subpublications - 1] = true;
1462 
1463  update_tuple = true;
1464 
1465  /* Refresh if user asked us to. */
1466  if (opts.refresh)
1467  {
1468  /* We only need to validate user specified publications. */
1469  List *validate_publications = (isadd) ? stmt->publication : NULL;
1470 
1471  if (!sub->enabled)
1472  ereport(ERROR,
1473  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1474  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1475  /* translator: %s is an SQL ALTER command */
1476  errhint("Use %s instead.",
1477  isadd ?
1478  "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
1479  "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
1480 
1481  /*
1482  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1483  * not allowed.
1484  */
1485  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1486  ereport(ERROR,
1487  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1488  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1489  /* translator: %s is an SQL ALTER command */
1490  errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
1491  isadd ?
1492  "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
1493  "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
1494 
1495  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1496 
1497  /* Refresh the new list of publications. */
1498  sub->publications = publist;
1499 
1500  AlterSubscription_refresh(sub, opts.copy_data,
1501  validate_publications);
1502  }
1503 
1504  break;
1505  }
1506 
1508  {
1509  if (!sub->enabled)
1510  ereport(ERROR,
1511  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1512  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1513 
1514  parse_subscription_options(pstate, stmt->options,
1516 
1517  /*
1518  * The subscription option "two_phase" requires that
1519  * replication has passed the initial table synchronization
1520  * phase before the two_phase becomes properly enabled.
1521  *
1522  * But, having reached this two-phase commit "enabled" state
1523  * we must not allow any subsequent table initialization to
1524  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1525  * when the user had requested two_phase = on mode.
1526  *
1527  * The exception to this restriction is when copy_data =
1528  * false, because when copy_data is false the tablesync will
1529  * start already in READY state and will exit directly without
1530  * doing anything.
1531  *
1532  * For more details see comments atop worker.c.
1533  */
1534  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1535  ereport(ERROR,
1536  (errcode(ERRCODE_SYNTAX_ERROR),
1537  errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1538  errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1539 
1540  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1541 
1542  AlterSubscription_refresh(sub, opts.copy_data, NULL);
1543 
1544  break;
1545  }
1546 
1548  {
1549  parse_subscription_options(pstate, stmt->options, SUBOPT_LSN, &opts);
1550 
1551  /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
1552  Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
1553 
1554  /*
1555  * If the user sets subskiplsn, we do a sanity check to make
1556  * sure that the specified LSN is a probable value.
1557  */
1558  if (!XLogRecPtrIsInvalid(opts.lsn))
1559  {
1560  RepOriginId originid;
1561  char originname[NAMEDATALEN];
1562  XLogRecPtr remote_lsn;
1563 
1565  originname, sizeof(originname));
1566  originid = replorigin_by_name(originname, false);
1567  remote_lsn = replorigin_get_progress(originid, false);
1568 
1569  /* Check the given LSN is at least a future LSN */
1570  if (!XLogRecPtrIsInvalid(remote_lsn) && opts.lsn < remote_lsn)
1571  ereport(ERROR,
1572  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1573  errmsg("skip WAL location (LSN %X/%X) must be greater than origin LSN %X/%X",
1574  LSN_FORMAT_ARGS(opts.lsn),
1575  LSN_FORMAT_ARGS(remote_lsn))));
1576  }
1577 
1578  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
1579  replaces[Anum_pg_subscription_subskiplsn - 1] = true;
1580 
1581  update_tuple = true;
1582  break;
1583  }
1584 
1585  default:
1586  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1587  stmt->kind);
1588  }
1589 
1590  /* Update the catalog if needed. */
1591  if (update_tuple)
1592  {
1593  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1594  replaces);
1595 
1596  CatalogTupleUpdate(rel, &tup->t_self, tup);
1597 
1598  heap_freetuple(tup);
1599  }
1600 
1601  /*
1602  * Try to acquire the connection necessary for altering the slot, if
1603  * needed.
1604  *
1605  * This has to be at the end because otherwise if there is an error while
1606  * doing the database operations we won't be able to rollback altered
1607  * slot.
1608  */
1609  if (update_failover || update_two_phase)
1610  {
1611  bool must_use_password;
1612  char *err;
1614 
1615  /* Load the library providing us libpq calls. */
1616  load_file("libpqwalreceiver", false);
1617 
1618  /* Try to connect to the publisher. */
1619  must_use_password = sub->passwordrequired && !sub->ownersuperuser;
1620  wrconn = walrcv_connect(sub->conninfo, true, true, must_use_password,
1621  sub->name, &err);
1622  if (!wrconn)
1623  ereport(ERROR,
1624  (errcode(ERRCODE_CONNECTION_FAILURE),
1625  errmsg("subscription \"%s\" could not connect to the publisher: %s",
1626  sub->name, err)));
1627 
1628  PG_TRY();
1629  {
1631  update_failover ? &opts.failover : NULL,
1632  update_two_phase ? &opts.twophase : NULL);
1633  }
1634  PG_FINALLY();
1635  {
1637  }
1638  PG_END_TRY();
1639  }
1640 
1642 
1643  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1644 
1645  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1646 
1647  /* Wake up related replication workers to handle this change quickly. */
1649 
1650  return myself;
1651 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2700
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4142
void LogicalRepWorkersWakeupAtCommit(Oid subid)
Definition: worker.c:4969
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition: worker.c:425
static Datum values[MAXATTR]
Definition: bootstrap.c:150
#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:853
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:92
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
List * logicalrep_workers_find(Oid subid, bool only_running, bool acquire_lock)
Definition: launcher.c:275
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:1111
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1073
#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:4216
@ ALTER_SUBSCRIPTION_DROP_PUBLICATION
Definition: parsenodes.h:4214
@ ALTER_SUBSCRIPTION_SET_PUBLICATION
Definition: parsenodes.h:4212
@ ALTER_SUBSCRIPTION_REFRESH
Definition: parsenodes.h:4215
@ ALTER_SUBSCRIPTION_SKIP
Definition: parsenodes.h:4217
@ ALTER_SUBSCRIPTION_OPTIONS
Definition: parsenodes.h:4210
@ ALTER_SUBSCRIPTION_CONNECTION
Definition: parsenodes.h:4211
@ ALTER_SUBSCRIPTION_ADD_PUBLICATION
Definition: parsenodes.h:4213
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:2299
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_DISABLED
#define LOGICALREP_TWOPHASE_STATE_PENDING
#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
static void CheckAlterSubOption(Subscription *sub, const char *option, bool slot_needs_update, bool isTopLevel)
#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
#define SUBOPT_TWOPHASE_COMMIT
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
bool LookupGXactBySubid(Oid subid)
Definition: twophase.c:2742
static WalReceiverConn * wrconn
Definition: walreceiver.c:92
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
Definition: walreceiver.h:434
#define walrcv_check_conninfo(conninfo, must_use_password)
Definition: walreceiver.h:436
#define walrcv_alter_slot(conn, slotname, failover, two_phase)
Definition: walreceiver.h:460
#define walrcv_disconnect(conn)
Definition: walreceiver.h:466
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3622
#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(), CheckAlterSubOption(), 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_DISABLED, LOGICALREP_TWOPHASE_STATE_ENABLED, LOGICALREP_TWOPHASE_STATE_PENDING, logicalrep_workers_find(), LogicalRepWorkersWakeupAtCommit(), LookupGXactBySubid(), 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, SUBOPT_TWOPHASE_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 2059 of file subscriptioncmds.c.

2060 {
2061  Oid subid;
2062  HeapTuple tup;
2063  Relation rel;
2064  ObjectAddress address;
2065  Form_pg_subscription form;
2066 
2067  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
2068 
2069  tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, MyDatabaseId,
2071 
2072  if (!HeapTupleIsValid(tup))
2073  ereport(ERROR,
2074  (errcode(ERRCODE_UNDEFINED_OBJECT),
2075  errmsg("subscription \"%s\" does not exist", name)));
2076 
2077  form = (Form_pg_subscription) GETSTRUCT(tup);
2078  subid = form->oid;
2079 
2080  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
2081 
2082  ObjectAddressSet(address, SubscriptionRelationId, subid);
2083 
2084  heap_freetuple(tup);
2085 
2087 
2088  return address;
2089 }
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 2095 of file subscriptioncmds.c.

2096 {
2097  HeapTuple tup;
2098  Relation rel;
2099 
2100  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
2101 
2102  tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
2103 
2104  if (!HeapTupleIsValid(tup))
2105  ereport(ERROR,
2106  (errcode(ERRCODE_UNDEFINED_OBJECT),
2107  errmsg("subscription with OID %u does not exist", subid)));
2108 
2109  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
2110 
2111  heap_freetuple(tup);
2112 
2114 }
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_Owner().

◆ CreateSubscription()

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

Definition at line 570 of file subscriptioncmds.c.

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

2489 {
2490  /*
2491  * If no parameter value given, assume "true" is meant.
2492  */
2493  if (!def->arg)
2494  return LOGICALREP_STREAM_ON;
2495 
2496  /*
2497  * Allow 0, 1, "false", "true", "off", "on" or "parallel".
2498  */
2499  switch (nodeTag(def->arg))
2500  {
2501  case T_Integer:
2502  switch (intVal(def->arg))
2503  {
2504  case 0:
2505  return LOGICALREP_STREAM_OFF;
2506  case 1:
2507  return LOGICALREP_STREAM_ON;
2508  default:
2509  /* otherwise, error out below */
2510  break;
2511  }
2512  break;
2513  default:
2514  {
2515  char *sval = defGetString(def);
2516 
2517  /*
2518  * The set of strings accepted here should match up with the
2519  * grammar's opt_boolean_or_string production.
2520  */
2521  if (pg_strcasecmp(sval, "false") == 0 ||
2522  pg_strcasecmp(sval, "off") == 0)
2523  return LOGICALREP_STREAM_OFF;
2524  if (pg_strcasecmp(sval, "true") == 0 ||
2525  pg_strcasecmp(sval, "on") == 0)
2526  return LOGICALREP_STREAM_ON;
2527  if (pg_strcasecmp(sval, "parallel") == 0)
2529  }
2530  break;
2531  }
2532 
2533  ereport(ERROR,
2534  (errcode(ERRCODE_SYNTAX_ERROR),
2535  errmsg("%s requires a Boolean value or \"parallel\"",
2536  def->defname)));
2537  return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
2538 }
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 1657 of file subscriptioncmds.c.

1658 {
1659  Relation rel;
1660  ObjectAddress myself;
1661  HeapTuple tup;
1662  Oid subid;
1663  Oid subowner;
1664  Datum datum;
1665  bool isnull;
1666  char *subname;
1667  char *conninfo;
1668  char *slotname;
1669  List *subworkers;
1670  ListCell *lc;
1671  char originname[NAMEDATALEN];
1672  char *err = NULL;
1674  Form_pg_subscription form;
1675  List *rstates;
1676  bool must_use_password;
1677 
1678  /*
1679  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1680  * launcher doesn't restart new worker during dropping the subscription
1681  */
1682  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1683 
1684  tup = SearchSysCache2(SUBSCRIPTIONNAME, MyDatabaseId,
1685  CStringGetDatum(stmt->subname));
1686 
1687  if (!HeapTupleIsValid(tup))
1688  {
1689  table_close(rel, NoLock);
1690 
1691  if (!stmt->missing_ok)
1692  ereport(ERROR,
1693  (errcode(ERRCODE_UNDEFINED_OBJECT),
1694  errmsg("subscription \"%s\" does not exist",
1695  stmt->subname)));
1696  else
1697  ereport(NOTICE,
1698  (errmsg("subscription \"%s\" does not exist, skipping",
1699  stmt->subname)));
1700 
1701  return;
1702  }
1703 
1704  form = (Form_pg_subscription) GETSTRUCT(tup);
1705  subid = form->oid;
1706  subowner = form->subowner;
1707  must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
1708 
1709  /* must be owner */
1710  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1712  stmt->subname);
1713 
1714  /* DROP hook for the subscription being removed */
1715  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1716 
1717  /*
1718  * Lock the subscription so nobody else can do anything with it (including
1719  * the replication workers).
1720  */
1721  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1722 
1723  /* Get subname */
1724  datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
1725  Anum_pg_subscription_subname);
1726  subname = pstrdup(NameStr(*DatumGetName(datum)));
1727 
1728  /* Get conninfo */
1729  datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
1730  Anum_pg_subscription_subconninfo);
1731  conninfo = TextDatumGetCString(datum);
1732 
1733  /* Get slotname */
1734  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1735  Anum_pg_subscription_subslotname, &isnull);
1736  if (!isnull)
1737  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1738  else
1739  slotname = NULL;
1740 
1741  /*
1742  * Since dropping a replication slot is not transactional, the replication
1743  * slot stays dropped even if the transaction rolls back. So we cannot
1744  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1745  * replication slot. Also, in this case, we report a message for dropping
1746  * the subscription to the cumulative stats system.
1747  *
1748  * XXX The command name should really be something like "DROP SUBSCRIPTION
1749  * of a subscription that is associated with a replication slot", but we
1750  * don't have the proper facilities for that.
1751  */
1752  if (slotname)
1753  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1754 
1755  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1756  EventTriggerSQLDropAddObject(&myself, true, true);
1757 
1758  /* Remove the tuple from catalog. */
1759  CatalogTupleDelete(rel, &tup->t_self);
1760 
1761  ReleaseSysCache(tup);
1762 
1763  /*
1764  * Stop all the subscription workers immediately.
1765  *
1766  * This is necessary if we are dropping the replication slot, so that the
1767  * slot becomes accessible.
1768  *
1769  * It is also necessary if the subscription is disabled and was disabled
1770  * in the same transaction. Then the workers haven't seen the disabling
1771  * yet and will still be running, leading to hangs later when we want to
1772  * drop the replication origin. If the subscription was disabled before
1773  * this transaction, then there shouldn't be any workers left, so this
1774  * won't make a difference.
1775  *
1776  * New workers won't be started because we hold an exclusive lock on the
1777  * subscription till the end of the transaction.
1778  */
1779  subworkers = logicalrep_workers_find(subid, false, true);
1780  foreach(lc, subworkers)
1781  {
1783 
1785  }
1786  list_free(subworkers);
1787 
1788  /*
1789  * Remove the no-longer-useful entry in the launcher's table of apply
1790  * worker start times.
1791  *
1792  * If this transaction rolls back, the launcher might restart a failed
1793  * apply worker before wal_retrieve_retry_interval milliseconds have
1794  * elapsed, but that's pretty harmless.
1795  */
1797 
1798  /*
1799  * Cleanup of tablesync replication origins.
1800  *
1801  * Any READY-state relations would already have dealt with clean-ups.
1802  *
1803  * Note that the state can't change because we have already stopped both
1804  * the apply and tablesync workers and they can't restart because of
1805  * exclusive lock on the subscription.
1806  */
1807  rstates = GetSubscriptionRelations(subid, true);
1808  foreach(lc, rstates)
1809  {
1811  Oid relid = rstate->relid;
1812 
1813  /* Only cleanup resources of tablesync workers */
1814  if (!OidIsValid(relid))
1815  continue;
1816 
1817  /*
1818  * Drop the tablesync's origin tracking if exists.
1819  *
1820  * It is possible that the origin is not yet created for tablesync
1821  * worker so passing missing_ok = true. This can happen for the states
1822  * before SUBREL_STATE_FINISHEDCOPY.
1823  */
1824  ReplicationOriginNameForLogicalRep(subid, relid, originname,
1825  sizeof(originname));
1826  replorigin_drop_by_name(originname, true, false);
1827  }
1828 
1829  /* Clean up dependencies */
1830  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1831 
1832  /* Remove any associated relation synchronization states. */
1834 
1835  /* Remove the origin tracking if exists. */
1836  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
1837  replorigin_drop_by_name(originname, true, false);
1838 
1839  /*
1840  * Tell the cumulative stats system that the subscription is getting
1841  * dropped.
1842  */
1843  pgstat_drop_subscription(subid);
1844 
1845  /*
1846  * If there is no slot associated with the subscription, we can finish
1847  * here.
1848  */
1849  if (!slotname && rstates == NIL)
1850  {
1851  table_close(rel, NoLock);
1852  return;
1853  }
1854 
1855  /*
1856  * Try to acquire the connection necessary for dropping slots.
1857  *
1858  * Note: If the slotname is NONE/NULL then we allow the command to finish
1859  * and users need to manually cleanup the apply and tablesync worker slots
1860  * later.
1861  *
1862  * This has to be at the end because otherwise if there is an error while
1863  * doing the database operations we won't be able to rollback dropped
1864  * slot.
1865  */
1866  load_file("libpqwalreceiver", false);
1867 
1868  wrconn = walrcv_connect(conninfo, true, true, must_use_password,
1869  subname, &err);
1870  if (wrconn == NULL)
1871  {
1872  if (!slotname)
1873  {
1874  /* be tidy */
1875  list_free(rstates);
1876  table_close(rel, NoLock);
1877  return;
1878  }
1879  else
1880  {
1881  ReportSlotConnectionError(rstates, subid, slotname, err);
1882  }
1883  }
1884 
1885  PG_TRY();
1886  {
1887  foreach(lc, rstates)
1888  {
1890  Oid relid = rstate->relid;
1891 
1892  /* Only cleanup resources of tablesync workers */
1893  if (!OidIsValid(relid))
1894  continue;
1895 
1896  /*
1897  * Drop the tablesync slots associated with removed tables.
1898  *
1899  * For SYNCDONE/READY states, the tablesync slot is known to have
1900  * already been dropped by the tablesync worker.
1901  *
1902  * For other states, there is no certainty, maybe the slot does
1903  * not exist yet. Also, if we fail after removing some of the
1904  * slots, next time, it will again try to drop already dropped
1905  * slots and fail. For these reasons, we allow missing_ok = true
1906  * for the drop.
1907  */
1908  if (rstate->state != SUBREL_STATE_SYNCDONE)
1909  {
1910  char syncslotname[NAMEDATALEN] = {0};
1911 
1912  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1913  sizeof(syncslotname));
1914  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1915  }
1916  }
1917 
1918  list_free(rstates);
1919 
1920  /*
1921  * If there is a slot associated with the subscription, then drop the
1922  * replication slot at the publisher.
1923  */
1924  if (slotname)
1925  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1926  }
1927  PG_FINALLY();
1928  {
1930  }
1931  PG_END_TRY();
1932 
1933  table_close(rel, NoLock);
1934 }
#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
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:615
void ApplyLauncherForgetWorkerStartTime(Oid subid)
Definition: launcher.c:1081
void list_free(List *list)
Definition: list.c:1546
#define NoLock
Definition: lockdefs.h:34
char * pstrdup(const char *in)
Definition: mcxt.c:1696
#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:1047
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(), 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().