Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * subscriptioncmds.c
4 : : * subscription catalog manipulation functions
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : * IDENTIFICATION
10 : : * src/backend/commands/subscriptioncmds.c
11 : : *
12 : : *-------------------------------------------------------------------------
13 : : */
14 : :
15 : : #include "postgres.h"
16 : :
17 : : #include "access/commit_ts.h"
18 : : #include "access/htup_details.h"
19 : : #include "access/table.h"
20 : : #include "access/twophase.h"
21 : : #include "access/xact.h"
22 : : #include "catalog/catalog.h"
23 : : #include "catalog/dependency.h"
24 : : #include "catalog/indexing.h"
25 : : #include "catalog/namespace.h"
26 : : #include "catalog/objectaccess.h"
27 : : #include "catalog/objectaddress.h"
28 : : #include "catalog/pg_authid_d.h"
29 : : #include "catalog/pg_database_d.h"
30 : : #include "catalog/pg_foreign_server.h"
31 : : #include "catalog/pg_namespace.h"
32 : : #include "catalog/pg_subscription.h"
33 : : #include "catalog/pg_subscription_rel.h"
34 : : #include "catalog/pg_type.h"
35 : : #include "catalog/pg_user_mapping.h"
36 : : #include "commands/defrem.h"
37 : : #include "commands/event_trigger.h"
38 : : #include "commands/subscriptioncmds.h"
39 : : #include "commands/tablecmds.h"
40 : : #include "executor/executor.h"
41 : : #include "foreign/foreign.h"
42 : : #include "miscadmin.h"
43 : : #include "nodes/makefuncs.h"
44 : : #include "pgstat.h"
45 : : #include "replication/logicallauncher.h"
46 : : #include "replication/logicalworker.h"
47 : : #include "replication/origin.h"
48 : : #include "replication/slot.h"
49 : : #include "replication/walreceiver.h"
50 : : #include "replication/walsender.h"
51 : : #include "replication/worker_internal.h"
52 : : #include "storage/lmgr.h"
53 : : #include "storage/lock.h"
54 : : #include "utils/acl.h"
55 : : #include "utils/builtins.h"
56 : : #include "utils/guc.h"
57 : : #include "utils/lsyscache.h"
58 : : #include "utils/memutils.h"
59 : : #include "utils/pg_lsn.h"
60 : : #include "utils/syscache.h"
61 : :
62 : : /*
63 : : * Options that can be specified by the user in CREATE/ALTER SUBSCRIPTION
64 : : * command.
65 : : */
66 : : #define SUBOPT_CONNECT 0x00000001
67 : : #define SUBOPT_ENABLED 0x00000002
68 : : #define SUBOPT_CREATE_SLOT 0x00000004
69 : : #define SUBOPT_SLOT_NAME 0x00000008
70 : : #define SUBOPT_COPY_DATA 0x00000010
71 : : #define SUBOPT_SYNCHRONOUS_COMMIT 0x00000020
72 : : #define SUBOPT_REFRESH 0x00000040
73 : : #define SUBOPT_BINARY 0x00000080
74 : : #define SUBOPT_STREAMING 0x00000100
75 : : #define SUBOPT_TWOPHASE_COMMIT 0x00000200
76 : : #define SUBOPT_DISABLE_ON_ERR 0x00000400
77 : : #define SUBOPT_PASSWORD_REQUIRED 0x00000800
78 : : #define SUBOPT_RUN_AS_OWNER 0x00001000
79 : : #define SUBOPT_FAILOVER 0x00002000
80 : : #define SUBOPT_RETAIN_DEAD_TUPLES 0x00004000
81 : : #define SUBOPT_MAX_RETENTION_DURATION 0x00008000
82 : : #define SUBOPT_WAL_RECEIVER_TIMEOUT 0x00010000
83 : : #define SUBOPT_LSN 0x00020000
84 : : #define SUBOPT_ORIGIN 0x00040000
85 : : #define SUBOPT_CONFLICT_LOG_DEST 0x00080000
86 : :
87 : : /* check if the 'val' has 'bits' set */
88 : : #define IsSet(val, bits) (((val) & (bits)) == (bits))
89 : :
90 : : /*
91 : : * Structure to hold a bitmap representing the user-provided CREATE/ALTER
92 : : * SUBSCRIPTION command options and the parsed/default values of each of them.
93 : : */
94 : : typedef struct SubOpts
95 : : {
96 : : uint32 specified_opts;
97 : : char *slot_name;
98 : : char *synchronous_commit;
99 : : bool connect;
100 : : bool enabled;
101 : : bool create_slot;
102 : : bool copy_data;
103 : : bool refresh;
104 : : bool binary;
105 : : char streaming;
106 : : bool twophase;
107 : : bool disableonerr;
108 : : bool passwordrequired;
109 : : bool runasowner;
110 : : bool failover;
111 : : bool retaindeadtuples;
112 : : int32 maxretention;
113 : : char *origin;
114 : : ConflictLogDest conflictlogdest;
115 : : XLogRecPtr lsn;
116 : : char *wal_receiver_timeout;
117 : : } SubOpts;
118 : :
119 : : /*
120 : : * PublicationRelKind represents a relation included in a publication.
121 : : * It stores the schema-qualified relation name (rv) and its kind (relkind).
122 : : */
123 : : typedef struct PublicationRelKind
124 : : {
125 : : RangeVar *rv;
126 : : char relkind;
127 : : } PublicationRelKind;
128 : :
129 : : static List *fetch_relation_list(WalReceiverConn *wrconn, List *publications);
130 : : static void check_publications_origin_tables(WalReceiverConn *wrconn,
131 : : List *publications, bool copydata,
132 : : bool retain_dead_tuples,
133 : : char *origin,
134 : : Oid *subrel_local_oids,
135 : : int subrel_count, char *subname);
136 : : static void check_publications_origin_sequences(WalReceiverConn *wrconn,
137 : : List *publications,
138 : : bool copydata, char *origin,
139 : : Oid *subrel_local_oids,
140 : : int subrel_count,
141 : : char *subname);
142 : : static void check_pub_dead_tuple_retention(WalReceiverConn *wrconn);
143 : : static void check_duplicates_in_publist(List *publist, Datum *datums);
144 : : static List *merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname);
145 : : static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err);
146 : : static void CheckAlterSubOption(Subscription *sub, const char *option,
147 : : bool slot_needs_update, bool isTopLevel);
148 : : static bool alter_sub_conflict_log_dest(Subscription *sub,
149 : : ConflictLogDest oldlogdest,
150 : : ConflictLogDest newlogdest,
151 : : Oid *conflicttablerelid);
152 : : static void drop_sub_conflict_log_table(Oid subid, char *subname,
153 : : Oid subconflictlogrelid);
154 : :
155 : : /*
156 : : * Common option parsing function for CREATE and ALTER SUBSCRIPTION commands.
157 : : *
158 : : * Since not all options can be specified in both commands, this function
159 : : * will report an error if mutually exclusive options are specified.
160 : : */
161 : : static void
162 : 716 : parse_subscription_options(ParseState *pstate, List *stmt_options,
163 : : uint32 supported_opts, SubOpts *opts)
164 : : {
165 : : ListCell *lc;
166 : :
167 : : /* Start out with cleared opts. */
168 : 716 : memset(opts, 0, sizeof(SubOpts));
169 : :
170 : : /* caller must expect some option */
171 : : Assert(supported_opts != 0);
172 : :
173 : : /* If connect option is supported, these others also need to be. */
174 : : Assert(!IsSet(supported_opts, SUBOPT_CONNECT) ||
175 : : IsSet(supported_opts, SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
176 : : SUBOPT_COPY_DATA));
177 : :
178 : : /* Set default values for the supported options. */
179 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_CONNECT))
180 : 338 : opts->connect = true;
181 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_ENABLED))
182 : 417 : opts->enabled = true;
183 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
184 : 338 : opts->create_slot = true;
185 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_COPY_DATA))
186 : 429 : opts->copy_data = true;
187 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_REFRESH))
188 : 54 : opts->refresh = true;
189 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_BINARY))
190 : 531 : opts->binary = false;
191 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_STREAMING))
192 : 531 : opts->streaming = LOGICALREP_STREAM_PARALLEL;
193 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
194 : 531 : opts->twophase = false;
195 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
196 : 531 : opts->disableonerr = false;
197 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED))
198 : 531 : opts->passwordrequired = true;
199 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER))
200 : 531 : opts->runasowner = false;
201 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_FAILOVER))
202 : 531 : opts->failover = false;
203 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_RETAIN_DEAD_TUPLES))
204 : 531 : opts->retaindeadtuples = false;
205 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_MAX_RETENTION_DURATION))
206 : 531 : opts->maxretention = 0;
207 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_ORIGIN))
208 : 531 : opts->origin = pstrdup(LOGICALREP_ORIGIN_ANY);
209 [ + + ]: 716 : if (IsSet(supported_opts, SUBOPT_CONFLICT_LOG_DEST))
210 : 531 : opts->conflictlogdest = CONFLICT_LOG_DEST_LOG;
211 : :
212 : : /* Parse options */
213 [ + + + + : 1456 : foreach(lc, stmt_options)
+ + ]
214 : : {
215 : 804 : DefElem *defel = (DefElem *) lfirst(lc);
216 : :
217 [ + + ]: 804 : if (IsSet(supported_opts, SUBOPT_CONNECT) &&
218 [ + + ]: 466 : strcmp(defel->defname, "connect") == 0)
219 : : {
220 [ - + ]: 175 : if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
221 : 0 : errorConflictingDefElem(defel, pstate);
222 : :
223 : 175 : opts->specified_opts |= SUBOPT_CONNECT;
224 : 175 : opts->connect = defGetBoolean(defel);
225 : : }
226 [ + + ]: 629 : else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
227 [ + + ]: 370 : strcmp(defel->defname, "enabled") == 0)
228 : : {
229 [ - + ]: 103 : if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
230 : 0 : errorConflictingDefElem(defel, pstate);
231 : :
232 : 103 : opts->specified_opts |= SUBOPT_ENABLED;
233 : 103 : opts->enabled = defGetBoolean(defel);
234 : : }
235 [ + + ]: 526 : else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
236 [ + + ]: 267 : strcmp(defel->defname, "create_slot") == 0)
237 : : {
238 [ - + ]: 25 : if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
239 : 0 : errorConflictingDefElem(defel, pstate);
240 : :
241 : 25 : opts->specified_opts |= SUBOPT_CREATE_SLOT;
242 : 25 : opts->create_slot = defGetBoolean(defel);
243 : : }
244 [ + + ]: 501 : else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
245 [ + + ]: 437 : strcmp(defel->defname, "slot_name") == 0)
246 : : {
247 [ - + ]: 147 : if (IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
248 : 0 : errorConflictingDefElem(defel, pstate);
249 : :
250 : 147 : opts->specified_opts |= SUBOPT_SLOT_NAME;
251 : 147 : opts->slot_name = defGetString(defel);
252 : :
253 : : /* Setting slot_name = NONE is treated as no slot name. */
254 [ + + ]: 290 : if (strcmp(opts->slot_name, "none") == 0)
255 : 119 : opts->slot_name = NULL;
256 : : else
257 : 28 : ReplicationSlotValidateName(opts->slot_name, false, ERROR);
258 : : }
259 [ + + ]: 354 : else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
260 [ + + ]: 220 : strcmp(defel->defname, "copy_data") == 0)
261 : : {
262 [ - + ]: 31 : if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
263 : 0 : errorConflictingDefElem(defel, pstate);
264 : :
265 : 31 : opts->specified_opts |= SUBOPT_COPY_DATA;
266 : 31 : opts->copy_data = defGetBoolean(defel);
267 : : }
268 [ + + ]: 323 : else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
269 [ + + ]: 264 : strcmp(defel->defname, "synchronous_commit") == 0)
270 : : {
271 [ - + ]: 8 : if (IsSet(opts->specified_opts, SUBOPT_SYNCHRONOUS_COMMIT))
272 : 0 : errorConflictingDefElem(defel, pstate);
273 : :
274 : 8 : opts->specified_opts |= SUBOPT_SYNCHRONOUS_COMMIT;
275 : 8 : opts->synchronous_commit = defGetString(defel);
276 : :
277 : : /* Test if the given value is valid for synchronous_commit GUC. */
278 : 8 : (void) set_config_option("synchronous_commit", opts->synchronous_commit,
279 : : PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
280 : : false, 0, false);
281 : : }
282 [ + + ]: 315 : else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
283 [ + - ]: 44 : strcmp(defel->defname, "refresh") == 0)
284 : : {
285 [ - + ]: 44 : if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
286 : 0 : errorConflictingDefElem(defel, pstate);
287 : :
288 : 44 : opts->specified_opts |= SUBOPT_REFRESH;
289 : 44 : opts->refresh = defGetBoolean(defel);
290 : : }
291 [ + + ]: 271 : else if (IsSet(supported_opts, SUBOPT_BINARY) &&
292 [ + + ]: 256 : strcmp(defel->defname, "binary") == 0)
293 : : {
294 [ - + ]: 19 : if (IsSet(opts->specified_opts, SUBOPT_BINARY))
295 : 0 : errorConflictingDefElem(defel, pstate);
296 : :
297 : 19 : opts->specified_opts |= SUBOPT_BINARY;
298 : 19 : opts->binary = defGetBoolean(defel);
299 : : }
300 [ + + ]: 252 : else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
301 [ + + ]: 237 : strcmp(defel->defname, "streaming") == 0)
302 : : {
303 [ - + ]: 43 : if (IsSet(opts->specified_opts, SUBOPT_STREAMING))
304 : 0 : errorConflictingDefElem(defel, pstate);
305 : :
306 : 43 : opts->specified_opts |= SUBOPT_STREAMING;
307 : 43 : opts->streaming = defGetStreamingMode(defel);
308 : : }
309 [ + + ]: 209 : else if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT) &&
310 [ + + ]: 194 : strcmp(defel->defname, "two_phase") == 0)
311 : : {
312 [ - + ]: 24 : if (IsSet(opts->specified_opts, SUBOPT_TWOPHASE_COMMIT))
313 : 0 : errorConflictingDefElem(defel, pstate);
314 : :
315 : 24 : opts->specified_opts |= SUBOPT_TWOPHASE_COMMIT;
316 : 24 : opts->twophase = defGetBoolean(defel);
317 : : }
318 [ + + ]: 185 : else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
319 [ + + ]: 170 : strcmp(defel->defname, "disable_on_error") == 0)
320 : : {
321 [ - + ]: 13 : if (IsSet(opts->specified_opts, SUBOPT_DISABLE_ON_ERR))
322 : 0 : errorConflictingDefElem(defel, pstate);
323 : :
324 : 13 : opts->specified_opts |= SUBOPT_DISABLE_ON_ERR;
325 : 13 : opts->disableonerr = defGetBoolean(defel);
326 : : }
327 [ + + ]: 172 : else if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED) &&
328 [ + + ]: 157 : strcmp(defel->defname, "password_required") == 0)
329 : : {
330 [ - + ]: 16 : if (IsSet(opts->specified_opts, SUBOPT_PASSWORD_REQUIRED))
331 : 0 : errorConflictingDefElem(defel, pstate);
332 : :
333 : 16 : opts->specified_opts |= SUBOPT_PASSWORD_REQUIRED;
334 : 16 : opts->passwordrequired = defGetBoolean(defel);
335 : : }
336 [ + + ]: 156 : else if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER) &&
337 [ + + ]: 141 : strcmp(defel->defname, "run_as_owner") == 0)
338 : : {
339 [ - + ]: 11 : if (IsSet(opts->specified_opts, SUBOPT_RUN_AS_OWNER))
340 : 0 : errorConflictingDefElem(defel, pstate);
341 : :
342 : 11 : opts->specified_opts |= SUBOPT_RUN_AS_OWNER;
343 : 11 : opts->runasowner = defGetBoolean(defel);
344 : : }
345 [ + + ]: 145 : else if (IsSet(supported_opts, SUBOPT_FAILOVER) &&
346 [ + + ]: 130 : strcmp(defel->defname, "failover") == 0)
347 : : {
348 [ - + ]: 16 : if (IsSet(opts->specified_opts, SUBOPT_FAILOVER))
349 : 0 : errorConflictingDefElem(defel, pstate);
350 : :
351 : 16 : opts->specified_opts |= SUBOPT_FAILOVER;
352 : 16 : opts->failover = defGetBoolean(defel);
353 : : }
354 [ + + ]: 129 : else if (IsSet(supported_opts, SUBOPT_RETAIN_DEAD_TUPLES) &&
355 [ + + ]: 114 : strcmp(defel->defname, "retain_dead_tuples") == 0)
356 : : {
357 [ - + ]: 14 : if (IsSet(opts->specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
358 : 0 : errorConflictingDefElem(defel, pstate);
359 : :
360 : 14 : opts->specified_opts |= SUBOPT_RETAIN_DEAD_TUPLES;
361 : 14 : opts->retaindeadtuples = defGetBoolean(defel);
362 : : }
363 [ + + ]: 115 : else if (IsSet(supported_opts, SUBOPT_MAX_RETENTION_DURATION) &&
364 [ + + ]: 100 : strcmp(defel->defname, "max_retention_duration") == 0)
365 : : {
366 [ - + ]: 22 : if (IsSet(opts->specified_opts, SUBOPT_MAX_RETENTION_DURATION))
367 : 0 : errorConflictingDefElem(defel, pstate);
368 : :
369 : 22 : opts->specified_opts |= SUBOPT_MAX_RETENTION_DURATION;
370 : 22 : opts->maxretention = defGetInt32(defel);
371 : :
372 [ + + ]: 18 : if (opts->maxretention < 0)
373 [ + - ]: 8 : ereport(ERROR,
374 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
375 : : errmsg("max_retention_duration cannot be negative"));
376 : : }
377 [ + + ]: 93 : else if (IsSet(supported_opts, SUBOPT_ORIGIN) &&
378 [ + + ]: 78 : strcmp(defel->defname, "origin") == 0)
379 : : {
380 [ - + ]: 24 : if (IsSet(opts->specified_opts, SUBOPT_ORIGIN))
381 : 0 : errorConflictingDefElem(defel, pstate);
382 : :
383 : 24 : opts->specified_opts |= SUBOPT_ORIGIN;
384 : 24 : pfree(opts->origin);
385 : :
386 : : /*
387 : : * Even though the "origin" parameter allows only "none" and "any"
388 : : * values, it is implemented as a string type so that the
389 : : * parameter can be extended in future versions to support
390 : : * filtering using origin names specified by the user.
391 : : */
392 : 24 : opts->origin = defGetString(defel);
393 : :
394 [ + + + + ]: 34 : if ((pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_NONE) != 0) &&
395 : 10 : (pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_ANY) != 0))
396 [ + - ]: 4 : ereport(ERROR,
397 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
398 : : errmsg("unrecognized origin value: \"%s\"", opts->origin));
399 : : }
400 [ + + ]: 69 : else if (IsSet(supported_opts, SUBOPT_LSN) &&
401 [ + - ]: 15 : strcmp(defel->defname, "lsn") == 0)
402 : 11 : {
403 : 15 : char *lsn_str = defGetString(defel);
404 : : XLogRecPtr lsn;
405 : :
406 [ - + ]: 15 : if (IsSet(opts->specified_opts, SUBOPT_LSN))
407 : 0 : errorConflictingDefElem(defel, pstate);
408 : :
409 : : /* Setting lsn = NONE is treated as resetting LSN */
410 [ + + ]: 15 : if (strcmp(lsn_str, "none") == 0)
411 : 4 : lsn = InvalidXLogRecPtr;
412 : : else
413 : : {
414 : : /* Parse the argument as LSN */
415 : 11 : lsn = DatumGetLSN(DirectFunctionCall1(pg_lsn_in,
416 : : CStringGetDatum(lsn_str)));
417 : :
418 [ + + ]: 11 : if (!XLogRecPtrIsValid(lsn))
419 [ + - ]: 4 : ereport(ERROR,
420 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
421 : : errmsg("invalid WAL location (LSN): %s", lsn_str)));
422 : : }
423 : :
424 : 11 : opts->specified_opts |= SUBOPT_LSN;
425 : 11 : opts->lsn = lsn;
426 : : }
427 [ + - ]: 54 : else if (IsSet(supported_opts, SUBOPT_WAL_RECEIVER_TIMEOUT) &&
428 [ + + ]: 54 : strcmp(defel->defname, "wal_receiver_timeout") == 0)
429 : 8 : {
430 : : bool parsed;
431 : : int val;
432 : :
433 [ - + ]: 12 : if (IsSet(opts->specified_opts, SUBOPT_WAL_RECEIVER_TIMEOUT))
434 : 0 : errorConflictingDefElem(defel, pstate);
435 : :
436 : 12 : opts->specified_opts |= SUBOPT_WAL_RECEIVER_TIMEOUT;
437 : 12 : opts->wal_receiver_timeout = defGetString(defel);
438 : :
439 : : /*
440 : : * Test if the given value is valid for wal_receiver_timeout GUC.
441 : : * Skip this test if the value is -1, since -1 is allowed for the
442 : : * wal_receiver_timeout subscription option, but not for the GUC
443 : : * itself.
444 : : */
445 : 12 : parsed = parse_int(opts->wal_receiver_timeout, &val, 0, NULL);
446 [ + + - + ]: 12 : if (!parsed || val != -1)
447 : 8 : (void) set_config_option("wal_receiver_timeout", opts->wal_receiver_timeout,
448 : : PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
449 : : false, 0, false);
450 : : }
451 [ + - ]: 42 : else if (IsSet(supported_opts, SUBOPT_CONFLICT_LOG_DEST) &&
452 [ + + ]: 42 : strcmp(defel->defname, "conflict_log_destination") == 0)
453 : 30 : {
454 : : char *val;
455 : :
456 [ - + ]: 38 : if (IsSet(opts->specified_opts, SUBOPT_CONFLICT_LOG_DEST))
457 : 0 : errorConflictingDefElem(defel, pstate);
458 : :
459 : 38 : val = defGetString(defel);
460 : 38 : opts->conflictlogdest = GetConflictLogDest(val);
461 : 30 : opts->specified_opts |= SUBOPT_CONFLICT_LOG_DEST;
462 : : }
463 : : else
464 [ + - ]: 4 : ereport(ERROR,
465 : : (errcode(ERRCODE_SYNTAX_ERROR),
466 : : errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
467 : : }
468 : :
469 : : /*
470 : : * We've been explicitly asked to not connect, that requires some
471 : : * additional processing.
472 : : */
473 [ + + + + ]: 652 : if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
474 : : {
475 : : /* Check for incompatible options from the user. */
476 [ + - ]: 135 : if (opts->enabled &&
477 [ + + ]: 135 : IsSet(opts->specified_opts, SUBOPT_ENABLED))
478 [ + - ]: 4 : ereport(ERROR,
479 : : (errcode(ERRCODE_SYNTAX_ERROR),
480 : : /*- translator: both %s are strings of the form "option = value" */
481 : : errmsg("%s and %s are mutually exclusive options",
482 : : "connect = false", "enabled = true")));
483 : :
484 [ + + ]: 131 : if (opts->create_slot &&
485 [ + + ]: 127 : IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
486 [ + - ]: 4 : ereport(ERROR,
487 : : (errcode(ERRCODE_SYNTAX_ERROR),
488 : : errmsg("%s and %s are mutually exclusive options",
489 : : "connect = false", "create_slot = true")));
490 : :
491 [ + + ]: 127 : if (opts->copy_data &&
492 [ + + ]: 123 : IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
493 [ + - ]: 4 : ereport(ERROR,
494 : : (errcode(ERRCODE_SYNTAX_ERROR),
495 : : errmsg("%s and %s are mutually exclusive options",
496 : : "connect = false", "copy_data = true")));
497 : :
498 : : /* Change the defaults of other options. */
499 : 123 : opts->enabled = false;
500 : 123 : opts->create_slot = false;
501 : 123 : opts->copy_data = false;
502 : : }
503 : :
504 : : /*
505 : : * Do additional checking for disallowed combination when slot_name = NONE
506 : : * was used.
507 : : */
508 [ + + ]: 640 : if (!opts->slot_name &&
509 [ + + ]: 616 : IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
510 : : {
511 [ + + ]: 115 : if (opts->enabled)
512 : : {
513 [ + + ]: 12 : if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
514 [ + - ]: 4 : ereport(ERROR,
515 : : (errcode(ERRCODE_SYNTAX_ERROR),
516 : : /*- translator: both %s are strings of the form "option = value" */
517 : : errmsg("%s and %s are mutually exclusive options",
518 : : "slot_name = NONE", "enabled = true")));
519 : : else
520 [ + - ]: 8 : ereport(ERROR,
521 : : (errcode(ERRCODE_SYNTAX_ERROR),
522 : : /*- translator: both %s are strings of the form "option = value" */
523 : : errmsg("subscription with %s must also set %s",
524 : : "slot_name = NONE", "enabled = false")));
525 : : }
526 : :
527 [ + + ]: 103 : if (opts->create_slot)
528 : : {
529 [ + + ]: 8 : if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
530 [ + - ]: 4 : ereport(ERROR,
531 : : (errcode(ERRCODE_SYNTAX_ERROR),
532 : : /*- translator: both %s are strings of the form "option = value" */
533 : : errmsg("%s and %s are mutually exclusive options",
534 : : "slot_name = NONE", "create_slot = true")));
535 : : else
536 [ + - ]: 4 : ereport(ERROR,
537 : : (errcode(ERRCODE_SYNTAX_ERROR),
538 : : /*- translator: both %s are strings of the form "option = value" */
539 : : errmsg("subscription with %s must also set %s",
540 : : "slot_name = NONE", "create_slot = false")));
541 : : }
542 : : }
543 : 620 : }
544 : :
545 : : /*
546 : : * Append a suitably-quoted identifier or string literal to buf.
547 : : * "quote" should be either a double-quote or single-quote character.
548 : : *
549 : : * Caution: this quoting logic is sufficient for identifiers and literals
550 : : * in the replication grammar, but not always in regular SQL. Specifically,
551 : : * it'd fail for a string literal if standard_conforming_strings is off.
552 : : */
553 : : static void
554 : 292 : appendQuotedString(StringInfo buf, const char *str, char quote)
555 : : {
556 : 292 : appendStringInfoChar(buf, quote);
557 [ + + ]: 9312 : while (*str)
558 : : {
559 : 9020 : char c = *str++;
560 : :
561 [ - + ]: 9020 : if (c == quote)
562 : 0 : appendStringInfoChar(buf, c);
563 : 9020 : appendStringInfoChar(buf, c);
564 : : }
565 : 292 : appendStringInfoChar(buf, quote);
566 : 292 : }
567 : :
568 : : #define appendQuotedIdentifier(b, s) appendQuotedString(b, s, '"')
569 : : #define appendQuotedLiteral(b, s) appendQuotedString(b, s, '\'')
570 : :
571 : : /*
572 : : * Check that the specified publications are present on the publisher.
573 : : */
574 : : static void
575 : 135 : check_publications(WalReceiverConn *wrconn, List *publications)
576 : : {
577 : : WalRcvExecResult *res;
578 : : StringInfoData cmd;
579 : : TupleTableSlot *slot;
580 : 135 : List *publicationsCopy = NIL;
581 : 135 : Oid tableRow[1] = {TEXTOID};
582 : :
583 : 135 : initStringInfo(&cmd);
584 : 135 : appendStringInfoString(&cmd, "SELECT t.pubname FROM\n"
585 : : " pg_catalog.pg_publication t WHERE\n"
586 : : " t.pubname IN (");
587 : 135 : GetPublicationsStr(publications, &cmd, true);
588 : 135 : appendStringInfoChar(&cmd, ')');
589 : :
590 : 135 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
591 : 135 : pfree(cmd.data);
592 : :
593 [ - + ]: 135 : if (res->status != WALRCV_OK_TUPLES)
594 [ # # ]: 0 : ereport(ERROR,
595 : : errmsg("could not receive list of publications from the publisher: %s",
596 : : res->err));
597 : :
598 : 135 : publicationsCopy = list_copy(publications);
599 : :
600 : : /* Process publication(s). */
601 : 135 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
602 [ + + ]: 299 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
603 : : {
604 : : char *pubname;
605 : : bool isnull;
606 : :
607 : 164 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
608 : : Assert(!isnull);
609 : :
610 : : /* Delete the publication present in publisher from the list. */
611 : 164 : publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
612 : 164 : ExecClearTuple(slot);
613 : : }
614 : :
615 : 135 : ExecDropSingleTupleTableSlot(slot);
616 : :
617 : 135 : walrcv_clear_result(res);
618 : :
619 [ + + ]: 135 : if (list_length(publicationsCopy))
620 : : {
621 : : /* Prepare the list of non-existent publication(s) for error message. */
622 : : StringInfoData pubnames;
623 : :
624 : 4 : initStringInfo(&pubnames);
625 : :
626 : 4 : GetPublicationsStr(publicationsCopy, &pubnames, false);
627 [ + - ]: 4 : ereport(WARNING,
628 : : errcode(ERRCODE_UNDEFINED_OBJECT),
629 : : errmsg_plural("publication %s does not exist on the publisher",
630 : : "publications %s do not exist on the publisher",
631 : : list_length(publicationsCopy),
632 : : pubnames.data));
633 : : }
634 : 135 : }
635 : :
636 : : /*
637 : : * Auxiliary function to build a text array out of a list of String nodes.
638 : : */
639 : : static Datum
640 : 251 : publicationListToArray(List *publist)
641 : : {
642 : : ArrayType *arr;
643 : : Datum *datums;
644 : : MemoryContext memcxt;
645 : : MemoryContext oldcxt;
646 : :
647 : : /* Create memory context for temporary allocations. */
648 : 251 : memcxt = AllocSetContextCreate(CurrentMemoryContext,
649 : : "publicationListToArray to array",
650 : : ALLOCSET_DEFAULT_SIZES);
651 : 251 : oldcxt = MemoryContextSwitchTo(memcxt);
652 : :
653 : 251 : datums = palloc_array(Datum, list_length(publist));
654 : :
655 : 251 : check_duplicates_in_publist(publist, datums);
656 : :
657 : 247 : MemoryContextSwitchTo(oldcxt);
658 : :
659 : 247 : arr = construct_array_builtin(datums, list_length(publist), TEXTOID);
660 : :
661 : 247 : MemoryContextDelete(memcxt);
662 : :
663 : 247 : return PointerGetDatum(arr);
664 : : }
665 : :
666 : : /*
667 : : * Create new subscription.
668 : : */
669 : : ObjectAddress
670 : 338 : CreateSubscription(ParseState *pstate, CreateSubscriptionStmt *stmt,
671 : : bool isTopLevel)
672 : : {
673 : : Relation rel;
674 : : ObjectAddress myself;
675 : : Oid subid;
676 : : bool nulls[Natts_pg_subscription];
677 : : Datum values[Natts_pg_subscription];
678 : 338 : Oid owner = GetUserId();
679 : : HeapTuple tup;
680 : : Oid serverid;
681 : : char *conninfo;
682 : : char originname[NAMEDATALEN];
683 : : List *publications;
684 : : uint32 supported_opts;
685 : 338 : SubOpts opts = {0};
686 : : AclResult aclresult;
687 : 338 : Oid logrelid = InvalidOid;
688 : :
689 : : /*
690 : : * Parse and check options.
691 : : *
692 : : * Connection and publication should not be specified here.
693 : : */
694 : 338 : supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
695 : : SUBOPT_SLOT_NAME | SUBOPT_COPY_DATA |
696 : : SUBOPT_SYNCHRONOUS_COMMIT | SUBOPT_BINARY |
697 : : SUBOPT_STREAMING | SUBOPT_TWOPHASE_COMMIT |
698 : : SUBOPT_DISABLE_ON_ERR | SUBOPT_PASSWORD_REQUIRED |
699 : : SUBOPT_RUN_AS_OWNER | SUBOPT_FAILOVER |
700 : : SUBOPT_RETAIN_DEAD_TUPLES |
701 : : SUBOPT_MAX_RETENTION_DURATION |
702 : : SUBOPT_WAL_RECEIVER_TIMEOUT | SUBOPT_ORIGIN |
703 : : SUBOPT_CONFLICT_LOG_DEST);
704 : 338 : parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
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 [ + + ]: 266 : if (opts.create_slot)
713 : 138 : 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 : : */
720 [ + + ]: 262 : if (!has_privs_of_role(owner, ROLE_PG_CREATE_SUBSCRIPTION))
721 [ + - ]: 4 : ereport(ERROR,
722 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
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 : : */
731 : 258 : aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
732 : : owner, ACL_CREATE);
733 [ + + ]: 258 : if (aclresult != ACLCHECK_OK)
734 : 8 : aclcheck_error(aclresult, OBJECT_DATABASE,
735 : 4 : get_database_name(MyDatabaseId));
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 [ + + + + ]: 254 : if (!opts.passwordrequired && !superuser_arg(owner))
743 [ + - ]: 4 : ereport(ERROR,
744 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
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 : :
757 : 250 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
758 : :
759 : : /* Check if name is used */
760 : 250 : subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
761 : : ObjectIdGetDatum(MyDatabaseId), CStringGetDatum(stmt->subname));
762 [ + + ]: 250 : if (OidIsValid(subid))
763 : : {
764 [ + - ]: 5 : ereport(ERROR,
765 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
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 : : */
774 : 245 : CheckSubDeadTupleRetention(true, !opts.enabled, WARNING,
775 : 245 : opts.retaindeadtuples, opts.retaindeadtuples,
776 : 245 : (opts.maxretention > 0));
777 : :
778 [ + + ]: 245 : if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
779 [ + - ]: 198 : opts.slot_name == NULL)
780 : 198 : opts.slot_name = stmt->subname;
781 : :
782 : : /* The default for synchronous_commit of subscriptions is off. */
783 [ + - ]: 245 : if (opts.synchronous_commit == NULL)
784 : 245 : 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 [ + - ]: 245 : if (opts.wal_receiver_timeout == NULL)
792 : 245 : opts.wal_receiver_timeout = "-1";
793 : :
794 : : /* Load the library providing us libpq calls. */
795 : 245 : load_file("libpqwalreceiver", false);
796 : :
797 [ + + ]: 245 : if (stmt->servername)
798 : : {
799 : : ForeignServer *server;
800 : :
801 : : Assert(!stmt->conninfo);
802 : 23 : conninfo = NULL;
803 : :
804 : 23 : server = GetForeignServerByName(stmt->servername, false);
805 : 23 : aclresult = object_aclcheck(ForeignServerRelationId, server->serverid, owner, ACL_USAGE);
806 [ + + ]: 23 : if (aclresult != ACLCHECK_OK)
807 : 4 : aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, server->servername);
808 : :
809 : : /* make sure a user mapping exists */
810 : 19 : GetUserMapping(owner, server->serverid);
811 : :
812 : 15 : serverid = server->serverid;
813 : 15 : conninfo = ForeignServerConnectionString(owner, server);
814 : : }
815 : : else
816 : : {
817 : : Assert(stmt->conninfo);
818 : :
819 : 222 : serverid = InvalidOid;
820 : 222 : conninfo = stmt->conninfo;
821 : : }
822 : :
823 : : /* Check the connection info string. */
824 [ + + + + ]: 233 : walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
825 : :
826 : 221 : publications = stmt->publication;
827 : :
828 : : /* Everything ok, form a new tuple. */
829 : 221 : memset(values, 0, sizeof(values));
830 : 221 : memset(nulls, false, sizeof(nulls));
831 : :
832 : 221 : subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
833 : : Anum_pg_subscription_oid);
834 : 221 : values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
835 : 221 : values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
836 : 221 : values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
837 : 221 : values[Anum_pg_subscription_subname - 1] =
838 : 221 : DirectFunctionCall1(namein, CStringGetDatum(stmt->subname));
839 : 221 : values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
840 : 221 : values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
841 : 221 : values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
842 : 221 : values[Anum_pg_subscription_substream - 1] = CharGetDatum(opts.streaming);
843 : 221 : values[Anum_pg_subscription_subtwophasestate - 1] =
844 [ + + ]: 221 : CharGetDatum(opts.twophase ?
845 : : LOGICALREP_TWOPHASE_STATE_PENDING :
846 : : LOGICALREP_TWOPHASE_STATE_DISABLED);
847 : 221 : values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
848 : 221 : values[Anum_pg_subscription_subpasswordrequired - 1] = BoolGetDatum(opts.passwordrequired);
849 : 221 : values[Anum_pg_subscription_subrunasowner - 1] = BoolGetDatum(opts.runasowner);
850 : 221 : values[Anum_pg_subscription_subfailover - 1] = BoolGetDatum(opts.failover);
851 : 221 : values[Anum_pg_subscription_subretaindeadtuples - 1] =
852 : 221 : BoolGetDatum(opts.retaindeadtuples);
853 : 221 : values[Anum_pg_subscription_submaxretention - 1] =
854 : 221 : Int32GetDatum(opts.maxretention);
855 : 221 : values[Anum_pg_subscription_subretentionactive - 1] =
856 : 221 : BoolGetDatum(opts.retaindeadtuples);
857 : 221 : values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(serverid);
858 [ + + ]: 221 : if (!OidIsValid(serverid))
859 : 210 : values[Anum_pg_subscription_subconninfo - 1] =
860 : 210 : CStringGetTextDatum(conninfo);
861 : : else
862 : 11 : nulls[Anum_pg_subscription_subconninfo - 1] = true;
863 [ + + ]: 221 : if (opts.slot_name)
864 : 206 : values[Anum_pg_subscription_subslotname - 1] =
865 : 206 : DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
866 : : else
867 : 15 : nulls[Anum_pg_subscription_subslotname - 1] = true;
868 : 221 : values[Anum_pg_subscription_subsynccommit - 1] =
869 : 221 : CStringGetTextDatum(opts.synchronous_commit);
870 : 221 : values[Anum_pg_subscription_subwalrcvtimeout - 1] =
871 : 221 : CStringGetTextDatum(opts.wal_receiver_timeout);
872 : 217 : values[Anum_pg_subscription_subpublications - 1] =
873 : 221 : publicationListToArray(publications);
874 : 217 : values[Anum_pg_subscription_suborigin - 1] =
875 : 217 : CStringGetTextDatum(opts.origin);
876 : :
877 : 217 : values[Anum_pg_subscription_subconflictlogdest - 1] =
878 : 217 : CStringGetTextDatum(ConflictLogDestNames[opts.conflictlogdest]);
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 [ + + + + ]: 217 : if (CONFLICTS_LOGGED_TO_TABLE(opts.conflictlogdest))
886 : 10 : logrelid = create_conflict_log_table(subid, stmt->subname, owner);
887 : :
888 : : /* Store table OID in the catalog. */
889 : 217 : values[Anum_pg_subscription_subconflictlogrelid - 1] =
890 : 217 : ObjectIdGetDatum(logrelid);
891 : :
892 : 217 : tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
893 : :
894 : : /* Insert tuple into catalog. */
895 : 217 : CatalogTupleInsert(rel, tup);
896 : 217 : heap_freetuple(tup);
897 : :
898 : 217 : recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
899 : :
900 : 217 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
901 : :
902 [ + + ]: 217 : if (stmt->servername)
903 : : {
904 : : ObjectAddress referenced;
905 : :
906 : : Assert(OidIsValid(serverid));
907 : :
908 : 11 : ObjectAddressSet(referenced, ForeignServerRelationId, serverid);
909 : 11 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
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 [ + + ]: 217 : if (OidIsValid(logrelid))
924 : : {
925 : : ObjectAddress cltaddr;
926 : :
927 : 10 : ObjectAddressSet(cltaddr, RelationRelationId, logrelid);
928 : 10 : recordDependencyOn(&cltaddr, &myself, DEPENDENCY_INTERNAL);
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 : : */
941 : 217 : ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
942 : 217 : replorigin_create(originname);
943 : :
944 : : /*
945 : : * Connect to remote side to execute requested commands and fetch table
946 : : * and sequence info.
947 : : */
948 [ + + ]: 217 : if (opts.connect)
949 : : {
950 : : char *err;
951 : : WalReceiverConn *wrconn;
952 : : bool must_use_password;
953 : :
954 : : /* Try to connect to the publisher. */
955 [ - + - - ]: 130 : must_use_password = !superuser_arg(owner) && opts.passwordrequired;
956 : 130 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
957 : : stmt->subname, &err);
958 [ + + ]: 130 : if (!wrconn)
959 [ + - ]: 4 : ereport(ERROR,
960 : : (errcode(ERRCODE_CONNECTION_FAILURE),
961 : : errmsg("subscription \"%s\" could not connect to the publisher: %s",
962 : : stmt->subname, err)));
963 : :
964 [ + + ]: 126 : PG_TRY();
965 : : {
966 : 126 : bool has_tables = false;
967 : : List *pubrels;
968 : : char relation_state;
969 : :
970 : 126 : check_publications(wrconn, publications);
971 : 126 : check_publications_origin_tables(wrconn, publications,
972 : 126 : opts.copy_data,
973 : 126 : opts.retaindeadtuples, opts.origin,
974 : : NULL, 0, stmt->subname);
975 : 126 : check_publications_origin_sequences(wrconn, publications,
976 : 126 : opts.copy_data, opts.origin,
977 : : NULL, 0, stmt->subname);
978 : :
979 [ + + ]: 126 : if (opts.retaindeadtuples)
980 : 3 : check_pub_dead_tuple_retention(wrconn);
981 : :
982 : : /*
983 : : * Set sync state based on if we were asked to do data copy or
984 : : * not.
985 : : */
986 [ + + ]: 126 : relation_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
987 : :
988 : : /*
989 : : * Build local relation status info. Relations are for both tables
990 : : * and sequences from the publisher.
991 : : */
992 : 126 : pubrels = fetch_relation_list(wrconn, publications);
993 : :
994 [ + + + + : 445 : foreach_ptr(PublicationRelKind, pubrelinfo, pubrels)
+ + ]
995 : : {
996 : : Oid relid;
997 : : char relkind;
998 : 195 : RangeVar *rv = pubrelinfo->rv;
999 : :
1000 : 195 : relid = RangeVarGetRelid(rv, AccessShareLock, false);
1001 : 195 : relkind = get_rel_relkind(relid);
1002 : :
1003 : : /* Check for supported relkind. */
1004 : 195 : CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
1005 : 195 : rv->schemaname, rv->relname);
1006 : 195 : has_tables |= (relkind != RELKIND_SEQUENCE);
1007 : 195 : AddSubscriptionRelState(subid, relid, relation_state,
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 [ + + ]: 125 : if (opts.create_slot)
1021 : : {
1022 : 120 : 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 [ + + + + : 120 : if (opts.twophase && !opts.copy_data && has_tables)
+ - ]
1043 : 1 : twophase_enabled = true;
1044 : :
1045 : 120 : walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
1046 : : opts.failover, CRS_NOEXPORT_SNAPSHOT, NULL);
1047 : :
1048 [ + + ]: 120 : if (twophase_enabled)
1049 : 1 : UpdateTwoPhaseState(subid, LOGICALREP_TWOPHASE_STATE_ENABLED);
1050 : :
1051 [ + - ]: 120 : ereport(NOTICE,
1052 : : (errmsg("created replication slot \"%s\" on publisher",
1053 : : opts.slot_name)));
1054 : : }
1055 : : }
1056 : 1 : PG_FINALLY();
1057 : : {
1058 : 126 : walrcv_disconnect(wrconn);
1059 : : }
1060 [ + + ]: 126 : PG_END_TRY();
1061 : : }
1062 : : else
1063 [ + - ]: 87 : ereport(WARNING,
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 : :
1067 : 212 : table_close(rel, RowExclusiveLock);
1068 : :
1069 : 212 : pgstat_create_subscription(subid);
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 [ + + + + ]: 212 : if (opts.enabled || opts.retaindeadtuples)
1082 : 119 : ApplyLauncherWakeupAtCommit();
1083 : :
1084 [ - + ]: 212 : InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
1085 : :
1086 : 212 : return myself;
1087 : : }
1088 : :
1089 : : static void
1090 : 39 : AlterSubscription_refresh(Subscription *sub, bool copy_data,
1091 : : List *validate_publications)
1092 : : {
1093 : : char *err;
1094 : 39 : List *pubrels = NIL;
1095 : : Oid *pubrel_local_oids;
1096 : : List *subrel_states;
1097 : 39 : List *sub_remove_rels = NIL;
1098 : : Oid *subrel_local_oids;
1099 : : Oid *subseq_local_oids;
1100 : : int subrel_count;
1101 : : ListCell *lc;
1102 : : int off;
1103 : 39 : int tbl_count = 0;
1104 : 39 : int seq_count = 0;
1105 : 39 : Relation rel = NULL;
1106 : : typedef struct SubRemoveRels
1107 : : {
1108 : : Oid relid;
1109 : : char state;
1110 : : } SubRemoveRels;
1111 : :
1112 : : WalReceiverConn *wrconn;
1113 : : bool must_use_password;
1114 : :
1115 : : /* Load the library providing us libpq calls. */
1116 : 39 : load_file("libpqwalreceiver", false);
1117 : :
1118 : : /* Try to connect to the publisher. */
1119 [ + - + + ]: 39 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
1120 : 39 : wrconn = walrcv_connect(sub->conninfo, true, true, must_use_password,
1121 : : sub->name, &err);
1122 [ - + ]: 38 : if (!wrconn)
1123 [ # # ]: 0 : ereport(ERROR,
1124 : : (errcode(ERRCODE_CONNECTION_FAILURE),
1125 : : errmsg("subscription \"%s\" could not connect to the publisher: %s",
1126 : : sub->name, err)));
1127 : :
1128 [ + - ]: 38 : PG_TRY();
1129 : : {
1130 [ + + ]: 38 : if (validate_publications)
1131 : 9 : check_publications(wrconn, validate_publications);
1132 : :
1133 : : /* Get the relation list from publisher. */
1134 : 38 : pubrels = fetch_relation_list(wrconn, sub->publications);
1135 : :
1136 : : /* Get local relation list. */
1137 : 38 : subrel_states = GetSubscriptionRelations(sub->oid, true, true, false);
1138 : 38 : subrel_count = list_length(subrel_states);
1139 : :
1140 : : /*
1141 : : * Build qsorted arrays of local table oids and sequence oids for
1142 : : * faster lookup. This can potentially contain all tables and
1143 : : * sequences in the database so speed of lookup is important.
1144 : : *
1145 : : * We do not yet know the exact count of tables and sequences, so we
1146 : : * allocate separate arrays for table OIDs and sequence OIDs based on
1147 : : * the total number of relations (subrel_count).
1148 : : */
1149 : 38 : subrel_local_oids = palloc(subrel_count * sizeof(Oid));
1150 : 38 : subseq_local_oids = palloc(subrel_count * sizeof(Oid));
1151 [ + + + + : 136 : foreach(lc, subrel_states)
+ + ]
1152 : : {
1153 : 98 : SubscriptionRelState *relstate = (SubscriptionRelState *) lfirst(lc);
1154 : :
1155 [ + + ]: 98 : if (get_rel_relkind(relstate->relid) == RELKIND_SEQUENCE)
1156 : 9 : subseq_local_oids[seq_count++] = relstate->relid;
1157 : : else
1158 : 89 : subrel_local_oids[tbl_count++] = relstate->relid;
1159 : : }
1160 : :
1161 : 38 : qsort(subrel_local_oids, tbl_count, sizeof(Oid), oid_cmp);
1162 : 38 : check_publications_origin_tables(wrconn, sub->publications, copy_data,
1163 : 38 : sub->retaindeadtuples, sub->origin,
1164 : : subrel_local_oids, tbl_count,
1165 : : sub->name);
1166 : :
1167 : 38 : qsort(subseq_local_oids, seq_count, sizeof(Oid), oid_cmp);
1168 : 38 : check_publications_origin_sequences(wrconn, sub->publications,
1169 : : copy_data, sub->origin,
1170 : : subseq_local_oids, seq_count,
1171 : : sub->name);
1172 : :
1173 : : /*
1174 : : * Walk over the remote relations and try to match them to locally
1175 : : * known relations. If the relation is not known locally create a new
1176 : : * state for it.
1177 : : *
1178 : : * Also builds array of local oids of remote relations for the next
1179 : : * step.
1180 : : */
1181 : 38 : off = 0;
1182 : 38 : pubrel_local_oids = palloc(list_length(pubrels) * sizeof(Oid));
1183 : :
1184 [ + + + + : 183 : foreach_ptr(PublicationRelKind, pubrelinfo, pubrels)
+ + ]
1185 : : {
1186 : 107 : RangeVar *rv = pubrelinfo->rv;
1187 : : Oid relid;
1188 : : char relkind;
1189 : :
1190 : 107 : relid = RangeVarGetRelid(rv, AccessShareLock, false);
1191 : 107 : relkind = get_rel_relkind(relid);
1192 : :
1193 : : /* Check for supported relkind. */
1194 : 107 : CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
1195 : 107 : rv->schemaname, rv->relname);
1196 : :
1197 : 107 : pubrel_local_oids[off++] = relid;
1198 : :
1199 [ + + ]: 107 : if (!bsearch(&relid, subrel_local_oids,
1200 : 39 : tbl_count, sizeof(Oid), oid_cmp) &&
1201 [ + + ]: 39 : !bsearch(&relid, subseq_local_oids,
1202 : : seq_count, sizeof(Oid), oid_cmp))
1203 : : {
1204 [ + + ]: 30 : AddSubscriptionRelState(sub->oid, relid,
1205 : : copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
1206 : : InvalidXLogRecPtr, true);
1207 [ + + - + ]: 30 : ereport(DEBUG1,
1208 : : errmsg_internal("%s \"%s.%s\" added to subscription \"%s\"",
1209 : : relkind == RELKIND_SEQUENCE ? "sequence" : "table",
1210 : : rv->schemaname, rv->relname, sub->name));
1211 : : }
1212 : : }
1213 : :
1214 : : /*
1215 : : * Next remove state for tables we should not care about anymore using
1216 : : * the data we collected above
1217 : : */
1218 : 38 : qsort(pubrel_local_oids, list_length(pubrels), sizeof(Oid), oid_cmp);
1219 : :
1220 [ + + ]: 127 : for (off = 0; off < tbl_count; off++)
1221 : : {
1222 : 89 : Oid relid = subrel_local_oids[off];
1223 : :
1224 [ + + ]: 89 : if (!bsearch(&relid, pubrel_local_oids,
1225 : 89 : list_length(pubrels), sizeof(Oid), oid_cmp))
1226 : : {
1227 : : char state;
1228 : : XLogRecPtr statelsn;
1229 : 21 : SubRemoveRels *remove_rel = palloc_object(SubRemoveRels);
1230 : :
1231 : : /*
1232 : : * Lock pg_subscription_rel with AccessExclusiveLock to
1233 : : * prevent any race conditions with the apply worker
1234 : : * re-launching workers at the same time this code is trying
1235 : : * to remove those tables.
1236 : : *
1237 : : * Even if new worker for this particular rel is restarted it
1238 : : * won't be able to make any progress as we hold exclusive
1239 : : * lock on pg_subscription_rel till the transaction end. It
1240 : : * will simply exit as there is no corresponding rel entry.
1241 : : *
1242 : : * This locking also ensures that the state of rels won't
1243 : : * change till we are done with this refresh operation.
1244 : : */
1245 [ + + ]: 21 : if (!rel)
1246 : 9 : rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
1247 : :
1248 : : /* Last known rel state. */
1249 : 21 : state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
1250 : :
1251 : 21 : RemoveSubscriptionRel(sub->oid, relid);
1252 : :
1253 : 21 : remove_rel->relid = relid;
1254 : 21 : remove_rel->state = state;
1255 : :
1256 : 21 : sub_remove_rels = lappend(sub_remove_rels, remove_rel);
1257 : :
1258 : 21 : logicalrep_worker_stop(WORKERTYPE_TABLESYNC, sub->oid, relid);
1259 : :
1260 : : /*
1261 : : * For READY state, we would have already dropped the
1262 : : * tablesync origin.
1263 : : */
1264 [ - + ]: 21 : if (state != SUBREL_STATE_READY)
1265 : : {
1266 : : char originname[NAMEDATALEN];
1267 : :
1268 : : /*
1269 : : * Drop the tablesync's origin tracking if exists.
1270 : : *
1271 : : * It is possible that the origin is not yet created for
1272 : : * tablesync worker, this can happen for the states before
1273 : : * SUBREL_STATE_DATASYNC. The tablesync worker or apply
1274 : : * worker can also concurrently try to drop the origin and
1275 : : * by this time the origin might be already removed. For
1276 : : * these reasons, passing missing_ok = true.
1277 : : */
1278 : 0 : ReplicationOriginNameForLogicalRep(sub->oid, relid, originname,
1279 : : sizeof(originname));
1280 : 0 : replorigin_drop_by_name(originname, true, false);
1281 : : }
1282 : :
1283 [ + + ]: 21 : ereport(DEBUG1,
1284 : : (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
1285 : : get_namespace_name(get_rel_namespace(relid)),
1286 : : get_rel_name(relid),
1287 : : sub->name)));
1288 : : }
1289 : : }
1290 : :
1291 : : /*
1292 : : * Drop the tablesync slots associated with removed tables. This has
1293 : : * to be at the end because otherwise if there is an error while doing
1294 : : * the database operations we won't be able to rollback dropped slots.
1295 : : */
1296 [ + + + + : 97 : foreach_ptr(SubRemoveRels, sub_remove_rel, sub_remove_rels)
+ + ]
1297 : : {
1298 [ - + ]: 21 : if (sub_remove_rel->state != SUBREL_STATE_READY &&
1299 [ # # ]: 0 : sub_remove_rel->state != SUBREL_STATE_SYNCDONE)
1300 : : {
1301 : 0 : char syncslotname[NAMEDATALEN] = {0};
1302 : :
1303 : : /*
1304 : : * For READY/SYNCDONE states we know the tablesync slot has
1305 : : * already been dropped by the tablesync worker.
1306 : : *
1307 : : * For other states, there is no certainty, maybe the slot
1308 : : * does not exist yet. Also, if we fail after removing some of
1309 : : * the slots, next time, it will again try to drop already
1310 : : * dropped slots and fail. For these reasons, we allow
1311 : : * missing_ok = true for the drop.
1312 : : */
1313 : 0 : ReplicationSlotNameForTablesync(sub->oid, sub_remove_rel->relid,
1314 : : syncslotname, sizeof(syncslotname));
1315 : 0 : ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1316 : : }
1317 : : }
1318 : :
1319 : : /*
1320 : : * Next remove state for sequences we should not care about anymore
1321 : : * using the data we collected above
1322 : : */
1323 [ + + ]: 47 : for (off = 0; off < seq_count; off++)
1324 : : {
1325 : 9 : Oid relid = subseq_local_oids[off];
1326 : :
1327 [ - + ]: 9 : if (!bsearch(&relid, pubrel_local_oids,
1328 : 9 : list_length(pubrels), sizeof(Oid), oid_cmp))
1329 : : {
1330 : : /*
1331 : : * This locking ensures that the state of rels won't change
1332 : : * till we are done with this refresh operation.
1333 : : */
1334 [ # # ]: 0 : if (!rel)
1335 : 0 : rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
1336 : :
1337 : 0 : RemoveSubscriptionRel(sub->oid, relid);
1338 : :
1339 [ # # ]: 0 : ereport(DEBUG1,
1340 : : errmsg_internal("sequence \"%s.%s\" removed from subscription \"%s\"",
1341 : : get_namespace_name(get_rel_namespace(relid)),
1342 : : get_rel_name(relid),
1343 : : sub->name));
1344 : : }
1345 : : }
1346 : : }
1347 : 0 : PG_FINALLY();
1348 : : {
1349 : 38 : walrcv_disconnect(wrconn);
1350 : : }
1351 [ - + ]: 38 : PG_END_TRY();
1352 : :
1353 [ + + ]: 38 : if (rel)
1354 : 9 : table_close(rel, NoLock);
1355 : 38 : }
1356 : :
1357 : : /*
1358 : : * Marks all sequences with INIT state.
1359 : : */
1360 : : static void
1361 : 5 : AlterSubscription_refresh_seq(Subscription *sub)
1362 : : {
1363 : 5 : char *err = NULL;
1364 : : WalReceiverConn *wrconn;
1365 : : bool must_use_password;
1366 : : List *subrel_states;
1367 : :
1368 : : /* Load the library providing us libpq calls. */
1369 : 5 : load_file("libpqwalreceiver", false);
1370 : :
1371 : : /* Try to connect to the publisher. */
1372 [ + - - + ]: 5 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
1373 : 5 : wrconn = walrcv_connect(sub->conninfo, true, true, must_use_password,
1374 : : sub->name, &err);
1375 [ - + ]: 5 : if (!wrconn)
1376 [ # # ]: 0 : ereport(ERROR,
1377 : : errcode(ERRCODE_CONNECTION_FAILURE),
1378 : : errmsg("subscription \"%s\" could not connect to the publisher: %s",
1379 : : sub->name, err));
1380 : :
1381 : : /* The publisher connection is only needed for the origin check. */
1382 [ + - ]: 5 : PG_TRY();
1383 : : {
1384 : : /*
1385 : : * Sequence synchronization depends on publisher-side functionality
1386 : : * introduced in PostgreSQL 19, so it cannot work against an older
1387 : : * publisher.
1388 : : */
1389 [ - + ]: 5 : if (walrcv_server_version(wrconn) < 190000)
1390 [ # # ]: 0 : ereport(ERROR,
1391 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1392 : : errmsg("cannot synchronize sequences if the publisher is running a version earlier than PostgreSQL 19"));
1393 : :
1394 : 5 : check_publications_origin_sequences(wrconn, sub->publications, true,
1395 : : sub->origin, NULL, 0, sub->name);
1396 : : }
1397 : 0 : PG_FINALLY();
1398 : : {
1399 : 5 : walrcv_disconnect(wrconn);
1400 : : }
1401 [ - + ]: 5 : PG_END_TRY();
1402 : :
1403 : : /*
1404 : : * Reset the sequences to INIT so they get re-synchronized with the latest
1405 : : * publisher values.
1406 : : *
1407 : : * A sequence sync worker may already be running. If it has fetched a
1408 : : * sequence's value from the publisher but not yet marked it READY, it
1409 : : * must not be allowed to complete that update, as it would overwrite the
1410 : : * reset below with a stale value and silently lose this refresh request.
1411 : : * So we stop any running sequence sync worker before resetting the
1412 : : * states.
1413 : : *
1414 : : * This is race-free because AlterSubscription() already holds
1415 : : * AccessExclusiveLock on the subscription object. That lock blocks a
1416 : : * running worker's update of sequence state to READY, see
1417 : : * UpdateSubscriptionRelState() which takes AccessShareLock on the object.
1418 : : * It also blocks any worker the apply worker re-launches, because a new
1419 : : * worker takes AccessShareLock on the object before it reads
1420 : : * pg_subscription_rel, see InitializeLogRepWorker(). Such a worker cannot
1421 : : * act on the states until we commit, by which time they are reset to INIT
1422 : : * and it will sync the latest values.
1423 : : */
1424 : : #ifdef USE_ASSERT_CHECKING
1425 : : {
1426 : : LOCKTAG tag;
1427 : :
1428 : : SET_LOCKTAG_OBJECT(tag, InvalidOid, SubscriptionRelationId, sub->oid, 0);
1429 : : Assert(LockHeldByMe(&tag, AccessExclusiveLock, true));
1430 : : }
1431 : : #endif
1432 : :
1433 : 5 : logicalrep_worker_stop(WORKERTYPE_SEQUENCESYNC, sub->oid, InvalidOid);
1434 : :
1435 : : /* Reset every local sequence of this subscription to INIT. */
1436 : 5 : subrel_states = GetSubscriptionRelations(sub->oid, false, true, false);
1437 [ + - + + : 31 : foreach_ptr(SubscriptionRelState, subrel, subrel_states)
+ + ]
1438 : : {
1439 : 21 : Oid relid = subrel->relid;
1440 : :
1441 : 21 : UpdateSubscriptionRelState(sub->oid, relid, SUBREL_STATE_INIT,
1442 : : InvalidXLogRecPtr, false);
1443 [ - + ]: 21 : ereport(DEBUG1,
1444 : : errmsg_internal("sequence \"%s.%s\" of subscription \"%s\" set to INIT state",
1445 : : get_namespace_name(get_rel_namespace(relid)),
1446 : : get_rel_name(relid),
1447 : : sub->name));
1448 : : }
1449 : 5 : }
1450 : :
1451 : : /*
1452 : : * Common checks for altering failover, two_phase, and retain_dead_tuples
1453 : : * options.
1454 : : */
1455 : : static void
1456 : 14 : CheckAlterSubOption(Subscription *sub, const char *option,
1457 : : bool slot_needs_update, bool isTopLevel)
1458 : : {
1459 : : Assert(strcmp(option, "failover") == 0 ||
1460 : : strcmp(option, "two_phase") == 0 ||
1461 : : strcmp(option, "retain_dead_tuples") == 0);
1462 : :
1463 : : /*
1464 : : * Altering the retain_dead_tuples option does not update the slot on the
1465 : : * publisher.
1466 : : */
1467 : : Assert(!slot_needs_update || strcmp(option, "retain_dead_tuples") != 0);
1468 : :
1469 : : /*
1470 : : * Do not allow changing the option if the subscription is enabled. This
1471 : : * is because both failover and two_phase options of the slot on the
1472 : : * publisher cannot be modified if the slot is currently acquired by the
1473 : : * existing walsender.
1474 : : *
1475 : : * Note that two_phase is enabled (aka changed from 'false' to 'true') on
1476 : : * the publisher by the existing walsender, so we could have allowed that
1477 : : * even when the subscription is enabled. But we kept this restriction for
1478 : : * the sake of consistency and simplicity.
1479 : : *
1480 : : * Additionally, do not allow changing the retain_dead_tuples option when
1481 : : * the subscription is enabled to prevent race conditions arising from the
1482 : : * new option value being acknowledged asynchronously by the launcher and
1483 : : * apply workers.
1484 : : *
1485 : : * Without the restriction, a race condition may arise when a user
1486 : : * disables and immediately re-enables the retain_dead_tuples option. In
1487 : : * this case, the launcher might drop the slot upon noticing the disabled
1488 : : * action, while the apply worker may keep maintaining
1489 : : * oldest_nonremovable_xid without noticing the option change. During this
1490 : : * period, a transaction ID wraparound could falsely make this ID appear
1491 : : * as if it originates from the future w.r.t the transaction ID stored in
1492 : : * the slot maintained by launcher.
1493 : : *
1494 : : * Similarly, if the user enables retain_dead_tuples concurrently with the
1495 : : * launcher starting the worker, the apply worker may start calculating
1496 : : * oldest_nonremovable_xid before the launcher notices the enable action.
1497 : : * Consequently, the launcher may update slot.xmin to a newer value than
1498 : : * that maintained by the worker. In subsequent cycles, upon integrating
1499 : : * the worker's oldest_nonremovable_xid, the launcher might detect a
1500 : : * retreat in the calculated xmin, necessitating additional handling.
1501 : : *
1502 : : * XXX To address the above race conditions, we can define
1503 : : * oldest_nonremovable_xid as FullTransactionId and adds the check to
1504 : : * disallow retreating the conflict slot's xmin. For now, we kept the
1505 : : * implementation simple by disallowing change to the retain_dead_tuples,
1506 : : * but in the future we can change this after some more analysis.
1507 : : *
1508 : : * Note that we could restrict only the enabling of retain_dead_tuples to
1509 : : * avoid the race conditions described above, but we maintain the
1510 : : * restriction for both enable and disable operations for the sake of
1511 : : * consistency.
1512 : : */
1513 [ + + ]: 14 : if (sub->enabled)
1514 [ + - ]: 2 : ereport(ERROR,
1515 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1516 : : errmsg("cannot set option \"%s\" for enabled subscription",
1517 : : option)));
1518 : :
1519 [ + + ]: 12 : if (slot_needs_update)
1520 : : {
1521 : : StringInfoData cmd;
1522 : :
1523 : : /*
1524 : : * A valid slot must be associated with the subscription for us to
1525 : : * modify any of the slot's properties.
1526 : : */
1527 [ - + ]: 9 : if (!sub->slotname)
1528 [ # # ]: 0 : ereport(ERROR,
1529 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1530 : : errmsg("cannot set option \"%s\" for a subscription that does not have a slot name",
1531 : : option)));
1532 : :
1533 : : /* The changed option of the slot can't be rolled back. */
1534 : 9 : initStringInfo(&cmd);
1535 : 9 : appendStringInfo(&cmd, "ALTER SUBSCRIPTION ... SET (%s)", option);
1536 : :
1537 : 9 : PreventInTransactionBlock(isTopLevel, cmd.data);
1538 : 5 : pfree(cmd.data);
1539 : : }
1540 : 8 : }
1541 : :
1542 : : /*
1543 : : * alter_sub_conflict_log_dest
1544 : : *
1545 : : * When the subscription's 'conflict_log_destination' is changed, update the
1546 : : * conflict log table if required.
1547 : : *
1548 : : * If the new destination no longer requires a conflict log table, the existing
1549 : : * conflict log table associated with the subscription is removed via internal
1550 : : * dependency cleanup to prevent orphaned relations.
1551 : : *
1552 : : * On success, *conflicttablerelid is set to the OID of the conflict log table
1553 : : * that was created or validated, or to InvalidOid if no table is required.
1554 : : *
1555 : : * Returns true if the subscription's conflict log table reference must be
1556 : : * updated as a result of the destination change; false otherwise.
1557 : : */
1558 : : static bool
1559 : 12 : alter_sub_conflict_log_dest(Subscription *sub, ConflictLogDest oldlogdest,
1560 : : ConflictLogDest newlogdest,
1561 : : Oid *conflicttablerelid)
1562 : : {
1563 : : bool want_table;
1564 : : bool has_oldtable;
1565 : 12 : bool update_relid = false;
1566 : 12 : Oid relid = InvalidOid;
1567 : :
1568 [ + + + + ]: 12 : want_table = CONFLICTS_LOGGED_TO_TABLE(newlogdest);
1569 [ + + + + ]: 12 : has_oldtable = CONFLICTS_LOGGED_TO_TABLE(oldlogdest);
1570 : :
1571 [ + + ]: 12 : if (has_oldtable)
1572 : : {
1573 : : /* There is a conflict log table already. */
1574 [ + + ]: 8 : if (!want_table)
1575 : : {
1576 : 4 : drop_sub_conflict_log_table(sub->oid, sub->name,
1577 : : sub->conflictlogrelid);
1578 : 4 : update_relid = true;
1579 : : }
1580 : : }
1581 : : else
1582 : : {
1583 : : /* There was no previous conflict log table. */
1584 [ + - ]: 4 : if (want_table)
1585 : : {
1586 : : ObjectAddress cltaddr;
1587 : : ObjectAddress subobj;
1588 : :
1589 : 4 : relid = create_conflict_log_table(sub->oid, sub->name, sub->owner);
1590 : 4 : update_relid = true;
1591 : :
1592 : : /*
1593 : : * Establish an internal dependency between the conflict log table
1594 : : * and the subscription. For details refer comments in
1595 : : * CreateSubscription function.
1596 : : */
1597 : 4 : ObjectAddressSet(cltaddr, RelationRelationId, relid);
1598 : 4 : ObjectAddressSet(subobj, SubscriptionRelationId, sub->oid);
1599 : 4 : recordDependencyOn(&cltaddr, &subobj, DEPENDENCY_INTERNAL);
1600 : : }
1601 : : }
1602 : :
1603 : 12 : *conflicttablerelid = relid;
1604 : 12 : return update_relid;
1605 : : }
1606 : :
1607 : : /*
1608 : : * Alter the existing subscription.
1609 : : */
1610 : : ObjectAddress
1611 : 410 : AlterSubscription(ParseState *pstate, AlterSubscriptionStmt *stmt,
1612 : : bool isTopLevel)
1613 : : {
1614 : : Relation rel;
1615 : : ObjectAddress myself;
1616 : : bool nulls[Natts_pg_subscription];
1617 : : bool replaces[Natts_pg_subscription];
1618 : : Datum values[Natts_pg_subscription];
1619 : : HeapTuple tup;
1620 : : Oid subid;
1621 : 410 : bool orig_conninfo_needed = true;
1622 : 410 : bool update_tuple = false;
1623 : 410 : bool update_failover = false;
1624 : 410 : bool update_two_phase = false;
1625 : 410 : bool check_pub_rdt = false;
1626 : : bool retain_dead_tuples;
1627 : : int max_retention;
1628 : : bool retention_active;
1629 : 410 : char *new_conninfo = NULL;
1630 : : char *origin;
1631 : : Subscription *sub;
1632 : : Form_pg_subscription form;
1633 : : uint32 supported_opts;
1634 : 410 : SubOpts opts = {0};
1635 : :
1636 : 410 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1637 : :
1638 : : /* Fetch the existing tuple. */
1639 : 410 : tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
1640 : : CStringGetDatum(stmt->subname));
1641 : :
1642 [ + + ]: 410 : if (!HeapTupleIsValid(tup))
1643 [ + - ]: 4 : ereport(ERROR,
1644 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
1645 : : errmsg("subscription \"%s\" does not exist",
1646 : : stmt->subname)));
1647 : :
1648 : 406 : form = (Form_pg_subscription) GETSTRUCT(tup);
1649 : 406 : subid = form->oid;
1650 : :
1651 : : /* must be owner */
1652 [ - + ]: 406 : if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1653 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
1654 : 0 : stmt->subname);
1655 : :
1656 : : /* parse and check options */
1657 [ + + + + : 406 : switch (stmt->kind)
+ + + ]
1658 : : {
1659 : 193 : case ALTER_SUBSCRIPTION_OPTIONS:
1660 : 193 : supported_opts = (SUBOPT_SLOT_NAME |
1661 : : SUBOPT_SYNCHRONOUS_COMMIT | SUBOPT_BINARY |
1662 : : SUBOPT_STREAMING | SUBOPT_TWOPHASE_COMMIT |
1663 : : SUBOPT_DISABLE_ON_ERR |
1664 : : SUBOPT_PASSWORD_REQUIRED |
1665 : : SUBOPT_RUN_AS_OWNER | SUBOPT_FAILOVER |
1666 : : SUBOPT_RETAIN_DEAD_TUPLES |
1667 : : SUBOPT_MAX_RETENTION_DURATION |
1668 : : SUBOPT_WAL_RECEIVER_TIMEOUT |
1669 : : SUBOPT_ORIGIN |
1670 : : SUBOPT_CONFLICT_LOG_DEST);
1671 : 193 : break;
1672 : :
1673 : 79 : case ALTER_SUBSCRIPTION_ENABLED:
1674 : 79 : supported_opts = SUBOPT_ENABLED;
1675 : 79 : break;
1676 : :
1677 : 19 : case ALTER_SUBSCRIPTION_SET_PUBLICATION:
1678 : 19 : supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1679 : 19 : break;
1680 : :
1681 : 35 : case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
1682 : : case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
1683 : 35 : supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1684 : 35 : break;
1685 : :
1686 : 37 : case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
1687 : 37 : supported_opts = SUBOPT_COPY_DATA;
1688 : 37 : break;
1689 : :
1690 : 15 : case ALTER_SUBSCRIPTION_SKIP:
1691 : 15 : supported_opts = SUBOPT_LSN;
1692 : 15 : break;
1693 : :
1694 : 28 : default:
1695 : 28 : supported_opts = 0;
1696 : 28 : break;
1697 : : }
1698 : :
1699 [ + + ]: 406 : if (supported_opts > 0)
1700 : 378 : parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
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 [ + + ]: 382 : if (stmt->kind == ALTER_SUBSCRIPTION_ENABLED)
1716 : : {
1717 [ + - + + ]: 79 : if (opts.specified_opts == SUBOPT_ENABLED && !opts.enabled)
1718 : 45 : orig_conninfo_needed = false;
1719 : : }
1720 [ + + ]: 303 : else if (stmt->kind == ALTER_SUBSCRIPTION_SERVER ||
1721 [ + + ]: 302 : stmt->kind == ALTER_SUBSCRIPTION_CONNECTION)
1722 : : {
1723 : 23 : orig_conninfo_needed = false;
1724 : : }
1725 [ + + ]: 280 : else if (stmt->kind == ALTER_SUBSCRIPTION_OPTIONS)
1726 : : {
1727 : : /* ... SET (slot_name = NONE) with no other options */
1728 [ + + + + ]: 173 : if (opts.specified_opts == SUBOPT_SLOT_NAME && !opts.slot_name)
1729 : 68 : 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 : 382 : sub = GetSubscription(subid, false, orig_conninfo_needed, false);
1740 : :
1741 : 382 : retain_dead_tuples = sub->retaindeadtuples;
1742 : 382 : origin = sub->origin;
1743 : 382 : max_retention = sub->maxretention;
1744 : 382 : retention_active = sub->retentionactive;
1745 : :
1746 : : /*
1747 : : * Don't allow non-superuser modification of a subscription with
1748 : : * password_required=false.
1749 : : */
1750 [ + + - + ]: 382 : if (!sub->passwordrequired && !superuser())
1751 [ # # ]: 0 : ereport(ERROR,
1752 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
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. */
1757 : 382 : LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1758 : :
1759 : : /* Form a new tuple. */
1760 : 382 : memset(values, 0, sizeof(values));
1761 : 382 : memset(nulls, false, sizeof(nulls));
1762 : 382 : memset(replaces, false, sizeof(replaces));
1763 : :
1764 : 382 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
1765 : :
1766 [ + + + + : 382 : switch (stmt->kind)
+ + + + +
- ]
1767 : : {
1768 : 173 : case ALTER_SUBSCRIPTION_OPTIONS:
1769 : : {
1770 [ + + ]: 173 : 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 [ - + - - ]: 72 : if (sub->enabled && !opts.slot_name)
1780 [ # # ]: 0 : ereport(ERROR,
1781 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1782 : : errmsg("cannot set %s for enabled subscription",
1783 : : "slot_name = NONE")));
1784 : :
1785 [ + + ]: 72 : if (opts.slot_name)
1786 : 4 : values[Anum_pg_subscription_subslotname - 1] =
1787 : 4 : DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
1788 : : else
1789 : 68 : nulls[Anum_pg_subscription_subslotname - 1] = true;
1790 : 72 : replaces[Anum_pg_subscription_subslotname - 1] = true;
1791 : : }
1792 : :
1793 [ + + ]: 173 : if (opts.synchronous_commit)
1794 : : {
1795 : 4 : values[Anum_pg_subscription_subsynccommit - 1] =
1796 : 4 : CStringGetTextDatum(opts.synchronous_commit);
1797 : 4 : replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1798 : : }
1799 : :
1800 [ + + ]: 173 : if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1801 : : {
1802 : 10 : values[Anum_pg_subscription_subbinary - 1] =
1803 : 10 : BoolGetDatum(opts.binary);
1804 : 10 : replaces[Anum_pg_subscription_subbinary - 1] = true;
1805 : : }
1806 : :
1807 [ + + ]: 173 : if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1808 : : {
1809 : 18 : values[Anum_pg_subscription_substream - 1] =
1810 : 18 : CharGetDatum(opts.streaming);
1811 : 18 : replaces[Anum_pg_subscription_substream - 1] = true;
1812 : : }
1813 : :
1814 [ + + ]: 173 : if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1815 : : {
1816 : : values[Anum_pg_subscription_subdisableonerr - 1]
1817 : 4 : = BoolGetDatum(opts.disableonerr);
1818 : : replaces[Anum_pg_subscription_subdisableonerr - 1]
1819 : 4 : = true;
1820 : : }
1821 : :
1822 [ + + ]: 173 : if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1823 : : {
1824 : : /* Non-superuser may not disable password_required. */
1825 [ + + - + ]: 8 : if (!opts.passwordrequired && !superuser())
1826 [ # # ]: 0 : ereport(ERROR,
1827 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
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 : :
1831 : : values[Anum_pg_subscription_subpasswordrequired - 1]
1832 : 8 : = BoolGetDatum(opts.passwordrequired);
1833 : : replaces[Anum_pg_subscription_subpasswordrequired - 1]
1834 : 8 : = true;
1835 : : }
1836 : :
1837 [ + + ]: 173 : if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
1838 : : {
1839 : 9 : values[Anum_pg_subscription_subrunasowner - 1] =
1840 : 9 : BoolGetDatum(opts.runasowner);
1841 : 9 : replaces[Anum_pg_subscription_subrunasowner - 1] = true;
1842 : : }
1843 : :
1844 [ + + ]: 173 : 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 : 3 : update_two_phase = !opts.twophase;
1854 : :
1855 : 3 : 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 [ + + ]: 3 : if (update_two_phase &&
1864 [ - + ]: 1 : IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1865 [ # # ]: 0 : ereport(ERROR,
1866 : : (errcode(ERRCODE_SYNTAX_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 [ - + ]: 3 : if (logicalrep_workers_find(subid, true, true))
1881 [ # # ]: 0 : ereport(ERROR,
1882 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 [ + + ]: 3 : if (update_two_phase &&
1893 [ + - ]: 1 : sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED &&
1894 [ - + ]: 1 : LookupGXactBySubid(subid))
1895 [ # # ]: 0 : ereport(ERROR,
1896 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1897 : : errmsg("cannot disable \"two_phase\" when prepared transactions exist"),
1898 : : errhint("Resolve these transactions and try again.")));
1899 : :
1900 : : /* Change system catalog accordingly */
1901 : 3 : values[Anum_pg_subscription_subtwophasestate - 1] =
1902 [ + + ]: 3 : CharGetDatum(opts.twophase ?
1903 : : LOGICALREP_TWOPHASE_STATE_PENDING :
1904 : : LOGICALREP_TWOPHASE_STATE_DISABLED);
1905 : 3 : replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
1906 : : }
1907 : :
1908 [ + + ]: 173 : 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 : 9 : update_failover = true;
1916 : :
1917 : 9 : CheckAlterSubOption(sub, "failover", update_failover,
1918 : : isTopLevel);
1919 : :
1920 : 4 : values[Anum_pg_subscription_subfailover - 1] =
1921 : 4 : BoolGetDatum(opts.failover);
1922 : 4 : replaces[Anum_pg_subscription_subfailover - 1] = true;
1923 : : }
1924 : :
1925 [ + + ]: 168 : if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
1926 : : {
1927 : 2 : values[Anum_pg_subscription_subretaindeadtuples - 1] =
1928 : 2 : BoolGetDatum(opts.retaindeadtuples);
1929 : 2 : replaces[Anum_pg_subscription_subretaindeadtuples - 1] = true;
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 [ + - ]: 2 : if (opts.retaindeadtuples != sub->retaindeadtuples)
1946 : : {
1947 : 2 : values[Anum_pg_subscription_subretentionactive - 1] =
1948 : 2 : BoolGetDatum(opts.retaindeadtuples);
1949 : 2 : replaces[Anum_pg_subscription_subretentionactive - 1] = true;
1950 : :
1951 : 2 : retention_active = opts.retaindeadtuples;
1952 : : }
1953 : :
1954 : 2 : 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 [ - + ]: 1 : if (logicalrep_workers_find(subid, true, true))
1965 [ # # ]: 0 : ereport(ERROR,
1966 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 : : */
1976 : 1 : ApplyLauncherWakeupAtCommit();
1977 : :
1978 : 1 : check_pub_rdt = opts.retaindeadtuples;
1979 : 1 : retain_dead_tuples = opts.retaindeadtuples;
1980 : : }
1981 : :
1982 [ + + ]: 167 : if (IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
1983 : : {
1984 : 6 : values[Anum_pg_subscription_submaxretention - 1] =
1985 : 6 : Int32GetDatum(opts.maxretention);
1986 : 6 : replaces[Anum_pg_subscription_submaxretention - 1] = true;
1987 : :
1988 : 6 : 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 [ + + ]: 167 : if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) ||
1997 [ + + ]: 166 : IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
1998 : 7 : CheckSubDeadTupleRetention(true, !sub->enabled, NOTICE,
1999 : : retain_dead_tuples,
2000 : : retention_active,
2001 : 7 : (max_retention > 0));
2002 : :
2003 [ + + ]: 167 : if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
2004 : : {
2005 : 6 : values[Anum_pg_subscription_suborigin - 1] =
2006 : 6 : CStringGetTextDatum(opts.origin);
2007 : 6 : replaces[Anum_pg_subscription_suborigin - 1] = true;
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 : : */
2016 [ + + ]: 8 : check_pub_rdt |= retain_dead_tuples &&
2017 [ + + ]: 2 : pg_strcasecmp(opts.origin, LOGICALREP_ORIGIN_ANY) == 0;
2018 : :
2019 : 6 : origin = opts.origin;
2020 : : }
2021 : :
2022 [ + + ]: 167 : if (IsSet(opts.specified_opts, SUBOPT_WAL_RECEIVER_TIMEOUT))
2023 : : {
2024 : 8 : values[Anum_pg_subscription_subwalrcvtimeout - 1] =
2025 : 8 : CStringGetTextDatum(opts.wal_receiver_timeout);
2026 : 8 : replaces[Anum_pg_subscription_subwalrcvtimeout - 1] = true;
2027 : : }
2028 : :
2029 [ + + ]: 167 : if (IsSet(opts.specified_opts, SUBOPT_CONFLICT_LOG_DEST))
2030 : : {
2031 : : ConflictLogDest old_dest =
2032 : 16 : GetConflictLogDest(sub->conflictlogdest);
2033 : :
2034 [ + + ]: 16 : if (opts.conflictlogdest != old_dest)
2035 : : {
2036 : : bool update_relid;
2037 : 12 : Oid relid = InvalidOid;
2038 : :
2039 : 12 : values[Anum_pg_subscription_subconflictlogdest - 1] =
2040 : 12 : CStringGetTextDatum(ConflictLogDestNames[opts.conflictlogdest]);
2041 : 12 : replaces[Anum_pg_subscription_subconflictlogdest - 1] = true;
2042 : :
2043 : 12 : update_relid = alter_sub_conflict_log_dest(sub,
2044 : : old_dest,
2045 : : opts.conflictlogdest,
2046 : : &relid);
2047 [ + + ]: 12 : if (update_relid)
2048 : : {
2049 : 8 : values[Anum_pg_subscription_subconflictlogrelid - 1] =
2050 : 8 : ObjectIdGetDatum(relid);
2051 : 8 : replaces[Anum_pg_subscription_subconflictlogrelid - 1] =
2052 : : true;
2053 : : }
2054 : : }
2055 : : }
2056 : :
2057 : 167 : update_tuple = true;
2058 : 167 : break;
2059 : : }
2060 : :
2061 : 79 : case ALTER_SUBSCRIPTION_ENABLED:
2062 : : {
2063 : : Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
2064 : :
2065 [ + + + - ]: 79 : if (!sub->slotname && opts.enabled)
2066 [ + - ]: 4 : ereport(ERROR,
2067 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 : 75 : CheckSubDeadTupleRetention(opts.enabled, !opts.enabled,
2076 : 75 : WARNING, sub->retaindeadtuples,
2077 : 75 : sub->retentionactive, false);
2078 : :
2079 : 75 : values[Anum_pg_subscription_subenabled - 1] =
2080 : 75 : BoolGetDatum(opts.enabled);
2081 : 75 : replaces[Anum_pg_subscription_subenabled - 1] = true;
2082 : :
2083 [ + + ]: 75 : if (opts.enabled)
2084 : 30 : ApplyLauncherWakeupAtCommit();
2085 : :
2086 : 75 : 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 [ + + + + ]: 75 : check_pub_rdt = sub->retaindeadtuples && opts.enabled;
2095 : 75 : break;
2096 : : }
2097 : :
2098 : 1 : case ALTER_SUBSCRIPTION_SERVER:
2099 : : {
2100 : : ForeignServer *new_server;
2101 : : ObjectAddress referenced;
2102 : : AclResult aclresult;
2103 : :
2104 : : /*
2105 : : * Remove what was there before, either another foreign server
2106 : : * or a connection string.
2107 : : */
2108 [ - + ]: 1 : if (form->subserver)
2109 : : {
2110 : 0 : deleteDependencyRecordsForSpecific(SubscriptionRelationId, form->oid,
2111 : : DEPENDENCY_NORMAL,
2112 : : ForeignServerRelationId, form->subserver);
2113 : : }
2114 : : else
2115 : : {
2116 : 1 : nulls[Anum_pg_subscription_subconninfo - 1] = true;
2117 : 1 : replaces[Anum_pg_subscription_subconninfo - 1] = true;
2118 : : }
2119 : :
2120 : : /*
2121 : : * Check that the subscription owner has USAGE privileges on
2122 : : * the server.
2123 : : */
2124 : 1 : new_server = GetForeignServerByName(stmt->servername, false);
2125 : 1 : aclresult = object_aclcheck(ForeignServerRelationId,
2126 : : new_server->serverid,
2127 : : form->subowner, ACL_USAGE);
2128 [ - + ]: 1 : if (aclresult != ACLCHECK_OK)
2129 [ # # ]: 0 : ereport(ERROR,
2130 : : errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
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 : 1 : GetUserMapping(form->subowner, new_server->serverid);
2137 : :
2138 : 1 : new_conninfo = ForeignServerConnectionString(form->subowner,
2139 : : new_server);
2140 : :
2141 : : /* Load the library providing us libpq calls. */
2142 : 1 : load_file("libpqwalreceiver", false);
2143 : : /* Check the connection info string. */
2144 [ - + - - ]: 1 : walrcv_check_conninfo(new_conninfo,
2145 : : sub->passwordrequired && !sub->ownersuperuser);
2146 : :
2147 : 1 : values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(new_server->serverid);
2148 : 1 : replaces[Anum_pg_subscription_subserver - 1] = true;
2149 : :
2150 : 1 : ObjectAddressSet(referenced, ForeignServerRelationId, new_server->serverid);
2151 : 1 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
2152 : :
2153 : 1 : 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 : : */
2161 : 1 : check_pub_rdt = sub->retaindeadtuples;
2162 : 1 : break;
2163 : :
2164 : 22 : case ALTER_SUBSCRIPTION_CONNECTION:
2165 : : /* remove reference to foreign server and dependencies, if present */
2166 [ + + ]: 22 : if (form->subserver)
2167 : : {
2168 : 9 : deleteDependencyRecordsForSpecific(SubscriptionRelationId, form->oid,
2169 : : DEPENDENCY_NORMAL,
2170 : : ForeignServerRelationId, form->subserver);
2171 : :
2172 : 9 : values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(InvalidOid);
2173 : 9 : replaces[Anum_pg_subscription_subserver - 1] = true;
2174 : : }
2175 : :
2176 : 22 : new_conninfo = stmt->conninfo;
2177 : :
2178 : : /* Load the library providing us libpq calls. */
2179 : 22 : load_file("libpqwalreceiver", false);
2180 : : /* Check the connection info string. */
2181 [ + + + + ]: 22 : walrcv_check_conninfo(new_conninfo,
2182 : : sub->passwordrequired && !sub->ownersuperuser);
2183 : :
2184 : 18 : values[Anum_pg_subscription_subconninfo - 1] =
2185 : 18 : CStringGetTextDatum(stmt->conninfo);
2186 : 18 : replaces[Anum_pg_subscription_subconninfo - 1] = true;
2187 : 18 : 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 : : */
2194 : 18 : check_pub_rdt = sub->retaindeadtuples;
2195 : 18 : break;
2196 : :
2197 : 19 : case ALTER_SUBSCRIPTION_SET_PUBLICATION:
2198 : : {
2199 : 19 : values[Anum_pg_subscription_subpublications - 1] =
2200 : 19 : publicationListToArray(stmt->publication);
2201 : 19 : replaces[Anum_pg_subscription_subpublications - 1] = true;
2202 : :
2203 : 19 : update_tuple = true;
2204 : :
2205 : : /* Refresh if user asked us to. */
2206 [ + + ]: 19 : if (opts.refresh)
2207 : : {
2208 [ - + ]: 15 : if (!sub->enabled)
2209 [ # # ]: 0 : ereport(ERROR,
2210 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 [ - + - - ]: 15 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2219 [ # # ]: 0 : ereport(ERROR,
2220 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 : 15 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2225 : :
2226 : : /* Make sure refresh sees the new list of publications. */
2227 : 7 : sub->publications = stmt->publication;
2228 : :
2229 : 7 : AlterSubscription_refresh(sub, opts.copy_data,
2230 : : stmt->publication);
2231 : : }
2232 : :
2233 : 11 : break;
2234 : : }
2235 : :
2236 : 35 : case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
2237 : : case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
2238 : : {
2239 : : List *publist;
2240 : 35 : bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
2241 : :
2242 : 35 : publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
2243 : 11 : values[Anum_pg_subscription_subpublications - 1] =
2244 : 11 : publicationListToArray(publist);
2245 : 11 : replaces[Anum_pg_subscription_subpublications - 1] = true;
2246 : :
2247 : 11 : update_tuple = true;
2248 : :
2249 : : /* Refresh if user asked us to. */
2250 [ + + ]: 11 : if (opts.refresh)
2251 : : {
2252 : : /* We only need to validate user specified publications. */
2253 [ + + ]: 3 : List *validate_publications = (isadd) ? stmt->publication : NULL;
2254 : :
2255 [ - + ]: 3 : if (!sub->enabled)
2256 [ # # # # ]: 0 : ereport(ERROR,
2257 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 [ - + - - ]: 3 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2270 [ # # # # ]: 0 : ereport(ERROR,
2271 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 : 3 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2280 : :
2281 : : /* Refresh the new list of publications. */
2282 : 3 : sub->publications = publist;
2283 : :
2284 : 3 : AlterSubscription_refresh(sub, opts.copy_data,
2285 : : validate_publications);
2286 : : }
2287 : :
2288 : 11 : break;
2289 : : }
2290 : :
2291 : 37 : case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
2292 : : {
2293 [ + + ]: 37 : if (!sub->enabled)
2294 [ + - ]: 4 : ereport(ERROR,
2295 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 [ - + - - ]: 33 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2317 [ # # ]: 0 : ereport(ERROR,
2318 : : (errcode(ERRCODE_SYNTAX_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 : 33 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH PUBLICATION");
2323 : :
2324 : 29 : AlterSubscription_refresh(sub, opts.copy_data, NULL);
2325 : :
2326 : 28 : break;
2327 : : }
2328 : :
2329 : 5 : case ALTER_SUBSCRIPTION_REFRESH_SEQUENCES:
2330 : : {
2331 [ - + ]: 5 : if (!sub->enabled)
2332 [ # # ]: 0 : ereport(ERROR,
2333 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2334 : : errmsg("%s is not allowed for disabled subscriptions",
2335 : : "ALTER SUBSCRIPTION ... REFRESH SEQUENCES"));
2336 : :
2337 : 5 : AlterSubscription_refresh_seq(sub);
2338 : :
2339 : 5 : break;
2340 : : }
2341 : :
2342 : 11 : case ALTER_SUBSCRIPTION_SKIP:
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 [ + + ]: 11 : if (XLogRecPtrIsValid(opts.lsn))
2352 : : {
2353 : : ReplOriginId originid;
2354 : : char originname[NAMEDATALEN];
2355 : : XLogRecPtr remote_lsn;
2356 : :
2357 : 7 : ReplicationOriginNameForLogicalRep(subid, InvalidOid,
2358 : : originname, sizeof(originname));
2359 : 7 : originid = replorigin_by_name(originname, false);
2360 : 7 : remote_lsn = replorigin_get_progress(originid, false);
2361 : :
2362 : : /* Check the given LSN is at least a future LSN */
2363 [ + + - + ]: 7 : if (XLogRecPtrIsValid(remote_lsn) && opts.lsn < remote_lsn)
2364 [ # # ]: 0 : ereport(ERROR,
2365 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
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 : :
2371 : 11 : values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
2372 : 11 : replaces[Anum_pg_subscription_subskiplsn - 1] = true;
2373 : :
2374 : 11 : update_tuple = true;
2375 : 11 : break;
2376 : : }
2377 : :
2378 : 0 : default:
2379 [ # # ]: 0 : elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
2380 : : stmt->kind);
2381 : : }
2382 : :
2383 : : /* Update the catalog if needed. */
2384 [ + + ]: 327 : if (update_tuple)
2385 : : {
2386 : 294 : tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
2387 : : replaces);
2388 : :
2389 : 294 : CatalogTupleUpdate(rel, &tup->t_self, tup);
2390 : :
2391 : 294 : heap_freetuple(tup);
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 : : */
2403 [ + + + + : 327 : if (update_failover || update_two_phase || check_pub_rdt)
+ + ]
2404 : : {
2405 : : bool must_use_password;
2406 : : char *err;
2407 : : WalReceiverConn *wrconn;
2408 : :
2409 : : Assert(new_conninfo || orig_conninfo_needed);
2410 : :
2411 : : /* Load the library providing us libpq calls. */
2412 : 13 : load_file("libpqwalreceiver", false);
2413 : :
2414 : : /*
2415 : : * Try to connect to the publisher, using the new connection string if
2416 : : * available.
2417 : : */
2418 [ + - - + ]: 13 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
2419 [ + - ]: 13 : wrconn = walrcv_connect(new_conninfo ? new_conninfo : sub->conninfo,
2420 : : true, true, must_use_password, sub->name,
2421 : : &err);
2422 [ - + ]: 13 : if (!wrconn)
2423 [ # # ]: 0 : ereport(ERROR,
2424 : : (errcode(ERRCODE_CONNECTION_FAILURE),
2425 : : errmsg("subscription \"%s\" could not connect to the publisher: %s",
2426 : : sub->name, err)));
2427 : :
2428 [ + - ]: 13 : PG_TRY();
2429 : : {
2430 [ + + ]: 13 : if (retain_dead_tuples)
2431 : 9 : check_pub_dead_tuple_retention(wrconn);
2432 : :
2433 : 13 : check_publications_origin_tables(wrconn, sub->publications, false,
2434 : : retain_dead_tuples, origin, NULL, 0,
2435 : : sub->name);
2436 : :
2437 [ + + + + ]: 13 : if (update_failover || update_two_phase)
2438 [ + + + + ]: 5 : walrcv_alter_slot(wrconn, sub->slotname,
2439 : : update_failover ? &opts.failover : NULL,
2440 : : update_two_phase ? &opts.twophase : NULL);
2441 : : }
2442 : 0 : PG_FINALLY();
2443 : : {
2444 : 13 : walrcv_disconnect(wrconn);
2445 : : }
2446 [ - + ]: 13 : PG_END_TRY();
2447 : : }
2448 : :
2449 : 327 : table_close(rel, RowExclusiveLock);
2450 : :
2451 [ - + ]: 327 : InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
2452 : :
2453 : : /* Wake up related replication workers to handle this change quickly. */
2454 : 327 : LogicalRepWorkersWakeupAtCommit(subid);
2455 : :
2456 : 327 : return myself;
2457 : : }
2458 : :
2459 : : /*
2460 : : * Construct conninfo from a subscription's server. Like libpqrcv_connect(),
2461 : : * if an error occurs, set *err to the error message and return NULL.
2462 : : *
2463 : : * However, failures in ForeignServerConnectionString() may ereport(ERROR),
2464 : : * and (also like libpqrcv_connect) it's not worth adding the machinery to
2465 : : * pass all of those back to the caller just to cover this one case.
2466 : : */
2467 : : static char *
2468 : 8 : construct_subserver_conninfo(Oid subserver, Oid subowner, char **err)
2469 : : {
2470 : : AclResult aclresult;
2471 : : ForeignServer *server;
2472 : :
2473 : 8 : *err = NULL;
2474 : :
2475 : 8 : server = GetForeignServer(subserver);
2476 : :
2477 : 8 : aclresult = object_aclcheck(ForeignServerRelationId, subserver,
2478 : : subowner, ACL_USAGE);
2479 [ + + ]: 8 : if (aclresult != ACLCHECK_OK)
2480 : : {
2481 : : /*
2482 : : * Unable to generate connection string because permissions on the
2483 : : * foreign server have been removed. Follow the same logic as an
2484 : : * unusable subconninfo (which will result in an ERROR later unless
2485 : : * slot_name = NONE).
2486 : : */
2487 : 4 : *err = psprintf(_("subscription owner \"%s\" does not have permission on foreign server \"%s\""),
2488 : : GetUserNameFromId(subowner, false),
2489 : : server->servername);
2490 : 4 : return NULL;
2491 : : }
2492 : :
2493 : 4 : return ForeignServerConnectionString(subowner, server);
2494 : : }
2495 : :
2496 : : /*
2497 : : * Drop subscription's conflict log table
2498 : : *
2499 : : * The conflict log table is registered as an internal dependency of the
2500 : : * subscription. This function removes the dependency by performing a
2501 : : * cascading deletion on the subscription object, which in turn drops the
2502 : : * associated conflict log table.
2503 : : *
2504 : : * This is used to clean up conflict log tables that are no longer required,
2505 : : * preventing accumulation of stale or orphaned relations.
2506 : : *
2507 : : * NOTE:
2508 : : * Only conflict log tables are currently managed via this internal dependency
2509 : : * mechanism.
2510 : : */
2511 : : static void
2512 : 172 : drop_sub_conflict_log_table(Oid subid, char *subname, Oid subconflictlogrelid)
2513 : : {
2514 : : /* Drop any dependent conflict log table */
2515 [ + + ]: 172 : if (OidIsValid(subconflictlogrelid))
2516 : : {
2517 : : ObjectAddress object;
2518 : : char *conflictrelname;
2519 : :
2520 : 13 : conflictrelname = get_rel_name(subconflictlogrelid);
2521 [ - + ]: 13 : if (conflictrelname == NULL)
2522 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u",
2523 : : subconflictlogrelid);
2524 : :
2525 : : /*
2526 : : * By using PERFORM_DELETION_SKIP_ORIGINAL, we ensure that only the
2527 : : * conflict log table is deleted while the subscription remains.
2528 : : */
2529 : 13 : ObjectAddressSet(object, SubscriptionRelationId, subid);
2530 : 13 : performDeletion(&object, DROP_CASCADE,
2531 : : PERFORM_DELETION_INTERNAL |
2532 : : PERFORM_DELETION_SKIP_ORIGINAL);
2533 : :
2534 [ + + ]: 13 : ereport(NOTICE,
2535 : : errmsg("dropped conflict log table \"%s\" for subscription \"%s\"",
2536 : : get_qualified_objname(PG_CONFLICT_NAMESPACE, conflictrelname),
2537 : : subname));
2538 : : }
2539 : 172 : }
2540 : :
2541 : : /*
2542 : : * Drop a subscription
2543 : : */
2544 : : void
2545 : 180 : DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
2546 : : {
2547 : : Relation rel;
2548 : : ObjectAddress myself;
2549 : : HeapTuple tup;
2550 : : Oid subid;
2551 : : Oid subowner;
2552 : : Oid subserver;
2553 : : Oid subconflictlogrelid;
2554 : 180 : char *subconninfo = NULL;
2555 : : Datum datum;
2556 : : bool isnull;
2557 : : char *subname;
2558 : 180 : char *conninfo = NULL;
2559 : : char *slotname;
2560 : : List *subworkers;
2561 : : ListCell *lc;
2562 : : char originname[NAMEDATALEN];
2563 : 180 : char *err = NULL;
2564 : 180 : WalReceiverConn *wrconn = NULL;
2565 : : Form_pg_subscription form;
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 : : */
2575 : 180 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
2576 : :
2577 : 180 : tup = SearchSysCache2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
2578 : 180 : CStringGetDatum(stmt->subname));
2579 : :
2580 [ + + ]: 180 : if (!HeapTupleIsValid(tup))
2581 : : {
2582 : 8 : table_close(rel, NoLock);
2583 : :
2584 [ + + ]: 8 : if (!stmt->missing_ok)
2585 [ + - ]: 4 : ereport(ERROR,
2586 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
2587 : : errmsg("subscription \"%s\" does not exist",
2588 : : stmt->subname)));
2589 : : else
2590 [ + - ]: 4 : ereport(NOTICE,
2591 : : (errmsg("subscription \"%s\" does not exist, skipping",
2592 : : stmt->subname)));
2593 : :
2594 : 85 : return;
2595 : : }
2596 : :
2597 : 172 : datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
2598 : : Anum_pg_subscription_subconninfo, &isnull);
2599 [ + + ]: 172 : if (!isnull)
2600 : 155 : subconninfo = TextDatumGetCString(datum);
2601 : :
2602 : 172 : form = (Form_pg_subscription) GETSTRUCT(tup);
2603 : 172 : subid = form->oid;
2604 : 172 : subowner = form->subowner;
2605 : 172 : subserver = form->subserver;
2606 : 172 : subconflictlogrelid = form->subconflictlogrelid;
2607 [ + + + + ]: 172 : must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
2608 : :
2609 : : /* must be owner */
2610 [ - + ]: 172 : if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
2611 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
2612 : 0 : stmt->subname);
2613 : :
2614 : : /* DROP hook for the subscription being removed */
2615 [ - + ]: 172 : InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
2616 : :
2617 : : /*
2618 : : * Lock the subscription so nobody else can do anything with it (including
2619 : : * the replication workers).
2620 : : */
2621 : 172 : LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
2622 : :
2623 : : /* Get subname */
2624 : 172 : datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
2625 : : Anum_pg_subscription_subname);
2626 : 172 : subname = pstrdup(NameStr(*DatumGetName(datum)));
2627 : :
2628 : : /* Get slotname */
2629 : 172 : datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
2630 : : Anum_pg_subscription_subslotname, &isnull);
2631 [ + + ]: 172 : if (!isnull)
2632 : 90 : slotname = pstrdup(NameStr(*DatumGetName(datum)));
2633 : : else
2634 : 82 : 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 [ + + ]: 172 : if (slotname)
2648 : 90 : PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
2649 : :
2650 : 168 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
2651 : 168 : EventTriggerSQLDropAddObject(&myself, true, true);
2652 : :
2653 : : /* Remove the tuple from catalog. */
2654 : 168 : CatalogTupleDelete(rel, &tup->t_self);
2655 : :
2656 : 168 : ReleaseSysCache(tup);
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 : 168 : subworkers = logicalrep_workers_find(subid, false, true);
2675 [ + + + + : 250 : foreach(lc, subworkers)
+ + ]
2676 : : {
2677 : 82 : LogicalRepWorker *w = (LogicalRepWorker *) lfirst(lc);
2678 : :
2679 : 82 : logicalrep_worker_stop(w->type, w->subid, w->relid);
2680 : : }
2681 : 168 : list_free(subworkers);
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 : : */
2691 : 168 : ApplyLauncherForgetWorkerStartTime(subid);
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 : 168 : rstates = GetSubscriptionRelations(subid, true, false, true);
2703 [ + + + + : 174 : foreach(lc, rstates)
+ + ]
2704 : : {
2705 : 6 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
2706 : 6 : Oid relid = rstate->relid;
2707 : :
2708 : : /* Only cleanup resources of tablesync workers */
2709 [ - + ]: 6 : if (!OidIsValid(relid))
2710 : 0 : 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 : : */
2719 : 6 : ReplicationOriginNameForLogicalRep(subid, relid, originname,
2720 : : sizeof(originname));
2721 : 6 : replorigin_drop_by_name(originname, true, false);
2722 : : }
2723 : :
2724 : : /* Drop subscription's conflict log table */
2725 : 168 : drop_sub_conflict_log_table(subid, subname, subconflictlogrelid);
2726 : :
2727 : : /* Clean up dependencies */
2728 : 168 : deleteDependencyRecordsFor(SubscriptionRelationId, subid, false);
2729 : 168 : deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
2730 : :
2731 : : /* Remove any associated relation synchronization states. */
2732 : 168 : RemoveSubscriptionRel(subid, InvalidOid);
2733 : :
2734 : : /* Remove the origin tracking if exists. */
2735 : 168 : ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
2736 : 168 : replorigin_drop_by_name(originname, true, false);
2737 : :
2738 : : /*
2739 : : * Tell the cumulative stats system that the subscription is getting
2740 : : * dropped.
2741 : : */
2742 : 168 : pgstat_drop_subscription(subid);
2743 : :
2744 : : /*
2745 : : * If there is no slot associated with the subscription, we can finish
2746 : : * here.
2747 : : */
2748 [ + + + + ]: 168 : if (!slotname && rstates == NIL)
2749 : : {
2750 : 81 : table_close(rel, NoLock);
2751 : 81 : 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 : 87 : load_file("libpqwalreceiver", false);
2766 : :
2767 [ + + ]: 87 : if (OidIsValid(subserver))
2768 : 8 : conninfo = construct_subserver_conninfo(subserver, subowner, &err);
2769 : : else
2770 : 79 : conninfo = subconninfo;
2771 : :
2772 [ + + ]: 83 : if (conninfo)
2773 : 79 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
2774 : : subname, &err);
2775 : :
2776 [ + + ]: 83 : if (wrconn == NULL)
2777 : : {
2778 [ - + ]: 4 : if (!slotname)
2779 : : {
2780 : : /* be tidy */
2781 : 0 : list_free(rstates);
2782 : 0 : table_close(rel, NoLock);
2783 : 0 : return;
2784 : : }
2785 : : else
2786 : : {
2787 : 4 : ReportSlotConnectionError(rstates, subid, slotname, err);
2788 : : }
2789 : : }
2790 : :
2791 [ + + ]: 79 : PG_TRY();
2792 : : {
2793 [ + + + + : 85 : foreach(lc, rstates)
+ + ]
2794 : : {
2795 : 6 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
2796 : 6 : Oid relid = rstate->relid;
2797 : :
2798 : : /* Only cleanup resources of tablesync workers */
2799 [ - + ]: 6 : if (!OidIsValid(relid))
2800 : 0 : 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 [ + + ]: 6 : if (rstate->state != SUBREL_STATE_SYNCDONE)
2815 : : {
2816 : 3 : char syncslotname[NAMEDATALEN] = {0};
2817 : :
2818 : 3 : ReplicationSlotNameForTablesync(subid, relid, syncslotname,
2819 : : sizeof(syncslotname));
2820 : 3 : ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
2821 : : }
2822 : : }
2823 : :
2824 : 79 : list_free(rstates);
2825 : :
2826 : : /*
2827 : : * If there is a slot associated with the subscription, then drop the
2828 : : * replication slot at the publisher.
2829 : : */
2830 [ + + ]: 79 : if (slotname)
2831 : 78 : ReplicationSlotDropAtPubNode(wrconn, slotname, false);
2832 : : }
2833 : 1 : PG_FINALLY();
2834 : : {
2835 : 79 : walrcv_disconnect(wrconn);
2836 : : }
2837 [ + + ]: 79 : PG_END_TRY();
2838 : :
2839 : 78 : table_close(rel, NoLock);
2840 : : }
2841 : :
2842 : : /*
2843 : : * Drop the replication slot at the publisher node using the replication
2844 : : * connection.
2845 : : *
2846 : : * missing_ok - if true then only issue a LOG message if the slot doesn't
2847 : : * exist.
2848 : : */
2849 : : void
2850 : 292 : ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
2851 : : {
2852 : : StringInfoData cmd;
2853 : :
2854 : : Assert(wrconn);
2855 : :
2856 : 292 : load_file("libpqwalreceiver", false);
2857 : :
2858 : 292 : initStringInfo(&cmd);
2859 : 292 : appendStringInfoString(&cmd, "DROP_REPLICATION_SLOT ");
2860 : 292 : appendQuotedIdentifier(&cmd, slotname);
2861 : 292 : appendStringInfoString(&cmd, " WAIT");
2862 : :
2863 [ + + ]: 292 : PG_TRY();
2864 : : {
2865 : : WalRcvExecResult *res;
2866 : :
2867 : 292 : res = walrcv_exec(wrconn, cmd.data, 0, NULL);
2868 : :
2869 [ + + ]: 292 : if (res->status == WALRCV_OK_COMMAND)
2870 : : {
2871 : : /* NOTICE. Success. */
2872 [ + + ]: 290 : ereport(NOTICE,
2873 : : (errmsg("dropped replication slot \"%s\" on publisher",
2874 : : slotname)));
2875 : : }
2876 [ + - + + ]: 2 : else if (res->status == WALRCV_ERROR &&
2877 : 1 : missing_ok &&
2878 [ + - ]: 1 : res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
2879 : : {
2880 : : /* LOG. Error, but missing_ok = true. */
2881 [ + - ]: 1 : ereport(LOG,
2882 : : (errmsg("could not drop replication slot \"%s\" on publisher: %s",
2883 : : slotname, res->err)));
2884 : : }
2885 : : else
2886 : : {
2887 : : /* ERROR. */
2888 [ + - ]: 1 : ereport(ERROR,
2889 : : (errcode(ERRCODE_CONNECTION_FAILURE),
2890 : : errmsg("could not drop replication slot \"%s\" on publisher: %s",
2891 : : slotname, res->err)));
2892 : : }
2893 : :
2894 : 291 : walrcv_clear_result(res);
2895 : : }
2896 : 1 : PG_FINALLY();
2897 : : {
2898 : 292 : pfree(cmd.data);
2899 : : }
2900 [ + + ]: 292 : PG_END_TRY();
2901 : 291 : }
2902 : :
2903 : : /*
2904 : : * Internal workhorse for changing a subscription owner
2905 : : */
2906 : : static void
2907 : 24 : AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
2908 : : {
2909 : : Form_pg_subscription form;
2910 : : AclResult aclresult;
2911 : :
2912 : 24 : form = (Form_pg_subscription) GETSTRUCT(tup);
2913 : :
2914 : : /* Must only alter subscriptions belonging to the current database. */
2915 : : Assert(form->subdbid == MyDatabaseId);
2916 : :
2917 [ + + ]: 24 : if (form->subowner == newOwnerId)
2918 : 2 : return;
2919 : :
2920 [ - + ]: 22 : if (!object_ownercheck(SubscriptionRelationId, form->oid, GetUserId()))
2921 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
2922 : 0 : NameStr(form->subname));
2923 : :
2924 : : /*
2925 : : * Don't allow non-superuser modification of a subscription with
2926 : : * password_required=false.
2927 : : */
2928 [ - + - - ]: 22 : if (!form->subpasswordrequired && !superuser())
2929 [ # # ]: 0 : ereport(ERROR,
2930 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2931 : : errmsg("password_required=false is superuser-only"),
2932 : : errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
2933 : :
2934 : : /* Must be able to become new owner */
2935 : 22 : check_can_set_role(GetUserId(), newOwnerId);
2936 : :
2937 : : /*
2938 : : * current owner must have CREATE on database
2939 : : *
2940 : : * This is consistent with how ALTER SCHEMA ... OWNER TO works, but some
2941 : : * other object types behave differently (e.g. you can't give a table to a
2942 : : * user who lacks CREATE privileges on a schema).
2943 : : */
2944 : 18 : aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
2945 : : GetUserId(), ACL_CREATE);
2946 [ - + ]: 18 : if (aclresult != ACLCHECK_OK)
2947 : 0 : aclcheck_error(aclresult, OBJECT_DATABASE,
2948 : 0 : get_database_name(MyDatabaseId));
2949 : :
2950 : : /*
2951 : : * If the subscription uses a server, check that the new owner has USAGE
2952 : : * privileges on the server, that a user mapping exists, and that the
2953 : : * resulting connection string is valid for the new owner.
2954 : : */
2955 [ + + ]: 18 : if (OidIsValid(form->subserver))
2956 : : {
2957 : : char *conninfo;
2958 : 5 : ForeignServer *server = GetForeignServer(form->subserver);
2959 : :
2960 : 5 : aclresult = object_aclcheck(ForeignServerRelationId, server->serverid, newOwnerId, ACL_USAGE);
2961 [ - + ]: 5 : if (aclresult != ACLCHECK_OK)
2962 [ # # ]: 0 : ereport(ERROR,
2963 : : errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2964 : : errmsg("new subscription owner \"%s\" does not have permission on foreign server \"%s\"",
2965 : : GetUserNameFromId(newOwnerId, false),
2966 : : server->servername));
2967 : :
2968 : : /* make sure a user mapping exists */
2969 : 5 : GetUserMapping(newOwnerId, server->serverid);
2970 : :
2971 : 5 : conninfo = ForeignServerConnectionString(newOwnerId, server);
2972 : :
2973 : : /* Load the library providing us libpq calls. */
2974 : 5 : load_file("libpqwalreceiver", false);
2975 : : /* Check the connection info string. */
2976 [ + - + - ]: 5 : walrcv_check_conninfo(conninfo,
2977 : : form->subpasswordrequired &&
2978 : : !superuser_arg(newOwnerId));
2979 : : }
2980 : :
2981 : 14 : form->subowner = newOwnerId;
2982 : 14 : CatalogTupleUpdate(rel, &tup->t_self, tup);
2983 : :
2984 : : /* Update owner of the conflict log table if it exists. */
2985 [ + + ]: 14 : if (OidIsValid(form->subconflictlogrelid))
2986 : 8 : ATExecChangeOwner(form->subconflictlogrelid, newOwnerId, true,
2987 : : AccessExclusiveLock);
2988 : :
2989 : : /* Update owner dependency reference */
2990 : 14 : changeDependencyOnOwner(SubscriptionRelationId,
2991 : : form->oid,
2992 : : newOwnerId);
2993 : :
2994 [ - + ]: 14 : InvokeObjectPostAlterHook(SubscriptionRelationId,
2995 : : form->oid, 0);
2996 : :
2997 : : /* Wake up related background processes to handle this change quickly. */
2998 : 14 : ApplyLauncherWakeupAtCommit();
2999 : 14 : LogicalRepWorkersWakeupAtCommit(form->oid);
3000 : : }
3001 : :
3002 : : /*
3003 : : * Change subscription owner -- by name
3004 : : */
3005 : : ObjectAddress
3006 : 23 : AlterSubscriptionOwner(const char *name, Oid newOwnerId)
3007 : : {
3008 : : Oid subid;
3009 : : HeapTuple tup;
3010 : : Relation rel;
3011 : : ObjectAddress address;
3012 : : Form_pg_subscription form;
3013 : :
3014 : 23 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
3015 : :
3016 : 23 : tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
3017 : : CStringGetDatum(name));
3018 : :
3019 [ - + ]: 23 : if (!HeapTupleIsValid(tup))
3020 [ # # ]: 0 : ereport(ERROR,
3021 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
3022 : : errmsg("subscription \"%s\" does not exist", name)));
3023 : :
3024 : 23 : form = (Form_pg_subscription) GETSTRUCT(tup);
3025 : 23 : subid = form->oid;
3026 : :
3027 : 23 : AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
3028 : :
3029 : 15 : ObjectAddressSet(address, SubscriptionRelationId, subid);
3030 : :
3031 : 15 : heap_freetuple(tup);
3032 : :
3033 : 15 : table_close(rel, RowExclusiveLock);
3034 : :
3035 : 15 : return address;
3036 : : }
3037 : :
3038 : : /*
3039 : : * Change subscription owner -- by OID
3040 : : */
3041 : : void
3042 : 2 : AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
3043 : : {
3044 : : HeapTuple tup;
3045 : : Relation rel;
3046 : : Form_pg_subscription form;
3047 : :
3048 : 2 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
3049 : :
3050 : 2 : tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
3051 : :
3052 [ - + ]: 2 : if (!HeapTupleIsValid(tup))
3053 [ # # ]: 0 : ereport(ERROR,
3054 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
3055 : : errmsg("subscription with OID %u does not exist", subid)));
3056 : :
3057 : 2 : form = (Form_pg_subscription) GETSTRUCT(tup);
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 [ + + ]: 2 : if (form->subdbid == MyDatabaseId)
3065 : 1 : AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
3066 : :
3067 : 2 : heap_freetuple(tup);
3068 : :
3069 : 2 : table_close(rel, RowExclusiveLock);
3070 : 2 : }
3071 : :
3072 : : /*
3073 : : * Check and log a warning if the publisher has subscribed to the same table,
3074 : : * its partition ancestors (if it's a partition), or its partition children (if
3075 : : * it's a partitioned table), from some other publishers. This check is
3076 : : * required in the following scenarios:
3077 : : *
3078 : : * 1) For CREATE SUBSCRIPTION and ALTER SUBSCRIPTION ... REFRESH PUBLICATION
3079 : : * statements with "copy_data = true" and "origin = none":
3080 : : * - Warn the user that data with an origin might have been copied.
3081 : : * - This check is skipped for tables already added, as incremental sync via
3082 : : * WAL allows origin tracking. The list of such tables is in
3083 : : * subrel_local_oids.
3084 : : *
3085 : : * 2) For CREATE SUBSCRIPTION and ALTER SUBSCRIPTION ... REFRESH PUBLICATION
3086 : : * statements with "retain_dead_tuples = true" and "origin = any", and for
3087 : : * ALTER SUBSCRIPTION statements that modify retain_dead_tuples or origin,
3088 : : * or when the publisher's status changes (e.g., due to a connection string
3089 : : * update):
3090 : : * - Warn the user that only conflict detection info for local changes on
3091 : : * the publisher is retained. Data from other origins may lack sufficient
3092 : : * details for reliable conflict detection.
3093 : : * - See comments atop worker.c for more details.
3094 : : */
3095 : : static void
3096 : 177 : check_publications_origin_tables(WalReceiverConn *wrconn, List *publications,
3097 : : bool copydata, bool retain_dead_tuples,
3098 : : char *origin, Oid *subrel_local_oids,
3099 : : int subrel_count, char *subname)
3100 : : {
3101 : : WalRcvExecResult *res;
3102 : : StringInfoData cmd;
3103 : : TupleTableSlot *slot;
3104 : 177 : Oid tableRow[1] = {TEXTOID};
3105 : 177 : List *publist = NIL;
3106 : : int i;
3107 : : bool check_rdt;
3108 : : bool check_table_sync;
3109 [ + - + + ]: 354 : bool origin_none = origin &&
3110 : 177 : pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) == 0;
3111 : :
3112 : : /*
3113 : : * Enable retain_dead_tuples checks only when origin is set to 'any',
3114 : : * since with origin='none' only local changes are replicated to the
3115 : : * subscriber.
3116 : : */
3117 [ + + + + ]: 177 : check_rdt = retain_dead_tuples && !origin_none;
3118 : :
3119 : : /*
3120 : : * Enable table synchronization checks only when origin is 'none', to
3121 : : * ensure that data from other origins is not inadvertently copied.
3122 : : */
3123 [ + + + + ]: 177 : check_table_sync = copydata && origin_none;
3124 : :
3125 : : /* retain_dead_tuples and table sync checks occur separately */
3126 : : Assert(!(check_rdt && check_table_sync));
3127 : :
3128 : : /* Return if no checks are required */
3129 [ + + + + ]: 177 : if (!check_rdt && !check_table_sync)
3130 : 163 : return;
3131 : :
3132 : 14 : initStringInfo(&cmd);
3133 : 14 : appendStringInfoString(&cmd,
3134 : : "SELECT DISTINCT P.pubname AS pubname\n"
3135 : : "FROM pg_publication P,\n"
3136 : : " LATERAL pg_get_publication_tables(P.pubname) GPT\n"
3137 : : " JOIN pg_subscription_rel PS ON (GPT.relid = PS.srrelid OR"
3138 : : " GPT.relid IN (SELECT relid FROM pg_partition_ancestors(PS.srrelid) UNION"
3139 : : " SELECT relid FROM pg_partition_tree(PS.srrelid))),\n"
3140 : : " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
3141 : : "WHERE C.oid = GPT.relid AND P.pubname IN (");
3142 : 14 : GetPublicationsStr(publications, &cmd, true);
3143 : 14 : appendStringInfoString(&cmd, ")\n");
3144 : :
3145 : : /*
3146 : : * In case of ALTER SUBSCRIPTION ... REFRESH PUBLICATION,
3147 : : * subrel_local_oids contains the list of relation oids that are already
3148 : : * present on the subscriber. This check should be skipped for these
3149 : : * tables if checking for table sync scenario. However, when handling the
3150 : : * retain_dead_tuples scenario, ensure all tables are checked, as some
3151 : : * existing tables may now include changes from other origins due to newly
3152 : : * created subscriptions on the publisher.
3153 : : */
3154 [ + + ]: 14 : if (check_table_sync)
3155 : : {
3156 [ + + ]: 14 : for (i = 0; i < subrel_count; i++)
3157 : : {
3158 : 4 : Oid relid = subrel_local_oids[i];
3159 : 4 : char *schemaname = get_namespace_name(get_rel_namespace(relid));
3160 : 4 : char *tablename = get_rel_name(relid);
3161 : 4 : char *schemaname_lit = quote_literal_cstr(schemaname);
3162 : 4 : char *tablename_lit = quote_literal_cstr(tablename);
3163 : :
3164 : 4 : appendStringInfo(&cmd, "AND NOT (N.nspname = %s AND C.relname = %s)\n",
3165 : : schemaname_lit, tablename_lit);
3166 : :
3167 : 4 : pfree(schemaname_lit);
3168 : 4 : pfree(tablename_lit);
3169 : : }
3170 : : }
3171 : :
3172 : 14 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
3173 : 14 : pfree(cmd.data);
3174 : :
3175 [ - + ]: 14 : if (res->status != WALRCV_OK_TUPLES)
3176 [ # # ]: 0 : ereport(ERROR,
3177 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3178 : : errmsg("could not receive list of replicated tables from the publisher: %s",
3179 : : res->err)));
3180 : :
3181 : : /* Process publications. */
3182 : 14 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3183 [ + + ]: 19 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3184 : : {
3185 : : char *pubname;
3186 : : bool isnull;
3187 : :
3188 : 5 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
3189 : : Assert(!isnull);
3190 : :
3191 : 5 : ExecClearTuple(slot);
3192 : 5 : publist = list_append_unique(publist, makeString(pubname));
3193 : : }
3194 : :
3195 : : /*
3196 : : * Log a warning if the publisher has subscribed to the same table from
3197 : : * some other publisher. We cannot know the origin of data during the
3198 : : * initial sync. Data origins can be found only from the WAL by looking at
3199 : : * the origin id.
3200 : : *
3201 : : * XXX: For simplicity, we don't check whether the table has any data or
3202 : : * not. If the table doesn't have any data then we don't need to
3203 : : * distinguish between data having origin and data not having origin so we
3204 : : * can avoid logging a warning for table sync scenario.
3205 : : */
3206 [ + + ]: 14 : if (publist)
3207 : : {
3208 : : StringInfoData pubnames;
3209 : :
3210 : : /* Prepare the list of publication(s) for warning message. */
3211 : 5 : initStringInfo(&pubnames);
3212 : 5 : GetPublicationsStr(publist, &pubnames, false);
3213 : :
3214 [ + + ]: 5 : if (check_table_sync)
3215 [ + - ]: 4 : ereport(WARNING,
3216 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3217 : : errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
3218 : : subname),
3219 : : errdetail_plural("The subscription subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
3220 : : "The subscription subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
3221 : : list_length(publist), pubnames.data),
3222 : : errhint("Verify that initial data copied from the publisher tables did not come from other origins."));
3223 : : else
3224 [ + - ]: 1 : ereport(WARNING,
3225 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3226 : : errmsg("subscription \"%s\" enabled retain_dead_tuples but might not reliably detect conflicts for changes from different origins",
3227 : : subname),
3228 : : errdetail_plural("The subscription subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
3229 : : "The subscription subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
3230 : : list_length(publist), pubnames.data),
3231 : : errhint("Consider using origin = NONE or disabling retain_dead_tuples."));
3232 : : }
3233 : :
3234 : 14 : ExecDropSingleTupleTableSlot(slot);
3235 : :
3236 : 14 : walrcv_clear_result(res);
3237 : : }
3238 : :
3239 : : /*
3240 : : * This function is similar to check_publications_origin_tables and serves
3241 : : * same purpose for sequences.
3242 : : */
3243 : : static void
3244 : 169 : check_publications_origin_sequences(WalReceiverConn *wrconn, List *publications,
3245 : : bool copydata, char *origin,
3246 : : Oid *subrel_local_oids, int subrel_count,
3247 : : char *subname)
3248 : : {
3249 : : WalRcvExecResult *res;
3250 : : StringInfoData cmd;
3251 : : TupleTableSlot *slot;
3252 : 169 : Oid tableRow[1] = {TEXTOID};
3253 : 169 : List *publist = NIL;
3254 : :
3255 : : /*
3256 : : * Enable sequence synchronization checks only when origin is 'none' , to
3257 : : * ensure that sequence data from other origins is not inadvertently
3258 : : * copied. This check is necessary if the publisher is running PG19 or
3259 : : * later, where logical replication sequence synchronization is supported.
3260 : : */
3261 [ + + + + : 179 : if (!copydata || pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) != 0 ||
- + ]
3262 : 10 : walrcv_server_version(wrconn) < 190000)
3263 : 159 : return;
3264 : :
3265 : 10 : initStringInfo(&cmd);
3266 : 10 : appendStringInfoString(&cmd,
3267 : : "SELECT DISTINCT P.pubname AS pubname\n"
3268 : : "FROM pg_publication P,\n"
3269 : : " LATERAL pg_get_publication_sequences(P.pubname) GPS\n"
3270 : : " JOIN pg_subscription_rel PS ON (GPS.relid = PS.srrelid),\n"
3271 : : " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
3272 : : "WHERE C.oid = GPS.relid AND P.pubname IN (");
3273 : :
3274 : 10 : GetPublicationsStr(publications, &cmd, true);
3275 : 10 : appendStringInfoString(&cmd, ")\n");
3276 : :
3277 : : /*
3278 : : * In case of ALTER SUBSCRIPTION ... REFRESH PUBLICATION,
3279 : : * subrel_local_oids contains the list of relations that are already
3280 : : * present on the subscriber. This check should be skipped as these will
3281 : : * not be re-synced.
3282 : : */
3283 [ - + ]: 10 : for (int i = 0; i < subrel_count; i++)
3284 : : {
3285 : 0 : Oid relid = subrel_local_oids[i];
3286 : 0 : char *schemaname = get_namespace_name(get_rel_namespace(relid));
3287 : 0 : char *seqname = get_rel_name(relid);
3288 : 0 : char *schemaname_lit = quote_literal_cstr(schemaname);
3289 : 0 : char *seqname_lit = quote_literal_cstr(seqname);
3290 : :
3291 : 0 : appendStringInfo(&cmd,
3292 : : "AND NOT (N.nspname = %s AND C.relname = %s)\n",
3293 : : schemaname_lit, seqname_lit);
3294 : :
3295 : 0 : pfree(schemaname_lit);
3296 : 0 : pfree(seqname_lit);
3297 : : }
3298 : :
3299 : 10 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
3300 : 10 : pfree(cmd.data);
3301 : :
3302 [ - + ]: 10 : if (res->status != WALRCV_OK_TUPLES)
3303 [ # # ]: 0 : ereport(ERROR,
3304 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3305 : : errmsg("could not receive list of replicated sequences from the publisher: %s",
3306 : : res->err)));
3307 : :
3308 : : /* Process publications. */
3309 : 10 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3310 [ - + ]: 10 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3311 : : {
3312 : : char *pubname;
3313 : : bool isnull;
3314 : :
3315 : 0 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
3316 : : Assert(!isnull);
3317 : :
3318 : 0 : ExecClearTuple(slot);
3319 : 0 : publist = list_append_unique(publist, makeString(pubname));
3320 : : }
3321 : :
3322 : : /*
3323 : : * Log a warning if the publisher has subscribed to the same sequence from
3324 : : * some other publisher. We cannot know the origin of sequences data
3325 : : * during the initial sync.
3326 : : */
3327 [ - + ]: 10 : if (publist)
3328 : : {
3329 : : StringInfoData pubnames;
3330 : :
3331 : : /* Prepare the list of publication(s) for warning message. */
3332 : 0 : initStringInfo(&pubnames);
3333 : 0 : GetPublicationsStr(publist, &pubnames, false);
3334 : :
3335 [ # # ]: 0 : ereport(WARNING,
3336 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3337 : : errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
3338 : : subname),
3339 : : errdetail_plural("The subscription subscribes to a publication (%s) that contains sequences that are written to by other subscriptions.",
3340 : : "The subscription subscribes to publications (%s) that contain sequences that are written to by other subscriptions.",
3341 : : list_length(publist), pubnames.data),
3342 : : errhint("Verify that initial data copied from the publisher sequences did not come from other origins."));
3343 : : }
3344 : :
3345 : 10 : ExecDropSingleTupleTableSlot(slot);
3346 : :
3347 : 10 : walrcv_clear_result(res);
3348 : : }
3349 : :
3350 : : /*
3351 : : * Determine whether the retain_dead_tuples can be enabled based on the
3352 : : * publisher's status.
3353 : : *
3354 : : * This option is disallowed if the publisher is running a version earlier
3355 : : * than the PG19, or if the publisher is in recovery (i.e., it is a standby
3356 : : * server).
3357 : : *
3358 : : * See comments atop worker.c for a detailed explanation.
3359 : : */
3360 : : static void
3361 : 12 : check_pub_dead_tuple_retention(WalReceiverConn *wrconn)
3362 : : {
3363 : : WalRcvExecResult *res;
3364 : 12 : Oid RecoveryRow[1] = {BOOLOID};
3365 : : TupleTableSlot *slot;
3366 : : bool isnull;
3367 : : bool remote_in_recovery;
3368 : :
3369 [ - + ]: 12 : if (walrcv_server_version(wrconn) < 190000)
3370 [ # # ]: 0 : ereport(ERROR,
3371 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3372 : : errmsg("cannot enable retain_dead_tuples if the publisher is running a version earlier than PostgreSQL 19"));
3373 : :
3374 : 12 : res = walrcv_exec(wrconn, "SELECT pg_is_in_recovery()", 1, RecoveryRow);
3375 : :
3376 [ - + ]: 12 : if (res->status != WALRCV_OK_TUPLES)
3377 [ # # ]: 0 : ereport(ERROR,
3378 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3379 : : errmsg("could not obtain recovery progress from the publisher: %s",
3380 : : res->err)));
3381 : :
3382 : 12 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3383 [ - + ]: 12 : if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3384 [ # # ]: 0 : elog(ERROR, "failed to fetch tuple for the recovery progress");
3385 : :
3386 : 12 : remote_in_recovery = DatumGetBool(slot_getattr(slot, 1, &isnull));
3387 : :
3388 [ - + ]: 12 : if (remote_in_recovery)
3389 [ # # ]: 0 : ereport(ERROR,
3390 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3391 : : errmsg("cannot enable retain_dead_tuples if the publisher is in recovery"));
3392 : :
3393 : 12 : ExecDropSingleTupleTableSlot(slot);
3394 : :
3395 : 12 : walrcv_clear_result(res);
3396 : 12 : }
3397 : :
3398 : : /*
3399 : : * Check if the subscriber's configuration is adequate to enable the
3400 : : * retain_dead_tuples option.
3401 : : *
3402 : : * Issue an ERROR if the wal_level does not support the use of replication
3403 : : * slots when check_guc is set to true.
3404 : : *
3405 : : * Issue a WARNING if track_commit_timestamp is not enabled when check_guc is
3406 : : * set to true. This is only to highlight the importance of enabling
3407 : : * track_commit_timestamp instead of catching all the misconfigurations, as
3408 : : * this setting can be adjusted after subscription creation. Without it, the
3409 : : * apply worker will simply skip conflict detection.
3410 : : *
3411 : : * Issue a WARNING or NOTICE if the subscription is disabled and the retention
3412 : : * is active. Do not raise an ERROR since users can only modify
3413 : : * retain_dead_tuples for disabled subscriptions. And as long as the
3414 : : * subscription is enabled promptly, it will not pose issues.
3415 : : *
3416 : : * Issue a NOTICE to inform users that max_retention_duration is
3417 : : * ineffective when retain_dead_tuples is disabled for a subscription. An ERROR
3418 : : * is not issued because setting max_retention_duration causes no harm,
3419 : : * even when it is ineffective.
3420 : : */
3421 : : void
3422 : 331 : CheckSubDeadTupleRetention(bool check_guc, bool sub_disabled,
3423 : : int elevel_for_sub_disabled,
3424 : : bool retain_dead_tuples, bool retention_active,
3425 : : bool max_retention_set)
3426 : : {
3427 : : Assert(elevel_for_sub_disabled == NOTICE ||
3428 : : elevel_for_sub_disabled == WARNING);
3429 : :
3430 [ + + ]: 331 : if (retain_dead_tuples)
3431 : : {
3432 [ + + - + ]: 17 : if (check_guc && wal_level < WAL_LEVEL_REPLICA)
3433 [ # # ]: 0 : ereport(ERROR,
3434 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 : :
3438 [ + + + + ]: 17 : if (check_guc && !track_commit_timestamp)
3439 [ + - ]: 4 : ereport(WARNING,
3440 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
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 : :
3445 [ + + + - ]: 17 : if (sub_disabled && retention_active)
3446 [ + - + + ]: 7 : ereport(elevel_for_sub_disabled,
3447 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3448 : : errmsg("deleted rows to detect conflicts would not be removed until the subscription is enabled"),
3449 : : (elevel_for_sub_disabled > NOTICE)
3450 : : ? errhint("Consider setting %s to false.",
3451 : : "retain_dead_tuples") : 0);
3452 : : }
3453 [ + + ]: 314 : else if (max_retention_set)
3454 : : {
3455 [ + - ]: 4 : ereport(NOTICE,
3456 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3457 : : errmsg("max_retention_duration is ineffective when retain_dead_tuples is disabled"));
3458 : : }
3459 : 331 : }
3460 : :
3461 : : /*
3462 : : * Return true iff 'rv' is a member of the list.
3463 : : */
3464 : : static bool
3465 : 287 : list_member_rangevar(const List *list, RangeVar *rv)
3466 : : {
3467 [ + + + + : 1044 : foreach_ptr(PublicationRelKind, relinfo, list)
+ + ]
3468 : : {
3469 [ + + ]: 472 : if (equal(relinfo->rv, rv))
3470 : 1 : return true;
3471 : : }
3472 : :
3473 : 286 : return false;
3474 : : }
3475 : :
3476 : : /*
3477 : : * Get the list of tables and sequences which belong to specified publications
3478 : : * on the publisher connection.
3479 : : *
3480 : : * Note that we don't support the case where the column list is different for
3481 : : * the same table in different publications to avoid sending unwanted column
3482 : : * information for some of the rows. This can happen when both the column
3483 : : * list and row filter are specified for different publications.
3484 : : */
3485 : : static List *
3486 : 164 : fetch_relation_list(WalReceiverConn *wrconn, List *publications)
3487 : : {
3488 : : WalRcvExecResult *res;
3489 : : StringInfoData cmd;
3490 : : TupleTableSlot *slot;
3491 : 164 : Oid tableRow[4] = {TEXTOID, TEXTOID, CHAROID, InvalidOid};
3492 : 164 : List *relationlist = NIL;
3493 : 164 : int server_version = walrcv_server_version(wrconn);
3494 : 164 : bool check_columnlist = (server_version >= 150000);
3495 [ + - ]: 164 : int column_count = check_columnlist ? 4 : 3;
3496 : : StringInfoData pub_names;
3497 : :
3498 : 164 : initStringInfo(&cmd);
3499 : 164 : initStringInfo(&pub_names);
3500 : :
3501 : : /* Build the pub_names comma-separated string. */
3502 : 164 : GetPublicationsStr(publications, &pub_names, true);
3503 : :
3504 : : /* Get the list of relations from the publisher */
3505 [ + - ]: 164 : if (server_version >= 160000)
3506 : : {
3507 : 164 : tableRow[3] = INT2VECTOROID;
3508 : :
3509 : : /*
3510 : : * From version 16, we allowed passing multiple publications to the
3511 : : * function pg_get_publication_tables. This helped to filter out the
3512 : : * partition table whose ancestor is also published in this
3513 : : * publication array.
3514 : : *
3515 : : * Join pg_get_publication_tables with pg_publication to exclude
3516 : : * non-existing publications.
3517 : : *
3518 : : * Note that attrs are always stored in sorted order so we don't need
3519 : : * to worry if different publications have specified them in a
3520 : : * different order. See pub_collist_validate.
3521 : : */
3522 : 164 : appendStringInfo(&cmd, "SELECT DISTINCT n.nspname, c.relname, c.relkind, gpt.attrs\n"
3523 : : " FROM pg_class c\n"
3524 : : " JOIN pg_namespace n ON n.oid = c.relnamespace\n"
3525 : : " JOIN ( SELECT (pg_get_publication_tables(VARIADIC array_agg(pubname::text))).*\n"
3526 : : " FROM pg_publication\n"
3527 : : " WHERE pubname IN ( %s )) AS gpt\n"
3528 : : " ON gpt.relid = c.oid\n",
3529 : : pub_names.data);
3530 : :
3531 : : /* From version 19, inclusion of sequences in the target is supported */
3532 [ + - ]: 164 : if (server_version >= 190000)
3533 : 164 : appendStringInfo(&cmd,
3534 : : "UNION ALL\n"
3535 : : " SELECT DISTINCT s.schemaname, s.sequencename, " CppAsString2(RELKIND_SEQUENCE) "::\"char\" AS relkind, NULL::int2vector AS attrs\n"
3536 : : " FROM pg_catalog.pg_publication_sequences s\n"
3537 : : " WHERE s.pubname IN ( %s )",
3538 : : pub_names.data);
3539 : : }
3540 : : else
3541 : : {
3542 : 0 : tableRow[3] = NAMEARRAYOID;
3543 : 0 : appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename, " CppAsString2(RELKIND_RELATION) "::\"char\" AS relkind \n");
3544 : :
3545 : : /* Get column lists for each relation if the publisher supports it */
3546 [ # # ]: 0 : if (check_columnlist)
3547 : 0 : appendStringInfoString(&cmd, ", t.attnames\n");
3548 : :
3549 : 0 : appendStringInfo(&cmd, "FROM pg_catalog.pg_publication_tables t\n"
3550 : : " WHERE t.pubname IN ( %s )",
3551 : : pub_names.data);
3552 : : }
3553 : :
3554 : 164 : pfree(pub_names.data);
3555 : :
3556 : 164 : res = walrcv_exec(wrconn, cmd.data, column_count, tableRow);
3557 : 164 : pfree(cmd.data);
3558 : :
3559 [ - + ]: 164 : if (res->status != WALRCV_OK_TUPLES)
3560 [ # # ]: 0 : ereport(ERROR,
3561 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3562 : : errmsg("could not receive list of replicated tables from the publisher: %s",
3563 : : res->err)));
3564 : :
3565 : : /* Process tables. */
3566 : 164 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3567 [ + + ]: 467 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3568 : : {
3569 : : char *nspname;
3570 : : char *relname;
3571 : : bool isnull;
3572 : : char relkind;
3573 : 304 : PublicationRelKind *relinfo = palloc_object(PublicationRelKind);
3574 : :
3575 : 304 : nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
3576 : : Assert(!isnull);
3577 : 304 : relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
3578 : : Assert(!isnull);
3579 : 304 : relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
3580 : : Assert(!isnull);
3581 : :
3582 : 304 : relinfo->rv = makeRangeVar(nspname, relname, -1);
3583 : 304 : relinfo->relkind = relkind;
3584 : :
3585 [ + + + - ]: 304 : if (relkind != RELKIND_SEQUENCE &&
3586 [ + + ]: 287 : check_columnlist &&
3587 : 287 : list_member_rangevar(relationlist, relinfo->rv))
3588 [ + - ]: 1 : ereport(ERROR,
3589 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3590 : : errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
3591 : : nspname, relname));
3592 : : else
3593 : 303 : relationlist = lappend(relationlist, relinfo);
3594 : :
3595 : 303 : ExecClearTuple(slot);
3596 : : }
3597 : 163 : ExecDropSingleTupleTableSlot(slot);
3598 : :
3599 : 163 : walrcv_clear_result(res);
3600 : :
3601 : 163 : return relationlist;
3602 : : }
3603 : :
3604 : : /*
3605 : : * This is to report the connection failure while dropping replication slots.
3606 : : * Here, we report the WARNING for all tablesync slots so that user can drop
3607 : : * them manually, if required.
3608 : : */
3609 : : static void
3610 : 4 : ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
3611 : : {
3612 : : ListCell *lc;
3613 : :
3614 [ - + - - : 4 : foreach(lc, rstates)
- + ]
3615 : : {
3616 : 0 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
3617 : 0 : Oid relid = rstate->relid;
3618 : :
3619 : : /* Only cleanup resources of tablesync workers */
3620 [ # # ]: 0 : if (!OidIsValid(relid))
3621 : 0 : continue;
3622 : :
3623 : : /*
3624 : : * Caller needs to ensure that relstate doesn't change underneath us.
3625 : : * See DropSubscription where we get the relstates.
3626 : : */
3627 [ # # ]: 0 : if (rstate->state != SUBREL_STATE_SYNCDONE)
3628 : : {
3629 : 0 : char syncslotname[NAMEDATALEN] = {0};
3630 : :
3631 : 0 : ReplicationSlotNameForTablesync(subid, relid, syncslotname,
3632 : : sizeof(syncslotname));
3633 [ # # ]: 0 : elog(WARNING, "could not drop tablesync replication slot \"%s\"",
3634 : : syncslotname);
3635 : : }
3636 : : }
3637 : :
3638 [ + - ]: 4 : ereport(ERROR,
3639 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3640 : : errmsg("could not connect to publisher when attempting to drop replication slot \"%s\": %s",
3641 : : slotname, err),
3642 : : /* translator: %s is an SQL ALTER command */
3643 : : errhint("Use %s to disable the subscription, and then use %s to disassociate it from the slot.",
3644 : : "ALTER SUBSCRIPTION ... DISABLE",
3645 : : "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
3646 : : }
3647 : :
3648 : : /*
3649 : : * Check for duplicates in the given list of publications and error out if
3650 : : * found one. Add publications to datums as text datums, if datums is not
3651 : : * NULL.
3652 : : */
3653 : : static void
3654 : 286 : check_duplicates_in_publist(List *publist, Datum *datums)
3655 : : {
3656 : : ListCell *cell;
3657 : 286 : int j = 0;
3658 : :
3659 [ + - + + : 646 : foreach(cell, publist)
+ + ]
3660 : : {
3661 : 372 : char *name = strVal(lfirst(cell));
3662 : : ListCell *pcell;
3663 : :
3664 [ + - + - : 535 : foreach(pcell, publist)
+ - ]
3665 : : {
3666 : 535 : char *pname = strVal(lfirst(pcell));
3667 : :
3668 [ + + ]: 535 : if (pcell == cell)
3669 : 360 : break;
3670 : :
3671 [ + + ]: 175 : if (strcmp(name, pname) == 0)
3672 [ + - ]: 12 : ereport(ERROR,
3673 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
3674 : : errmsg("publication name \"%s\" used more than once",
3675 : : pname)));
3676 : : }
3677 : :
3678 [ + + ]: 360 : if (datums)
3679 : 304 : datums[j++] = CStringGetTextDatum(name);
3680 : : }
3681 : 274 : }
3682 : :
3683 : : /*
3684 : : * Merge current subscription's publications and user-specified publications
3685 : : * from ADD/DROP PUBLICATIONS.
3686 : : *
3687 : : * If addpub is true, we will add the list of publications into oldpublist.
3688 : : * Otherwise, we will delete the list of publications from oldpublist. The
3689 : : * returned list is a copy, oldpublist itself is not changed.
3690 : : *
3691 : : * subname is the subscription name, for error messages.
3692 : : */
3693 : : static List *
3694 : 35 : merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
3695 : : {
3696 : : ListCell *lc;
3697 : :
3698 : 35 : oldpublist = list_copy(oldpublist);
3699 : :
3700 : 35 : check_duplicates_in_publist(newpublist, NULL);
3701 : :
3702 [ + - + + : 59 : foreach(lc, newpublist)
+ + ]
3703 : : {
3704 : 44 : char *name = strVal(lfirst(lc));
3705 : : ListCell *lc2;
3706 : 44 : bool found = false;
3707 : :
3708 [ + - + + : 86 : foreach(lc2, oldpublist)
+ + ]
3709 : : {
3710 : 71 : char *pubname = strVal(lfirst(lc2));
3711 : :
3712 [ + + ]: 71 : if (strcmp(name, pubname) == 0)
3713 : : {
3714 : 29 : found = true;
3715 [ + + ]: 29 : if (addpub)
3716 [ + - ]: 8 : ereport(ERROR,
3717 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
3718 : : errmsg("publication \"%s\" is already in subscription \"%s\"",
3719 : : name, subname)));
3720 : : else
3721 : 21 : oldpublist = foreach_delete_current(oldpublist, lc2);
3722 : :
3723 : 21 : break;
3724 : : }
3725 : : }
3726 : :
3727 [ + + + - ]: 36 : if (addpub && !found)
3728 : 11 : oldpublist = lappend(oldpublist, makeString(name));
3729 [ + - + + ]: 25 : else if (!addpub && !found)
3730 [ + - ]: 4 : ereport(ERROR,
3731 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3732 : : errmsg("publication \"%s\" is not in subscription \"%s\"",
3733 : : name, subname)));
3734 : : }
3735 : :
3736 : : /*
3737 : : * XXX Probably no strong reason for this, but for now it's to make ALTER
3738 : : * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
3739 : : */
3740 [ + + ]: 15 : if (!oldpublist)
3741 [ + - ]: 4 : ereport(ERROR,
3742 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3743 : : errmsg("cannot drop all the publications from a subscription")));
3744 : :
3745 : 11 : return oldpublist;
3746 : : }
3747 : :
3748 : : /*
3749 : : * Extract the streaming mode value from a DefElem. This is like
3750 : : * defGetBoolean() but also accepts the special value of "parallel".
3751 : : */
3752 : : char
3753 : 498 : defGetStreamingMode(DefElem *def)
3754 : : {
3755 : : /*
3756 : : * If no parameter value given, assume "true" is meant.
3757 : : */
3758 [ - + ]: 498 : if (!def->arg)
3759 : 0 : return LOGICALREP_STREAM_ON;
3760 : :
3761 : : /*
3762 : : * Allow 0, 1, "false", "true", "off", "on" or "parallel".
3763 : : */
3764 [ - + ]: 498 : switch (nodeTag(def->arg))
3765 : : {
3766 : 0 : case T_Integer:
3767 [ # # # ]: 0 : switch (intVal(def->arg))
3768 : : {
3769 : 0 : case 0:
3770 : 0 : return LOGICALREP_STREAM_OFF;
3771 : 0 : case 1:
3772 : 0 : return LOGICALREP_STREAM_ON;
3773 : 0 : default:
3774 : : /* otherwise, error out below */
3775 : 0 : break;
3776 : : }
3777 : 0 : break;
3778 : 498 : default:
3779 : : {
3780 : 498 : 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 [ + + + + ]: 992 : if (pg_strcasecmp(sval, "false") == 0 ||
3787 : 494 : pg_strcasecmp(sval, "off") == 0)
3788 : 7 : return LOGICALREP_STREAM_OFF;
3789 [ + + + + ]: 970 : if (pg_strcasecmp(sval, "true") == 0 ||
3790 : 479 : pg_strcasecmp(sval, "on") == 0)
3791 : 48 : return LOGICALREP_STREAM_ON;
3792 [ + + ]: 443 : if (pg_strcasecmp(sval, "parallel") == 0)
3793 : 439 : return LOGICALREP_STREAM_PARALLEL;
3794 : : }
3795 : 4 : break;
3796 : : }
3797 : :
3798 [ + - ]: 4 : ereport(ERROR,
3799 : : (errcode(ERRCODE_SYNTAX_ERROR),
3800 : : errmsg("%s requires a Boolean value or \"parallel\"",
3801 : : def->defname)));
3802 : : return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
3803 : : }
|