Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * subscriptioncmds.c
4 : * subscription catalog manipulation functions
5 : *
6 : * Portions Copyright (c) 1996-2024, 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/htup_details.h"
18 : #include "access/table.h"
19 : #include "access/twophase.h"
20 : #include "access/xact.h"
21 : #include "catalog/catalog.h"
22 : #include "catalog/dependency.h"
23 : #include "catalog/indexing.h"
24 : #include "catalog/namespace.h"
25 : #include "catalog/objectaccess.h"
26 : #include "catalog/objectaddress.h"
27 : #include "catalog/pg_authid_d.h"
28 : #include "catalog/pg_database_d.h"
29 : #include "catalog/pg_subscription.h"
30 : #include "catalog/pg_subscription_rel.h"
31 : #include "catalog/pg_type.h"
32 : #include "commands/dbcommands.h"
33 : #include "commands/defrem.h"
34 : #include "commands/event_trigger.h"
35 : #include "commands/subscriptioncmds.h"
36 : #include "executor/executor.h"
37 : #include "miscadmin.h"
38 : #include "nodes/makefuncs.h"
39 : #include "pgstat.h"
40 : #include "replication/logicallauncher.h"
41 : #include "replication/logicalworker.h"
42 : #include "replication/origin.h"
43 : #include "replication/slot.h"
44 : #include "replication/walreceiver.h"
45 : #include "replication/walsender.h"
46 : #include "replication/worker_internal.h"
47 : #include "storage/lmgr.h"
48 : #include "utils/acl.h"
49 : #include "utils/builtins.h"
50 : #include "utils/guc.h"
51 : #include "utils/lsyscache.h"
52 : #include "utils/memutils.h"
53 : #include "utils/pg_lsn.h"
54 : #include "utils/syscache.h"
55 :
56 : /*
57 : * Options that can be specified by the user in CREATE/ALTER SUBSCRIPTION
58 : * command.
59 : */
60 : #define SUBOPT_CONNECT 0x00000001
61 : #define SUBOPT_ENABLED 0x00000002
62 : #define SUBOPT_CREATE_SLOT 0x00000004
63 : #define SUBOPT_SLOT_NAME 0x00000008
64 : #define SUBOPT_COPY_DATA 0x00000010
65 : #define SUBOPT_SYNCHRONOUS_COMMIT 0x00000020
66 : #define SUBOPT_REFRESH 0x00000040
67 : #define SUBOPT_BINARY 0x00000080
68 : #define SUBOPT_STREAMING 0x00000100
69 : #define SUBOPT_TWOPHASE_COMMIT 0x00000200
70 : #define SUBOPT_DISABLE_ON_ERR 0x00000400
71 : #define SUBOPT_PASSWORD_REQUIRED 0x00000800
72 : #define SUBOPT_RUN_AS_OWNER 0x00001000
73 : #define SUBOPT_FAILOVER 0x00002000
74 : #define SUBOPT_LSN 0x00004000
75 : #define SUBOPT_ORIGIN 0x00008000
76 :
77 : /* check if the 'val' has 'bits' set */
78 : #define IsSet(val, bits) (((val) & (bits)) == (bits))
79 :
80 : /*
81 : * Structure to hold a bitmap representing the user-provided CREATE/ALTER
82 : * SUBSCRIPTION command options and the parsed/default values of each of them.
83 : */
84 : typedef struct SubOpts
85 : {
86 : bits32 specified_opts;
87 : char *slot_name;
88 : char *synchronous_commit;
89 : bool connect;
90 : bool enabled;
91 : bool create_slot;
92 : bool copy_data;
93 : bool refresh;
94 : bool binary;
95 : char streaming;
96 : bool twophase;
97 : bool disableonerr;
98 : bool passwordrequired;
99 : bool runasowner;
100 : bool failover;
101 : char *origin;
102 : XLogRecPtr lsn;
103 : } SubOpts;
104 :
105 : static List *fetch_table_list(WalReceiverConn *wrconn, List *publications);
106 : static void check_publications_origin(WalReceiverConn *wrconn,
107 : List *publications, bool copydata,
108 : char *origin, Oid *subrel_local_oids,
109 : int subrel_count, char *subname);
110 : static void check_duplicates_in_publist(List *publist, Datum *datums);
111 : static List *merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname);
112 : static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err);
113 : static void CheckAlterSubOption(Subscription *sub, const char *option,
114 : bool slot_needs_update, bool isTopLevel);
115 :
116 :
117 : /*
118 : * Common option parsing function for CREATE and ALTER SUBSCRIPTION commands.
119 : *
120 : * Since not all options can be specified in both commands, this function
121 : * will report an error if mutually exclusive options are specified.
122 : */
123 : static void
124 836 : parse_subscription_options(ParseState *pstate, List *stmt_options,
125 : bits32 supported_opts, SubOpts *opts)
126 : {
127 : ListCell *lc;
128 :
129 : /* Start out with cleared opts. */
130 836 : memset(opts, 0, sizeof(SubOpts));
131 :
132 : /* caller must expect some option */
133 : Assert(supported_opts != 0);
134 :
135 : /* If connect option is supported, these others also need to be. */
136 : Assert(!IsSet(supported_opts, SUBOPT_CONNECT) ||
137 : IsSet(supported_opts, SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
138 : SUBOPT_COPY_DATA));
139 :
140 : /* Set default values for the supported options. */
141 836 : if (IsSet(supported_opts, SUBOPT_CONNECT))
142 418 : opts->connect = true;
143 836 : if (IsSet(supported_opts, SUBOPT_ENABLED))
144 498 : opts->enabled = true;
145 836 : if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
146 418 : opts->create_slot = true;
147 836 : if (IsSet(supported_opts, SUBOPT_COPY_DATA))
148 548 : opts->copy_data = true;
149 836 : if (IsSet(supported_opts, SUBOPT_REFRESH))
150 82 : opts->refresh = true;
151 836 : if (IsSet(supported_opts, SUBOPT_BINARY))
152 602 : opts->binary = false;
153 836 : if (IsSet(supported_opts, SUBOPT_STREAMING))
154 602 : opts->streaming = LOGICALREP_STREAM_OFF;
155 836 : if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
156 602 : opts->twophase = false;
157 836 : if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
158 602 : opts->disableonerr = false;
159 836 : if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED))
160 602 : opts->passwordrequired = true;
161 836 : if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER))
162 602 : opts->runasowner = false;
163 836 : if (IsSet(supported_opts, SUBOPT_FAILOVER))
164 602 : opts->failover = false;
165 836 : if (IsSet(supported_opts, SUBOPT_ORIGIN))
166 602 : opts->origin = pstrdup(LOGICALREP_ORIGIN_ANY);
167 :
168 : /* Parse options */
169 1640 : foreach(lc, stmt_options)
170 : {
171 858 : DefElem *defel = (DefElem *) lfirst(lc);
172 :
173 858 : if (IsSet(supported_opts, SUBOPT_CONNECT) &&
174 494 : strcmp(defel->defname, "connect") == 0)
175 : {
176 164 : if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
177 0 : errorConflictingDefElem(defel, pstate);
178 :
179 164 : opts->specified_opts |= SUBOPT_CONNECT;
180 164 : opts->connect = defGetBoolean(defel);
181 : }
182 694 : else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
183 410 : strcmp(defel->defname, "enabled") == 0)
184 : {
185 116 : if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
186 0 : errorConflictingDefElem(defel, pstate);
187 :
188 116 : opts->specified_opts |= SUBOPT_ENABLED;
189 116 : opts->enabled = defGetBoolean(defel);
190 : }
191 578 : else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
192 294 : strcmp(defel->defname, "create_slot") == 0)
193 : {
194 40 : if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
195 0 : errorConflictingDefElem(defel, pstate);
196 :
197 40 : opts->specified_opts |= SUBOPT_CREATE_SLOT;
198 40 : opts->create_slot = defGetBoolean(defel);
199 : }
200 538 : else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
201 442 : strcmp(defel->defname, "slot_name") == 0)
202 : {
203 144 : if (IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
204 0 : errorConflictingDefElem(defel, pstate);
205 :
206 144 : opts->specified_opts |= SUBOPT_SLOT_NAME;
207 144 : opts->slot_name = defGetString(defel);
208 :
209 : /* Setting slot_name = NONE is treated as no slot name. */
210 144 : if (strcmp(opts->slot_name, "none") == 0)
211 110 : opts->slot_name = NULL;
212 : else
213 34 : ReplicationSlotValidateName(opts->slot_name, ERROR);
214 : }
215 394 : else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
216 248 : strcmp(defel->defname, "copy_data") == 0)
217 : {
218 40 : if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
219 0 : errorConflictingDefElem(defel, pstate);
220 :
221 40 : opts->specified_opts |= SUBOPT_COPY_DATA;
222 40 : opts->copy_data = defGetBoolean(defel);
223 : }
224 354 : else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
225 264 : strcmp(defel->defname, "synchronous_commit") == 0)
226 : {
227 12 : if (IsSet(opts->specified_opts, SUBOPT_SYNCHRONOUS_COMMIT))
228 0 : errorConflictingDefElem(defel, pstate);
229 :
230 12 : opts->specified_opts |= SUBOPT_SYNCHRONOUS_COMMIT;
231 12 : opts->synchronous_commit = defGetString(defel);
232 :
233 : /* Test if the given value is valid for synchronous_commit GUC. */
234 12 : (void) set_config_option("synchronous_commit", opts->synchronous_commit,
235 : PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
236 : false, 0, false);
237 : }
238 342 : else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
239 66 : strcmp(defel->defname, "refresh") == 0)
240 : {
241 66 : if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
242 0 : errorConflictingDefElem(defel, pstate);
243 :
244 66 : opts->specified_opts |= SUBOPT_REFRESH;
245 66 : opts->refresh = defGetBoolean(defel);
246 : }
247 276 : else if (IsSet(supported_opts, SUBOPT_BINARY) &&
248 252 : strcmp(defel->defname, "binary") == 0)
249 : {
250 32 : if (IsSet(opts->specified_opts, SUBOPT_BINARY))
251 0 : errorConflictingDefElem(defel, pstate);
252 :
253 32 : opts->specified_opts |= SUBOPT_BINARY;
254 32 : opts->binary = defGetBoolean(defel);
255 : }
256 244 : else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
257 220 : strcmp(defel->defname, "streaming") == 0)
258 : {
259 62 : if (IsSet(opts->specified_opts, SUBOPT_STREAMING))
260 0 : errorConflictingDefElem(defel, pstate);
261 :
262 62 : opts->specified_opts |= SUBOPT_STREAMING;
263 62 : opts->streaming = defGetStreamingMode(defel);
264 : }
265 182 : else if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT) &&
266 158 : strcmp(defel->defname, "two_phase") == 0)
267 : {
268 36 : if (IsSet(opts->specified_opts, SUBOPT_TWOPHASE_COMMIT))
269 0 : errorConflictingDefElem(defel, pstate);
270 :
271 36 : opts->specified_opts |= SUBOPT_TWOPHASE_COMMIT;
272 36 : opts->twophase = defGetBoolean(defel);
273 : }
274 146 : else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
275 122 : strcmp(defel->defname, "disable_on_error") == 0)
276 : {
277 20 : if (IsSet(opts->specified_opts, SUBOPT_DISABLE_ON_ERR))
278 0 : errorConflictingDefElem(defel, pstate);
279 :
280 20 : opts->specified_opts |= SUBOPT_DISABLE_ON_ERR;
281 20 : opts->disableonerr = defGetBoolean(defel);
282 : }
283 126 : else if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED) &&
284 102 : strcmp(defel->defname, "password_required") == 0)
285 : {
286 24 : if (IsSet(opts->specified_opts, SUBOPT_PASSWORD_REQUIRED))
287 0 : errorConflictingDefElem(defel, pstate);
288 :
289 24 : opts->specified_opts |= SUBOPT_PASSWORD_REQUIRED;
290 24 : opts->passwordrequired = defGetBoolean(defel);
291 : }
292 102 : else if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER) &&
293 78 : strcmp(defel->defname, "run_as_owner") == 0)
294 : {
295 18 : if (IsSet(opts->specified_opts, SUBOPT_RUN_AS_OWNER))
296 0 : errorConflictingDefElem(defel, pstate);
297 :
298 18 : opts->specified_opts |= SUBOPT_RUN_AS_OWNER;
299 18 : opts->runasowner = defGetBoolean(defel);
300 : }
301 84 : else if (IsSet(supported_opts, SUBOPT_FAILOVER) &&
302 60 : strcmp(defel->defname, "failover") == 0)
303 : {
304 24 : if (IsSet(opts->specified_opts, SUBOPT_FAILOVER))
305 0 : errorConflictingDefElem(defel, pstate);
306 :
307 24 : opts->specified_opts |= SUBOPT_FAILOVER;
308 24 : opts->failover = defGetBoolean(defel);
309 : }
310 60 : else if (IsSet(supported_opts, SUBOPT_ORIGIN) &&
311 36 : strcmp(defel->defname, "origin") == 0)
312 : {
313 30 : if (IsSet(opts->specified_opts, SUBOPT_ORIGIN))
314 0 : errorConflictingDefElem(defel, pstate);
315 :
316 30 : opts->specified_opts |= SUBOPT_ORIGIN;
317 30 : pfree(opts->origin);
318 :
319 : /*
320 : * Even though the "origin" parameter allows only "none" and "any"
321 : * values, it is implemented as a string type so that the
322 : * parameter can be extended in future versions to support
323 : * filtering using origin names specified by the user.
324 : */
325 30 : opts->origin = defGetString(defel);
326 :
327 44 : if ((pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_NONE) != 0) &&
328 14 : (pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_ANY) != 0))
329 6 : ereport(ERROR,
330 : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
331 : errmsg("unrecognized origin value: \"%s\"", opts->origin));
332 : }
333 30 : else if (IsSet(supported_opts, SUBOPT_LSN) &&
334 24 : strcmp(defel->defname, "lsn") == 0)
335 18 : {
336 24 : char *lsn_str = defGetString(defel);
337 : XLogRecPtr lsn;
338 :
339 24 : if (IsSet(opts->specified_opts, SUBOPT_LSN))
340 0 : errorConflictingDefElem(defel, pstate);
341 :
342 : /* Setting lsn = NONE is treated as resetting LSN */
343 24 : if (strcmp(lsn_str, "none") == 0)
344 6 : lsn = InvalidXLogRecPtr;
345 : else
346 : {
347 : /* Parse the argument as LSN */
348 18 : lsn = DatumGetLSN(DirectFunctionCall1(pg_lsn_in,
349 : CStringGetDatum(lsn_str)));
350 :
351 18 : if (XLogRecPtrIsInvalid(lsn))
352 6 : ereport(ERROR,
353 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
354 : errmsg("invalid WAL location (LSN): %s", lsn_str)));
355 : }
356 :
357 18 : opts->specified_opts |= SUBOPT_LSN;
358 18 : opts->lsn = lsn;
359 : }
360 : else
361 6 : ereport(ERROR,
362 : (errcode(ERRCODE_SYNTAX_ERROR),
363 : errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
364 : }
365 :
366 : /*
367 : * We've been explicitly asked to not connect, that requires some
368 : * additional processing.
369 : */
370 782 : if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
371 : {
372 : /* Check for incompatible options from the user. */
373 134 : if (opts->enabled &&
374 134 : IsSet(opts->specified_opts, SUBOPT_ENABLED))
375 6 : ereport(ERROR,
376 : (errcode(ERRCODE_SYNTAX_ERROR),
377 : /*- translator: both %s are strings of the form "option = value" */
378 : errmsg("%s and %s are mutually exclusive options",
379 : "connect = false", "enabled = true")));
380 :
381 128 : if (opts->create_slot &&
382 122 : IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
383 6 : ereport(ERROR,
384 : (errcode(ERRCODE_SYNTAX_ERROR),
385 : errmsg("%s and %s are mutually exclusive options",
386 : "connect = false", "create_slot = true")));
387 :
388 122 : if (opts->copy_data &&
389 116 : IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
390 6 : ereport(ERROR,
391 : (errcode(ERRCODE_SYNTAX_ERROR),
392 : errmsg("%s and %s are mutually exclusive options",
393 : "connect = false", "copy_data = true")));
394 :
395 : /* Change the defaults of other options. */
396 116 : opts->enabled = false;
397 116 : opts->create_slot = false;
398 116 : opts->copy_data = false;
399 : }
400 :
401 : /*
402 : * Do additional checking for disallowed combination when slot_name = NONE
403 : * was used.
404 : */
405 764 : if (!opts->slot_name &&
406 736 : IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
407 : {
408 104 : if (opts->enabled)
409 : {
410 18 : if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
411 6 : ereport(ERROR,
412 : (errcode(ERRCODE_SYNTAX_ERROR),
413 : /*- translator: both %s are strings of the form "option = value" */
414 : errmsg("%s and %s are mutually exclusive options",
415 : "slot_name = NONE", "enabled = true")));
416 : else
417 12 : ereport(ERROR,
418 : (errcode(ERRCODE_SYNTAX_ERROR),
419 : /*- translator: both %s are strings of the form "option = value" */
420 : errmsg("subscription with %s must also set %s",
421 : "slot_name = NONE", "enabled = false")));
422 : }
423 :
424 86 : if (opts->create_slot)
425 : {
426 12 : if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
427 6 : ereport(ERROR,
428 : (errcode(ERRCODE_SYNTAX_ERROR),
429 : /*- translator: both %s are strings of the form "option = value" */
430 : errmsg("%s and %s are mutually exclusive options",
431 : "slot_name = NONE", "create_slot = true")));
432 : else
433 6 : ereport(ERROR,
434 : (errcode(ERRCODE_SYNTAX_ERROR),
435 : /*- translator: both %s are strings of the form "option = value" */
436 : errmsg("subscription with %s must also set %s",
437 : "slot_name = NONE", "create_slot = false")));
438 : }
439 : }
440 734 : }
441 :
442 : /*
443 : * Add publication names from the list to a string.
444 : */
445 : static void
446 492 : get_publications_str(List *publications, StringInfo dest, bool quote_literal)
447 : {
448 : ListCell *lc;
449 492 : bool first = true;
450 :
451 : Assert(publications != NIL);
452 :
453 1140 : foreach(lc, publications)
454 : {
455 648 : char *pubname = strVal(lfirst(lc));
456 :
457 648 : if (first)
458 492 : first = false;
459 : else
460 156 : appendStringInfoString(dest, ", ");
461 :
462 648 : if (quote_literal)
463 636 : appendStringInfoString(dest, quote_literal_cstr(pubname));
464 : else
465 : {
466 12 : appendStringInfoChar(dest, '"');
467 12 : appendStringInfoString(dest, pubname);
468 12 : appendStringInfoChar(dest, '"');
469 : }
470 : }
471 492 : }
472 :
473 : /*
474 : * Check that the specified publications are present on the publisher.
475 : */
476 : static void
477 214 : check_publications(WalReceiverConn *wrconn, List *publications)
478 : {
479 : WalRcvExecResult *res;
480 : StringInfo cmd;
481 : TupleTableSlot *slot;
482 214 : List *publicationsCopy = NIL;
483 214 : Oid tableRow[1] = {TEXTOID};
484 :
485 214 : cmd = makeStringInfo();
486 214 : appendStringInfoString(cmd, "SELECT t.pubname FROM\n"
487 : " pg_catalog.pg_publication t WHERE\n"
488 : " t.pubname IN (");
489 214 : get_publications_str(publications, cmd, true);
490 214 : appendStringInfoChar(cmd, ')');
491 :
492 214 : res = walrcv_exec(wrconn, cmd->data, 1, tableRow);
493 214 : destroyStringInfo(cmd);
494 :
495 214 : if (res->status != WALRCV_OK_TUPLES)
496 0 : ereport(ERROR,
497 : errmsg("could not receive list of publications from the publisher: %s",
498 : res->err));
499 :
500 214 : publicationsCopy = list_copy(publications);
501 :
502 : /* Process publication(s). */
503 214 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
504 480 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
505 : {
506 : char *pubname;
507 : bool isnull;
508 :
509 266 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
510 : Assert(!isnull);
511 :
512 : /* Delete the publication present in publisher from the list. */
513 266 : publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
514 266 : ExecClearTuple(slot);
515 : }
516 :
517 214 : ExecDropSingleTupleTableSlot(slot);
518 :
519 214 : walrcv_clear_result(res);
520 :
521 214 : if (list_length(publicationsCopy))
522 : {
523 : /* Prepare the list of non-existent publication(s) for error message. */
524 6 : StringInfo pubnames = makeStringInfo();
525 :
526 6 : get_publications_str(publicationsCopy, pubnames, false);
527 6 : ereport(WARNING,
528 : errcode(ERRCODE_UNDEFINED_OBJECT),
529 : errmsg_plural("publication %s does not exist on the publisher",
530 : "publications %s do not exist on the publisher",
531 : list_length(publicationsCopy),
532 : pubnames->data));
533 : }
534 214 : }
535 :
536 : /*
537 : * Auxiliary function to build a text array out of a list of String nodes.
538 : */
539 : static Datum
540 338 : publicationListToArray(List *publist)
541 : {
542 : ArrayType *arr;
543 : Datum *datums;
544 : MemoryContext memcxt;
545 : MemoryContext oldcxt;
546 :
547 : /* Create memory context for temporary allocations. */
548 338 : memcxt = AllocSetContextCreate(CurrentMemoryContext,
549 : "publicationListToArray to array",
550 : ALLOCSET_DEFAULT_SIZES);
551 338 : oldcxt = MemoryContextSwitchTo(memcxt);
552 :
553 338 : datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
554 :
555 338 : check_duplicates_in_publist(publist, datums);
556 :
557 332 : MemoryContextSwitchTo(oldcxt);
558 :
559 332 : arr = construct_array_builtin(datums, list_length(publist), TEXTOID);
560 :
561 332 : MemoryContextDelete(memcxt);
562 :
563 332 : return PointerGetDatum(arr);
564 : }
565 :
566 : /*
567 : * Create new subscription.
568 : */
569 : ObjectAddress
570 418 : CreateSubscription(ParseState *pstate, CreateSubscriptionStmt *stmt,
571 : bool isTopLevel)
572 : {
573 : Relation rel;
574 : ObjectAddress myself;
575 : Oid subid;
576 : bool nulls[Natts_pg_subscription];
577 : Datum values[Natts_pg_subscription];
578 418 : Oid owner = GetUserId();
579 : HeapTuple tup;
580 : char *conninfo;
581 : char originname[NAMEDATALEN];
582 : List *publications;
583 : bits32 supported_opts;
584 418 : SubOpts opts = {0};
585 : AclResult aclresult;
586 :
587 : /*
588 : * Parse and check options.
589 : *
590 : * Connection and publication should not be specified here.
591 : */
592 418 : supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
593 : SUBOPT_SLOT_NAME | SUBOPT_COPY_DATA |
594 : SUBOPT_SYNCHRONOUS_COMMIT | SUBOPT_BINARY |
595 : SUBOPT_STREAMING | SUBOPT_TWOPHASE_COMMIT |
596 : SUBOPT_DISABLE_ON_ERR | SUBOPT_PASSWORD_REQUIRED |
597 : SUBOPT_RUN_AS_OWNER | SUBOPT_FAILOVER | SUBOPT_ORIGIN);
598 418 : parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
599 :
600 : /*
601 : * Since creating a replication slot is not transactional, rolling back
602 : * the transaction leaves the created replication slot. So we cannot run
603 : * CREATE SUBSCRIPTION inside a transaction block if creating a
604 : * replication slot.
605 : */
606 340 : if (opts.create_slot)
607 214 : PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
608 :
609 : /*
610 : * We don't want to allow unprivileged users to be able to trigger
611 : * attempts to access arbitrary network destinations, so require the user
612 : * to have been specifically authorized to create subscriptions.
613 : */
614 334 : if (!has_privs_of_role(owner, ROLE_PG_CREATE_SUBSCRIPTION))
615 6 : ereport(ERROR,
616 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
617 : errmsg("permission denied to create subscription"),
618 : errdetail("Only roles with privileges of the \"%s\" role may create subscriptions.",
619 : "pg_create_subscription")));
620 :
621 : /*
622 : * Since a subscription is a database object, we also check for CREATE
623 : * permission on the database.
624 : */
625 328 : aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
626 : owner, ACL_CREATE);
627 328 : if (aclresult != ACLCHECK_OK)
628 12 : aclcheck_error(aclresult, OBJECT_DATABASE,
629 6 : get_database_name(MyDatabaseId));
630 :
631 : /*
632 : * Non-superusers are required to set a password for authentication, and
633 : * that password must be used by the target server, but the superuser can
634 : * exempt a subscription from this requirement.
635 : */
636 322 : if (!opts.passwordrequired && !superuser_arg(owner))
637 6 : ereport(ERROR,
638 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
639 : errmsg("password_required=false is superuser-only"),
640 : errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
641 :
642 : /*
643 : * If built with appropriate switch, whine when regression-testing
644 : * conventions for subscription names are violated.
645 : */
646 : #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
647 : if (strncmp(stmt->subname, "regress_", 8) != 0)
648 : elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
649 : #endif
650 :
651 316 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
652 :
653 : /* Check if name is used */
654 316 : subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
655 : MyDatabaseId, CStringGetDatum(stmt->subname));
656 316 : if (OidIsValid(subid))
657 : {
658 6 : ereport(ERROR,
659 : (errcode(ERRCODE_DUPLICATE_OBJECT),
660 : errmsg("subscription \"%s\" already exists",
661 : stmt->subname)));
662 : }
663 :
664 310 : if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
665 268 : opts.slot_name == NULL)
666 268 : opts.slot_name = stmt->subname;
667 :
668 : /* The default for synchronous_commit of subscriptions is off. */
669 310 : if (opts.synchronous_commit == NULL)
670 310 : opts.synchronous_commit = "off";
671 :
672 310 : conninfo = stmt->conninfo;
673 310 : publications = stmt->publication;
674 :
675 : /* Load the library providing us libpq calls. */
676 310 : load_file("libpqwalreceiver", false);
677 :
678 : /* Check the connection info string. */
679 310 : walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
680 :
681 : /* Everything ok, form a new tuple. */
682 292 : memset(values, 0, sizeof(values));
683 292 : memset(nulls, false, sizeof(nulls));
684 :
685 292 : subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
686 : Anum_pg_subscription_oid);
687 292 : values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
688 292 : values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
689 292 : values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
690 292 : values[Anum_pg_subscription_subname - 1] =
691 292 : DirectFunctionCall1(namein, CStringGetDatum(stmt->subname));
692 292 : values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
693 292 : values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
694 292 : values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
695 292 : values[Anum_pg_subscription_substream - 1] = CharGetDatum(opts.streaming);
696 292 : values[Anum_pg_subscription_subtwophasestate - 1] =
697 292 : CharGetDatum(opts.twophase ?
698 : LOGICALREP_TWOPHASE_STATE_PENDING :
699 : LOGICALREP_TWOPHASE_STATE_DISABLED);
700 292 : values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
701 292 : values[Anum_pg_subscription_subpasswordrequired - 1] = BoolGetDatum(opts.passwordrequired);
702 292 : values[Anum_pg_subscription_subrunasowner - 1] = BoolGetDatum(opts.runasowner);
703 292 : values[Anum_pg_subscription_subfailover - 1] = BoolGetDatum(opts.failover);
704 292 : values[Anum_pg_subscription_subconninfo - 1] =
705 292 : CStringGetTextDatum(conninfo);
706 292 : if (opts.slot_name)
707 272 : values[Anum_pg_subscription_subslotname - 1] =
708 272 : DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
709 : else
710 20 : nulls[Anum_pg_subscription_subslotname - 1] = true;
711 292 : values[Anum_pg_subscription_subsynccommit - 1] =
712 292 : CStringGetTextDatum(opts.synchronous_commit);
713 286 : values[Anum_pg_subscription_subpublications - 1] =
714 292 : publicationListToArray(publications);
715 286 : values[Anum_pg_subscription_suborigin - 1] =
716 286 : CStringGetTextDatum(opts.origin);
717 :
718 286 : tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
719 :
720 : /* Insert tuple into catalog. */
721 286 : CatalogTupleInsert(rel, tup);
722 286 : heap_freetuple(tup);
723 :
724 286 : recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
725 :
726 286 : ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
727 286 : replorigin_create(originname);
728 :
729 : /*
730 : * Connect to remote side to execute requested commands and fetch table
731 : * info.
732 : */
733 286 : if (opts.connect)
734 : {
735 : char *err;
736 : WalReceiverConn *wrconn;
737 : List *tables;
738 : ListCell *lc;
739 : char table_state;
740 : bool must_use_password;
741 :
742 : /* Try to connect to the publisher. */
743 206 : must_use_password = !superuser_arg(owner) && opts.passwordrequired;
744 206 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
745 : stmt->subname, &err);
746 206 : if (!wrconn)
747 6 : ereport(ERROR,
748 : (errcode(ERRCODE_CONNECTION_FAILURE),
749 : errmsg("subscription \"%s\" could not connect to the publisher: %s",
750 : stmt->subname, err)));
751 :
752 200 : PG_TRY();
753 : {
754 200 : check_publications(wrconn, publications);
755 200 : check_publications_origin(wrconn, publications, opts.copy_data,
756 : opts.origin, NULL, 0, stmt->subname);
757 :
758 : /*
759 : * Set sync state based on if we were asked to do data copy or
760 : * not.
761 : */
762 200 : table_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
763 :
764 : /*
765 : * Get the table list from publisher and build local table status
766 : * info.
767 : */
768 200 : tables = fetch_table_list(wrconn, publications);
769 506 : foreach(lc, tables)
770 : {
771 308 : RangeVar *rv = (RangeVar *) lfirst(lc);
772 : Oid relid;
773 :
774 308 : relid = RangeVarGetRelid(rv, AccessShareLock, false);
775 :
776 : /* Check for supported relkind. */
777 308 : CheckSubscriptionRelkind(get_rel_relkind(relid),
778 308 : rv->schemaname, rv->relname);
779 :
780 308 : AddSubscriptionRelState(subid, relid, table_state,
781 : InvalidXLogRecPtr, true);
782 : }
783 :
784 : /*
785 : * If requested, create permanent slot for the subscription. We
786 : * won't use the initial snapshot for anything, so no need to
787 : * export it.
788 : */
789 198 : if (opts.create_slot)
790 : {
791 188 : bool twophase_enabled = false;
792 :
793 : Assert(opts.slot_name);
794 :
795 : /*
796 : * Even if two_phase is set, don't create the slot with
797 : * two-phase enabled. Will enable it once all the tables are
798 : * synced and ready. This avoids race-conditions like prepared
799 : * transactions being skipped due to changes not being applied
800 : * due to checks in should_apply_changes_for_rel() when
801 : * tablesync for the corresponding tables are in progress. See
802 : * comments atop worker.c.
803 : *
804 : * Note that if tables were specified but copy_data is false
805 : * then it is safe to enable two_phase up-front because those
806 : * tables are already initially in READY state. When the
807 : * subscription has no tables, we leave the twophase state as
808 : * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
809 : * PUBLICATION to work.
810 : */
811 188 : if (opts.twophase && !opts.copy_data && tables != NIL)
812 2 : twophase_enabled = true;
813 :
814 188 : walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
815 : opts.failover, CRS_NOEXPORT_SNAPSHOT, NULL);
816 :
817 188 : if (twophase_enabled)
818 2 : UpdateTwoPhaseState(subid, LOGICALREP_TWOPHASE_STATE_ENABLED);
819 :
820 188 : ereport(NOTICE,
821 : (errmsg("created replication slot \"%s\" on publisher",
822 : opts.slot_name)));
823 : }
824 : }
825 2 : PG_FINALLY();
826 : {
827 200 : walrcv_disconnect(wrconn);
828 : }
829 200 : PG_END_TRY();
830 : }
831 : else
832 80 : ereport(WARNING,
833 : (errmsg("subscription was created, but is not connected"),
834 : errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and refresh the subscription.")));
835 :
836 278 : table_close(rel, RowExclusiveLock);
837 :
838 278 : pgstat_create_subscription(subid);
839 :
840 278 : if (opts.enabled)
841 186 : ApplyLauncherWakeupAtCommit();
842 :
843 278 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
844 :
845 278 : InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
846 :
847 278 : return myself;
848 : }
849 :
850 : static void
851 58 : AlterSubscription_refresh(Subscription *sub, bool copy_data,
852 : List *validate_publications)
853 : {
854 : char *err;
855 : List *pubrel_names;
856 : List *subrel_states;
857 : Oid *subrel_local_oids;
858 : Oid *pubrel_local_oids;
859 : ListCell *lc;
860 : int off;
861 : int remove_rel_len;
862 : int subrel_count;
863 58 : Relation rel = NULL;
864 : typedef struct SubRemoveRels
865 : {
866 : Oid relid;
867 : char state;
868 : } SubRemoveRels;
869 : SubRemoveRels *sub_remove_rels;
870 : WalReceiverConn *wrconn;
871 : bool must_use_password;
872 :
873 : /* Load the library providing us libpq calls. */
874 58 : load_file("libpqwalreceiver", false);
875 :
876 : /* Try to connect to the publisher. */
877 58 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
878 58 : wrconn = walrcv_connect(sub->conninfo, true, true, must_use_password,
879 : sub->name, &err);
880 56 : if (!wrconn)
881 0 : ereport(ERROR,
882 : (errcode(ERRCODE_CONNECTION_FAILURE),
883 : errmsg("subscription \"%s\" could not connect to the publisher: %s",
884 : sub->name, err)));
885 :
886 56 : PG_TRY();
887 : {
888 56 : if (validate_publications)
889 14 : check_publications(wrconn, validate_publications);
890 :
891 : /* Get the table list from publisher. */
892 56 : pubrel_names = fetch_table_list(wrconn, sub->publications);
893 :
894 : /* Get local table list. */
895 56 : subrel_states = GetSubscriptionRelations(sub->oid, false);
896 56 : subrel_count = list_length(subrel_states);
897 :
898 : /*
899 : * Build qsorted array of local table oids for faster lookup. This can
900 : * potentially contain all tables in the database so speed of lookup
901 : * is important.
902 : */
903 56 : subrel_local_oids = palloc(subrel_count * sizeof(Oid));
904 56 : off = 0;
905 218 : foreach(lc, subrel_states)
906 : {
907 162 : SubscriptionRelState *relstate = (SubscriptionRelState *) lfirst(lc);
908 :
909 162 : subrel_local_oids[off++] = relstate->relid;
910 : }
911 56 : qsort(subrel_local_oids, subrel_count,
912 : sizeof(Oid), oid_cmp);
913 :
914 56 : check_publications_origin(wrconn, sub->publications, copy_data,
915 : sub->origin, subrel_local_oids,
916 : subrel_count, sub->name);
917 :
918 : /*
919 : * Rels that we want to remove from subscription and drop any slots
920 : * and origins corresponding to them.
921 : */
922 56 : sub_remove_rels = palloc(subrel_count * sizeof(SubRemoveRels));
923 :
924 : /*
925 : * Walk over the remote tables and try to match them to locally known
926 : * tables. If the table is not known locally create a new state for
927 : * it.
928 : *
929 : * Also builds array of local oids of remote tables for the next step.
930 : */
931 56 : off = 0;
932 56 : pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
933 :
934 220 : foreach(lc, pubrel_names)
935 : {
936 164 : RangeVar *rv = (RangeVar *) lfirst(lc);
937 : Oid relid;
938 :
939 164 : relid = RangeVarGetRelid(rv, AccessShareLock, false);
940 :
941 : /* Check for supported relkind. */
942 164 : CheckSubscriptionRelkind(get_rel_relkind(relid),
943 164 : rv->schemaname, rv->relname);
944 :
945 164 : pubrel_local_oids[off++] = relid;
946 :
947 164 : if (!bsearch(&relid, subrel_local_oids,
948 : subrel_count, sizeof(Oid), oid_cmp))
949 : {
950 38 : AddSubscriptionRelState(sub->oid, relid,
951 : copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
952 : InvalidXLogRecPtr, true);
953 38 : ereport(DEBUG1,
954 : (errmsg_internal("table \"%s.%s\" added to subscription \"%s\"",
955 : rv->schemaname, rv->relname, sub->name)));
956 : }
957 : }
958 :
959 : /*
960 : * Next remove state for tables we should not care about anymore using
961 : * the data we collected above
962 : */
963 56 : qsort(pubrel_local_oids, list_length(pubrel_names),
964 : sizeof(Oid), oid_cmp);
965 :
966 56 : remove_rel_len = 0;
967 218 : for (off = 0; off < subrel_count; off++)
968 : {
969 162 : Oid relid = subrel_local_oids[off];
970 :
971 162 : if (!bsearch(&relid, pubrel_local_oids,
972 162 : list_length(pubrel_names), sizeof(Oid), oid_cmp))
973 : {
974 : char state;
975 : XLogRecPtr statelsn;
976 :
977 : /*
978 : * Lock pg_subscription_rel with AccessExclusiveLock to
979 : * prevent any race conditions with the apply worker
980 : * re-launching workers at the same time this code is trying
981 : * to remove those tables.
982 : *
983 : * Even if new worker for this particular rel is restarted it
984 : * won't be able to make any progress as we hold exclusive
985 : * lock on pg_subscription_rel till the transaction end. It
986 : * will simply exit as there is no corresponding rel entry.
987 : *
988 : * This locking also ensures that the state of rels won't
989 : * change till we are done with this refresh operation.
990 : */
991 36 : if (!rel)
992 14 : rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
993 :
994 : /* Last known rel state. */
995 36 : state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
996 :
997 36 : sub_remove_rels[remove_rel_len].relid = relid;
998 36 : sub_remove_rels[remove_rel_len++].state = state;
999 :
1000 36 : RemoveSubscriptionRel(sub->oid, relid);
1001 :
1002 36 : logicalrep_worker_stop(sub->oid, relid);
1003 :
1004 : /*
1005 : * For READY state, we would have already dropped the
1006 : * tablesync origin.
1007 : */
1008 36 : if (state != SUBREL_STATE_READY)
1009 : {
1010 : char originname[NAMEDATALEN];
1011 :
1012 : /*
1013 : * Drop the tablesync's origin tracking if exists.
1014 : *
1015 : * It is possible that the origin is not yet created for
1016 : * tablesync worker, this can happen for the states before
1017 : * SUBREL_STATE_FINISHEDCOPY. The tablesync worker or
1018 : * apply worker can also concurrently try to drop the
1019 : * origin and by this time the origin might be already
1020 : * removed. For these reasons, passing missing_ok = true.
1021 : */
1022 0 : ReplicationOriginNameForLogicalRep(sub->oid, relid, originname,
1023 : sizeof(originname));
1024 0 : replorigin_drop_by_name(originname, true, false);
1025 : }
1026 :
1027 36 : ereport(DEBUG1,
1028 : (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
1029 : get_namespace_name(get_rel_namespace(relid)),
1030 : get_rel_name(relid),
1031 : sub->name)));
1032 : }
1033 : }
1034 :
1035 : /*
1036 : * Drop the tablesync slots associated with removed tables. This has
1037 : * to be at the end because otherwise if there is an error while doing
1038 : * the database operations we won't be able to rollback dropped slots.
1039 : */
1040 92 : for (off = 0; off < remove_rel_len; off++)
1041 : {
1042 36 : if (sub_remove_rels[off].state != SUBREL_STATE_READY &&
1043 0 : sub_remove_rels[off].state != SUBREL_STATE_SYNCDONE)
1044 : {
1045 0 : char syncslotname[NAMEDATALEN] = {0};
1046 :
1047 : /*
1048 : * For READY/SYNCDONE states we know the tablesync slot has
1049 : * already been dropped by the tablesync worker.
1050 : *
1051 : * For other states, there is no certainty, maybe the slot
1052 : * does not exist yet. Also, if we fail after removing some of
1053 : * the slots, next time, it will again try to drop already
1054 : * dropped slots and fail. For these reasons, we allow
1055 : * missing_ok = true for the drop.
1056 : */
1057 0 : ReplicationSlotNameForTablesync(sub->oid, sub_remove_rels[off].relid,
1058 : syncslotname, sizeof(syncslotname));
1059 0 : ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1060 : }
1061 : }
1062 : }
1063 0 : PG_FINALLY();
1064 : {
1065 56 : walrcv_disconnect(wrconn);
1066 : }
1067 56 : PG_END_TRY();
1068 :
1069 56 : if (rel)
1070 14 : table_close(rel, NoLock);
1071 56 : }
1072 :
1073 : /*
1074 : * Common checks for altering failover and two_phase options.
1075 : */
1076 : static void
1077 18 : CheckAlterSubOption(Subscription *sub, const char *option,
1078 : bool slot_needs_update, bool isTopLevel)
1079 : {
1080 : /*
1081 : * The checks in this function are required only for failover and
1082 : * two_phase options.
1083 : */
1084 : Assert(strcmp(option, "failover") == 0 ||
1085 : strcmp(option, "two_phase") == 0);
1086 :
1087 : /*
1088 : * Do not allow changing the option if the subscription is enabled. This
1089 : * is because both failover and two_phase options of the slot on the
1090 : * publisher cannot be modified if the slot is currently acquired by the
1091 : * existing walsender.
1092 : *
1093 : * Note that two_phase is enabled (aka changed from 'false' to 'true') on
1094 : * the publisher by the existing walsender, so we could have allowed that
1095 : * even when the subscription is enabled. But we kept this restriction for
1096 : * the sake of consistency and simplicity.
1097 : */
1098 18 : if (sub->enabled)
1099 2 : ereport(ERROR,
1100 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1101 : errmsg("cannot set option \"%s\" for enabled subscription",
1102 : option)));
1103 :
1104 16 : if (slot_needs_update)
1105 : {
1106 : StringInfoData cmd;
1107 :
1108 : /*
1109 : * A valid slot must be associated with the subscription for us to
1110 : * modify any of the slot's properties.
1111 : */
1112 14 : if (!sub->slotname)
1113 0 : ereport(ERROR,
1114 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1115 : errmsg("cannot set option \"%s\" for a subscription that does not have a slot name",
1116 : option)));
1117 :
1118 : /* The changed option of the slot can't be rolled back. */
1119 14 : initStringInfo(&cmd);
1120 14 : appendStringInfo(&cmd, "ALTER SUBSCRIPTION ... SET (%s)", option);
1121 :
1122 14 : PreventInTransactionBlock(isTopLevel, cmd.data);
1123 8 : pfree(cmd.data);
1124 : }
1125 10 : }
1126 :
1127 : /*
1128 : * Alter the existing subscription.
1129 : */
1130 : ObjectAddress
1131 450 : AlterSubscription(ParseState *pstate, AlterSubscriptionStmt *stmt,
1132 : bool isTopLevel)
1133 : {
1134 : Relation rel;
1135 : ObjectAddress myself;
1136 : bool nulls[Natts_pg_subscription];
1137 : bool replaces[Natts_pg_subscription];
1138 : Datum values[Natts_pg_subscription];
1139 : HeapTuple tup;
1140 : Oid subid;
1141 450 : bool update_tuple = false;
1142 450 : bool update_failover = false;
1143 450 : bool update_two_phase = false;
1144 : Subscription *sub;
1145 : Form_pg_subscription form;
1146 : bits32 supported_opts;
1147 450 : SubOpts opts = {0};
1148 :
1149 450 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1150 :
1151 : /* Fetch the existing tuple. */
1152 450 : tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, MyDatabaseId,
1153 : CStringGetDatum(stmt->subname));
1154 :
1155 450 : if (!HeapTupleIsValid(tup))
1156 6 : ereport(ERROR,
1157 : (errcode(ERRCODE_UNDEFINED_OBJECT),
1158 : errmsg("subscription \"%s\" does not exist",
1159 : stmt->subname)));
1160 :
1161 444 : form = (Form_pg_subscription) GETSTRUCT(tup);
1162 444 : subid = form->oid;
1163 :
1164 : /* must be owner */
1165 444 : if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1166 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
1167 0 : stmt->subname);
1168 :
1169 444 : sub = GetSubscription(subid, false);
1170 :
1171 : /*
1172 : * Don't allow non-superuser modification of a subscription with
1173 : * password_required=false.
1174 : */
1175 444 : if (!sub->passwordrequired && !superuser())
1176 0 : ereport(ERROR,
1177 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1178 : errmsg("password_required=false is superuser-only"),
1179 : errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1180 :
1181 : /* Lock the subscription so nobody else can do anything with it. */
1182 444 : LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1183 :
1184 : /* Form a new tuple. */
1185 444 : memset(values, 0, sizeof(values));
1186 444 : memset(nulls, false, sizeof(nulls));
1187 444 : memset(replaces, false, sizeof(replaces));
1188 :
1189 444 : switch (stmt->kind)
1190 : {
1191 184 : case ALTER_SUBSCRIPTION_OPTIONS:
1192 : {
1193 184 : supported_opts = (SUBOPT_SLOT_NAME |
1194 : SUBOPT_SYNCHRONOUS_COMMIT | SUBOPT_BINARY |
1195 : SUBOPT_STREAMING | SUBOPT_TWOPHASE_COMMIT |
1196 : SUBOPT_DISABLE_ON_ERR |
1197 : SUBOPT_PASSWORD_REQUIRED |
1198 : SUBOPT_RUN_AS_OWNER | SUBOPT_FAILOVER |
1199 : SUBOPT_ORIGIN);
1200 :
1201 184 : parse_subscription_options(pstate, stmt->options,
1202 : supported_opts, &opts);
1203 :
1204 166 : if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1205 : {
1206 : /*
1207 : * The subscription must be disabled to allow slot_name as
1208 : * 'none', otherwise, the apply worker will repeatedly try
1209 : * to stream the data using that slot_name which neither
1210 : * exists on the publisher nor the user will be allowed to
1211 : * create it.
1212 : */
1213 60 : if (sub->enabled && !opts.slot_name)
1214 0 : ereport(ERROR,
1215 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1216 : errmsg("cannot set %s for enabled subscription",
1217 : "slot_name = NONE")));
1218 :
1219 60 : if (opts.slot_name)
1220 6 : values[Anum_pg_subscription_subslotname - 1] =
1221 6 : DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
1222 : else
1223 54 : nulls[Anum_pg_subscription_subslotname - 1] = true;
1224 60 : replaces[Anum_pg_subscription_subslotname - 1] = true;
1225 : }
1226 :
1227 166 : if (opts.synchronous_commit)
1228 : {
1229 6 : values[Anum_pg_subscription_subsynccommit - 1] =
1230 6 : CStringGetTextDatum(opts.synchronous_commit);
1231 6 : replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1232 : }
1233 :
1234 166 : if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1235 : {
1236 18 : values[Anum_pg_subscription_subbinary - 1] =
1237 18 : BoolGetDatum(opts.binary);
1238 18 : replaces[Anum_pg_subscription_subbinary - 1] = true;
1239 : }
1240 :
1241 166 : if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1242 : {
1243 30 : values[Anum_pg_subscription_substream - 1] =
1244 30 : CharGetDatum(opts.streaming);
1245 30 : replaces[Anum_pg_subscription_substream - 1] = true;
1246 : }
1247 :
1248 166 : if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1249 : {
1250 : values[Anum_pg_subscription_subdisableonerr - 1]
1251 6 : = BoolGetDatum(opts.disableonerr);
1252 : replaces[Anum_pg_subscription_subdisableonerr - 1]
1253 6 : = true;
1254 : }
1255 :
1256 166 : if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1257 : {
1258 : /* Non-superuser may not disable password_required. */
1259 12 : if (!opts.passwordrequired && !superuser())
1260 0 : ereport(ERROR,
1261 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1262 : errmsg("password_required=false is superuser-only"),
1263 : errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1264 :
1265 : values[Anum_pg_subscription_subpasswordrequired - 1]
1266 12 : = BoolGetDatum(opts.passwordrequired);
1267 : replaces[Anum_pg_subscription_subpasswordrequired - 1]
1268 12 : = true;
1269 : }
1270 :
1271 166 : if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
1272 : {
1273 14 : values[Anum_pg_subscription_subrunasowner - 1] =
1274 14 : BoolGetDatum(opts.runasowner);
1275 14 : replaces[Anum_pg_subscription_subrunasowner - 1] = true;
1276 : }
1277 :
1278 166 : if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT))
1279 : {
1280 : /*
1281 : * We need to update both the slot and the subscription
1282 : * for the two_phase option. We can enable the two_phase
1283 : * option for a slot only once the initial data
1284 : * synchronization is done. This is to avoid missing some
1285 : * data as explained in comments atop worker.c.
1286 : */
1287 4 : update_two_phase = !opts.twophase;
1288 :
1289 4 : CheckAlterSubOption(sub, "two_phase", update_two_phase,
1290 : isTopLevel);
1291 :
1292 : /*
1293 : * Modifying the two_phase slot option requires a slot
1294 : * lookup by slot name, so changing the slot name at the
1295 : * same time is not allowed.
1296 : */
1297 4 : if (update_two_phase &&
1298 2 : IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1299 0 : ereport(ERROR,
1300 : (errcode(ERRCODE_SYNTAX_ERROR),
1301 : errmsg("slot_name and two_phase cannot be altered at the same time")));
1302 :
1303 : /*
1304 : * Note that workers may still survive even if the
1305 : * subscription has been disabled.
1306 : *
1307 : * Ensure workers have already been exited to avoid
1308 : * getting prepared transactions while we are disabling
1309 : * the two_phase option. Otherwise, the changes of an
1310 : * already prepared transaction can be replicated again
1311 : * along with its corresponding commit, leading to
1312 : * duplicate data or errors.
1313 : */
1314 4 : if (logicalrep_workers_find(subid, true, true))
1315 0 : ereport(ERROR,
1316 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1317 : errmsg("cannot alter two_phase when logical replication worker is still running"),
1318 : errhint("Try again after some time.")));
1319 :
1320 : /*
1321 : * two_phase cannot be disabled if there are any
1322 : * uncommitted prepared transactions present otherwise it
1323 : * can lead to duplicate data or errors as explained in
1324 : * the comment above.
1325 : */
1326 4 : if (update_two_phase &&
1327 2 : sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED &&
1328 2 : LookupGXactBySubid(subid))
1329 0 : ereport(ERROR,
1330 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1331 : errmsg("cannot disable two_phase when prepared transactions are present"),
1332 : errhint("Resolve these transactions and try again.")));
1333 :
1334 : /* Change system catalog accordingly */
1335 4 : values[Anum_pg_subscription_subtwophasestate - 1] =
1336 4 : CharGetDatum(opts.twophase ?
1337 : LOGICALREP_TWOPHASE_STATE_PENDING :
1338 : LOGICALREP_TWOPHASE_STATE_DISABLED);
1339 4 : replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
1340 : }
1341 :
1342 166 : if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
1343 : {
1344 : /*
1345 : * Similar to the two_phase case above, we need to update
1346 : * the failover option for both the slot and the
1347 : * subscription.
1348 : */
1349 14 : update_failover = true;
1350 :
1351 14 : CheckAlterSubOption(sub, "failover", update_failover,
1352 : isTopLevel);
1353 :
1354 6 : values[Anum_pg_subscription_subfailover - 1] =
1355 6 : BoolGetDatum(opts.failover);
1356 6 : replaces[Anum_pg_subscription_subfailover - 1] = true;
1357 : }
1358 :
1359 158 : if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1360 : {
1361 6 : values[Anum_pg_subscription_suborigin - 1] =
1362 6 : CStringGetTextDatum(opts.origin);
1363 6 : replaces[Anum_pg_subscription_suborigin - 1] = true;
1364 : }
1365 :
1366 158 : update_tuple = true;
1367 158 : break;
1368 : }
1369 :
1370 80 : case ALTER_SUBSCRIPTION_ENABLED:
1371 : {
1372 80 : parse_subscription_options(pstate, stmt->options,
1373 : SUBOPT_ENABLED, &opts);
1374 : Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
1375 :
1376 80 : if (!sub->slotname && opts.enabled)
1377 6 : ereport(ERROR,
1378 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1379 : errmsg("cannot enable subscription that does not have a slot name")));
1380 :
1381 74 : values[Anum_pg_subscription_subenabled - 1] =
1382 74 : BoolGetDatum(opts.enabled);
1383 74 : replaces[Anum_pg_subscription_subenabled - 1] = true;
1384 :
1385 74 : if (opts.enabled)
1386 42 : ApplyLauncherWakeupAtCommit();
1387 :
1388 74 : update_tuple = true;
1389 74 : break;
1390 : }
1391 :
1392 20 : case ALTER_SUBSCRIPTION_CONNECTION:
1393 : /* Load the library providing us libpq calls. */
1394 20 : load_file("libpqwalreceiver", false);
1395 : /* Check the connection info string. */
1396 20 : walrcv_check_conninfo(stmt->conninfo,
1397 : sub->passwordrequired && !sub->ownersuperuser);
1398 :
1399 14 : values[Anum_pg_subscription_subconninfo - 1] =
1400 14 : CStringGetTextDatum(stmt->conninfo);
1401 14 : replaces[Anum_pg_subscription_subconninfo - 1] = true;
1402 14 : update_tuple = true;
1403 14 : break;
1404 :
1405 28 : case ALTER_SUBSCRIPTION_SET_PUBLICATION:
1406 : {
1407 28 : supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1408 28 : parse_subscription_options(pstate, stmt->options,
1409 : supported_opts, &opts);
1410 :
1411 28 : values[Anum_pg_subscription_subpublications - 1] =
1412 28 : publicationListToArray(stmt->publication);
1413 28 : replaces[Anum_pg_subscription_subpublications - 1] = true;
1414 :
1415 28 : update_tuple = true;
1416 :
1417 : /* Refresh if user asked us to. */
1418 28 : if (opts.refresh)
1419 : {
1420 22 : if (!sub->enabled)
1421 0 : ereport(ERROR,
1422 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1423 : errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1424 : errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1425 :
1426 : /*
1427 : * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1428 : * not allowed.
1429 : */
1430 22 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1431 0 : ereport(ERROR,
1432 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1433 : errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1434 : errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1435 :
1436 22 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1437 :
1438 : /* Make sure refresh sees the new list of publications. */
1439 10 : sub->publications = stmt->publication;
1440 :
1441 10 : AlterSubscription_refresh(sub, opts.copy_data,
1442 : stmt->publication);
1443 : }
1444 :
1445 16 : break;
1446 : }
1447 :
1448 54 : case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
1449 : case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
1450 : {
1451 : List *publist;
1452 54 : bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1453 :
1454 54 : supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1455 54 : parse_subscription_options(pstate, stmt->options,
1456 : supported_opts, &opts);
1457 :
1458 54 : publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1459 18 : values[Anum_pg_subscription_subpublications - 1] =
1460 18 : publicationListToArray(publist);
1461 18 : replaces[Anum_pg_subscription_subpublications - 1] = true;
1462 :
1463 18 : update_tuple = true;
1464 :
1465 : /* Refresh if user asked us to. */
1466 18 : if (opts.refresh)
1467 : {
1468 : /* We only need to validate user specified publications. */
1469 6 : List *validate_publications = (isadd) ? stmt->publication : NULL;
1470 :
1471 6 : if (!sub->enabled)
1472 0 : ereport(ERROR,
1473 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1474 : errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1475 : /* translator: %s is an SQL ALTER command */
1476 : errhint("Use %s instead.",
1477 : isadd ?
1478 : "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
1479 : "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
1480 :
1481 : /*
1482 : * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1483 : * not allowed.
1484 : */
1485 6 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1486 0 : ereport(ERROR,
1487 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1488 : errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1489 : /* translator: %s is an SQL ALTER command */
1490 : errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
1491 : isadd ?
1492 : "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
1493 : "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
1494 :
1495 6 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1496 :
1497 : /* Refresh the new list of publications. */
1498 6 : sub->publications = publist;
1499 :
1500 6 : AlterSubscription_refresh(sub, opts.copy_data,
1501 : validate_publications);
1502 : }
1503 :
1504 18 : break;
1505 : }
1506 :
1507 54 : case ALTER_SUBSCRIPTION_REFRESH:
1508 : {
1509 54 : if (!sub->enabled)
1510 6 : ereport(ERROR,
1511 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1512 : errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1513 :
1514 48 : parse_subscription_options(pstate, stmt->options,
1515 : SUBOPT_COPY_DATA, &opts);
1516 :
1517 : /*
1518 : * The subscription option "two_phase" requires that
1519 : * replication has passed the initial table synchronization
1520 : * phase before the two_phase becomes properly enabled.
1521 : *
1522 : * But, having reached this two-phase commit "enabled" state
1523 : * we must not allow any subsequent table initialization to
1524 : * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1525 : * when the user had requested two_phase = on mode.
1526 : *
1527 : * The exception to this restriction is when copy_data =
1528 : * false, because when copy_data is false the tablesync will
1529 : * start already in READY state and will exit directly without
1530 : * doing anything.
1531 : *
1532 : * For more details see comments atop worker.c.
1533 : */
1534 48 : if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1535 0 : ereport(ERROR,
1536 : (errcode(ERRCODE_SYNTAX_ERROR),
1537 : errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1538 : errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1539 :
1540 48 : PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1541 :
1542 42 : AlterSubscription_refresh(sub, opts.copy_data, NULL);
1543 :
1544 40 : break;
1545 : }
1546 :
1547 24 : case ALTER_SUBSCRIPTION_SKIP:
1548 : {
1549 24 : parse_subscription_options(pstate, stmt->options, SUBOPT_LSN, &opts);
1550 :
1551 : /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
1552 : Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
1553 :
1554 : /*
1555 : * If the user sets subskiplsn, we do a sanity check to make
1556 : * sure that the specified LSN is a probable value.
1557 : */
1558 18 : if (!XLogRecPtrIsInvalid(opts.lsn))
1559 : {
1560 : RepOriginId originid;
1561 : char originname[NAMEDATALEN];
1562 : XLogRecPtr remote_lsn;
1563 :
1564 12 : ReplicationOriginNameForLogicalRep(subid, InvalidOid,
1565 : originname, sizeof(originname));
1566 12 : originid = replorigin_by_name(originname, false);
1567 12 : remote_lsn = replorigin_get_progress(originid, false);
1568 :
1569 : /* Check the given LSN is at least a future LSN */
1570 12 : if (!XLogRecPtrIsInvalid(remote_lsn) && opts.lsn < remote_lsn)
1571 0 : ereport(ERROR,
1572 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1573 : errmsg("skip WAL location (LSN %X/%X) must be greater than origin LSN %X/%X",
1574 : LSN_FORMAT_ARGS(opts.lsn),
1575 : LSN_FORMAT_ARGS(remote_lsn))));
1576 : }
1577 :
1578 18 : values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
1579 18 : replaces[Anum_pg_subscription_subskiplsn - 1] = true;
1580 :
1581 18 : update_tuple = true;
1582 18 : break;
1583 : }
1584 :
1585 0 : default:
1586 0 : elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1587 : stmt->kind);
1588 : }
1589 :
1590 : /* Update the catalog if needed. */
1591 338 : if (update_tuple)
1592 : {
1593 298 : tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1594 : replaces);
1595 :
1596 298 : CatalogTupleUpdate(rel, &tup->t_self, tup);
1597 :
1598 298 : heap_freetuple(tup);
1599 : }
1600 :
1601 : /*
1602 : * Try to acquire the connection necessary for altering the slot, if
1603 : * needed.
1604 : *
1605 : * This has to be at the end because otherwise if there is an error while
1606 : * doing the database operations we won't be able to rollback altered
1607 : * slot.
1608 : */
1609 338 : if (update_failover || update_two_phase)
1610 : {
1611 : bool must_use_password;
1612 : char *err;
1613 : WalReceiverConn *wrconn;
1614 :
1615 : /* Load the library providing us libpq calls. */
1616 8 : load_file("libpqwalreceiver", false);
1617 :
1618 : /* Try to connect to the publisher. */
1619 8 : must_use_password = sub->passwordrequired && !sub->ownersuperuser;
1620 8 : wrconn = walrcv_connect(sub->conninfo, true, true, must_use_password,
1621 : sub->name, &err);
1622 8 : if (!wrconn)
1623 0 : ereport(ERROR,
1624 : (errcode(ERRCODE_CONNECTION_FAILURE),
1625 : errmsg("subscription \"%s\" could not connect to the publisher: %s",
1626 : sub->name, err)));
1627 :
1628 8 : PG_TRY();
1629 : {
1630 8 : walrcv_alter_slot(wrconn, sub->slotname,
1631 : update_failover ? &opts.failover : NULL,
1632 : update_two_phase ? &opts.twophase : NULL);
1633 : }
1634 0 : PG_FINALLY();
1635 : {
1636 8 : walrcv_disconnect(wrconn);
1637 : }
1638 8 : PG_END_TRY();
1639 : }
1640 :
1641 338 : table_close(rel, RowExclusiveLock);
1642 :
1643 338 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
1644 :
1645 338 : InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1646 :
1647 : /* Wake up related replication workers to handle this change quickly. */
1648 338 : LogicalRepWorkersWakeupAtCommit(subid);
1649 :
1650 338 : return myself;
1651 : }
1652 :
1653 : /*
1654 : * Drop a subscription
1655 : */
1656 : void
1657 194 : DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
1658 : {
1659 : Relation rel;
1660 : ObjectAddress myself;
1661 : HeapTuple tup;
1662 : Oid subid;
1663 : Oid subowner;
1664 : Datum datum;
1665 : bool isnull;
1666 : char *subname;
1667 : char *conninfo;
1668 : char *slotname;
1669 : List *subworkers;
1670 : ListCell *lc;
1671 : char originname[NAMEDATALEN];
1672 194 : char *err = NULL;
1673 : WalReceiverConn *wrconn;
1674 : Form_pg_subscription form;
1675 : List *rstates;
1676 : bool must_use_password;
1677 :
1678 : /*
1679 : * Lock pg_subscription with AccessExclusiveLock to ensure that the
1680 : * launcher doesn't restart new worker during dropping the subscription
1681 : */
1682 194 : rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1683 :
1684 194 : tup = SearchSysCache2(SUBSCRIPTIONNAME, MyDatabaseId,
1685 194 : CStringGetDatum(stmt->subname));
1686 :
1687 194 : if (!HeapTupleIsValid(tup))
1688 : {
1689 12 : table_close(rel, NoLock);
1690 :
1691 12 : if (!stmt->missing_ok)
1692 6 : ereport(ERROR,
1693 : (errcode(ERRCODE_UNDEFINED_OBJECT),
1694 : errmsg("subscription \"%s\" does not exist",
1695 : stmt->subname)));
1696 : else
1697 6 : ereport(NOTICE,
1698 : (errmsg("subscription \"%s\" does not exist, skipping",
1699 : stmt->subname)));
1700 :
1701 80 : return;
1702 : }
1703 :
1704 182 : form = (Form_pg_subscription) GETSTRUCT(tup);
1705 182 : subid = form->oid;
1706 182 : subowner = form->subowner;
1707 182 : must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
1708 :
1709 : /* must be owner */
1710 182 : if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1711 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
1712 0 : stmt->subname);
1713 :
1714 : /* DROP hook for the subscription being removed */
1715 182 : InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1716 :
1717 : /*
1718 : * Lock the subscription so nobody else can do anything with it (including
1719 : * the replication workers).
1720 : */
1721 182 : LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1722 :
1723 : /* Get subname */
1724 182 : datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
1725 : Anum_pg_subscription_subname);
1726 182 : subname = pstrdup(NameStr(*DatumGetName(datum)));
1727 :
1728 : /* Get conninfo */
1729 182 : datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
1730 : Anum_pg_subscription_subconninfo);
1731 182 : conninfo = TextDatumGetCString(datum);
1732 :
1733 : /* Get slotname */
1734 182 : datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1735 : Anum_pg_subscription_subslotname, &isnull);
1736 182 : if (!isnull)
1737 108 : slotname = pstrdup(NameStr(*DatumGetName(datum)));
1738 : else
1739 74 : slotname = NULL;
1740 :
1741 : /*
1742 : * Since dropping a replication slot is not transactional, the replication
1743 : * slot stays dropped even if the transaction rolls back. So we cannot
1744 : * run DROP SUBSCRIPTION inside a transaction block if dropping the
1745 : * replication slot. Also, in this case, we report a message for dropping
1746 : * the subscription to the cumulative stats system.
1747 : *
1748 : * XXX The command name should really be something like "DROP SUBSCRIPTION
1749 : * of a subscription that is associated with a replication slot", but we
1750 : * don't have the proper facilities for that.
1751 : */
1752 182 : if (slotname)
1753 108 : PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1754 :
1755 176 : ObjectAddressSet(myself, SubscriptionRelationId, subid);
1756 176 : EventTriggerSQLDropAddObject(&myself, true, true);
1757 :
1758 : /* Remove the tuple from catalog. */
1759 176 : CatalogTupleDelete(rel, &tup->t_self);
1760 :
1761 176 : ReleaseSysCache(tup);
1762 :
1763 : /*
1764 : * Stop all the subscription workers immediately.
1765 : *
1766 : * This is necessary if we are dropping the replication slot, so that the
1767 : * slot becomes accessible.
1768 : *
1769 : * It is also necessary if the subscription is disabled and was disabled
1770 : * in the same transaction. Then the workers haven't seen the disabling
1771 : * yet and will still be running, leading to hangs later when we want to
1772 : * drop the replication origin. If the subscription was disabled before
1773 : * this transaction, then there shouldn't be any workers left, so this
1774 : * won't make a difference.
1775 : *
1776 : * New workers won't be started because we hold an exclusive lock on the
1777 : * subscription till the end of the transaction.
1778 : */
1779 176 : subworkers = logicalrep_workers_find(subid, false, true);
1780 282 : foreach(lc, subworkers)
1781 : {
1782 106 : LogicalRepWorker *w = (LogicalRepWorker *) lfirst(lc);
1783 :
1784 106 : logicalrep_worker_stop(w->subid, w->relid);
1785 : }
1786 176 : list_free(subworkers);
1787 :
1788 : /*
1789 : * Remove the no-longer-useful entry in the launcher's table of apply
1790 : * worker start times.
1791 : *
1792 : * If this transaction rolls back, the launcher might restart a failed
1793 : * apply worker before wal_retrieve_retry_interval milliseconds have
1794 : * elapsed, but that's pretty harmless.
1795 : */
1796 176 : ApplyLauncherForgetWorkerStartTime(subid);
1797 :
1798 : /*
1799 : * Cleanup of tablesync replication origins.
1800 : *
1801 : * Any READY-state relations would already have dealt with clean-ups.
1802 : *
1803 : * Note that the state can't change because we have already stopped both
1804 : * the apply and tablesync workers and they can't restart because of
1805 : * exclusive lock on the subscription.
1806 : */
1807 176 : rstates = GetSubscriptionRelations(subid, true);
1808 180 : foreach(lc, rstates)
1809 : {
1810 4 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
1811 4 : Oid relid = rstate->relid;
1812 :
1813 : /* Only cleanup resources of tablesync workers */
1814 4 : if (!OidIsValid(relid))
1815 0 : continue;
1816 :
1817 : /*
1818 : * Drop the tablesync's origin tracking if exists.
1819 : *
1820 : * It is possible that the origin is not yet created for tablesync
1821 : * worker so passing missing_ok = true. This can happen for the states
1822 : * before SUBREL_STATE_FINISHEDCOPY.
1823 : */
1824 4 : ReplicationOriginNameForLogicalRep(subid, relid, originname,
1825 : sizeof(originname));
1826 4 : replorigin_drop_by_name(originname, true, false);
1827 : }
1828 :
1829 : /* Clean up dependencies */
1830 176 : deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1831 :
1832 : /* Remove any associated relation synchronization states. */
1833 176 : RemoveSubscriptionRel(subid, InvalidOid);
1834 :
1835 : /* Remove the origin tracking if exists. */
1836 176 : ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
1837 176 : replorigin_drop_by_name(originname, true, false);
1838 :
1839 : /*
1840 : * Tell the cumulative stats system that the subscription is getting
1841 : * dropped.
1842 : */
1843 176 : pgstat_drop_subscription(subid);
1844 :
1845 : /*
1846 : * If there is no slot associated with the subscription, we can finish
1847 : * here.
1848 : */
1849 176 : if (!slotname && rstates == NIL)
1850 : {
1851 74 : table_close(rel, NoLock);
1852 74 : return;
1853 : }
1854 :
1855 : /*
1856 : * Try to acquire the connection necessary for dropping slots.
1857 : *
1858 : * Note: If the slotname is NONE/NULL then we allow the command to finish
1859 : * and users need to manually cleanup the apply and tablesync worker slots
1860 : * later.
1861 : *
1862 : * This has to be at the end because otherwise if there is an error while
1863 : * doing the database operations we won't be able to rollback dropped
1864 : * slot.
1865 : */
1866 102 : load_file("libpqwalreceiver", false);
1867 :
1868 102 : wrconn = walrcv_connect(conninfo, true, true, must_use_password,
1869 : subname, &err);
1870 102 : if (wrconn == NULL)
1871 : {
1872 0 : if (!slotname)
1873 : {
1874 : /* be tidy */
1875 0 : list_free(rstates);
1876 0 : table_close(rel, NoLock);
1877 0 : return;
1878 : }
1879 : else
1880 : {
1881 0 : ReportSlotConnectionError(rstates, subid, slotname, err);
1882 : }
1883 : }
1884 :
1885 102 : PG_TRY();
1886 : {
1887 106 : foreach(lc, rstates)
1888 : {
1889 4 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
1890 4 : Oid relid = rstate->relid;
1891 :
1892 : /* Only cleanup resources of tablesync workers */
1893 4 : if (!OidIsValid(relid))
1894 0 : continue;
1895 :
1896 : /*
1897 : * Drop the tablesync slots associated with removed tables.
1898 : *
1899 : * For SYNCDONE/READY states, the tablesync slot is known to have
1900 : * already been dropped by the tablesync worker.
1901 : *
1902 : * For other states, there is no certainty, maybe the slot does
1903 : * not exist yet. Also, if we fail after removing some of the
1904 : * slots, next time, it will again try to drop already dropped
1905 : * slots and fail. For these reasons, we allow missing_ok = true
1906 : * for the drop.
1907 : */
1908 4 : if (rstate->state != SUBREL_STATE_SYNCDONE)
1909 : {
1910 4 : char syncslotname[NAMEDATALEN] = {0};
1911 :
1912 4 : ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1913 : sizeof(syncslotname));
1914 4 : ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1915 : }
1916 : }
1917 :
1918 102 : list_free(rstates);
1919 :
1920 : /*
1921 : * If there is a slot associated with the subscription, then drop the
1922 : * replication slot at the publisher.
1923 : */
1924 102 : if (slotname)
1925 102 : ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1926 : }
1927 0 : PG_FINALLY();
1928 : {
1929 102 : walrcv_disconnect(wrconn);
1930 : }
1931 102 : PG_END_TRY();
1932 :
1933 102 : table_close(rel, NoLock);
1934 : }
1935 :
1936 : /*
1937 : * Drop the replication slot at the publisher node using the replication
1938 : * connection.
1939 : *
1940 : * missing_ok - if true then only issue a LOG message if the slot doesn't
1941 : * exist.
1942 : */
1943 : void
1944 438 : ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
1945 : {
1946 : StringInfoData cmd;
1947 :
1948 : Assert(wrconn);
1949 :
1950 438 : load_file("libpqwalreceiver", false);
1951 :
1952 438 : initStringInfo(&cmd);
1953 438 : appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1954 :
1955 438 : PG_TRY();
1956 : {
1957 : WalRcvExecResult *res;
1958 :
1959 438 : res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1960 :
1961 438 : if (res->status == WALRCV_OK_COMMAND)
1962 : {
1963 : /* NOTICE. Success. */
1964 438 : ereport(NOTICE,
1965 : (errmsg("dropped replication slot \"%s\" on publisher",
1966 : slotname)));
1967 : }
1968 0 : else if (res->status == WALRCV_ERROR &&
1969 0 : missing_ok &&
1970 0 : res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1971 : {
1972 : /* LOG. Error, but missing_ok = true. */
1973 0 : ereport(LOG,
1974 : (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1975 : slotname, res->err)));
1976 : }
1977 : else
1978 : {
1979 : /* ERROR. */
1980 0 : ereport(ERROR,
1981 : (errcode(ERRCODE_CONNECTION_FAILURE),
1982 : errmsg("could not drop replication slot \"%s\" on publisher: %s",
1983 : slotname, res->err)));
1984 : }
1985 :
1986 438 : walrcv_clear_result(res);
1987 : }
1988 0 : PG_FINALLY();
1989 : {
1990 438 : pfree(cmd.data);
1991 : }
1992 438 : PG_END_TRY();
1993 438 : }
1994 :
1995 : /*
1996 : * Internal workhorse for changing a subscription owner
1997 : */
1998 : static void
1999 18 : AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
2000 : {
2001 : Form_pg_subscription form;
2002 : AclResult aclresult;
2003 :
2004 18 : form = (Form_pg_subscription) GETSTRUCT(tup);
2005 :
2006 18 : if (form->subowner == newOwnerId)
2007 4 : return;
2008 :
2009 14 : if (!object_ownercheck(SubscriptionRelationId, form->oid, GetUserId()))
2010 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
2011 0 : NameStr(form->subname));
2012 :
2013 : /*
2014 : * Don't allow non-superuser modification of a subscription with
2015 : * password_required=false.
2016 : */
2017 14 : if (!form->subpasswordrequired && !superuser())
2018 0 : ereport(ERROR,
2019 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2020 : errmsg("password_required=false is superuser-only"),
2021 : errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
2022 :
2023 : /* Must be able to become new owner */
2024 14 : check_can_set_role(GetUserId(), newOwnerId);
2025 :
2026 : /*
2027 : * current owner must have CREATE on database
2028 : *
2029 : * This is consistent with how ALTER SCHEMA ... OWNER TO works, but some
2030 : * other object types behave differently (e.g. you can't give a table to a
2031 : * user who lacks CREATE privileges on a schema).
2032 : */
2033 8 : aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
2034 : GetUserId(), ACL_CREATE);
2035 8 : if (aclresult != ACLCHECK_OK)
2036 0 : aclcheck_error(aclresult, OBJECT_DATABASE,
2037 0 : get_database_name(MyDatabaseId));
2038 :
2039 8 : form->subowner = newOwnerId;
2040 8 : CatalogTupleUpdate(rel, &tup->t_self, tup);
2041 :
2042 : /* Update owner dependency reference */
2043 8 : changeDependencyOnOwner(SubscriptionRelationId,
2044 : form->oid,
2045 : newOwnerId);
2046 :
2047 8 : InvokeObjectPostAlterHook(SubscriptionRelationId,
2048 : form->oid, 0);
2049 :
2050 : /* Wake up related background processes to handle this change quickly. */
2051 8 : ApplyLauncherWakeupAtCommit();
2052 8 : LogicalRepWorkersWakeupAtCommit(form->oid);
2053 : }
2054 :
2055 : /*
2056 : * Change subscription owner -- by name
2057 : */
2058 : ObjectAddress
2059 18 : AlterSubscriptionOwner(const char *name, Oid newOwnerId)
2060 : {
2061 : Oid subid;
2062 : HeapTuple tup;
2063 : Relation rel;
2064 : ObjectAddress address;
2065 : Form_pg_subscription form;
2066 :
2067 18 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
2068 :
2069 18 : tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, MyDatabaseId,
2070 : CStringGetDatum(name));
2071 :
2072 18 : if (!HeapTupleIsValid(tup))
2073 0 : ereport(ERROR,
2074 : (errcode(ERRCODE_UNDEFINED_OBJECT),
2075 : errmsg("subscription \"%s\" does not exist", name)));
2076 :
2077 18 : form = (Form_pg_subscription) GETSTRUCT(tup);
2078 18 : subid = form->oid;
2079 :
2080 18 : AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
2081 :
2082 12 : ObjectAddressSet(address, SubscriptionRelationId, subid);
2083 :
2084 12 : heap_freetuple(tup);
2085 :
2086 12 : table_close(rel, RowExclusiveLock);
2087 :
2088 12 : return address;
2089 : }
2090 :
2091 : /*
2092 : * Change subscription owner -- by OID
2093 : */
2094 : void
2095 0 : AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
2096 : {
2097 : HeapTuple tup;
2098 : Relation rel;
2099 :
2100 0 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
2101 :
2102 0 : tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
2103 :
2104 0 : if (!HeapTupleIsValid(tup))
2105 0 : ereport(ERROR,
2106 : (errcode(ERRCODE_UNDEFINED_OBJECT),
2107 : errmsg("subscription with OID %u does not exist", subid)));
2108 :
2109 0 : AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
2110 :
2111 0 : heap_freetuple(tup);
2112 :
2113 0 : table_close(rel, RowExclusiveLock);
2114 0 : }
2115 :
2116 : /*
2117 : * Check and log a warning if the publisher has subscribed to the same table
2118 : * from some other publisher. This check is required only if "copy_data = true"
2119 : * and "origin = none" for CREATE SUBSCRIPTION and
2120 : * ALTER SUBSCRIPTION ... REFRESH statements to notify the user that data
2121 : * having origin might have been copied.
2122 : *
2123 : * This check need not be performed on the tables that are already added
2124 : * because incremental sync for those tables will happen through WAL and the
2125 : * origin of the data can be identified from the WAL records.
2126 : *
2127 : * subrel_local_oids contains the list of relation oids that are already
2128 : * present on the subscriber.
2129 : */
2130 : static void
2131 256 : check_publications_origin(WalReceiverConn *wrconn, List *publications,
2132 : bool copydata, char *origin, Oid *subrel_local_oids,
2133 : int subrel_count, char *subname)
2134 : {
2135 : WalRcvExecResult *res;
2136 : StringInfoData cmd;
2137 : TupleTableSlot *slot;
2138 256 : Oid tableRow[1] = {TEXTOID};
2139 256 : List *publist = NIL;
2140 : int i;
2141 :
2142 490 : if (!copydata || !origin ||
2143 234 : (pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) != 0))
2144 244 : return;
2145 :
2146 12 : initStringInfo(&cmd);
2147 12 : appendStringInfoString(&cmd,
2148 : "SELECT DISTINCT P.pubname AS pubname\n"
2149 : "FROM pg_publication P,\n"
2150 : " LATERAL pg_get_publication_tables(P.pubname) GPT\n"
2151 : " JOIN pg_subscription_rel PS ON (GPT.relid = PS.srrelid),\n"
2152 : " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
2153 : "WHERE C.oid = GPT.relid AND P.pubname IN (");
2154 12 : get_publications_str(publications, &cmd, true);
2155 12 : appendStringInfoString(&cmd, ")\n");
2156 :
2157 : /*
2158 : * In case of ALTER SUBSCRIPTION ... REFRESH, subrel_local_oids contains
2159 : * the list of relation oids that are already present on the subscriber.
2160 : * This check should be skipped for these tables.
2161 : */
2162 18 : for (i = 0; i < subrel_count; i++)
2163 : {
2164 6 : Oid relid = subrel_local_oids[i];
2165 6 : char *schemaname = get_namespace_name(get_rel_namespace(relid));
2166 6 : char *tablename = get_rel_name(relid);
2167 :
2168 6 : appendStringInfo(&cmd, "AND NOT (N.nspname = '%s' AND C.relname = '%s')\n",
2169 : schemaname, tablename);
2170 : }
2171 :
2172 12 : res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
2173 12 : pfree(cmd.data);
2174 :
2175 12 : if (res->status != WALRCV_OK_TUPLES)
2176 0 : ereport(ERROR,
2177 : (errcode(ERRCODE_CONNECTION_FAILURE),
2178 : errmsg("could not receive list of replicated tables from the publisher: %s",
2179 : res->err)));
2180 :
2181 : /* Process tables. */
2182 12 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
2183 16 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
2184 : {
2185 : char *pubname;
2186 : bool isnull;
2187 :
2188 4 : pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
2189 : Assert(!isnull);
2190 :
2191 4 : ExecClearTuple(slot);
2192 4 : publist = list_append_unique(publist, makeString(pubname));
2193 : }
2194 :
2195 : /*
2196 : * Log a warning if the publisher has subscribed to the same table from
2197 : * some other publisher. We cannot know the origin of data during the
2198 : * initial sync. Data origins can be found only from the WAL by looking at
2199 : * the origin id.
2200 : *
2201 : * XXX: For simplicity, we don't check whether the table has any data or
2202 : * not. If the table doesn't have any data then we don't need to
2203 : * distinguish between data having origin and data not having origin so we
2204 : * can avoid logging a warning in that case.
2205 : */
2206 12 : if (publist)
2207 : {
2208 4 : StringInfo pubnames = makeStringInfo();
2209 :
2210 : /* Prepare the list of publication(s) for warning message. */
2211 4 : get_publications_str(publist, pubnames, false);
2212 4 : ereport(WARNING,
2213 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2214 : errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
2215 : subname),
2216 : errdetail_plural("The subscription being created subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
2217 : "The subscription being created subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
2218 : list_length(publist), pubnames->data),
2219 : errhint("Verify that initial data copied from the publisher tables did not come from other origins."));
2220 : }
2221 :
2222 12 : ExecDropSingleTupleTableSlot(slot);
2223 :
2224 12 : walrcv_clear_result(res);
2225 : }
2226 :
2227 : /*
2228 : * Get the list of tables which belong to specified publications on the
2229 : * publisher connection.
2230 : *
2231 : * Note that we don't support the case where the column list is different for
2232 : * the same table in different publications to avoid sending unwanted column
2233 : * information for some of the rows. This can happen when both the column
2234 : * list and row filter are specified for different publications.
2235 : */
2236 : static List *
2237 256 : fetch_table_list(WalReceiverConn *wrconn, List *publications)
2238 : {
2239 : WalRcvExecResult *res;
2240 : StringInfoData cmd;
2241 : TupleTableSlot *slot;
2242 256 : Oid tableRow[3] = {TEXTOID, TEXTOID, InvalidOid};
2243 256 : List *tablelist = NIL;
2244 256 : int server_version = walrcv_server_version(wrconn);
2245 256 : bool check_columnlist = (server_version >= 150000);
2246 :
2247 256 : initStringInfo(&cmd);
2248 :
2249 : /* Get the list of tables from the publisher. */
2250 256 : if (server_version >= 160000)
2251 : {
2252 : StringInfoData pub_names;
2253 :
2254 256 : tableRow[2] = INT2VECTOROID;
2255 256 : initStringInfo(&pub_names);
2256 256 : get_publications_str(publications, &pub_names, true);
2257 :
2258 : /*
2259 : * From version 16, we allowed passing multiple publications to the
2260 : * function pg_get_publication_tables. This helped to filter out the
2261 : * partition table whose ancestor is also published in this
2262 : * publication array.
2263 : *
2264 : * Join pg_get_publication_tables with pg_publication to exclude
2265 : * non-existing publications.
2266 : *
2267 : * Note that attrs are always stored in sorted order so we don't need
2268 : * to worry if different publications have specified them in a
2269 : * different order. See pub_collist_validate.
2270 : */
2271 256 : appendStringInfo(&cmd, "SELECT DISTINCT n.nspname, c.relname, gpt.attrs\n"
2272 : " FROM pg_class c\n"
2273 : " JOIN pg_namespace n ON n.oid = c.relnamespace\n"
2274 : " JOIN ( SELECT (pg_get_publication_tables(VARIADIC array_agg(pubname::text))).*\n"
2275 : " FROM pg_publication\n"
2276 : " WHERE pubname IN ( %s )) AS gpt\n"
2277 : " ON gpt.relid = c.oid\n",
2278 : pub_names.data);
2279 :
2280 256 : pfree(pub_names.data);
2281 : }
2282 : else
2283 : {
2284 0 : tableRow[2] = NAMEARRAYOID;
2285 0 : appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename \n");
2286 :
2287 : /* Get column lists for each relation if the publisher supports it */
2288 0 : if (check_columnlist)
2289 0 : appendStringInfoString(&cmd, ", t.attnames\n");
2290 :
2291 0 : appendStringInfoString(&cmd, "FROM pg_catalog.pg_publication_tables t\n"
2292 : " WHERE t.pubname IN (");
2293 0 : get_publications_str(publications, &cmd, true);
2294 0 : appendStringInfoChar(&cmd, ')');
2295 : }
2296 :
2297 256 : res = walrcv_exec(wrconn, cmd.data, check_columnlist ? 3 : 2, tableRow);
2298 256 : pfree(cmd.data);
2299 :
2300 256 : if (res->status != WALRCV_OK_TUPLES)
2301 0 : ereport(ERROR,
2302 : (errcode(ERRCODE_CONNECTION_FAILURE),
2303 : errmsg("could not receive list of replicated tables from the publisher: %s",
2304 : res->err)));
2305 :
2306 : /* Process tables. */
2307 256 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
2308 730 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
2309 : {
2310 : char *nspname;
2311 : char *relname;
2312 : bool isnull;
2313 : RangeVar *rv;
2314 :
2315 476 : nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
2316 : Assert(!isnull);
2317 476 : relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
2318 : Assert(!isnull);
2319 :
2320 476 : rv = makeRangeVar(nspname, relname, -1);
2321 :
2322 476 : if (check_columnlist && list_member(tablelist, rv))
2323 2 : ereport(ERROR,
2324 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2325 : errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
2326 : nspname, relname));
2327 : else
2328 474 : tablelist = lappend(tablelist, rv);
2329 :
2330 474 : ExecClearTuple(slot);
2331 : }
2332 254 : ExecDropSingleTupleTableSlot(slot);
2333 :
2334 254 : walrcv_clear_result(res);
2335 :
2336 254 : return tablelist;
2337 : }
2338 :
2339 : /*
2340 : * This is to report the connection failure while dropping replication slots.
2341 : * Here, we report the WARNING for all tablesync slots so that user can drop
2342 : * them manually, if required.
2343 : */
2344 : static void
2345 0 : ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
2346 : {
2347 : ListCell *lc;
2348 :
2349 0 : foreach(lc, rstates)
2350 : {
2351 0 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
2352 0 : Oid relid = rstate->relid;
2353 :
2354 : /* Only cleanup resources of tablesync workers */
2355 0 : if (!OidIsValid(relid))
2356 0 : continue;
2357 :
2358 : /*
2359 : * Caller needs to ensure that relstate doesn't change underneath us.
2360 : * See DropSubscription where we get the relstates.
2361 : */
2362 0 : if (rstate->state != SUBREL_STATE_SYNCDONE)
2363 : {
2364 0 : char syncslotname[NAMEDATALEN] = {0};
2365 :
2366 0 : ReplicationSlotNameForTablesync(subid, relid, syncslotname,
2367 : sizeof(syncslotname));
2368 0 : elog(WARNING, "could not drop tablesync replication slot \"%s\"",
2369 : syncslotname);
2370 : }
2371 : }
2372 :
2373 0 : ereport(ERROR,
2374 : (errcode(ERRCODE_CONNECTION_FAILURE),
2375 : errmsg("could not connect to publisher when attempting to drop replication slot \"%s\": %s",
2376 : slotname, err),
2377 : /* translator: %s is an SQL ALTER command */
2378 : errhint("Use %s to disable the subscription, and then use %s to disassociate it from the slot.",
2379 : "ALTER SUBSCRIPTION ... DISABLE",
2380 : "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
2381 : }
2382 :
2383 : /*
2384 : * Check for duplicates in the given list of publications and error out if
2385 : * found one. Add publications to datums as text datums, if datums is not
2386 : * NULL.
2387 : */
2388 : static void
2389 392 : check_duplicates_in_publist(List *publist, Datum *datums)
2390 : {
2391 : ListCell *cell;
2392 392 : int j = 0;
2393 :
2394 906 : foreach(cell, publist)
2395 : {
2396 532 : char *name = strVal(lfirst(cell));
2397 : ListCell *pcell;
2398 :
2399 804 : foreach(pcell, publist)
2400 : {
2401 804 : char *pname = strVal(lfirst(pcell));
2402 :
2403 804 : if (pcell == cell)
2404 514 : break;
2405 :
2406 290 : if (strcmp(name, pname) == 0)
2407 18 : ereport(ERROR,
2408 : (errcode(ERRCODE_DUPLICATE_OBJECT),
2409 : errmsg("publication name \"%s\" used more than once",
2410 : pname)));
2411 : }
2412 :
2413 514 : if (datums)
2414 428 : datums[j++] = CStringGetTextDatum(name);
2415 : }
2416 374 : }
2417 :
2418 : /*
2419 : * Merge current subscription's publications and user-specified publications
2420 : * from ADD/DROP PUBLICATIONS.
2421 : *
2422 : * If addpub is true, we will add the list of publications into oldpublist.
2423 : * Otherwise, we will delete the list of publications from oldpublist. The
2424 : * returned list is a copy, oldpublist itself is not changed.
2425 : *
2426 : * subname is the subscription name, for error messages.
2427 : */
2428 : static List *
2429 54 : merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
2430 : {
2431 : ListCell *lc;
2432 :
2433 54 : oldpublist = list_copy(oldpublist);
2434 :
2435 54 : check_duplicates_in_publist(newpublist, NULL);
2436 :
2437 92 : foreach(lc, newpublist)
2438 : {
2439 68 : char *name = strVal(lfirst(lc));
2440 : ListCell *lc2;
2441 68 : bool found = false;
2442 :
2443 134 : foreach(lc2, oldpublist)
2444 : {
2445 110 : char *pubname = strVal(lfirst(lc2));
2446 :
2447 110 : if (strcmp(name, pubname) == 0)
2448 : {
2449 44 : found = true;
2450 44 : if (addpub)
2451 12 : ereport(ERROR,
2452 : (errcode(ERRCODE_DUPLICATE_OBJECT),
2453 : errmsg("publication \"%s\" is already in subscription \"%s\"",
2454 : name, subname)));
2455 : else
2456 32 : oldpublist = foreach_delete_current(oldpublist, lc2);
2457 :
2458 32 : break;
2459 : }
2460 : }
2461 :
2462 56 : if (addpub && !found)
2463 18 : oldpublist = lappend(oldpublist, makeString(name));
2464 38 : else if (!addpub && !found)
2465 6 : ereport(ERROR,
2466 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2467 : errmsg("publication \"%s\" is not in subscription \"%s\"",
2468 : name, subname)));
2469 : }
2470 :
2471 : /*
2472 : * XXX Probably no strong reason for this, but for now it's to make ALTER
2473 : * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
2474 : */
2475 24 : if (!oldpublist)
2476 6 : ereport(ERROR,
2477 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2478 : errmsg("cannot drop all the publications from a subscription")));
2479 :
2480 18 : return oldpublist;
2481 : }
2482 :
2483 : /*
2484 : * Extract the streaming mode value from a DefElem. This is like
2485 : * defGetBoolean() but also accepts the special value of "parallel".
2486 : */
2487 : char
2488 132 : defGetStreamingMode(DefElem *def)
2489 : {
2490 : /*
2491 : * If no parameter value given, assume "true" is meant.
2492 : */
2493 132 : if (!def->arg)
2494 0 : return LOGICALREP_STREAM_ON;
2495 :
2496 : /*
2497 : * Allow 0, 1, "false", "true", "off", "on" or "parallel".
2498 : */
2499 132 : switch (nodeTag(def->arg))
2500 : {
2501 0 : case T_Integer:
2502 0 : switch (intVal(def->arg))
2503 : {
2504 0 : case 0:
2505 0 : return LOGICALREP_STREAM_OFF;
2506 0 : case 1:
2507 0 : return LOGICALREP_STREAM_ON;
2508 0 : default:
2509 : /* otherwise, error out below */
2510 0 : break;
2511 : }
2512 0 : break;
2513 132 : default:
2514 : {
2515 132 : char *sval = defGetString(def);
2516 :
2517 : /*
2518 : * The set of strings accepted here should match up with the
2519 : * grammar's opt_boolean_or_string production.
2520 : */
2521 258 : if (pg_strcasecmp(sval, "false") == 0 ||
2522 126 : pg_strcasecmp(sval, "off") == 0)
2523 6 : return LOGICALREP_STREAM_OFF;
2524 234 : if (pg_strcasecmp(sval, "true") == 0 ||
2525 108 : pg_strcasecmp(sval, "on") == 0)
2526 90 : return LOGICALREP_STREAM_ON;
2527 36 : if (pg_strcasecmp(sval, "parallel") == 0)
2528 30 : return LOGICALREP_STREAM_PARALLEL;
2529 : }
2530 6 : break;
2531 : }
2532 :
2533 6 : ereport(ERROR,
2534 : (errcode(ERRCODE_SYNTAX_ERROR),
2535 : errmsg("%s requires a Boolean value or \"parallel\"",
2536 : def->defname)));
2537 : return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
2538 : }
|