PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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 1100 of file subscriptioncmds.c.

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

2029{
2030 Oid subid;
2031 HeapTuple tup;
2032 Relation rel;
2033 ObjectAddress address;
2035
2036 rel = table_open(SubscriptionRelationId, RowExclusiveLock);
2037
2038 tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, MyDatabaseId,
2040
2041 if (!HeapTupleIsValid(tup))
2042 ereport(ERROR,
2043 (errcode(ERRCODE_UNDEFINED_OBJECT),
2044 errmsg("subscription \"%s\" does not exist", name)));
2045
2046 form = (Form_pg_subscription) GETSTRUCT(tup);
2047 subid = form->oid;
2048
2049 AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
2050
2051 ObjectAddressSet(address, SubscriptionRelationId, subid);
2052
2053 heap_freetuple(tup);
2054
2056
2057 return address;
2058}
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 2064 of file subscriptioncmds.c.

2065{
2066 HeapTuple tup;
2067 Relation rel;
2068
2069 rel = table_open(SubscriptionRelationId, RowExclusiveLock);
2070
2071 tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
2072
2073 if (!HeapTupleIsValid(tup))
2074 ereport(ERROR,
2075 (errcode(ERRCODE_UNDEFINED_OBJECT),
2076 errmsg("subscription with OID %u does not exist", subid)));
2077
2078 AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
2079
2080 heap_freetuple(tup);
2081
2083}
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:91

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

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

2460{
2461 /*
2462 * If no parameter value given, assume "true" is meant.
2463 */
2464 if (!def->arg)
2465 return LOGICALREP_STREAM_ON;
2466
2467 /*
2468 * Allow 0, 1, "false", "true", "off", "on" or "parallel".
2469 */
2470 switch (nodeTag(def->arg))
2471 {
2472 case T_Integer:
2473 switch (intVal(def->arg))
2474 {
2475 case 0:
2476 return LOGICALREP_STREAM_OFF;
2477 case 1:
2478 return LOGICALREP_STREAM_ON;
2479 default:
2480 /* otherwise, error out below */
2481 break;
2482 }
2483 break;
2484 default:
2485 {
2486 char *sval = defGetString(def);
2487
2488 /*
2489 * The set of strings accepted here should match up with the
2490 * grammar's opt_boolean_or_string production.
2491 */
2492 if (pg_strcasecmp(sval, "false") == 0 ||
2493 pg_strcasecmp(sval, "off") == 0)
2494 return LOGICALREP_STREAM_OFF;
2495 if (pg_strcasecmp(sval, "true") == 0 ||
2496 pg_strcasecmp(sval, "on") == 0)
2497 return LOGICALREP_STREAM_ON;
2498 if (pg_strcasecmp(sval, "parallel") == 0)
2499 return LOGICALREP_STREAM_PARALLEL;
2500 }
2501 break;
2502 }
2503
2504 ereport(ERROR,
2505 (errcode(ERRCODE_SYNTAX_ERROR),
2506 errmsg("%s requires a Boolean value or \"parallel\"",
2507 def->defname)));
2508 return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
2509}
char * defGetString(DefElem *def)
Definition: define.c:35
#define nodeTag(nodeptr)
Definition: nodes.h:139
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
char * defname
Definition: parsenodes.h:826
Node * arg
Definition: parsenodes.h:827
#define intVal(v)
Definition: value.h:79

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

Referenced by parse_output_parameters(), and parse_subscription_options().

◆ DropSubscription()

void DropSubscription ( DropSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 1626 of file subscriptioncmds.c.

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

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().