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

1570{
1571 Relation rel;
1573 bool nulls[Natts_pg_subscription];
1576 HeapTuple tup;
1577 Oid subid;
1578 bool orig_conninfo_needed = true;
1579 bool update_tuple = false;
1580 bool update_failover = false;
1581 bool update_two_phase = false;
1582 bool check_pub_rdt = false;
1583 bool retain_dead_tuples;
1584 int max_retention;
1585 bool retention_active;
1586 char *new_conninfo = NULL;
1587 char *origin;
1588 Subscription *sub;
1591 SubOpts opts = {0};
1592
1594
1595 /* Fetch the existing tuple. */
1597 CStringGetDatum(stmt->subname));
1598
1599 if (!HeapTupleIsValid(tup))
1600 ereport(ERROR,
1602 errmsg("subscription \"%s\" does not exist",
1603 stmt->subname)));
1604
1606 subid = form->oid;
1607
1608 /* must be owner */
1611 stmt->subname);
1612
1613 /* parse and check options */
1614 switch (stmt->kind)
1615 {
1628 break;
1629
1632 break;
1633
1636 break;
1637
1641 break;
1642
1645 break;
1646
1649 break;
1650
1651 default:
1652 supported_opts = 0;
1653 break;
1654 }
1655
1656 if (supported_opts > 0)
1658
1659 /*
1660 * Ensure that ALTER SUBSCRIPTION commands that could be used to fix a
1661 * broken connection or prepare to drop a broken subscription don't
1662 * attempt to construct the conninfo. Otherwise, we might encounter the
1663 * error the user is trying to fix.
1664 *
1665 * Specifically, ALTER SUBSCRIPTION DISABLE, ALTER SUBSCRIPTION SERVER,
1666 * ALTER SUBSCRIPTION CONNECTION, or ALTER SUBSCRIPTION SET
1667 * (slot_name=NONE).
1668 *
1669 * NB: if the user specifies multiple SET options, then we may still need
1670 * to construct conninfo even if slot_name is set to NONE.
1671 */
1672 if (stmt->kind == ALTER_SUBSCRIPTION_ENABLED)
1673 {
1674 if (opts.specified_opts == SUBOPT_ENABLED && !opts.enabled)
1675 orig_conninfo_needed = false;
1676 }
1677 else if (stmt->kind == ALTER_SUBSCRIPTION_SERVER ||
1679 {
1680 orig_conninfo_needed = false;
1681 }
1682 else if (stmt->kind == ALTER_SUBSCRIPTION_OPTIONS)
1683 {
1684 /* ... SET (slot_name = NONE) with no other options */
1685 if (opts.specified_opts == SUBOPT_SLOT_NAME && !opts.slot_name)
1686 orig_conninfo_needed = false;
1687 }
1688
1689 /*
1690 * Skip ACL checks on the subscription's foreign server, if any. If
1691 * changing the server (or replacing it with a raw connection), then the
1692 * old one will be removed anyway. If changing something unrelated,
1693 * there's no need to do an additional ACL check here; that will be done
1694 * by the subscription worker.
1695 */
1696 sub = GetSubscription(subid, false, orig_conninfo_needed, false);
1697
1699 origin = sub->origin;
1702
1703 /*
1704 * Don't allow non-superuser modification of a subscription with
1705 * password_required=false.
1706 */
1707 if (!sub->passwordrequired && !superuser())
1708 ereport(ERROR,
1710 errmsg("password_required=false is superuser-only"),
1711 errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1712
1713 /* Lock the subscription so nobody else can do anything with it. */
1715
1716 /* Form a new tuple. */
1717 memset(values, 0, sizeof(values));
1718 memset(nulls, false, sizeof(nulls));
1719 memset(replaces, false, sizeof(replaces));
1720
1722
1723 switch (stmt->kind)
1724 {
1726 {
1727 if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1728 {
1729 /*
1730 * The subscription must be disabled to allow slot_name as
1731 * 'none', otherwise, the apply worker will repeatedly try
1732 * to stream the data using that slot_name which neither
1733 * exists on the publisher nor the user will be allowed to
1734 * create it.
1735 */
1736 if (sub->enabled && !opts.slot_name)
1737 ereport(ERROR,
1739 errmsg("cannot set %s for enabled subscription",
1740 "slot_name = NONE")));
1741
1742 if (opts.slot_name)
1745 else
1746 nulls[Anum_pg_subscription_subslotname - 1] = true;
1748 }
1749
1750 if (opts.synchronous_commit)
1751 {
1753 CStringGetTextDatum(opts.synchronous_commit);
1755 }
1756
1757 if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1758 {
1760 BoolGetDatum(opts.binary);
1762 }
1763
1764 if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1765 {
1767 CharGetDatum(opts.streaming);
1769 }
1770
1771 if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1772 {
1774 = BoolGetDatum(opts.disableonerr);
1776 = true;
1777 }
1778
1779 if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1780 {
1781 /* Non-superuser may not disable password_required. */
1782 if (!opts.passwordrequired && !superuser())
1783 ereport(ERROR,
1785 errmsg("password_required=false is superuser-only"),
1786 errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1787
1789 = BoolGetDatum(opts.passwordrequired);
1791 = true;
1792 }
1793
1794 if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
1795 {
1797 BoolGetDatum(opts.runasowner);
1799 }
1800
1801 if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT))
1802 {
1803 /*
1804 * We need to update both the slot and the subscription
1805 * for the two_phase option. We can enable the two_phase
1806 * option for a slot only once the initial data
1807 * synchronization is done. This is to avoid missing some
1808 * data as explained in comments atop worker.c.
1809 */
1810 update_two_phase = !opts.twophase;
1811
1812 CheckAlterSubOption(sub, "two_phase", update_two_phase,
1813 isTopLevel);
1814
1815 /*
1816 * Modifying the two_phase slot option requires a slot
1817 * lookup by slot name, so changing the slot name at the
1818 * same time is not allowed.
1819 */
1820 if (update_two_phase &&
1821 IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1822 ereport(ERROR,
1824 errmsg("\"slot_name\" and \"two_phase\" cannot be altered at the same time")));
1825
1826 /*
1827 * Note that workers may still survive even if the
1828 * subscription has been disabled.
1829 *
1830 * Ensure workers have already been exited to avoid
1831 * getting prepared transactions while we are disabling
1832 * the two_phase option. Otherwise, the changes of an
1833 * already prepared transaction can be replicated again
1834 * along with its corresponding commit, leading to
1835 * duplicate data or errors.
1836 */
1837 if (logicalrep_workers_find(subid, true, true))
1838 ereport(ERROR,
1840 errmsg("cannot alter \"two_phase\" when logical replication worker is still running"),
1841 errhint("Try again after some time.")));
1842
1843 /*
1844 * two_phase cannot be disabled if there are any
1845 * uncommitted prepared transactions present otherwise it
1846 * can lead to duplicate data or errors as explained in
1847 * the comment above.
1848 */
1849 if (update_two_phase &&
1851 LookupGXactBySubid(subid))
1852 ereport(ERROR,
1854 errmsg("cannot disable \"two_phase\" when prepared transactions exist"),
1855 errhint("Resolve these transactions and try again.")));
1856
1857 /* Change system catalog accordingly */
1859 CharGetDatum(opts.twophase ?
1863 }
1864
1865 if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1866 {
1867 /*
1868 * Similar to the two_phase case above, we need to update
1869 * the failover option for both the slot and the
1870 * subscription.
1871 */
1872 update_failover = true;
1873
1874 CheckAlterSubOption(sub, "failover", update_failover,
1875 isTopLevel);
1876
1878 BoolGetDatum(opts.failover);
1880 }
1881
1882 if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
1883 {
1885 BoolGetDatum(opts.retaindeadtuples);
1887
1888 /*
1889 * Update the retention status only if there's a change in
1890 * the retain_dead_tuples option value.
1891 *
1892 * Automatically marking retention as active when
1893 * retain_dead_tuples is enabled may not always be ideal,
1894 * especially if retention was previously stopped and the
1895 * user toggles retain_dead_tuples without adjusting the
1896 * publisher workload. However, this behavior provides a
1897 * convenient way for users to manually refresh the
1898 * retention status. Since retention will be stopped again
1899 * unless the publisher workload is reduced, this approach
1900 * is acceptable for now.
1901 */
1902 if (opts.retaindeadtuples != sub->retaindeadtuples)
1903 {
1905 BoolGetDatum(opts.retaindeadtuples);
1907
1908 retention_active = opts.retaindeadtuples;
1909 }
1910
1911 CheckAlterSubOption(sub, "retain_dead_tuples", false, isTopLevel);
1912
1913 /*
1914 * Workers may continue running even after the
1915 * subscription has been disabled.
1916 *
1917 * To prevent race conditions (as described in
1918 * CheckAlterSubOption()), ensure that all worker
1919 * processes have already exited before proceeding.
1920 */
1921 if (logicalrep_workers_find(subid, true, true))
1922 ereport(ERROR,
1924 errmsg("cannot alter retain_dead_tuples when logical replication worker is still running"),
1925 errhint("Try again after some time.")));
1926
1927 /*
1928 * Notify the launcher to manage the replication slot for
1929 * conflict detection. This ensures that replication slot
1930 * is efficiently handled (created, updated, or dropped)
1931 * in response to any configuration changes.
1932 */
1934
1935 check_pub_rdt = opts.retaindeadtuples;
1936 retain_dead_tuples = opts.retaindeadtuples;
1937 }
1938
1939 if (IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
1940 {
1942 Int32GetDatum(opts.maxretention);
1944
1945 max_retention = opts.maxretention;
1946 }
1947
1948 /*
1949 * Ensure that system configuration parameters are set
1950 * appropriately to support retain_dead_tuples and
1951 * max_retention_duration.
1952 */
1953 if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) ||
1954 IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
1958 (max_retention > 0));
1959
1960 if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1961 {
1963 CStringGetTextDatum(opts.origin);
1965
1966 /*
1967 * Check if changes from different origins may be received
1968 * from the publisher when the origin is changed to ANY
1969 * and retain_dead_tuples is enabled. Use |= so that we
1970 * don't clear the flag already set when
1971 * retain_dead_tuples was changed in the same command.
1972 */
1975
1976 origin = opts.origin;
1977 }
1978
1979 if (IsSet(opts.specified_opts, SUBOPT_WAL_RECEIVER_TIMEOUT))
1980 {
1982 CStringGetTextDatum(opts.wal_receiver_timeout);
1984 }
1985
1986 if (IsSet(opts.specified_opts, SUBOPT_CONFLICT_LOG_DEST))
1987 {
1990
1991 if (opts.conflictlogdest != old_dest)
1992 {
1993 bool update_relid;
1994 Oid relid = InvalidOid;
1995
1999
2001 old_dest,
2002 opts.conflictlogdest,
2003 &relid);
2004 if (update_relid)
2005 {
2007 ObjectIdGetDatum(relid);
2009 true;
2010 }
2011 }
2012 }
2013
2014 update_tuple = true;
2015 break;
2016 }
2017
2019 {
2020 Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
2021
2022 if (!sub->slotname && opts.enabled)
2023 ereport(ERROR,
2025 errmsg("cannot enable subscription that does not have a slot name")));
2026
2027 /*
2028 * Check track_commit_timestamp only when enabling the
2029 * subscription in case it was disabled after creation. See
2030 * comments atop CheckSubDeadTupleRetention() for details.
2031 */
2032 CheckSubDeadTupleRetention(opts.enabled, !opts.enabled,
2034 sub->retentionactive, false);
2035
2037 BoolGetDatum(opts.enabled);
2039
2040 if (opts.enabled)
2042
2043 update_tuple = true;
2044
2045 /*
2046 * The subscription might be initially created with
2047 * connect=false and retain_dead_tuples=true, meaning the
2048 * remote server's status may not be checked. Ensure this
2049 * check is conducted now.
2050 */
2051 check_pub_rdt = sub->retaindeadtuples && opts.enabled;
2052 break;
2053 }
2054
2056 {
2060
2061 /*
2062 * Remove what was there before, either another foreign server
2063 * or a connection string.
2064 */
2065 if (form->subserver)
2066 {
2069 ForeignServerRelationId, form->subserver);
2070 }
2071 else
2072 {
2073 nulls[Anum_pg_subscription_subconninfo - 1] = true;
2075 }
2076
2077 /*
2078 * Check that the subscription owner has USAGE privileges on
2079 * the server.
2080 */
2081 new_server = GetForeignServerByName(stmt->servername, false);
2083 new_server->serverid,
2084 form->subowner, ACL_USAGE);
2085 if (aclresult != ACLCHECK_OK)
2086 ereport(ERROR,
2088 errmsg("subscription owner \"%s\" does not have permission on foreign server \"%s\"",
2089 GetUserNameFromId(form->subowner, false),
2090 new_server->servername));
2091
2092 /* make sure a user mapping exists */
2093 GetUserMapping(form->subowner, new_server->serverid);
2094
2096 new_server);
2097
2098 /* Load the library providing us libpq calls. */
2099 load_file("libpqwalreceiver", false);
2100 /* Check the connection info string. */
2102 sub->passwordrequired && !sub->ownersuperuser);
2103
2106
2109
2110 update_tuple = true;
2111 }
2112
2113 /*
2114 * Since the remote server configuration might have changed,
2115 * perform a check to ensure it permits enabling
2116 * retain_dead_tuples.
2117 */
2119 break;
2120
2122 /* remove reference to foreign server and dependencies, if present */
2123 if (form->subserver)
2124 {
2127 ForeignServerRelationId, form->subserver);
2128
2131 }
2132
2133 new_conninfo = stmt->conninfo;
2134
2135 /* Load the library providing us libpq calls. */
2136 load_file("libpqwalreceiver", false);
2137 /* Check the connection info string. */
2139 sub->passwordrequired && !sub->ownersuperuser);
2140
2142 CStringGetTextDatum(stmt->conninfo);
2144 update_tuple = true;
2145
2146 /*
2147 * Since the remote server configuration might have changed,
2148 * perform a check to ensure it permits enabling
2149 * retain_dead_tuples.
2150 */
2152 break;
2153
2155 {
2157 publicationListToArray(stmt->publication);
2159
2160 update_tuple = true;
2161
2162 /* Refresh if user asked us to. */
2163 if (opts.refresh)
2164 {
2165 if (!sub->enabled)
2166 ereport(ERROR,
2168 errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
2169 errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
2170
2171 /*
2172 * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
2173 * why this is not allowed.
2174 */
2175 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2176 ereport(ERROR,
2178 errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
2179 errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
2180
2181 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2182
2183 /* Make sure refresh sees the new list of publications. */
2184 sub->publications = stmt->publication;
2185
2186 AlterSubscription_refresh(sub, opts.copy_data,
2187 stmt->publication);
2188 }
2189
2190 break;
2191 }
2192
2195 {
2196 List *publist;
2198
2199 publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
2203
2204 update_tuple = true;
2205
2206 /* Refresh if user asked us to. */
2207 if (opts.refresh)
2208 {
2209 /* We only need to validate user specified publications. */
2210 List *validate_publications = (isadd) ? stmt->publication : NULL;
2211
2212 if (!sub->enabled)
2213 ereport(ERROR,
2215 errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
2216 /* translator: %s is an SQL ALTER command */
2217 errhint("Use %s instead.",
2218 isadd ?
2219 "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
2220 "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
2221
2222 /*
2223 * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
2224 * why this is not allowed.
2225 */
2226 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2227 ereport(ERROR,
2229 errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
2230 /* translator: %s is an SQL ALTER command */
2231 errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
2232 isadd ?
2233 "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
2234 "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
2235
2236 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2237
2238 /* Refresh the new list of publications. */
2239 sub->publications = publist;
2240
2241 AlterSubscription_refresh(sub, opts.copy_data,
2243 }
2244
2245 break;
2246 }
2247
2249 {
2250 if (!sub->enabled)
2251 ereport(ERROR,
2253 errmsg("%s is not allowed for disabled subscriptions",
2254 "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
2255
2256 /*
2257 * The subscription option "two_phase" requires that
2258 * replication has passed the initial table synchronization
2259 * phase before the two_phase becomes properly enabled.
2260 *
2261 * But, having reached this two-phase commit "enabled" state
2262 * we must not allow any subsequent table initialization to
2263 * occur. So the ALTER SUBSCRIPTION ... REFRESH PUBLICATION is
2264 * disallowed when the user had requested two_phase = on mode.
2265 *
2266 * The exception to this restriction is when copy_data =
2267 * false, because when copy_data is false the tablesync will
2268 * start already in READY state and will exit directly without
2269 * doing anything.
2270 *
2271 * For more details see comments atop worker.c.
2272 */
2273 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2274 ereport(ERROR,
2276 errmsg("ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data is not allowed when two_phase is enabled"),
2277 errhint("Use ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
2278
2279 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH PUBLICATION");
2280
2281 AlterSubscription_refresh(sub, opts.copy_data, NULL);
2282
2283 break;
2284 }
2285
2287 {
2288 if (!sub->enabled)
2289 ereport(ERROR,
2291 errmsg("%s is not allowed for disabled subscriptions",
2292 "ALTER SUBSCRIPTION ... REFRESH SEQUENCES"));
2293
2295
2296 break;
2297 }
2298
2300 {
2301 /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
2302 Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
2303
2304 /*
2305 * If the user sets subskiplsn, we do a sanity check to make
2306 * sure that the specified LSN is a probable value.
2307 */
2308 if (XLogRecPtrIsValid(opts.lsn))
2309 {
2311 char originname[NAMEDATALEN];
2312 XLogRecPtr remote_lsn;
2313
2315 originname, sizeof(originname));
2317 remote_lsn = replorigin_get_progress(originid, false);
2318
2319 /* Check the given LSN is at least a future LSN */
2320 if (XLogRecPtrIsValid(remote_lsn) && opts.lsn < remote_lsn)
2321 ereport(ERROR,
2323 errmsg("skip WAL location (LSN %X/%08X) must be greater than origin LSN %X/%08X",
2324 LSN_FORMAT_ARGS(opts.lsn),
2325 LSN_FORMAT_ARGS(remote_lsn))));
2326 }
2327
2330
2331 update_tuple = true;
2332 break;
2333 }
2334
2335 default:
2336 elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
2337 stmt->kind);
2338 }
2339
2340 /* Update the catalog if needed. */
2341 if (update_tuple)
2342 {
2344 replaces);
2345
2346 CatalogTupleUpdate(rel, &tup->t_self, tup);
2347
2349 }
2350
2351 /*
2352 * Try to acquire the connection necessary either for modifying the slot
2353 * or for checking if the remote server permits enabling
2354 * retain_dead_tuples.
2355 *
2356 * This has to be at the end because otherwise if there is an error while
2357 * doing the database operations we won't be able to rollback altered
2358 * slot.
2359 */
2361 {
2362 bool must_use_password;
2363 char *err;
2365
2367
2368 /* Load the library providing us libpq calls. */
2369 load_file("libpqwalreceiver", false);
2370
2371 /*
2372 * Try to connect to the publisher, using the new connection string if
2373 * available.
2374 */
2376 wrconn = walrcv_connect(new_conninfo ? new_conninfo : sub->conninfo,
2378 &err);
2379 if (!wrconn)
2380 ereport(ERROR,
2382 errmsg("subscription \"%s\" could not connect to the publisher: %s",
2383 sub->name, err)));
2384
2385 PG_TRY();
2386 {
2389
2391 retain_dead_tuples, origin, NULL, 0,
2392 sub->name);
2393
2396 update_failover ? &opts.failover : NULL,
2397 update_two_phase ? &opts.twophase : NULL);
2398 }
2399 PG_FINALLY();
2400 {
2402 }
2403 PG_END_TRY();
2404 }
2405
2407
2409
2410 /* Wake up related replication workers to handle this change quickly. */
2412
2413 return myself;
2414}
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:3902
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4156
void LogicalRepWorkersWakeupAtCommit(Oid subid)
Definition worker.c:6334
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition worker.c:648
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define CStringGetTextDatum(s)
Definition builtins.h:98
#define Assert(condition)
Definition c.h:1002
uint32_t uint32
Definition c.h:683
const char *const ConflictLogDestNames[]
Definition conflict.c:34
ConflictLogDest GetConflictLogDest(const char *dest)
Definition conflict.c:210
ConflictLogDest
Definition conflict.h:90
@ 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:875
int errhint(const char *fmt,...) pg_attribute_printf(1
#define PG_TRY(...)
Definition elog.h:374
#define WARNING
Definition elog.h:37
#define PG_END_TRY(...)
Definition elog.h:399
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define NOTICE
Definition elog.h:36
#define PG_FINALLY(...)
Definition elog.h:391
#define ereport(elevel,...)
Definition elog.h:152
void err(int eval, const char *fmt,...)
Definition err.c:43
#define DirectFunctionCall1(func, arg1)
Definition fmgr.h:688
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition foreign.c:185
char * ForeignServerConnectionString(Oid userid, ForeignServer *server)
Definition foreign.c:202
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition foreign.c:232
Oid MyDatabaseId
Definition globals.c:96
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1118
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
#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:303
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:990
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:243
XLogRecPtr replorigin_get_progress(ReplOriginId node, bool flush)
Definition origin.c:1057
@ 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:51
long deleteDependencyRecordsForSpecific(Oid classId, Oid objectId, char deptype, Oid refclassId, Oid refobjectId)
Definition pg_depend.c:411
static Datum LSNGetDatum(XLogRecPtr X)
Definition pg_lsn.h:31
Subscription * GetSubscription(Oid subid, bool missing_ok, bool conninfo_needed, bool conninfo_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:383
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:542
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 bool alter_sub_conflict_log_dest(Subscription *sub, ConflictLogDest oldlogdest, ConflictLogDest newlogdest, Oid *conflicttablerelid)
#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_CONFLICT_LOG_DEST
static void parse_subscription_options(ParseState *pstate, List *stmt_options, uint32 supported_opts, SubOpts *opts)
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:2803
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:3701
#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_sub_conflict_log_dest(), 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::conflictlogdest, ConflictLogDestNames, Subscription::conninfo, CStringGetDatum(), CStringGetTextDatum, deleteDependencyRecordsForSpecific(), DEPENDENCY_NORMAL, DirectFunctionCall1, elog, Subscription::enabled, ereport, err(), errcode(), errhint(), errmsg, ERROR, fb(), ForeignServerConnectionString(), Form_pg_subscription, GetConflictLogDest(), 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_CONFLICT_LOG_DEST, 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 2950 of file subscriptioncmds.c.

2951{
2952 Oid subid;
2953 HeapTuple tup;
2954 Relation rel;
2955 ObjectAddress address;
2957
2959
2962
2963 if (!HeapTupleIsValid(tup))
2964 ereport(ERROR,
2966 errmsg("subscription \"%s\" does not exist", name)));
2967
2969 subid = form->oid;
2970
2972
2974
2976
2978
2979 return address;
2980}
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 2986 of file subscriptioncmds.c.

2987{
2988 HeapTuple tup;
2989 Relation rel;
2990
2992
2994
2995 if (!HeapTupleIsValid(tup))
2996 ereport(ERROR,
2998 errmsg("subscription with OID %u does not exist", subid)));
2999
3001
3003
3005}
#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 3357 of file subscriptioncmds.c.

3361{
3364
3366 {
3368 ereport(ERROR,
3370 errmsg("\"wal_level\" is insufficient to create the replication slot required by retain_dead_tuples"),
3371 errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start."));
3372
3376 errmsg("commit timestamp and origin data required for detecting conflicts won't be retained"),
3377 errhint("Consider setting \"%s\" to true.",
3378 "track_commit_timestamp"));
3379
3383 errmsg("deleted rows to detect conflicts would not be removed until the subscription is enabled"),
3385 ? errhint("Consider setting %s to false.",
3386 "retain_dead_tuples") : 0);
3387 }
3388 else if (max_retention_set)
3389 {
3392 errmsg("max_retention_duration is ineffective when retain_dead_tuples is disabled"));
3393 }
3394}
bool track_commit_timestamp
Definition commit_ts.c:121
int wal_level
Definition xlog.c:138
@ WAL_LEVEL_REPLICA
Definition xlog.h:77

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

Referenced by AlterSubscription(), and DisableSubscriptionAndExit().

◆ CreateSubscription()

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

Definition at line 669 of file subscriptioncmds.c.

671{
672 Relation rel;
674 Oid subid;
675 bool nulls[Natts_pg_subscription];
677 Oid owner = GetUserId();
679 Oid serverid;
680 char *conninfo;
682 List *publications;
684 SubOpts opts = {0};
687
688 /*
689 * Parse and check options.
690 *
691 * Connection and publication should not be specified here.
692 */
704
705 /*
706 * Since creating a replication slot is not transactional, rolling back
707 * the transaction leaves the created replication slot. So we cannot run
708 * CREATE SUBSCRIPTION inside a transaction block if creating a
709 * replication slot.
710 */
711 if (opts.create_slot)
712 PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
713
714 /*
715 * We don't want to allow unprivileged users to be able to trigger
716 * attempts to access arbitrary network destinations, so require the user
717 * to have been specifically authorized to create subscriptions.
718 */
722 errmsg("permission denied to create subscription"),
723 errdetail("Only roles with privileges of the \"%s\" role may create subscriptions.",
724 "pg_create_subscription")));
725
726 /*
727 * Since a subscription is a database object, we also check for CREATE
728 * permission on the database.
729 */
731 owner, ACL_CREATE);
732 if (aclresult != ACLCHECK_OK)
735
736 /*
737 * Non-superusers are required to set a password for authentication, and
738 * that password must be used by the target server, but the superuser can
739 * exempt a subscription from this requirement.
740 */
741 if (!opts.passwordrequired && !superuser_arg(owner))
744 errmsg("password_required=false is superuser-only"),
745 errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
746
747 /*
748 * If built with appropriate switch, whine when regression-testing
749 * conventions for subscription names are violated.
750 */
751#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
752 if (strncmp(stmt->subname, "regress_", 8) != 0)
753 elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
754#endif
755
757
758 /* Check if name is used */
761 if (OidIsValid(subid))
762 {
765 errmsg("subscription \"%s\" already exists",
766 stmt->subname)));
767 }
768
769 /*
770 * Ensure that system configuration parameters are set appropriately to
771 * support retain_dead_tuples and max_retention_duration.
772 */
774 opts.retaindeadtuples, opts.retaindeadtuples,
775 (opts.maxretention > 0));
776
777 if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
778 opts.slot_name == NULL)
779 opts.slot_name = stmt->subname;
780
781 /* The default for synchronous_commit of subscriptions is off. */
782 if (opts.synchronous_commit == NULL)
783 opts.synchronous_commit = "off";
784
785 /*
786 * The default for wal_receiver_timeout of subscriptions is -1, which
787 * means the value is inherited from the server configuration, command
788 * line, or role/database settings.
789 */
790 if (opts.wal_receiver_timeout == NULL)
791 opts.wal_receiver_timeout = "-1";
792
793 /* Load the library providing us libpq calls. */
794 load_file("libpqwalreceiver", false);
795
796 if (stmt->servername)
797 {
798 ForeignServer *server;
799
800 Assert(!stmt->conninfo);
801 conninfo = NULL;
802
803 server = GetForeignServerByName(stmt->servername, false);
805 if (aclresult != ACLCHECK_OK)
807
808 /* make sure a user mapping exists */
809 GetUserMapping(owner, server->serverid);
810
811 serverid = server->serverid;
812 conninfo = ForeignServerConnectionString(owner, server);
813 }
814 else
815 {
816 Assert(stmt->conninfo);
817
818 serverid = InvalidOid;
819 conninfo = stmt->conninfo;
820 }
821
822 /* Check the connection info string. */
823 walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
824
825 publications = stmt->publication;
826
827 /* Everything ok, form a new tuple. */
828 memset(values, 0, sizeof(values));
829 memset(nulls, false, sizeof(nulls));
830
843 CharGetDatum(opts.twophase ?
851 BoolGetDatum(opts.retaindeadtuples);
853 Int32GetDatum(opts.maxretention);
855 BoolGetDatum(opts.retaindeadtuples);
857 if (!OidIsValid(serverid))
859 CStringGetTextDatum(conninfo);
860 else
861 nulls[Anum_pg_subscription_subconninfo - 1] = true;
862 if (opts.slot_name)
865 else
866 nulls[Anum_pg_subscription_subslotname - 1] = true;
868 CStringGetTextDatum(opts.synchronous_commit);
870 CStringGetTextDatum(opts.wal_receiver_timeout);
872 publicationListToArray(publications);
875
878
879 /*
880 * We create the conflict log table here, if required, so that its
881 * relation OID can be stored when inserting the pg_subscription tuple
882 * below.
883 */
884 if (CONFLICTS_LOGGED_TO_TABLE(opts.conflictlogdest))
885 logrelid = create_conflict_log_table(subid, stmt->subname, owner);
886
887 /* Store table OID in the catalog. */
890
892
893 /* Insert tuple into catalog. */
896
898
900
901 if (stmt->servername)
902 {
904
905 Assert(OidIsValid(serverid));
906
909 }
910
911 /*
912 * Establish an internal dependency between the conflict log table and the
913 * subscription.
914 *
915 * We use DEPENDENCY_INTERNAL to signify that the table's lifecycle is
916 * strictly tied to the subscription, similar to how a TOAST table relates
917 * to its main table or a sequence relates to an identity column.
918 *
919 * This ensures the conflict log table is automatically reaped during a
920 * DROP SUBSCRIPTION via performDeletion().
921 */
922 if (OidIsValid(logrelid))
923 {
925
928 }
929
930 /*
931 * A replication origin is currently created for all subscriptions,
932 * including those that only contain sequences or are otherwise empty.
933 *
934 * XXX: While this is technically unnecessary, optimizing it would require
935 * additional logic to skip origin creation during DDL operations and
936 * apply workers initialization, and to handle origin creation dynamically
937 * when tables are added to the subscription. It is not clear whether
938 * preventing creation of origins is worth additional complexity.
939 */
942
943 /*
944 * Connect to remote side to execute requested commands and fetch table
945 * and sequence info.
946 */
947 if (opts.connect)
948 {
949 char *err;
952
953 /* Try to connect to the publisher. */
954 must_use_password = !superuser_arg(owner) && opts.passwordrequired;
955 wrconn = walrcv_connect(conninfo, true, true, must_use_password,
956 stmt->subname, &err);
957 if (!wrconn)
960 errmsg("subscription \"%s\" could not connect to the publisher: %s",
961 stmt->subname, err)));
962
963 PG_TRY();
964 {
965 bool has_tables = false;
966 List *pubrels;
967 char relation_state;
968
969 check_publications(wrconn, publications);
971 opts.copy_data,
972 opts.retaindeadtuples, opts.origin,
973 NULL, 0, stmt->subname);
975 opts.copy_data, opts.origin,
976 NULL, 0, stmt->subname);
977
978 if (opts.retaindeadtuples)
980
981 /*
982 * Set sync state based on if we were asked to do data copy or
983 * not.
984 */
986
987 /*
988 * Build local relation status info. Relations are for both tables
989 * and sequences from the publisher.
990 */
991 pubrels = fetch_relation_list(wrconn, publications);
992
994 {
995 Oid relid;
996 char relkind;
997 RangeVar *rv = pubrelinfo->rv;
998
999 relid = RangeVarGetRelid(rv, AccessShareLock, false);
1000 relkind = get_rel_relkind(relid);
1001
1002 /* Check for supported relkind. */
1003 CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
1004 rv->schemaname, rv->relname);
1005 has_tables |= (relkind != RELKIND_SEQUENCE);
1007 InvalidXLogRecPtr, true);
1008 }
1009
1010 /*
1011 * If requested, create permanent slot for the subscription. We
1012 * won't use the initial snapshot for anything, so no need to
1013 * export it.
1014 *
1015 * XXX: Similar to origins, it is not clear whether preventing the
1016 * slot creation for empty and sequence-only subscriptions is
1017 * worth additional complexity.
1018 */
1019 if (opts.create_slot)
1020 {
1021 bool twophase_enabled = false;
1022
1023 Assert(opts.slot_name);
1024
1025 /*
1026 * Even if two_phase is set, don't create the slot with
1027 * two-phase enabled. Will enable it once all the tables are
1028 * synced and ready. This avoids race-conditions like prepared
1029 * transactions being skipped due to changes not being applied
1030 * due to checks in should_apply_changes_for_rel() when
1031 * tablesync for the corresponding tables are in progress. See
1032 * comments atop worker.c.
1033 *
1034 * Note that if tables were specified but copy_data is false
1035 * then it is safe to enable two_phase up-front because those
1036 * tables are already initially in READY state. When the
1037 * subscription has no tables, we leave the twophase state as
1038 * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
1039 * PUBLICATION to work.
1040 */
1041 if (opts.twophase && !opts.copy_data && has_tables)
1042 twophase_enabled = true;
1043
1045 opts.failover, CRS_NOEXPORT_SNAPSHOT, NULL);
1046
1047 if (twophase_enabled)
1049
1051 (errmsg("created replication slot \"%s\" on publisher",
1052 opts.slot_name)));
1053 }
1054 }
1055 PG_FINALLY();
1056 {
1058 }
1059 PG_END_TRY();
1060 }
1061 else
1063 (errmsg("subscription was created, but is not connected"),
1064 errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and alter the subscription to refresh publications.")));
1065
1067
1069
1070 /*
1071 * Notify the launcher to start the apply worker if the subscription is
1072 * enabled, or to create the conflict detection slot if retain_dead_tuples
1073 * is enabled.
1074 *
1075 * Creating the conflict detection slot is essential even when the
1076 * subscription is not enabled. This ensures that dead tuples are
1077 * retained, which is necessary for accurately identifying the type of
1078 * conflict during replication.
1079 */
1080 if (opts.enabled || opts.retaindeadtuples)
1082
1084
1085 return myself;
1086}
bool has_privs_of_role(Oid member, Oid role)
Definition acl.c:5314
#define OidIsValid(objectId)
Definition c.h:917
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition catalog.c:475
Oid create_conflict_log_table(Oid subid, char *subname, Oid subowner)
Definition conflict.c:147
#define CONFLICTS_LOGGED_TO_TABLE(dest)
Definition conflict.h:96
@ DEPENDENCY_INTERNAL
Definition dependency.h:35
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:1025
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:1384
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2309
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition namespace.h:98
#define InvokeObjectPostCreateHook(classId, objectId, subId)
ReplOriginId replorigin_create(const char *roname)
Definition origin.c:274
@ OBJECT_DATABASE
@ OBJECT_FOREIGN_SERVER
#define ACL_CREATE
Definition parsenodes.h:85
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
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:1681
#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

Referenced by ProcessUtilitySlow().

◆ defGetStreamingMode()

char defGetStreamingMode ( DefElem def)
extern

Definition at line 3688 of file subscriptioncmds.c.

3689{
3690 /*
3691 * If no parameter value given, assume "true" is meant.
3692 */
3693 if (!def->arg)
3694 return LOGICALREP_STREAM_ON;
3695
3696 /*
3697 * Allow 0, 1, "false", "true", "off", "on" or "parallel".
3698 */
3699 switch (nodeTag(def->arg))
3700 {
3701 case T_Integer:
3702 switch (intVal(def->arg))
3703 {
3704 case 0:
3705 return LOGICALREP_STREAM_OFF;
3706 case 1:
3707 return LOGICALREP_STREAM_ON;
3708 default:
3709 /* otherwise, error out below */
3710 break;
3711 }
3712 break;
3713 default:
3714 {
3715 char *sval = defGetString(def);
3716
3717 /*
3718 * The set of strings accepted here should match up with the
3719 * grammar's opt_boolean_or_string production.
3720 */
3721 if (pg_strcasecmp(sval, "false") == 0 ||
3722 pg_strcasecmp(sval, "off") == 0)
3723 return LOGICALREP_STREAM_OFF;
3724 if (pg_strcasecmp(sval, "true") == 0 ||
3725 pg_strcasecmp(sval, "on") == 0)
3726 return LOGICALREP_STREAM_ON;
3727 if (pg_strcasecmp(sval, "parallel") == 0)
3729 }
3730 break;
3731 }
3732
3733 ereport(ERROR,
3735 errmsg("%s requires a Boolean value or \"parallel\"",
3736 def->defname)));
3737 return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
3738}
char * defGetString(DefElem *def)
Definition define.c:34
#define nodeTag(nodeptr)
Definition nodes.h:137
char * defname
Definition parsenodes.h:863
Node * arg
Definition parsenodes.h:864
#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 2502 of file subscriptioncmds.c.

2503{
2504 Relation rel;
2506 HeapTuple tup;
2507 Oid subid;
2508 Oid subowner;
2509 Oid subserver;
2511 char *subconninfo = NULL;
2512 Datum datum;
2513 bool isnull;
2514 char *subname;
2515 char *conninfo = NULL;
2516 char *slotname;
2518 ListCell *lc;
2519 char originname[NAMEDATALEN];
2520 char *err = NULL;
2523 List *rstates;
2524 bool must_use_password;
2525
2526 /*
2527 * The launcher may concurrently start a new worker for this subscription.
2528 * During initialization, the worker checks for subscription validity and
2529 * exits if the subscription has already been dropped. See
2530 * InitializeLogRepWorker.
2531 */
2533
2535 CStringGetDatum(stmt->subname));
2536
2537 if (!HeapTupleIsValid(tup))
2538 {
2539 table_close(rel, NoLock);
2540
2541 if (!stmt->missing_ok)
2542 ereport(ERROR,
2544 errmsg("subscription \"%s\" does not exist",
2545 stmt->subname)));
2546 else
2548 (errmsg("subscription \"%s\" does not exist, skipping",
2549 stmt->subname)));
2550
2551 return;
2552 }
2553
2556 if (!isnull)
2557 subconninfo = TextDatumGetCString(datum);
2558
2560 subid = form->oid;
2561 subowner = form->subowner;
2562 subserver = form->subserver;
2563 subconflictlogrelid = form->subconflictlogrelid;
2564 must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
2565
2566 /* must be owner */
2569 stmt->subname);
2570
2571 /* DROP hook for the subscription being removed */
2573
2574 /*
2575 * Lock the subscription so nobody else can do anything with it (including
2576 * the replication workers).
2577 */
2579
2580 /* Get subname */
2583 subname = pstrdup(NameStr(*DatumGetName(datum)));
2584
2585 /* Get slotname */
2588 if (!isnull)
2589 slotname = pstrdup(NameStr(*DatumGetName(datum)));
2590 else
2591 slotname = NULL;
2592
2593 /*
2594 * Since dropping a replication slot is not transactional, the replication
2595 * slot stays dropped even if the transaction rolls back. So we cannot
2596 * run DROP SUBSCRIPTION inside a transaction block if dropping the
2597 * replication slot. Also, in this case, we report a message for dropping
2598 * the subscription to the cumulative stats system.
2599 *
2600 * XXX The command name should really be something like "DROP SUBSCRIPTION
2601 * of a subscription that is associated with a replication slot", but we
2602 * don't have the proper facilities for that.
2603 */
2604 if (slotname)
2605 PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
2606
2609
2610 /* Remove the tuple from catalog. */
2611 CatalogTupleDelete(rel, &tup->t_self);
2612
2614
2615 /*
2616 * Stop all the subscription workers immediately.
2617 *
2618 * This is necessary if we are dropping the replication slot, so that the
2619 * slot becomes accessible.
2620 *
2621 * It is also necessary if the subscription is disabled and was disabled
2622 * in the same transaction. Then the workers haven't seen the disabling
2623 * yet and will still be running, leading to hangs later when we want to
2624 * drop the replication origin. If the subscription was disabled before
2625 * this transaction, then there shouldn't be any workers left, so this
2626 * won't make a difference.
2627 *
2628 * New workers won't be started because we hold an exclusive lock on the
2629 * subscription till the end of the transaction.
2630 */
2631 subworkers = logicalrep_workers_find(subid, false, true);
2632 foreach(lc, subworkers)
2633 {
2635
2637 }
2639
2640 /*
2641 * Remove the no-longer-useful entry in the launcher's table of apply
2642 * worker start times.
2643 *
2644 * If this transaction rolls back, the launcher might restart a failed
2645 * apply worker before wal_retrieve_retry_interval milliseconds have
2646 * elapsed, but that's pretty harmless.
2647 */
2649
2650 /*
2651 * Cleanup of tablesync replication origins.
2652 *
2653 * Any READY-state relations would already have dealt with clean-ups.
2654 *
2655 * Note that the state can't change because we have already stopped both
2656 * the apply and tablesync workers and they can't restart because of
2657 * exclusive lock on the subscription.
2658 */
2659 rstates = GetSubscriptionRelations(subid, true, false, true);
2660 foreach(lc, rstates)
2661 {
2663 Oid relid = rstate->relid;
2664
2665 /* Only cleanup resources of tablesync workers */
2666 if (!OidIsValid(relid))
2667 continue;
2668
2669 /*
2670 * Drop the tablesync's origin tracking if exists.
2671 *
2672 * It is possible that the origin is not yet created for tablesync
2673 * worker so passing missing_ok = true. This can happen for the states
2674 * before SUBREL_STATE_DATASYNC.
2675 */
2677 sizeof(originname));
2678 replorigin_drop_by_name(originname, true, false);
2679 }
2680
2681 /* Drop subscription's conflict log table */
2683
2684 /* Clean up dependencies */
2687
2688 /* Remove any associated relation synchronization states. */
2690
2691 /* Remove the origin tracking if exists. */
2693 replorigin_drop_by_name(originname, true, false);
2694
2695 /*
2696 * Tell the cumulative stats system that the subscription is getting
2697 * dropped.
2698 */
2700
2701 /*
2702 * If there is no slot associated with the subscription, we can finish
2703 * here.
2704 */
2705 if (!slotname && rstates == NIL)
2706 {
2707 table_close(rel, NoLock);
2708 return;
2709 }
2710
2711 /*
2712 * Try to acquire the connection necessary for dropping slots.
2713 *
2714 * Note: If the slotname is NONE/NULL then we allow the command to finish
2715 * and users need to manually cleanup the apply and tablesync worker slots
2716 * later.
2717 *
2718 * This has to be at the end because otherwise if there is an error while
2719 * doing the database operations we won't be able to rollback dropped
2720 * slot.
2721 */
2722 load_file("libpqwalreceiver", false);
2723
2724 if (OidIsValid(subserver))
2726 else
2727 conninfo = subconninfo;
2728
2729 if (conninfo)
2730 wrconn = walrcv_connect(conninfo, true, true, must_use_password,
2731 subname, &err);
2732
2733 if (wrconn == NULL)
2734 {
2735 if (!slotname)
2736 {
2737 /* be tidy */
2739 table_close(rel, NoLock);
2740 return;
2741 }
2742 else
2743 {
2744 ReportSlotConnectionError(rstates, subid, slotname, err);
2745 }
2746 }
2747
2748 PG_TRY();
2749 {
2750 foreach(lc, rstates)
2751 {
2753 Oid relid = rstate->relid;
2754
2755 /* Only cleanup resources of tablesync workers */
2756 if (!OidIsValid(relid))
2757 continue;
2758
2759 /*
2760 * Drop the tablesync slots associated with removed tables.
2761 *
2762 * For SYNCDONE/READY states, the tablesync slot is known to have
2763 * already been dropped by the tablesync worker.
2764 *
2765 * For other states, there is no certainty, maybe the slot does
2766 * not exist yet. Also, if we fail after removing some of the
2767 * slots, next time, it will again try to drop already dropped
2768 * slots and fail. For these reasons, we allow missing_ok = true
2769 * for the drop.
2770 */
2771 if (rstate->state != SUBREL_STATE_SYNCDONE)
2772 {
2773 char syncslotname[NAMEDATALEN] = {0};
2774
2776 sizeof(syncslotname));
2778 }
2779 }
2780
2782
2783 /*
2784 * If there is a slot associated with the subscription, then drop the
2785 * replication slot at the publisher.
2786 */
2787 if (slotname)
2788 ReplicationSlotDropAtPubNode(wrconn, slotname, false);
2789 }
2790 PG_FINALLY();
2791 {
2793 }
2794 PG_END_TRY();
2795
2796 table_close(rel, NoLock);
2797}
#define TextDatumGetCString(d)
Definition builtins.h:99
#define NameStr(name)
Definition c.h:894
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:662
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:1910
#define InvokeObjectDropHook(classId, objectId, subId)
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition origin.c:459
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition pg_depend.c:314
#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
Oid subconflictlogrelid
void pgstat_drop_subscription(Oid subid)
static Name DatumGetName(Datum X)
Definition postgres.h:393
LogicalRepWorkerType type
static void drop_sub_conflict_log_table(Oid subid, char *subname, Oid subconflictlogrelid)
static char * construct_subserver_conninfo(Oid subserver, Oid subowner, char **err)
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:265
HeapTuple SearchSysCache2(SysCacheIdentifier cacheId, Datum key1, Datum key2)
Definition syscache.c:231
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:626
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, Size szslot)
Definition tablesync.c:1236

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ApplyLauncherForgetWorkerStartTime(), CatalogTupleDelete(), construct_subserver_conninfo(), CStringGetDatum(), DatumGetName(), deleteDependencyRecordsFor(), deleteSharedDependencyRecordsFor(), drop_sub_conflict_log_table(), ereport, err(), errcode(), errmsg, ERROR, EventTriggerSQLDropAddObject(), fb(), Form_pg_subscription, 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, ObjectIdGetDatum(), 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(), RowExclusiveLock, SearchSysCache2(), SubscriptionRelState::state, stmt, subconflictlogrelid, LogicalRepWorker::subid, subname, superuser_arg(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), table_close(), table_open(), TextDatumGetCString, LogicalRepWorker::type, walrcv_connect, walrcv_disconnect, and wrconn.

Referenced by ProcessUtilitySlow().