PostgreSQL Source Code  git master
subscriptioncmds.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * subscriptioncmds.c
4  * subscription catalog manipulation functions
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * 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/xact.h"
20 #include "catalog/catalog.h"
21 #include "catalog/dependency.h"
22 #include "catalog/indexing.h"
23 #include "catalog/namespace.h"
24 #include "catalog/objectaccess.h"
25 #include "catalog/objectaddress.h"
28 #include "catalog/pg_type.h"
29 #include "commands/defrem.h"
30 #include "commands/event_trigger.h"
32 #include "executor/executor.h"
33 #include "miscadmin.h"
34 #include "nodes/makefuncs.h"
36 #include "replication/origin.h"
37 #include "replication/slot.h"
39 #include "replication/walsender.h"
41 #include "storage/lmgr.h"
42 #include "utils/acl.h"
43 #include "utils/builtins.h"
44 #include "utils/guc.h"
45 #include "utils/lsyscache.h"
46 #include "utils/memutils.h"
47 #include "utils/syscache.h"
48 
49 static List *fetch_table_list(WalReceiverConn *wrconn, List *publications);
50 static void check_duplicates_in_publist(List *publist, Datum *datums);
51 static List *merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname);
52 static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err);
53 
54 
55 /*
56  * Common option parsing function for CREATE and ALTER SUBSCRIPTION commands.
57  *
58  * Since not all options can be specified in both commands, this function
59  * will report an error on options if the target output pointer is NULL to
60  * accommodate that.
61  */
62 static void
64  bool *connect,
65  bool *enabled_given, bool *enabled,
66  bool *create_slot,
67  bool *slot_name_given, char **slot_name,
68  bool *copy_data,
69  char **synchronous_commit,
70  bool *refresh,
71  bool *binary_given, bool *binary,
72  bool *streaming_given, bool *streaming)
73 {
74  ListCell *lc;
75  bool connect_given = false;
76  bool create_slot_given = false;
77  bool copy_data_given = false;
78  bool refresh_given = false;
79 
80  /* If connect is specified, the others also need to be. */
81  Assert(!connect || (enabled && create_slot && copy_data));
82 
83  if (connect)
84  *connect = true;
85  if (enabled)
86  {
87  *enabled_given = false;
88  *enabled = true;
89  }
90  if (create_slot)
91  *create_slot = true;
92  if (slot_name)
93  {
94  *slot_name_given = false;
95  *slot_name = NULL;
96  }
97  if (copy_data)
98  *copy_data = true;
99  if (synchronous_commit)
100  *synchronous_commit = NULL;
101  if (refresh)
102  *refresh = true;
103  if (binary)
104  {
105  *binary_given = false;
106  *binary = false;
107  }
108  if (streaming)
109  {
110  *streaming_given = false;
111  *streaming = false;
112  }
113 
114  /* Parse options */
115  foreach(lc, options)
116  {
117  DefElem *defel = (DefElem *) lfirst(lc);
118 
119  if (strcmp(defel->defname, "connect") == 0 && connect)
120  {
121  if (connect_given)
122  ereport(ERROR,
123  (errcode(ERRCODE_SYNTAX_ERROR),
124  errmsg("conflicting or redundant options")));
125 
126  connect_given = true;
127  *connect = defGetBoolean(defel);
128  }
129  else if (strcmp(defel->defname, "enabled") == 0 && enabled)
130  {
131  if (*enabled_given)
132  ereport(ERROR,
133  (errcode(ERRCODE_SYNTAX_ERROR),
134  errmsg("conflicting or redundant options")));
135 
136  *enabled_given = true;
137  *enabled = defGetBoolean(defel);
138  }
139  else if (strcmp(defel->defname, "create_slot") == 0 && create_slot)
140  {
141  if (create_slot_given)
142  ereport(ERROR,
143  (errcode(ERRCODE_SYNTAX_ERROR),
144  errmsg("conflicting or redundant options")));
145 
146  create_slot_given = true;
147  *create_slot = defGetBoolean(defel);
148  }
149  else if (strcmp(defel->defname, "slot_name") == 0 && slot_name)
150  {
151  if (*slot_name_given)
152  ereport(ERROR,
153  (errcode(ERRCODE_SYNTAX_ERROR),
154  errmsg("conflicting or redundant options")));
155 
156  *slot_name_given = true;
157  *slot_name = defGetString(defel);
158 
159  /* Setting slot_name = NONE is treated as no slot name. */
160  if (strcmp(*slot_name, "none") == 0)
161  *slot_name = NULL;
162  }
163  else if (strcmp(defel->defname, "copy_data") == 0 && copy_data)
164  {
165  if (copy_data_given)
166  ereport(ERROR,
167  (errcode(ERRCODE_SYNTAX_ERROR),
168  errmsg("conflicting or redundant options")));
169 
170  copy_data_given = true;
171  *copy_data = defGetBoolean(defel);
172  }
173  else if (strcmp(defel->defname, "synchronous_commit") == 0 &&
174  synchronous_commit)
175  {
176  if (*synchronous_commit)
177  ereport(ERROR,
178  (errcode(ERRCODE_SYNTAX_ERROR),
179  errmsg("conflicting or redundant options")));
180 
181  *synchronous_commit = defGetString(defel);
182 
183  /* Test if the given value is valid for synchronous_commit GUC. */
184  (void) set_config_option("synchronous_commit", *synchronous_commit,
186  false, 0, false);
187  }
188  else if (strcmp(defel->defname, "refresh") == 0 && refresh)
189  {
190  if (refresh_given)
191  ereport(ERROR,
192  (errcode(ERRCODE_SYNTAX_ERROR),
193  errmsg("conflicting or redundant options")));
194 
195  refresh_given = true;
196  *refresh = defGetBoolean(defel);
197  }
198  else if (strcmp(defel->defname, "binary") == 0 && binary)
199  {
200  if (*binary_given)
201  ereport(ERROR,
202  (errcode(ERRCODE_SYNTAX_ERROR),
203  errmsg("conflicting or redundant options")));
204 
205  *binary_given = true;
206  *binary = defGetBoolean(defel);
207  }
208  else if (strcmp(defel->defname, "streaming") == 0 && streaming)
209  {
210  if (*streaming_given)
211  ereport(ERROR,
212  (errcode(ERRCODE_SYNTAX_ERROR),
213  errmsg("conflicting or redundant options")));
214 
215  *streaming_given = true;
216  *streaming = defGetBoolean(defel);
217  }
218  else
219  ereport(ERROR,
220  (errcode(ERRCODE_SYNTAX_ERROR),
221  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
222  }
223 
224  /*
225  * We've been explicitly asked to not connect, that requires some
226  * additional processing.
227  */
228  if (connect && !*connect)
229  {
230  /* Check for incompatible options from the user. */
231  if (enabled && *enabled_given && *enabled)
232  ereport(ERROR,
233  (errcode(ERRCODE_SYNTAX_ERROR),
234  /*- translator: both %s are strings of the form "option = value" */
235  errmsg("%s and %s are mutually exclusive options",
236  "connect = false", "enabled = true")));
237 
238  if (create_slot && create_slot_given && *create_slot)
239  ereport(ERROR,
240  (errcode(ERRCODE_SYNTAX_ERROR),
241  errmsg("%s and %s are mutually exclusive options",
242  "connect = false", "create_slot = true")));
243 
244  if (copy_data && copy_data_given && *copy_data)
245  ereport(ERROR,
246  (errcode(ERRCODE_SYNTAX_ERROR),
247  errmsg("%s and %s are mutually exclusive options",
248  "connect = false", "copy_data = true")));
249 
250  /* Change the defaults of other options. */
251  *enabled = false;
252  *create_slot = false;
253  *copy_data = false;
254  }
255 
256  /*
257  * Do additional checking for disallowed combination when slot_name = NONE
258  * was used.
259  */
260  if (slot_name && *slot_name_given && !*slot_name)
261  {
262  if (enabled && *enabled_given && *enabled)
263  ereport(ERROR,
264  (errcode(ERRCODE_SYNTAX_ERROR),
265  /*- translator: both %s are strings of the form "option = value" */
266  errmsg("%s and %s are mutually exclusive options",
267  "slot_name = NONE", "enabled = true")));
268 
269  if (create_slot && create_slot_given && *create_slot)
270  ereport(ERROR,
271  (errcode(ERRCODE_SYNTAX_ERROR),
272  errmsg("%s and %s are mutually exclusive options",
273  "slot_name = NONE", "create_slot = true")));
274 
275  if (enabled && !*enabled_given && *enabled)
276  ereport(ERROR,
277  (errcode(ERRCODE_SYNTAX_ERROR),
278  /*- translator: both %s are strings of the form "option = value" */
279  errmsg("subscription with %s must also set %s",
280  "slot_name = NONE", "enabled = false")));
281 
282  if (create_slot && !create_slot_given && *create_slot)
283  ereport(ERROR,
284  (errcode(ERRCODE_SYNTAX_ERROR),
285  errmsg("subscription with %s must also set %s",
286  "slot_name = NONE", "create_slot = false")));
287  }
288 }
289 
290 /*
291  * Auxiliary function to build a text array out of a list of String nodes.
292  */
293 static Datum
295 {
296  ArrayType *arr;
297  Datum *datums;
298  MemoryContext memcxt;
299  MemoryContext oldcxt;
300 
301  /* Create memory context for temporary allocations. */
303  "publicationListToArray to array",
305  oldcxt = MemoryContextSwitchTo(memcxt);
306 
307  datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
308 
309  check_duplicates_in_publist(publist, datums);
310 
311  MemoryContextSwitchTo(oldcxt);
312 
313  arr = construct_array(datums, list_length(publist),
314  TEXTOID, -1, false, TYPALIGN_INT);
315 
316  MemoryContextDelete(memcxt);
317 
318  return PointerGetDatum(arr);
319 }
320 
321 /*
322  * Create new subscription.
323  */
326 {
327  Relation rel;
328  ObjectAddress myself;
329  Oid subid;
330  bool nulls[Natts_pg_subscription];
331  Datum values[Natts_pg_subscription];
332  Oid owner = GetUserId();
333  HeapTuple tup;
334  bool connect;
335  bool enabled_given;
336  bool enabled;
337  bool copy_data;
338  bool streaming;
339  bool streaming_given;
340  char *synchronous_commit;
341  char *conninfo;
342  char *slotname;
343  bool slotname_given;
344  bool binary;
345  bool binary_given;
346  char originname[NAMEDATALEN];
347  bool create_slot;
348  List *publications;
349 
350  /*
351  * Parse and check options.
352  *
353  * Connection and publication should not be specified here.
354  */
356  &connect,
357  &enabled_given, &enabled,
358  &create_slot,
359  &slotname_given, &slotname,
360  &copy_data,
361  &synchronous_commit,
362  NULL, /* no "refresh" */
363  &binary_given, &binary,
364  &streaming_given, &streaming);
365 
366  /*
367  * Since creating a replication slot is not transactional, rolling back
368  * the transaction leaves the created replication slot. So we cannot run
369  * CREATE SUBSCRIPTION inside a transaction block if creating a
370  * replication slot.
371  */
372  if (create_slot)
373  PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
374 
375  if (!superuser())
376  ereport(ERROR,
377  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
378  errmsg("must be superuser to create subscriptions")));
379 
380  /*
381  * If built with appropriate switch, whine when regression-testing
382  * conventions for subscription names are violated.
383  */
384 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
385  if (strncmp(stmt->subname, "regress_", 8) != 0)
386  elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
387 #endif
388 
389  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
390 
391  /* Check if name is used */
392  subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
394  if (OidIsValid(subid))
395  {
396  ereport(ERROR,
398  errmsg("subscription \"%s\" already exists",
399  stmt->subname)));
400  }
401 
402  if (!slotname_given && slotname == NULL)
403  slotname = stmt->subname;
404 
405  /* The default for synchronous_commit of subscriptions is off. */
406  if (synchronous_commit == NULL)
407  synchronous_commit = "off";
408 
409  conninfo = stmt->conninfo;
410  publications = stmt->publication;
411 
412  /* Load the library providing us libpq calls. */
413  load_file("libpqwalreceiver", false);
414 
415  /* Check the connection info string. */
416  walrcv_check_conninfo(conninfo);
417 
418  /* Everything ok, form a new tuple. */
419  memset(values, 0, sizeof(values));
420  memset(nulls, false, sizeof(nulls));
421 
423  Anum_pg_subscription_oid);
424  values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
425  values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
426  values[Anum_pg_subscription_subname - 1] =
428  values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
429  values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(enabled);
430  values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(binary);
431  values[Anum_pg_subscription_substream - 1] = BoolGetDatum(streaming);
432  values[Anum_pg_subscription_subconninfo - 1] =
433  CStringGetTextDatum(conninfo);
434  if (slotname)
435  values[Anum_pg_subscription_subslotname - 1] =
437  else
438  nulls[Anum_pg_subscription_subslotname - 1] = true;
439  values[Anum_pg_subscription_subsynccommit - 1] =
440  CStringGetTextDatum(synchronous_commit);
441  values[Anum_pg_subscription_subpublications - 1] =
442  publicationListToArray(publications);
443 
444  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
445 
446  /* Insert tuple into catalog. */
447  CatalogTupleInsert(rel, tup);
448  heap_freetuple(tup);
449 
450  recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
451 
452  snprintf(originname, sizeof(originname), "pg_%u", subid);
453  replorigin_create(originname);
454 
455  /*
456  * Connect to remote side to execute requested commands and fetch table
457  * info.
458  */
459  if (connect)
460  {
461  char *err;
463  List *tables;
464  ListCell *lc;
465  char table_state;
466 
467  /* Try to connect to the publisher. */
468  wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
469  if (!wrconn)
470  ereport(ERROR,
471  (errmsg("could not connect to the publisher: %s", err)));
472 
473  PG_TRY();
474  {
475  /*
476  * Set sync state based on if we were asked to do data copy or
477  * not.
478  */
479  table_state = copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
480 
481  /*
482  * Get the table list from publisher and build local table status
483  * info.
484  */
485  tables = fetch_table_list(wrconn, publications);
486  foreach(lc, tables)
487  {
488  RangeVar *rv = (RangeVar *) lfirst(lc);
489  Oid relid;
490 
491  relid = RangeVarGetRelid(rv, AccessShareLock, false);
492 
493  /* Check for supported relkind. */
495  rv->schemaname, rv->relname);
496 
497  AddSubscriptionRelState(subid, relid, table_state,
499  }
500 
501  /*
502  * If requested, create permanent slot for the subscription. We
503  * won't use the initial snapshot for anything, so no need to
504  * export it.
505  */
506  if (create_slot)
507  {
508  Assert(slotname);
509 
510  walrcv_create_slot(wrconn, slotname, false,
511  CRS_NOEXPORT_SNAPSHOT, NULL);
512  ereport(NOTICE,
513  (errmsg("created replication slot \"%s\" on publisher",
514  slotname)));
515  }
516  }
517  PG_FINALLY();
518  {
519  walrcv_disconnect(wrconn);
520  }
521  PG_END_TRY();
522  }
523  else
525  /* translator: %s is an SQL ALTER statement */
526  (errmsg("tables were not subscribed, you will have to run %s to subscribe the tables",
527  "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
528 
530 
531  if (enabled)
533 
534  ObjectAddressSet(myself, SubscriptionRelationId, subid);
535 
536  InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
537 
538  return myself;
539 }
540 
541 static void
543 {
544  char *err;
545  List *pubrel_names;
546  List *subrel_states;
547  Oid *subrel_local_oids;
548  Oid *pubrel_local_oids;
549  ListCell *lc;
550  int off;
551  int remove_rel_len;
552  Relation rel = NULL;
553  typedef struct SubRemoveRels
554  {
555  Oid relid;
556  char state;
557  } SubRemoveRels;
558  SubRemoveRels *sub_remove_rels;
560 
561  /* Load the library providing us libpq calls. */
562  load_file("libpqwalreceiver", false);
563 
564  /* Try to connect to the publisher. */
565  wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
566  if (!wrconn)
567  ereport(ERROR,
568  (errmsg("could not connect to the publisher: %s", err)));
569 
570  PG_TRY();
571  {
572  /* Get the table list from publisher. */
573  pubrel_names = fetch_table_list(wrconn, sub->publications);
574 
575  /* Get local table list. */
576  subrel_states = GetSubscriptionRelations(sub->oid);
577 
578  /*
579  * Build qsorted array of local table oids for faster lookup. This can
580  * potentially contain all tables in the database so speed of lookup
581  * is important.
582  */
583  subrel_local_oids = palloc(list_length(subrel_states) * sizeof(Oid));
584  off = 0;
585  foreach(lc, subrel_states)
586  {
588 
589  subrel_local_oids[off++] = relstate->relid;
590  }
591  qsort(subrel_local_oids, list_length(subrel_states),
592  sizeof(Oid), oid_cmp);
593 
594  /*
595  * Rels that we want to remove from subscription and drop any slots
596  * and origins corresponding to them.
597  */
598  sub_remove_rels = palloc(list_length(subrel_states) * sizeof(SubRemoveRels));
599 
600  /*
601  * Walk over the remote tables and try to match them to locally known
602  * tables. If the table is not known locally create a new state for
603  * it.
604  *
605  * Also builds array of local oids of remote tables for the next step.
606  */
607  off = 0;
608  pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
609 
610  foreach(lc, pubrel_names)
611  {
612  RangeVar *rv = (RangeVar *) lfirst(lc);
613  Oid relid;
614 
615  relid = RangeVarGetRelid(rv, AccessShareLock, false);
616 
617  /* Check for supported relkind. */
619  rv->schemaname, rv->relname);
620 
621  pubrel_local_oids[off++] = relid;
622 
623  if (!bsearch(&relid, subrel_local_oids,
624  list_length(subrel_states), sizeof(Oid), oid_cmp))
625  {
626  AddSubscriptionRelState(sub->oid, relid,
627  copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
629  ereport(DEBUG1,
630  (errmsg_internal("table \"%s.%s\" added to subscription \"%s\"",
631  rv->schemaname, rv->relname, sub->name)));
632  }
633  }
634 
635  /*
636  * Next remove state for tables we should not care about anymore using
637  * the data we collected above
638  */
639  qsort(pubrel_local_oids, list_length(pubrel_names),
640  sizeof(Oid), oid_cmp);
641 
642  remove_rel_len = 0;
643  for (off = 0; off < list_length(subrel_states); off++)
644  {
645  Oid relid = subrel_local_oids[off];
646 
647  if (!bsearch(&relid, pubrel_local_oids,
648  list_length(pubrel_names), sizeof(Oid), oid_cmp))
649  {
650  char state;
651  XLogRecPtr statelsn;
652 
653  /*
654  * Lock pg_subscription_rel with AccessExclusiveLock to
655  * prevent any race conditions with the apply worker
656  * re-launching workers at the same time this code is trying
657  * to remove those tables.
658  *
659  * Even if new worker for this particular rel is restarted it
660  * won't be able to make any progress as we hold exclusive
661  * lock on subscription_rel till the transaction end. It will
662  * simply exit as there is no corresponding rel entry.
663  *
664  * This locking also ensures that the state of rels won't
665  * change till we are done with this refresh operation.
666  */
667  if (!rel)
668  rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
669 
670  /* Last known rel state. */
671  state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
672 
673  sub_remove_rels[remove_rel_len].relid = relid;
674  sub_remove_rels[remove_rel_len++].state = state;
675 
676  RemoveSubscriptionRel(sub->oid, relid);
677 
678  logicalrep_worker_stop(sub->oid, relid);
679 
680  /*
681  * For READY state, we would have already dropped the
682  * tablesync origin.
683  */
684  if (state != SUBREL_STATE_READY)
685  {
686  char originname[NAMEDATALEN];
687 
688  /*
689  * Drop the tablesync's origin tracking if exists.
690  *
691  * It is possible that the origin is not yet created for
692  * tablesync worker, this can happen for the states before
693  * SUBREL_STATE_FINISHEDCOPY. The apply worker can also
694  * concurrently try to drop the origin and by this time
695  * the origin might be already removed. For these reasons,
696  * passing missing_ok = true.
697  */
698  ReplicationOriginNameForTablesync(sub->oid, relid, originname,
699  sizeof(originname));
700  replorigin_drop_by_name(originname, true, false);
701  }
702 
703  ereport(DEBUG1,
704  (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
706  get_rel_name(relid),
707  sub->name)));
708  }
709  }
710 
711  /*
712  * Drop the tablesync slots associated with removed tables. This has
713  * to be at the end because otherwise if there is an error while doing
714  * the database operations we won't be able to rollback dropped slots.
715  */
716  for (off = 0; off < remove_rel_len; off++)
717  {
718  if (sub_remove_rels[off].state != SUBREL_STATE_READY &&
719  sub_remove_rels[off].state != SUBREL_STATE_SYNCDONE)
720  {
721  char syncslotname[NAMEDATALEN] = {0};
722 
723  /*
724  * For READY/SYNCDONE states we know the tablesync slot has
725  * already been dropped by the tablesync worker.
726  *
727  * For other states, there is no certainty, maybe the slot
728  * does not exist yet. Also, if we fail after removing some of
729  * the slots, next time, it will again try to drop already
730  * dropped slots and fail. For these reasons, we allow
731  * missing_ok = true for the drop.
732  */
733  ReplicationSlotNameForTablesync(sub->oid, sub_remove_rels[off].relid,
734  syncslotname, sizeof(syncslotname));
735  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
736  }
737  }
738  }
739  PG_FINALLY();
740  {
741  walrcv_disconnect(wrconn);
742  }
743  PG_END_TRY();
744 
745  if (rel)
746  table_close(rel, NoLock);
747 }
748 
749 /*
750  * Alter the existing subscription.
751  */
754 {
755  Relation rel;
756  ObjectAddress myself;
757  bool nulls[Natts_pg_subscription];
758  bool replaces[Natts_pg_subscription];
759  Datum values[Natts_pg_subscription];
760  HeapTuple tup;
761  Oid subid;
762  bool update_tuple = false;
763  Subscription *sub;
765 
766  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
767 
768  /* Fetch the existing tuple. */
770  CStringGetDatum(stmt->subname));
771 
772  if (!HeapTupleIsValid(tup))
773  ereport(ERROR,
774  (errcode(ERRCODE_UNDEFINED_OBJECT),
775  errmsg("subscription \"%s\" does not exist",
776  stmt->subname)));
777 
778  form = (Form_pg_subscription) GETSTRUCT(tup);
779  subid = form->oid;
780 
781  /* must be owner */
782  if (!pg_subscription_ownercheck(subid, GetUserId()))
784  stmt->subname);
785 
786  sub = GetSubscription(subid, false);
787 
788  /* Lock the subscription so nobody else can do anything with it. */
789  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
790 
791  /* Form a new tuple. */
792  memset(values, 0, sizeof(values));
793  memset(nulls, false, sizeof(nulls));
794  memset(replaces, false, sizeof(replaces));
795 
796  switch (stmt->kind)
797  {
799  {
800  char *slotname;
801  bool slotname_given;
802  char *synchronous_commit;
803  bool binary_given;
804  bool binary;
805  bool streaming_given;
806  bool streaming;
807 
809  NULL, /* no "connect" */
810  NULL, NULL, /* no "enabled" */
811  NULL, /* no "create_slot" */
812  &slotname_given, &slotname,
813  NULL, /* no "copy_data" */
814  &synchronous_commit,
815  NULL, /* no "refresh" */
816  &binary_given, &binary,
817  &streaming_given, &streaming);
818 
819  if (slotname_given)
820  {
821  if (sub->enabled && !slotname)
822  ereport(ERROR,
823  (errcode(ERRCODE_SYNTAX_ERROR),
824  errmsg("cannot set %s for enabled subscription",
825  "slot_name = NONE")));
826 
827  if (slotname)
828  values[Anum_pg_subscription_subslotname - 1] =
830  else
831  nulls[Anum_pg_subscription_subslotname - 1] = true;
832  replaces[Anum_pg_subscription_subslotname - 1] = true;
833  }
834 
835  if (synchronous_commit)
836  {
837  values[Anum_pg_subscription_subsynccommit - 1] =
838  CStringGetTextDatum(synchronous_commit);
839  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
840  }
841 
842  if (binary_given)
843  {
844  values[Anum_pg_subscription_subbinary - 1] =
845  BoolGetDatum(binary);
846  replaces[Anum_pg_subscription_subbinary - 1] = true;
847  }
848 
849  if (streaming_given)
850  {
851  values[Anum_pg_subscription_substream - 1] =
852  BoolGetDatum(streaming);
853  replaces[Anum_pg_subscription_substream - 1] = true;
854  }
855 
856  update_tuple = true;
857  break;
858  }
859 
861  {
862  bool enabled,
863  enabled_given;
864 
866  NULL, /* no "connect" */
867  &enabled_given, &enabled,
868  NULL, /* no "create_slot" */
869  NULL, NULL, /* no "slot_name" */
870  NULL, /* no "copy_data" */
871  NULL, /* no "synchronous_commit" */
872  NULL, /* no "refresh" */
873  NULL, NULL, /* no "binary" */
874  NULL, NULL); /* no streaming */
875  Assert(enabled_given);
876 
877  if (!sub->slotname && enabled)
878  ereport(ERROR,
879  (errcode(ERRCODE_SYNTAX_ERROR),
880  errmsg("cannot enable subscription that does not have a slot name")));
881 
882  values[Anum_pg_subscription_subenabled - 1] =
883  BoolGetDatum(enabled);
884  replaces[Anum_pg_subscription_subenabled - 1] = true;
885 
886  if (enabled)
888 
889  update_tuple = true;
890  break;
891  }
892 
894  /* Load the library providing us libpq calls. */
895  load_file("libpqwalreceiver", false);
896  /* Check the connection info string. */
898 
899  values[Anum_pg_subscription_subconninfo - 1] =
901  replaces[Anum_pg_subscription_subconninfo - 1] = true;
902  update_tuple = true;
903  break;
904 
906  {
907  bool copy_data;
908  bool refresh;
909 
911  NULL, /* no "connect" */
912  NULL, NULL, /* no "enabled" */
913  NULL, /* no "create_slot" */
914  NULL, NULL, /* no "slot_name" */
915  &copy_data,
916  NULL, /* no "synchronous_commit" */
917  &refresh,
918  NULL, NULL, /* no "binary" */
919  NULL, NULL); /* no "streaming" */
920  values[Anum_pg_subscription_subpublications - 1] =
922  replaces[Anum_pg_subscription_subpublications - 1] = true;
923 
924  update_tuple = true;
925 
926  /* Refresh if user asked us to. */
927  if (refresh)
928  {
929  if (!sub->enabled)
930  ereport(ERROR,
931  (errcode(ERRCODE_SYNTAX_ERROR),
932  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
933  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
934 
935  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
936 
937  /* Make sure refresh sees the new list of publications. */
938  sub->publications = stmt->publication;
939 
940  AlterSubscription_refresh(sub, copy_data);
941  }
942 
943  break;
944  }
945 
948  {
949  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
950  bool copy_data;
951  bool refresh;
952  List *publist;
953 
954  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
955 
957  NULL, /* no "connect" */
958  NULL, NULL, /* no "enabled" */
959  NULL, /* no "create_slot" */
960  NULL, NULL, /* no "slot_name" */
961  isadd ? &copy_data : NULL, /* for drop, no
962  * "copy_data" */
963  NULL, /* no "synchronous_commit" */
964  &refresh,
965  NULL, NULL, /* no "binary" */
966  NULL, NULL); /* no "streaming" */
967 
968  values[Anum_pg_subscription_subpublications - 1] =
969  publicationListToArray(publist);
970  replaces[Anum_pg_subscription_subpublications - 1] = true;
971 
972  update_tuple = true;
973 
974  /* Refresh if user asked us to. */
975  if (refresh)
976  {
977  if (!sub->enabled)
978  ereport(ERROR,
979  (errcode(ERRCODE_SYNTAX_ERROR),
980  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
981  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
982 
983  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
984 
985  /* Only refresh the added/dropped list of publications. */
986  sub->publications = stmt->publication;
987 
988  AlterSubscription_refresh(sub, copy_data);
989  }
990 
991  break;
992  }
993 
995  {
996  bool copy_data;
997 
998  if (!sub->enabled)
999  ereport(ERROR,
1000  (errcode(ERRCODE_SYNTAX_ERROR),
1001  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1002 
1004  NULL, /* no "connect" */
1005  NULL, NULL, /* no "enabled" */
1006  NULL, /* no "create_slot" */
1007  NULL, NULL, /* no "slot_name" */
1008  &copy_data,
1009  NULL, /* no "synchronous_commit" */
1010  NULL, /* no "refresh" */
1011  NULL, NULL, /* no "binary" */
1012  NULL, NULL); /* no "streaming" */
1013 
1014  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1015 
1016  AlterSubscription_refresh(sub, copy_data);
1017 
1018  break;
1019  }
1020 
1021  default:
1022  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1023  stmt->kind);
1024  }
1025 
1026  /* Update the catalog if needed. */
1027  if (update_tuple)
1028  {
1029  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1030  replaces);
1031 
1032  CatalogTupleUpdate(rel, &tup->t_self, tup);
1033 
1034  heap_freetuple(tup);
1035  }
1036 
1038 
1039  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1040 
1041  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1042 
1043  return myself;
1044 }
1045 
1046 /*
1047  * Drop a subscription
1048  */
1049 void
1051 {
1052  Relation rel;
1053  ObjectAddress myself;
1054  HeapTuple tup;
1055  Oid subid;
1056  Datum datum;
1057  bool isnull;
1058  char *subname;
1059  char *conninfo;
1060  char *slotname;
1061  List *subworkers;
1062  ListCell *lc;
1063  char originname[NAMEDATALEN];
1064  char *err = NULL;
1066  Form_pg_subscription form;
1067  List *rstates;
1068 
1069  /*
1070  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1071  * launcher doesn't restart new worker during dropping the subscription
1072  */
1073  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1074 
1076  CStringGetDatum(stmt->subname));
1077 
1078  if (!HeapTupleIsValid(tup))
1079  {
1080  table_close(rel, NoLock);
1081 
1082  if (!stmt->missing_ok)
1083  ereport(ERROR,
1084  (errcode(ERRCODE_UNDEFINED_OBJECT),
1085  errmsg("subscription \"%s\" does not exist",
1086  stmt->subname)));
1087  else
1088  ereport(NOTICE,
1089  (errmsg("subscription \"%s\" does not exist, skipping",
1090  stmt->subname)));
1091 
1092  return;
1093  }
1094 
1095  form = (Form_pg_subscription) GETSTRUCT(tup);
1096  subid = form->oid;
1097 
1098  /* must be owner */
1099  if (!pg_subscription_ownercheck(subid, GetUserId()))
1101  stmt->subname);
1102 
1103  /* DROP hook for the subscription being removed */
1104  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1105 
1106  /*
1107  * Lock the subscription so nobody else can do anything with it (including
1108  * the replication workers).
1109  */
1110  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1111 
1112  /* Get subname */
1113  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1114  Anum_pg_subscription_subname, &isnull);
1115  Assert(!isnull);
1116  subname = pstrdup(NameStr(*DatumGetName(datum)));
1117 
1118  /* Get conninfo */
1119  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1120  Anum_pg_subscription_subconninfo, &isnull);
1121  Assert(!isnull);
1122  conninfo = TextDatumGetCString(datum);
1123 
1124  /* Get slotname */
1125  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1126  Anum_pg_subscription_subslotname, &isnull);
1127  if (!isnull)
1128  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1129  else
1130  slotname = NULL;
1131 
1132  /*
1133  * Since dropping a replication slot is not transactional, the replication
1134  * slot stays dropped even if the transaction rolls back. So we cannot
1135  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1136  * replication slot.
1137  *
1138  * XXX The command name should really be something like "DROP SUBSCRIPTION
1139  * of a subscription that is associated with a replication slot", but we
1140  * don't have the proper facilities for that.
1141  */
1142  if (slotname)
1143  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1144 
1145  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1146  EventTriggerSQLDropAddObject(&myself, true, true);
1147 
1148  /* Remove the tuple from catalog. */
1149  CatalogTupleDelete(rel, &tup->t_self);
1150 
1151  ReleaseSysCache(tup);
1152 
1153  /*
1154  * Stop all the subscription workers immediately.
1155  *
1156  * This is necessary if we are dropping the replication slot, so that the
1157  * slot becomes accessible.
1158  *
1159  * It is also necessary if the subscription is disabled and was disabled
1160  * in the same transaction. Then the workers haven't seen the disabling
1161  * yet and will still be running, leading to hangs later when we want to
1162  * drop the replication origin. If the subscription was disabled before
1163  * this transaction, then there shouldn't be any workers left, so this
1164  * won't make a difference.
1165  *
1166  * New workers won't be started because we hold an exclusive lock on the
1167  * subscription till the end of the transaction.
1168  */
1169  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1170  subworkers = logicalrep_workers_find(subid, false);
1171  LWLockRelease(LogicalRepWorkerLock);
1172  foreach(lc, subworkers)
1173  {
1175 
1177  }
1178  list_free(subworkers);
1179 
1180  /*
1181  * Cleanup of tablesync replication origins.
1182  *
1183  * Any READY-state relations would already have dealt with clean-ups.
1184  *
1185  * Note that the state can't change because we have already stopped both
1186  * the apply and tablesync workers and they can't restart because of
1187  * exclusive lock on the subscription.
1188  */
1189  rstates = GetSubscriptionNotReadyRelations(subid);
1190  foreach(lc, rstates)
1191  {
1193  Oid relid = rstate->relid;
1194 
1195  /* Only cleanup resources of tablesync workers */
1196  if (!OidIsValid(relid))
1197  continue;
1198 
1199  /*
1200  * Drop the tablesync's origin tracking if exists.
1201  *
1202  * It is possible that the origin is not yet created for tablesync
1203  * worker so passing missing_ok = true. This can happen for the states
1204  * before SUBREL_STATE_FINISHEDCOPY.
1205  */
1206  ReplicationOriginNameForTablesync(subid, relid, originname,
1207  sizeof(originname));
1208  replorigin_drop_by_name(originname, true, false);
1209  }
1210 
1211  /* Clean up dependencies */
1212  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1213 
1214  /* Remove any associated relation synchronization states. */
1216 
1217  /* Remove the origin tracking if exists. */
1218  snprintf(originname, sizeof(originname), "pg_%u", subid);
1219  replorigin_drop_by_name(originname, true, false);
1220 
1221  /*
1222  * If there is no slot associated with the subscription, we can finish
1223  * here.
1224  */
1225  if (!slotname && rstates == NIL)
1226  {
1227  table_close(rel, NoLock);
1228  return;
1229  }
1230 
1231  /*
1232  * Try to acquire the connection necessary for dropping slots.
1233  *
1234  * Note: If the slotname is NONE/NULL then we allow the command to finish
1235  * and users need to manually cleanup the apply and tablesync worker slots
1236  * later.
1237  *
1238  * This has to be at the end because otherwise if there is an error while
1239  * doing the database operations we won't be able to rollback dropped
1240  * slot.
1241  */
1242  load_file("libpqwalreceiver", false);
1243 
1244  wrconn = walrcv_connect(conninfo, true, subname, &err);
1245  if (wrconn == NULL)
1246  {
1247  if (!slotname)
1248  {
1249  /* be tidy */
1250  list_free(rstates);
1251  table_close(rel, NoLock);
1252  return;
1253  }
1254  else
1255  {
1256  ReportSlotConnectionError(rstates, subid, slotname, err);
1257  }
1258  }
1259 
1260  PG_TRY();
1261  {
1262  foreach(lc, rstates)
1263  {
1265  Oid relid = rstate->relid;
1266 
1267  /* Only cleanup resources of tablesync workers */
1268  if (!OidIsValid(relid))
1269  continue;
1270 
1271  /*
1272  * Drop the tablesync slots associated with removed tables.
1273  *
1274  * For SYNCDONE/READY states, the tablesync slot is known to have
1275  * already been dropped by the tablesync worker.
1276  *
1277  * For other states, there is no certainty, maybe the slot does
1278  * not exist yet. Also, if we fail after removing some of the
1279  * slots, next time, it will again try to drop already dropped
1280  * slots and fail. For these reasons, we allow missing_ok = true
1281  * for the drop.
1282  */
1283  if (rstate->state != SUBREL_STATE_SYNCDONE)
1284  {
1285  char syncslotname[NAMEDATALEN] = {0};
1286 
1287  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1288  sizeof(syncslotname));
1289  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1290  }
1291  }
1292 
1293  list_free(rstates);
1294 
1295  /*
1296  * If there is a slot associated with the subscription, then drop the
1297  * replication slot at the publisher.
1298  */
1299  if (slotname)
1300  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1301 
1302  }
1303  PG_FINALLY();
1304  {
1305  walrcv_disconnect(wrconn);
1306  }
1307  PG_END_TRY();
1308 
1309  table_close(rel, NoLock);
1310 }
1311 
1312 /*
1313  * Drop the replication slot at the publisher node using the replication
1314  * connection.
1315  *
1316  * missing_ok - if true then only issue a LOG message if the slot doesn't
1317  * exist.
1318  */
1319 void
1320 ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
1321 {
1322  StringInfoData cmd;
1323 
1324  Assert(wrconn);
1325 
1326  load_file("libpqwalreceiver", false);
1327 
1328  initStringInfo(&cmd);
1329  appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1330 
1331  PG_TRY();
1332  {
1333  WalRcvExecResult *res;
1334 
1335  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1336 
1337  if (res->status == WALRCV_OK_COMMAND)
1338  {
1339  /* NOTICE. Success. */
1340  ereport(NOTICE,
1341  (errmsg("dropped replication slot \"%s\" on publisher",
1342  slotname)));
1343  }
1344  else if (res->status == WALRCV_ERROR &&
1345  missing_ok &&
1346  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1347  {
1348  /* LOG. Error, but missing_ok = true. */
1349  ereport(LOG,
1350  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1351  slotname, res->err)));
1352  }
1353  else
1354  {
1355  /* ERROR. */
1356  ereport(ERROR,
1357  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1358  slotname, res->err)));
1359  }
1360 
1361  walrcv_clear_result(res);
1362  }
1363  PG_FINALLY();
1364  {
1365  pfree(cmd.data);
1366  }
1367  PG_END_TRY();
1368 }
1369 
1370 /*
1371  * Internal workhorse for changing a subscription owner
1372  */
1373 static void
1375 {
1376  Form_pg_subscription form;
1377 
1378  form = (Form_pg_subscription) GETSTRUCT(tup);
1379 
1380  if (form->subowner == newOwnerId)
1381  return;
1382 
1383  if (!pg_subscription_ownercheck(form->oid, GetUserId()))
1385  NameStr(form->subname));
1386 
1387  /* New owner must be a superuser */
1388  if (!superuser_arg(newOwnerId))
1389  ereport(ERROR,
1390  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1391  errmsg("permission denied to change owner of subscription \"%s\"",
1392  NameStr(form->subname)),
1393  errhint("The owner of a subscription must be a superuser.")));
1394 
1395  form->subowner = newOwnerId;
1396  CatalogTupleUpdate(rel, &tup->t_self, tup);
1397 
1398  /* Update owner dependency reference */
1399  changeDependencyOnOwner(SubscriptionRelationId,
1400  form->oid,
1401  newOwnerId);
1402 
1403  InvokeObjectPostAlterHook(SubscriptionRelationId,
1404  form->oid, 0);
1405 }
1406 
1407 /*
1408  * Change subscription owner -- by name
1409  */
1411 AlterSubscriptionOwner(const char *name, Oid newOwnerId)
1412 {
1413  Oid subid;
1414  HeapTuple tup;
1415  Relation rel;
1416  ObjectAddress address;
1417  Form_pg_subscription form;
1418 
1419  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1420 
1422  CStringGetDatum(name));
1423 
1424  if (!HeapTupleIsValid(tup))
1425  ereport(ERROR,
1426  (errcode(ERRCODE_UNDEFINED_OBJECT),
1427  errmsg("subscription \"%s\" does not exist", name)));
1428 
1429  form = (Form_pg_subscription) GETSTRUCT(tup);
1430  subid = form->oid;
1431 
1432  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1433 
1434  ObjectAddressSet(address, SubscriptionRelationId, subid);
1435 
1436  heap_freetuple(tup);
1437 
1439 
1440  return address;
1441 }
1442 
1443 /*
1444  * Change subscription owner -- by OID
1445  */
1446 void
1448 {
1449  HeapTuple tup;
1450  Relation rel;
1451 
1452  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1453 
1455 
1456  if (!HeapTupleIsValid(tup))
1457  ereport(ERROR,
1458  (errcode(ERRCODE_UNDEFINED_OBJECT),
1459  errmsg("subscription with OID %u does not exist", subid)));
1460 
1461  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1462 
1463  heap_freetuple(tup);
1464 
1466 }
1467 
1468 /*
1469  * Get the list of tables which belong to specified publications on the
1470  * publisher connection.
1471  */
1472 static List *
1474 {
1475  WalRcvExecResult *res;
1476  StringInfoData cmd;
1477  TupleTableSlot *slot;
1478  Oid tableRow[2] = {TEXTOID, TEXTOID};
1479  ListCell *lc;
1480  bool first;
1481  List *tablelist = NIL;
1482 
1483  Assert(list_length(publications) > 0);
1484 
1485  initStringInfo(&cmd);
1486  appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename\n"
1487  " FROM pg_catalog.pg_publication_tables t\n"
1488  " WHERE t.pubname IN (");
1489  first = true;
1490  foreach(lc, publications)
1491  {
1492  char *pubname = strVal(lfirst(lc));
1493 
1494  if (first)
1495  first = false;
1496  else
1497  appendStringInfoString(&cmd, ", ");
1498 
1500  }
1501  appendStringInfoChar(&cmd, ')');
1502 
1503  res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
1504  pfree(cmd.data);
1505 
1506  if (res->status != WALRCV_OK_TUPLES)
1507  ereport(ERROR,
1508  (errmsg("could not receive list of replicated tables from the publisher: %s",
1509  res->err)));
1510 
1511  /* Process tables. */
1513  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1514  {
1515  char *nspname;
1516  char *relname;
1517  bool isnull;
1518  RangeVar *rv;
1519 
1520  nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
1521  Assert(!isnull);
1522  relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
1523  Assert(!isnull);
1524 
1525  rv = makeRangeVar(nspname, relname, -1);
1526  tablelist = lappend(tablelist, rv);
1527 
1528  ExecClearTuple(slot);
1529  }
1531 
1532  walrcv_clear_result(res);
1533 
1534  return tablelist;
1535 }
1536 
1537 /*
1538  * This is to report the connection failure while dropping replication slots.
1539  * Here, we report the WARNING for all tablesync slots so that user can drop
1540  * them manually, if required.
1541  */
1542 static void
1543 ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
1544 {
1545  ListCell *lc;
1546 
1547  foreach(lc, rstates)
1548  {
1550  Oid relid = rstate->relid;
1551 
1552  /* Only cleanup resources of tablesync workers */
1553  if (!OidIsValid(relid))
1554  continue;
1555 
1556  /*
1557  * Caller needs to ensure that relstate doesn't change underneath us.
1558  * See DropSubscription where we get the relstates.
1559  */
1560  if (rstate->state != SUBREL_STATE_SYNCDONE)
1561  {
1562  char syncslotname[NAMEDATALEN] = {0};
1563 
1564  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1565  sizeof(syncslotname));
1566  elog(WARNING, "could not drop tablesync replication slot \"%s\"",
1567  syncslotname);
1568  }
1569  }
1570 
1571  ereport(ERROR,
1572  (errmsg("could not connect to publisher when attempting to "
1573  "drop replication slot \"%s\": %s", slotname, err),
1574  /* translator: %s is an SQL ALTER command */
1575  errhint("Use %s to disassociate the subscription from the slot.",
1576  "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
1577 }
1578 
1579 /*
1580  * Check for duplicates in the given list of publications and error out if
1581  * found one. Add publications to datums as text datums, if datums is not
1582  * NULL.
1583  */
1584 static void
1586 {
1587  ListCell *cell;
1588  int j = 0;
1589 
1590  foreach(cell, publist)
1591  {
1592  char *name = strVal(lfirst(cell));
1593  ListCell *pcell;
1594 
1595  foreach(pcell, publist)
1596  {
1597  char *pname = strVal(lfirst(pcell));
1598 
1599  if (pcell == cell)
1600  break;
1601 
1602  if (strcmp(name, pname) == 0)
1603  ereport(ERROR,
1604  (errcode(ERRCODE_SYNTAX_ERROR),
1605  errmsg("publication name \"%s\" used more than once",
1606  pname)));
1607  }
1608 
1609  if (datums)
1610  datums[j++] = CStringGetTextDatum(name);
1611  }
1612 }
1613 
1614 /*
1615  * Merge current subscription's publications and user-specified publications
1616  * from ADD/DROP PUBLICATIONS.
1617  *
1618  * If addpub is true, we will add the list of publications into oldpublist.
1619  * Otherwise, we will delete the list of publications from oldpublist. The
1620  * returned list is a copy, oldpublist itself is not changed.
1621  *
1622  * subname is the subscription name, for error messages.
1623  */
1624 static List *
1625 merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
1626 {
1627  ListCell *lc;
1628 
1629  oldpublist = list_copy(oldpublist);
1630 
1631  check_duplicates_in_publist(newpublist, NULL);
1632 
1633  foreach(lc, newpublist)
1634  {
1635  char *name = strVal(lfirst(lc));
1636  ListCell *lc2;
1637  bool found = false;
1638 
1639  foreach(lc2, oldpublist)
1640  {
1641  char *pubname = strVal(lfirst(lc2));
1642 
1643  if (strcmp(name, pubname) == 0)
1644  {
1645  found = true;
1646  if (addpub)
1647  ereport(ERROR,
1649  errmsg("publication \"%s\" is already in subscription \"%s\"",
1650  name, subname)));
1651  else
1652  oldpublist = foreach_delete_current(oldpublist, lc2);
1653 
1654  break;
1655  }
1656  }
1657 
1658  if (addpub && !found)
1659  oldpublist = lappend(oldpublist, makeString(name));
1660  else if (!addpub && !found)
1661  ereport(ERROR,
1662  (errcode(ERRCODE_SYNTAX_ERROR),
1663  errmsg("publication \"%s\" is not in subscription \"%s\"",
1664  name, subname)));
1665  }
1666 
1667  /*
1668  * XXX Probably no strong reason for this, but for now it's to make ALTER
1669  * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
1670  */
1671  if (!oldpublist)
1672  ereport(ERROR,
1673  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1674  errmsg("subscription must contain at least one publication")));
1675 
1676  return oldpublist;
1677 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:322
void DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:243
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
void RemoveSubscriptionRel(Oid subid, Oid relid)
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11324
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
#define RelationGetDescr(relation)
Definition: rel.h:495
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
Oid GetUserId(void)
Definition: miscinit.c:478
#define PointerGetDatum(X)
Definition: postgres.h:600
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:78
#define walrcv_check_conninfo(conninfo)
Definition: walreceiver.h:403
void replorigin_drop_by_name(char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
char * pstrdup(const char *in)
Definition: mcxt.c:1299
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:160
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3318
#define AccessShareLock
Definition: lockdefs.h:36
static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
List * list_copy(const List *oldlist)
Definition: list.c:1418
#define strVal(v)
Definition: value.h:54
static bool create_slot
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
static Datum publicationListToArray(List *publist)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define connect(s, name, namelen)
Definition: win32_port.h:463
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
FormData_pg_subscription * Form_pg_subscription
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
#define LOG
Definition: elog.h:26
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
NameData relname
Definition: pg_class.h:38
unsigned int Oid
Definition: postgres_ext.h:31
NameData subname
ObjectAddress CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:423
#define OidIsValid(objectId)
Definition: c.h:710
static WalReceiverConn * wrconn
Definition: walreceiver.c:94
char * schemaname
Definition: primnodes.h:67
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1816
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
#define NAMEDATALEN
#define DatumGetName(X)
Definition: postgres.h:629
char * relname
Definition: primnodes.h:68
Subscription * GetSubscription(Oid subid, bool missing_ok)
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:313
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
bool defGetBoolean(DefElem *def)
Definition: define.c:111
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:433
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
TupleDesc tupledesc
Definition: walreceiver.h:218
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
char * defGetString(DefElem *def)
Definition: define.c:49
ItemPointerData t_self
Definition: htup.h:65
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
static void parse_subscription_options(List *options, bool *connect, bool *enabled_given, bool *enabled, bool *create_slot, bool *slot_name_given, char **slot_name, bool *copy_data, char **synchronous_commit, bool *refresh, bool *binary_given, bool *binary, bool *streaming_given, bool *streaming)
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
AlterSubscriptionType kind
Definition: parsenodes.h:3654
#define SubscriptionObjectIndexId
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:436
#define RowExclusiveLock
Definition: lockdefs.h:38
List * GetSubscriptionRelations(Oid subid)
#define CStringGetDatum(X)
Definition: postgres.h:622
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
List * publications
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
RepOriginId replorigin_create(char *roname)
Definition: origin.c:240
ObjectAddress AlterSubscriptionOwner(const char *name, Oid newOwnerId)
int synchronous_commit
Definition: xact.c:83
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1001
List * lappend(List *list, void *datum)
Definition: list.c:336
static void check_duplicates_in_publist(List *publist, Datum *datums)
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define WARNING
Definition: elog.h:40
#define PG_FINALLY()
Definition: elog.h:330
#define TextDatumGetCString(d)
Definition: builtins.h:83
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
Oid MyDatabaseId
Definition: globals.c:88
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1017
#define BoolGetDatum(X)
Definition: postgres.h:446
#define InvalidOid
Definition: postgres_ext.h:36
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
#define ereport(elevel,...)
Definition: elog.h:157
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
#define NOTICE
Definition: elog.h:37
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
Tuplestorestate * tuplestore
Definition: walreceiver.h:217
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
WalRcvExecStatus status
Definition: walreceiver.h:214
Definition: regguts.h:317
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:195
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
int oid_cmp(const void *p1, const void *p2)
Definition: oid.c:336
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
static int list_length(const List *l)
Definition: pg_list.h:149
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1138
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:904
#define walrcv_disconnect(conn)
Definition: walreceiver.h:429
const char * name
Definition: encode.c:515
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define AccessExclusiveLock
Definition: lockdefs.h:45
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
void AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
#define NameStr(name)
Definition: c.h:681
#define CStringGetTextDatum(s)
Definition: builtins.h:82
char * defname
Definition: parsenodes.h:746
#define qsort(a, b, c, d)
Definition: port.h:504
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:780
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:177
#define PG_TRY()
Definition: elog.h:313
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:7277
Definition: pg_list.h:50
List * GetSubscriptionNotReadyRelations(Oid subid)
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define snprintf
Definition: port.h:216
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
#define PG_END_TRY()
Definition: elog.h:338
static void AlterSubscription_refresh(Subscription *sub, bool copy_data)
ObjectAddress AlterSubscription(AlterSubscriptionStmt *stmt, bool isTopLevel)
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:427
static List * merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:891
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5387
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:401