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/injection_point.h"
58 : : #include "utils/lsyscache.h"
59 : : #include "utils/memutils.h"
60 : : #include "utils/pg_lsn.h"
61 : : #include "utils/syscache.h"
62 : :
63 : : /*
64 : : * Options that can be specified by the user in CREATE/ALTER SUBSCRIPTION
65 : : * command.
66 : : */
67 : : #define SUBOPT_CONNECT 0x00000001
68 : : #define SUBOPT_ENABLED 0x00000002
69 : : #define SUBOPT_CREATE_SLOT 0x00000004
70 : : #define SUBOPT_SLOT_NAME 0x00000008
71 : : #define SUBOPT_COPY_DATA 0x00000010
72 : : #define SUBOPT_SYNCHRONOUS_COMMIT 0x00000020
73 : : #define SUBOPT_REFRESH 0x00000040
74 : : #define SUBOPT_BINARY 0x00000080
75 : : #define SUBOPT_STREAMING 0x00000100
76 : : #define SUBOPT_TWOPHASE_COMMIT 0x00000200
77 : : #define SUBOPT_DISABLE_ON_ERR 0x00000400
78 : : #define SUBOPT_PASSWORD_REQUIRED 0x00000800
79 : : #define SUBOPT_RUN_AS_OWNER 0x00001000
80 : : #define SUBOPT_FAILOVER 0x00002000
81 : : #define SUBOPT_RETAIN_DEAD_TUPLES 0x00004000
82 : : #define SUBOPT_MAX_RETENTION_DURATION 0x00008000
83 : : #define SUBOPT_WAL_RECEIVER_TIMEOUT 0x00010000
84 : : #define SUBOPT_LSN 0x00020000
85 : : #define SUBOPT_ORIGIN 0x00040000
86 : : #define SUBOPT_CONFLICT_LOG_DEST 0x00080000
87 : :
88 : : /* check if the 'val' has 'bits' set */
89 : : #define IsSet(val, bits) (((val) & (bits)) == (bits))
90 : :
91 : : /*
92 : : * Structure to hold a bitmap representing the user-provided CREATE/ALTER
93 : : * SUBSCRIPTION command options and the parsed/default values of each of them.
94 : : */
95 : : typedef struct SubOpts
96 : : {
97 : : uint32 specified_opts;
98 : : char *slot_name;
99 : : char *synchronous_commit;
100 : : bool connect;
101 : : bool enabled;
102 : : bool create_slot;
103 : : bool copy_data;
104 : : bool refresh;
105 : : bool binary;
106 : : char streaming;
107 : : bool twophase;
108 : : bool disableonerr;
109 : : bool passwordrequired;
110 : : bool runasowner;
111 : : bool failover;
112 : : bool retaindeadtuples;
113 : : int32 maxretention;
114 : : char *origin;
115 : : ConflictLogDest conflictlogdest;
116 : : XLogRecPtr lsn;
117 : : char *wal_receiver_timeout;
118 : : } SubOpts;
119 : :
120 : : /*
121 : : * PublicationRelKind represents a relation included in a publication.
122 : : * It stores the schema-qualified relation name (rv) and its kind (relkind).
123 : : */
124 : : typedef struct PublicationRelKind
125 : : {
126 : : RangeVar *rv;
127 : : char relkind;
128 : : } PublicationRelKind;
129 : :
130 : : static List *fetch_relation_list(WalReceiverConn *wrconn, List *publications);
131 : : static void check_publications_origin_tables(WalReceiverConn *wrconn,
132 : : List *publications, bool copydata,
133 : : bool retain_dead_tuples,
134 : : char *origin,
135 : : Oid *subrel_local_oids,
136 : : int subrel_count, char *subname);
137 : : static void check_publications_origin_sequences(WalReceiverConn *wrconn,
138 : : List *publications,
139 : : bool copydata, char *origin,
140 : : Oid *subrel_local_oids,
141 : : int subrel_count,
142 : : char *subname);
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 : 749 : 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 : 749 : 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 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_CONNECT))
180 : 338 : opts->connect = true;
181 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_ENABLED))
182 : 425 : opts->enabled = true;
183 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
184 : 338 : opts->create_slot = true;
185 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_COPY_DATA))
186 : 438 : opts->copy_data = true;
187 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_REFRESH))
188 : 58 : opts->refresh = true;
189 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_BINARY))
190 : 547 : opts->binary = false;
191 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_STREAMING))
192 : 547 : opts->streaming = LOGICALREP_STREAM_PARALLEL;
193 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
194 : 547 : opts->twophase = false;
195 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
196 : 547 : opts->disableonerr = false;
197 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED))
198 : 547 : opts->passwordrequired = true;
199 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER))
200 : 547 : opts->runasowner = false;
201 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_FAILOVER))
202 : 547 : opts->failover = false;
203 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_RETAIN_DEAD_TUPLES))
204 : 547 : opts->retaindeadtuples = false;
205 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_MAX_RETENTION_DURATION))
206 : 547 : opts->maxretention = 0;
207 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_ORIGIN))
208 : 547 : opts->origin = pstrdup(LOGICALREP_ORIGIN_ANY);
209 [ + + ]: 749 : if (IsSet(supported_opts, SUBOPT_CONFLICT_LOG_DEST))
210 : 547 : opts->conflictlogdest = CONFLICT_LOG_DEST_LOG;
211 : :
212 : : /* Parse options */
213 [ + + + + : 1514 : foreach(lc, stmt_options)
+ + ]
214 : : {
215 : 829 : DefElem *defel = (DefElem *) lfirst(lc);
216 : :
217 [ + + ]: 829 : if (IsSet(supported_opts, SUBOPT_CONNECT) &&
218 [ + + ]: 463 : strcmp(defel->defname, "connect") == 0)
219 : : {
220 [ - + ]: 171 : if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
221 : 0 : errorConflictingDefElem(defel, pstate);
222 : :
223 : 171 : opts->specified_opts |= SUBOPT_CONNECT;
224 : 171 : opts->connect = defGetBoolean(defel);
225 : : }
226 [ + + ]: 658 : else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
227 [ + + ]: 379 : strcmp(defel->defname, "enabled") == 0)
228 : : {
229 [ - + ]: 111 : if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
230 : 0 : errorConflictingDefElem(defel, pstate);
231 : :
232 : 111 : opts->specified_opts |= SUBOPT_ENABLED;
233 : 111 : opts->enabled = defGetBoolean(defel);
234 : : }
235 [ + + ]: 547 : else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
236 [ + + ]: 268 : 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 [ + + ]: 522 : else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
245 [ + + ]: 454 : strcmp(defel->defname, "slot_name") == 0)
246 : : {
247 [ - + ]: 143 : if (IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
248 : 0 : errorConflictingDefElem(defel, pstate);
249 : :
250 : 143 : opts->specified_opts |= SUBOPT_SLOT_NAME;
251 : 143 : opts->slot_name = defGetString(defel);
252 : :
253 : : /* Setting slot_name = NONE is treated as no slot name. */
254 [ + + ]: 282 : if (strcmp(opts->slot_name, "none") == 0)
255 : 115 : opts->slot_name = NULL;
256 : : else
257 : 28 : ReplicationSlotValidateName(opts->slot_name, false, ERROR);
258 : : }
259 [ + + ]: 379 : else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
260 [ + + ]: 229 : strcmp(defel->defname, "copy_data") == 0)
261 : : {
262 [ - + ]: 32 : if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
263 : 0 : errorConflictingDefElem(defel, pstate);
264 : :
265 : 32 : opts->specified_opts |= SUBOPT_COPY_DATA;
266 : 32 : opts->copy_data = defGetBoolean(defel);
267 : : }
268 [ + + ]: 347 : else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
269 [ + + ]: 284 : strcmp(defel->defname, "synchronous_commit") == 0)
270 : : {
271 [ - + ]: 16 : if (IsSet(opts->specified_opts, SUBOPT_SYNCHRONOUS_COMMIT))
272 : 0 : errorConflictingDefElem(defel, pstate);
273 : :
274 : 16 : opts->specified_opts |= SUBOPT_SYNCHRONOUS_COMMIT;
275 : 16 : opts->synchronous_commit = defGetString(defel);
276 : :
277 : : /* Test if the given value is valid for synchronous_commit GUC. */
278 : 16 : (void) set_config_option("synchronous_commit", opts->synchronous_commit,
279 : : PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
280 : : false, 0, false);
281 : : }
282 [ + + ]: 331 : else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
283 [ + - ]: 48 : strcmp(defel->defname, "refresh") == 0)
284 : : {
285 [ - + ]: 48 : if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
286 : 0 : errorConflictingDefElem(defel, pstate);
287 : :
288 : 48 : opts->specified_opts |= SUBOPT_REFRESH;
289 : 48 : opts->refresh = defGetBoolean(defel);
290 : : }
291 [ + + ]: 283 : else if (IsSet(supported_opts, SUBOPT_BINARY) &&
292 [ + + ]: 268 : 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 [ + + ]: 264 : else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
301 [ + + ]: 249 : 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 [ + + ]: 221 : else if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT) &&
310 [ + + ]: 206 : 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 [ + + ]: 197 : else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
319 [ + + ]: 182 : strcmp(defel->defname, "disable_on_error") == 0)
320 : : {
321 [ - + ]: 21 : if (IsSet(opts->specified_opts, SUBOPT_DISABLE_ON_ERR))
322 : 0 : errorConflictingDefElem(defel, pstate);
323 : :
324 : 21 : opts->specified_opts |= SUBOPT_DISABLE_ON_ERR;
325 : 21 : opts->disableonerr = defGetBoolean(defel);
326 : : }
327 [ + + ]: 176 : else if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED) &&
328 [ + + ]: 161 : strcmp(defel->defname, "password_required") == 0)
329 : : {
330 [ - + ]: 17 : if (IsSet(opts->specified_opts, SUBOPT_PASSWORD_REQUIRED))
331 : 0 : errorConflictingDefElem(defel, pstate);
332 : :
333 : 17 : opts->specified_opts |= SUBOPT_PASSWORD_REQUIRED;
334 : 17 : opts->passwordrequired = defGetBoolean(defel);
335 : : }
336 [ + + ]: 159 : else if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER) &&
337 [ + + ]: 144 : 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 [ + + ]: 148 : else if (IsSet(supported_opts, SUBOPT_FAILOVER) &&
346 [ + + ]: 133 : 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 [ + + ]: 132 : else if (IsSet(supported_opts, SUBOPT_RETAIN_DEAD_TUPLES) &&
355 [ + + ]: 117 : strcmp(defel->defname, "retain_dead_tuples") == 0)
356 : : {
357 [ - + ]: 15 : if (IsSet(opts->specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
358 : 0 : errorConflictingDefElem(defel, pstate);
359 : :
360 : 15 : opts->specified_opts |= SUBOPT_RETAIN_DEAD_TUPLES;
361 : 15 : opts->retaindeadtuples = defGetBoolean(defel);
362 : : }
363 [ + + ]: 117 : else if (IsSet(supported_opts, SUBOPT_MAX_RETENTION_DURATION) &&
364 [ + + ]: 102 : 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("option \"%s\" cannot be negative", "max_retention_duration"));
376 : : }
377 [ + + ]: 95 : else if (IsSet(supported_opts, SUBOPT_ORIGIN) &&
378 [ + + ]: 80 : strcmp(defel->defname, "origin") == 0)
379 : : {
380 [ - + ]: 26 : if (IsSet(opts->specified_opts, SUBOPT_ORIGIN))
381 : 0 : errorConflictingDefElem(defel, pstate);
382 : :
383 : 26 : opts->specified_opts |= SUBOPT_ORIGIN;
384 : 26 : 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 : 26 : opts->origin = defGetString(defel);
393 : :
394 [ + + + + ]: 36 : 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 [ + + + + ]: 685 : if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
474 : : {
475 : : /* Check for incompatible options from the user. */
476 [ + - ]: 131 : if (opts->enabled &&
477 [ + + ]: 131 : 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 [ + + ]: 127 : if (opts->create_slot &&
485 [ + + ]: 123 : 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 [ + + ]: 123 : if (opts->copy_data &&
492 [ + + ]: 119 : 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 : 119 : opts->enabled = false;
500 : 119 : opts->create_slot = false;
501 : 119 : opts->copy_data = false;
502 : : }
503 : :
504 : : /*
505 : : * Do additional checking for disallowed combination when slot_name = NONE
506 : : * was used.
507 : : */
508 [ + + ]: 673 : if (!opts->slot_name &&
509 [ + + ]: 649 : IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
510 : : {
511 [ + + ]: 111 : 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 [ + + ]: 99 : 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 : 653 : }
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 : 301 : appendQuotedString(StringInfo buf, const char *str, char quote)
555 : : {
556 : 301 : appendStringInfoChar(buf, quote);
557 [ + + ]: 9598 : while (*str)
558 : : {
559 : 9297 : char c = *str++;
560 : :
561 [ - + ]: 9297 : if (c == quote)
562 : 0 : appendStringInfoChar(buf, c);
563 : 9297 : appendStringInfoChar(buf, c);
564 : : }
565 : 301 : appendStringInfoChar(buf, quote);
566 : 301 : }
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 : 139 : check_publications(WalReceiverConn *wrconn, List *publications)
576 : : {
577 : : WalRcvExecResult *res;
578 : : StringInfoData cmd;
579 : : TupleTableSlot *slot;
580 : 139 : List *publicationsCopy = NIL;
581 : 139 : Oid tableRow[1] = {TEXTOID};
582 : :
583 : 139 : initStringInfo(&cmd);
584 : 139 : appendStringInfoString(&cmd, "SELECT t.pubname FROM\n"
585 : : " pg_catalog.pg_publication t WHERE\n"
586 : : " t.pubname IN (");
587 : 139 : GetPublicationsStr(publications, &cmd, true);
588 : 139 : appendStringInfoChar(&cmd, ')');
589 : :
590 : 139 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
591 : 139 : pfree(cmd.data);
592 : :
593 [ - + ]: 139 : 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 : 139 : publicationsCopy = list_copy(publications);
599 : :
600 : : /* Process publication(s). */
601 : 139 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
602 [ + + ]: 309 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
603 : : {
604 : : char *pubname;
605 : : bool isnull;
606 : :
607 : 170 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
608 : : Assert(!isnull);
609 : :
610 : : /* Delete the publication present in publisher from the list. */
611 : 170 : publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
612 : 170 : ExecClearTuple(slot);
613 : : }
614 : :
615 : 139 : ExecDropSingleTupleTableSlot(slot);
616 : :
617 : 139 : walrcv_clear_result(res);
618 : :
619 [ + + ]: 139 : 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 : 139 : }
635 : :
636 : : /*
637 : : * Auxiliary function to build a text array out of a list of String nodes.
638 : : */
639 : : static Datum
640 : 259 : 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 : 259 : memcxt = AllocSetContextCreate(CurrentMemoryContext,
649 : : "publicationListToArray to array",
650 : : ALLOCSET_DEFAULT_SIZES);
651 : 259 : oldcxt = MemoryContextSwitchTo(memcxt);
652 : :
653 : 259 : datums = palloc_array(Datum, list_length(publist));
654 : :
655 : 259 : check_duplicates_in_publist(publist, datums);
656 : :
657 : 255 : MemoryContextSwitchTo(oldcxt);
658 : :
659 : 255 : arr = construct_array_builtin(datums, list_length(publist), TEXTOID);
660 : :
661 : 255 : MemoryContextDelete(memcxt);
662 : :
663 : 255 : 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 : 338 : Oid serverid = InvalidOid;
681 : 338 : char *conninfo = NULL;
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 : 142 : 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 [ + - ]: 4 : 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 : 246 : CheckSubDeadTupleRetention(true, !opts.enabled, WARNING,
775 : 246 : opts.retaindeadtuples, opts.retaindeadtuples,
776 : 246 : (opts.maxretention > 0));
777 : :
778 [ + + ]: 246 : if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
779 [ + - ]: 203 : opts.slot_name == NULL)
780 : 203 : opts.slot_name = stmt->subname;
781 : :
782 : : /* The default for synchronous_commit of subscriptions is off. */
783 [ + - ]: 246 : if (opts.synchronous_commit == NULL)
784 : 246 : 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 [ + - ]: 246 : if (opts.wal_receiver_timeout == NULL)
792 : 246 : opts.wal_receiver_timeout = "-1";
793 : :
794 : : /* Load the library providing us libpq calls. */
795 : 246 : load_file("libpqwalreceiver", false);
796 : :
797 [ + + ]: 246 : if (stmt->servername)
798 : : {
799 : : ForeignServer *server;
800 : :
801 : : Assert(!stmt->conninfo);
802 : :
803 : 20 : server = GetForeignServerByName(stmt->servername, false);
804 : 20 : serverid = server->serverid;
805 : :
806 : : /* check USAGE privileges on server */
807 : 20 : aclresult = object_aclcheck(ForeignServerRelationId, serverid, owner, ACL_USAGE);
808 [ + + ]: 20 : if (aclresult != ACLCHECK_OK)
809 : 4 : aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, server->servername);
810 : :
811 : : /* check user mapping */
812 : 16 : GetUserMappingExtended(owner, server->serverid, WARNING);
813 : :
814 : : /*
815 : : * Check conninfo if connecting; otherwise only check that the
816 : : * server's FDW supports connections.
817 : : */
818 [ + + ]: 16 : if (opts.connect)
819 : : {
820 : 2 : conninfo = ForeignServerConnectionString(owner, server);
821 [ - + - - ]: 1 : walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
822 : : }
823 : : else
824 : : {
825 : 14 : ForeignDataWrapper *fdw = GetForeignDataWrapper(server->fdwid);
826 : :
827 [ + + ]: 14 : if (!OidIsValid(fdw->fdwconnection))
828 [ + - ]: 4 : ereport(ERROR,
829 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
830 : : errmsg("foreign-data wrapper \"%s\" does not support subscription connections",
831 : : fdw->fdwname),
832 : : errdetail("Foreign-data wrapper must be defined with CONNECTION specified.")));
833 : : }
834 : : }
835 : : else
836 : : {
837 : : Assert(stmt->conninfo);
838 : :
839 : 226 : conninfo = stmt->conninfo;
840 [ + + + + ]: 226 : walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
841 : : }
842 : :
843 : 225 : publications = stmt->publication;
844 : :
845 : : /* Everything ok, form a new tuple. */
846 : 225 : memset(values, 0, sizeof(values));
847 : 225 : memset(nulls, false, sizeof(nulls));
848 : :
849 : 225 : subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
850 : : Anum_pg_subscription_oid);
851 : 225 : values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
852 : 225 : values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
853 : 225 : values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
854 : 225 : values[Anum_pg_subscription_subname - 1] =
855 : 225 : DirectFunctionCall1(namein, CStringGetDatum(stmt->subname));
856 : 225 : values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
857 : 225 : values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
858 : 225 : values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
859 : 225 : values[Anum_pg_subscription_substream - 1] = CharGetDatum(opts.streaming);
860 : 225 : values[Anum_pg_subscription_subtwophasestate - 1] =
861 [ + + ]: 225 : CharGetDatum(opts.twophase ?
862 : : LOGICALREP_TWOPHASE_STATE_PENDING :
863 : : LOGICALREP_TWOPHASE_STATE_DISABLED);
864 : 225 : values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
865 : 225 : values[Anum_pg_subscription_subpasswordrequired - 1] = BoolGetDatum(opts.passwordrequired);
866 : 225 : values[Anum_pg_subscription_subrunasowner - 1] = BoolGetDatum(opts.runasowner);
867 : 225 : values[Anum_pg_subscription_subfailover - 1] = BoolGetDatum(opts.failover);
868 : 225 : values[Anum_pg_subscription_subretaindeadtuples - 1] =
869 : 225 : BoolGetDatum(opts.retaindeadtuples);
870 : 225 : values[Anum_pg_subscription_submaxretention - 1] =
871 : 225 : Int32GetDatum(opts.maxretention);
872 : 225 : values[Anum_pg_subscription_subretentionactive - 1] =
873 : 225 : BoolGetDatum(opts.retaindeadtuples);
874 : 225 : values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(serverid);
875 [ + + ]: 225 : if (stmt->conninfo)
876 : : {
877 : : Assert(stmt->conninfo == conninfo && !OidIsValid(serverid));
878 : 214 : values[Anum_pg_subscription_subconninfo - 1] =
879 : 214 : CStringGetTextDatum(stmt->conninfo);
880 : : }
881 : : else
882 : : {
883 : : Assert(OidIsValid(serverid));
884 : 11 : nulls[Anum_pg_subscription_subconninfo - 1] = true;
885 : : }
886 [ + + ]: 225 : if (opts.slot_name)
887 : 210 : values[Anum_pg_subscription_subslotname - 1] =
888 : 210 : DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
889 : : else
890 : 15 : nulls[Anum_pg_subscription_subslotname - 1] = true;
891 : 225 : values[Anum_pg_subscription_subsynccommit - 1] =
892 : 225 : CStringGetTextDatum(opts.synchronous_commit);
893 : 225 : values[Anum_pg_subscription_subwalrcvtimeout - 1] =
894 : 225 : CStringGetTextDatum(opts.wal_receiver_timeout);
895 : 221 : values[Anum_pg_subscription_subpublications - 1] =
896 : 225 : publicationListToArray(publications);
897 : 221 : values[Anum_pg_subscription_suborigin - 1] =
898 : 221 : CStringGetTextDatum(opts.origin);
899 : :
900 : 221 : values[Anum_pg_subscription_subconflictlogdest - 1] =
901 : 221 : CStringGetTextDatum(ConflictLogDestNames[opts.conflictlogdest]);
902 : :
903 : : /*
904 : : * We create the conflict log table here, if required, so that its
905 : : * relation OID can be stored when inserting the pg_subscription tuple
906 : : * below.
907 : : */
908 [ + + + + ]: 221 : if (CONFLICTS_LOGGED_TO_TABLE(opts.conflictlogdest))
909 : 10 : logrelid = create_conflict_log_table(subid, stmt->subname, owner);
910 : :
911 : : /* Store table OID in the catalog. */
912 : 221 : values[Anum_pg_subscription_subconflictlogrelid - 1] =
913 : 221 : ObjectIdGetDatum(logrelid);
914 : :
915 : 221 : tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
916 : :
917 : : /* Insert tuple into catalog. */
918 : 221 : CatalogTupleInsert(rel, tup);
919 : 221 : heap_freetuple(tup);
920 : :
921 : 221 : recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
922 : :
923 : 221 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
924 : :
925 [ + + ]: 221 : if (stmt->servername)
926 : : {
927 : : ObjectAddress referenced;
928 : :
929 : : Assert(OidIsValid(serverid));
930 : :
931 : 11 : ObjectAddressSet(referenced, ForeignServerRelationId, serverid);
932 : 11 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
933 : : }
934 : :
935 : : /*
936 : : * Establish an internal dependency between the conflict log table and the
937 : : * subscription.
938 : : *
939 : : * We use DEPENDENCY_INTERNAL to signify that the table's lifecycle is
940 : : * strictly tied to the subscription, similar to how a TOAST table relates
941 : : * to its main table or a sequence relates to an identity column.
942 : : *
943 : : * This ensures the conflict log table is automatically reaped during a
944 : : * DROP SUBSCRIPTION via performDeletion().
945 : : */
946 [ + + ]: 221 : if (OidIsValid(logrelid))
947 : : {
948 : : ObjectAddress cltaddr;
949 : :
950 : 10 : ObjectAddressSet(cltaddr, RelationRelationId, logrelid);
951 : 10 : recordDependencyOn(&cltaddr, &myself, DEPENDENCY_INTERNAL);
952 : : }
953 : :
954 : : /*
955 : : * A replication origin is currently created for all subscriptions,
956 : : * including those that only contain sequences or are otherwise empty.
957 : : *
958 : : * XXX: While this is technically unnecessary, optimizing it would require
959 : : * additional logic to skip origin creation during DDL operations and
960 : : * apply workers initialization, and to handle origin creation dynamically
961 : : * when tables are added to the subscription. It is not clear whether
962 : : * preventing creation of origins is worth additional complexity.
963 : : */
964 : 221 : ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
965 : 221 : replorigin_create(originname);
966 : :
967 : : /*
968 : : * Connect to remote side to execute requested commands and fetch table
969 : : * and sequence info.
970 : : */
971 [ + + ]: 221 : if (opts.connect)
972 : : {
973 : : char *err;
974 : : WalReceiverConn *wrconn;
975 : : bool must_use_password;
976 : :
977 : : /* Try to connect to the publisher. */
978 [ - + - - ]: 134 : must_use_password = !superuser_arg(owner) && opts.passwordrequired;
979 : 134 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
980 : : stmt->subname, &err);
981 [ + + ]: 134 : if (!wrconn)
982 [ + - ]: 4 : ereport(ERROR,
983 : : (errcode(ERRCODE_CONNECTION_FAILURE),
984 : : errmsg("subscription \"%s\" could not connect to the publisher: %s",
985 : : stmt->subname, err)));
986 : :
987 [ + + ]: 130 : PG_TRY();
988 : : {
989 : 130 : bool has_tables = false;
990 : : List *pubrels;
991 : : char relation_state;
992 : :
993 : 130 : check_publications(wrconn, publications);
994 : 130 : check_publications_origin_tables(wrconn, publications,
995 : 130 : opts.copy_data,
996 : 130 : opts.retaindeadtuples, opts.origin,
997 : : NULL, 0, stmt->subname);
998 : 130 : check_publications_origin_sequences(wrconn, publications,
999 : 130 : opts.copy_data, opts.origin,
1000 : : NULL, 0, stmt->subname);
1001 : :
1002 [ + + ]: 130 : if (opts.retaindeadtuples)
1003 : 4 : CheckPubDeadTupleRetention(wrconn);
1004 : :
1005 : : /*
1006 : : * Set sync state based on if we were asked to do data copy or
1007 : : * not.
1008 : : */
1009 [ + + ]: 130 : relation_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
1010 : :
1011 : : /*
1012 : : * Build local relation status info. Relations are for both tables
1013 : : * and sequences from the publisher.
1014 : : */
1015 : 130 : pubrels = fetch_relation_list(wrconn, publications);
1016 : :
1017 [ + + + + : 460 : foreach_ptr(PublicationRelKind, pubrelinfo, pubrels)
+ + ]
1018 : : {
1019 : : Oid relid;
1020 : : char relkind;
1021 : 202 : RangeVar *rv = pubrelinfo->rv;
1022 : :
1023 : 202 : relid = RangeVarGetRelid(rv, AccessShareLock, false);
1024 : 202 : relkind = get_rel_relkind(relid);
1025 : :
1026 : : /* Check for supported relkind. */
1027 : 202 : CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
1028 : 202 : rv->schemaname, rv->relname);
1029 : 202 : has_tables |= (relkind != RELKIND_SEQUENCE);
1030 : 202 : AddSubscriptionRelState(subid, relid, relation_state,
1031 : : InvalidXLogRecPtr, true);
1032 : : }
1033 : :
1034 : : /*
1035 : : * If requested, create permanent slot for the subscription. We
1036 : : * won't use the initial snapshot for anything, so no need to
1037 : : * export it.
1038 : : *
1039 : : * XXX: Similar to origins, it is not clear whether preventing the
1040 : : * slot creation for empty and sequence-only subscriptions is
1041 : : * worth additional complexity.
1042 : : */
1043 [ + + ]: 129 : if (opts.create_slot)
1044 : : {
1045 : 124 : bool twophase_enabled = false;
1046 : :
1047 : : Assert(opts.slot_name);
1048 : :
1049 : : /*
1050 : : * Even if two_phase is set, don't create the slot with
1051 : : * two-phase enabled. Will enable it once all the tables are
1052 : : * synced and ready. This avoids race-conditions like prepared
1053 : : * transactions being skipped due to changes not being applied
1054 : : * due to checks in should_apply_changes_for_rel() when
1055 : : * tablesync for the corresponding tables are in progress. See
1056 : : * comments atop worker.c.
1057 : : *
1058 : : * Note that if tables were specified but copy_data is false
1059 : : * then it is safe to enable two_phase up-front because those
1060 : : * tables are already initially in READY state. When the
1061 : : * subscription has no tables, we leave the twophase state as
1062 : : * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
1063 : : * PUBLICATION to work.
1064 : : */
1065 [ + + + + : 124 : if (opts.twophase && !opts.copy_data && has_tables)
+ - ]
1066 : 1 : twophase_enabled = true;
1067 : :
1068 : 124 : walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
1069 : : opts.failover, CRS_NOEXPORT_SNAPSHOT, NULL);
1070 : :
1071 [ + + ]: 124 : if (twophase_enabled)
1072 : 1 : UpdateTwoPhaseState(subid, LOGICALREP_TWOPHASE_STATE_ENABLED);
1073 : :
1074 [ + - ]: 124 : ereport(NOTICE,
1075 : : (errmsg("created replication slot \"%s\" on publisher",
1076 : : opts.slot_name)));
1077 : : }
1078 : : }
1079 : 1 : PG_FINALLY();
1080 : : {
1081 : 130 : walrcv_disconnect(wrconn);
1082 : : }
1083 [ + + ]: 130 : PG_END_TRY();
1084 : : }
1085 : : else
1086 [ + - ]: 87 : ereport(WARNING,
1087 : : (errmsg("subscription was created, but is not connected"),
1088 : : errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and alter the subscription to refresh publications.")));
1089 : :
1090 : 216 : table_close(rel, RowExclusiveLock);
1091 : :
1092 : 216 : pgstat_create_subscription(subid);
1093 : :
1094 : : /*
1095 : : * Notify the launcher to start the apply worker if the subscription is
1096 : : * enabled, or to create the conflict detection slot if retain_dead_tuples
1097 : : * is enabled.
1098 : : *
1099 : : * Creating the conflict detection slot is essential even when the
1100 : : * subscription is not enabled. This ensures that dead tuples are
1101 : : * retained, which is necessary for accurately identifying the type of
1102 : : * conflict during replication.
1103 : : */
1104 [ + + + + ]: 216 : if (opts.enabled || opts.retaindeadtuples)
1105 : 123 : ApplyLauncherWakeupAtCommit();
1106 : :
1107 [ - + ]: 216 : InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
1108 : :
1109 : 216 : return myself;
1110 : : }
1111 : :
1112 : : static void
1113 : 40 : AlterSubscription_refresh(Subscription *sub, bool copy_data,
1114 : : List *validate_publications, char *conninfo)
1115 : : {
1116 : : char *err;
1117 : 40 : List *pubrels = NIL;
1118 : : Oid *pubrel_local_oids;
1119 : : List *subrel_states;
1120 : 40 : List *sub_remove_rels = NIL;
1121 : : Oid *subrel_local_oids;
1122 : : Oid *subseq_local_oids;
1123 : : int subrel_count;
1124 : : ListCell *lc;
1125 : : int off;
1126 : 40 : int tbl_count = 0;
1127 : 40 : int seq_count = 0;
1128 : 40 : Relation rel = NULL;
1129 : : typedef struct SubRemoveRels
1130 : : {
1131 : : Oid relid;
1132 : : char state;
1133 : : } SubRemoveRels;
1134 : :
1135 : : WalReceiverConn *wrconn;
1136 : : bool must_use_password;
1137 : :
1138 : : /*
1139 : : * Should not happen: CREATE/ALTER/DROP SUBSCRIPTION did not call
1140 : : * SubscriptionConninfo() in a path where it's required.
1141 : : */
1142 [ - + ]: 40 : if (!conninfo)
1143 [ # # ]: 0 : elog(ERROR, "no connection string provided for subscription");
1144 : :
1145 : : /* Load the library providing us libpq calls. */
1146 : 40 : load_file("libpqwalreceiver", false);
1147 : :
1148 : : /* Try to connect to the publisher. */
1149 [ + - + + ]: 40 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
1150 : 40 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
1151 : : sub->name, &err);
1152 [ - + ]: 39 : if (!wrconn)
1153 [ # # ]: 0 : ereport(ERROR,
1154 : : (errcode(ERRCODE_CONNECTION_FAILURE),
1155 : : errmsg("subscription \"%s\" could not connect to the publisher: %s",
1156 : : sub->name, err)));
1157 : :
1158 [ + - ]: 39 : PG_TRY();
1159 : : {
1160 [ + + ]: 39 : if (validate_publications)
1161 : 9 : check_publications(wrconn, validate_publications);
1162 : :
1163 : : /* Get the relation list from publisher. */
1164 : 39 : pubrels = fetch_relation_list(wrconn, sub->publications);
1165 : :
1166 : : /* Get local relation list. */
1167 : 39 : subrel_states = GetSubscriptionRelations(sub->oid, true, true, false);
1168 : 39 : subrel_count = list_length(subrel_states);
1169 : :
1170 : : /* Allow a test to drop a subscribed relation before the origin check. */
1171 : 39 : INJECTION_POINT("subscription-refresh-before-origin-check", NULL);
1172 : :
1173 : : /*
1174 : : * Build qsorted arrays of local table oids and sequence oids for
1175 : : * faster lookup. This can potentially contain all tables and
1176 : : * sequences in the database so speed of lookup is important.
1177 : : *
1178 : : * We do not yet know the exact count of tables and sequences, so we
1179 : : * allocate separate arrays for table OIDs and sequence OIDs based on
1180 : : * the total number of relations (subrel_count).
1181 : : */
1182 : 39 : subrel_local_oids = palloc_array(Oid, subrel_count);
1183 : 39 : subseq_local_oids = palloc_array(Oid, subrel_count);
1184 [ + + + + : 139 : foreach(lc, subrel_states)
+ + ]
1185 : : {
1186 : 100 : SubscriptionRelState *relstate = (SubscriptionRelState *) lfirst(lc);
1187 : :
1188 [ + + ]: 100 : if (get_rel_relkind(relstate->relid) == RELKIND_SEQUENCE)
1189 : 10 : subseq_local_oids[seq_count++] = relstate->relid;
1190 : : else
1191 : 90 : subrel_local_oids[tbl_count++] = relstate->relid;
1192 : : }
1193 : :
1194 : 39 : qsort(subrel_local_oids, tbl_count, sizeof(Oid), oid_cmp);
1195 : 39 : check_publications_origin_tables(wrconn, sub->publications, copy_data,
1196 : 39 : sub->retaindeadtuples, sub->origin,
1197 : : subrel_local_oids, tbl_count,
1198 : : sub->name);
1199 : :
1200 : 39 : qsort(subseq_local_oids, seq_count, sizeof(Oid), oid_cmp);
1201 : 39 : check_publications_origin_sequences(wrconn, sub->publications,
1202 : : copy_data, sub->origin,
1203 : : subseq_local_oids, seq_count,
1204 : : sub->name);
1205 : :
1206 : : /*
1207 : : * Walk over the remote relations and try to match them to locally
1208 : : * known relations. If the relation is not known locally create a new
1209 : : * state for it.
1210 : : *
1211 : : * Also builds array of local oids of remote relations for the next
1212 : : * step.
1213 : : */
1214 : 39 : off = 0;
1215 : 39 : pubrel_local_oids = palloc_array(Oid, list_length(pubrels));
1216 : :
1217 [ + + + + : 185 : foreach_ptr(PublicationRelKind, pubrelinfo, pubrels)
+ + ]
1218 : : {
1219 : 107 : RangeVar *rv = pubrelinfo->rv;
1220 : : Oid relid;
1221 : : char relkind;
1222 : :
1223 : 107 : relid = RangeVarGetRelid(rv, AccessShareLock, false);
1224 : 107 : relkind = get_rel_relkind(relid);
1225 : :
1226 : : /* Check for supported relkind. */
1227 : 107 : CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
1228 : 107 : rv->schemaname, rv->relname);
1229 : :
1230 : 107 : pubrel_local_oids[off++] = relid;
1231 : :
1232 [ + + ]: 107 : if (!bsearch(&relid, subrel_local_oids,
1233 : 39 : tbl_count, sizeof(Oid), oid_cmp) &&
1234 [ + + ]: 39 : !bsearch(&relid, subseq_local_oids,
1235 : : seq_count, sizeof(Oid), oid_cmp))
1236 : : {
1237 [ + + ]: 30 : AddSubscriptionRelState(sub->oid, relid,
1238 : : copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
1239 : : InvalidXLogRecPtr, true);
1240 [ + + - + ]: 30 : ereport(DEBUG1,
1241 : : errmsg_internal("%s \"%s.%s\" added to subscription \"%s\"",
1242 : : relkind == RELKIND_SEQUENCE ? "sequence" : "table",
1243 : : rv->schemaname, rv->relname, sub->name));
1244 : : }
1245 : : }
1246 : :
1247 : : /*
1248 : : * Next remove state for tables we should not care about anymore using
1249 : : * the data we collected above
1250 : : */
1251 : 39 : qsort(pubrel_local_oids, list_length(pubrels), sizeof(Oid), oid_cmp);
1252 : :
1253 [ + + ]: 129 : for (off = 0; off < tbl_count; off++)
1254 : : {
1255 : 90 : Oid relid = subrel_local_oids[off];
1256 : :
1257 [ + + ]: 90 : if (!bsearch(&relid, pubrel_local_oids,
1258 : 90 : list_length(pubrels), sizeof(Oid), oid_cmp))
1259 : : {
1260 : : char state;
1261 : : XLogRecPtr statelsn;
1262 : 22 : SubRemoveRels *remove_rel = palloc_object(SubRemoveRels);
1263 : :
1264 : : /*
1265 : : * Lock pg_subscription_rel with AccessExclusiveLock to
1266 : : * prevent any race conditions with the apply worker
1267 : : * re-launching workers at the same time this code is trying
1268 : : * to remove those tables.
1269 : : *
1270 : : * Even if new worker for this particular rel is restarted it
1271 : : * won't be able to make any progress as we hold exclusive
1272 : : * lock on pg_subscription_rel till the transaction end. It
1273 : : * will simply exit as there is no corresponding rel entry.
1274 : : *
1275 : : * This locking also ensures that the state of rels won't
1276 : : * change till we are done with this refresh operation.
1277 : : */
1278 [ + + ]: 22 : if (!rel)
1279 : 10 : rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
1280 : :
1281 : : /* Last known rel state. */
1282 : 22 : state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
1283 : :
1284 : 22 : RemoveSubscriptionRel(sub->oid, relid);
1285 : :
1286 : 22 : remove_rel->relid = relid;
1287 : 22 : remove_rel->state = state;
1288 : :
1289 : 22 : sub_remove_rels = lappend(sub_remove_rels, remove_rel);
1290 : :
1291 : 22 : logicalrep_worker_stop(WORKERTYPE_TABLESYNC, sub->oid, relid);
1292 : :
1293 : : /*
1294 : : * For READY state, we would have already dropped the
1295 : : * tablesync origin.
1296 : : */
1297 [ + + ]: 22 : if (state != SUBREL_STATE_READY)
1298 : : {
1299 : : char originname[NAMEDATALEN];
1300 : :
1301 : : /*
1302 : : * Drop the tablesync's origin tracking if exists.
1303 : : *
1304 : : * It is possible that the origin is not yet created for
1305 : : * tablesync worker, this can happen for the states before
1306 : : * SUBREL_STATE_DATASYNC. The tablesync worker or apply
1307 : : * worker can also concurrently try to drop the origin and
1308 : : * by this time the origin might be already removed. For
1309 : : * these reasons, passing missing_ok = true.
1310 : : */
1311 : 1 : ReplicationOriginNameForLogicalRep(sub->oid, relid, originname,
1312 : : sizeof(originname));
1313 : 1 : replorigin_drop_by_name(originname, true, false);
1314 : : }
1315 : :
1316 [ + + ]: 22 : ereport(DEBUG1,
1317 : : (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
1318 : : get_namespace_name(get_rel_namespace(relid)),
1319 : : get_rel_name(relid),
1320 : : sub->name)));
1321 : : }
1322 : : }
1323 : :
1324 : : /*
1325 : : * Next remove state for sequences we should not care about anymore
1326 : : * using the data we collected above
1327 : : */
1328 [ + + ]: 49 : for (off = 0; off < seq_count; off++)
1329 : : {
1330 : 10 : Oid relid = subseq_local_oids[off];
1331 : :
1332 [ + + ]: 10 : if (!bsearch(&relid, pubrel_local_oids,
1333 : 10 : list_length(pubrels), sizeof(Oid), oid_cmp))
1334 : : {
1335 : : /*
1336 : : * This locking ensures that the state of rels won't change
1337 : : * till we are done with this refresh operation.
1338 : : */
1339 [ - + ]: 1 : if (!rel)
1340 : 0 : rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
1341 : :
1342 : 1 : RemoveSubscriptionRel(sub->oid, relid);
1343 : :
1344 : : /*
1345 : : * A sequence sync worker may already be running with this
1346 : : * sequence in its to-do list. It does not have to be stopped.
1347 : : * It notices that the sequence is no longer part of the
1348 : : * subscription and skips it, see copy_sequence().
1349 : : */
1350 [ - + ]: 1 : ereport(DEBUG1,
1351 : : errmsg_internal("sequence \"%s.%s\" removed from subscription \"%s\"",
1352 : : get_namespace_name(get_rel_namespace(relid)),
1353 : : get_rel_name(relid),
1354 : : sub->name));
1355 : : }
1356 : : }
1357 : :
1358 : : /*
1359 : : * Drop the tablesync slots associated with removed tables. This has
1360 : : * to be at the end because otherwise if there is an error while doing
1361 : : * the database operations we won't be able to rollback dropped slots.
1362 : : */
1363 [ + + + + : 100 : foreach_ptr(SubRemoveRels, sub_remove_rel, sub_remove_rels)
+ + ]
1364 : : {
1365 [ + + ]: 22 : if (sub_remove_rel->state != SUBREL_STATE_READY &&
1366 [ + - ]: 1 : sub_remove_rel->state != SUBREL_STATE_SYNCDONE)
1367 : : {
1368 : 1 : char syncslotname[NAMEDATALEN] = {0};
1369 : :
1370 : : /*
1371 : : * For READY/SYNCDONE states we know the tablesync slot has
1372 : : * already been dropped by the tablesync worker.
1373 : : *
1374 : : * For other states, there is no certainty, maybe the slot
1375 : : * does not exist yet. Also, if we fail after removing some of
1376 : : * the slots, next time, it will again try to drop already
1377 : : * dropped slots and fail. For these reasons, we allow
1378 : : * missing_ok = true for the drop.
1379 : : */
1380 : 1 : ReplicationSlotNameForTablesync(sub->oid, sub_remove_rel->relid,
1381 : : syncslotname, sizeof(syncslotname));
1382 : 1 : ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1383 : : }
1384 : : }
1385 : : }
1386 : 0 : PG_FINALLY();
1387 : : {
1388 : 39 : walrcv_disconnect(wrconn);
1389 : : }
1390 [ - + ]: 39 : PG_END_TRY();
1391 : :
1392 [ + + ]: 39 : if (rel)
1393 : 10 : table_close(rel, NoLock);
1394 : 39 : }
1395 : :
1396 : : /*
1397 : : * Marks all sequences with INIT state.
1398 : : */
1399 : : static void
1400 : 5 : AlterSubscription_refresh_seq(Subscription *sub, char *conninfo)
1401 : : {
1402 : 5 : char *err = NULL;
1403 : : WalReceiverConn *wrconn;
1404 : : bool must_use_password;
1405 : : List *subrel_states;
1406 : :
1407 : : /*
1408 : : * Should not happen: CREATE/ALTER/DROP SUBSCRIPTION did not call
1409 : : * SubscriptionConninfo() in a path where it's required.
1410 : : */
1411 [ - + ]: 5 : if (!conninfo)
1412 [ # # ]: 0 : elog(ERROR, "no connection string provided for subscription");
1413 : :
1414 : : /* Load the library providing us libpq calls. */
1415 : 5 : load_file("libpqwalreceiver", false);
1416 : :
1417 : : /* Try to connect to the publisher. */
1418 [ + - - + ]: 5 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
1419 : 5 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
1420 : : sub->name, &err);
1421 [ - + ]: 5 : if (!wrconn)
1422 [ # # ]: 0 : ereport(ERROR,
1423 : : errcode(ERRCODE_CONNECTION_FAILURE),
1424 : : errmsg("subscription \"%s\" could not connect to the publisher: %s",
1425 : : sub->name, err));
1426 : :
1427 : : /* The publisher connection is only needed for the origin check. */
1428 [ + - ]: 5 : PG_TRY();
1429 : : {
1430 : : /*
1431 : : * Sequence synchronization depends on publisher-side functionality
1432 : : * introduced in PostgreSQL 19, so it cannot work against an older
1433 : : * publisher.
1434 : : */
1435 [ - + ]: 5 : if (walrcv_server_version(wrconn) < 190000)
1436 [ # # ]: 0 : ereport(ERROR,
1437 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1438 : : errmsg("cannot synchronize sequences if the publisher is running a version earlier than PostgreSQL 19"));
1439 : :
1440 : 5 : check_publications_origin_sequences(wrconn, sub->publications, true,
1441 : : sub->origin, NULL, 0, sub->name);
1442 : : }
1443 : 0 : PG_FINALLY();
1444 : : {
1445 : 5 : walrcv_disconnect(wrconn);
1446 : : }
1447 [ - + ]: 5 : PG_END_TRY();
1448 : :
1449 : : /*
1450 : : * Reset the sequences to INIT so they get re-synchronized with the latest
1451 : : * publisher values.
1452 : : *
1453 : : * A sequence sync worker may already be running. If it has fetched a
1454 : : * sequence's value from the publisher but not yet marked it READY, it
1455 : : * must not be allowed to complete that update, as it would overwrite the
1456 : : * reset below with a stale value and silently lose this refresh request.
1457 : : * So we stop any running sequence sync worker before resetting the
1458 : : * states.
1459 : : *
1460 : : * This is race-free because AlterSubscription() already holds
1461 : : * AccessExclusiveLock on the subscription object. That lock blocks a
1462 : : * running worker's update of sequence state to READY, see
1463 : : * UpdateSubscriptionRelState() which takes AccessShareLock on the object.
1464 : : * It also blocks any worker the apply worker re-launches, because a new
1465 : : * worker takes AccessShareLock on the object before it reads
1466 : : * pg_subscription_rel, see InitializeLogRepWorker(). Such a worker cannot
1467 : : * act on the states until we commit, by which time they are reset to INIT
1468 : : * and it will sync the latest values.
1469 : : */
1470 : : #ifdef USE_ASSERT_CHECKING
1471 : : {
1472 : : LOCKTAG tag;
1473 : :
1474 : : SET_LOCKTAG_OBJECT(tag, InvalidOid, SubscriptionRelationId, sub->oid, 0);
1475 : : Assert(LockHeldByMe(&tag, AccessExclusiveLock, true));
1476 : : }
1477 : : #endif
1478 : :
1479 : 5 : logicalrep_worker_stop(WORKERTYPE_SEQUENCESYNC, sub->oid, InvalidOid);
1480 : :
1481 : : /* Reset every local sequence of this subscription to INIT. */
1482 : 5 : subrel_states = GetSubscriptionRelations(sub->oid, false, true, false);
1483 [ + - + + : 31 : foreach_ptr(SubscriptionRelState, subrel, subrel_states)
+ + ]
1484 : : {
1485 : 21 : Oid relid = subrel->relid;
1486 : :
1487 : 21 : UpdateSubscriptionRelState(sub->oid, relid, SUBREL_STATE_INIT,
1488 : : InvalidXLogRecPtr, false);
1489 [ - + ]: 21 : ereport(DEBUG1,
1490 : : errmsg_internal("sequence \"%s.%s\" of subscription \"%s\" set to INIT state",
1491 : : get_namespace_name(get_rel_namespace(relid)),
1492 : : get_rel_name(relid),
1493 : : sub->name));
1494 : : }
1495 : 5 : }
1496 : :
1497 : : /*
1498 : : * Common checks for altering failover, two_phase, and retain_dead_tuples
1499 : : * options.
1500 : : */
1501 : : static void
1502 : 14 : CheckAlterSubOption(Subscription *sub, const char *option,
1503 : : bool slot_needs_update, bool isTopLevel)
1504 : : {
1505 : : Assert(strcmp(option, "failover") == 0 ||
1506 : : strcmp(option, "two_phase") == 0 ||
1507 : : strcmp(option, "retain_dead_tuples") == 0);
1508 : :
1509 : : /*
1510 : : * Altering the retain_dead_tuples option does not update the slot on the
1511 : : * publisher.
1512 : : */
1513 : : Assert(!slot_needs_update || strcmp(option, "retain_dead_tuples") != 0);
1514 : :
1515 : : /*
1516 : : * Do not allow changing the option if the subscription is enabled. This
1517 : : * is because both failover and two_phase options of the slot on the
1518 : : * publisher cannot be modified if the slot is currently acquired by the
1519 : : * existing walsender.
1520 : : *
1521 : : * Note that two_phase is enabled (aka changed from 'false' to 'true') on
1522 : : * the publisher by the existing walsender, so we could have allowed that
1523 : : * even when the subscription is enabled. But we kept this restriction for
1524 : : * the sake of consistency and simplicity.
1525 : : *
1526 : : * Additionally, do not allow changing the retain_dead_tuples option when
1527 : : * the subscription is enabled to prevent race conditions arising from the
1528 : : * new option value being acknowledged asynchronously by the launcher and
1529 : : * apply workers.
1530 : : *
1531 : : * Without the restriction, a race condition may arise when a user
1532 : : * disables and immediately re-enables the retain_dead_tuples option. In
1533 : : * this case, the launcher might drop the slot upon noticing the disabled
1534 : : * action, while the apply worker may keep maintaining
1535 : : * oldest_nonremovable_xid without noticing the option change. During this
1536 : : * period, a transaction ID wraparound could falsely make this ID appear
1537 : : * as if it originates from the future w.r.t the transaction ID stored in
1538 : : * the slot maintained by launcher.
1539 : : *
1540 : : * Similarly, if the user enables retain_dead_tuples concurrently with the
1541 : : * launcher starting the worker, the apply worker may start calculating
1542 : : * oldest_nonremovable_xid before the launcher notices the enable action.
1543 : : * Consequently, the launcher may update slot.xmin to a newer value than
1544 : : * that maintained by the worker. In subsequent cycles, upon integrating
1545 : : * the worker's oldest_nonremovable_xid, the launcher might detect a
1546 : : * retreat in the calculated xmin, necessitating additional handling.
1547 : : *
1548 : : * XXX To address the above race conditions, we can define
1549 : : * oldest_nonremovable_xid as FullTransactionId and adds the check to
1550 : : * disallow retreating the conflict slot's xmin. For now, we kept the
1551 : : * implementation simple by disallowing change to the retain_dead_tuples,
1552 : : * but in the future we can change this after some more analysis.
1553 : : *
1554 : : * Note that we could restrict only the enabling of retain_dead_tuples to
1555 : : * avoid the race conditions described above, but we maintain the
1556 : : * restriction for both enable and disable operations for the sake of
1557 : : * consistency.
1558 : : */
1559 [ + + ]: 14 : if (sub->enabled)
1560 [ + - ]: 2 : ereport(ERROR,
1561 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1562 : : errmsg("cannot set option \"%s\" for enabled subscription",
1563 : : option)));
1564 : :
1565 [ + + ]: 12 : if (slot_needs_update)
1566 : : {
1567 : : StringInfoData cmd;
1568 : :
1569 : : /*
1570 : : * A valid slot must be associated with the subscription for us to
1571 : : * modify any of the slot's properties.
1572 : : */
1573 [ - + ]: 9 : if (!sub->slotname)
1574 [ # # ]: 0 : ereport(ERROR,
1575 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1576 : : errmsg("cannot set option \"%s\" for a subscription that does not have a slot name",
1577 : : option)));
1578 : :
1579 : : /* The changed option of the slot can't be rolled back. */
1580 : 9 : initStringInfo(&cmd);
1581 : 9 : appendStringInfo(&cmd, "ALTER SUBSCRIPTION ... SET (%s)", option);
1582 : :
1583 : 9 : PreventInTransactionBlock(isTopLevel, cmd.data);
1584 : 5 : pfree(cmd.data);
1585 : : }
1586 : 8 : }
1587 : :
1588 : : /*
1589 : : * alter_sub_conflict_log_dest
1590 : : *
1591 : : * When the subscription's 'conflict_log_destination' is changed, update the
1592 : : * conflict log table if required.
1593 : : *
1594 : : * If the new destination no longer requires a conflict log table, the existing
1595 : : * conflict log table associated with the subscription is removed via internal
1596 : : * dependency cleanup to prevent orphaned relations.
1597 : : *
1598 : : * On success, *conflicttablerelid is set to the OID of the conflict log table
1599 : : * that was created or validated, or to InvalidOid if no table is required.
1600 : : *
1601 : : * Returns true if the subscription's conflict log table reference must be
1602 : : * updated as a result of the destination change; false otherwise.
1603 : : */
1604 : : static bool
1605 : 12 : alter_sub_conflict_log_dest(Subscription *sub, ConflictLogDest oldlogdest,
1606 : : ConflictLogDest newlogdest,
1607 : : Oid *conflicttablerelid)
1608 : : {
1609 : : bool want_table;
1610 : : bool has_oldtable;
1611 : 12 : bool update_relid = false;
1612 : 12 : Oid relid = InvalidOid;
1613 : :
1614 [ + + + + ]: 12 : want_table = CONFLICTS_LOGGED_TO_TABLE(newlogdest);
1615 [ + + + + ]: 12 : has_oldtable = CONFLICTS_LOGGED_TO_TABLE(oldlogdest);
1616 : :
1617 [ + + ]: 12 : if (has_oldtable)
1618 : : {
1619 : : /* There is a conflict log table already. */
1620 [ + + ]: 8 : if (!want_table)
1621 : : {
1622 : 4 : drop_sub_conflict_log_table(sub->oid, sub->name,
1623 : : sub->conflictlogrelid);
1624 : 4 : update_relid = true;
1625 : : }
1626 : : }
1627 : : else
1628 : : {
1629 : : /* There was no previous conflict log table. */
1630 [ + - ]: 4 : if (want_table)
1631 : : {
1632 : : ObjectAddress cltaddr;
1633 : : ObjectAddress subobj;
1634 : :
1635 : 4 : relid = create_conflict_log_table(sub->oid, sub->name, sub->owner);
1636 : 4 : update_relid = true;
1637 : :
1638 : : /*
1639 : : * Establish an internal dependency between the conflict log table
1640 : : * and the subscription. For details refer comments in
1641 : : * CreateSubscription function.
1642 : : */
1643 : 4 : ObjectAddressSet(cltaddr, RelationRelationId, relid);
1644 : 4 : ObjectAddressSet(subobj, SubscriptionRelationId, sub->oid);
1645 : 4 : recordDependencyOn(&cltaddr, &subobj, DEPENDENCY_INTERNAL);
1646 : : }
1647 : : }
1648 : :
1649 : 12 : *conflicttablerelid = relid;
1650 : 12 : return update_relid;
1651 : : }
1652 : :
1653 : : /*
1654 : : * Alter the existing subscription.
1655 : : */
1656 : : ObjectAddress
1657 : 443 : AlterSubscription(ParseState *pstate, AlterSubscriptionStmt *stmt,
1658 : : bool isTopLevel)
1659 : : {
1660 : : Relation rel;
1661 : : ObjectAddress myself;
1662 : : bool nulls[Natts_pg_subscription];
1663 : : bool replaces[Natts_pg_subscription];
1664 : : Datum values[Natts_pg_subscription];
1665 : : HeapTuple tup;
1666 : : Oid subid;
1667 : 443 : bool orig_conninfo_needed = false;
1668 : 443 : bool update_tuple = false;
1669 : 443 : bool update_failover = false;
1670 : 443 : bool update_two_phase = false;
1671 : 443 : bool check_pub_rdt = false;
1672 : : bool retain_dead_tuples;
1673 : : int max_retention;
1674 : : bool retention_active;
1675 : 443 : char *new_conninfo = NULL;
1676 : 443 : char *orig_conninfo = NULL;
1677 : : char *origin;
1678 : : Subscription *sub;
1679 : : Form_pg_subscription form;
1680 : : uint32 supported_opts;
1681 : 443 : SubOpts opts = {0};
1682 : :
1683 : 443 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1684 : :
1685 : : /* Fetch the existing tuple. */
1686 : 443 : tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
1687 : : CStringGetDatum(stmt->subname));
1688 : :
1689 [ + + ]: 443 : if (!HeapTupleIsValid(tup))
1690 [ + - ]: 4 : ereport(ERROR,
1691 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
1692 : : errmsg("subscription \"%s\" does not exist",
1693 : : stmt->subname)));
1694 : :
1695 : 439 : form = (Form_pg_subscription) GETSTRUCT(tup);
1696 : 439 : subid = form->oid;
1697 : :
1698 : : /* must be owner */
1699 [ - + ]: 439 : if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1700 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
1701 : 0 : stmt->subname);
1702 : :
1703 : : /* parse and check options */
1704 [ + + + + : 439 : switch (stmt->kind)
+ + + ]
1705 : : {
1706 : 209 : case ALTER_SUBSCRIPTION_OPTIONS:
1707 : 209 : supported_opts = (SUBOPT_SLOT_NAME |
1708 : : SUBOPT_SYNCHRONOUS_COMMIT | SUBOPT_BINARY |
1709 : : SUBOPT_STREAMING | SUBOPT_TWOPHASE_COMMIT |
1710 : : SUBOPT_DISABLE_ON_ERR |
1711 : : SUBOPT_PASSWORD_REQUIRED |
1712 : : SUBOPT_RUN_AS_OWNER | SUBOPT_FAILOVER |
1713 : : SUBOPT_RETAIN_DEAD_TUPLES |
1714 : : SUBOPT_MAX_RETENTION_DURATION |
1715 : : SUBOPT_WAL_RECEIVER_TIMEOUT |
1716 : : SUBOPT_ORIGIN |
1717 : : SUBOPT_CONFLICT_LOG_DEST);
1718 : 209 : break;
1719 : :
1720 : 87 : case ALTER_SUBSCRIPTION_ENABLED:
1721 : 87 : supported_opts = SUBOPT_ENABLED;
1722 : 87 : break;
1723 : :
1724 : 23 : case ALTER_SUBSCRIPTION_SET_PUBLICATION:
1725 : 23 : supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1726 : 23 : break;
1727 : :
1728 : 35 : case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
1729 : : case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
1730 : 35 : supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1731 : 35 : break;
1732 : :
1733 : 42 : case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
1734 : 42 : supported_opts = SUBOPT_COPY_DATA;
1735 : 42 : break;
1736 : :
1737 : 15 : case ALTER_SUBSCRIPTION_SKIP:
1738 : 15 : supported_opts = SUBOPT_LSN;
1739 : 15 : break;
1740 : :
1741 : 28 : default:
1742 : 28 : supported_opts = 0;
1743 : 28 : break;
1744 : : }
1745 : :
1746 [ + + ]: 439 : if (supported_opts > 0)
1747 : 411 : parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
1748 : :
1749 : 415 : sub = GetSubscription(subid, false);
1750 : :
1751 : : /*
1752 : : * Determine in advance whether we need the original conninfo or not, so
1753 : : * that errors are generated consistently in cases where we do need it;
1754 : : * and not generated at all if we don't.
1755 : : */
1756 : :
1757 : : /* conninfo needed when refreshing */
1758 [ + + + + ]: 415 : switch (stmt->kind)
1759 : : {
1760 : 47 : case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
1761 : : case ALTER_SUBSCRIPTION_REFRESH_SEQUENCES:
1762 : 47 : orig_conninfo_needed = true;
1763 : 47 : break;
1764 : :
1765 : 58 : case ALTER_SUBSCRIPTION_SET_PUBLICATION:
1766 : : case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
1767 : : case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
1768 : : /* opts.refresh defaults to true when the option is supported */
1769 : 58 : orig_conninfo_needed = opts.refresh;
1770 : 58 : break;
1771 : :
1772 : 189 : case ALTER_SUBSCRIPTION_OPTIONS:
1773 : : {
1774 [ + + ]: 189 : if (sub->slotname)
1775 : : {
1776 [ + + ]: 185 : if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1777 : 9 : orig_conninfo_needed = true;
1778 [ + + ]: 185 : if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT) &&
1779 [ + + ]: 3 : !opts.twophase)
1780 : 1 : orig_conninfo_needed = true;
1781 : : }
1782 : :
1783 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) &&
1784 [ + - ]: 2 : opts.retaindeadtuples)
1785 : 2 : orig_conninfo_needed = true;
1786 : :
1787 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1788 : : {
1789 : : bool rdt;
1790 : :
1791 : 12 : rdt = IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) ?
1792 [ - + ]: 6 : opts.retaindeadtuples : sub->retaindeadtuples;
1793 : :
1794 [ + + + + ]: 6 : if (rdt && pg_strcasecmp(opts.origin, LOGICALREP_ORIGIN_ANY) == 0)
1795 : 1 : orig_conninfo_needed = true;
1796 : : }
1797 : : }
1798 : 189 : break;
1799 : :
1800 : 121 : default:
1801 : 121 : break;
1802 : : }
1803 : :
1804 [ + + ]: 415 : if (orig_conninfo_needed)
1805 : 78 : orig_conninfo = SubscriptionConninfo(sub);
1806 : :
1807 : 411 : retain_dead_tuples = sub->retaindeadtuples;
1808 : 411 : origin = sub->origin;
1809 : 411 : max_retention = sub->maxretention;
1810 : 411 : retention_active = sub->retentionactive;
1811 : :
1812 : : /*
1813 : : * Don't allow non-superuser modification of a subscription with
1814 : : * password_required=false.
1815 : : */
1816 [ + + - + ]: 411 : if (!sub->passwordrequired && !superuser())
1817 [ # # ]: 0 : ereport(ERROR,
1818 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1819 : : errmsg("password_required=false is superuser-only"),
1820 : : errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1821 : :
1822 : : /* Lock the subscription so nobody else can do anything with it. */
1823 : 411 : LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1824 : :
1825 : : /* Form a new tuple. */
1826 : 411 : memset(values, 0, sizeof(values));
1827 : 411 : memset(nulls, false, sizeof(nulls));
1828 : 411 : memset(replaces, false, sizeof(replaces));
1829 : :
1830 : 411 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
1831 : :
1832 [ + + + + : 411 : switch (stmt->kind)
+ + + + +
- ]
1833 : : {
1834 : 189 : case ALTER_SUBSCRIPTION_OPTIONS:
1835 : : {
1836 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1837 : : {
1838 : : /*
1839 : : * The subscription must be disabled to allow slot_name as
1840 : : * 'none', otherwise, the apply worker will repeatedly try
1841 : : * to stream the data using that slot_name which neither
1842 : : * exists on the publisher nor the user will be allowed to
1843 : : * create it.
1844 : : */
1845 [ - + - - ]: 72 : if (sub->enabled && !opts.slot_name)
1846 [ # # ]: 0 : ereport(ERROR,
1847 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1848 : : errmsg("cannot set %s for enabled subscription",
1849 : : "slot_name = NONE")));
1850 : :
1851 [ + + ]: 72 : if (opts.slot_name)
1852 : 4 : values[Anum_pg_subscription_subslotname - 1] =
1853 : 4 : DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
1854 : : else
1855 : 68 : nulls[Anum_pg_subscription_subslotname - 1] = true;
1856 : 72 : replaces[Anum_pg_subscription_subslotname - 1] = true;
1857 : : }
1858 : :
1859 [ + + ]: 189 : if (opts.synchronous_commit)
1860 : : {
1861 : 12 : values[Anum_pg_subscription_subsynccommit - 1] =
1862 : 12 : CStringGetTextDatum(opts.synchronous_commit);
1863 : 12 : replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1864 : : }
1865 : :
1866 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1867 : : {
1868 : 10 : values[Anum_pg_subscription_subbinary - 1] =
1869 : 10 : BoolGetDatum(opts.binary);
1870 : 10 : replaces[Anum_pg_subscription_subbinary - 1] = true;
1871 : : }
1872 : :
1873 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1874 : : {
1875 : 18 : values[Anum_pg_subscription_substream - 1] =
1876 : 18 : CharGetDatum(opts.streaming);
1877 : 18 : replaces[Anum_pg_subscription_substream - 1] = true;
1878 : : }
1879 : :
1880 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1881 : : {
1882 : : values[Anum_pg_subscription_subdisableonerr - 1]
1883 : 12 : = BoolGetDatum(opts.disableonerr);
1884 : : replaces[Anum_pg_subscription_subdisableonerr - 1]
1885 : 12 : = true;
1886 : : }
1887 : :
1888 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1889 : : {
1890 : : /* Non-superuser may not disable password_required. */
1891 [ + + - + ]: 8 : if (!opts.passwordrequired && !superuser())
1892 [ # # ]: 0 : ereport(ERROR,
1893 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1894 : : errmsg("password_required=false is superuser-only"),
1895 : : errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1896 : :
1897 : : values[Anum_pg_subscription_subpasswordrequired - 1]
1898 : 8 : = BoolGetDatum(opts.passwordrequired);
1899 : : replaces[Anum_pg_subscription_subpasswordrequired - 1]
1900 : 8 : = true;
1901 : : }
1902 : :
1903 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
1904 : : {
1905 : 9 : values[Anum_pg_subscription_subrunasowner - 1] =
1906 : 9 : BoolGetDatum(opts.runasowner);
1907 : 9 : replaces[Anum_pg_subscription_subrunasowner - 1] = true;
1908 : : }
1909 : :
1910 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT))
1911 : : {
1912 : : /*
1913 : : * We need to update both the slot and the subscription
1914 : : * for the two_phase option. We can enable the two_phase
1915 : : * option for a slot only once the initial data
1916 : : * synchronization is done. This is to avoid missing some
1917 : : * data as explained in comments atop worker.c.
1918 : : */
1919 : 3 : update_two_phase = !opts.twophase;
1920 : :
1921 : 3 : CheckAlterSubOption(sub, "two_phase", update_two_phase,
1922 : : isTopLevel);
1923 : :
1924 : : /*
1925 : : * Modifying the two_phase slot option requires a slot
1926 : : * lookup by slot name, so changing the slot name at the
1927 : : * same time is not allowed.
1928 : : */
1929 [ + + ]: 3 : if (update_two_phase &&
1930 [ - + ]: 1 : IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1931 [ # # ]: 0 : ereport(ERROR,
1932 : : (errcode(ERRCODE_SYNTAX_ERROR),
1933 : : errmsg("\"slot_name\" and \"two_phase\" cannot be altered at the same time")));
1934 : :
1935 : : /*
1936 : : * Note that workers may still survive even if the
1937 : : * subscription has been disabled.
1938 : : *
1939 : : * Ensure workers have already been exited to avoid
1940 : : * getting prepared transactions while we are disabling
1941 : : * the two_phase option. Otherwise, the changes of an
1942 : : * already prepared transaction can be replicated again
1943 : : * along with its corresponding commit, leading to
1944 : : * duplicate data or errors.
1945 : : */
1946 [ - + ]: 3 : if (logicalrep_workers_find(subid, true, true))
1947 [ # # ]: 0 : ereport(ERROR,
1948 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1949 : : errmsg("cannot alter \"two_phase\" when logical replication worker is still running"),
1950 : : errhint("Try again after some time.")));
1951 : :
1952 : : /*
1953 : : * two_phase cannot be disabled if there are any
1954 : : * uncommitted prepared transactions present otherwise it
1955 : : * can lead to duplicate data or errors as explained in
1956 : : * the comment above.
1957 : : */
1958 [ + + ]: 3 : if (update_two_phase &&
1959 [ + - ]: 1 : sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED &&
1960 [ - + ]: 1 : LookupGXactBySubid(subid))
1961 [ # # ]: 0 : ereport(ERROR,
1962 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1963 : : errmsg("cannot disable \"two_phase\" when prepared transactions exist"),
1964 : : errhint("Resolve these transactions and try again.")));
1965 : :
1966 : : /* Change system catalog accordingly */
1967 : 3 : values[Anum_pg_subscription_subtwophasestate - 1] =
1968 [ + + ]: 3 : CharGetDatum(opts.twophase ?
1969 : : LOGICALREP_TWOPHASE_STATE_PENDING :
1970 : : LOGICALREP_TWOPHASE_STATE_DISABLED);
1971 : 3 : replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
1972 : : }
1973 : :
1974 [ + + ]: 189 : if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1975 : : {
1976 : : /*
1977 : : * Similar to the two_phase case above, we need to update
1978 : : * the failover option for both the slot and the
1979 : : * subscription.
1980 : : */
1981 : 9 : update_failover = true;
1982 : :
1983 : 9 : CheckAlterSubOption(sub, "failover", update_failover,
1984 : : isTopLevel);
1985 : :
1986 : 4 : values[Anum_pg_subscription_subfailover - 1] =
1987 : 4 : BoolGetDatum(opts.failover);
1988 : 4 : replaces[Anum_pg_subscription_subfailover - 1] = true;
1989 : : }
1990 : :
1991 [ + + ]: 184 : if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
1992 : : {
1993 : 2 : values[Anum_pg_subscription_subretaindeadtuples - 1] =
1994 : 2 : BoolGetDatum(opts.retaindeadtuples);
1995 : 2 : replaces[Anum_pg_subscription_subretaindeadtuples - 1] = true;
1996 : :
1997 : : /*
1998 : : * Update the retention status only if there's a change in
1999 : : * the retain_dead_tuples option value.
2000 : : *
2001 : : * Automatically marking retention as active when
2002 : : * retain_dead_tuples is enabled may not always be ideal,
2003 : : * especially if retention was previously stopped and the
2004 : : * user toggles retain_dead_tuples without adjusting the
2005 : : * publisher workload. However, this behavior provides a
2006 : : * convenient way for users to manually refresh the
2007 : : * retention status. Since retention will be stopped again
2008 : : * unless the publisher workload is reduced, this approach
2009 : : * is acceptable for now.
2010 : : */
2011 [ + - ]: 2 : if (opts.retaindeadtuples != sub->retaindeadtuples)
2012 : : {
2013 : 2 : values[Anum_pg_subscription_subretentionactive - 1] =
2014 : 2 : BoolGetDatum(opts.retaindeadtuples);
2015 : 2 : replaces[Anum_pg_subscription_subretentionactive - 1] = true;
2016 : :
2017 : 2 : retention_active = opts.retaindeadtuples;
2018 : : }
2019 : :
2020 : 2 : CheckAlterSubOption(sub, "retain_dead_tuples", false, isTopLevel);
2021 : :
2022 : : /*
2023 : : * Workers may continue running even after the
2024 : : * subscription has been disabled.
2025 : : *
2026 : : * To prevent race conditions (as described in
2027 : : * CheckAlterSubOption()), ensure that all worker
2028 : : * processes have already exited before proceeding.
2029 : : */
2030 [ - + ]: 1 : if (logicalrep_workers_find(subid, true, true))
2031 [ # # ]: 0 : ereport(ERROR,
2032 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2033 : : errmsg("cannot alter option \"%s\" when logical replication worker is still running",
2034 : : "retain_dead_tuples"),
2035 : : errhint("Try again after some time.")));
2036 : :
2037 : : /*
2038 : : * Notify the launcher to manage the replication slot for
2039 : : * conflict detection. This ensures that replication slot
2040 : : * is efficiently handled (created, updated, or dropped)
2041 : : * in response to any configuration changes.
2042 : : */
2043 : 1 : ApplyLauncherWakeupAtCommit();
2044 : :
2045 : 1 : check_pub_rdt = opts.retaindeadtuples;
2046 : 1 : retain_dead_tuples = opts.retaindeadtuples;
2047 : : }
2048 : :
2049 [ + + ]: 183 : if (IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
2050 : : {
2051 : 6 : values[Anum_pg_subscription_submaxretention - 1] =
2052 : 6 : Int32GetDatum(opts.maxretention);
2053 : 6 : replaces[Anum_pg_subscription_submaxretention - 1] = true;
2054 : :
2055 : 6 : max_retention = opts.maxretention;
2056 : : }
2057 : :
2058 : : /*
2059 : : * Ensure that system configuration parameters are set
2060 : : * appropriately to support retain_dead_tuples and
2061 : : * max_retention_duration.
2062 : : */
2063 [ + + ]: 183 : if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) ||
2064 [ + + ]: 182 : IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
2065 : 7 : CheckSubDeadTupleRetention(true, !sub->enabled, NOTICE,
2066 : : retain_dead_tuples,
2067 : : retention_active,
2068 : 7 : (max_retention > 0));
2069 : :
2070 [ + + ]: 183 : if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
2071 : : {
2072 : 6 : values[Anum_pg_subscription_suborigin - 1] =
2073 : 6 : CStringGetTextDatum(opts.origin);
2074 : 6 : replaces[Anum_pg_subscription_suborigin - 1] = true;
2075 : :
2076 : : /*
2077 : : * Check if changes from different origins may be received
2078 : : * from the publisher when the origin is changed to ANY
2079 : : * and retain_dead_tuples is enabled. Use |= so that we
2080 : : * don't clear the flag already set when
2081 : : * retain_dead_tuples was changed in the same command.
2082 : : */
2083 [ + + ]: 8 : check_pub_rdt |= retain_dead_tuples &&
2084 [ + + ]: 2 : pg_strcasecmp(opts.origin, LOGICALREP_ORIGIN_ANY) == 0;
2085 : :
2086 : 6 : origin = opts.origin;
2087 : : }
2088 : :
2089 [ + + ]: 183 : if (IsSet(opts.specified_opts, SUBOPT_WAL_RECEIVER_TIMEOUT))
2090 : : {
2091 : 8 : values[Anum_pg_subscription_subwalrcvtimeout - 1] =
2092 : 8 : CStringGetTextDatum(opts.wal_receiver_timeout);
2093 : 8 : replaces[Anum_pg_subscription_subwalrcvtimeout - 1] = true;
2094 : : }
2095 : :
2096 [ + + ]: 183 : if (IsSet(opts.specified_opts, SUBOPT_CONFLICT_LOG_DEST))
2097 : : {
2098 : : ConflictLogDest old_dest =
2099 : 16 : GetConflictLogDest(sub->conflictlogdest);
2100 : :
2101 [ + + ]: 16 : if (opts.conflictlogdest != old_dest)
2102 : : {
2103 : : bool update_relid;
2104 : 12 : Oid relid = InvalidOid;
2105 : :
2106 : 12 : values[Anum_pg_subscription_subconflictlogdest - 1] =
2107 : 12 : CStringGetTextDatum(ConflictLogDestNames[opts.conflictlogdest]);
2108 : 12 : replaces[Anum_pg_subscription_subconflictlogdest - 1] = true;
2109 : :
2110 : 12 : update_relid = alter_sub_conflict_log_dest(sub,
2111 : : old_dest,
2112 : : opts.conflictlogdest,
2113 : : &relid);
2114 [ + + ]: 12 : if (update_relid)
2115 : : {
2116 : 8 : values[Anum_pg_subscription_subconflictlogrelid - 1] =
2117 : 8 : ObjectIdGetDatum(relid);
2118 : 8 : replaces[Anum_pg_subscription_subconflictlogrelid - 1] =
2119 : : true;
2120 : : }
2121 : : }
2122 : : }
2123 : :
2124 : 183 : update_tuple = true;
2125 : 183 : break;
2126 : : }
2127 : :
2128 : 87 : case ALTER_SUBSCRIPTION_ENABLED:
2129 : : {
2130 : : Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
2131 : :
2132 [ + + + - ]: 87 : if (!sub->slotname && opts.enabled)
2133 [ + - ]: 4 : ereport(ERROR,
2134 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2135 : : errmsg("cannot enable subscription that does not have a slot name")));
2136 : :
2137 : : /*
2138 : : * Check track_commit_timestamp only when enabling the
2139 : : * subscription in case it was disabled after creation. See
2140 : : * comments atop CheckSubDeadTupleRetention() for details.
2141 : : */
2142 : 83 : CheckSubDeadTupleRetention(opts.enabled, !opts.enabled,
2143 : 83 : WARNING, sub->retaindeadtuples,
2144 : 83 : sub->retentionactive, false);
2145 : :
2146 : 83 : values[Anum_pg_subscription_subenabled - 1] =
2147 : 83 : BoolGetDatum(opts.enabled);
2148 : 83 : replaces[Anum_pg_subscription_subenabled - 1] = true;
2149 : :
2150 [ + + ]: 83 : if (opts.enabled)
2151 : 34 : ApplyLauncherWakeupAtCommit();
2152 : :
2153 : 83 : update_tuple = true;
2154 : 83 : break;
2155 : : }
2156 : :
2157 : 1 : case ALTER_SUBSCRIPTION_SERVER:
2158 : : {
2159 : : ForeignServer *new_server;
2160 : : ObjectAddress referenced;
2161 : : AclResult aclresult;
2162 : :
2163 : : /*
2164 : : * Remove what was there before, either another foreign server
2165 : : * or a connection string.
2166 : : */
2167 [ - + ]: 1 : if (form->subserver)
2168 : : {
2169 : 0 : deleteDependencyRecordsForSpecific(SubscriptionRelationId, form->oid,
2170 : : DEPENDENCY_NORMAL,
2171 : : ForeignServerRelationId, form->subserver);
2172 : : }
2173 : : else
2174 : : {
2175 : 1 : nulls[Anum_pg_subscription_subconninfo - 1] = true;
2176 : 1 : replaces[Anum_pg_subscription_subconninfo - 1] = true;
2177 : : }
2178 : :
2179 : : /*
2180 : : * Check that the subscription owner has USAGE privileges on
2181 : : * the server.
2182 : : */
2183 : 1 : new_server = GetForeignServerByName(stmt->servername, false);
2184 : 1 : aclresult = object_aclcheck(ForeignServerRelationId,
2185 : : new_server->serverid,
2186 : : form->subowner, ACL_USAGE);
2187 [ - + ]: 1 : if (aclresult != ACLCHECK_OK)
2188 [ # # ]: 0 : ereport(ERROR,
2189 : : errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2190 : : errmsg("subscription owner \"%s\" does not have permission on foreign server \"%s\"",
2191 : : GetUserNameFromId(form->subowner, false),
2192 : : new_server->servername));
2193 : :
2194 : : /* check user mapping */
2195 : 1 : GetUserMappingExtended(form->subowner, new_server->serverid, WARNING);
2196 : :
2197 : 1 : new_conninfo = ForeignServerConnectionString(form->subowner,
2198 : : new_server);
2199 : :
2200 : : /* Load the library providing us libpq calls. */
2201 : 1 : load_file("libpqwalreceiver", false);
2202 : : /* Check the connection info string. */
2203 [ - + - - ]: 1 : walrcv_check_conninfo(new_conninfo,
2204 : : sub->passwordrequired && !sub->ownersuperuser);
2205 : :
2206 : 1 : values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(new_server->serverid);
2207 : 1 : replaces[Anum_pg_subscription_subserver - 1] = true;
2208 : :
2209 : 1 : ObjectAddressSet(referenced, ForeignServerRelationId, new_server->serverid);
2210 : 1 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
2211 : :
2212 : 1 : update_tuple = true;
2213 : : }
2214 : :
2215 : : /*
2216 : : * Since the remote server configuration might have changed,
2217 : : * perform a check to ensure it permits enabling
2218 : : * retain_dead_tuples.
2219 : : */
2220 : 1 : check_pub_rdt = sub->retaindeadtuples;
2221 : 1 : break;
2222 : :
2223 : 22 : case ALTER_SUBSCRIPTION_CONNECTION:
2224 : : /* remove reference to foreign server and dependencies, if present */
2225 [ + + ]: 22 : if (form->subserver)
2226 : : {
2227 : 9 : deleteDependencyRecordsForSpecific(SubscriptionRelationId, form->oid,
2228 : : DEPENDENCY_NORMAL,
2229 : : ForeignServerRelationId, form->subserver);
2230 : :
2231 : 9 : values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(InvalidOid);
2232 : 9 : replaces[Anum_pg_subscription_subserver - 1] = true;
2233 : : }
2234 : :
2235 : 22 : new_conninfo = stmt->conninfo;
2236 : :
2237 : : /* Load the library providing us libpq calls. */
2238 : 22 : load_file("libpqwalreceiver", false);
2239 : : /* Check the connection info string. */
2240 [ + + + + ]: 22 : walrcv_check_conninfo(new_conninfo,
2241 : : sub->passwordrequired && !sub->ownersuperuser);
2242 : :
2243 : 18 : values[Anum_pg_subscription_subconninfo - 1] =
2244 : 18 : CStringGetTextDatum(stmt->conninfo);
2245 : 18 : replaces[Anum_pg_subscription_subconninfo - 1] = true;
2246 : 18 : update_tuple = true;
2247 : :
2248 : : /*
2249 : : * Since the remote server configuration might have changed,
2250 : : * perform a check to ensure it permits enabling
2251 : : * retain_dead_tuples.
2252 : : */
2253 : 18 : check_pub_rdt = sub->retaindeadtuples;
2254 : 18 : break;
2255 : :
2256 : 23 : case ALTER_SUBSCRIPTION_SET_PUBLICATION:
2257 : : {
2258 : 23 : values[Anum_pg_subscription_subpublications - 1] =
2259 : 23 : publicationListToArray(stmt->publication);
2260 : 23 : replaces[Anum_pg_subscription_subpublications - 1] = true;
2261 : :
2262 : 23 : update_tuple = true;
2263 : :
2264 : : /* Refresh if user asked us to. */
2265 [ + + ]: 23 : if (opts.refresh)
2266 : : {
2267 [ - + ]: 15 : if (!sub->enabled)
2268 [ # # ]: 0 : ereport(ERROR,
2269 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2270 : : errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
2271 : : errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
2272 : :
2273 : : /*
2274 : : * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
2275 : : * why this is not allowed.
2276 : : */
2277 [ - + - - ]: 15 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2278 [ # # ]: 0 : ereport(ERROR,
2279 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2280 : : errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
2281 : : errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
2282 : :
2283 : 15 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2284 : :
2285 : : /* Make sure refresh sees the new list of publications. */
2286 : 7 : sub->publications = stmt->publication;
2287 : :
2288 : 7 : AlterSubscription_refresh(sub, opts.copy_data,
2289 : : stmt->publication,
2290 : : orig_conninfo);
2291 : : }
2292 : :
2293 : 15 : break;
2294 : : }
2295 : :
2296 : 35 : case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
2297 : : case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
2298 : : {
2299 : : List *publist;
2300 : 35 : bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
2301 : :
2302 : 35 : publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
2303 : 11 : values[Anum_pg_subscription_subpublications - 1] =
2304 : 11 : publicationListToArray(publist);
2305 : 11 : replaces[Anum_pg_subscription_subpublications - 1] = true;
2306 : :
2307 : 11 : update_tuple = true;
2308 : :
2309 : : /* Refresh if user asked us to. */
2310 [ + + ]: 11 : if (opts.refresh)
2311 : : {
2312 : : /* We only need to validate user specified publications. */
2313 [ + + ]: 3 : List *validate_publications = (isadd) ? stmt->publication : NULL;
2314 : :
2315 [ - + ]: 3 : if (!sub->enabled)
2316 [ # # # # ]: 0 : ereport(ERROR,
2317 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2318 : : errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
2319 : : /* translator: %s is an SQL ALTER command */
2320 : : errhint("Use %s instead.",
2321 : : isadd ?
2322 : : "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
2323 : : "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
2324 : :
2325 : : /*
2326 : : * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
2327 : : * why this is not allowed.
2328 : : */
2329 [ - + - - ]: 3 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2330 [ # # # # ]: 0 : ereport(ERROR,
2331 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2332 : : errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
2333 : : /* translator: %s is an SQL ALTER command */
2334 : : errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
2335 : : isadd ?
2336 : : "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
2337 : : "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
2338 : :
2339 : 3 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2340 : :
2341 : : /* Refresh the new list of publications. */
2342 : 3 : sub->publications = publist;
2343 : :
2344 : 3 : AlterSubscription_refresh(sub, opts.copy_data,
2345 : : validate_publications,
2346 : : orig_conninfo);
2347 : : }
2348 : :
2349 : 11 : break;
2350 : : }
2351 : :
2352 : 38 : case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
2353 : : {
2354 [ + + ]: 38 : if (!sub->enabled)
2355 [ + - ]: 4 : ereport(ERROR,
2356 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2357 : : errmsg("%s is not allowed for disabled subscriptions",
2358 : : "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
2359 : :
2360 : : /*
2361 : : * The subscription option "two_phase" requires that
2362 : : * replication has passed the initial table synchronization
2363 : : * phase before the two_phase becomes properly enabled.
2364 : : *
2365 : : * But, having reached this two-phase commit "enabled" state
2366 : : * we must not allow any subsequent table initialization to
2367 : : * occur. So the ALTER SUBSCRIPTION ... REFRESH PUBLICATION is
2368 : : * disallowed when the user had requested two_phase = on mode.
2369 : : *
2370 : : * The exception to this restriction is when copy_data =
2371 : : * false, because when copy_data is false the tablesync will
2372 : : * start already in READY state and will exit directly without
2373 : : * doing anything.
2374 : : *
2375 : : * For more details see comments atop worker.c.
2376 : : */
2377 [ - + - - ]: 34 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2378 [ # # ]: 0 : ereport(ERROR,
2379 : : (errcode(ERRCODE_SYNTAX_ERROR),
2380 : : errmsg("ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data is not allowed when two_phase is enabled"),
2381 : : errhint("Use ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
2382 : :
2383 : 34 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH PUBLICATION");
2384 : :
2385 : 30 : AlterSubscription_refresh(sub, opts.copy_data, NULL,
2386 : : orig_conninfo);
2387 : :
2388 : 29 : break;
2389 : : }
2390 : :
2391 : 5 : case ALTER_SUBSCRIPTION_REFRESH_SEQUENCES:
2392 : : {
2393 [ - + ]: 5 : if (!sub->enabled)
2394 [ # # ]: 0 : ereport(ERROR,
2395 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2396 : : errmsg("%s is not allowed for disabled subscriptions",
2397 : : "ALTER SUBSCRIPTION ... REFRESH SEQUENCES"));
2398 : :
2399 : 5 : AlterSubscription_refresh_seq(sub, orig_conninfo);
2400 : :
2401 : 5 : break;
2402 : : }
2403 : :
2404 : 11 : case ALTER_SUBSCRIPTION_SKIP:
2405 : : {
2406 : : /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
2407 : : Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
2408 : :
2409 : : /*
2410 : : * If the user sets subskiplsn, we do a sanity check to make
2411 : : * sure that the specified LSN is a probable value.
2412 : : */
2413 [ + + ]: 11 : if (XLogRecPtrIsValid(opts.lsn))
2414 : : {
2415 : : ReplOriginId originid;
2416 : : char originname[NAMEDATALEN];
2417 : : XLogRecPtr remote_lsn;
2418 : :
2419 : 7 : ReplicationOriginNameForLogicalRep(subid, InvalidOid,
2420 : : originname, sizeof(originname));
2421 : 7 : originid = replorigin_by_name(originname, false);
2422 : 7 : remote_lsn = replorigin_get_progress(originid, false);
2423 : :
2424 : : /* Check the given LSN is at least a future LSN */
2425 [ + + - + ]: 7 : if (XLogRecPtrIsValid(remote_lsn) && opts.lsn < remote_lsn)
2426 [ # # ]: 0 : ereport(ERROR,
2427 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2428 : : errmsg("skip WAL location (LSN %X/%08X) must be greater than origin LSN %X/%08X",
2429 : : LSN_FORMAT_ARGS(opts.lsn),
2430 : : LSN_FORMAT_ARGS(remote_lsn))));
2431 : : }
2432 : :
2433 : 11 : values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
2434 : 11 : replaces[Anum_pg_subscription_subskiplsn - 1] = true;
2435 : :
2436 : 11 : update_tuple = true;
2437 : 11 : break;
2438 : : }
2439 : :
2440 : 0 : default:
2441 [ # # ]: 0 : elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
2442 : : stmt->kind);
2443 : : }
2444 : :
2445 : : /* Update the catalog if needed. */
2446 [ + + ]: 356 : if (update_tuple)
2447 : : {
2448 : 322 : tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
2449 : : replaces);
2450 : :
2451 : 322 : CatalogTupleUpdate(rel, &tup->t_self, tup);
2452 : :
2453 : 322 : heap_freetuple(tup);
2454 : : }
2455 : :
2456 : : /*
2457 : : * Try to acquire the connection necessary either for modifying the slot
2458 : : * or for checking if the remote server permits enabling
2459 : : * retain_dead_tuples.
2460 : : *
2461 : : * This has to be at the end because otherwise if there is an error while
2462 : : * doing the database operations we won't be able to rollback altered
2463 : : * slot.
2464 : : */
2465 [ + + + + : 356 : if (update_failover || update_two_phase || check_pub_rdt)
+ + ]
2466 : : {
2467 : : bool must_use_password;
2468 : : char *err;
2469 : : WalReceiverConn *wrconn;
2470 : :
2471 : : Assert(new_conninfo || orig_conninfo);
2472 : :
2473 : : /* Load the library providing us libpq calls. */
2474 : 7 : load_file("libpqwalreceiver", false);
2475 : :
2476 : : /*
2477 : : * Try to connect to the publisher, using the new connection string if
2478 : : * available.
2479 : : */
2480 [ + - - + ]: 7 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
2481 [ - + ]: 7 : wrconn = walrcv_connect(new_conninfo ? new_conninfo : orig_conninfo,
2482 : : true, true, must_use_password, sub->name,
2483 : : &err);
2484 [ - + ]: 7 : if (!wrconn)
2485 [ # # ]: 0 : ereport(ERROR,
2486 : : (errcode(ERRCODE_CONNECTION_FAILURE),
2487 : : errmsg("subscription \"%s\" could not connect to the publisher: %s",
2488 : : sub->name, err)));
2489 : :
2490 [ + - ]: 7 : PG_TRY();
2491 : : {
2492 [ + + ]: 7 : if (retain_dead_tuples)
2493 : 3 : CheckPubDeadTupleRetention(wrconn);
2494 : :
2495 : 7 : check_publications_origin_tables(wrconn, sub->publications, false,
2496 : : retain_dead_tuples, origin, NULL, 0,
2497 : : sub->name);
2498 : :
2499 [ + + + + ]: 7 : if (update_failover || update_two_phase)
2500 [ + + + + ]: 5 : walrcv_alter_slot(wrconn, sub->slotname,
2501 : : update_failover ? &opts.failover : NULL,
2502 : : update_two_phase ? &opts.twophase : NULL);
2503 : : }
2504 : 0 : PG_FINALLY();
2505 : : {
2506 : 7 : walrcv_disconnect(wrconn);
2507 : : }
2508 [ - + ]: 7 : PG_END_TRY();
2509 : : }
2510 : :
2511 : 356 : table_close(rel, RowExclusiveLock);
2512 : :
2513 [ - + ]: 356 : InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
2514 : :
2515 : : /* Wake up related replication workers to handle this change quickly. */
2516 : 356 : LogicalRepWorkersWakeupAtCommit(subid);
2517 : :
2518 : 356 : return myself;
2519 : : }
2520 : :
2521 : : /*
2522 : : * Construct conninfo from a subscription's server. Like libpqrcv_connect(),
2523 : : * if an error occurs, set *err to the error message and return NULL.
2524 : : *
2525 : : * However, failures in ForeignServerConnectionString() may ereport(ERROR),
2526 : : * and (also like libpqrcv_connect) it's not worth adding the machinery to
2527 : : * pass all of those back to the caller just to cover this one case.
2528 : : */
2529 : : static char *
2530 : 8 : construct_subserver_conninfo(Oid subserver, Oid subowner, char **err)
2531 : : {
2532 : : AclResult aclresult;
2533 : : ForeignServer *server;
2534 : :
2535 : 8 : *err = NULL;
2536 : :
2537 : 8 : server = GetForeignServer(subserver);
2538 : :
2539 : 8 : aclresult = object_aclcheck(ForeignServerRelationId, subserver,
2540 : : subowner, ACL_USAGE);
2541 [ + + ]: 8 : if (aclresult != ACLCHECK_OK)
2542 : : {
2543 : : /*
2544 : : * Unable to generate connection string because permissions on the
2545 : : * foreign server have been removed. Follow the same logic as an
2546 : : * unusable subconninfo (which will result in an ERROR later unless
2547 : : * slot_name = NONE).
2548 : : */
2549 : 4 : *err = psprintf(_("subscription owner \"%s\" does not have permission on foreign server \"%s\""),
2550 : : GetUserNameFromId(subowner, false),
2551 : : server->servername);
2552 : 4 : return NULL;
2553 : : }
2554 : :
2555 : 4 : return ForeignServerConnectionString(subowner, server);
2556 : : }
2557 : :
2558 : : /*
2559 : : * Drop subscription's conflict log table
2560 : : *
2561 : : * The conflict log table is registered as an internal dependency of the
2562 : : * subscription. This function removes the dependency by performing a
2563 : : * cascading deletion on the subscription object, which in turn drops the
2564 : : * associated conflict log table.
2565 : : *
2566 : : * This is used to clean up conflict log tables that are no longer required,
2567 : : * preventing accumulation of stale or orphaned relations.
2568 : : *
2569 : : * NOTE:
2570 : : * Only conflict log tables are currently managed via this internal dependency
2571 : : * mechanism.
2572 : : */
2573 : : static void
2574 : 175 : drop_sub_conflict_log_table(Oid subid, char *subname, Oid subconflictlogrelid)
2575 : : {
2576 : : /* Drop any dependent conflict log table */
2577 [ + + ]: 175 : if (OidIsValid(subconflictlogrelid))
2578 : : {
2579 : : ObjectAddress object;
2580 : : char *conflictrelname;
2581 : :
2582 : 13 : conflictrelname = get_rel_name(subconflictlogrelid);
2583 [ - + ]: 13 : if (conflictrelname == NULL)
2584 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u",
2585 : : subconflictlogrelid);
2586 : :
2587 : : /*
2588 : : * By using PERFORM_DELETION_SKIP_ORIGINAL, we ensure that only the
2589 : : * conflict log table is deleted while the subscription remains.
2590 : : */
2591 : 13 : ObjectAddressSet(object, SubscriptionRelationId, subid);
2592 : 13 : performDeletion(&object, DROP_CASCADE,
2593 : : PERFORM_DELETION_INTERNAL |
2594 : : PERFORM_DELETION_SKIP_ORIGINAL);
2595 : :
2596 [ + + ]: 13 : ereport(NOTICE,
2597 : : errmsg("dropped conflict log table \"%s\" for subscription \"%s\"",
2598 : : get_qualified_objname(PG_CONFLICT_NAMESPACE, conflictrelname),
2599 : : subname));
2600 : : }
2601 : 175 : }
2602 : :
2603 : : /*
2604 : : * Drop a subscription
2605 : : */
2606 : : void
2607 : 183 : DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
2608 : : {
2609 : : Relation rel;
2610 : : ObjectAddress myself;
2611 : : HeapTuple tup;
2612 : : Oid subid;
2613 : : Oid subowner;
2614 : : Oid subserver;
2615 : : Oid subconflictlogrelid;
2616 : 183 : char *subconninfo = NULL;
2617 : : Datum datum;
2618 : : bool isnull;
2619 : : char *subname;
2620 : 183 : char *conninfo = NULL;
2621 : : char *slotname;
2622 : : List *subworkers;
2623 : : ListCell *lc;
2624 : : char originname[NAMEDATALEN];
2625 : 183 : char *err = NULL;
2626 : 183 : WalReceiverConn *wrconn = NULL;
2627 : : Form_pg_subscription form;
2628 : : List *rstates;
2629 : : bool must_use_password;
2630 : :
2631 : : /*
2632 : : * The launcher may concurrently start a new worker for this subscription.
2633 : : * During initialization, the worker checks for subscription validity and
2634 : : * exits if the subscription has already been dropped. See
2635 : : * InitializeLogRepWorker.
2636 : : */
2637 : 183 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
2638 : :
2639 : 183 : tup = SearchSysCache2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
2640 : 183 : CStringGetDatum(stmt->subname));
2641 : :
2642 [ + + ]: 183 : if (!HeapTupleIsValid(tup))
2643 : : {
2644 : 8 : table_close(rel, NoLock);
2645 : :
2646 [ + + ]: 8 : if (!stmt->missing_ok)
2647 [ + - ]: 4 : ereport(ERROR,
2648 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
2649 : : errmsg("subscription \"%s\" does not exist",
2650 : : stmt->subname)));
2651 : : else
2652 [ + - ]: 4 : ereport(NOTICE,
2653 : : (errmsg("subscription \"%s\" does not exist, skipping",
2654 : : stmt->subname)));
2655 : :
2656 : 86 : return;
2657 : : }
2658 : :
2659 : 175 : datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
2660 : : Anum_pg_subscription_subconninfo, &isnull);
2661 [ + + ]: 175 : if (!isnull)
2662 : 158 : subconninfo = TextDatumGetCString(datum);
2663 : :
2664 : 175 : form = (Form_pg_subscription) GETSTRUCT(tup);
2665 : 175 : subid = form->oid;
2666 : 175 : subowner = form->subowner;
2667 : 175 : subserver = form->subserver;
2668 : 175 : subconflictlogrelid = form->subconflictlogrelid;
2669 [ + + + + ]: 175 : must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
2670 : :
2671 : : /* must be owner */
2672 [ - + ]: 175 : if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
2673 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
2674 : 0 : stmt->subname);
2675 : :
2676 : : /* DROP hook for the subscription being removed */
2677 [ - + ]: 175 : InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
2678 : :
2679 : : /*
2680 : : * Lock the subscription so nobody else can do anything with it (including
2681 : : * the replication workers).
2682 : : */
2683 : 175 : LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
2684 : :
2685 : : /* Get subname */
2686 : 175 : datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
2687 : : Anum_pg_subscription_subname);
2688 : 175 : subname = pstrdup(NameStr(*DatumGetName(datum)));
2689 : :
2690 : : /* Get slotname */
2691 : 175 : datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
2692 : : Anum_pg_subscription_subslotname, &isnull);
2693 [ + + ]: 175 : if (!isnull)
2694 : 93 : slotname = pstrdup(NameStr(*DatumGetName(datum)));
2695 : : else
2696 : 82 : slotname = NULL;
2697 : :
2698 : : /*
2699 : : * Since dropping a replication slot is not transactional, the replication
2700 : : * slot stays dropped even if the transaction rolls back. So we cannot
2701 : : * run DROP SUBSCRIPTION inside a transaction block if dropping the
2702 : : * replication slot. Also, in this case, we report a message for dropping
2703 : : * the subscription to the cumulative stats system.
2704 : : *
2705 : : * XXX The command name should really be something like "DROP SUBSCRIPTION
2706 : : * of a subscription that is associated with a replication slot", but we
2707 : : * don't have the proper facilities for that.
2708 : : */
2709 [ + + ]: 175 : if (slotname)
2710 : 93 : PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
2711 : :
2712 : 171 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
2713 : 171 : EventTriggerSQLDropAddObject(&myself, true, true);
2714 : :
2715 : : /* Remove the tuple from catalog. */
2716 : 171 : CatalogTupleDelete(rel, &tup->t_self);
2717 : :
2718 : 171 : ReleaseSysCache(tup);
2719 : :
2720 : : /*
2721 : : * Stop all the subscription workers immediately.
2722 : : *
2723 : : * This is necessary if we are dropping the replication slot, so that the
2724 : : * slot becomes accessible.
2725 : : *
2726 : : * It is also necessary if the subscription is disabled and was disabled
2727 : : * in the same transaction. Then the workers haven't seen the disabling
2728 : : * yet and will still be running, leading to hangs later when we want to
2729 : : * drop the replication origin. If the subscription was disabled before
2730 : : * this transaction, then there shouldn't be any workers left, so this
2731 : : * won't make a difference.
2732 : : *
2733 : : * New workers won't be started because we hold an exclusive lock on the
2734 : : * subscription till the end of the transaction.
2735 : : */
2736 : 171 : subworkers = logicalrep_workers_find(subid, false, true);
2737 [ + + + + : 259 : foreach(lc, subworkers)
+ + ]
2738 : : {
2739 : 88 : LogicalRepWorker *w = (LogicalRepWorker *) lfirst(lc);
2740 : :
2741 : 88 : logicalrep_worker_stop(w->type, w->subid, w->relid);
2742 : : }
2743 : 171 : list_free(subworkers);
2744 : :
2745 : : /*
2746 : : * Remove the no-longer-useful entry in the launcher's table of apply
2747 : : * worker start times.
2748 : : *
2749 : : * If this transaction rolls back, the launcher might restart a failed
2750 : : * apply worker before wal_retrieve_retry_interval milliseconds have
2751 : : * elapsed, but that's pretty harmless.
2752 : : */
2753 : 171 : ApplyLauncherForgetWorkerStartTime(subid);
2754 : :
2755 : : /*
2756 : : * Cleanup of tablesync replication origins.
2757 : : *
2758 : : * Any READY-state relations would already have dealt with clean-ups.
2759 : : *
2760 : : * Note that the state can't change because we have already stopped both
2761 : : * the apply and tablesync workers and they can't restart because of
2762 : : * exclusive lock on the subscription.
2763 : : */
2764 : 171 : rstates = GetSubscriptionRelations(subid, true, false, true);
2765 [ + + + + : 176 : foreach(lc, rstates)
+ + ]
2766 : : {
2767 : 5 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
2768 : 5 : Oid relid = rstate->relid;
2769 : :
2770 : : /* Only cleanup resources of tablesync workers */
2771 [ - + ]: 5 : if (!OidIsValid(relid))
2772 : 0 : continue;
2773 : :
2774 : : /*
2775 : : * Drop the tablesync's origin tracking if exists.
2776 : : *
2777 : : * It is possible that the origin is not yet created for tablesync
2778 : : * worker so passing missing_ok = true. This can happen for the states
2779 : : * before SUBREL_STATE_DATASYNC.
2780 : : */
2781 : 5 : ReplicationOriginNameForLogicalRep(subid, relid, originname,
2782 : : sizeof(originname));
2783 : 5 : replorigin_drop_by_name(originname, true, false);
2784 : : }
2785 : :
2786 : : /* Drop subscription's conflict log table */
2787 : 171 : drop_sub_conflict_log_table(subid, subname, subconflictlogrelid);
2788 : :
2789 : : /* Clean up dependencies */
2790 : 171 : deleteDependencyRecordsFor(SubscriptionRelationId, subid, false);
2791 : 171 : deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
2792 : :
2793 : : /* Remove any associated relation synchronization states. */
2794 : 171 : RemoveSubscriptionRel(subid, InvalidOid);
2795 : :
2796 : : /* Remove the origin tracking if exists. */
2797 : 171 : ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
2798 : 171 : replorigin_drop_by_name(originname, true, false);
2799 : :
2800 : : /*
2801 : : * Tell the cumulative stats system that the subscription is getting
2802 : : * dropped.
2803 : : */
2804 : 171 : pgstat_drop_subscription(subid);
2805 : :
2806 : : /*
2807 : : * If there is no slot associated with the subscription, we can finish
2808 : : * here.
2809 : : */
2810 [ + + + - ]: 171 : if (!slotname && rstates == NIL)
2811 : : {
2812 : 82 : table_close(rel, NoLock);
2813 : 82 : return;
2814 : : }
2815 : :
2816 : : /*
2817 : : * Try to acquire the connection necessary for dropping slots.
2818 : : *
2819 : : * Note: If the slotname is NONE/NULL then we allow the command to finish
2820 : : * and users need to manually cleanup the apply and tablesync worker slots
2821 : : * later.
2822 : : *
2823 : : * This has to be at the end because otherwise if there is an error while
2824 : : * doing the database operations we won't be able to rollback dropped
2825 : : * slot.
2826 : : */
2827 : 89 : load_file("libpqwalreceiver", false);
2828 : :
2829 [ + + ]: 89 : if (OidIsValid(subserver))
2830 : 8 : conninfo = construct_subserver_conninfo(subserver, subowner, &err);
2831 : : else
2832 : 81 : conninfo = subconninfo;
2833 : :
2834 [ + + ]: 85 : if (conninfo)
2835 : 81 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
2836 : : subname, &err);
2837 : :
2838 [ + + ]: 85 : if (wrconn == NULL)
2839 : : {
2840 [ - + ]: 4 : if (!slotname)
2841 : : {
2842 : : /* be tidy */
2843 : 0 : list_free(rstates);
2844 : 0 : table_close(rel, NoLock);
2845 : 0 : return;
2846 : : }
2847 : : else
2848 : : {
2849 : 4 : ReportSlotConnectionError(rstates, subid, slotname, err);
2850 : : }
2851 : : }
2852 : :
2853 [ + + ]: 81 : PG_TRY();
2854 : : {
2855 [ + + + + : 86 : foreach(lc, rstates)
+ + ]
2856 : : {
2857 : 5 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
2858 : 5 : Oid relid = rstate->relid;
2859 : :
2860 : : /* Only cleanup resources of tablesync workers */
2861 [ - + ]: 5 : if (!OidIsValid(relid))
2862 : 0 : continue;
2863 : :
2864 : : /*
2865 : : * Drop the tablesync slots associated with removed tables.
2866 : : *
2867 : : * For SYNCDONE/READY states, the tablesync slot is known to have
2868 : : * already been dropped by the tablesync worker.
2869 : : *
2870 : : * For other states, there is no certainty, maybe the slot does
2871 : : * not exist yet. Also, if we fail after removing some of the
2872 : : * slots, next time, it will again try to drop already dropped
2873 : : * slots and fail. For these reasons, we allow missing_ok = true
2874 : : * for the drop.
2875 : : */
2876 [ + + ]: 5 : if (rstate->state != SUBREL_STATE_SYNCDONE)
2877 : : {
2878 : 4 : char syncslotname[NAMEDATALEN] = {0};
2879 : :
2880 : 4 : ReplicationSlotNameForTablesync(subid, relid, syncslotname,
2881 : : sizeof(syncslotname));
2882 : 4 : ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
2883 : : }
2884 : : }
2885 : :
2886 : 81 : list_free(rstates);
2887 : :
2888 : : /*
2889 : : * If there is a slot associated with the subscription, then drop the
2890 : : * replication slot at the publisher.
2891 : : */
2892 [ + - ]: 81 : if (slotname)
2893 : 81 : ReplicationSlotDropAtPubNode(wrconn, slotname, false);
2894 : : }
2895 : 1 : PG_FINALLY();
2896 : : {
2897 : 81 : walrcv_disconnect(wrconn);
2898 : : }
2899 [ + + ]: 81 : PG_END_TRY();
2900 : :
2901 : 80 : table_close(rel, NoLock);
2902 : : }
2903 : :
2904 : : /*
2905 : : * Drop the replication slot at the publisher node using the replication
2906 : : * connection.
2907 : : *
2908 : : * missing_ok - if true then only issue a LOG message if the slot doesn't
2909 : : * exist.
2910 : : */
2911 : : void
2912 : 301 : ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
2913 : : {
2914 : : StringInfoData cmd;
2915 : :
2916 : : Assert(wrconn);
2917 : :
2918 : 301 : load_file("libpqwalreceiver", false);
2919 : :
2920 : 301 : initStringInfo(&cmd);
2921 : 301 : appendStringInfoString(&cmd, "DROP_REPLICATION_SLOT ");
2922 : 301 : appendQuotedIdentifier(&cmd, slotname);
2923 : 301 : appendStringInfoString(&cmd, " WAIT");
2924 : :
2925 [ + + ]: 301 : PG_TRY();
2926 : : {
2927 : : WalRcvExecResult *res;
2928 : :
2929 : 301 : res = walrcv_exec(wrconn, cmd.data, 0, NULL);
2930 : :
2931 [ + + ]: 301 : if (res->status == WALRCV_OK_COMMAND)
2932 : : {
2933 : : /* NOTICE. Success. */
2934 [ + + ]: 299 : ereport(NOTICE,
2935 : : (errmsg("dropped replication slot \"%s\" on publisher",
2936 : : slotname)));
2937 : : }
2938 [ + - + + ]: 2 : else if (res->status == WALRCV_ERROR &&
2939 : 1 : missing_ok &&
2940 [ + - ]: 1 : res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
2941 : : {
2942 : : /* LOG. Error, but missing_ok = true. */
2943 [ + - ]: 1 : ereport(LOG,
2944 : : (errmsg("could not drop replication slot \"%s\" on publisher: %s",
2945 : : slotname, res->err)));
2946 : : }
2947 : : else
2948 : : {
2949 : : /* ERROR. */
2950 [ + - ]: 1 : ereport(ERROR,
2951 : : (errcode(ERRCODE_CONNECTION_FAILURE),
2952 : : errmsg("could not drop replication slot \"%s\" on publisher: %s",
2953 : : slotname, res->err)));
2954 : : }
2955 : :
2956 : 300 : walrcv_clear_result(res);
2957 : : }
2958 : 1 : PG_FINALLY();
2959 : : {
2960 : 301 : pfree(cmd.data);
2961 : : }
2962 [ + + ]: 301 : PG_END_TRY();
2963 : 300 : }
2964 : :
2965 : : /*
2966 : : * Internal workhorse for changing a subscription owner
2967 : : */
2968 : : static void
2969 : 28 : AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
2970 : : {
2971 : : Form_pg_subscription form;
2972 : : AclResult aclresult;
2973 : :
2974 : 28 : form = (Form_pg_subscription) GETSTRUCT(tup);
2975 : :
2976 : : /* Must only alter subscriptions belonging to the current database. */
2977 : : Assert(form->subdbid == MyDatabaseId);
2978 : :
2979 [ + + ]: 28 : if (form->subowner == newOwnerId)
2980 : 2 : return;
2981 : :
2982 [ - + ]: 26 : if (!object_ownercheck(SubscriptionRelationId, form->oid, GetUserId()))
2983 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
2984 : 0 : NameStr(form->subname));
2985 : :
2986 : : /*
2987 : : * Don't allow non-superuser modification of a subscription with
2988 : : * password_required=false.
2989 : : */
2990 [ - + - - ]: 26 : if (!form->subpasswordrequired && !superuser())
2991 [ # # ]: 0 : ereport(ERROR,
2992 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2993 : : errmsg("password_required=false is superuser-only"),
2994 : : errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
2995 : :
2996 : : /* Must be able to become new owner */
2997 : 26 : check_can_set_role(GetUserId(), newOwnerId);
2998 : :
2999 : : /*
3000 : : * current owner must have CREATE on database
3001 : : *
3002 : : * This is consistent with how ALTER SCHEMA ... OWNER TO works, but some
3003 : : * other object types behave differently (e.g. you can't give a table to a
3004 : : * user who lacks CREATE privileges on a schema).
3005 : : */
3006 : 22 : aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
3007 : : GetUserId(), ACL_CREATE);
3008 [ - + ]: 22 : if (aclresult != ACLCHECK_OK)
3009 : 0 : aclcheck_error(aclresult, OBJECT_DATABASE,
3010 : 0 : get_database_name(MyDatabaseId));
3011 : :
3012 : : /*
3013 : : * The privileges will be checked before the connection is actually used,
3014 : : * so it does not need to be done here. Avoid unnecessary risk of errors
3015 : : * here, which could interfere with restore.
3016 : : *
3017 : : * However, it is convenient to check if a user mapping exists, and raise
3018 : : * a WARNING if not.
3019 : : */
3020 [ + + ]: 22 : if (OidIsValid(form->subserver))
3021 : 9 : GetUserMappingExtended(newOwnerId, form->subserver, WARNING);
3022 : :
3023 : 22 : form->subowner = newOwnerId;
3024 : 22 : CatalogTupleUpdate(rel, &tup->t_self, tup);
3025 : :
3026 : : /* Update owner of the conflict log table if it exists. */
3027 [ + + ]: 22 : if (OidIsValid(form->subconflictlogrelid))
3028 : 8 : ATExecChangeOwner(form->subconflictlogrelid, newOwnerId, true,
3029 : : AccessExclusiveLock);
3030 : :
3031 : : /* Update owner dependency reference */
3032 : 22 : changeDependencyOnOwner(SubscriptionRelationId,
3033 : : form->oid,
3034 : : newOwnerId);
3035 : :
3036 [ - + ]: 22 : InvokeObjectPostAlterHook(SubscriptionRelationId,
3037 : : form->oid, 0);
3038 : :
3039 : : /* Wake up related background processes to handle this change quickly. */
3040 : 22 : ApplyLauncherWakeupAtCommit();
3041 : 22 : LogicalRepWorkersWakeupAtCommit(form->oid);
3042 : : }
3043 : :
3044 : : /*
3045 : : * Change subscription owner -- by name
3046 : : */
3047 : : ObjectAddress
3048 : 27 : AlterSubscriptionOwner(const char *name, Oid newOwnerId)
3049 : : {
3050 : : Oid subid;
3051 : : HeapTuple tup;
3052 : : Relation rel;
3053 : : ObjectAddress address;
3054 : : Form_pg_subscription form;
3055 : :
3056 : 27 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
3057 : :
3058 : 27 : tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
3059 : : CStringGetDatum(name));
3060 : :
3061 [ - + ]: 27 : if (!HeapTupleIsValid(tup))
3062 [ # # ]: 0 : ereport(ERROR,
3063 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
3064 : : errmsg("subscription \"%s\" does not exist", name)));
3065 : :
3066 : 27 : form = (Form_pg_subscription) GETSTRUCT(tup);
3067 : 27 : subid = form->oid;
3068 : :
3069 : 27 : AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
3070 : :
3071 : 23 : ObjectAddressSet(address, SubscriptionRelationId, subid);
3072 : :
3073 : 23 : heap_freetuple(tup);
3074 : :
3075 : 23 : table_close(rel, RowExclusiveLock);
3076 : :
3077 : 23 : return address;
3078 : : }
3079 : :
3080 : : /*
3081 : : * Change subscription owner -- by OID
3082 : : */
3083 : : void
3084 : 2 : AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
3085 : : {
3086 : : HeapTuple tup;
3087 : : Relation rel;
3088 : : Form_pg_subscription form;
3089 : :
3090 : 2 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
3091 : :
3092 : 2 : tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
3093 : :
3094 [ - + ]: 2 : if (!HeapTupleIsValid(tup))
3095 [ # # ]: 0 : ereport(ERROR,
3096 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
3097 : : errmsg("subscription with OID %u does not exist", subid)));
3098 : :
3099 : 2 : form = (Form_pg_subscription) GETSTRUCT(tup);
3100 : :
3101 : : /*
3102 : : * Don't process subscriptions belonging to other databases. While
3103 : : * pg_subscription is a shared catalog, subscriptions refer to db-local
3104 : : * objects which exist only in the database identified by subdbid.
3105 : : */
3106 [ + + ]: 2 : if (form->subdbid == MyDatabaseId)
3107 : 1 : AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
3108 : :
3109 : 2 : heap_freetuple(tup);
3110 : :
3111 : 2 : table_close(rel, RowExclusiveLock);
3112 : 2 : }
3113 : :
3114 : : /*
3115 : : * Check and log a warning if the publisher has subscribed to the same table,
3116 : : * its partition ancestors (if it's a partition), or its partition children (if
3117 : : * it's a partitioned table), from some other publishers. This check is
3118 : : * required in the following scenarios:
3119 : : *
3120 : : * 1) For CREATE SUBSCRIPTION and ALTER SUBSCRIPTION ... REFRESH PUBLICATION
3121 : : * statements with "copy_data = true" and "origin = none":
3122 : : * - Warn the user that data with an origin might have been copied.
3123 : : * - This check is skipped for tables already added, as incremental sync via
3124 : : * WAL allows origin tracking. The list of such tables is in
3125 : : * subrel_local_oids.
3126 : : *
3127 : : * 2) For CREATE SUBSCRIPTION and ALTER SUBSCRIPTION ... REFRESH PUBLICATION
3128 : : * statements with "retain_dead_tuples = true" and "origin = any", and for
3129 : : * ALTER SUBSCRIPTION statements that modify retain_dead_tuples or origin,
3130 : : * or when the publisher's status changes (e.g., due to a connection string
3131 : : * update):
3132 : : * - Warn the user that only conflict detection info for local changes on
3133 : : * the publisher is retained. Data from other origins may lack sufficient
3134 : : * details for reliable conflict detection.
3135 : : * - See comments atop worker.c for more details.
3136 : : */
3137 : : static void
3138 : 176 : check_publications_origin_tables(WalReceiverConn *wrconn, List *publications,
3139 : : bool copydata, bool retain_dead_tuples,
3140 : : char *origin, Oid *subrel_local_oids,
3141 : : int subrel_count, char *subname)
3142 : : {
3143 : : WalRcvExecResult *res;
3144 : : StringInfoData cmd;
3145 : : TupleTableSlot *slot;
3146 : 176 : Oid tableRow[1] = {TEXTOID};
3147 : 176 : List *publist = NIL;
3148 : : int i;
3149 : : bool check_rdt;
3150 : : bool check_table_sync;
3151 [ + - + + ]: 352 : bool origin_none = origin &&
3152 : 176 : pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) == 0;
3153 : :
3154 : : /*
3155 : : * Enable retain_dead_tuples checks only when origin is set to 'any',
3156 : : * since with origin='none' only local changes are replicated to the
3157 : : * subscriber.
3158 : : */
3159 [ + + + + ]: 176 : check_rdt = retain_dead_tuples && !origin_none;
3160 : :
3161 : : /*
3162 : : * Enable table synchronization checks only when origin is 'none', to
3163 : : * ensure that data from other origins is not inadvertently copied.
3164 : : */
3165 [ + + + + ]: 176 : check_table_sync = copydata && origin_none;
3166 : :
3167 : : /* retain_dead_tuples and table sync checks occur separately */
3168 : : Assert(!(check_rdt && check_table_sync));
3169 : :
3170 : : /* Return if no checks are required */
3171 [ + + + + ]: 176 : if (!check_rdt && !check_table_sync)
3172 : 161 : return;
3173 : :
3174 : 15 : initStringInfo(&cmd);
3175 : 15 : appendStringInfoString(&cmd,
3176 : : "SELECT DISTINCT P.pubname AS pubname\n"
3177 : : "FROM pg_publication P,\n"
3178 : : " LATERAL pg_get_publication_tables(P.pubname) GPT\n"
3179 : : " JOIN pg_subscription_rel PS ON (GPT.relid = PS.srrelid OR"
3180 : : " GPT.relid IN (SELECT relid FROM pg_partition_ancestors(PS.srrelid) UNION"
3181 : : " SELECT relid FROM pg_partition_tree(PS.srrelid))),\n"
3182 : : " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
3183 : : "WHERE C.oid = GPT.relid AND P.pubname IN (");
3184 : 15 : GetPublicationsStr(publications, &cmd, true);
3185 : 15 : appendStringInfoString(&cmd, ")\n");
3186 : :
3187 : : /*
3188 : : * In case of ALTER SUBSCRIPTION ... REFRESH PUBLICATION,
3189 : : * subrel_local_oids contains the list of relation oids that are already
3190 : : * present on the subscriber. This check should be skipped for these
3191 : : * tables if checking for table sync scenario. However, when handling the
3192 : : * retain_dead_tuples scenario, ensure all tables are checked, as some
3193 : : * existing tables may now include changes from other origins due to newly
3194 : : * created subscriptions on the publisher.
3195 : : */
3196 [ + + ]: 15 : if (check_table_sync)
3197 : : {
3198 [ + + ]: 17 : for (i = 0; i < subrel_count; i++)
3199 : : {
3200 : 5 : Oid relid = subrel_local_oids[i];
3201 : : char *schemaname;
3202 : : char *tablename;
3203 : : char *schemaname_lit;
3204 : : char *tablename_lit;
3205 : :
3206 : : /* The table may have been dropped concurrently; skip if gone. */
3207 : 5 : tablename = get_rel_name(relid);
3208 [ - + ]: 5 : if (tablename == NULL)
3209 : 0 : continue;
3210 : :
3211 : 5 : schemaname = get_namespace_name(get_rel_namespace(relid));
3212 [ - + ]: 5 : if (schemaname == NULL)
3213 : 0 : continue;
3214 : :
3215 : 5 : schemaname_lit = quote_literal_cstr(schemaname);
3216 : 5 : tablename_lit = quote_literal_cstr(tablename);
3217 : :
3218 : 5 : appendStringInfo(&cmd, "AND NOT (N.nspname = %s AND C.relname = %s)\n",
3219 : : schemaname_lit, tablename_lit);
3220 : :
3221 : 5 : pfree(schemaname_lit);
3222 : 5 : pfree(tablename_lit);
3223 : : }
3224 : : }
3225 : :
3226 : 15 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
3227 : 15 : pfree(cmd.data);
3228 : :
3229 [ - + ]: 15 : if (res->status != WALRCV_OK_TUPLES)
3230 [ # # ]: 0 : ereport(ERROR,
3231 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3232 : : errmsg("could not receive list of replicated tables from the publisher: %s",
3233 : : res->err)));
3234 : :
3235 : : /* Process publications. */
3236 : 15 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3237 [ + + ]: 21 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3238 : : {
3239 : : char *pubname;
3240 : : bool isnull;
3241 : :
3242 : 6 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
3243 : : Assert(!isnull);
3244 : :
3245 : 6 : ExecClearTuple(slot);
3246 : 6 : publist = list_append_unique(publist, makeString(pubname));
3247 : : }
3248 : :
3249 : : /*
3250 : : * Log a warning if the publisher has subscribed to the same table from
3251 : : * some other publisher. We cannot know the origin of data during the
3252 : : * initial sync. Data origins can be found only from the WAL by looking at
3253 : : * the origin id.
3254 : : *
3255 : : * XXX: For simplicity, we don't check whether the table has any data or
3256 : : * not. If the table doesn't have any data then we don't need to
3257 : : * distinguish between data having origin and data not having origin so we
3258 : : * can avoid logging a warning for table sync scenario.
3259 : : */
3260 [ + + ]: 15 : if (publist)
3261 : : {
3262 : : StringInfoData pubnames;
3263 : :
3264 : : /* Prepare the list of publication(s) for warning message. */
3265 : 6 : initStringInfo(&pubnames);
3266 : 6 : GetPublicationsStr(publist, &pubnames, false);
3267 : :
3268 [ + + ]: 6 : if (check_table_sync)
3269 [ + - ]: 5 : ereport(WARNING,
3270 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3271 : : errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
3272 : : subname),
3273 : : errdetail_plural("The subscription subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
3274 : : "The subscription subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
3275 : : list_length(publist), pubnames.data),
3276 : : errhint("Verify that initial data copied from the publisher tables did not come from other origins."));
3277 : : else
3278 [ + - ]: 1 : ereport(WARNING,
3279 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3280 : : errmsg("subscription \"%s\" enabled retain_dead_tuples but might not reliably detect conflicts for changes from different origins",
3281 : : subname),
3282 : : errdetail_plural("The subscription subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
3283 : : "The subscription subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
3284 : : list_length(publist), pubnames.data),
3285 : : errhint("Consider using origin = NONE or disabling retain_dead_tuples."));
3286 : : }
3287 : :
3288 : 15 : ExecDropSingleTupleTableSlot(slot);
3289 : :
3290 : 15 : walrcv_clear_result(res);
3291 : : }
3292 : :
3293 : : /*
3294 : : * This function is similar to check_publications_origin_tables and serves
3295 : : * same purpose for sequences.
3296 : : */
3297 : : static void
3298 : 174 : check_publications_origin_sequences(WalReceiverConn *wrconn, List *publications,
3299 : : bool copydata, char *origin,
3300 : : Oid *subrel_local_oids, int subrel_count,
3301 : : char *subname)
3302 : : {
3303 : : WalRcvExecResult *res;
3304 : : StringInfoData cmd;
3305 : : TupleTableSlot *slot;
3306 : 174 : Oid tableRow[1] = {TEXTOID};
3307 : 174 : List *publist = NIL;
3308 : :
3309 : : /*
3310 : : * Enable sequence synchronization checks only when origin is 'none' , to
3311 : : * ensure that sequence data from other origins is not inadvertently
3312 : : * copied. This check is necessary if the publisher is running PG19 or
3313 : : * later, where logical replication sequence synchronization is supported.
3314 : : */
3315 [ + + + + : 186 : if (!copydata || pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) != 0 ||
- + ]
3316 : 12 : walrcv_server_version(wrconn) < 190000)
3317 : 162 : return;
3318 : :
3319 : 12 : initStringInfo(&cmd);
3320 : 12 : appendStringInfoString(&cmd,
3321 : : "SELECT DISTINCT P.pubname AS pubname\n"
3322 : : "FROM pg_publication P,\n"
3323 : : " LATERAL pg_get_publication_sequences(P.pubname) GPS\n"
3324 : : " JOIN pg_subscription_rel PS ON (GPS.relid = PS.srrelid),\n"
3325 : : " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
3326 : : "WHERE C.oid = GPS.relid AND P.pubname IN (");
3327 : :
3328 : 12 : GetPublicationsStr(publications, &cmd, true);
3329 : 12 : appendStringInfoString(&cmd, ")\n");
3330 : :
3331 : : /*
3332 : : * In case of ALTER SUBSCRIPTION ... REFRESH PUBLICATION,
3333 : : * subrel_local_oids contains the list of relations that are already
3334 : : * present on the subscriber. This check should be skipped as these will
3335 : : * not be re-synced.
3336 : : */
3337 [ + + ]: 13 : for (int i = 0; i < subrel_count; i++)
3338 : : {
3339 : 1 : Oid relid = subrel_local_oids[i];
3340 : : char *schemaname;
3341 : : char *seqname;
3342 : : char *schemaname_lit;
3343 : : char *seqname_lit;
3344 : :
3345 : : /* The sequence may have been dropped concurrently; skip if gone. */
3346 : 1 : seqname = get_rel_name(relid);
3347 [ + - ]: 1 : if (seqname == NULL)
3348 : 1 : continue;
3349 : :
3350 : 0 : schemaname = get_namespace_name(get_rel_namespace(relid));
3351 [ # # ]: 0 : if (schemaname == NULL)
3352 : 0 : continue;
3353 : :
3354 : 0 : schemaname_lit = quote_literal_cstr(schemaname);
3355 : 0 : seqname_lit = quote_literal_cstr(seqname);
3356 : :
3357 : 0 : appendStringInfo(&cmd,
3358 : : "AND NOT (N.nspname = %s AND C.relname = %s)\n",
3359 : : schemaname_lit, seqname_lit);
3360 : :
3361 : 0 : pfree(schemaname_lit);
3362 : 0 : pfree(seqname_lit);
3363 : : }
3364 : :
3365 : 12 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
3366 : 12 : pfree(cmd.data);
3367 : :
3368 [ - + ]: 12 : if (res->status != WALRCV_OK_TUPLES)
3369 [ # # ]: 0 : ereport(ERROR,
3370 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3371 : : errmsg("could not receive list of replicated sequences from the publisher: %s",
3372 : : res->err)));
3373 : :
3374 : : /* Process publications. */
3375 : 12 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3376 [ - + ]: 12 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3377 : : {
3378 : : char *pubname;
3379 : : bool isnull;
3380 : :
3381 : 0 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
3382 : : Assert(!isnull);
3383 : :
3384 : 0 : ExecClearTuple(slot);
3385 : 0 : publist = list_append_unique(publist, makeString(pubname));
3386 : : }
3387 : :
3388 : : /*
3389 : : * Log a warning if the publisher has subscribed to the same sequence from
3390 : : * some other publisher. We cannot know the origin of sequences data
3391 : : * during the initial sync.
3392 : : */
3393 [ - + ]: 12 : if (publist)
3394 : : {
3395 : : StringInfoData pubnames;
3396 : :
3397 : : /* Prepare the list of publication(s) for warning message. */
3398 : 0 : initStringInfo(&pubnames);
3399 : 0 : GetPublicationsStr(publist, &pubnames, false);
3400 : :
3401 [ # # ]: 0 : ereport(WARNING,
3402 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3403 : : errmsg("subscription \"%s\" requested origin = NONE but might synchronize sequence values that had a different origin",
3404 : : subname),
3405 : : errdetail_plural("The subscription subscribes to a publication (%s) that contains sequences that are synchronized from other subscriptions.",
3406 : : "The subscription subscribes to publications (%s) that contain sequences that are synchronized from other subscriptions.",
3407 : : list_length(publist), pubnames.data),
3408 : : errhint("Verify that the initial values copied from the publisher sequences did not come from other origins."));
3409 : : }
3410 : :
3411 : 12 : ExecDropSingleTupleTableSlot(slot);
3412 : :
3413 : 12 : walrcv_clear_result(res);
3414 : : }
3415 : :
3416 : : /*
3417 : : * Determine whether the retain_dead_tuples can be enabled based on the
3418 : : * publisher's status.
3419 : : *
3420 : : * This option is disallowed if the publisher is running a version earlier
3421 : : * than the PG19, or if the publisher is in recovery (i.e., it is a standby
3422 : : * server).
3423 : : *
3424 : : * This is used both at DDL time (as a convenience, when a connection to the
3425 : : * publisher is already being made) and by the apply worker when it connects,
3426 : : * which is the authoritative check because the publisher's version and
3427 : : * recovery status can change after the DDL command.
3428 : : *
3429 : : * See comments atop worker.c for a detailed explanation.
3430 : : */
3431 : : void
3432 : 21 : CheckPubDeadTupleRetention(WalReceiverConn *wrconn)
3433 : : {
3434 : : WalRcvExecResult *res;
3435 : 21 : Oid RecoveryRow[1] = {BOOLOID};
3436 : : TupleTableSlot *slot;
3437 : : bool isnull;
3438 : : bool remote_in_recovery;
3439 : :
3440 [ - + ]: 21 : if (walrcv_server_version(wrconn) < 190000)
3441 [ # # ]: 0 : ereport(ERROR,
3442 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3443 : : errmsg("cannot enable retain_dead_tuples if the publisher is running a version earlier than PostgreSQL 19"));
3444 : :
3445 : 21 : res = walrcv_exec(wrconn, "SELECT pg_is_in_recovery()", 1, RecoveryRow);
3446 : :
3447 [ - + ]: 21 : if (res->status != WALRCV_OK_TUPLES)
3448 [ # # ]: 0 : ereport(ERROR,
3449 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3450 : : errmsg("could not obtain recovery progress from the publisher: %s",
3451 : : res->err)));
3452 : :
3453 : 21 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3454 [ - + ]: 21 : if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3455 [ # # ]: 0 : elog(ERROR, "failed to fetch tuple for the recovery progress");
3456 : :
3457 : 21 : remote_in_recovery = DatumGetBool(slot_getattr(slot, 1, &isnull));
3458 : :
3459 [ - + ]: 21 : if (remote_in_recovery)
3460 [ # # ]: 0 : ereport(ERROR,
3461 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3462 : : errmsg("cannot enable retain_dead_tuples if the publisher is in recovery"));
3463 : :
3464 : 21 : ExecDropSingleTupleTableSlot(slot);
3465 : :
3466 : 21 : walrcv_clear_result(res);
3467 : 21 : }
3468 : :
3469 : : /*
3470 : : * Check if the subscriber's configuration is adequate to enable the
3471 : : * retain_dead_tuples option.
3472 : : *
3473 : : * Issue an ERROR if the wal_level does not support the use of replication
3474 : : * slots when check_guc is set to true.
3475 : : *
3476 : : * Issue a WARNING if track_commit_timestamp is not enabled when check_guc is
3477 : : * set to true. This is only to highlight the importance of enabling
3478 : : * track_commit_timestamp instead of catching all the misconfigurations, as
3479 : : * this setting can be adjusted after subscription creation. Without it, the
3480 : : * apply worker will simply skip conflict detection.
3481 : : *
3482 : : * Issue a WARNING or NOTICE if the subscription is disabled and the retention
3483 : : * is active. Do not raise an ERROR since users can only modify
3484 : : * retain_dead_tuples for disabled subscriptions. And as long as the
3485 : : * subscription is enabled promptly, it will not pose issues.
3486 : : *
3487 : : * Issue a NOTICE to inform users that max_retention_duration is
3488 : : * ineffective when retain_dead_tuples is disabled for a subscription. An ERROR
3489 : : * is not issued because setting max_retention_duration causes no harm,
3490 : : * even when it is ineffective.
3491 : : */
3492 : : void
3493 : 340 : CheckSubDeadTupleRetention(bool check_guc, bool sub_disabled,
3494 : : int elevel_for_sub_disabled,
3495 : : bool retain_dead_tuples, bool retention_active,
3496 : : bool max_retention_set)
3497 : : {
3498 : : Assert(elevel_for_sub_disabled == NOTICE ||
3499 : : elevel_for_sub_disabled == WARNING);
3500 : :
3501 [ + + ]: 340 : if (retain_dead_tuples)
3502 : : {
3503 [ + + - + ]: 18 : if (check_guc && wal_level < WAL_LEVEL_REPLICA)
3504 [ # # ]: 0 : ereport(ERROR,
3505 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3506 : : errmsg("\"wal_level\" is insufficient to create the replication slot required by retain_dead_tuples"),
3507 : : errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start."));
3508 : :
3509 [ + + + + ]: 18 : if (check_guc && !track_commit_timestamp)
3510 [ + - ]: 4 : ereport(WARNING,
3511 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3512 : : errmsg("commit timestamp and origin data required for detecting conflicts won't be retained"),
3513 : : errhint("Consider setting \"%s\" to true.",
3514 : : "track_commit_timestamp"));
3515 : :
3516 [ + + + - ]: 18 : if (sub_disabled && retention_active)
3517 [ + - + + ]: 7 : ereport(elevel_for_sub_disabled,
3518 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3519 : : errmsg("deleted rows to detect conflicts would not be removed until the subscription is enabled"),
3520 : : (elevel_for_sub_disabled > NOTICE)
3521 : : ? errhint("Consider setting %s to false.",
3522 : : "retain_dead_tuples") : 0);
3523 : : }
3524 [ + + ]: 322 : else if (max_retention_set)
3525 : : {
3526 [ + - ]: 4 : ereport(NOTICE,
3527 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3528 : : errmsg("max_retention_duration is ineffective when retain_dead_tuples is disabled"));
3529 : : }
3530 : 340 : }
3531 : :
3532 : : /*
3533 : : * Return true iff 'rv' is a member of the list.
3534 : : */
3535 : : static bool
3536 : 293 : list_member_rangevar(const List *list, RangeVar *rv)
3537 : : {
3538 [ + + + + : 1059 : foreach_ptr(PublicationRelKind, relinfo, list)
+ + ]
3539 : : {
3540 [ + + ]: 475 : if (equal(relinfo->rv, rv))
3541 : 1 : return true;
3542 : : }
3543 : :
3544 : 292 : return false;
3545 : : }
3546 : :
3547 : : /*
3548 : : * Get the list of tables and sequences which belong to specified publications
3549 : : * on the publisher connection.
3550 : : *
3551 : : * Note that we don't support the case where the column list is different for
3552 : : * the same table in different publications to avoid sending unwanted column
3553 : : * information for some of the rows. This can happen when both the column
3554 : : * list and row filter are specified for different publications.
3555 : : */
3556 : : static List *
3557 : 169 : fetch_relation_list(WalReceiverConn *wrconn, List *publications)
3558 : : {
3559 : : WalRcvExecResult *res;
3560 : : StringInfoData cmd;
3561 : : TupleTableSlot *slot;
3562 : 169 : Oid tableRow[4] = {TEXTOID, TEXTOID, CHAROID, InvalidOid};
3563 : 169 : List *relationlist = NIL;
3564 : 169 : int server_version = walrcv_server_version(wrconn);
3565 : 169 : bool check_columnlist = (server_version >= 150000);
3566 [ + - ]: 169 : int column_count = check_columnlist ? 4 : 3;
3567 : : StringInfoData pub_names;
3568 : :
3569 : 169 : initStringInfo(&cmd);
3570 : 169 : initStringInfo(&pub_names);
3571 : :
3572 : : /* Build the pub_names comma-separated string. */
3573 : 169 : GetPublicationsStr(publications, &pub_names, true);
3574 : :
3575 : : /* Get the list of relations from the publisher */
3576 [ + - ]: 169 : if (server_version >= 160000)
3577 : : {
3578 : 169 : tableRow[3] = INT2VECTOROID;
3579 : :
3580 : : /*
3581 : : * From version 16, we allowed passing multiple publications to the
3582 : : * function pg_get_publication_tables. This helped to filter out the
3583 : : * partition table whose ancestor is also published in this
3584 : : * publication array.
3585 : : *
3586 : : * Join pg_get_publication_tables with pg_publication to exclude
3587 : : * non-existing publications.
3588 : : *
3589 : : * Note that attrs are always stored in sorted order so we don't need
3590 : : * to worry if different publications have specified them in a
3591 : : * different order. See pub_collist_validate.
3592 : : */
3593 : 169 : appendStringInfo(&cmd, "SELECT DISTINCT n.nspname, c.relname, c.relkind, gpt.attrs\n"
3594 : : " FROM pg_class c\n"
3595 : : " JOIN pg_namespace n ON n.oid = c.relnamespace\n"
3596 : : " JOIN ( SELECT (pg_get_publication_tables(VARIADIC array_agg(pubname::text))).*\n"
3597 : : " FROM pg_publication\n"
3598 : : " WHERE pubname IN ( %s )) AS gpt\n"
3599 : : " ON gpt.relid = c.oid\n",
3600 : : pub_names.data);
3601 : :
3602 : : /* From version 19, inclusion of sequences in the target is supported */
3603 [ + - ]: 169 : if (server_version >= 190000)
3604 : 169 : appendStringInfo(&cmd,
3605 : : "UNION ALL\n"
3606 : : " SELECT DISTINCT s.schemaname, s.sequencename, " CppAsString2(RELKIND_SEQUENCE) "::\"char\" AS relkind, NULL::int2vector AS attrs\n"
3607 : : " FROM pg_catalog.pg_publication_sequences s\n"
3608 : : " WHERE s.pubname IN ( %s )",
3609 : : pub_names.data);
3610 : : }
3611 : : else
3612 : : {
3613 : 0 : tableRow[3] = NAMEARRAYOID;
3614 : 0 : appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename, " CppAsString2(RELKIND_RELATION) "::\"char\" AS relkind \n");
3615 : :
3616 : : /* Get column lists for each relation if the publisher supports it */
3617 [ # # ]: 0 : if (check_columnlist)
3618 : 0 : appendStringInfoString(&cmd, ", t.attnames\n");
3619 : :
3620 : 0 : appendStringInfo(&cmd, "FROM pg_catalog.pg_publication_tables t\n"
3621 : : " WHERE t.pubname IN ( %s )",
3622 : : pub_names.data);
3623 : : }
3624 : :
3625 : 169 : pfree(pub_names.data);
3626 : :
3627 : 169 : res = walrcv_exec(wrconn, cmd.data, column_count, tableRow);
3628 : 169 : pfree(cmd.data);
3629 : :
3630 [ - + ]: 169 : if (res->status != WALRCV_OK_TUPLES)
3631 [ # # ]: 0 : ereport(ERROR,
3632 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3633 : : errmsg("could not receive list of replicated tables from the publisher: %s",
3634 : : res->err)));
3635 : :
3636 : : /* Process tables. */
3637 : 169 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3638 [ + + ]: 479 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3639 : : {
3640 : : char *nspname;
3641 : : char *relname;
3642 : : bool isnull;
3643 : : char relkind;
3644 : 311 : PublicationRelKind *relinfo = palloc_object(PublicationRelKind);
3645 : :
3646 : 311 : nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
3647 : : Assert(!isnull);
3648 : 311 : relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
3649 : : Assert(!isnull);
3650 : 311 : relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
3651 : : Assert(!isnull);
3652 : :
3653 : 311 : relinfo->rv = makeRangeVar(nspname, relname, -1);
3654 : 311 : relinfo->relkind = relkind;
3655 : :
3656 [ + + + - ]: 311 : if (relkind != RELKIND_SEQUENCE &&
3657 [ + + ]: 293 : check_columnlist &&
3658 : 293 : list_member_rangevar(relationlist, relinfo->rv))
3659 [ + - ]: 1 : ereport(ERROR,
3660 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3661 : : errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
3662 : : nspname, relname));
3663 : : else
3664 : 310 : relationlist = lappend(relationlist, relinfo);
3665 : :
3666 : 310 : ExecClearTuple(slot);
3667 : : }
3668 : 168 : ExecDropSingleTupleTableSlot(slot);
3669 : :
3670 : 168 : walrcv_clear_result(res);
3671 : :
3672 : 168 : return relationlist;
3673 : : }
3674 : :
3675 : : /*
3676 : : * This is to report the connection failure while dropping replication slots.
3677 : : * Here, we report the WARNING for all tablesync slots so that user can drop
3678 : : * them manually, if required.
3679 : : */
3680 : : static void
3681 : 4 : ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
3682 : : {
3683 : : ListCell *lc;
3684 : :
3685 [ - + - - : 4 : foreach(lc, rstates)
- + ]
3686 : : {
3687 : 0 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
3688 : 0 : Oid relid = rstate->relid;
3689 : :
3690 : : /* Only cleanup resources of tablesync workers */
3691 [ # # ]: 0 : if (!OidIsValid(relid))
3692 : 0 : continue;
3693 : :
3694 : : /*
3695 : : * Caller needs to ensure that relstate doesn't change underneath us.
3696 : : * See DropSubscription where we get the relstates.
3697 : : */
3698 [ # # ]: 0 : if (rstate->state != SUBREL_STATE_SYNCDONE)
3699 : : {
3700 : 0 : char syncslotname[NAMEDATALEN] = {0};
3701 : :
3702 : 0 : ReplicationSlotNameForTablesync(subid, relid, syncslotname,
3703 : : sizeof(syncslotname));
3704 [ # # ]: 0 : elog(WARNING, "could not drop tablesync replication slot \"%s\"",
3705 : : syncslotname);
3706 : : }
3707 : : }
3708 : :
3709 [ + - ]: 4 : ereport(ERROR,
3710 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3711 : : errmsg("could not connect to publisher when attempting to drop replication slot \"%s\": %s",
3712 : : slotname, err),
3713 : : /* translator: %s is an SQL ALTER command */
3714 : : errhint("Use %s to disable the subscription, and then use %s to disassociate it from the slot.",
3715 : : "ALTER SUBSCRIPTION ... DISABLE",
3716 : : "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
3717 : : }
3718 : :
3719 : : /*
3720 : : * Check for duplicates in the given list of publications and error out if
3721 : : * found one. Add publications to datums as text datums, if datums is not
3722 : : * NULL.
3723 : : */
3724 : : static void
3725 : 294 : check_duplicates_in_publist(List *publist, Datum *datums)
3726 : : {
3727 : : ListCell *cell;
3728 : 294 : int j = 0;
3729 : :
3730 [ + - + + : 664 : foreach(cell, publist)
+ + ]
3731 : : {
3732 : 382 : char *name = strVal(lfirst(cell));
3733 : : ListCell *pcell;
3734 : :
3735 [ + - + - : 547 : foreach(pcell, publist)
+ - ]
3736 : : {
3737 : 547 : char *pname = strVal(lfirst(pcell));
3738 : :
3739 [ + + ]: 547 : if (pcell == cell)
3740 : 370 : break;
3741 : :
3742 [ + + ]: 177 : if (strcmp(name, pname) == 0)
3743 [ + - ]: 12 : ereport(ERROR,
3744 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
3745 : : errmsg("publication name \"%s\" used more than once",
3746 : : pname)));
3747 : : }
3748 : :
3749 [ + + ]: 370 : if (datums)
3750 : 314 : datums[j++] = CStringGetTextDatum(name);
3751 : : }
3752 : 282 : }
3753 : :
3754 : : /*
3755 : : * Merge current subscription's publications and user-specified publications
3756 : : * from ADD/DROP PUBLICATIONS.
3757 : : *
3758 : : * If addpub is true, we will add the list of publications into oldpublist.
3759 : : * Otherwise, we will delete the list of publications from oldpublist. The
3760 : : * returned list is a copy, oldpublist itself is not changed.
3761 : : *
3762 : : * subname is the subscription name, for error messages.
3763 : : */
3764 : : static List *
3765 : 35 : merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
3766 : : {
3767 : : ListCell *lc;
3768 : :
3769 : 35 : oldpublist = list_copy(oldpublist);
3770 : :
3771 : 35 : check_duplicates_in_publist(newpublist, NULL);
3772 : :
3773 [ + - + + : 59 : foreach(lc, newpublist)
+ + ]
3774 : : {
3775 : 44 : char *name = strVal(lfirst(lc));
3776 : : ListCell *lc2;
3777 : 44 : bool found = false;
3778 : :
3779 [ + - + + : 86 : foreach(lc2, oldpublist)
+ + ]
3780 : : {
3781 : 71 : char *pubname = strVal(lfirst(lc2));
3782 : :
3783 [ + + ]: 71 : if (strcmp(name, pubname) == 0)
3784 : : {
3785 : 29 : found = true;
3786 [ + + ]: 29 : if (addpub)
3787 [ + - ]: 8 : ereport(ERROR,
3788 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
3789 : : errmsg("publication \"%s\" is already in subscription \"%s\"",
3790 : : name, subname)));
3791 : : else
3792 : 21 : oldpublist = foreach_delete_current(oldpublist, lc2);
3793 : :
3794 : 21 : break;
3795 : : }
3796 : : }
3797 : :
3798 [ + + + - ]: 36 : if (addpub && !found)
3799 : 11 : oldpublist = lappend(oldpublist, makeString(name));
3800 [ + - + + ]: 25 : else if (!addpub && !found)
3801 [ + - ]: 4 : ereport(ERROR,
3802 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3803 : : errmsg("publication \"%s\" is not in subscription \"%s\"",
3804 : : name, subname)));
3805 : : }
3806 : :
3807 : : /*
3808 : : * XXX Probably no strong reason for this, but for now it's to make ALTER
3809 : : * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
3810 : : */
3811 [ + + ]: 15 : if (!oldpublist)
3812 [ + - ]: 4 : ereport(ERROR,
3813 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3814 : : errmsg("cannot drop all the publications from a subscription")));
3815 : :
3816 : 11 : return oldpublist;
3817 : : }
3818 : :
3819 : : /*
3820 : : * Extract the streaming mode value from a DefElem. This is like
3821 : : * defGetBoolean() but also accepts the special value of "parallel".
3822 : : */
3823 : : char
3824 : 506 : defGetStreamingMode(DefElem *def)
3825 : : {
3826 : : /*
3827 : : * If no parameter value given, assume "true" is meant.
3828 : : */
3829 [ - + ]: 506 : if (!def->arg)
3830 : 0 : return LOGICALREP_STREAM_ON;
3831 : :
3832 : : /*
3833 : : * Allow 0, 1, "false", "true", "off", "on" or "parallel".
3834 : : */
3835 [ - + ]: 506 : switch (nodeTag(def->arg))
3836 : : {
3837 : 0 : case T_Integer:
3838 [ # # # ]: 0 : switch (intVal(def->arg))
3839 : : {
3840 : 0 : case 0:
3841 : 0 : return LOGICALREP_STREAM_OFF;
3842 : 0 : case 1:
3843 : 0 : return LOGICALREP_STREAM_ON;
3844 : 0 : default:
3845 : : /* otherwise, error out below */
3846 : 0 : break;
3847 : : }
3848 : 0 : break;
3849 : 506 : default:
3850 : : {
3851 : 506 : char *sval = defGetString(def);
3852 : :
3853 : : /*
3854 : : * The set of strings accepted here should match up with the
3855 : : * grammar's opt_boolean_or_string production.
3856 : : */
3857 [ + + + + ]: 1008 : if (pg_strcasecmp(sval, "false") == 0 ||
3858 : 502 : pg_strcasecmp(sval, "off") == 0)
3859 : 7 : return LOGICALREP_STREAM_OFF;
3860 [ + + + + ]: 986 : if (pg_strcasecmp(sval, "true") == 0 ||
3861 : 487 : pg_strcasecmp(sval, "on") == 0)
3862 : 49 : return LOGICALREP_STREAM_ON;
3863 [ + + ]: 450 : if (pg_strcasecmp(sval, "parallel") == 0)
3864 : 446 : return LOGICALREP_STREAM_PARALLEL;
3865 : : }
3866 : 4 : break;
3867 : : }
3868 : :
3869 [ + - ]: 4 : ereport(ERROR,
3870 : : (errcode(ERRCODE_SYNTAX_ERROR),
3871 : : errmsg("%s requires a Boolean value or \"parallel\"",
3872 : : def->defname)));
3873 : : return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
3874 : : }
|