PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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)
 
void CheckSubDeadTupleRetention (bool check_guc, bool sub_disabled, int elevel_for_sub_disabled, bool retain_dead_tuples, bool retention_active, bool max_retention_set)
 

Function Documentation

◆ AlterSubscription()

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

Definition at line 1413 of file subscriptioncmds.c.

1415{
1416 Relation rel;
1418 bool nulls[Natts_pg_subscription];
1421 HeapTuple tup;
1422 Oid subid;
1423 bool update_tuple = false;
1424 bool update_failover = false;
1425 bool update_two_phase = false;
1426 bool check_pub_rdt = false;
1427 bool retain_dead_tuples;
1428 int max_retention;
1429 bool retention_active;
1430 char *origin;
1431 Subscription *sub;
1434 SubOpts opts = {0};
1435
1437
1438 /* Fetch the existing tuple. */
1440 CStringGetDatum(stmt->subname));
1441
1442 if (!HeapTupleIsValid(tup))
1443 ereport(ERROR,
1445 errmsg("subscription \"%s\" does not exist",
1446 stmt->subname)));
1447
1449 subid = form->oid;
1450
1451 /* must be owner */
1454 stmt->subname);
1455
1456 /*
1457 * Skip ACL checks on the subscription's foreign server, if any. If
1458 * changing the server (or replacing it with a raw connection), then the
1459 * old one will be removed anyway. If changing something unrelated,
1460 * there's no need to do an additional ACL check here; that will be done
1461 * by the subscription worker anyway.
1462 */
1463 sub = GetSubscription(subid, false, false);
1464
1466 origin = sub->origin;
1469
1470 /*
1471 * Don't allow non-superuser modification of a subscription with
1472 * password_required=false.
1473 */
1474 if (!sub->passwordrequired && !superuser())
1475 ereport(ERROR,
1477 errmsg("password_required=false is superuser-only"),
1478 errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1479
1480 /* Lock the subscription so nobody else can do anything with it. */
1482
1483 /* Form a new tuple. */
1484 memset(values, 0, sizeof(values));
1485 memset(nulls, false, sizeof(nulls));
1486 memset(replaces, false, sizeof(replaces));
1487
1489
1490 switch (stmt->kind)
1491 {
1493 {
1504
1505 parse_subscription_options(pstate, stmt->options,
1507
1508 if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1509 {
1510 /*
1511 * The subscription must be disabled to allow slot_name as
1512 * 'none', otherwise, the apply worker will repeatedly try
1513 * to stream the data using that slot_name which neither
1514 * exists on the publisher nor the user will be allowed to
1515 * create it.
1516 */
1517 if (sub->enabled && !opts.slot_name)
1518 ereport(ERROR,
1520 errmsg("cannot set %s for enabled subscription",
1521 "slot_name = NONE")));
1522
1523 if (opts.slot_name)
1526 else
1527 nulls[Anum_pg_subscription_subslotname - 1] = true;
1529 }
1530
1531 if (opts.synchronous_commit)
1532 {
1534 CStringGetTextDatum(opts.synchronous_commit);
1536 }
1537
1538 if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1539 {
1541 BoolGetDatum(opts.binary);
1543 }
1544
1545 if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1546 {
1548 CharGetDatum(opts.streaming);
1550 }
1551
1552 if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1553 {
1555 = BoolGetDatum(opts.disableonerr);
1557 = true;
1558 }
1559
1560 if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1561 {
1562 /* Non-superuser may not disable password_required. */
1563 if (!opts.passwordrequired && !superuser())
1564 ereport(ERROR,
1566 errmsg("password_required=false is superuser-only"),
1567 errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1568
1570 = BoolGetDatum(opts.passwordrequired);
1572 = true;
1573 }
1574
1575 if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
1576 {
1578 BoolGetDatum(opts.runasowner);
1580 }
1581
1582 if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT))
1583 {
1584 /*
1585 * We need to update both the slot and the subscription
1586 * for the two_phase option. We can enable the two_phase
1587 * option for a slot only once the initial data
1588 * synchronization is done. This is to avoid missing some
1589 * data as explained in comments atop worker.c.
1590 */
1591 update_two_phase = !opts.twophase;
1592
1593 CheckAlterSubOption(sub, "two_phase", update_two_phase,
1594 isTopLevel);
1595
1596 /*
1597 * Modifying the two_phase slot option requires a slot
1598 * lookup by slot name, so changing the slot name at the
1599 * same time is not allowed.
1600 */
1601 if (update_two_phase &&
1602 IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1603 ereport(ERROR,
1605 errmsg("\"slot_name\" and \"two_phase\" cannot be altered at the same time")));
1606
1607 /*
1608 * Note that workers may still survive even if the
1609 * subscription has been disabled.
1610 *
1611 * Ensure workers have already been exited to avoid
1612 * getting prepared transactions while we are disabling
1613 * the two_phase option. Otherwise, the changes of an
1614 * already prepared transaction can be replicated again
1615 * along with its corresponding commit, leading to
1616 * duplicate data or errors.
1617 */
1618 if (logicalrep_workers_find(subid, true, true))
1619 ereport(ERROR,
1621 errmsg("cannot alter \"two_phase\" when logical replication worker is still running"),
1622 errhint("Try again after some time.")));
1623
1624 /*
1625 * two_phase cannot be disabled if there are any
1626 * uncommitted prepared transactions present otherwise it
1627 * can lead to duplicate data or errors as explained in
1628 * the comment above.
1629 */
1630 if (update_two_phase &&
1632 LookupGXactBySubid(subid))
1633 ereport(ERROR,
1635 errmsg("cannot disable \"two_phase\" when prepared transactions exist"),
1636 errhint("Resolve these transactions and try again.")));
1637
1638 /* Change system catalog accordingly */
1640 CharGetDatum(opts.twophase ?
1644 }
1645
1646 if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1647 {
1648 /*
1649 * Similar to the two_phase case above, we need to update
1650 * the failover option for both the slot and the
1651 * subscription.
1652 */
1653 update_failover = true;
1654
1655 CheckAlterSubOption(sub, "failover", update_failover,
1656 isTopLevel);
1657
1659 BoolGetDatum(opts.failover);
1661 }
1662
1663 if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
1664 {
1666 BoolGetDatum(opts.retaindeadtuples);
1668
1669 /*
1670 * Update the retention status only if there's a change in
1671 * the retain_dead_tuples option value.
1672 *
1673 * Automatically marking retention as active when
1674 * retain_dead_tuples is enabled may not always be ideal,
1675 * especially if retention was previously stopped and the
1676 * user toggles retain_dead_tuples without adjusting the
1677 * publisher workload. However, this behavior provides a
1678 * convenient way for users to manually refresh the
1679 * retention status. Since retention will be stopped again
1680 * unless the publisher workload is reduced, this approach
1681 * is acceptable for now.
1682 */
1683 if (opts.retaindeadtuples != sub->retaindeadtuples)
1684 {
1686 BoolGetDatum(opts.retaindeadtuples);
1688
1689 retention_active = opts.retaindeadtuples;
1690 }
1691
1692 CheckAlterSubOption(sub, "retain_dead_tuples", false, isTopLevel);
1693
1694 /*
1695 * Workers may continue running even after the
1696 * subscription has been disabled.
1697 *
1698 * To prevent race conditions (as described in
1699 * CheckAlterSubOption()), ensure that all worker
1700 * processes have already exited before proceeding.
1701 */
1702 if (logicalrep_workers_find(subid, true, true))
1703 ereport(ERROR,
1705 errmsg("cannot alter retain_dead_tuples when logical replication worker is still running"),
1706 errhint("Try again after some time.")));
1707
1708 /*
1709 * Notify the launcher to manage the replication slot for
1710 * conflict detection. This ensures that replication slot
1711 * is efficiently handled (created, updated, or dropped)
1712 * in response to any configuration changes.
1713 */
1715
1716 check_pub_rdt = opts.retaindeadtuples;
1717 retain_dead_tuples = opts.retaindeadtuples;
1718 }
1719
1720 if (IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
1721 {
1723 Int32GetDatum(opts.maxretention);
1725
1726 max_retention = opts.maxretention;
1727 }
1728
1729 /*
1730 * Ensure that system configuration parameters are set
1731 * appropriately to support retain_dead_tuples and
1732 * max_retention_duration.
1733 */
1734 if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) ||
1735 IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
1739 (max_retention > 0));
1740
1741 if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1742 {
1744 CStringGetTextDatum(opts.origin);
1746
1747 /*
1748 * Check if changes from different origins may be received
1749 * from the publisher when the origin is changed to ANY
1750 * and retain_dead_tuples is enabled.
1751 */
1754
1755 origin = opts.origin;
1756 }
1757
1758 if (IsSet(opts.specified_opts, SUBOPT_WAL_RECEIVER_TIMEOUT))
1759 {
1761 CStringGetTextDatum(opts.wal_receiver_timeout);
1763 }
1764
1765 update_tuple = true;
1766 break;
1767 }
1768
1770 {
1771 parse_subscription_options(pstate, stmt->options,
1773 Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
1774
1775 if (!sub->slotname && opts.enabled)
1776 ereport(ERROR,
1778 errmsg("cannot enable subscription that does not have a slot name")));
1779
1780 /*
1781 * Check track_commit_timestamp only when enabling the
1782 * subscription in case it was disabled after creation. See
1783 * comments atop CheckSubDeadTupleRetention() for details.
1784 */
1785 CheckSubDeadTupleRetention(opts.enabled, !opts.enabled,
1787 sub->retentionactive, false);
1788
1790 BoolGetDatum(opts.enabled);
1792
1793 if (opts.enabled)
1795
1796 update_tuple = true;
1797
1798 /*
1799 * The subscription might be initially created with
1800 * connect=false and retain_dead_tuples=true, meaning the
1801 * remote server's status may not be checked. Ensure this
1802 * check is conducted now.
1803 */
1804 check_pub_rdt = sub->retaindeadtuples && opts.enabled;
1805 break;
1806 }
1807
1809 {
1813 char *conninfo;
1814
1815 /*
1816 * Remove what was there before, either another foreign server
1817 * or a connection string.
1818 */
1819 if (form->subserver)
1820 {
1823 ForeignServerRelationId, form->subserver);
1824 }
1825 else
1826 {
1827 nulls[Anum_pg_subscription_subconninfo - 1] = true;
1829 }
1830
1831 /*
1832 * Check that the subscription owner has USAGE privileges on
1833 * the server.
1834 */
1835 new_server = GetForeignServerByName(stmt->servername, false);
1837 new_server->serverid,
1838 form->subowner, ACL_USAGE);
1839 if (aclresult != ACLCHECK_OK)
1840 ereport(ERROR,
1842 errmsg("subscription owner \"%s\" does not have permission on foreign server \"%s\"",
1843 GetUserNameFromId(form->subowner, false),
1844 ForeignServerName(new_server->serverid)));
1845
1846 /* make sure a user mapping exists */
1847 GetUserMapping(form->subowner, new_server->serverid);
1848
1849 conninfo = ForeignServerConnectionString(form->subowner,
1850 new_server->serverid);
1851
1852 /* Load the library providing us libpq calls. */
1853 load_file("libpqwalreceiver", false);
1854 /* Check the connection info string. */
1855 walrcv_check_conninfo(conninfo,
1856 sub->passwordrequired && !sub->ownersuperuser);
1857
1860
1863
1864 update_tuple = true;
1865 }
1866 break;
1867
1869 /* remove reference to foreign server and dependencies, if present */
1870 if (form->subserver)
1871 {
1874 ForeignServerRelationId, form->subserver);
1875
1878 }
1879
1880 /* Load the library providing us libpq calls. */
1881 load_file("libpqwalreceiver", false);
1882 /* Check the connection info string. */
1883 walrcv_check_conninfo(stmt->conninfo,
1884 sub->passwordrequired && !sub->ownersuperuser);
1885
1887 CStringGetTextDatum(stmt->conninfo);
1889 update_tuple = true;
1890
1891 /*
1892 * Since the remote server configuration might have changed,
1893 * perform a check to ensure it permits enabling
1894 * retain_dead_tuples.
1895 */
1897 break;
1898
1900 {
1902 parse_subscription_options(pstate, stmt->options,
1904
1906 publicationListToArray(stmt->publication);
1908
1909 update_tuple = true;
1910
1911 /* Refresh if user asked us to. */
1912 if (opts.refresh)
1913 {
1914 if (!sub->enabled)
1915 ereport(ERROR,
1917 errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1918 errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1919
1920 /*
1921 * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
1922 * why this is not allowed.
1923 */
1924 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1925 ereport(ERROR,
1927 errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1928 errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1929
1930 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1931
1932 /* Make sure refresh sees the new list of publications. */
1933 sub->publications = stmt->publication;
1934
1935 AlterSubscription_refresh(sub, opts.copy_data,
1936 stmt->publication);
1937 }
1938
1939 break;
1940 }
1941
1944 {
1945 List *publist;
1947
1949 parse_subscription_options(pstate, stmt->options,
1951
1952 publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1956
1957 update_tuple = true;
1958
1959 /* Refresh if user asked us to. */
1960 if (opts.refresh)
1961 {
1962 /* We only need to validate user specified publications. */
1963 List *validate_publications = (isadd) ? stmt->publication : NULL;
1964
1965 if (!sub->enabled)
1966 ereport(ERROR,
1968 errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1969 /* translator: %s is an SQL ALTER command */
1970 errhint("Use %s instead.",
1971 isadd ?
1972 "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
1973 "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
1974
1975 /*
1976 * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
1977 * why this is not allowed.
1978 */
1979 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1980 ereport(ERROR,
1982 errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1983 /* translator: %s is an SQL ALTER command */
1984 errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
1985 isadd ?
1986 "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
1987 "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
1988
1989 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1990
1991 /* Refresh the new list of publications. */
1992 sub->publications = publist;
1993
1994 AlterSubscription_refresh(sub, opts.copy_data,
1996 }
1997
1998 break;
1999 }
2000
2002 {
2003 if (!sub->enabled)
2004 ereport(ERROR,
2006 errmsg("%s is not allowed for disabled subscriptions",
2007 "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
2008
2009 parse_subscription_options(pstate, stmt->options,
2011
2012 /*
2013 * The subscription option "two_phase" requires that
2014 * replication has passed the initial table synchronization
2015 * phase before the two_phase becomes properly enabled.
2016 *
2017 * But, having reached this two-phase commit "enabled" state
2018 * we must not allow any subsequent table initialization to
2019 * occur. So the ALTER SUBSCRIPTION ... REFRESH PUBLICATION is
2020 * disallowed when the user had requested two_phase = on mode.
2021 *
2022 * The exception to this restriction is when copy_data =
2023 * false, because when copy_data is false the tablesync will
2024 * start already in READY state and will exit directly without
2025 * doing anything.
2026 *
2027 * For more details see comments atop worker.c.
2028 */
2029 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2030 ereport(ERROR,
2032 errmsg("ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data is not allowed when two_phase is enabled"),
2033 errhint("Use ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
2034
2035 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH PUBLICATION");
2036
2037 AlterSubscription_refresh(sub, opts.copy_data, NULL);
2038
2039 break;
2040 }
2041
2043 {
2044 if (!sub->enabled)
2045 ereport(ERROR,
2047 errmsg("%s is not allowed for disabled subscriptions",
2048 "ALTER SUBSCRIPTION ... REFRESH SEQUENCES"));
2049
2051
2052 break;
2053 }
2054
2056 {
2057 parse_subscription_options(pstate, stmt->options, SUBOPT_LSN, &opts);
2058
2059 /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
2060 Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
2061
2062 /*
2063 * If the user sets subskiplsn, we do a sanity check to make
2064 * sure that the specified LSN is a probable value.
2065 */
2066 if (XLogRecPtrIsValid(opts.lsn))
2067 {
2069 char originname[NAMEDATALEN];
2070 XLogRecPtr remote_lsn;
2071
2073 originname, sizeof(originname));
2075 remote_lsn = replorigin_get_progress(originid, false);
2076
2077 /* Check the given LSN is at least a future LSN */
2078 if (XLogRecPtrIsValid(remote_lsn) && opts.lsn < remote_lsn)
2079 ereport(ERROR,
2081 errmsg("skip WAL location (LSN %X/%08X) must be greater than origin LSN %X/%08X",
2082 LSN_FORMAT_ARGS(opts.lsn),
2083 LSN_FORMAT_ARGS(remote_lsn))));
2084 }
2085
2088
2089 update_tuple = true;
2090 break;
2091 }
2092
2093 default:
2094 elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
2095 stmt->kind);
2096 }
2097
2098 /* Update the catalog if needed. */
2099 if (update_tuple)
2100 {
2102 replaces);
2103
2104 CatalogTupleUpdate(rel, &tup->t_self, tup);
2105
2107 }
2108
2109 /*
2110 * Try to acquire the connection necessary either for modifying the slot
2111 * or for checking if the remote server permits enabling
2112 * retain_dead_tuples.
2113 *
2114 * This has to be at the end because otherwise if there is an error while
2115 * doing the database operations we won't be able to rollback altered
2116 * slot.
2117 */
2119 {
2120 bool must_use_password;
2121 char *err;
2123
2124 /* Load the library providing us libpq calls. */
2125 load_file("libpqwalreceiver", false);
2126
2127 /*
2128 * Try to connect to the publisher, using the new connection string if
2129 * available.
2130 */
2132 wrconn = walrcv_connect(stmt->conninfo ? stmt->conninfo : sub->conninfo,
2134 &err);
2135 if (!wrconn)
2136 ereport(ERROR,
2138 errmsg("subscription \"%s\" could not connect to the publisher: %s",
2139 sub->name, err)));
2140
2141 PG_TRY();
2142 {
2145
2147 retain_dead_tuples, origin, NULL, 0,
2148 sub->name);
2149
2152 update_failover ? &opts.failover : NULL,
2153 update_two_phase ? &opts.twophase : NULL);
2154 }
2155 PG_FINALLY();
2156 {
2158 }
2159 PG_END_TRY();
2160 }
2161
2163
2165
2166 /* Wake up related replication workers to handle this change quickly. */
2168
2169 return myself;
2170}
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
@ ACLCHECK_NOT_OWNER
Definition acl.h:186
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3879
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4133
void LogicalRepWorkersWakeupAtCommit(Oid subid)
Definition worker.c:6317
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition worker.c:647
static Datum values[MAXATTR]
Definition bootstrap.c:188
#define CStringGetTextDatum(s)
Definition builtins.h:98
#define Assert(condition)
Definition c.h:945
uint32 bits32
Definition c.h:627
@ DEPENDENCY_NORMAL
Definition dependency.h:33
void load_file(const char *filename, bool restricted)
Definition dfmgr.c:149
int errcode(int sqlerrcode)
Definition elog.c:874
int errhint(const char *fmt,...) pg_attribute_printf(1
#define PG_TRY(...)
Definition elog.h:372
#define WARNING
Definition elog.h:36
#define PG_END_TRY(...)
Definition elog.h:397
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define NOTICE
Definition elog.h:35
#define PG_FINALLY(...)
Definition elog.h:389
#define ereport(elevel,...)
Definition elog.h:150
void err(int eval, const char *fmt,...)
Definition err.c:43
#define DirectFunctionCall1(func, arg1)
Definition fmgr.h:684
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition foreign.c:210
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition foreign.c:289
char * ForeignServerName(Oid serverid)
Definition foreign.c:185
char * ForeignServerConnectionString(Oid userid, Oid serverid)
Definition foreign.c:225
Oid MyDatabaseId
Definition globals.c:94
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1130
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1384
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
#define stmt
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
return true
Definition isn.c:130
List * logicalrep_workers_find(Oid subid, bool only_running, bool acquire_lock)
Definition launcher.c:294
void ApplyLauncherWakeupAtCommit(void)
Definition launcher.c:1185
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1088
#define AccessExclusiveLock
Definition lockdefs.h:43
#define RowExclusiveLock
Definition lockdefs.h:38
Oid GetUserId(void)
Definition miscinit.c:470
char * GetUserNameFromId(Oid roleid, bool noerr)
Definition miscinit.c:989
Datum namein(PG_FUNCTION_ARGS)
Definition name.c:48
static char * errmsg
#define InvokeObjectPostAlterHook(classId, objectId, subId)
#define ObjectAddressSet(addr, class_id, object_id)
ReplOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition origin.c:232
XLogRecPtr replorigin_get_progress(ReplOriginId node, bool flush)
Definition origin.c:1048
@ ALTER_SUBSCRIPTION_REFRESH_PUBLICATION
@ ALTER_SUBSCRIPTION_ENABLED
@ ALTER_SUBSCRIPTION_DROP_PUBLICATION
@ ALTER_SUBSCRIPTION_SERVER
@ ALTER_SUBSCRIPTION_SET_PUBLICATION
@ ALTER_SUBSCRIPTION_REFRESH_SEQUENCES
@ ALTER_SUBSCRIPTION_SKIP
@ ALTER_SUBSCRIPTION_OPTIONS
@ ALTER_SUBSCRIPTION_CONNECTION
@ ALTER_SUBSCRIPTION_ADD_PUBLICATION
#define ACL_USAGE
Definition parsenodes.h:84
@ OBJECT_SUBSCRIPTION
static AmcheckOptions opts
Definition pg_amcheck.c:112
#define NAMEDATALEN
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition pg_depend.c:47
long deleteDependencyRecordsForSpecific(Oid classId, Oid objectId, char deptype, Oid refclassId, Oid refobjectId)
Definition pg_depend.c:400
static Datum LSNGetDatum(XLogRecPtr X)
Definition pg_lsn.h:31
Subscription * GetSubscription(Oid subid, bool missing_ok, bool aclcheck)
END_CATALOG_STRUCT typedef FormData_pg_subscription * Form_pg_subscription
int pg_strcasecmp(const char *s1, const char *s2)
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
static Datum CStringGetDatum(const char *X)
Definition postgres.h:370
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
static Datum CharGetDatum(char X)
Definition postgres.h:132
#define InvalidOid
unsigned int Oid
static int fb(int x)
#define RelationGetDescr(relation)
Definition rel.h:540
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_RETAIN_DEAD_TUPLES
#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
void CheckSubDeadTupleRetention(bool check_guc, bool sub_disabled, int elevel_for_sub_disabled, bool retain_dead_tuples, bool retention_active, bool max_retention_set)
static void AlterSubscription_refresh_seq(Subscription *sub)
#define SUBOPT_LSN
#define SUBOPT_MAX_RETENTION_DURATION
static List * merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
#define SUBOPT_WAL_RECEIVER_TIMEOUT
static void check_publications_origin_tables(WalReceiverConn *wrconn, List *publications, bool copydata, bool retain_dead_tuples, char *origin, Oid *subrel_local_oids, int subrel_count, char *subname)
#define SUBOPT_BINARY
#define IsSet(val, bits)
#define SUBOPT_REFRESH
static void check_pub_dead_tuple_retention(WalReceiverConn *wrconn)
bool superuser(void)
Definition superuser.c:47
#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:2800
const char * name
static WalReceiverConn * wrconn
Definition walreceiver.c:95
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
#define walrcv_check_conninfo(conninfo, must_use_password)
#define walrcv_alter_slot(conn, slotname, failover, two_phase)
#define walrcv_disconnect(conn)
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition xact.c:3670
#define XLogRecPtrIsValid(r)
Definition xlogdefs.h:29
#define LSN_FORMAT_ARGS(lsn)
Definition xlogdefs.h:47
uint16 ReplOriginId
Definition xlogdefs.h:69
uint64 XLogRecPtr
Definition xlogdefs.h:21

References AccessExclusiveLock, ACL_USAGE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, ALTER_SUBSCRIPTION_ADD_PUBLICATION, ALTER_SUBSCRIPTION_CONNECTION, ALTER_SUBSCRIPTION_DROP_PUBLICATION, ALTER_SUBSCRIPTION_ENABLED, ALTER_SUBSCRIPTION_OPTIONS, ALTER_SUBSCRIPTION_REFRESH_PUBLICATION, ALTER_SUBSCRIPTION_REFRESH_SEQUENCES, ALTER_SUBSCRIPTION_SERVER, ALTER_SUBSCRIPTION_SET_PUBLICATION, ALTER_SUBSCRIPTION_SKIP, AlterSubscription_refresh(), AlterSubscription_refresh_seq(), ApplyLauncherWakeupAtCommit(), Assert, BoolGetDatum(), CatalogTupleUpdate(), CharGetDatum(), check_pub_dead_tuple_retention(), check_publications_origin_tables(), CheckAlterSubOption(), CheckSubDeadTupleRetention(), Subscription::conninfo, CStringGetDatum(), CStringGetTextDatum, deleteDependencyRecordsForSpecific(), DEPENDENCY_NORMAL, DirectFunctionCall1, elog, Subscription::enabled, ereport, err(), errcode(), errhint(), errmsg, ERROR, fb(), ForeignServerConnectionString(), ForeignServerName(), Form_pg_subscription, GetForeignServerByName(), GETSTRUCT(), GetSubscription(), GetUserId(), GetUserMapping(), GetUserNameFromId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, Int32GetDatum(), InvalidOid, InvokeObjectPostAlterHook, IsSet, load_file(), LockSharedObject(), logicalrep_workers_find(), LogicalRepWorkersWakeupAtCommit(), LookupGXactBySubid(), LSN_FORMAT_ARGS, LSNGetDatum(), Subscription::maxretention, merge_publications(), MyDatabaseId, Subscription::name, NAMEDATALEN, namein(), NOTICE, object_aclcheck(), object_ownercheck(), OBJECT_SUBSCRIPTION, ObjectAddressSet, ObjectIdGetDatum(), opts, Subscription::origin, Subscription::ownersuperuser, parse_subscription_options(), Subscription::passwordrequired, PG_END_TRY, PG_FINALLY, pg_strcasecmp(), PG_TRY, PreventInTransactionBlock(), publicationListToArray(), Subscription::publications, recordDependencyOn(), RelationGetDescr, ReplicationOriginNameForLogicalRep(), replorigin_by_name(), replorigin_get_progress(), Subscription::retaindeadtuples, Subscription::retentionactive, RowExclusiveLock, SearchSysCacheCopy2, Subscription::slotname, stmt, SUBOPT_BINARY, SUBOPT_COPY_DATA, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_FAILOVER, SUBOPT_LSN, SUBOPT_MAX_RETENTION_DURATION, SUBOPT_ORIGIN, SUBOPT_PASSWORD_REQUIRED, SUBOPT_REFRESH, SUBOPT_RETAIN_DEAD_TUPLES, SUBOPT_RUN_AS_OWNER, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, SUBOPT_WAL_RECEIVER_TIMEOUT, superuser(), table_close(), table_open(), Subscription::twophasestate, values, walrcv_alter_slot, walrcv_check_conninfo, walrcv_connect, walrcv_disconnect, WARNING, wrconn, and XLogRecPtrIsValid.

Referenced by ProcessUtilitySlow().

◆ AlterSubscriptionOwner()

ObjectAddress AlterSubscriptionOwner ( const char name,
Oid  newOwnerId 
)
extern

Definition at line 2630 of file subscriptioncmds.c.

2631{
2632 Oid subid;
2633 HeapTuple tup;
2634 Relation rel;
2635 ObjectAddress address;
2637
2639
2642
2643 if (!HeapTupleIsValid(tup))
2644 ereport(ERROR,
2646 errmsg("subscription \"%s\" does not exist", name)));
2647
2649 subid = form->oid;
2650
2652
2654
2656
2658
2659 return address;
2660}
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)

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

Referenced by ExecAlterOwnerStmt().

◆ AlterSubscriptionOwner_oid()

void AlterSubscriptionOwner_oid ( Oid  subid,
Oid  newOwnerId 
)
extern

Definition at line 2666 of file subscriptioncmds.c.

2667{
2668 HeapTuple tup;
2669 Relation rel;
2670
2672
2674
2675 if (!HeapTupleIsValid(tup))
2676 ereport(ERROR,
2678 errmsg("subscription with OID %u does not exist", subid)));
2679
2681
2683
2685}
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91

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

Referenced by shdepReassignOwned_Owner().

◆ CheckSubDeadTupleRetention()

void CheckSubDeadTupleRetention ( bool  check_guc,
bool  sub_disabled,
int  elevel_for_sub_disabled,
bool  retain_dead_tuples,
bool  retention_active,
bool  max_retention_set 
)
extern

Definition at line 3027 of file subscriptioncmds.c.

3031{
3034
3036 {
3038 ereport(ERROR,
3040 errmsg("\"wal_level\" is insufficient to create the replication slot required by retain_dead_tuples"),
3041 errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start."));
3042
3046 errmsg("commit timestamp and origin data required for detecting conflicts won't be retained"),
3047 errhint("Consider setting \"%s\" to true.",
3048 "track_commit_timestamp"));
3049
3053 errmsg("deleted rows to detect conflicts would not be removed until the subscription is enabled"),
3055 ? errhint("Consider setting %s to false.",
3056 "retain_dead_tuples") : 0);
3057 }
3058 else if (max_retention_set)
3059 {
3062 errmsg("max_retention_duration is ineffective when retain_dead_tuples is disabled"));
3063 }
3064}
bool track_commit_timestamp
Definition commit_ts.c:109
int wal_level
Definition xlog.c:135
@ WAL_LEVEL_REPLICA
Definition xlog.h:76

References Assert, ereport, errcode(), errhint(), errmsg, ERROR, fb(), NOTICE, track_commit_timestamp, wal_level, WAL_LEVEL_REPLICA, and WARNING.

Referenced by AlterSubscription(), CreateSubscription(), and DisableSubscriptionAndExit().

◆ CreateSubscription()

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

Definition at line 615 of file subscriptioncmds.c.

617{
618 Relation rel;
620 Oid subid;
621 bool nulls[Natts_pg_subscription];
623 Oid owner = GetUserId();
625 Oid serverid;
626 char *conninfo;
628 List *publications;
630 SubOpts opts = {0};
632
633 /*
634 * Parse and check options.
635 *
636 * Connection and publication should not be specified here.
637 */
648
649 /*
650 * Since creating a replication slot is not transactional, rolling back
651 * the transaction leaves the created replication slot. So we cannot run
652 * CREATE SUBSCRIPTION inside a transaction block if creating a
653 * replication slot.
654 */
655 if (opts.create_slot)
656 PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
657
658 /*
659 * We don't want to allow unprivileged users to be able to trigger
660 * attempts to access arbitrary network destinations, so require the user
661 * to have been specifically authorized to create subscriptions.
662 */
666 errmsg("permission denied to create subscription"),
667 errdetail("Only roles with privileges of the \"%s\" role may create subscriptions.",
668 "pg_create_subscription")));
669
670 /*
671 * Since a subscription is a database object, we also check for CREATE
672 * permission on the database.
673 */
675 owner, ACL_CREATE);
676 if (aclresult != ACLCHECK_OK)
679
680 /*
681 * Non-superusers are required to set a password for authentication, and
682 * that password must be used by the target server, but the superuser can
683 * exempt a subscription from this requirement.
684 */
685 if (!opts.passwordrequired && !superuser_arg(owner))
688 errmsg("password_required=false is superuser-only"),
689 errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
690
691 /*
692 * If built with appropriate switch, whine when regression-testing
693 * conventions for subscription names are violated.
694 */
695#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
696 if (strncmp(stmt->subname, "regress_", 8) != 0)
697 elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
698#endif
699
701
702 /* Check if name is used */
705 if (OidIsValid(subid))
706 {
709 errmsg("subscription \"%s\" already exists",
710 stmt->subname)));
711 }
712
713 /*
714 * Ensure that system configuration parameters are set appropriately to
715 * support retain_dead_tuples and max_retention_duration.
716 */
718 opts.retaindeadtuples, opts.retaindeadtuples,
719 (opts.maxretention > 0));
720
721 if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
722 opts.slot_name == NULL)
723 opts.slot_name = stmt->subname;
724
725 /* The default for synchronous_commit of subscriptions is off. */
726 if (opts.synchronous_commit == NULL)
727 opts.synchronous_commit = "off";
728
729 /*
730 * The default for wal_receiver_timeout of subscriptions is -1, which
731 * means the value is inherited from the server configuration, command
732 * line, or role/database settings.
733 */
734 if (opts.wal_receiver_timeout == NULL)
735 opts.wal_receiver_timeout = "-1";
736
737 /* Load the library providing us libpq calls. */
738 load_file("libpqwalreceiver", false);
739
740 if (stmt->servername)
741 {
742 ForeignServer *server;
743
744 Assert(!stmt->conninfo);
745 conninfo = NULL;
746
747 server = GetForeignServerByName(stmt->servername, false);
749 if (aclresult != ACLCHECK_OK)
751
752 /* make sure a user mapping exists */
753 GetUserMapping(owner, server->serverid);
754
755 serverid = server->serverid;
756 conninfo = ForeignServerConnectionString(owner, serverid);
757 }
758 else
759 {
760 Assert(stmt->conninfo);
761
762 serverid = InvalidOid;
763 conninfo = stmt->conninfo;
764 }
765
766 /* Check the connection info string. */
767 walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
768
769 publications = stmt->publication;
770
771 /* Everything ok, form a new tuple. */
772 memset(values, 0, sizeof(values));
773 memset(nulls, false, sizeof(nulls));
774
787 CharGetDatum(opts.twophase ?
795 BoolGetDatum(opts.retaindeadtuples);
797 Int32GetDatum(opts.maxretention);
799 Int32GetDatum(opts.retaindeadtuples);
801 if (!OidIsValid(serverid))
803 CStringGetTextDatum(conninfo);
804 else
805 nulls[Anum_pg_subscription_subconninfo - 1] = true;
806 if (opts.slot_name)
809 else
810 nulls[Anum_pg_subscription_subslotname - 1] = true;
812 CStringGetTextDatum(opts.synchronous_commit);
814 CStringGetTextDatum(opts.wal_receiver_timeout);
816 publicationListToArray(publications);
819
821
822 /* Insert tuple into catalog. */
825
827
829
830 if (stmt->servername)
831 {
833
834 Assert(OidIsValid(serverid));
835
838 }
839
840 /*
841 * A replication origin is currently created for all subscriptions,
842 * including those that only contain sequences or are otherwise empty.
843 *
844 * XXX: While this is technically unnecessary, optimizing it would require
845 * additional logic to skip origin creation during DDL operations and
846 * apply workers initialization, and to handle origin creation dynamically
847 * when tables are added to the subscription. It is not clear whether
848 * preventing creation of origins is worth additional complexity.
849 */
852
853 /*
854 * Connect to remote side to execute requested commands and fetch table
855 * and sequence info.
856 */
857 if (opts.connect)
858 {
859 char *err;
862
863 /* Try to connect to the publisher. */
864 must_use_password = !superuser_arg(owner) && opts.passwordrequired;
865 wrconn = walrcv_connect(conninfo, true, true, must_use_password,
866 stmt->subname, &err);
867 if (!wrconn)
870 errmsg("subscription \"%s\" could not connect to the publisher: %s",
871 stmt->subname, err)));
872
873 PG_TRY();
874 {
875 bool has_tables = false;
876 List *pubrels;
877 char relation_state;
878
879 check_publications(wrconn, publications);
881 opts.copy_data,
882 opts.retaindeadtuples, opts.origin,
883 NULL, 0, stmt->subname);
885 opts.copy_data, opts.origin,
886 NULL, 0, stmt->subname);
887
888 if (opts.retaindeadtuples)
890
891 /*
892 * Set sync state based on if we were asked to do data copy or
893 * not.
894 */
896
897 /*
898 * Build local relation status info. Relations are for both tables
899 * and sequences from the publisher.
900 */
901 pubrels = fetch_relation_list(wrconn, publications);
902
904 {
905 Oid relid;
906 char relkind;
907 RangeVar *rv = pubrelinfo->rv;
908
909 relid = RangeVarGetRelid(rv, AccessShareLock, false);
910 relkind = get_rel_relkind(relid);
911
912 /* Check for supported relkind. */
913 CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
914 rv->schemaname, rv->relname);
915 has_tables |= (relkind != RELKIND_SEQUENCE);
917 InvalidXLogRecPtr, true);
918 }
919
920 /*
921 * If requested, create permanent slot for the subscription. We
922 * won't use the initial snapshot for anything, so no need to
923 * export it.
924 *
925 * XXX: Similar to origins, it is not clear whether preventing the
926 * slot creation for empty and sequence-only subscriptions is
927 * worth additional complexity.
928 */
929 if (opts.create_slot)
930 {
931 bool twophase_enabled = false;
932
933 Assert(opts.slot_name);
934
935 /*
936 * Even if two_phase is set, don't create the slot with
937 * two-phase enabled. Will enable it once all the tables are
938 * synced and ready. This avoids race-conditions like prepared
939 * transactions being skipped due to changes not being applied
940 * due to checks in should_apply_changes_for_rel() when
941 * tablesync for the corresponding tables are in progress. See
942 * comments atop worker.c.
943 *
944 * Note that if tables were specified but copy_data is false
945 * then it is safe to enable two_phase up-front because those
946 * tables are already initially in READY state. When the
947 * subscription has no tables, we leave the twophase state as
948 * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
949 * PUBLICATION to work.
950 */
951 if (opts.twophase && !opts.copy_data && has_tables)
952 twophase_enabled = true;
953
955 opts.failover, CRS_NOEXPORT_SNAPSHOT, NULL);
956
959
961 (errmsg("created replication slot \"%s\" on publisher",
962 opts.slot_name)));
963 }
964 }
965 PG_FINALLY();
966 {
968 }
969 PG_END_TRY();
970 }
971 else
973 (errmsg("subscription was created, but is not connected"),
974 errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and alter the subscription to refresh publications.")));
975
977
979
980 /*
981 * Notify the launcher to start the apply worker if the subscription is
982 * enabled, or to create the conflict detection slot if retain_dead_tuples
983 * is enabled.
984 *
985 * Creating the conflict detection slot is essential even when the
986 * subscription is not enabled. This ensures that dead tuples are
987 * retained, which is necessary for accurately identifying the type of
988 * conflict during replication.
989 */
990 if (opts.enabled || opts.retaindeadtuples)
992
994
995 return myself;
996}
bool has_privs_of_role(Oid member, Oid role)
Definition acl.c:5314
#define OidIsValid(objectId)
Definition c.h:860
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition catalog.c:448
int errdetail(const char *fmt,...) pg_attribute_printf(1
void CheckSubscriptionRelkind(char localrelkind, char remoterelkind, const char *nspname, const char *relname)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1037
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
#define AccessShareLock
Definition lockdefs.h:36
char * get_database_name(Oid dbid)
Definition lsyscache.c:1312
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2223
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition namespace.h:98
#define InvokeObjectPostCreateHook(classId, objectId, subId)
ReplOriginId replorigin_create(const char *roname)
Definition origin.c:263
@ OBJECT_DATABASE
@ OBJECT_FOREIGN_SERVER
#define ACL_CREATE
Definition parsenodes.h:85
#define foreach_ptr(type, var, lst)
Definition pg_list.h:469
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
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 * servername
Definition foreign.h:40
char * relname
Definition primnodes.h:84
char * schemaname
Definition primnodes.h:81
#define SUBOPT_CREATE_SLOT
static void check_publications_origin_sequences(WalReceiverConn *wrconn, List *publications, bool copydata, char *origin, Oid *subrel_local_oids, int subrel_count, char *subname)
static void check_publications(WalReceiverConn *wrconn, List *publications)
static List * fetch_relation_list(WalReceiverConn *wrconn, List *publications)
#define SUBOPT_CONNECT
bool superuser_arg(Oid roleid)
Definition superuser.c:57
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition syscache.h:111
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition tablesync.c:1648
#define walrcv_create_slot(conn, slotname, temporary, two_phase, failover, snapshot_action, lsn)
@ CRS_NOEXPORT_SNAPSHOT
Definition walsender.h:23
#define InvalidXLogRecPtr
Definition xlogdefs.h:28

References AccessShareLock, ACL_CREATE, ACL_USAGE, aclcheck_error(), ACLCHECK_OK, AddSubscriptionRelState(), ApplyLauncherWakeupAtCommit(), Assert, BoolGetDatum(), CatalogTupleInsert(), CharGetDatum(), check_pub_dead_tuple_retention(), check_publications(), check_publications_origin_sequences(), check_publications_origin_tables(), CheckSubDeadTupleRetention(), CheckSubscriptionRelkind(), CRS_NOEXPORT_SNAPSHOT, CStringGetDatum(), CStringGetTextDatum, DEPENDENCY_NORMAL, DirectFunctionCall1, elog, ereport, err(), errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errhint(), errmsg, ERROR, fb(), fetch_relation_list(), foreach_ptr, ForeignServerConnectionString(), get_database_name(), get_rel_relkind(), GetForeignServerByName(), GetNewOidWithIndex(), GetSysCacheOid2, GetUserId(), GetUserMapping(), has_privs_of_role(), heap_form_tuple(), heap_freetuple(), Int32GetDatum(), InvalidOid, InvalidXLogRecPtr, InvokeObjectPostCreateHook, IsSet, load_file(), LSNGetDatum(), MyDatabaseId, NAMEDATALEN, namein(), NOTICE, object_aclcheck(), OBJECT_DATABASE, OBJECT_FOREIGN_SERVER, ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, opts, parse_subscription_options(), PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_create_subscription(), PreventInTransactionBlock(), publicationListToArray(), RangeVarGetRelid, recordDependencyOn(), recordDependencyOnOwner(), RelationGetDescr, RangeVar::relname, ReplicationOriginNameForLogicalRep(), replorigin_create(), RowExclusiveLock, RangeVar::schemaname, ForeignServer::serverid, ForeignServer::servername, stmt, SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_FAILOVER, SUBOPT_MAX_RETENTION_DURATION, SUBOPT_ORIGIN, SUBOPT_PASSWORD_REQUIRED, SUBOPT_RETAIN_DEAD_TUPLES, SUBOPT_RUN_AS_OWNER, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, SUBOPT_WAL_RECEIVER_TIMEOUT, 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)
extern

Definition at line 3358 of file subscriptioncmds.c.

3359{
3360 /*
3361 * If no parameter value given, assume "true" is meant.
3362 */
3363 if (!def->arg)
3364 return LOGICALREP_STREAM_ON;
3365
3366 /*
3367 * Allow 0, 1, "false", "true", "off", "on" or "parallel".
3368 */
3369 switch (nodeTag(def->arg))
3370 {
3371 case T_Integer:
3372 switch (intVal(def->arg))
3373 {
3374 case 0:
3375 return LOGICALREP_STREAM_OFF;
3376 case 1:
3377 return LOGICALREP_STREAM_ON;
3378 default:
3379 /* otherwise, error out below */
3380 break;
3381 }
3382 break;
3383 default:
3384 {
3385 char *sval = defGetString(def);
3386
3387 /*
3388 * The set of strings accepted here should match up with the
3389 * grammar's opt_boolean_or_string production.
3390 */
3391 if (pg_strcasecmp(sval, "false") == 0 ||
3392 pg_strcasecmp(sval, "off") == 0)
3393 return LOGICALREP_STREAM_OFF;
3394 if (pg_strcasecmp(sval, "true") == 0 ||
3395 pg_strcasecmp(sval, "on") == 0)
3396 return LOGICALREP_STREAM_ON;
3397 if (pg_strcasecmp(sval, "parallel") == 0)
3399 }
3400 break;
3401 }
3402
3403 ereport(ERROR,
3405 errmsg("%s requires a Boolean value or \"parallel\"",
3406 def->defname)));
3407 return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
3408}
char * defGetString(DefElem *def)
Definition define.c:34
#define nodeTag(nodeptr)
Definition nodes.h:139
char * defname
Definition parsenodes.h:857
Node * arg
Definition parsenodes.h:858
#define intVal(v)
Definition value.h:79

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

Referenced by parse_output_parameters(), and parse_subscription_options().

◆ DropSubscription()

void DropSubscription ( DropSubscriptionStmt stmt,
bool  isTopLevel 
)
extern

Definition at line 2176 of file subscriptioncmds.c.

2177{
2178 Relation rel;
2180 HeapTuple tup;
2181 Oid subid;
2182 Oid subowner;
2183 Datum datum;
2184 bool isnull;
2185 char *subname;
2186 char *conninfo;
2187 char *slotname;
2189 ListCell *lc;
2190 char originname[NAMEDATALEN];
2191 char *err = NULL;
2194 List *rstates;
2195 bool must_use_password;
2196
2197 /*
2198 * The launcher may concurrently start a new worker for this subscription.
2199 * During initialization, the worker checks for subscription validity and
2200 * exits if the subscription has already been dropped. See
2201 * InitializeLogRepWorker.
2202 */
2204
2206 CStringGetDatum(stmt->subname));
2207
2208 if (!HeapTupleIsValid(tup))
2209 {
2210 table_close(rel, NoLock);
2211
2212 if (!stmt->missing_ok)
2213 ereport(ERROR,
2215 errmsg("subscription \"%s\" does not exist",
2216 stmt->subname)));
2217 else
2219 (errmsg("subscription \"%s\" does not exist, skipping",
2220 stmt->subname)));
2221
2222 return;
2223 }
2224
2226 subid = form->oid;
2227 subowner = form->subowner;
2228 must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
2229
2230 /* must be owner */
2233 stmt->subname);
2234
2235 /* DROP hook for the subscription being removed */
2237
2238 /*
2239 * Lock the subscription so nobody else can do anything with it (including
2240 * the replication workers).
2241 */
2243
2244 /* Get subname */
2247 subname = pstrdup(NameStr(*DatumGetName(datum)));
2248
2249 /* Get conninfo */
2250 if (OidIsValid(form->subserver))
2251 {
2253
2255 form->subowner, ACL_USAGE);
2256 if (aclresult != ACLCHECK_OK)
2257 {
2258 /*
2259 * Unable to generate connection string because permissions on the
2260 * foreign server have been removed. Follow the same logic as an
2261 * unusable subconninfo (which will result in an ERROR later
2262 * unless slot_name = NONE).
2263 */
2264 err = psprintf(_("subscription owner \"%s\" does not have permission on foreign server \"%s\""),
2265 GetUserNameFromId(form->subowner, false),
2266 ForeignServerName(form->subserver));
2267 conninfo = NULL;
2268 }
2269 else
2270 conninfo = ForeignServerConnectionString(form->subowner,
2271 form->subserver);
2272 }
2273 else
2274 {
2277 conninfo = TextDatumGetCString(datum);
2278 }
2279
2280 /* Get slotname */
2283 if (!isnull)
2284 slotname = pstrdup(NameStr(*DatumGetName(datum)));
2285 else
2286 slotname = NULL;
2287
2288 /*
2289 * Since dropping a replication slot is not transactional, the replication
2290 * slot stays dropped even if the transaction rolls back. So we cannot
2291 * run DROP SUBSCRIPTION inside a transaction block if dropping the
2292 * replication slot. Also, in this case, we report a message for dropping
2293 * the subscription to the cumulative stats system.
2294 *
2295 * XXX The command name should really be something like "DROP SUBSCRIPTION
2296 * of a subscription that is associated with a replication slot", but we
2297 * don't have the proper facilities for that.
2298 */
2299 if (slotname)
2300 PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
2301
2304
2305 /* Remove the tuple from catalog. */
2306 CatalogTupleDelete(rel, &tup->t_self);
2307
2309
2310 /*
2311 * Stop all the subscription workers immediately.
2312 *
2313 * This is necessary if we are dropping the replication slot, so that the
2314 * slot becomes accessible.
2315 *
2316 * It is also necessary if the subscription is disabled and was disabled
2317 * in the same transaction. Then the workers haven't seen the disabling
2318 * yet and will still be running, leading to hangs later when we want to
2319 * drop the replication origin. If the subscription was disabled before
2320 * this transaction, then there shouldn't be any workers left, so this
2321 * won't make a difference.
2322 *
2323 * New workers won't be started because we hold an exclusive lock on the
2324 * subscription till the end of the transaction.
2325 */
2326 subworkers = logicalrep_workers_find(subid, false, true);
2327 foreach(lc, subworkers)
2328 {
2330
2332 }
2334
2335 /*
2336 * Remove the no-longer-useful entry in the launcher's table of apply
2337 * worker start times.
2338 *
2339 * If this transaction rolls back, the launcher might restart a failed
2340 * apply worker before wal_retrieve_retry_interval milliseconds have
2341 * elapsed, but that's pretty harmless.
2342 */
2344
2345 /*
2346 * Cleanup of tablesync replication origins.
2347 *
2348 * Any READY-state relations would already have dealt with clean-ups.
2349 *
2350 * Note that the state can't change because we have already stopped both
2351 * the apply and tablesync workers and they can't restart because of
2352 * exclusive lock on the subscription.
2353 */
2354 rstates = GetSubscriptionRelations(subid, true, false, true);
2355 foreach(lc, rstates)
2356 {
2358 Oid relid = rstate->relid;
2359
2360 /* Only cleanup resources of tablesync workers */
2361 if (!OidIsValid(relid))
2362 continue;
2363
2364 /*
2365 * Drop the tablesync's origin tracking if exists.
2366 *
2367 * It is possible that the origin is not yet created for tablesync
2368 * worker so passing missing_ok = true. This can happen for the states
2369 * before SUBREL_STATE_DATASYNC.
2370 */
2372 sizeof(originname));
2373 replorigin_drop_by_name(originname, true, false);
2374 }
2375
2376 /* Clean up dependencies */
2379
2380 /* Remove any associated relation synchronization states. */
2382
2383 /* Remove the origin tracking if exists. */
2385 replorigin_drop_by_name(originname, true, false);
2386
2387 /*
2388 * Tell the cumulative stats system that the subscription is getting
2389 * dropped.
2390 */
2392
2393 /*
2394 * If there is no slot associated with the subscription, we can finish
2395 * here.
2396 */
2397 if (!slotname && rstates == NIL)
2398 {
2399 table_close(rel, NoLock);
2400 return;
2401 }
2402
2403 /*
2404 * Try to acquire the connection necessary for dropping slots.
2405 *
2406 * Note: If the slotname is NONE/NULL then we allow the command to finish
2407 * and users need to manually cleanup the apply and tablesync worker slots
2408 * later.
2409 *
2410 * This has to be at the end because otherwise if there is an error while
2411 * doing the database operations we won't be able to rollback dropped
2412 * slot.
2413 */
2414 load_file("libpqwalreceiver", false);
2415
2416 if (conninfo)
2417 wrconn = walrcv_connect(conninfo, true, true, must_use_password,
2418 subname, &err);
2419
2420 if (wrconn == NULL)
2421 {
2422 if (!slotname)
2423 {
2424 /* be tidy */
2426 table_close(rel, NoLock);
2427 return;
2428 }
2429 else
2430 {
2431 ReportSlotConnectionError(rstates, subid, slotname, err);
2432 }
2433 }
2434
2435 PG_TRY();
2436 {
2437 foreach(lc, rstates)
2438 {
2440 Oid relid = rstate->relid;
2441
2442 /* Only cleanup resources of tablesync workers */
2443 if (!OidIsValid(relid))
2444 continue;
2445
2446 /*
2447 * Drop the tablesync slots associated with removed tables.
2448 *
2449 * For SYNCDONE/READY states, the tablesync slot is known to have
2450 * already been dropped by the tablesync worker.
2451 *
2452 * For other states, there is no certainty, maybe the slot does
2453 * not exist yet. Also, if we fail after removing some of the
2454 * slots, next time, it will again try to drop already dropped
2455 * slots and fail. For these reasons, we allow missing_ok = true
2456 * for the drop.
2457 */
2458 if (rstate->state != SUBREL_STATE_SYNCDONE)
2459 {
2460 char syncslotname[NAMEDATALEN] = {0};
2461
2463 sizeof(syncslotname));
2465 }
2466 }
2467
2469
2470 /*
2471 * If there is a slot associated with the subscription, then drop the
2472 * replication slot at the publisher.
2473 */
2474 if (slotname)
2475 ReplicationSlotDropAtPubNode(wrconn, slotname, false);
2476 }
2477 PG_FINALLY();
2478 {
2480 }
2481 PG_END_TRY();
2482
2483 table_close(rel, NoLock);
2484}
#define TextDatumGetCString(d)
Definition builtins.h:99
#define NameStr(name)
Definition c.h:837
#define _(x)
Definition elog.c:95
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
void CatalogTupleDelete(Relation heapRel, const ItemPointerData *tid)
Definition indexing.c:365
void logicalrep_worker_stop(LogicalRepWorkerType wtype, Oid subid, Oid relid)
Definition launcher.c:653
void ApplyLauncherForgetWorkerStartTime(Oid subid)
Definition launcher.c:1155
void list_free(List *list)
Definition list.c:1546
#define NoLock
Definition lockdefs.h:34
char * pstrdup(const char *in)
Definition mcxt.c:1781
#define InvokeObjectDropHook(classId, objectId, subId)
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition origin.c:448
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition pg_depend.c:303
#define lfirst(lc)
Definition pg_list.h:172
#define NIL
Definition pg_list.h:68
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
void RemoveSubscriptionRel(Oid subid, Oid relid)
List * GetSubscriptionRelations(Oid subid, bool tables, bool sequences, bool not_ready)
NameData subname
void pgstat_drop_subscription(Oid subid)
static Name DatumGetName(Datum X)
Definition postgres.h:380
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
LogicalRepWorkerType type
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:264
HeapTuple SearchSysCache2(SysCacheIdentifier cacheId, Datum key1, Datum key2)
Definition syscache.c:230
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:625
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, Size szslot)
Definition tablesync.c:1203

References _, AccessExclusiveLock, ACL_USAGE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, ApplyLauncherForgetWorkerStartTime(), CatalogTupleDelete(), CStringGetDatum(), DatumGetName(), deleteDependencyRecordsFor(), deleteSharedDependencyRecordsFor(), ereport, err(), errcode(), errmsg, ERROR, EventTriggerSQLDropAddObject(), fb(), ForeignServerConnectionString(), ForeignServerName(), Form_pg_subscription, GETSTRUCT(), GetSubscriptionRelations(), GetUserId(), GetUserNameFromId(), HeapTupleIsValid, InvalidOid, InvokeObjectDropHook, lfirst, list_free(), load_file(), LockSharedObject(), logicalrep_worker_stop(), logicalrep_workers_find(), MyDatabaseId, NAMEDATALEN, NameStr, NIL, NoLock, NOTICE, object_aclcheck(), object_ownercheck(), OBJECT_SUBSCRIPTION, ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_drop_subscription(), PreventInTransactionBlock(), psprintf(), pstrdup(), ReleaseSysCache(), SubscriptionRelState::relid, LogicalRepWorker::relid, RemoveSubscriptionRel(), ReplicationOriginNameForLogicalRep(), ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), replorigin_drop_by_name(), ReportSlotConnectionError(), RowExclusiveLock, SearchSysCache2(), SubscriptionRelState::state, stmt, LogicalRepWorker::subid, subname, superuser_arg(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), table_close(), table_open(), TextDatumGetCString, LogicalRepWorker::type, walrcv_connect, walrcv_disconnect, and wrconn.

Referenced by ProcessUtilitySlow().