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

1613{
1614 Relation rel;
1616 bool nulls[Natts_pg_subscription];
1619 HeapTuple tup;
1620 Oid subid;
1621 bool orig_conninfo_needed = true;
1622 bool update_tuple = false;
1623 bool update_failover = false;
1624 bool update_two_phase = false;
1625 bool check_pub_rdt = false;
1626 bool retain_dead_tuples;
1627 int max_retention;
1628 bool retention_active;
1629 char *new_conninfo = NULL;
1630 char *origin;
1631 Subscription *sub;
1634 SubOpts opts = {0};
1635
1637
1638 /* Fetch the existing tuple. */
1640 CStringGetDatum(stmt->subname));
1641
1642 if (!HeapTupleIsValid(tup))
1643 ereport(ERROR,
1645 errmsg("subscription \"%s\" does not exist",
1646 stmt->subname)));
1647
1649 subid = form->oid;
1650
1651 /* must be owner */
1654 stmt->subname);
1655
1656 /* parse and check options */
1657 switch (stmt->kind)
1658 {
1671 break;
1672
1675 break;
1676
1679 break;
1680
1684 break;
1685
1688 break;
1689
1692 break;
1693
1694 default:
1695 supported_opts = 0;
1696 break;
1697 }
1698
1699 if (supported_opts > 0)
1701
1702 /*
1703 * Ensure that ALTER SUBSCRIPTION commands that could be used to fix a
1704 * broken connection or prepare to drop a broken subscription don't
1705 * attempt to construct the conninfo. Otherwise, we might encounter the
1706 * error the user is trying to fix.
1707 *
1708 * Specifically, ALTER SUBSCRIPTION DISABLE, ALTER SUBSCRIPTION SERVER,
1709 * ALTER SUBSCRIPTION CONNECTION, or ALTER SUBSCRIPTION SET
1710 * (slot_name=NONE).
1711 *
1712 * NB: if the user specifies multiple SET options, then we may still need
1713 * to construct conninfo even if slot_name is set to NONE.
1714 */
1715 if (stmt->kind == ALTER_SUBSCRIPTION_ENABLED)
1716 {
1717 if (opts.specified_opts == SUBOPT_ENABLED && !opts.enabled)
1718 orig_conninfo_needed = false;
1719 }
1720 else if (stmt->kind == ALTER_SUBSCRIPTION_SERVER ||
1722 {
1723 orig_conninfo_needed = false;
1724 }
1725 else if (stmt->kind == ALTER_SUBSCRIPTION_OPTIONS)
1726 {
1727 /* ... SET (slot_name = NONE) with no other options */
1728 if (opts.specified_opts == SUBOPT_SLOT_NAME && !opts.slot_name)
1729 orig_conninfo_needed = false;
1730 }
1731
1732 /*
1733 * Skip ACL checks on the subscription's foreign server, if any. If
1734 * changing the server (or replacing it with a raw connection), then the
1735 * old one will be removed anyway. If changing something unrelated,
1736 * there's no need to do an additional ACL check here; that will be done
1737 * by the subscription worker.
1738 */
1739 sub = GetSubscription(subid, false, orig_conninfo_needed, false);
1740
1742 origin = sub->origin;
1745
1746 /*
1747 * Don't allow non-superuser modification of a subscription with
1748 * password_required=false.
1749 */
1750 if (!sub->passwordrequired && !superuser())
1751 ereport(ERROR,
1753 errmsg("password_required=false is superuser-only"),
1754 errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1755
1756 /* Lock the subscription so nobody else can do anything with it. */
1758
1759 /* Form a new tuple. */
1760 memset(values, 0, sizeof(values));
1761 memset(nulls, false, sizeof(nulls));
1762 memset(replaces, false, sizeof(replaces));
1763
1765
1766 switch (stmt->kind)
1767 {
1769 {
1770 if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1771 {
1772 /*
1773 * The subscription must be disabled to allow slot_name as
1774 * 'none', otherwise, the apply worker will repeatedly try
1775 * to stream the data using that slot_name which neither
1776 * exists on the publisher nor the user will be allowed to
1777 * create it.
1778 */
1779 if (sub->enabled && !opts.slot_name)
1780 ereport(ERROR,
1782 errmsg("cannot set %s for enabled subscription",
1783 "slot_name = NONE")));
1784
1785 if (opts.slot_name)
1788 else
1789 nulls[Anum_pg_subscription_subslotname - 1] = true;
1791 }
1792
1793 if (opts.synchronous_commit)
1794 {
1796 CStringGetTextDatum(opts.synchronous_commit);
1798 }
1799
1800 if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1801 {
1803 BoolGetDatum(opts.binary);
1805 }
1806
1807 if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1808 {
1810 CharGetDatum(opts.streaming);
1812 }
1813
1814 if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1815 {
1817 = BoolGetDatum(opts.disableonerr);
1819 = true;
1820 }
1821
1822 if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1823 {
1824 /* Non-superuser may not disable password_required. */
1825 if (!opts.passwordrequired && !superuser())
1826 ereport(ERROR,
1828 errmsg("password_required=false is superuser-only"),
1829 errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1830
1832 = BoolGetDatum(opts.passwordrequired);
1834 = true;
1835 }
1836
1837 if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
1838 {
1840 BoolGetDatum(opts.runasowner);
1842 }
1843
1844 if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT))
1845 {
1846 /*
1847 * We need to update both the slot and the subscription
1848 * for the two_phase option. We can enable the two_phase
1849 * option for a slot only once the initial data
1850 * synchronization is done. This is to avoid missing some
1851 * data as explained in comments atop worker.c.
1852 */
1853 update_two_phase = !opts.twophase;
1854
1855 CheckAlterSubOption(sub, "two_phase", update_two_phase,
1856 isTopLevel);
1857
1858 /*
1859 * Modifying the two_phase slot option requires a slot
1860 * lookup by slot name, so changing the slot name at the
1861 * same time is not allowed.
1862 */
1863 if (update_two_phase &&
1864 IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1865 ereport(ERROR,
1867 errmsg("\"slot_name\" and \"two_phase\" cannot be altered at the same time")));
1868
1869 /*
1870 * Note that workers may still survive even if the
1871 * subscription has been disabled.
1872 *
1873 * Ensure workers have already been exited to avoid
1874 * getting prepared transactions while we are disabling
1875 * the two_phase option. Otherwise, the changes of an
1876 * already prepared transaction can be replicated again
1877 * along with its corresponding commit, leading to
1878 * duplicate data or errors.
1879 */
1880 if (logicalrep_workers_find(subid, true, true))
1881 ereport(ERROR,
1883 errmsg("cannot alter \"two_phase\" when logical replication worker is still running"),
1884 errhint("Try again after some time.")));
1885
1886 /*
1887 * two_phase cannot be disabled if there are any
1888 * uncommitted prepared transactions present otherwise it
1889 * can lead to duplicate data or errors as explained in
1890 * the comment above.
1891 */
1892 if (update_two_phase &&
1894 LookupGXactBySubid(subid))
1895 ereport(ERROR,
1897 errmsg("cannot disable \"two_phase\" when prepared transactions exist"),
1898 errhint("Resolve these transactions and try again.")));
1899
1900 /* Change system catalog accordingly */
1902 CharGetDatum(opts.twophase ?
1906 }
1907
1908 if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1909 {
1910 /*
1911 * Similar to the two_phase case above, we need to update
1912 * the failover option for both the slot and the
1913 * subscription.
1914 */
1915 update_failover = true;
1916
1917 CheckAlterSubOption(sub, "failover", update_failover,
1918 isTopLevel);
1919
1921 BoolGetDatum(opts.failover);
1923 }
1924
1925 if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
1926 {
1928 BoolGetDatum(opts.retaindeadtuples);
1930
1931 /*
1932 * Update the retention status only if there's a change in
1933 * the retain_dead_tuples option value.
1934 *
1935 * Automatically marking retention as active when
1936 * retain_dead_tuples is enabled may not always be ideal,
1937 * especially if retention was previously stopped and the
1938 * user toggles retain_dead_tuples without adjusting the
1939 * publisher workload. However, this behavior provides a
1940 * convenient way for users to manually refresh the
1941 * retention status. Since retention will be stopped again
1942 * unless the publisher workload is reduced, this approach
1943 * is acceptable for now.
1944 */
1945 if (opts.retaindeadtuples != sub->retaindeadtuples)
1946 {
1948 BoolGetDatum(opts.retaindeadtuples);
1950
1951 retention_active = opts.retaindeadtuples;
1952 }
1953
1954 CheckAlterSubOption(sub, "retain_dead_tuples", false, isTopLevel);
1955
1956 /*
1957 * Workers may continue running even after the
1958 * subscription has been disabled.
1959 *
1960 * To prevent race conditions (as described in
1961 * CheckAlterSubOption()), ensure that all worker
1962 * processes have already exited before proceeding.
1963 */
1964 if (logicalrep_workers_find(subid, true, true))
1965 ereport(ERROR,
1967 errmsg("cannot alter retain_dead_tuples when logical replication worker is still running"),
1968 errhint("Try again after some time.")));
1969
1970 /*
1971 * Notify the launcher to manage the replication slot for
1972 * conflict detection. This ensures that replication slot
1973 * is efficiently handled (created, updated, or dropped)
1974 * in response to any configuration changes.
1975 */
1977
1978 check_pub_rdt = opts.retaindeadtuples;
1979 retain_dead_tuples = opts.retaindeadtuples;
1980 }
1981
1982 if (IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
1983 {
1985 Int32GetDatum(opts.maxretention);
1987
1988 max_retention = opts.maxretention;
1989 }
1990
1991 /*
1992 * Ensure that system configuration parameters are set
1993 * appropriately to support retain_dead_tuples and
1994 * max_retention_duration.
1995 */
1996 if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) ||
1997 IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
2001 (max_retention > 0));
2002
2003 if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
2004 {
2006 CStringGetTextDatum(opts.origin);
2008
2009 /*
2010 * Check if changes from different origins may be received
2011 * from the publisher when the origin is changed to ANY
2012 * and retain_dead_tuples is enabled. Use |= so that we
2013 * don't clear the flag already set when
2014 * retain_dead_tuples was changed in the same command.
2015 */
2018
2019 origin = opts.origin;
2020 }
2021
2022 if (IsSet(opts.specified_opts, SUBOPT_WAL_RECEIVER_TIMEOUT))
2023 {
2025 CStringGetTextDatum(opts.wal_receiver_timeout);
2027 }
2028
2029 if (IsSet(opts.specified_opts, SUBOPT_CONFLICT_LOG_DEST))
2030 {
2033
2034 if (opts.conflictlogdest != old_dest)
2035 {
2036 bool update_relid;
2037 Oid relid = InvalidOid;
2038
2042
2044 old_dest,
2045 opts.conflictlogdest,
2046 &relid);
2047 if (update_relid)
2048 {
2050 ObjectIdGetDatum(relid);
2052 true;
2053 }
2054 }
2055 }
2056
2057 update_tuple = true;
2058 break;
2059 }
2060
2062 {
2063 Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
2064
2065 if (!sub->slotname && opts.enabled)
2066 ereport(ERROR,
2068 errmsg("cannot enable subscription that does not have a slot name")));
2069
2070 /*
2071 * Check track_commit_timestamp only when enabling the
2072 * subscription in case it was disabled after creation. See
2073 * comments atop CheckSubDeadTupleRetention() for details.
2074 */
2075 CheckSubDeadTupleRetention(opts.enabled, !opts.enabled,
2077 sub->retentionactive, false);
2078
2080 BoolGetDatum(opts.enabled);
2082
2083 if (opts.enabled)
2085
2086 update_tuple = true;
2087
2088 /*
2089 * The subscription might be initially created with
2090 * connect=false and retain_dead_tuples=true, meaning the
2091 * remote server's status may not be checked. Ensure this
2092 * check is conducted now.
2093 */
2094 check_pub_rdt = sub->retaindeadtuples && opts.enabled;
2095 break;
2096 }
2097
2099 {
2103
2104 /*
2105 * Remove what was there before, either another foreign server
2106 * or a connection string.
2107 */
2108 if (form->subserver)
2109 {
2112 ForeignServerRelationId, form->subserver);
2113 }
2114 else
2115 {
2116 nulls[Anum_pg_subscription_subconninfo - 1] = true;
2118 }
2119
2120 /*
2121 * Check that the subscription owner has USAGE privileges on
2122 * the server.
2123 */
2124 new_server = GetForeignServerByName(stmt->servername, false);
2126 new_server->serverid,
2127 form->subowner, ACL_USAGE);
2128 if (aclresult != ACLCHECK_OK)
2129 ereport(ERROR,
2131 errmsg("subscription owner \"%s\" does not have permission on foreign server \"%s\"",
2132 GetUserNameFromId(form->subowner, false),
2133 new_server->servername));
2134
2135 /* make sure a user mapping exists */
2136 GetUserMapping(form->subowner, new_server->serverid);
2137
2139 new_server);
2140
2141 /* Load the library providing us libpq calls. */
2142 load_file("libpqwalreceiver", false);
2143 /* Check the connection info string. */
2145 sub->passwordrequired && !sub->ownersuperuser);
2146
2149
2152
2153 update_tuple = true;
2154 }
2155
2156 /*
2157 * Since the remote server configuration might have changed,
2158 * perform a check to ensure it permits enabling
2159 * retain_dead_tuples.
2160 */
2162 break;
2163
2165 /* remove reference to foreign server and dependencies, if present */
2166 if (form->subserver)
2167 {
2170 ForeignServerRelationId, form->subserver);
2171
2174 }
2175
2176 new_conninfo = stmt->conninfo;
2177
2178 /* Load the library providing us libpq calls. */
2179 load_file("libpqwalreceiver", false);
2180 /* Check the connection info string. */
2182 sub->passwordrequired && !sub->ownersuperuser);
2183
2185 CStringGetTextDatum(stmt->conninfo);
2187 update_tuple = true;
2188
2189 /*
2190 * Since the remote server configuration might have changed,
2191 * perform a check to ensure it permits enabling
2192 * retain_dead_tuples.
2193 */
2195 break;
2196
2198 {
2200 publicationListToArray(stmt->publication);
2202
2203 update_tuple = true;
2204
2205 /* Refresh if user asked us to. */
2206 if (opts.refresh)
2207 {
2208 if (!sub->enabled)
2209 ereport(ERROR,
2211 errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
2212 errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
2213
2214 /*
2215 * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
2216 * why this is not allowed.
2217 */
2218 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2219 ereport(ERROR,
2221 errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
2222 errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
2223
2224 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2225
2226 /* Make sure refresh sees the new list of publications. */
2227 sub->publications = stmt->publication;
2228
2229 AlterSubscription_refresh(sub, opts.copy_data,
2230 stmt->publication);
2231 }
2232
2233 break;
2234 }
2235
2238 {
2239 List *publist;
2241
2242 publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
2246
2247 update_tuple = true;
2248
2249 /* Refresh if user asked us to. */
2250 if (opts.refresh)
2251 {
2252 /* We only need to validate user specified publications. */
2253 List *validate_publications = (isadd) ? stmt->publication : NULL;
2254
2255 if (!sub->enabled)
2256 ereport(ERROR,
2258 errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
2259 /* translator: %s is an SQL ALTER command */
2260 errhint("Use %s instead.",
2261 isadd ?
2262 "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
2263 "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
2264
2265 /*
2266 * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
2267 * why this is not allowed.
2268 */
2269 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2270 ereport(ERROR,
2272 errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
2273 /* translator: %s is an SQL ALTER command */
2274 errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
2275 isadd ?
2276 "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
2277 "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
2278
2279 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2280
2281 /* Refresh the new list of publications. */
2282 sub->publications = publist;
2283
2284 AlterSubscription_refresh(sub, opts.copy_data,
2286 }
2287
2288 break;
2289 }
2290
2292 {
2293 if (!sub->enabled)
2294 ereport(ERROR,
2296 errmsg("%s is not allowed for disabled subscriptions",
2297 "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
2298
2299 /*
2300 * The subscription option "two_phase" requires that
2301 * replication has passed the initial table synchronization
2302 * phase before the two_phase becomes properly enabled.
2303 *
2304 * But, having reached this two-phase commit "enabled" state
2305 * we must not allow any subsequent table initialization to
2306 * occur. So the ALTER SUBSCRIPTION ... REFRESH PUBLICATION is
2307 * disallowed when the user had requested two_phase = on mode.
2308 *
2309 * The exception to this restriction is when copy_data =
2310 * false, because when copy_data is false the tablesync will
2311 * start already in READY state and will exit directly without
2312 * doing anything.
2313 *
2314 * For more details see comments atop worker.c.
2315 */
2316 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2317 ereport(ERROR,
2319 errmsg("ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data is not allowed when two_phase is enabled"),
2320 errhint("Use ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
2321
2322 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH PUBLICATION");
2323
2324 AlterSubscription_refresh(sub, opts.copy_data, NULL);
2325
2326 break;
2327 }
2328
2330 {
2331 if (!sub->enabled)
2332 ereport(ERROR,
2334 errmsg("%s is not allowed for disabled subscriptions",
2335 "ALTER SUBSCRIPTION ... REFRESH SEQUENCES"));
2336
2338
2339 break;
2340 }
2341
2343 {
2344 /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
2345 Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
2346
2347 /*
2348 * If the user sets subskiplsn, we do a sanity check to make
2349 * sure that the specified LSN is a probable value.
2350 */
2351 if (XLogRecPtrIsValid(opts.lsn))
2352 {
2354 char originname[NAMEDATALEN];
2355 XLogRecPtr remote_lsn;
2356
2358 originname, sizeof(originname));
2360 remote_lsn = replorigin_get_progress(originid, false);
2361
2362 /* Check the given LSN is at least a future LSN */
2363 if (XLogRecPtrIsValid(remote_lsn) && opts.lsn < remote_lsn)
2364 ereport(ERROR,
2366 errmsg("skip WAL location (LSN %X/%08X) must be greater than origin LSN %X/%08X",
2367 LSN_FORMAT_ARGS(opts.lsn),
2368 LSN_FORMAT_ARGS(remote_lsn))));
2369 }
2370
2373
2374 update_tuple = true;
2375 break;
2376 }
2377
2378 default:
2379 elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
2380 stmt->kind);
2381 }
2382
2383 /* Update the catalog if needed. */
2384 if (update_tuple)
2385 {
2387 replaces);
2388
2389 CatalogTupleUpdate(rel, &tup->t_self, tup);
2390
2392 }
2393
2394 /*
2395 * Try to acquire the connection necessary either for modifying the slot
2396 * or for checking if the remote server permits enabling
2397 * retain_dead_tuples.
2398 *
2399 * This has to be at the end because otherwise if there is an error while
2400 * doing the database operations we won't be able to rollback altered
2401 * slot.
2402 */
2404 {
2405 bool must_use_password;
2406 char *err;
2408
2410
2411 /* Load the library providing us libpq calls. */
2412 load_file("libpqwalreceiver", false);
2413
2414 /*
2415 * Try to connect to the publisher, using the new connection string if
2416 * available.
2417 */
2419 wrconn = walrcv_connect(new_conninfo ? new_conninfo : sub->conninfo,
2421 &err);
2422 if (!wrconn)
2423 ereport(ERROR,
2425 errmsg("subscription \"%s\" could not connect to the publisher: %s",
2426 sub->name, err)));
2427
2428 PG_TRY();
2429 {
2432
2434 retain_dead_tuples, origin, NULL, 0,
2435 sub->name);
2436
2439 update_failover ? &opts.failover : NULL,
2440 update_two_phase ? &opts.twophase : NULL);
2441 }
2442 PG_FINALLY();
2443 {
2445 }
2446 PG_END_TRY();
2447 }
2448
2450
2452
2453 /* Wake up related replication workers to handle this change quickly. */
2455
2456 return myself;
2457}
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:6342
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:2805
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 3006 of file subscriptioncmds.c.

3007{
3008 Oid subid;
3009 HeapTuple tup;
3010 Relation rel;
3011 ObjectAddress address;
3013
3015
3018
3019 if (!HeapTupleIsValid(tup))
3020 ereport(ERROR,
3022 errmsg("subscription \"%s\" does not exist", name)));
3023
3025 subid = form->oid;
3026
3028
3030
3032
3034
3035 return address;
3036}
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 3042 of file subscriptioncmds.c.

3043{
3044 HeapTuple tup;
3045 Relation rel;
3047
3049
3051
3052 if (!HeapTupleIsValid(tup))
3053 ereport(ERROR,
3055 errmsg("subscription with OID %u does not exist", subid)));
3056
3058
3059 /*
3060 * Don't process subscriptions belonging to other databases. While
3061 * pg_subscription is a shared catalog, subscriptions refer to db-local
3062 * objects which exist only in the database identified by subdbid.
3063 */
3064 if (form->subdbid == MyDatabaseId)
3066
3068
3070}
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91

References AlterSubscriptionOwner_internal(), ereport, errcode(), errmsg, ERROR, fb(), Form_pg_subscription, GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, MyDatabaseId, 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 3422 of file subscriptioncmds.c.

3426{
3429
3431 {
3433 ereport(ERROR,
3435 errmsg("\"wal_level\" is insufficient to create the replication slot required by retain_dead_tuples"),
3436 errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start."));
3437
3441 errmsg("commit timestamp and origin data required for detecting conflicts won't be retained"),
3442 errhint("Consider setting \"%s\" to true.",
3443 "track_commit_timestamp"));
3444
3448 errmsg("deleted rows to detect conflicts would not be removed until the subscription is enabled"),
3450 ? errhint("Consider setting %s to false.",
3451 "retain_dead_tuples") : 0);
3452 }
3453 else if (max_retention_set)
3454 {
3457 errmsg("max_retention_duration is ineffective when retain_dead_tuples is disabled"));
3458 }
3459}
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 670 of file subscriptioncmds.c.

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

3754{
3755 /*
3756 * If no parameter value given, assume "true" is meant.
3757 */
3758 if (!def->arg)
3759 return LOGICALREP_STREAM_ON;
3760
3761 /*
3762 * Allow 0, 1, "false", "true", "off", "on" or "parallel".
3763 */
3764 switch (nodeTag(def->arg))
3765 {
3766 case T_Integer:
3767 switch (intVal(def->arg))
3768 {
3769 case 0:
3770 return LOGICALREP_STREAM_OFF;
3771 case 1:
3772 return LOGICALREP_STREAM_ON;
3773 default:
3774 /* otherwise, error out below */
3775 break;
3776 }
3777 break;
3778 default:
3779 {
3780 char *sval = defGetString(def);
3781
3782 /*
3783 * The set of strings accepted here should match up with the
3784 * grammar's opt_boolean_or_string production.
3785 */
3786 if (pg_strcasecmp(sval, "false") == 0 ||
3787 pg_strcasecmp(sval, "off") == 0)
3788 return LOGICALREP_STREAM_OFF;
3789 if (pg_strcasecmp(sval, "true") == 0 ||
3790 pg_strcasecmp(sval, "on") == 0)
3791 return LOGICALREP_STREAM_ON;
3792 if (pg_strcasecmp(sval, "parallel") == 0)
3794 }
3795 break;
3796 }
3797
3798 ereport(ERROR,
3800 errmsg("%s requires a Boolean value or \"parallel\"",
3801 def->defname)));
3802 return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
3803}
char * defGetString(DefElem *def)
Definition define.c:34
#define nodeTag(nodeptr)
Definition nodes.h:137
char * defname
Definition parsenodes.h:862
Node * arg
Definition parsenodes.h:863
#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 2545 of file subscriptioncmds.c.

2546{
2547 Relation rel;
2549 HeapTuple tup;
2550 Oid subid;
2551 Oid subowner;
2552 Oid subserver;
2554 char *subconninfo = NULL;
2555 Datum datum;
2556 bool isnull;
2557 char *subname;
2558 char *conninfo = NULL;
2559 char *slotname;
2561 ListCell *lc;
2562 char originname[NAMEDATALEN];
2563 char *err = NULL;
2566 List *rstates;
2567 bool must_use_password;
2568
2569 /*
2570 * The launcher may concurrently start a new worker for this subscription.
2571 * During initialization, the worker checks for subscription validity and
2572 * exits if the subscription has already been dropped. See
2573 * InitializeLogRepWorker.
2574 */
2576
2578 CStringGetDatum(stmt->subname));
2579
2580 if (!HeapTupleIsValid(tup))
2581 {
2582 table_close(rel, NoLock);
2583
2584 if (!stmt->missing_ok)
2585 ereport(ERROR,
2587 errmsg("subscription \"%s\" does not exist",
2588 stmt->subname)));
2589 else
2591 (errmsg("subscription \"%s\" does not exist, skipping",
2592 stmt->subname)));
2593
2594 return;
2595 }
2596
2599 if (!isnull)
2600 subconninfo = TextDatumGetCString(datum);
2601
2603 subid = form->oid;
2604 subowner = form->subowner;
2605 subserver = form->subserver;
2606 subconflictlogrelid = form->subconflictlogrelid;
2607 must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
2608
2609 /* must be owner */
2612 stmt->subname);
2613
2614 /* DROP hook for the subscription being removed */
2616
2617 /*
2618 * Lock the subscription so nobody else can do anything with it (including
2619 * the replication workers).
2620 */
2622
2623 /* Get subname */
2626 subname = pstrdup(NameStr(*DatumGetName(datum)));
2627
2628 /* Get slotname */
2631 if (!isnull)
2632 slotname = pstrdup(NameStr(*DatumGetName(datum)));
2633 else
2634 slotname = NULL;
2635
2636 /*
2637 * Since dropping a replication slot is not transactional, the replication
2638 * slot stays dropped even if the transaction rolls back. So we cannot
2639 * run DROP SUBSCRIPTION inside a transaction block if dropping the
2640 * replication slot. Also, in this case, we report a message for dropping
2641 * the subscription to the cumulative stats system.
2642 *
2643 * XXX The command name should really be something like "DROP SUBSCRIPTION
2644 * of a subscription that is associated with a replication slot", but we
2645 * don't have the proper facilities for that.
2646 */
2647 if (slotname)
2648 PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
2649
2652
2653 /* Remove the tuple from catalog. */
2654 CatalogTupleDelete(rel, &tup->t_self);
2655
2657
2658 /*
2659 * Stop all the subscription workers immediately.
2660 *
2661 * This is necessary if we are dropping the replication slot, so that the
2662 * slot becomes accessible.
2663 *
2664 * It is also necessary if the subscription is disabled and was disabled
2665 * in the same transaction. Then the workers haven't seen the disabling
2666 * yet and will still be running, leading to hangs later when we want to
2667 * drop the replication origin. If the subscription was disabled before
2668 * this transaction, then there shouldn't be any workers left, so this
2669 * won't make a difference.
2670 *
2671 * New workers won't be started because we hold an exclusive lock on the
2672 * subscription till the end of the transaction.
2673 */
2674 subworkers = logicalrep_workers_find(subid, false, true);
2675 foreach(lc, subworkers)
2676 {
2678
2680 }
2682
2683 /*
2684 * Remove the no-longer-useful entry in the launcher's table of apply
2685 * worker start times.
2686 *
2687 * If this transaction rolls back, the launcher might restart a failed
2688 * apply worker before wal_retrieve_retry_interval milliseconds have
2689 * elapsed, but that's pretty harmless.
2690 */
2692
2693 /*
2694 * Cleanup of tablesync replication origins.
2695 *
2696 * Any READY-state relations would already have dealt with clean-ups.
2697 *
2698 * Note that the state can't change because we have already stopped both
2699 * the apply and tablesync workers and they can't restart because of
2700 * exclusive lock on the subscription.
2701 */
2702 rstates = GetSubscriptionRelations(subid, true, false, true);
2703 foreach(lc, rstates)
2704 {
2706 Oid relid = rstate->relid;
2707
2708 /* Only cleanup resources of tablesync workers */
2709 if (!OidIsValid(relid))
2710 continue;
2711
2712 /*
2713 * Drop the tablesync's origin tracking if exists.
2714 *
2715 * It is possible that the origin is not yet created for tablesync
2716 * worker so passing missing_ok = true. This can happen for the states
2717 * before SUBREL_STATE_DATASYNC.
2718 */
2720 sizeof(originname));
2721 replorigin_drop_by_name(originname, true, false);
2722 }
2723
2724 /* Drop subscription's conflict log table */
2726
2727 /* Clean up dependencies */
2730
2731 /* Remove any associated relation synchronization states. */
2733
2734 /* Remove the origin tracking if exists. */
2736 replorigin_drop_by_name(originname, true, false);
2737
2738 /*
2739 * Tell the cumulative stats system that the subscription is getting
2740 * dropped.
2741 */
2743
2744 /*
2745 * If there is no slot associated with the subscription, we can finish
2746 * here.
2747 */
2748 if (!slotname && rstates == NIL)
2749 {
2750 table_close(rel, NoLock);
2751 return;
2752 }
2753
2754 /*
2755 * Try to acquire the connection necessary for dropping slots.
2756 *
2757 * Note: If the slotname is NONE/NULL then we allow the command to finish
2758 * and users need to manually cleanup the apply and tablesync worker slots
2759 * later.
2760 *
2761 * This has to be at the end because otherwise if there is an error while
2762 * doing the database operations we won't be able to rollback dropped
2763 * slot.
2764 */
2765 load_file("libpqwalreceiver", false);
2766
2767 if (OidIsValid(subserver))
2769 else
2770 conninfo = subconninfo;
2771
2772 if (conninfo)
2773 wrconn = walrcv_connect(conninfo, true, true, must_use_password,
2774 subname, &err);
2775
2776 if (wrconn == NULL)
2777 {
2778 if (!slotname)
2779 {
2780 /* be tidy */
2782 table_close(rel, NoLock);
2783 return;
2784 }
2785 else
2786 {
2787 ReportSlotConnectionError(rstates, subid, slotname, err);
2788 }
2789 }
2790
2791 PG_TRY();
2792 {
2793 foreach(lc, rstates)
2794 {
2796 Oid relid = rstate->relid;
2797
2798 /* Only cleanup resources of tablesync workers */
2799 if (!OidIsValid(relid))
2800 continue;
2801
2802 /*
2803 * Drop the tablesync slots associated with removed tables.
2804 *
2805 * For SYNCDONE/READY states, the tablesync slot is known to have
2806 * already been dropped by the tablesync worker.
2807 *
2808 * For other states, there is no certainty, maybe the slot does
2809 * not exist yet. Also, if we fail after removing some of the
2810 * slots, next time, it will again try to drop already dropped
2811 * slots and fail. For these reasons, we allow missing_ok = true
2812 * for the drop.
2813 */
2814 if (rstate->state != SUBREL_STATE_SYNCDONE)
2815 {
2816 char syncslotname[NAMEDATALEN] = {0};
2817
2819 sizeof(syncslotname));
2821 }
2822 }
2823
2825
2826 /*
2827 * If there is a slot associated with the subscription, then drop the
2828 * replication slot at the publisher.
2829 */
2830 if (slotname)
2831 ReplicationSlotDropAtPubNode(wrconn, slotname, false);
2832 }
2833 PG_FINALLY();
2834 {
2836 }
2837 PG_END_TRY();
2838
2839 table_close(rel, NoLock);
2840}
#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().