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 : 762 : 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 : 762 : 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 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_CONNECT))
180 : 340 : opts->connect = true;
181 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_ENABLED))
182 : 431 : opts->enabled = true;
183 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
184 : 340 : opts->create_slot = true;
185 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_COPY_DATA))
186 : 445 : opts->copy_data = true;
187 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_REFRESH))
188 : 58 : opts->refresh = true;
189 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_BINARY))
190 : 551 : opts->binary = false;
191 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_STREAMING))
192 : 551 : opts->streaming = LOGICALREP_STREAM_PARALLEL;
193 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
194 : 551 : opts->twophase = false;
195 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
196 : 551 : opts->disableonerr = false;
197 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED))
198 : 551 : opts->passwordrequired = true;
199 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER))
200 : 551 : opts->runasowner = false;
201 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_FAILOVER))
202 : 551 : opts->failover = false;
203 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_RETAIN_DEAD_TUPLES))
204 : 551 : opts->retaindeadtuples = false;
205 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_MAX_RETENTION_DURATION))
206 : 551 : opts->maxretention = 0;
207 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_ORIGIN))
208 : 551 : opts->origin = pstrdup(LOGICALREP_ORIGIN_ANY);
209 [ + + ]: 762 : if (IsSet(supported_opts, SUBOPT_CONFLICT_LOG_DEST))
210 : 551 : opts->conflictlogdest = CONFLICT_LOG_DEST_LOG;
211 : :
212 : : /* Parse options */
213 [ + + + + : 1536 : foreach(lc, stmt_options)
+ + ]
214 : : {
215 : 838 : DefElem *defel = (DefElem *) lfirst(lc);
216 : :
217 [ + + ]: 838 : 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 [ + + ]: 667 : else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
227 [ + + ]: 383 : strcmp(defel->defname, "enabled") == 0)
228 : : {
229 [ - + ]: 115 : if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
230 : 0 : errorConflictingDefElem(defel, pstate);
231 : :
232 : 115 : opts->specified_opts |= SUBOPT_ENABLED;
233 : 115 : opts->enabled = defGetBoolean(defel);
234 : : }
235 [ + + ]: 552 : 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 [ + + ]: 527 : else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
245 [ + + ]: 456 : 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 [ + + ]: 384 : else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
260 [ + + ]: 232 : strcmp(defel->defname, "copy_data") == 0)
261 : : {
262 [ - + ]: 35 : if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
263 : 0 : errorConflictingDefElem(defel, pstate);
264 : :
265 : 35 : opts->specified_opts |= SUBOPT_COPY_DATA;
266 : 35 : opts->copy_data = defGetBoolean(defel);
267 : : }
268 [ + + ]: 349 : else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
269 [ + + ]: 286 : 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 [ + + ]: 333 : 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 [ + + ]: 285 : else if (IsSet(supported_opts, SUBOPT_BINARY) &&
292 [ + + ]: 270 : 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 [ + + ]: 266 : else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
301 [ + + ]: 251 : 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 [ + + ]: 223 : else if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT) &&
310 [ + + ]: 208 : strcmp(defel->defname, "two_phase") == 0)
311 : : {
312 [ - + ]: 25 : if (IsSet(opts->specified_opts, SUBOPT_TWOPHASE_COMMIT))
313 : 0 : errorConflictingDefElem(defel, pstate);
314 : :
315 : 25 : opts->specified_opts |= SUBOPT_TWOPHASE_COMMIT;
316 : 25 : opts->twophase = defGetBoolean(defel);
317 : : }
318 [ + + ]: 198 : else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
319 [ + + ]: 183 : 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 [ + + ]: 177 : else if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED) &&
328 [ + + ]: 162 : strcmp(defel->defname, "password_required") == 0)
329 : : {
330 [ - + ]: 18 : if (IsSet(opts->specified_opts, SUBOPT_PASSWORD_REQUIRED))
331 : 0 : errorConflictingDefElem(defel, pstate);
332 : :
333 : 18 : opts->specified_opts |= SUBOPT_PASSWORD_REQUIRED;
334 : 18 : 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 [ + + + + ]: 698 : 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 [ + + ]: 686 : if (!opts->slot_name &&
509 [ + + ]: 662 : 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 : 666 : }
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 : 305 : appendQuotedString(StringInfo buf, const char *str, char quote)
555 : : {
556 : 305 : appendStringInfoChar(buf, quote);
557 [ + + ]: 9698 : while (*str)
558 : : {
559 : 9393 : char c = *str++;
560 : :
561 [ - + ]: 9393 : if (c == quote)
562 : 0 : appendStringInfoChar(buf, c);
563 : 9393 : appendStringInfoChar(buf, c);
564 : : }
565 : 305 : appendStringInfoChar(buf, quote);
566 : 305 : }
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 : 141 : check_publications(WalReceiverConn *wrconn, List *publications)
576 : : {
577 : : WalRcvExecResult *res;
578 : : StringInfoData cmd;
579 : : TupleTableSlot *slot;
580 : 141 : List *publicationsCopy = NIL;
581 : 141 : Oid tableRow[1] = {TEXTOID};
582 : :
583 : 141 : initStringInfo(&cmd);
584 : 141 : appendStringInfoString(&cmd, "SELECT t.pubname FROM\n"
585 : : " pg_catalog.pg_publication t WHERE\n"
586 : : " t.pubname IN (");
587 : 141 : GetPublicationsStr(publications, &cmd, true);
588 : 141 : appendStringInfoChar(&cmd, ')');
589 : :
590 : 141 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
591 : 141 : pfree(cmd.data);
592 : :
593 [ - + ]: 141 : 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 : 141 : publicationsCopy = list_copy(publications);
599 : :
600 : : /* Process publication(s). */
601 : 141 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
602 [ + + ]: 313 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
603 : : {
604 : : char *pubname;
605 : : bool isnull;
606 : :
607 : 172 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
608 : : Assert(!isnull);
609 : :
610 : : /* Delete the publication present in publisher from the list. */
611 : 172 : publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
612 : 172 : ExecClearTuple(slot);
613 : : }
614 : :
615 : 141 : ExecDropSingleTupleTableSlot(slot);
616 : :
617 : 141 : walrcv_clear_result(res);
618 : :
619 [ + + ]: 141 : 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 : 141 : }
635 : :
636 : : /*
637 : : * Auxiliary function to build a text array out of a list of String nodes.
638 : : */
639 : : static Datum
640 : 261 : 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 : 261 : memcxt = AllocSetContextCreate(CurrentMemoryContext,
649 : : "publicationListToArray to array",
650 : : ALLOCSET_DEFAULT_SIZES);
651 : 261 : oldcxt = MemoryContextSwitchTo(memcxt);
652 : :
653 : 261 : datums = palloc_array(Datum, list_length(publist));
654 : :
655 : 261 : check_duplicates_in_publist(publist, datums);
656 : :
657 : 257 : MemoryContextSwitchTo(oldcxt);
658 : :
659 : 257 : arr = construct_array_builtin(datums, list_length(publist), TEXTOID);
660 : :
661 : 257 : MemoryContextDelete(memcxt);
662 : :
663 : 257 : return PointerGetDatum(arr);
664 : : }
665 : :
666 : : /*
667 : : * Create new subscription.
668 : : */
669 : : ObjectAddress
670 : 340 : 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 : 340 : Oid owner = GetUserId();
679 : : HeapTuple tup;
680 : 340 : Oid serverid = InvalidOid;
681 : 340 : char *conninfo = NULL;
682 : : char originname[NAMEDATALEN];
683 : : List *publications;
684 : : uint32 supported_opts;
685 : 340 : SubOpts opts = {0};
686 : : AclResult aclresult;
687 : 340 : Oid logrelid = InvalidOid;
688 : :
689 : : /*
690 : : * Parse and check options.
691 : : *
692 : : * Connection and publication should not be specified here.
693 : : */
694 : 340 : 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 : 340 : 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 [ + + ]: 268 : if (opts.create_slot)
713 : 144 : 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 [ + + ]: 264 : 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 : 260 : aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
732 : : owner, ACL_CREATE);
733 [ + + ]: 260 : 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 [ + + + + ]: 256 : 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 : 252 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
758 : :
759 : : /* Check if name is used */
760 : 252 : subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
761 : : ObjectIdGetDatum(MyDatabaseId), CStringGetDatum(stmt->subname));
762 [ + + ]: 252 : 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 : 248 : CheckSubDeadTupleRetention(true, !opts.enabled, WARNING,
775 : 248 : opts.retaindeadtuples, opts.retaindeadtuples,
776 : 248 : (opts.maxretention > 0));
777 : :
778 [ + + ]: 248 : if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
779 [ + - ]: 205 : opts.slot_name == NULL)
780 : 205 : opts.slot_name = stmt->subname;
781 : :
782 : : /* The default for synchronous_commit of subscriptions is off. */
783 [ + - ]: 248 : if (opts.synchronous_commit == NULL)
784 : 248 : 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 [ + - ]: 248 : if (opts.wal_receiver_timeout == NULL)
792 : 248 : opts.wal_receiver_timeout = "-1";
793 : :
794 : : /* Load the library providing us libpq calls. */
795 : 248 : load_file("libpqwalreceiver", false);
796 : :
797 [ + + ]: 248 : 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 : 228 : conninfo = stmt->conninfo;
840 [ + + + + ]: 228 : walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
841 : : }
842 : :
843 : 227 : publications = stmt->publication;
844 : :
845 : : /* Everything ok, form a new tuple. */
846 : 227 : memset(values, 0, sizeof(values));
847 : 227 : memset(nulls, false, sizeof(nulls));
848 : :
849 : 227 : subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
850 : : Anum_pg_subscription_oid);
851 : 227 : values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
852 : 227 : values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
853 : 227 : values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
854 : 227 : values[Anum_pg_subscription_subname - 1] =
855 : 227 : DirectFunctionCall1(namein, CStringGetDatum(stmt->subname));
856 : 227 : values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
857 : 227 : values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
858 : 227 : values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
859 : 227 : values[Anum_pg_subscription_substream - 1] = CharGetDatum(opts.streaming);
860 : 227 : values[Anum_pg_subscription_subtwophasestate - 1] =
861 [ + + ]: 227 : CharGetDatum(opts.twophase ?
862 : : LOGICALREP_TWOPHASE_STATE_PENDING :
863 : : LOGICALREP_TWOPHASE_STATE_DISABLED);
864 : 227 : values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
865 : 227 : values[Anum_pg_subscription_subpasswordrequired - 1] = BoolGetDatum(opts.passwordrequired);
866 : 227 : values[Anum_pg_subscription_subrunasowner - 1] = BoolGetDatum(opts.runasowner);
867 : 227 : values[Anum_pg_subscription_subfailover - 1] = BoolGetDatum(opts.failover);
868 : 227 : values[Anum_pg_subscription_subretaindeadtuples - 1] =
869 : 227 : BoolGetDatum(opts.retaindeadtuples);
870 : 227 : values[Anum_pg_subscription_submaxretention - 1] =
871 : 227 : Int32GetDatum(opts.maxretention);
872 : 227 : values[Anum_pg_subscription_subretentionactive - 1] =
873 : 227 : BoolGetDatum(opts.retaindeadtuples);
874 : 227 : values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(serverid);
875 [ + + ]: 227 : if (stmt->conninfo)
876 : : {
877 : : Assert(stmt->conninfo == conninfo && !OidIsValid(serverid));
878 : 216 : values[Anum_pg_subscription_subconninfo - 1] =
879 : 216 : CStringGetTextDatum(stmt->conninfo);
880 : : }
881 : : else
882 : : {
883 : : Assert(OidIsValid(serverid));
884 : 11 : nulls[Anum_pg_subscription_subconninfo - 1] = true;
885 : : }
886 [ + + ]: 227 : if (opts.slot_name)
887 : 212 : values[Anum_pg_subscription_subslotname - 1] =
888 : 212 : DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
889 : : else
890 : 15 : nulls[Anum_pg_subscription_subslotname - 1] = true;
891 : 227 : values[Anum_pg_subscription_subsynccommit - 1] =
892 : 227 : CStringGetTextDatum(opts.synchronous_commit);
893 : 227 : values[Anum_pg_subscription_subwalrcvtimeout - 1] =
894 : 227 : CStringGetTextDatum(opts.wal_receiver_timeout);
895 : 223 : values[Anum_pg_subscription_subpublications - 1] =
896 : 227 : publicationListToArray(publications);
897 : 223 : values[Anum_pg_subscription_suborigin - 1] =
898 : 223 : CStringGetTextDatum(opts.origin);
899 : :
900 : 223 : values[Anum_pg_subscription_subconflictlogdest - 1] =
901 : 223 : 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 [ + + + + ]: 223 : 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 : 223 : values[Anum_pg_subscription_subconflictlogrelid - 1] =
913 : 223 : ObjectIdGetDatum(logrelid);
914 : :
915 : 223 : tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
916 : :
917 : : /* Insert tuple into catalog. */
918 : 223 : CatalogTupleInsert(rel, tup);
919 : 223 : heap_freetuple(tup);
920 : :
921 : 223 : recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
922 : :
923 : 223 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
924 : :
925 [ + + ]: 223 : 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 [ + + ]: 223 : 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 : 223 : ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
965 : 223 : replorigin_create(originname);
966 : :
967 : : /*
968 : : * Connect to remote side to execute requested commands and fetch table
969 : : * and sequence info.
970 : : */
971 [ + + ]: 223 : if (opts.connect)
972 : : {
973 : : char *err;
974 : : WalReceiverConn *wrconn;
975 : : bool must_use_password;
976 : :
977 : : /* Try to connect to the publisher. */
978 [ - + - - ]: 136 : must_use_password = !superuser_arg(owner) && opts.passwordrequired;
979 : 136 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
980 : : stmt->subname, &err);
981 [ + + ]: 136 : 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 [ + + ]: 132 : PG_TRY();
988 : : {
989 : 132 : bool has_tables = false;
990 : : List *pubrels;
991 : : char relation_state;
992 : :
993 : 132 : check_publications(wrconn, publications);
994 : 132 : check_publications_origin_tables(wrconn, publications,
995 : 132 : opts.copy_data,
996 : 132 : opts.retaindeadtuples, opts.origin,
997 : : NULL, 0, stmt->subname);
998 : 132 : check_publications_origin_sequences(wrconn, publications,
999 : 132 : opts.copy_data, opts.origin,
1000 : : NULL, 0, stmt->subname);
1001 : :
1002 [ + + ]: 132 : 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 [ + + ]: 132 : 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 : 132 : pubrels = fetch_relation_list(wrconn, publications);
1016 : :
1017 [ + + + + : 466 : foreach_ptr(PublicationRelKind, pubrelinfo, pubrels)
+ + ]
1018 : : {
1019 : : Oid relid;
1020 : : char relkind;
1021 : 204 : RangeVar *rv = pubrelinfo->rv;
1022 : :
1023 : 204 : relid = RangeVarGetRelid(rv, AccessShareLock, false);
1024 : 204 : relkind = get_rel_relkind(relid);
1025 : :
1026 : : /* Check for supported relkind. */
1027 : 204 : CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
1028 : 204 : rv->schemaname, rv->relname);
1029 : 204 : has_tables |= (relkind != RELKIND_SEQUENCE);
1030 : 204 : 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 [ + + ]: 131 : if (opts.create_slot)
1044 : : {
1045 : 126 : 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 [ + + + + : 126 : if (opts.twophase && !opts.copy_data && has_tables)
+ - ]
1066 : 1 : twophase_enabled = true;
1067 : :
1068 : 126 : walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
1069 : : opts.failover, CRS_NOEXPORT_SNAPSHOT, NULL);
1070 : :
1071 [ + + ]: 126 : if (twophase_enabled)
1072 : 1 : UpdateTwoPhaseState(subid, LOGICALREP_TWOPHASE_STATE_ENABLED);
1073 : :
1074 [ + - ]: 126 : ereport(NOTICE,
1075 : : (errmsg("created replication slot \"%s\" on publisher",
1076 : : opts.slot_name)));
1077 : : }
1078 : : }
1079 : 1 : PG_FINALLY();
1080 : : {
1081 : 132 : walrcv_disconnect(wrconn);
1082 : : }
1083 [ + + ]: 132 : 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 : 218 : table_close(rel, RowExclusiveLock);
1091 : :
1092 : 218 : 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 [ + + + + ]: 218 : if (opts.enabled || opts.retaindeadtuples)
1105 : 125 : ApplyLauncherWakeupAtCommit();
1106 : :
1107 [ - + ]: 218 : InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
1108 : :
1109 : 218 : return myself;
1110 : : }
1111 : :
1112 : : static void
1113 : 45 : AlterSubscription_refresh(Subscription *sub, bool copy_data,
1114 : : List *validate_publications, char *conninfo)
1115 : : {
1116 : : char *err;
1117 : 45 : List *pubrels = NIL;
1118 : : Oid *pubrel_local_oids;
1119 : : List *subrel_states;
1120 : 45 : 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 : 45 : int tbl_count = 0;
1127 : 45 : int seq_count = 0;
1128 : 45 : 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 [ - + ]: 45 : if (!conninfo)
1143 [ # # ]: 0 : elog(ERROR, "no connection string provided for subscription");
1144 : :
1145 : : /* Load the library providing us libpq calls. */
1146 : 45 : load_file("libpqwalreceiver", false);
1147 : :
1148 : : /* Try to connect to the publisher. */
1149 [ + - + + ]: 45 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
1150 : 45 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
1151 : : sub->name, &err);
1152 [ - + ]: 44 : 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 [ + - ]: 44 : PG_TRY();
1159 : : {
1160 [ + + ]: 44 : if (validate_publications)
1161 : 9 : check_publications(wrconn, validate_publications);
1162 : :
1163 : : /* Get the relation list from publisher. */
1164 : 44 : pubrels = fetch_relation_list(wrconn, sub->publications);
1165 : :
1166 : : /* Get local relation list. */
1167 : 44 : subrel_states = GetSubscriptionRelations(sub->oid, true, true, false);
1168 : 44 : subrel_count = list_length(subrel_states);
1169 : :
1170 : : /* Allow a test to drop a subscribed relation before the origin check. */
1171 : 44 : 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 : 44 : subrel_local_oids = palloc_array(Oid, subrel_count);
1183 : 44 : subseq_local_oids = palloc_array(Oid, subrel_count);
1184 [ + + + + : 155 : foreach(lc, subrel_states)
+ + ]
1185 : : {
1186 : 111 : SubscriptionRelState *relstate = (SubscriptionRelState *) lfirst(lc);
1187 : :
1188 [ + + ]: 111 : if (get_rel_relkind(relstate->relid) == RELKIND_SEQUENCE)
1189 : 15 : subseq_local_oids[seq_count++] = relstate->relid;
1190 : : else
1191 : 96 : subrel_local_oids[tbl_count++] = relstate->relid;
1192 : : }
1193 : :
1194 : 44 : qsort(subrel_local_oids, tbl_count, sizeof(Oid), oid_cmp);
1195 : 44 : check_publications_origin_tables(wrconn, sub->publications, copy_data,
1196 : 44 : sub->retaindeadtuples, sub->origin,
1197 : : subrel_local_oids, tbl_count,
1198 : : sub->name);
1199 : :
1200 : 44 : qsort(subseq_local_oids, seq_count, sizeof(Oid), oid_cmp);
1201 : 44 : 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 : 44 : off = 0;
1215 : 44 : pubrel_local_oids = palloc_array(Oid, list_length(pubrels));
1216 : :
1217 [ + + + + : 205 : foreach_ptr(PublicationRelKind, pubrelinfo, pubrels)
+ + ]
1218 : : {
1219 : 117 : RangeVar *rv = pubrelinfo->rv;
1220 : : Oid relid;
1221 : : char relkind;
1222 : :
1223 : 117 : relid = RangeVarGetRelid(rv, AccessShareLock, false);
1224 : 117 : relkind = get_rel_relkind(relid);
1225 : :
1226 : : /* Check for supported relkind. */
1227 : 117 : CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
1228 : 117 : rv->schemaname, rv->relname);
1229 : :
1230 : 117 : pubrel_local_oids[off++] = relid;
1231 : :
1232 [ + + ]: 117 : if (!bsearch(&relid, subrel_local_oids,
1233 : 45 : tbl_count, sizeof(Oid), oid_cmp) &&
1234 [ + + ]: 45 : !bsearch(&relid, subseq_local_oids,
1235 : : seq_count, sizeof(Oid), oid_cmp))
1236 : : {
1237 [ + + ]: 32 : AddSubscriptionRelState(sub->oid, relid,
1238 : : copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
1239 : : InvalidXLogRecPtr, true);
1240 [ + + - + ]: 32 : 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 : 44 : qsort(pubrel_local_oids, list_length(pubrels), sizeof(Oid), oid_cmp);
1252 : :
1253 [ + + ]: 140 : for (off = 0; off < tbl_count; off++)
1254 : : {
1255 : 96 : Oid relid = subrel_local_oids[off];
1256 : :
1257 [ + + ]: 96 : if (!bsearch(&relid, pubrel_local_oids,
1258 : 96 : list_length(pubrels), sizeof(Oid), oid_cmp))
1259 : : {
1260 : : char state;
1261 : : XLogRecPtr statelsn;
1262 : 24 : 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 [ + + ]: 24 : if (!rel)
1279 : 12 : rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
1280 : :
1281 : : /* Last known rel state. */
1282 : 24 : state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
1283 : :
1284 : 24 : RemoveSubscriptionRel(sub->oid, relid);
1285 : :
1286 : 24 : remove_rel->relid = relid;
1287 : 24 : remove_rel->state = state;
1288 : :
1289 : 24 : sub_remove_rels = lappend(sub_remove_rels, remove_rel);
1290 : :
1291 : 24 : 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 [ + + ]: 24 : 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 [ + + ]: 24 : 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 [ + + ]: 59 : for (off = 0; off < seq_count; off++)
1329 : : {
1330 : 15 : Oid relid = subseq_local_oids[off];
1331 : :
1332 [ + + ]: 15 : if (!bsearch(&relid, pubrel_local_oids,
1333 : 15 : 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 [ + + ]: 2 : if (!rel)
1340 : 1 : rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
1341 : :
1342 : 2 : 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 [ - + ]: 2 : 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 [ + + + + : 112 : foreach_ptr(SubRemoveRels, sub_remove_rel, sub_remove_rels)
+ + ]
1364 : : {
1365 [ + + ]: 24 : 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 : 44 : walrcv_disconnect(wrconn);
1389 : : }
1390 [ - + ]: 44 : PG_END_TRY();
1391 : :
1392 [ + + ]: 44 : if (rel)
1393 : 13 : table_close(rel, NoLock);
1394 : 44 : }
1395 : :
1396 : : /*
1397 : : * Marks all sequences with INIT state.
1398 : : */
1399 : : static void
1400 : 6 : AlterSubscription_refresh_seq(Subscription *sub, char *conninfo)
1401 : : {
1402 : 6 : 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 [ - + ]: 6 : if (!conninfo)
1412 [ # # ]: 0 : elog(ERROR, "no connection string provided for subscription");
1413 : :
1414 : : /* Load the library providing us libpq calls. */
1415 : 6 : load_file("libpqwalreceiver", false);
1416 : :
1417 : : /* Try to connect to the publisher. */
1418 [ + + - + ]: 6 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
1419 : 6 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
1420 : : sub->name, &err);
1421 [ - + ]: 6 : 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 [ + - ]: 6 : 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 [ - + ]: 6 : 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 : 6 : check_publications_origin_sequences(wrconn, sub->publications, true,
1441 : : sub->origin, NULL, 0, sub->name);
1442 : : }
1443 : 0 : PG_FINALLY();
1444 : : {
1445 : 6 : walrcv_disconnect(wrconn);
1446 : : }
1447 [ - + ]: 6 : 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 : 6 : logicalrep_worker_stop(WORKERTYPE_SEQUENCESYNC, sub->oid, InvalidOid);
1480 : :
1481 : : /* Reset every local sequence of this subscription to INIT. */
1482 : 6 : subrel_states = GetSubscriptionRelations(sub->oid, false, true, false);
1483 [ + - + + : 37 : foreach_ptr(SubscriptionRelState, subrel, subrel_states)
+ + ]
1484 : : {
1485 : 25 : Oid relid = subrel->relid;
1486 : :
1487 : 25 : UpdateSubscriptionRelState(sub->oid, relid, SUBREL_STATE_INIT,
1488 : : InvalidXLogRecPtr, false);
1489 [ - + ]: 25 : 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 : 6 : }
1496 : :
1497 : : /*
1498 : : * Common checks for altering failover, two_phase, and retain_dead_tuples
1499 : : * options.
1500 : : */
1501 : : static void
1502 : 15 : 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 [ + + ]: 15 : 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 [ + + ]: 13 : 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 : 9 : }
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 : 456 : 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 : 456 : bool orig_conninfo_needed = false;
1668 : 456 : bool update_tuple = false;
1669 : 456 : bool update_failover = false;
1670 : 456 : bool update_two_phase = false;
1671 : 456 : bool check_pub_rdt = false;
1672 : : bool retain_dead_tuples;
1673 : : int max_retention;
1674 : : bool retention_active;
1675 : 456 : char *new_conninfo = NULL;
1676 : 456 : char *orig_conninfo = NULL;
1677 : : char *origin;
1678 : : Subscription *sub;
1679 : : Form_pg_subscription form;
1680 : : uint32 supported_opts;
1681 : 456 : SubOpts opts = {0};
1682 : :
1683 : 456 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1684 : :
1685 : : /* Fetch the existing tuple. */
1686 : 456 : tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
1687 : : CStringGetDatum(stmt->subname));
1688 : :
1689 [ + + ]: 456 : if (!HeapTupleIsValid(tup))
1690 [ + - ]: 4 : ereport(ERROR,
1691 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
1692 : : errmsg("subscription \"%s\" does not exist",
1693 : : stmt->subname)));
1694 : :
1695 : 452 : form = (Form_pg_subscription) GETSTRUCT(tup);
1696 : 452 : subid = form->oid;
1697 : :
1698 : : /* must be owner */
1699 [ - + ]: 452 : 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 [ + + + + : 452 : switch (stmt->kind)
+ + + ]
1705 : : {
1706 : 211 : case ALTER_SUBSCRIPTION_OPTIONS:
1707 : 211 : 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 : 211 : break;
1719 : :
1720 : 91 : case ALTER_SUBSCRIPTION_ENABLED:
1721 : 91 : supported_opts = SUBOPT_ENABLED;
1722 : 91 : 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 : 47 : case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
1734 : 47 : supported_opts = SUBOPT_COPY_DATA;
1735 : 47 : break;
1736 : :
1737 : 15 : case ALTER_SUBSCRIPTION_SKIP:
1738 : 15 : supported_opts = SUBOPT_LSN;
1739 : 15 : break;
1740 : :
1741 : 30 : default:
1742 : 30 : supported_opts = 0;
1743 : 30 : break;
1744 : : }
1745 : :
1746 [ + + ]: 452 : if (supported_opts > 0)
1747 : 422 : parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
1748 : :
1749 : 428 : 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 [ + + + + ]: 428 : switch (stmt->kind)
1759 : : {
1760 : 53 : case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
1761 : : case ALTER_SUBSCRIPTION_REFRESH_SEQUENCES:
1762 : 53 : orig_conninfo_needed = true;
1763 : 53 : 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 : 191 : case ALTER_SUBSCRIPTION_OPTIONS:
1773 : : {
1774 [ + + ]: 191 : if (sub->slotname)
1775 : : {
1776 [ + + ]: 187 : if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1777 : 9 : orig_conninfo_needed = true;
1778 [ + + ]: 187 : if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT) &&
1779 [ + + ]: 4 : !opts.twophase)
1780 : 1 : orig_conninfo_needed = true;
1781 : : }
1782 : :
1783 [ + + ]: 191 : if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) &&
1784 [ + - ]: 2 : opts.retaindeadtuples)
1785 : 2 : orig_conninfo_needed = true;
1786 : :
1787 [ + + ]: 191 : 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 : 191 : break;
1799 : :
1800 : 126 : default:
1801 : 126 : break;
1802 : : }
1803 : :
1804 [ + + ]: 428 : if (orig_conninfo_needed)
1805 : 84 : orig_conninfo = SubscriptionConninfo(sub);
1806 : :
1807 : 424 : retain_dead_tuples = sub->retaindeadtuples;
1808 : 424 : origin = sub->origin;
1809 : 424 : max_retention = sub->maxretention;
1810 : 424 : retention_active = sub->retentionactive;
1811 : :
1812 : : /*
1813 : : * Don't allow non-superuser modification of a subscription with
1814 : : * password_required=false.
1815 : : */
1816 [ + + - + ]: 424 : 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 : 424 : LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1824 : :
1825 : : /* Form a new tuple. */
1826 : 424 : memset(values, 0, sizeof(values));
1827 : 424 : memset(nulls, false, sizeof(nulls));
1828 : 424 : memset(replaces, false, sizeof(replaces));
1829 : :
1830 : 424 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
1831 : :
1832 [ + + + + : 424 : switch (stmt->kind)
+ + + + +
- ]
1833 : : {
1834 : 191 : case ALTER_SUBSCRIPTION_OPTIONS:
1835 : : {
1836 [ + + ]: 191 : 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 [ + + ]: 191 : 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 [ + + ]: 191 : 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 [ + + ]: 191 : 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 [ + + ]: 191 : 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 [ + + ]: 191 : if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1889 : : {
1890 : : /* Non-superuser may not disable password_required. */
1891 [ + + - + ]: 9 : 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 : 9 : = BoolGetDatum(opts.passwordrequired);
1899 : : replaces[Anum_pg_subscription_subpasswordrequired - 1]
1900 : 9 : = true;
1901 : : }
1902 : :
1903 [ + + ]: 191 : 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 [ + + ]: 191 : 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 : 4 : update_two_phase = !opts.twophase;
1920 : :
1921 : 4 : 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 [ + + ]: 4 : 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 [ - + ]: 4 : 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 [ + + ]: 4 : 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 : : /*
1967 : : * Change system catalog accordingly, but do not reset the
1968 : : * state to PENDING if two_phase is already enabled.
1969 : : */
1970 [ + + ]: 4 : if (!(opts.twophase &&
1971 [ + + ]: 3 : sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED))
1972 : : {
1973 : 3 : values[Anum_pg_subscription_subtwophasestate - 1] =
1974 [ + + ]: 3 : CharGetDatum(opts.twophase ?
1975 : : LOGICALREP_TWOPHASE_STATE_PENDING :
1976 : : LOGICALREP_TWOPHASE_STATE_DISABLED);
1977 : 3 : replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
1978 : : }
1979 : : }
1980 : :
1981 [ + + ]: 191 : if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1982 : : {
1983 : : /*
1984 : : * Similar to the two_phase case above, we need to update
1985 : : * the failover option for both the slot and the
1986 : : * subscription.
1987 : : */
1988 : 9 : update_failover = true;
1989 : :
1990 : 9 : CheckAlterSubOption(sub, "failover", update_failover,
1991 : : isTopLevel);
1992 : :
1993 : 4 : values[Anum_pg_subscription_subfailover - 1] =
1994 : 4 : BoolGetDatum(opts.failover);
1995 : 4 : replaces[Anum_pg_subscription_subfailover - 1] = true;
1996 : : }
1997 : :
1998 [ + + ]: 186 : if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
1999 : : {
2000 : 2 : values[Anum_pg_subscription_subretaindeadtuples - 1] =
2001 : 2 : BoolGetDatum(opts.retaindeadtuples);
2002 : 2 : replaces[Anum_pg_subscription_subretaindeadtuples - 1] = true;
2003 : :
2004 : : /*
2005 : : * Update the retention status only if there's a change in
2006 : : * the retain_dead_tuples option value.
2007 : : *
2008 : : * Automatically marking retention as active when
2009 : : * retain_dead_tuples is enabled may not always be ideal,
2010 : : * especially if retention was previously stopped and the
2011 : : * user toggles retain_dead_tuples without adjusting the
2012 : : * publisher workload. However, this behavior provides a
2013 : : * convenient way for users to manually refresh the
2014 : : * retention status. Since retention will be stopped again
2015 : : * unless the publisher workload is reduced, this approach
2016 : : * is acceptable for now.
2017 : : */
2018 [ + - ]: 2 : if (opts.retaindeadtuples != sub->retaindeadtuples)
2019 : : {
2020 : 2 : values[Anum_pg_subscription_subretentionactive - 1] =
2021 : 2 : BoolGetDatum(opts.retaindeadtuples);
2022 : 2 : replaces[Anum_pg_subscription_subretentionactive - 1] = true;
2023 : :
2024 : 2 : retention_active = opts.retaindeadtuples;
2025 : : }
2026 : :
2027 : 2 : CheckAlterSubOption(sub, "retain_dead_tuples", false, isTopLevel);
2028 : :
2029 : : /*
2030 : : * Workers may continue running even after the
2031 : : * subscription has been disabled.
2032 : : *
2033 : : * To prevent race conditions (as described in
2034 : : * CheckAlterSubOption()), ensure that all worker
2035 : : * processes have already exited before proceeding.
2036 : : */
2037 [ - + ]: 1 : if (logicalrep_workers_find(subid, true, true))
2038 [ # # ]: 0 : ereport(ERROR,
2039 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2040 : : errmsg("cannot alter option \"%s\" when logical replication worker is still running",
2041 : : "retain_dead_tuples"),
2042 : : errhint("Try again after some time.")));
2043 : :
2044 : : /*
2045 : : * Notify the launcher to manage the replication slot for
2046 : : * conflict detection. This ensures that replication slot
2047 : : * is efficiently handled (created, updated, or dropped)
2048 : : * in response to any configuration changes.
2049 : : */
2050 : 1 : ApplyLauncherWakeupAtCommit();
2051 : :
2052 : 1 : check_pub_rdt = opts.retaindeadtuples;
2053 : 1 : retain_dead_tuples = opts.retaindeadtuples;
2054 : : }
2055 : :
2056 [ + + ]: 185 : if (IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
2057 : : {
2058 : 6 : values[Anum_pg_subscription_submaxretention - 1] =
2059 : 6 : Int32GetDatum(opts.maxretention);
2060 : 6 : replaces[Anum_pg_subscription_submaxretention - 1] = true;
2061 : :
2062 : 6 : max_retention = opts.maxretention;
2063 : : }
2064 : :
2065 : : /*
2066 : : * Ensure that system configuration parameters are set
2067 : : * appropriately to support retain_dead_tuples and
2068 : : * max_retention_duration.
2069 : : */
2070 [ + + ]: 185 : if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) ||
2071 [ + + ]: 184 : IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
2072 : 7 : CheckSubDeadTupleRetention(true, !sub->enabled, NOTICE,
2073 : : retain_dead_tuples,
2074 : : retention_active,
2075 : 7 : (max_retention > 0));
2076 : :
2077 [ + + ]: 185 : if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
2078 : : {
2079 : 6 : values[Anum_pg_subscription_suborigin - 1] =
2080 : 6 : CStringGetTextDatum(opts.origin);
2081 : 6 : replaces[Anum_pg_subscription_suborigin - 1] = true;
2082 : :
2083 : : /*
2084 : : * Check if changes from different origins may be received
2085 : : * from the publisher when the origin is changed to ANY
2086 : : * and retain_dead_tuples is enabled. Use |= so that we
2087 : : * don't clear the flag already set when
2088 : : * retain_dead_tuples was changed in the same command.
2089 : : */
2090 [ + + ]: 8 : check_pub_rdt |= retain_dead_tuples &&
2091 [ + + ]: 2 : pg_strcasecmp(opts.origin, LOGICALREP_ORIGIN_ANY) == 0;
2092 : :
2093 : 6 : origin = opts.origin;
2094 : : }
2095 : :
2096 [ + + ]: 185 : if (IsSet(opts.specified_opts, SUBOPT_WAL_RECEIVER_TIMEOUT))
2097 : : {
2098 : 8 : values[Anum_pg_subscription_subwalrcvtimeout - 1] =
2099 : 8 : CStringGetTextDatum(opts.wal_receiver_timeout);
2100 : 8 : replaces[Anum_pg_subscription_subwalrcvtimeout - 1] = true;
2101 : : }
2102 : :
2103 [ + + ]: 185 : if (IsSet(opts.specified_opts, SUBOPT_CONFLICT_LOG_DEST))
2104 : : {
2105 : : ConflictLogDest old_dest =
2106 : 16 : GetConflictLogDest(sub->conflictlogdest);
2107 : :
2108 [ + + ]: 16 : if (opts.conflictlogdest != old_dest)
2109 : : {
2110 : : bool update_relid;
2111 : 12 : Oid relid = InvalidOid;
2112 : :
2113 : 12 : values[Anum_pg_subscription_subconflictlogdest - 1] =
2114 : 12 : CStringGetTextDatum(ConflictLogDestNames[opts.conflictlogdest]);
2115 : 12 : replaces[Anum_pg_subscription_subconflictlogdest - 1] = true;
2116 : :
2117 : 12 : update_relid = alter_sub_conflict_log_dest(sub,
2118 : : old_dest,
2119 : : opts.conflictlogdest,
2120 : : &relid);
2121 [ + + ]: 12 : if (update_relid)
2122 : : {
2123 : 8 : values[Anum_pg_subscription_subconflictlogrelid - 1] =
2124 : 8 : ObjectIdGetDatum(relid);
2125 : 8 : replaces[Anum_pg_subscription_subconflictlogrelid - 1] =
2126 : : true;
2127 : : }
2128 : : }
2129 : : }
2130 : :
2131 : 185 : update_tuple = true;
2132 : 185 : break;
2133 : : }
2134 : :
2135 : 91 : case ALTER_SUBSCRIPTION_ENABLED:
2136 : : {
2137 : : Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
2138 : :
2139 [ + + + - ]: 91 : if (!sub->slotname && opts.enabled)
2140 [ + - ]: 4 : ereport(ERROR,
2141 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2142 : : errmsg("cannot enable subscription that does not have a slot name")));
2143 : :
2144 : : /*
2145 : : * Check track_commit_timestamp only when enabling the
2146 : : * subscription in case it was disabled after creation. See
2147 : : * comments atop CheckSubDeadTupleRetention() for details.
2148 : : */
2149 : 87 : CheckSubDeadTupleRetention(opts.enabled, !opts.enabled,
2150 : 87 : WARNING, sub->retaindeadtuples,
2151 : 87 : sub->retentionactive, false);
2152 : :
2153 : 87 : values[Anum_pg_subscription_subenabled - 1] =
2154 : 87 : BoolGetDatum(opts.enabled);
2155 : 87 : replaces[Anum_pg_subscription_subenabled - 1] = true;
2156 : :
2157 [ + + ]: 87 : if (opts.enabled)
2158 : 36 : ApplyLauncherWakeupAtCommit();
2159 : :
2160 : 87 : update_tuple = true;
2161 : 87 : break;
2162 : : }
2163 : :
2164 : 1 : case ALTER_SUBSCRIPTION_SERVER:
2165 : : {
2166 : : ForeignServer *new_server;
2167 : : ObjectAddress referenced;
2168 : : AclResult aclresult;
2169 : :
2170 : : /*
2171 : : * Remove what was there before, either another foreign server
2172 : : * or a connection string.
2173 : : */
2174 [ - + ]: 1 : if (form->subserver)
2175 : : {
2176 : 0 : deleteDependencyRecordsForSpecific(SubscriptionRelationId, form->oid,
2177 : : DEPENDENCY_NORMAL,
2178 : : ForeignServerRelationId, form->subserver);
2179 : : }
2180 : : else
2181 : : {
2182 : 1 : nulls[Anum_pg_subscription_subconninfo - 1] = true;
2183 : 1 : replaces[Anum_pg_subscription_subconninfo - 1] = true;
2184 : : }
2185 : :
2186 : : /*
2187 : : * Check that the subscription owner has USAGE privileges on
2188 : : * the server.
2189 : : */
2190 : 1 : new_server = GetForeignServerByName(stmt->servername, false);
2191 : 1 : aclresult = object_aclcheck(ForeignServerRelationId,
2192 : : new_server->serverid,
2193 : : form->subowner, ACL_USAGE);
2194 [ - + ]: 1 : if (aclresult != ACLCHECK_OK)
2195 [ # # ]: 0 : ereport(ERROR,
2196 : : errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2197 : : errmsg("subscription owner \"%s\" does not have permission on foreign server \"%s\"",
2198 : : GetUserNameFromId(form->subowner, false),
2199 : : new_server->servername));
2200 : :
2201 : : /* check user mapping */
2202 : 1 : GetUserMappingExtended(form->subowner, new_server->serverid, WARNING);
2203 : :
2204 : 1 : new_conninfo = ForeignServerConnectionString(form->subowner,
2205 : : new_server);
2206 : :
2207 : : /* Load the library providing us libpq calls. */
2208 : 1 : load_file("libpqwalreceiver", false);
2209 : : /* Check the connection info string. */
2210 [ - + - - ]: 1 : walrcv_check_conninfo(new_conninfo,
2211 : : sub->passwordrequired && !sub->ownersuperuser);
2212 : :
2213 : 1 : values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(new_server->serverid);
2214 : 1 : replaces[Anum_pg_subscription_subserver - 1] = true;
2215 : :
2216 : 1 : ObjectAddressSet(referenced, ForeignServerRelationId, new_server->serverid);
2217 : 1 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
2218 : :
2219 : 1 : update_tuple = true;
2220 : : }
2221 : :
2222 : : /*
2223 : : * Since the remote server configuration might have changed,
2224 : : * perform a check to ensure it permits enabling
2225 : : * retain_dead_tuples.
2226 : : */
2227 : 1 : check_pub_rdt = sub->retaindeadtuples;
2228 : 1 : break;
2229 : :
2230 : 23 : case ALTER_SUBSCRIPTION_CONNECTION:
2231 : : /* remove reference to foreign server and dependencies, if present */
2232 [ + + ]: 23 : if (form->subserver)
2233 : : {
2234 : 9 : deleteDependencyRecordsForSpecific(SubscriptionRelationId, form->oid,
2235 : : DEPENDENCY_NORMAL,
2236 : : ForeignServerRelationId, form->subserver);
2237 : :
2238 : 9 : values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(InvalidOid);
2239 : 9 : replaces[Anum_pg_subscription_subserver - 1] = true;
2240 : : }
2241 : :
2242 : 23 : new_conninfo = stmt->conninfo;
2243 : :
2244 : : /* Load the library providing us libpq calls. */
2245 : 23 : load_file("libpqwalreceiver", false);
2246 : : /* Check the connection info string. */
2247 [ + + + + ]: 23 : walrcv_check_conninfo(new_conninfo,
2248 : : sub->passwordrequired && !sub->ownersuperuser);
2249 : :
2250 : 19 : values[Anum_pg_subscription_subconninfo - 1] =
2251 : 19 : CStringGetTextDatum(stmt->conninfo);
2252 : 19 : replaces[Anum_pg_subscription_subconninfo - 1] = true;
2253 : 19 : update_tuple = true;
2254 : :
2255 : : /*
2256 : : * Since the remote server configuration might have changed,
2257 : : * perform a check to ensure it permits enabling
2258 : : * retain_dead_tuples.
2259 : : */
2260 : 19 : check_pub_rdt = sub->retaindeadtuples;
2261 : 19 : break;
2262 : :
2263 : 23 : case ALTER_SUBSCRIPTION_SET_PUBLICATION:
2264 : : {
2265 : 23 : values[Anum_pg_subscription_subpublications - 1] =
2266 : 23 : publicationListToArray(stmt->publication);
2267 : 23 : replaces[Anum_pg_subscription_subpublications - 1] = true;
2268 : :
2269 : 23 : update_tuple = true;
2270 : :
2271 : : /* Refresh if user asked us to. */
2272 [ + + ]: 23 : if (opts.refresh)
2273 : : {
2274 [ - + ]: 15 : if (!sub->enabled)
2275 [ # # ]: 0 : ereport(ERROR,
2276 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2277 : : errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
2278 : : errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
2279 : :
2280 : : /*
2281 : : * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
2282 : : * why this is not allowed.
2283 : : */
2284 [ - + - - ]: 15 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2285 [ # # ]: 0 : ereport(ERROR,
2286 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2287 : : errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
2288 : : errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
2289 : :
2290 : 15 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2291 : :
2292 : : /* Make sure refresh sees the new list of publications. */
2293 : 7 : sub->publications = stmt->publication;
2294 : :
2295 : 7 : AlterSubscription_refresh(sub, opts.copy_data,
2296 : : stmt->publication,
2297 : : orig_conninfo);
2298 : : }
2299 : :
2300 : 15 : break;
2301 : : }
2302 : :
2303 : 35 : case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
2304 : : case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
2305 : : {
2306 : : List *publist;
2307 : 35 : bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
2308 : :
2309 : 35 : publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
2310 : 11 : values[Anum_pg_subscription_subpublications - 1] =
2311 : 11 : publicationListToArray(publist);
2312 : 11 : replaces[Anum_pg_subscription_subpublications - 1] = true;
2313 : :
2314 : 11 : update_tuple = true;
2315 : :
2316 : : /* Refresh if user asked us to. */
2317 [ + + ]: 11 : if (opts.refresh)
2318 : : {
2319 : : /* We only need to validate user specified publications. */
2320 [ + + ]: 3 : List *validate_publications = (isadd) ? stmt->publication : NULL;
2321 : :
2322 [ - + ]: 3 : if (!sub->enabled)
2323 [ # # # # ]: 0 : ereport(ERROR,
2324 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2325 : : errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
2326 : : /* translator: %s is an SQL ALTER command */
2327 : : errhint("Use %s instead.",
2328 : : isadd ?
2329 : : "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
2330 : : "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
2331 : :
2332 : : /*
2333 : : * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
2334 : : * why this is not allowed.
2335 : : */
2336 [ - + - - ]: 3 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2337 [ # # # # ]: 0 : ereport(ERROR,
2338 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2339 : : errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
2340 : : /* translator: %s is an SQL ALTER command */
2341 : : errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
2342 : : isadd ?
2343 : : "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
2344 : : "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
2345 : :
2346 : 3 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
2347 : :
2348 : : /* Refresh the new list of publications. */
2349 : 3 : sub->publications = publist;
2350 : :
2351 : 3 : AlterSubscription_refresh(sub, opts.copy_data,
2352 : : validate_publications,
2353 : : orig_conninfo);
2354 : : }
2355 : :
2356 : 11 : break;
2357 : : }
2358 : :
2359 : 43 : case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
2360 : : {
2361 [ + + ]: 43 : if (!sub->enabled)
2362 [ + - ]: 4 : ereport(ERROR,
2363 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2364 : : errmsg("%s is not allowed for disabled subscriptions",
2365 : : "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
2366 : :
2367 : : /*
2368 : : * The subscription option "two_phase" requires that
2369 : : * replication has passed the initial table synchronization
2370 : : * phase before the two_phase becomes properly enabled.
2371 : : *
2372 : : * But, having reached this two-phase commit "enabled" state
2373 : : * we must not allow any subsequent table initialization to
2374 : : * occur. So the ALTER SUBSCRIPTION ... REFRESH PUBLICATION is
2375 : : * disallowed when the user had requested two_phase = on mode.
2376 : : *
2377 : : * The exception to this restriction is when copy_data =
2378 : : * false, because when copy_data is false the tablesync will
2379 : : * start already in READY state and will exit directly without
2380 : : * doing anything.
2381 : : *
2382 : : * For more details see comments atop worker.c.
2383 : : */
2384 [ - + - - ]: 39 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
2385 [ # # ]: 0 : ereport(ERROR,
2386 : : (errcode(ERRCODE_SYNTAX_ERROR),
2387 : : errmsg("ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data is not allowed when two_phase is enabled"),
2388 : : errhint("Use ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
2389 : :
2390 : 39 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH PUBLICATION");
2391 : :
2392 : 35 : AlterSubscription_refresh(sub, opts.copy_data, NULL,
2393 : : orig_conninfo);
2394 : :
2395 : 34 : break;
2396 : : }
2397 : :
2398 : 6 : case ALTER_SUBSCRIPTION_REFRESH_SEQUENCES:
2399 : : {
2400 [ - + ]: 6 : if (!sub->enabled)
2401 [ # # ]: 0 : ereport(ERROR,
2402 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2403 : : errmsg("%s is not allowed for disabled subscriptions",
2404 : : "ALTER SUBSCRIPTION ... REFRESH SEQUENCES"));
2405 : :
2406 : 6 : AlterSubscription_refresh_seq(sub, orig_conninfo);
2407 : :
2408 : 6 : break;
2409 : : }
2410 : :
2411 : 11 : case ALTER_SUBSCRIPTION_SKIP:
2412 : : {
2413 : : /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
2414 : : Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
2415 : :
2416 : : /*
2417 : : * If the user sets subskiplsn, we do a sanity check to make
2418 : : * sure that the specified LSN is a probable value.
2419 : : */
2420 [ + + ]: 11 : if (XLogRecPtrIsValid(opts.lsn))
2421 : : {
2422 : : ReplOriginId originid;
2423 : : char originname[NAMEDATALEN];
2424 : : XLogRecPtr remote_lsn;
2425 : :
2426 : 7 : ReplicationOriginNameForLogicalRep(subid, InvalidOid,
2427 : : originname, sizeof(originname));
2428 : 7 : originid = replorigin_by_name(originname, false);
2429 : 7 : remote_lsn = replorigin_get_progress(originid, false);
2430 : :
2431 : : /* Check the given LSN is at least a future LSN */
2432 [ + + - + ]: 7 : if (XLogRecPtrIsValid(remote_lsn) && opts.lsn < remote_lsn)
2433 [ # # ]: 0 : ereport(ERROR,
2434 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2435 : : errmsg("skip WAL location (LSN %X/%08X) must be greater than origin LSN %X/%08X",
2436 : : LSN_FORMAT_ARGS(opts.lsn),
2437 : : LSN_FORMAT_ARGS(remote_lsn))));
2438 : : }
2439 : :
2440 : 11 : values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
2441 : 11 : replaces[Anum_pg_subscription_subskiplsn - 1] = true;
2442 : :
2443 : 11 : update_tuple = true;
2444 : 11 : break;
2445 : : }
2446 : :
2447 : 0 : default:
2448 [ # # ]: 0 : elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
2449 : : stmt->kind);
2450 : : }
2451 : :
2452 : : /* Update the catalog if needed. */
2453 [ + + ]: 369 : if (update_tuple)
2454 : : {
2455 : 329 : tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
2456 : : replaces);
2457 : :
2458 : 329 : CatalogTupleUpdate(rel, &tup->t_self, tup);
2459 : :
2460 : 329 : heap_freetuple(tup);
2461 : : }
2462 : :
2463 : : /*
2464 : : * Try to acquire the connection necessary either for modifying the slot
2465 : : * or for checking if the remote server permits enabling
2466 : : * retain_dead_tuples.
2467 : : *
2468 : : * This has to be at the end because otherwise if there is an error while
2469 : : * doing the database operations we won't be able to rollback altered
2470 : : * slot.
2471 : : */
2472 [ + + + + : 369 : if (update_failover || update_two_phase || check_pub_rdt)
+ + ]
2473 : : {
2474 : : bool must_use_password;
2475 : : char *err;
2476 : : WalReceiverConn *wrconn;
2477 : :
2478 : : Assert(new_conninfo || orig_conninfo);
2479 : :
2480 : : /* Load the library providing us libpq calls. */
2481 : 7 : load_file("libpqwalreceiver", false);
2482 : :
2483 : : /*
2484 : : * Try to connect to the publisher, using the new connection string if
2485 : : * available.
2486 : : */
2487 [ + - - + ]: 7 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
2488 [ - + ]: 7 : wrconn = walrcv_connect(new_conninfo ? new_conninfo : orig_conninfo,
2489 : : true, true, must_use_password, sub->name,
2490 : : &err);
2491 [ - + ]: 7 : if (!wrconn)
2492 [ # # ]: 0 : ereport(ERROR,
2493 : : (errcode(ERRCODE_CONNECTION_FAILURE),
2494 : : errmsg("subscription \"%s\" could not connect to the publisher: %s",
2495 : : sub->name, err)));
2496 : :
2497 [ + - ]: 7 : PG_TRY();
2498 : : {
2499 [ + + ]: 7 : if (retain_dead_tuples)
2500 : 3 : CheckPubDeadTupleRetention(wrconn);
2501 : :
2502 : 7 : check_publications_origin_tables(wrconn, sub->publications, false,
2503 : : retain_dead_tuples, origin, NULL, 0,
2504 : : sub->name);
2505 : :
2506 [ + + + + ]: 7 : if (update_failover || update_two_phase)
2507 [ + + + + ]: 5 : walrcv_alter_slot(wrconn, sub->slotname,
2508 : : update_failover ? &opts.failover : NULL,
2509 : : update_two_phase ? &opts.twophase : NULL);
2510 : : }
2511 : 0 : PG_FINALLY();
2512 : : {
2513 : 7 : walrcv_disconnect(wrconn);
2514 : : }
2515 [ - + ]: 7 : PG_END_TRY();
2516 : : }
2517 : :
2518 : 369 : table_close(rel, RowExclusiveLock);
2519 : :
2520 [ - + ]: 369 : InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
2521 : :
2522 : : /* Wake up related replication workers to handle this change quickly. */
2523 : 369 : LogicalRepWorkersWakeupAtCommit(subid);
2524 : :
2525 : 369 : return myself;
2526 : : }
2527 : :
2528 : : /*
2529 : : * Construct conninfo from a subscription's server. Like libpqrcv_connect(),
2530 : : * if an error occurs, set *err to the error message and return NULL.
2531 : : *
2532 : : * However, failures in ForeignServerConnectionString() may ereport(ERROR),
2533 : : * and (also like libpqrcv_connect) it's not worth adding the machinery to
2534 : : * pass all of those back to the caller just to cover this one case.
2535 : : */
2536 : : static char *
2537 : 8 : construct_subserver_conninfo(Oid subserver, Oid subowner, char **err)
2538 : : {
2539 : : AclResult aclresult;
2540 : : ForeignServer *server;
2541 : :
2542 : 8 : *err = NULL;
2543 : :
2544 : 8 : server = GetForeignServer(subserver);
2545 : :
2546 : 8 : aclresult = object_aclcheck(ForeignServerRelationId, subserver,
2547 : : subowner, ACL_USAGE);
2548 [ + + ]: 8 : if (aclresult != ACLCHECK_OK)
2549 : : {
2550 : : /*
2551 : : * Unable to generate connection string because permissions on the
2552 : : * foreign server have been removed. Follow the same logic as an
2553 : : * unusable subconninfo (which will result in an ERROR later unless
2554 : : * slot_name = NONE).
2555 : : */
2556 : 4 : *err = psprintf(_("subscription owner \"%s\" does not have permission on foreign server \"%s\""),
2557 : : GetUserNameFromId(subowner, false),
2558 : : server->servername);
2559 : 4 : return NULL;
2560 : : }
2561 : :
2562 : 4 : return ForeignServerConnectionString(subowner, server);
2563 : : }
2564 : :
2565 : : /*
2566 : : * Drop subscription's conflict log table
2567 : : *
2568 : : * The conflict log table is registered as an internal dependency of the
2569 : : * subscription. This function removes the dependency by performing a
2570 : : * cascading deletion on the subscription object, which in turn drops the
2571 : : * associated conflict log table.
2572 : : *
2573 : : * This is used to clean up conflict log tables that are no longer required,
2574 : : * preventing accumulation of stale or orphaned relations.
2575 : : *
2576 : : * NOTE:
2577 : : * Only conflict log tables are currently managed via this internal dependency
2578 : : * mechanism.
2579 : : */
2580 : : static void
2581 : 177 : drop_sub_conflict_log_table(Oid subid, char *subname, Oid subconflictlogrelid)
2582 : : {
2583 : : /* Drop any dependent conflict log table */
2584 [ + + ]: 177 : if (OidIsValid(subconflictlogrelid))
2585 : : {
2586 : : ObjectAddress object;
2587 : : char *conflictrelname;
2588 : :
2589 : 13 : conflictrelname = get_rel_name(subconflictlogrelid);
2590 [ - + ]: 13 : if (conflictrelname == NULL)
2591 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u",
2592 : : subconflictlogrelid);
2593 : :
2594 : : /*
2595 : : * By using PERFORM_DELETION_SKIP_ORIGINAL, we ensure that only the
2596 : : * conflict log table is deleted while the subscription remains.
2597 : : */
2598 : 13 : ObjectAddressSet(object, SubscriptionRelationId, subid);
2599 : 13 : performDeletion(&object, DROP_CASCADE,
2600 : : PERFORM_DELETION_INTERNAL |
2601 : : PERFORM_DELETION_SKIP_ORIGINAL);
2602 : :
2603 [ + + ]: 13 : ereport(NOTICE,
2604 : : errmsg("dropped conflict log table \"%s\" for subscription \"%s\"",
2605 : : get_qualified_objname(PG_CONFLICT_NAMESPACE, conflictrelname),
2606 : : subname));
2607 : : }
2608 : 177 : }
2609 : :
2610 : : /*
2611 : : * Drop a subscription
2612 : : */
2613 : : void
2614 : 185 : DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
2615 : : {
2616 : : Relation rel;
2617 : : ObjectAddress myself;
2618 : : HeapTuple tup;
2619 : : Oid subid;
2620 : : Oid subowner;
2621 : : Oid subserver;
2622 : : Oid subconflictlogrelid;
2623 : 185 : char *subconninfo = NULL;
2624 : : Datum datum;
2625 : : bool isnull;
2626 : : char *subname;
2627 : 185 : char *conninfo = NULL;
2628 : : char *slotname;
2629 : : List *subworkers;
2630 : : ListCell *lc;
2631 : : char originname[NAMEDATALEN];
2632 : 185 : char *err = NULL;
2633 : 185 : WalReceiverConn *wrconn = NULL;
2634 : : Form_pg_subscription form;
2635 : : List *rstates;
2636 : : bool must_use_password;
2637 : :
2638 : : /*
2639 : : * The launcher may concurrently start a new worker for this subscription.
2640 : : * During initialization, the worker checks for subscription validity and
2641 : : * exits if the subscription has already been dropped. See
2642 : : * InitializeLogRepWorker.
2643 : : */
2644 : 185 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
2645 : :
2646 : 185 : tup = SearchSysCache2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
2647 : 185 : CStringGetDatum(stmt->subname));
2648 : :
2649 [ + + ]: 185 : if (!HeapTupleIsValid(tup))
2650 : : {
2651 : 8 : table_close(rel, NoLock);
2652 : :
2653 [ + + ]: 8 : if (!stmt->missing_ok)
2654 [ + - ]: 4 : ereport(ERROR,
2655 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
2656 : : errmsg("subscription \"%s\" does not exist",
2657 : : stmt->subname)));
2658 : : else
2659 [ + - ]: 4 : ereport(NOTICE,
2660 : : (errmsg("subscription \"%s\" does not exist, skipping",
2661 : : stmt->subname)));
2662 : :
2663 : 86 : return;
2664 : : }
2665 : :
2666 : 177 : datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
2667 : : Anum_pg_subscription_subconninfo, &isnull);
2668 [ + + ]: 177 : if (!isnull)
2669 : 160 : subconninfo = TextDatumGetCString(datum);
2670 : :
2671 : 177 : form = (Form_pg_subscription) GETSTRUCT(tup);
2672 : 177 : subid = form->oid;
2673 : 177 : subowner = form->subowner;
2674 : 177 : subserver = form->subserver;
2675 : 177 : subconflictlogrelid = form->subconflictlogrelid;
2676 [ + + + + ]: 177 : must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
2677 : :
2678 : : /* must be owner */
2679 [ - + ]: 177 : if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
2680 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
2681 : 0 : stmt->subname);
2682 : :
2683 : : /* DROP hook for the subscription being removed */
2684 [ - + ]: 177 : InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
2685 : :
2686 : : /*
2687 : : * Lock the subscription so nobody else can do anything with it (including
2688 : : * the replication workers).
2689 : : */
2690 : 177 : LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
2691 : :
2692 : : /* Get subname */
2693 : 177 : datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
2694 : : Anum_pg_subscription_subname);
2695 : 177 : subname = pstrdup(NameStr(*DatumGetName(datum)));
2696 : :
2697 : : /* Get slotname */
2698 : 177 : datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
2699 : : Anum_pg_subscription_subslotname, &isnull);
2700 [ + + ]: 177 : if (!isnull)
2701 : 95 : slotname = pstrdup(NameStr(*DatumGetName(datum)));
2702 : : else
2703 : 82 : slotname = NULL;
2704 : :
2705 : : /*
2706 : : * Since dropping a replication slot is not transactional, the replication
2707 : : * slot stays dropped even if the transaction rolls back. So we cannot
2708 : : * run DROP SUBSCRIPTION inside a transaction block if dropping the
2709 : : * replication slot. Also, in this case, we report a message for dropping
2710 : : * the subscription to the cumulative stats system.
2711 : : *
2712 : : * XXX The command name should really be something like "DROP SUBSCRIPTION
2713 : : * of a subscription that is associated with a replication slot", but we
2714 : : * don't have the proper facilities for that.
2715 : : */
2716 [ + + ]: 177 : if (slotname)
2717 : 95 : PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
2718 : :
2719 : 173 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
2720 : 173 : EventTriggerSQLDropAddObject(&myself, true, true);
2721 : :
2722 : : /* Remove the tuple from catalog. */
2723 : 173 : CatalogTupleDelete(rel, &tup->t_self);
2724 : :
2725 : 173 : ReleaseSysCache(tup);
2726 : :
2727 : : /*
2728 : : * Stop all the subscription workers immediately.
2729 : : *
2730 : : * This is necessary if we are dropping the replication slot, so that the
2731 : : * slot becomes accessible.
2732 : : *
2733 : : * It is also necessary if the subscription is disabled and was disabled
2734 : : * in the same transaction. Then the workers haven't seen the disabling
2735 : : * yet and will still be running, leading to hangs later when we want to
2736 : : * drop the replication origin. If the subscription was disabled before
2737 : : * this transaction, then there shouldn't be any workers left, so this
2738 : : * won't make a difference.
2739 : : *
2740 : : * New workers won't be started because we hold an exclusive lock on the
2741 : : * subscription till the end of the transaction.
2742 : : */
2743 : 173 : subworkers = logicalrep_workers_find(subid, false, true);
2744 [ + + + + : 262 : foreach(lc, subworkers)
+ + ]
2745 : : {
2746 : 89 : LogicalRepWorker *w = (LogicalRepWorker *) lfirst(lc);
2747 : :
2748 : 89 : logicalrep_worker_stop(w->type, w->subid, w->relid);
2749 : : }
2750 : 173 : list_free(subworkers);
2751 : :
2752 : : /*
2753 : : * Remove the no-longer-useful entry in the launcher's table of apply
2754 : : * worker start times.
2755 : : *
2756 : : * If this transaction rolls back, the launcher might restart a failed
2757 : : * apply worker before wal_retrieve_retry_interval milliseconds have
2758 : : * elapsed, but that's pretty harmless.
2759 : : */
2760 : 173 : ApplyLauncherForgetWorkerStartTime(subid);
2761 : :
2762 : : /*
2763 : : * Cleanup of tablesync replication origins.
2764 : : *
2765 : : * Any READY-state relations would already have dealt with clean-ups.
2766 : : *
2767 : : * Note that the state can't change because we have already stopped both
2768 : : * the apply and tablesync workers and they can't restart because of
2769 : : * exclusive lock on the subscription.
2770 : : */
2771 : 173 : rstates = GetSubscriptionRelations(subid, true, false, true);
2772 [ + + + + : 178 : foreach(lc, rstates)
+ + ]
2773 : : {
2774 : 5 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
2775 : 5 : Oid relid = rstate->relid;
2776 : :
2777 : : /* Only cleanup resources of tablesync workers */
2778 [ - + ]: 5 : if (!OidIsValid(relid))
2779 : 0 : continue;
2780 : :
2781 : : /*
2782 : : * Drop the tablesync's origin tracking if exists.
2783 : : *
2784 : : * It is possible that the origin is not yet created for tablesync
2785 : : * worker so passing missing_ok = true. This can happen for the states
2786 : : * before SUBREL_STATE_DATASYNC.
2787 : : */
2788 : 5 : ReplicationOriginNameForLogicalRep(subid, relid, originname,
2789 : : sizeof(originname));
2790 : 5 : replorigin_drop_by_name(originname, true, false);
2791 : : }
2792 : :
2793 : : /* Drop subscription's conflict log table */
2794 : 173 : drop_sub_conflict_log_table(subid, subname, subconflictlogrelid);
2795 : :
2796 : : /* Clean up dependencies */
2797 : 173 : deleteDependencyRecordsFor(SubscriptionRelationId, subid, false);
2798 : 173 : deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
2799 : :
2800 : : /* Remove any associated relation synchronization states. */
2801 : 173 : RemoveSubscriptionRel(subid, InvalidOid);
2802 : :
2803 : : /* Remove the origin tracking if exists. */
2804 : 173 : ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
2805 : 173 : replorigin_drop_by_name(originname, true, false);
2806 : :
2807 : : /*
2808 : : * Tell the cumulative stats system that the subscription is getting
2809 : : * dropped.
2810 : : */
2811 : 173 : pgstat_drop_subscription(subid);
2812 : :
2813 : : /*
2814 : : * If there is no slot associated with the subscription, we can finish
2815 : : * here.
2816 : : */
2817 [ + + + - ]: 173 : if (!slotname && rstates == NIL)
2818 : : {
2819 : 82 : table_close(rel, NoLock);
2820 : 82 : return;
2821 : : }
2822 : :
2823 : : /*
2824 : : * Try to acquire the connection necessary for dropping slots.
2825 : : *
2826 : : * Note: If the slotname is NONE/NULL then we allow the command to finish
2827 : : * and users need to manually cleanup the apply and tablesync worker slots
2828 : : * later.
2829 : : *
2830 : : * This has to be at the end because otherwise if there is an error while
2831 : : * doing the database operations we won't be able to rollback dropped
2832 : : * slot.
2833 : : */
2834 : 91 : load_file("libpqwalreceiver", false);
2835 : :
2836 [ + + ]: 91 : if (OidIsValid(subserver))
2837 : 8 : conninfo = construct_subserver_conninfo(subserver, subowner, &err);
2838 : : else
2839 : 83 : conninfo = subconninfo;
2840 : :
2841 [ + + ]: 87 : if (conninfo)
2842 : 83 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
2843 : : subname, &err);
2844 : :
2845 [ + + ]: 87 : if (wrconn == NULL)
2846 : : {
2847 [ - + ]: 4 : if (!slotname)
2848 : : {
2849 : : /* be tidy */
2850 : 0 : list_free(rstates);
2851 : 0 : table_close(rel, NoLock);
2852 : 0 : return;
2853 : : }
2854 : : else
2855 : : {
2856 : 4 : ReportSlotConnectionError(rstates, subid, slotname, err);
2857 : : }
2858 : : }
2859 : :
2860 [ + + ]: 83 : PG_TRY();
2861 : : {
2862 [ + + + + : 88 : foreach(lc, rstates)
+ + ]
2863 : : {
2864 : 5 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
2865 : 5 : Oid relid = rstate->relid;
2866 : :
2867 : : /* Only cleanup resources of tablesync workers */
2868 [ - + ]: 5 : if (!OidIsValid(relid))
2869 : 0 : continue;
2870 : :
2871 : : /*
2872 : : * Drop the tablesync slots associated with removed tables.
2873 : : *
2874 : : * For SYNCDONE/READY states, the tablesync slot is known to have
2875 : : * already been dropped by the tablesync worker.
2876 : : *
2877 : : * For other states, there is no certainty, maybe the slot does
2878 : : * not exist yet. Also, if we fail after removing some of the
2879 : : * slots, next time, it will again try to drop already dropped
2880 : : * slots and fail. For these reasons, we allow missing_ok = true
2881 : : * for the drop.
2882 : : */
2883 [ + + ]: 5 : if (rstate->state != SUBREL_STATE_SYNCDONE)
2884 : : {
2885 : 3 : char syncslotname[NAMEDATALEN] = {0};
2886 : :
2887 : 3 : ReplicationSlotNameForTablesync(subid, relid, syncslotname,
2888 : : sizeof(syncslotname));
2889 : 3 : ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
2890 : : }
2891 : : }
2892 : :
2893 : 83 : list_free(rstates);
2894 : :
2895 : : /*
2896 : : * If there is a slot associated with the subscription, then drop the
2897 : : * replication slot at the publisher.
2898 : : */
2899 [ + - ]: 83 : if (slotname)
2900 : 83 : ReplicationSlotDropAtPubNode(wrconn, slotname, false);
2901 : : }
2902 : 1 : PG_FINALLY();
2903 : : {
2904 : 83 : walrcv_disconnect(wrconn);
2905 : : }
2906 [ + + ]: 83 : PG_END_TRY();
2907 : :
2908 : 82 : table_close(rel, NoLock);
2909 : : }
2910 : :
2911 : : /*
2912 : : * Drop the replication slot at the publisher node using the replication
2913 : : * connection.
2914 : : *
2915 : : * missing_ok - if true then only issue a LOG message if the slot doesn't
2916 : : * exist.
2917 : : */
2918 : : void
2919 : 305 : ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
2920 : : {
2921 : : StringInfoData cmd;
2922 : :
2923 : : Assert(wrconn);
2924 : :
2925 : 305 : load_file("libpqwalreceiver", false);
2926 : :
2927 : 305 : initStringInfo(&cmd);
2928 : 305 : appendStringInfoString(&cmd, "DROP_REPLICATION_SLOT ");
2929 : 305 : appendQuotedIdentifier(&cmd, slotname);
2930 : 305 : appendStringInfoString(&cmd, " WAIT");
2931 : :
2932 [ + + ]: 305 : PG_TRY();
2933 : : {
2934 : : WalRcvExecResult *res;
2935 : :
2936 : 305 : res = walrcv_exec(wrconn, cmd.data, 0, NULL);
2937 : :
2938 [ + + ]: 305 : if (res->status == WALRCV_OK_COMMAND)
2939 : : {
2940 : : /* NOTICE. Success. */
2941 [ + + ]: 303 : ereport(NOTICE,
2942 : : (errmsg("dropped replication slot \"%s\" on publisher",
2943 : : slotname)));
2944 : : }
2945 [ + - + + ]: 2 : else if (res->status == WALRCV_ERROR &&
2946 : 1 : missing_ok &&
2947 [ + - ]: 1 : res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
2948 : : {
2949 : : /* LOG. Error, but missing_ok = true. */
2950 [ + - ]: 1 : ereport(LOG,
2951 : : (errmsg("could not drop replication slot \"%s\" on publisher: %s",
2952 : : slotname, res->err)));
2953 : : }
2954 : : else
2955 : : {
2956 : : /* ERROR. */
2957 [ + - ]: 1 : ereport(ERROR,
2958 : : (errcode(ERRCODE_CONNECTION_FAILURE),
2959 : : errmsg("could not drop replication slot \"%s\" on publisher: %s",
2960 : : slotname, res->err)));
2961 : : }
2962 : :
2963 : 304 : walrcv_clear_result(res);
2964 : : }
2965 : 1 : PG_FINALLY();
2966 : : {
2967 : 305 : pfree(cmd.data);
2968 : : }
2969 [ + + ]: 305 : PG_END_TRY();
2970 : 304 : }
2971 : :
2972 : : /*
2973 : : * Internal workhorse for changing a subscription owner
2974 : : */
2975 : : static void
2976 : 29 : AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
2977 : : {
2978 : : Form_pg_subscription form;
2979 : : AclResult aclresult;
2980 : :
2981 : 29 : form = (Form_pg_subscription) GETSTRUCT(tup);
2982 : :
2983 : : /* Must only alter subscriptions belonging to the current database. */
2984 : : Assert(form->subdbid == MyDatabaseId);
2985 : :
2986 [ + + ]: 29 : if (form->subowner == newOwnerId)
2987 : 2 : return;
2988 : :
2989 [ - + ]: 27 : if (!object_ownercheck(SubscriptionRelationId, form->oid, GetUserId()))
2990 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
2991 : 0 : NameStr(form->subname));
2992 : :
2993 : : /*
2994 : : * Don't allow non-superuser modification of a subscription with
2995 : : * password_required=false.
2996 : : */
2997 [ + + - + ]: 27 : if (!form->subpasswordrequired && !superuser())
2998 [ # # ]: 0 : ereport(ERROR,
2999 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3000 : : errmsg("password_required=false is superuser-only"),
3001 : : errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
3002 : :
3003 : : /* Must be able to become new owner */
3004 : 27 : check_can_set_role(GetUserId(), newOwnerId);
3005 : :
3006 : : /*
3007 : : * current owner must have CREATE on database
3008 : : *
3009 : : * This is consistent with how ALTER SCHEMA ... OWNER TO works, but some
3010 : : * other object types behave differently (e.g. you can't give a table to a
3011 : : * user who lacks CREATE privileges on a schema).
3012 : : */
3013 : 23 : aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
3014 : : GetUserId(), ACL_CREATE);
3015 [ - + ]: 23 : if (aclresult != ACLCHECK_OK)
3016 : 0 : aclcheck_error(aclresult, OBJECT_DATABASE,
3017 : 0 : get_database_name(MyDatabaseId));
3018 : :
3019 : : /*
3020 : : * The privileges will be checked before the connection is actually used,
3021 : : * so it does not need to be done here. Avoid unnecessary risk of errors
3022 : : * here, which could interfere with restore.
3023 : : *
3024 : : * However, it is convenient to check if a user mapping exists, and raise
3025 : : * a WARNING if not.
3026 : : */
3027 [ + + ]: 23 : if (OidIsValid(form->subserver))
3028 : 9 : GetUserMappingExtended(newOwnerId, form->subserver, WARNING);
3029 : :
3030 : 23 : form->subowner = newOwnerId;
3031 : 23 : CatalogTupleUpdate(rel, &tup->t_self, tup);
3032 : :
3033 : : /* Update owner of the conflict log table if it exists. */
3034 [ + + ]: 23 : if (OidIsValid(form->subconflictlogrelid))
3035 : 8 : ATExecChangeOwner(form->subconflictlogrelid, newOwnerId, true,
3036 : : AccessExclusiveLock);
3037 : :
3038 : : /* Update owner dependency reference */
3039 : 23 : changeDependencyOnOwner(SubscriptionRelationId,
3040 : : form->oid,
3041 : : newOwnerId);
3042 : :
3043 [ - + ]: 23 : InvokeObjectPostAlterHook(SubscriptionRelationId,
3044 : : form->oid, 0);
3045 : :
3046 : : /* Wake up related background processes to handle this change quickly. */
3047 : 23 : ApplyLauncherWakeupAtCommit();
3048 : 23 : LogicalRepWorkersWakeupAtCommit(form->oid);
3049 : : }
3050 : :
3051 : : /*
3052 : : * Change subscription owner -- by name
3053 : : */
3054 : : ObjectAddress
3055 : 28 : AlterSubscriptionOwner(const char *name, Oid newOwnerId)
3056 : : {
3057 : : Oid subid;
3058 : : HeapTuple tup;
3059 : : Relation rel;
3060 : : ObjectAddress address;
3061 : : Form_pg_subscription form;
3062 : :
3063 : 28 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
3064 : :
3065 : 28 : tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
3066 : : CStringGetDatum(name));
3067 : :
3068 [ - + ]: 28 : if (!HeapTupleIsValid(tup))
3069 [ # # ]: 0 : ereport(ERROR,
3070 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
3071 : : errmsg("subscription \"%s\" does not exist", name)));
3072 : :
3073 : 28 : form = (Form_pg_subscription) GETSTRUCT(tup);
3074 : 28 : subid = form->oid;
3075 : :
3076 : 28 : AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
3077 : :
3078 : 24 : ObjectAddressSet(address, SubscriptionRelationId, subid);
3079 : :
3080 : 24 : heap_freetuple(tup);
3081 : :
3082 : 24 : table_close(rel, RowExclusiveLock);
3083 : :
3084 : 24 : return address;
3085 : : }
3086 : :
3087 : : /*
3088 : : * Change subscription owner -- by OID
3089 : : */
3090 : : void
3091 : 2 : AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
3092 : : {
3093 : : HeapTuple tup;
3094 : : Relation rel;
3095 : : Form_pg_subscription form;
3096 : :
3097 : 2 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
3098 : :
3099 : 2 : tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
3100 : :
3101 [ - + ]: 2 : if (!HeapTupleIsValid(tup))
3102 [ # # ]: 0 : ereport(ERROR,
3103 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
3104 : : errmsg("subscription with OID %u does not exist", subid)));
3105 : :
3106 : 2 : form = (Form_pg_subscription) GETSTRUCT(tup);
3107 : :
3108 : : /*
3109 : : * Don't process subscriptions belonging to other databases. While
3110 : : * pg_subscription is a shared catalog, subscriptions refer to db-local
3111 : : * objects which exist only in the database identified by subdbid.
3112 : : */
3113 [ + + ]: 2 : if (form->subdbid == MyDatabaseId)
3114 : 1 : AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
3115 : :
3116 : 2 : heap_freetuple(tup);
3117 : :
3118 : 2 : table_close(rel, RowExclusiveLock);
3119 : 2 : }
3120 : :
3121 : : /*
3122 : : * Check and log a warning if the publisher has subscribed to the same table,
3123 : : * its partition ancestors (if it's a partition), or its partition children (if
3124 : : * it's a partitioned table), from some other publishers. This check is
3125 : : * required in the following scenarios:
3126 : : *
3127 : : * 1) For CREATE SUBSCRIPTION and ALTER SUBSCRIPTION ... REFRESH PUBLICATION
3128 : : * statements with "copy_data = true" and "origin = none":
3129 : : * - Warn the user that data with an origin might have been copied.
3130 : : * - This check is skipped for tables already added, as incremental sync via
3131 : : * WAL allows origin tracking. The list of such tables is in
3132 : : * subrel_local_oids.
3133 : : *
3134 : : * 2) For CREATE SUBSCRIPTION and ALTER SUBSCRIPTION ... REFRESH PUBLICATION
3135 : : * statements with "retain_dead_tuples = true" and "origin = any", and for
3136 : : * ALTER SUBSCRIPTION statements that modify retain_dead_tuples or origin,
3137 : : * or when the publisher's status changes (e.g., due to a connection string
3138 : : * update):
3139 : : * - Warn the user that only conflict detection info for local changes on
3140 : : * the publisher is retained. Data from other origins may lack sufficient
3141 : : * details for reliable conflict detection.
3142 : : * - See comments atop worker.c for more details.
3143 : : */
3144 : : static void
3145 : 183 : check_publications_origin_tables(WalReceiverConn *wrconn, List *publications,
3146 : : bool copydata, bool retain_dead_tuples,
3147 : : char *origin, Oid *subrel_local_oids,
3148 : : int subrel_count, char *subname)
3149 : : {
3150 : : WalRcvExecResult *res;
3151 : : StringInfoData cmd;
3152 : : TupleTableSlot *slot;
3153 : 183 : Oid tableRow[1] = {TEXTOID};
3154 : 183 : List *publist = NIL;
3155 : : int i;
3156 : : bool check_rdt;
3157 : : bool check_table_sync;
3158 [ + - + + ]: 366 : bool origin_none = origin &&
3159 : 183 : pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) == 0;
3160 : :
3161 : : /*
3162 : : * Enable retain_dead_tuples checks only when origin is set to 'any',
3163 : : * since with origin='none' only local changes are replicated to the
3164 : : * subscriber.
3165 : : */
3166 [ + + + + ]: 183 : check_rdt = retain_dead_tuples && !origin_none;
3167 : :
3168 : : /*
3169 : : * Enable table synchronization checks only when origin is 'none', to
3170 : : * ensure that data from other origins is not inadvertently copied.
3171 : : */
3172 [ + + + + ]: 183 : check_table_sync = copydata && origin_none;
3173 : :
3174 : : /* retain_dead_tuples and table sync checks occur separately */
3175 : : Assert(!(check_rdt && check_table_sync));
3176 : :
3177 : : /* Return if no checks are required */
3178 [ + + + + ]: 183 : if (!check_rdt && !check_table_sync)
3179 : 166 : return;
3180 : :
3181 : 17 : initStringInfo(&cmd);
3182 : 17 : appendStringInfoString(&cmd,
3183 : : "SELECT DISTINCT P.pubname AS pubname\n"
3184 : : "FROM pg_publication P,\n"
3185 : : " LATERAL pg_get_publication_tables(P.pubname) GPT\n"
3186 : : " JOIN pg_subscription_rel PS ON (GPT.relid = PS.srrelid OR"
3187 : : " GPT.relid IN (SELECT relid FROM pg_partition_ancestors(PS.srrelid) UNION"
3188 : : " SELECT relid FROM pg_partition_tree(PS.srrelid))),\n"
3189 : : " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
3190 : : "WHERE C.oid = GPT.relid AND P.pubname IN (");
3191 : 17 : GetPublicationsStr(publications, &cmd, true);
3192 : 17 : appendStringInfoString(&cmd, ")\n");
3193 : :
3194 : : /*
3195 : : * In case of ALTER SUBSCRIPTION ... REFRESH PUBLICATION,
3196 : : * subrel_local_oids contains the list of relation oids that are already
3197 : : * present on the subscriber. This check should be skipped for these
3198 : : * tables if checking for table sync scenario. However, when handling the
3199 : : * retain_dead_tuples scenario, ensure all tables are checked, as some
3200 : : * existing tables may now include changes from other origins due to newly
3201 : : * created subscriptions on the publisher.
3202 : : */
3203 [ + + ]: 17 : if (check_table_sync)
3204 : : {
3205 [ + + ]: 23 : for (i = 0; i < subrel_count; i++)
3206 : : {
3207 : 9 : Oid relid = subrel_local_oids[i];
3208 : : char *schemaname;
3209 : : char *tablename;
3210 : : char *schemaname_lit;
3211 : : char *tablename_lit;
3212 : :
3213 : : /* The table may have been dropped concurrently; skip if gone. */
3214 : 9 : tablename = get_rel_name(relid);
3215 [ - + ]: 9 : if (tablename == NULL)
3216 : 0 : continue;
3217 : :
3218 : 9 : schemaname = get_namespace_name(get_rel_namespace(relid));
3219 [ - + ]: 9 : if (schemaname == NULL)
3220 : 0 : continue;
3221 : :
3222 : 9 : schemaname_lit = quote_literal_cstr(schemaname);
3223 : 9 : tablename_lit = quote_literal_cstr(tablename);
3224 : :
3225 : 9 : appendStringInfo(&cmd, "AND NOT (N.nspname = %s AND C.relname = %s)\n",
3226 : : schemaname_lit, tablename_lit);
3227 : :
3228 : 9 : pfree(schemaname_lit);
3229 : 9 : pfree(tablename_lit);
3230 : : }
3231 : : }
3232 : :
3233 : 17 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
3234 : 17 : pfree(cmd.data);
3235 : :
3236 [ - + ]: 17 : if (res->status != WALRCV_OK_TUPLES)
3237 [ # # ]: 0 : ereport(ERROR,
3238 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3239 : : errmsg("could not receive list of replicated tables from the publisher: %s",
3240 : : res->err)));
3241 : :
3242 : : /* Process publications. */
3243 : 17 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3244 [ + + ]: 23 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3245 : : {
3246 : : char *pubname;
3247 : : bool isnull;
3248 : :
3249 : 6 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
3250 : : Assert(!isnull);
3251 : :
3252 : 6 : ExecClearTuple(slot);
3253 : 6 : publist = list_append_unique(publist, makeString(pubname));
3254 : : }
3255 : :
3256 : : /*
3257 : : * Log a warning if the publisher has subscribed to the same table from
3258 : : * some other publisher. We cannot know the origin of data during the
3259 : : * initial sync. Data origins can be found only from the WAL by looking at
3260 : : * the origin id.
3261 : : *
3262 : : * XXX: For simplicity, we don't check whether the table has any data or
3263 : : * not. If the table doesn't have any data then we don't need to
3264 : : * distinguish between data having origin and data not having origin so we
3265 : : * can avoid logging a warning for table sync scenario.
3266 : : */
3267 [ + + ]: 17 : if (publist)
3268 : : {
3269 : : StringInfoData pubnames;
3270 : :
3271 : : /* Prepare the list of publication(s) for warning message. */
3272 : 6 : initStringInfo(&pubnames);
3273 : 6 : GetPublicationsStr(publist, &pubnames, false);
3274 : :
3275 [ + + ]: 6 : if (check_table_sync)
3276 [ + - ]: 5 : ereport(WARNING,
3277 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3278 : : errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
3279 : : subname),
3280 : : errdetail_plural("The subscription subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
3281 : : "The subscription subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
3282 : : list_length(publist), pubnames.data),
3283 : : errhint("Verify that initial data copied from the publisher tables did not come from other origins."));
3284 : : else
3285 [ + - ]: 1 : ereport(WARNING,
3286 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3287 : : errmsg("subscription \"%s\" enabled retain_dead_tuples but might not reliably detect conflicts for changes from different origins",
3288 : : subname),
3289 : : errdetail_plural("The subscription subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
3290 : : "The subscription subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
3291 : : list_length(publist), pubnames.data),
3292 : : errhint("Consider using origin = NONE or disabling retain_dead_tuples."));
3293 : : }
3294 : :
3295 : 17 : ExecDropSingleTupleTableSlot(slot);
3296 : :
3297 : 17 : walrcv_clear_result(res);
3298 : : }
3299 : :
3300 : : /*
3301 : : * This function is similar to check_publications_origin_tables and serves
3302 : : * same purpose for sequences.
3303 : : */
3304 : : static void
3305 : 182 : check_publications_origin_sequences(WalReceiverConn *wrconn, List *publications,
3306 : : bool copydata, char *origin,
3307 : : Oid *subrel_local_oids, int subrel_count,
3308 : : char *subname)
3309 : : {
3310 : : WalRcvExecResult *res;
3311 : : StringInfoData cmd;
3312 : : TupleTableSlot *slot;
3313 : 182 : Oid tableRow[1] = {TEXTOID};
3314 : 182 : List *publist = NIL;
3315 : :
3316 : : /*
3317 : : * Enable sequence synchronization checks only when origin is 'none' , to
3318 : : * ensure that sequence data from other origins is not inadvertently
3319 : : * copied. This check is necessary if the publisher is running PG19 or
3320 : : * later, where logical replication sequence synchronization is supported.
3321 : : */
3322 [ + + + + : 196 : if (!copydata || pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) != 0 ||
- + ]
3323 : 14 : walrcv_server_version(wrconn) < 190000)
3324 : 168 : return;
3325 : :
3326 : 14 : initStringInfo(&cmd);
3327 : 14 : appendStringInfoString(&cmd,
3328 : : "SELECT DISTINCT P.pubname AS pubname\n"
3329 : : "FROM pg_publication P,\n"
3330 : : " LATERAL pg_get_publication_sequences(P.pubname) GPS\n"
3331 : : " JOIN pg_subscription_rel PS ON (GPS.relid = PS.srrelid),\n"
3332 : : " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
3333 : : "WHERE C.oid = GPS.relid AND P.pubname IN (");
3334 : :
3335 : 14 : GetPublicationsStr(publications, &cmd, true);
3336 : 14 : appendStringInfoString(&cmd, ")\n");
3337 : :
3338 : : /*
3339 : : * In case of ALTER SUBSCRIPTION ... REFRESH PUBLICATION,
3340 : : * subrel_local_oids contains the list of relations that are already
3341 : : * present on the subscriber. This check should be skipped as these will
3342 : : * not be re-synced.
3343 : : */
3344 [ + + ]: 15 : for (int i = 0; i < subrel_count; i++)
3345 : : {
3346 : 1 : Oid relid = subrel_local_oids[i];
3347 : : char *schemaname;
3348 : : char *seqname;
3349 : : char *schemaname_lit;
3350 : : char *seqname_lit;
3351 : :
3352 : : /* The sequence may have been dropped concurrently; skip if gone. */
3353 : 1 : seqname = get_rel_name(relid);
3354 [ + - ]: 1 : if (seqname == NULL)
3355 : 1 : continue;
3356 : :
3357 : 0 : schemaname = get_namespace_name(get_rel_namespace(relid));
3358 [ # # ]: 0 : if (schemaname == NULL)
3359 : 0 : continue;
3360 : :
3361 : 0 : schemaname_lit = quote_literal_cstr(schemaname);
3362 : 0 : seqname_lit = quote_literal_cstr(seqname);
3363 : :
3364 : 0 : appendStringInfo(&cmd,
3365 : : "AND NOT (N.nspname = %s AND C.relname = %s)\n",
3366 : : schemaname_lit, seqname_lit);
3367 : :
3368 : 0 : pfree(schemaname_lit);
3369 : 0 : pfree(seqname_lit);
3370 : : }
3371 : :
3372 : 14 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
3373 : 14 : pfree(cmd.data);
3374 : :
3375 [ - + ]: 14 : if (res->status != WALRCV_OK_TUPLES)
3376 [ # # ]: 0 : ereport(ERROR,
3377 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3378 : : errmsg("could not receive list of replicated sequences from the publisher: %s",
3379 : : res->err)));
3380 : :
3381 : : /* Process publications. */
3382 : 14 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3383 [ - + ]: 14 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3384 : : {
3385 : : char *pubname;
3386 : : bool isnull;
3387 : :
3388 : 0 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
3389 : : Assert(!isnull);
3390 : :
3391 : 0 : ExecClearTuple(slot);
3392 : 0 : publist = list_append_unique(publist, makeString(pubname));
3393 : : }
3394 : :
3395 : : /*
3396 : : * Log a warning if the publisher has subscribed to the same sequence from
3397 : : * some other publisher. We cannot know the origin of sequences data
3398 : : * during the initial sync.
3399 : : */
3400 [ - + ]: 14 : if (publist)
3401 : : {
3402 : : StringInfoData pubnames;
3403 : :
3404 : : /* Prepare the list of publication(s) for warning message. */
3405 : 0 : initStringInfo(&pubnames);
3406 : 0 : GetPublicationsStr(publist, &pubnames, false);
3407 : :
3408 [ # # ]: 0 : ereport(WARNING,
3409 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3410 : : errmsg("subscription \"%s\" requested origin = NONE but might synchronize sequence values that had a different origin",
3411 : : subname),
3412 : : errdetail_plural("The subscription subscribes to a publication (%s) that contains sequences that are synchronized from other subscriptions.",
3413 : : "The subscription subscribes to publications (%s) that contain sequences that are synchronized from other subscriptions.",
3414 : : list_length(publist), pubnames.data),
3415 : : errhint("Verify that the initial values copied from the publisher sequences did not come from other origins."));
3416 : : }
3417 : :
3418 : 14 : ExecDropSingleTupleTableSlot(slot);
3419 : :
3420 : 14 : walrcv_clear_result(res);
3421 : : }
3422 : :
3423 : : /*
3424 : : * Determine whether the retain_dead_tuples can be enabled based on the
3425 : : * publisher's status.
3426 : : *
3427 : : * This option is disallowed if the publisher is running a version earlier
3428 : : * than the PG19, or if the publisher is in recovery (i.e., it is a standby
3429 : : * server).
3430 : : *
3431 : : * This is used both at DDL time (as a convenience, when a connection to the
3432 : : * publisher is already being made) and by the apply worker when it connects,
3433 : : * which is the authoritative check because the publisher's version and
3434 : : * recovery status can change after the DDL command.
3435 : : *
3436 : : * See comments atop worker.c for a detailed explanation.
3437 : : */
3438 : : void
3439 : 22 : CheckPubDeadTupleRetention(WalReceiverConn *wrconn)
3440 : : {
3441 : : WalRcvExecResult *res;
3442 : 22 : Oid RecoveryRow[1] = {BOOLOID};
3443 : : TupleTableSlot *slot;
3444 : : bool isnull;
3445 : : bool remote_in_recovery;
3446 : :
3447 [ - + ]: 22 : if (walrcv_server_version(wrconn) < 190000)
3448 [ # # ]: 0 : ereport(ERROR,
3449 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3450 : : errmsg("cannot enable retain_dead_tuples if the publisher is running a version earlier than PostgreSQL 19"));
3451 : :
3452 : 22 : res = walrcv_exec(wrconn, "SELECT pg_is_in_recovery()", 1, RecoveryRow);
3453 : :
3454 [ - + ]: 22 : if (res->status != WALRCV_OK_TUPLES)
3455 [ # # ]: 0 : ereport(ERROR,
3456 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3457 : : errmsg("could not obtain recovery progress from the publisher: %s",
3458 : : res->err)));
3459 : :
3460 : 22 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3461 [ - + ]: 22 : if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3462 [ # # ]: 0 : elog(ERROR, "failed to fetch tuple for the recovery progress");
3463 : :
3464 : 22 : remote_in_recovery = DatumGetBool(slot_getattr(slot, 1, &isnull));
3465 : :
3466 [ - + ]: 22 : if (remote_in_recovery)
3467 [ # # ]: 0 : ereport(ERROR,
3468 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3469 : : errmsg("cannot enable retain_dead_tuples if the publisher is in recovery"));
3470 : :
3471 : 22 : ExecDropSingleTupleTableSlot(slot);
3472 : :
3473 : 22 : walrcv_clear_result(res);
3474 : 22 : }
3475 : :
3476 : : /*
3477 : : * Check if the subscriber's configuration is adequate to enable the
3478 : : * retain_dead_tuples option.
3479 : : *
3480 : : * Issue an ERROR if the wal_level does not support the use of replication
3481 : : * slots when check_guc is set to true.
3482 : : *
3483 : : * Issue a WARNING if track_commit_timestamp is not enabled when check_guc is
3484 : : * set to true. This is only to highlight the importance of enabling
3485 : : * track_commit_timestamp instead of catching all the misconfigurations, as
3486 : : * this setting can be adjusted after subscription creation. Without it, the
3487 : : * apply worker will simply skip conflict detection.
3488 : : *
3489 : : * Issue a WARNING or NOTICE if the subscription is disabled and the retention
3490 : : * is active. Do not raise an ERROR since users can only modify
3491 : : * retain_dead_tuples for disabled subscriptions. And as long as the
3492 : : * subscription is enabled promptly, it will not pose issues.
3493 : : *
3494 : : * Issue a NOTICE to inform users that max_retention_duration is
3495 : : * ineffective when retain_dead_tuples is disabled for a subscription. An ERROR
3496 : : * is not issued because setting max_retention_duration causes no harm,
3497 : : * even when it is ineffective.
3498 : : */
3499 : : void
3500 : 346 : CheckSubDeadTupleRetention(bool check_guc, bool sub_disabled,
3501 : : int elevel_for_sub_disabled,
3502 : : bool retain_dead_tuples, bool retention_active,
3503 : : bool max_retention_set)
3504 : : {
3505 : : Assert(elevel_for_sub_disabled == NOTICE ||
3506 : : elevel_for_sub_disabled == WARNING);
3507 : :
3508 [ + + ]: 346 : if (retain_dead_tuples)
3509 : : {
3510 [ + + - + ]: 20 : if (check_guc && wal_level < WAL_LEVEL_REPLICA)
3511 [ # # ]: 0 : ereport(ERROR,
3512 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3513 : : errmsg("\"wal_level\" is insufficient to create the replication slot required by retain_dead_tuples"),
3514 : : errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start."));
3515 : :
3516 [ + + + + ]: 20 : if (check_guc && !track_commit_timestamp)
3517 [ + - ]: 4 : ereport(WARNING,
3518 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3519 : : errmsg("commit timestamp and origin data required for detecting conflicts won't be retained"),
3520 : : errhint("Consider setting \"%s\" to true.",
3521 : : "track_commit_timestamp"));
3522 : :
3523 [ + + + - ]: 20 : if (sub_disabled && retention_active)
3524 [ + - + + ]: 8 : ereport(elevel_for_sub_disabled,
3525 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3526 : : errmsg("deleted rows to detect conflicts would not be removed until the subscription is enabled"),
3527 : : (elevel_for_sub_disabled > NOTICE)
3528 : : ? errhint("Consider setting %s to false.",
3529 : : "retain_dead_tuples") : 0);
3530 : : }
3531 [ + + ]: 326 : else if (max_retention_set)
3532 : : {
3533 [ + - ]: 4 : ereport(NOTICE,
3534 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3535 : : errmsg("max_retention_duration is ineffective when retain_dead_tuples is disabled"));
3536 : : }
3537 : 346 : }
3538 : :
3539 : : /*
3540 : : * Return true iff 'rv' is a member of the list.
3541 : : */
3542 : : static bool
3543 : 301 : list_member_rangevar(const List *list, RangeVar *rv)
3544 : : {
3545 [ + + + + : 1077 : foreach_ptr(PublicationRelKind, relinfo, list)
+ + ]
3546 : : {
3547 [ + + ]: 477 : if (equal(relinfo->rv, rv))
3548 : 1 : return true;
3549 : : }
3550 : :
3551 : 300 : return false;
3552 : : }
3553 : :
3554 : : /*
3555 : : * Get the list of tables and sequences which belong to specified publications
3556 : : * on the publisher connection.
3557 : : *
3558 : : * Note that we don't support the case where the column list is different for
3559 : : * the same table in different publications to avoid sending unwanted column
3560 : : * information for some of the rows. This can happen when both the column
3561 : : * list and row filter are specified for different publications.
3562 : : */
3563 : : static List *
3564 : 176 : fetch_relation_list(WalReceiverConn *wrconn, List *publications)
3565 : : {
3566 : : WalRcvExecResult *res;
3567 : : StringInfoData cmd;
3568 : : TupleTableSlot *slot;
3569 : 176 : Oid tableRow[4] = {TEXTOID, TEXTOID, CHAROID, InvalidOid};
3570 : 176 : List *relationlist = NIL;
3571 : 176 : int server_version = walrcv_server_version(wrconn);
3572 : 176 : bool check_columnlist = (server_version >= 150000);
3573 [ + - ]: 176 : int column_count = check_columnlist ? 4 : 3;
3574 : : StringInfoData pub_names;
3575 : :
3576 : 176 : initStringInfo(&cmd);
3577 : 176 : initStringInfo(&pub_names);
3578 : :
3579 : : /* Build the pub_names comma-separated string. */
3580 : 176 : GetPublicationsStr(publications, &pub_names, true);
3581 : :
3582 : : /* Get the list of relations from the publisher */
3583 [ + - ]: 176 : if (server_version >= 160000)
3584 : : {
3585 : 176 : tableRow[3] = INT2VECTOROID;
3586 : :
3587 : : /*
3588 : : * From version 16, we allowed passing multiple publications to the
3589 : : * function pg_get_publication_tables. This helped to filter out the
3590 : : * partition table whose ancestor is also published in this
3591 : : * publication array.
3592 : : *
3593 : : * Join pg_get_publication_tables with pg_publication to exclude
3594 : : * non-existing publications.
3595 : : *
3596 : : * Note that attrs are always stored in sorted order so we don't need
3597 : : * to worry if different publications have specified them in a
3598 : : * different order. See pub_collist_validate.
3599 : : */
3600 : 176 : appendStringInfo(&cmd, "SELECT DISTINCT n.nspname, c.relname, c.relkind, gpt.attrs\n"
3601 : : " FROM pg_class c\n"
3602 : : " JOIN pg_namespace n ON n.oid = c.relnamespace\n"
3603 : : " JOIN ( SELECT (pg_get_publication_tables(VARIADIC array_agg(pubname::text))).*\n"
3604 : : " FROM pg_publication\n"
3605 : : " WHERE pubname IN ( %s )) AS gpt\n"
3606 : : " ON gpt.relid = c.oid\n",
3607 : : pub_names.data);
3608 : :
3609 : : /* From version 19, inclusion of sequences in the target is supported */
3610 [ + - ]: 176 : if (server_version >= 190000)
3611 : 176 : appendStringInfo(&cmd,
3612 : : "UNION ALL\n"
3613 : : " SELECT DISTINCT s.schemaname, s.sequencename, " CppAsString2(RELKIND_SEQUENCE) "::\"char\" AS relkind, NULL::int2vector AS attrs\n"
3614 : : " FROM pg_catalog.pg_publication_sequences s\n"
3615 : : " WHERE s.pubname IN ( %s )",
3616 : : pub_names.data);
3617 : : }
3618 : : else
3619 : : {
3620 : 0 : tableRow[3] = NAMEARRAYOID;
3621 : 0 : appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename, " CppAsString2(RELKIND_RELATION) "::\"char\" AS relkind \n");
3622 : :
3623 : : /* Get column lists for each relation if the publisher supports it */
3624 [ # # ]: 0 : if (check_columnlist)
3625 : 0 : appendStringInfoString(&cmd, ", t.attnames\n");
3626 : :
3627 : 0 : appendStringInfo(&cmd, "FROM pg_catalog.pg_publication_tables t\n"
3628 : : " WHERE t.pubname IN ( %s )",
3629 : : pub_names.data);
3630 : : }
3631 : :
3632 : 176 : pfree(pub_names.data);
3633 : :
3634 : 176 : res = walrcv_exec(wrconn, cmd.data, column_count, tableRow);
3635 : 176 : pfree(cmd.data);
3636 : :
3637 [ - + ]: 176 : if (res->status != WALRCV_OK_TUPLES)
3638 [ # # ]: 0 : ereport(ERROR,
3639 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3640 : : errmsg("could not receive list of replicated tables from the publisher: %s",
3641 : : res->err)));
3642 : :
3643 : : /* Process tables. */
3644 : 176 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
3645 [ + + ]: 498 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
3646 : : {
3647 : : char *nspname;
3648 : : char *relname;
3649 : : bool isnull;
3650 : : char relkind;
3651 : 323 : PublicationRelKind *relinfo = palloc_object(PublicationRelKind);
3652 : :
3653 : 323 : nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
3654 : : Assert(!isnull);
3655 : 323 : relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
3656 : : Assert(!isnull);
3657 : 323 : relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
3658 : : Assert(!isnull);
3659 : :
3660 : 323 : relinfo->rv = makeRangeVar(nspname, relname, -1);
3661 : 323 : relinfo->relkind = relkind;
3662 : :
3663 [ + + + - ]: 323 : if (relkind != RELKIND_SEQUENCE &&
3664 [ + + ]: 301 : check_columnlist &&
3665 : 301 : list_member_rangevar(relationlist, relinfo->rv))
3666 [ + - ]: 1 : ereport(ERROR,
3667 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3668 : : errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
3669 : : nspname, relname));
3670 : : else
3671 : 322 : relationlist = lappend(relationlist, relinfo);
3672 : :
3673 : 322 : ExecClearTuple(slot);
3674 : : }
3675 : 175 : ExecDropSingleTupleTableSlot(slot);
3676 : :
3677 : 175 : walrcv_clear_result(res);
3678 : :
3679 : 175 : return relationlist;
3680 : : }
3681 : :
3682 : : /*
3683 : : * This is to report the connection failure while dropping replication slots.
3684 : : * Here, we report the WARNING for all tablesync slots so that user can drop
3685 : : * them manually, if required.
3686 : : */
3687 : : static void
3688 : 4 : ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
3689 : : {
3690 : : ListCell *lc;
3691 : :
3692 [ - + - - : 4 : foreach(lc, rstates)
- + ]
3693 : : {
3694 : 0 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
3695 : 0 : Oid relid = rstate->relid;
3696 : :
3697 : : /* Only cleanup resources of tablesync workers */
3698 [ # # ]: 0 : if (!OidIsValid(relid))
3699 : 0 : continue;
3700 : :
3701 : : /*
3702 : : * Caller needs to ensure that relstate doesn't change underneath us.
3703 : : * See DropSubscription where we get the relstates.
3704 : : */
3705 [ # # ]: 0 : if (rstate->state != SUBREL_STATE_SYNCDONE)
3706 : : {
3707 : 0 : char syncslotname[NAMEDATALEN] = {0};
3708 : :
3709 : 0 : ReplicationSlotNameForTablesync(subid, relid, syncslotname,
3710 : : sizeof(syncslotname));
3711 [ # # ]: 0 : elog(WARNING, "could not drop tablesync replication slot \"%s\"",
3712 : : syncslotname);
3713 : : }
3714 : : }
3715 : :
3716 [ + - ]: 4 : ereport(ERROR,
3717 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3718 : : errmsg("could not connect to publisher when attempting to drop replication slot \"%s\": %s",
3719 : : slotname, err),
3720 : : /* translator: %s is an SQL ALTER command */
3721 : : errhint("Use %s to disable the subscription, and then use %s to disassociate it from the slot.",
3722 : : "ALTER SUBSCRIPTION ... DISABLE",
3723 : : "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
3724 : : }
3725 : :
3726 : : /*
3727 : : * Check for duplicates in the given list of publications and error out if
3728 : : * found one. Add publications to datums as text datums, if datums is not
3729 : : * NULL.
3730 : : */
3731 : : static void
3732 : 296 : check_duplicates_in_publist(List *publist, Datum *datums)
3733 : : {
3734 : : ListCell *cell;
3735 : 296 : int j = 0;
3736 : :
3737 [ + - + + : 668 : foreach(cell, publist)
+ + ]
3738 : : {
3739 : 384 : char *name = strVal(lfirst(cell));
3740 : : ListCell *pcell;
3741 : :
3742 [ + - + - : 549 : foreach(pcell, publist)
+ - ]
3743 : : {
3744 : 549 : char *pname = strVal(lfirst(pcell));
3745 : :
3746 [ + + ]: 549 : if (pcell == cell)
3747 : 372 : break;
3748 : :
3749 [ + + ]: 177 : if (strcmp(name, pname) == 0)
3750 [ + - ]: 12 : ereport(ERROR,
3751 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
3752 : : errmsg("publication name \"%s\" used more than once",
3753 : : pname)));
3754 : : }
3755 : :
3756 [ + + ]: 372 : if (datums)
3757 : 316 : datums[j++] = CStringGetTextDatum(name);
3758 : : }
3759 : 284 : }
3760 : :
3761 : : /*
3762 : : * Merge current subscription's publications and user-specified publications
3763 : : * from ADD/DROP PUBLICATIONS.
3764 : : *
3765 : : * If addpub is true, we will add the list of publications into oldpublist.
3766 : : * Otherwise, we will delete the list of publications from oldpublist. The
3767 : : * returned list is a copy, oldpublist itself is not changed.
3768 : : *
3769 : : * subname is the subscription name, for error messages.
3770 : : */
3771 : : static List *
3772 : 35 : merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
3773 : : {
3774 : : ListCell *lc;
3775 : :
3776 : 35 : oldpublist = list_copy(oldpublist);
3777 : :
3778 : 35 : check_duplicates_in_publist(newpublist, NULL);
3779 : :
3780 [ + - + + : 59 : foreach(lc, newpublist)
+ + ]
3781 : : {
3782 : 44 : char *name = strVal(lfirst(lc));
3783 : : ListCell *lc2;
3784 : 44 : bool found = false;
3785 : :
3786 [ + - + + : 86 : foreach(lc2, oldpublist)
+ + ]
3787 : : {
3788 : 71 : char *pubname = strVal(lfirst(lc2));
3789 : :
3790 [ + + ]: 71 : if (strcmp(name, pubname) == 0)
3791 : : {
3792 : 29 : found = true;
3793 [ + + ]: 29 : if (addpub)
3794 [ + - ]: 8 : ereport(ERROR,
3795 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
3796 : : errmsg("publication \"%s\" is already in subscription \"%s\"",
3797 : : name, subname)));
3798 : : else
3799 : 21 : oldpublist = foreach_delete_current(oldpublist, lc2);
3800 : :
3801 : 21 : break;
3802 : : }
3803 : : }
3804 : :
3805 [ + + + - ]: 36 : if (addpub && !found)
3806 : 11 : oldpublist = lappend(oldpublist, makeString(name));
3807 [ + - + + ]: 25 : else if (!addpub && !found)
3808 [ + - ]: 4 : ereport(ERROR,
3809 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3810 : : errmsg("publication \"%s\" is not in subscription \"%s\"",
3811 : : name, subname)));
3812 : : }
3813 : :
3814 : : /*
3815 : : * XXX Probably no strong reason for this, but for now it's to make ALTER
3816 : : * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
3817 : : */
3818 [ + + ]: 15 : if (!oldpublist)
3819 [ + - ]: 4 : ereport(ERROR,
3820 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3821 : : errmsg("cannot drop all the publications from a subscription")));
3822 : :
3823 : 11 : return oldpublist;
3824 : : }
3825 : :
3826 : : /*
3827 : : * Extract the streaming mode value from a DefElem. This is like
3828 : : * defGetBoolean() but also accepts the special value of "parallel".
3829 : : */
3830 : : char
3831 : 520 : defGetStreamingMode(DefElem *def)
3832 : : {
3833 : : /*
3834 : : * If no parameter value given, assume "true" is meant.
3835 : : */
3836 [ - + ]: 520 : if (!def->arg)
3837 : 0 : return LOGICALREP_STREAM_ON;
3838 : :
3839 : : /*
3840 : : * Allow 0, 1, "false", "true", "off", "on" or "parallel".
3841 : : */
3842 [ - + ]: 520 : switch (nodeTag(def->arg))
3843 : : {
3844 : 0 : case T_Integer:
3845 [ # # # ]: 0 : switch (intVal(def->arg))
3846 : : {
3847 : 0 : case 0:
3848 : 0 : return LOGICALREP_STREAM_OFF;
3849 : 0 : case 1:
3850 : 0 : return LOGICALREP_STREAM_ON;
3851 : 0 : default:
3852 : : /* otherwise, error out below */
3853 : 0 : break;
3854 : : }
3855 : 0 : break;
3856 : 520 : default:
3857 : : {
3858 : 520 : char *sval = defGetString(def);
3859 : :
3860 : : /*
3861 : : * The set of strings accepted here should match up with the
3862 : : * grammar's opt_boolean_or_string production.
3863 : : */
3864 [ + + + + ]: 1036 : if (pg_strcasecmp(sval, "false") == 0 ||
3865 : 516 : pg_strcasecmp(sval, "off") == 0)
3866 : 7 : return LOGICALREP_STREAM_OFF;
3867 [ + + + + ]: 1014 : if (pg_strcasecmp(sval, "true") == 0 ||
3868 : 501 : pg_strcasecmp(sval, "on") == 0)
3869 : 49 : return LOGICALREP_STREAM_ON;
3870 [ + + ]: 464 : if (pg_strcasecmp(sval, "parallel") == 0)
3871 : 460 : return LOGICALREP_STREAM_PARALLEL;
3872 : : }
3873 : 4 : break;
3874 : : }
3875 : :
3876 [ + - ]: 4 : ereport(ERROR,
3877 : : (errcode(ERRCODE_SYNTAX_ERROR),
3878 : : errmsg("%s requires a Boolean value or \"parallel\"",
3879 : : def->defname)));
3880 : : return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
3881 : : }
|